AgentAccountService.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\AgentThread;
  4. use App\Models\AiModel;
  5. use Illuminate\Support\Str;
  6. use Illuminate\Validation\ValidationException;
  7. /**
  8. * AI 对话里「这次提问算谁的」:研究过程入库、额度、积分共用同一套口径。
  9. *
  10. * - 有效的人类 token → 登录用户(type user,id = 用户 uuid);
  11. * - 没有 token、token 失效、或是 AI 模型 token → 游客(type guest,id = 设备匿名 uuid),
  12. * 必须带设备匿名 id。
  13. *
  14. * 结果是 {@see AgentAccount},落库是 account_type + account_id 两列。
  15. *
  16. * 模型 token 也能通过 JWT 校验,但对话归属、额度都只认人类账号。
  17. */
  18. class AgentAccountService
  19. {
  20. /**
  21. * @throws ValidationException 游客没带 device_id
  22. */
  23. public function resolve(?string $bearerUid, ?string $deviceId): AgentAccount
  24. {
  25. $userUid = $this->humanUid($bearerUid);
  26. if ($userUid) {
  27. return AgentAccount::user($userUid);
  28. }
  29. if (! $deviceId) {
  30. throw ValidationException::withMessages([
  31. 'device_id' => __('messages.agent_device_required'),
  32. ]);
  33. }
  34. return AgentAccount::guest($deviceId);
  35. }
  36. /**
  37. * 会话 id(AG-UI threadId)由客户端生成、全局唯一。已经属于别的账号的 id 不准再用:
  38. * 扣费时就拦下(不跑、不扣),入库时再兜一次。同账号的已删除会话不算别人的。
  39. *
  40. * 游客登录(或退出)后客户端会换一个新的 threadId,所以这里不会误伤正常用户。
  41. */
  42. public function assertThreadOwnable(AgentAccount $account, ?string $threadId): void
  43. {
  44. if (! $threadId) {
  45. return;
  46. }
  47. $thread = AgentThread::withTrashed()->where('thread_id', $threadId)->first(['account_type', 'account_id']);
  48. if ($thread !== null && ! $thread->isOwnedBy($account)) {
  49. abort(403, __('messages.agent_thread_forbidden'));
  50. }
  51. }
  52. private function humanUid(?string $uid): ?string
  53. {
  54. if (! $uid || ! Str::isUuid($uid)) {
  55. return null;
  56. }
  57. return AiModel::where('uid', $uid)->exists() ? null : $uid;
  58. }
  59. }