Răsfoiți Sursa

✨ (api-v13): 新增 AI 对话的研究过程入库、额度与积分、评价与管理统计(v3)

- 研究过程入库:POST /v3/agent-traces(只认 AI 对话服务的 X-Agent-Service-Key);会话、提问、步骤三张表,
  删除会话=软删(连同问答),数据永久保留;threadId 全局唯一,别的账号的会话 403
- 账号:account_type(user / guest)+ account_id(用户 uuid / 设备匿名 uuid)两列,一律经
  AgentAccount 与模型的 ownedBy() 一起比,游客把设备 id 填成别人的 uid 也冒充不了
- 额度与积分:POST /v3/agent-charges 提问前扣费(先赠送池后积分,402 不足、同 IP 游客每日上限,
  游客没有客户端 IP 422)、出错退款;GET /v3/agent-quota、GET /v3/credit-policy(策略在 config mint.credits);
  读经时长上报 POST /v3/me/reading-time;credits:settle-activity 补发漏结算的读经 / 编辑积分(已登记 tasks.md),
  credits:adjust 手工调整
- 评价与隐式信号:POST/DELETE /v3/agent-feedback、POST /v3/agent-events;评价即同意用于改进
- 我的会话:/v3/me/agent-threads(列表、详情、改名、删除、存档),按 threadId(uuid)访问
- 管理端(root / administrator):AI 对话统计、提问记录与详情、评价审阅、分析用 digest、阅读统计;
  对外不暴露自增主键
- .env.example 补 AGENT_SERVICE_KEY 的用途、生成方法与保管要求

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 4 zile în urmă
părinte
comite
d3a9f8581b
80 a modificat fișierele cu 4348 adăugiri și 0 ștergeri
  1. 7 0
      api-v13/.env.example
  2. 46 0
      api-v13/app/Console/Commands/AdjustCredits.php
  3. 40 0
      api-v13/app/Console/Commands/SettleCreditActivity.php
  4. 36 0
      api-v13/app/Http/Controllers/V3/AdminAgentFeedbackController.php
  5. 83 0
      api-v13/app/Http/Controllers/V3/AdminAgentRunController.php
  6. 34 0
      api-v13/app/Http/Controllers/V3/AdminAgentStatsController.php
  7. 36 0
      api-v13/app/Http/Controllers/V3/AdminReadingStatsController.php
  8. 61 0
      api-v13/app/Http/Controllers/V3/AgentChargeController.php
  9. 34 0
      api-v13/app/Http/Controllers/V3/AgentEventController.php
  10. 66 0
      api-v13/app/Http/Controllers/V3/AgentFeedbackController.php
  11. 42 0
      api-v13/app/Http/Controllers/V3/AgentQuotaController.php
  12. 51 0
      api-v13/app/Http/Controllers/V3/AgentTraceController.php
  13. 30 0
      api-v13/app/Http/Controllers/V3/CreditPolicyController.php
  14. 49 0
      api-v13/app/Http/Controllers/V3/MeAgentThreadArchiveController.php
  15. 89 0
      api-v13/app/Http/Controllers/V3/MeAgentThreadController.php
  16. 42 0
      api-v13/app/Http/Controllers/V3/MeReadingTimeController.php
  17. 47 0
      api-v13/app/Http/Middleware/V3/AuthenticateAdmin.php
  18. 40 0
      api-v13/app/Http/Middleware/V3/AuthenticateAgentService.php
  19. 26 0
      api-v13/app/Http/Requests/V3/DestroyAgentFeedbackRequest.php
  20. 34 0
      api-v13/app/Http/Requests/V3/IndexAdminAgentDigestRequest.php
  21. 34 0
      api-v13/app/Http/Requests/V3/IndexAdminAgentFeedbackRequest.php
  22. 35 0
      api-v13/app/Http/Requests/V3/IndexAdminAgentRunRequest.php
  23. 32 0
      api-v13/app/Http/Requests/V3/IndexMeAgentThreadRequest.php
  24. 32 0
      api-v13/app/Http/Requests/V3/ShowAdminStatsRequest.php
  25. 26 0
      api-v13/app/Http/Requests/V3/ShowAgentQuotaRequest.php
  26. 30 0
      api-v13/app/Http/Requests/V3/StoreAgentChargeRequest.php
  27. 32 0
      api-v13/app/Http/Requests/V3/StoreAgentEventRequest.php
  28. 37 0
      api-v13/app/Http/Requests/V3/StoreAgentFeedbackRequest.php
  29. 83 0
      api-v13/app/Http/Requests/V3/StoreAgentTraceRequest.php
  30. 27 0
      api-v13/app/Http/Requests/V3/StoreMeReadingTimeRequest.php
  31. 26 0
      api-v13/app/Http/Requests/V3/UpdateMeAgentThreadRequest.php
  32. 53 0
      api-v13/app/Http/Resources/V3/AdminAgentFeedbackResource.php
  33. 105 0
      api-v13/app/Http/Resources/V3/AdminAgentRunResource.php
  34. 30 0
      api-v13/app/Http/Resources/V3/AdminAgentStatsResource.php
  35. 34 0
      api-v13/app/Http/Resources/V3/AdminReadingStatsResource.php
  36. 36 0
      api-v13/app/Http/Resources/V3/AgentChargeResource.php
  37. 27 0
      api-v13/app/Http/Resources/V3/AgentEventResource.php
  38. 30 0
      api-v13/app/Http/Resources/V3/AgentFeedbackResource.php
  39. 34 0
      api-v13/app/Http/Resources/V3/AgentQuotaResource.php
  40. 45 0
      api-v13/app/Http/Resources/V3/AgentThreadResource.php
  41. 47 0
      api-v13/app/Http/Resources/V3/AgentThreadRunResource.php
  42. 33 0
      api-v13/app/Http/Resources/V3/AgentTraceResource.php
  43. 39 0
      api-v13/app/Http/Resources/V3/CreditPolicyResource.php
  44. 27 0
      api-v13/app/Http/Resources/V3/ReadingTimeResource.php
  45. 20 0
      api-v13/app/Models/AgentEvent.php
  46. 30 0
      api-v13/app/Models/AgentFeedback.php
  47. 98 0
      api-v13/app/Models/AgentRun.php
  48. 33 0
      api-v13/app/Models/AgentRunStep.php
  49. 48 0
      api-v13/app/Models/AgentThread.php
  50. 38 0
      api-v13/app/Models/Concerns/OwnedByAgentAccount.php
  51. 28 0
      api-v13/app/Models/CreditLedgerEntry.php
  52. 18 0
      api-v13/app/Models/ReadingDaily.php
  53. 67 0
      api-v13/app/Services/V3/AgentAccount.php
  54. 66 0
      api-v13/app/Services/V3/AgentAccountService.php
  55. 123 0
      api-v13/app/Services/V3/AgentFeedbackService.php
  56. 331 0
      api-v13/app/Services/V3/AgentStatsService.php
  57. 103 0
      api-v13/app/Services/V3/AgentThreadService.php
  58. 139 0
      api-v13/app/Services/V3/AgentTraceService.php
  59. 411 0
      api-v13/app/Services/V3/CreditService.php
  60. 280 0
      api-v13/app/Services/V3/ReadingStatsService.php
  61. 58 0
      api-v13/app/Services/V3/ReadingTimeService.php
  62. 34 0
      api-v13/app/Services/V3/StatsRange.php
  63. 6 0
      api-v13/bootstrap/app.php
  64. 37 0
      api-v13/config/mint.php
  65. 39 0
      api-v13/database/factories/AgentRunFactory.php
  66. 54 0
      api-v13/database/factories/AgentThreadFactory.php
  67. 40 0
      api-v13/database/migrations/2026_10_23_043455_create_agent_threads_table.php
  68. 72 0
      api-v13/database/migrations/2026_10_23_043456_create_agent_runs_table.php
  69. 39 0
      api-v13/database/migrations/2026_10_23_043457_create_agent_run_steps_table.php
  70. 46 0
      api-v13/database/migrations/2026_10_23_044429_create_credit_ledger_table.php
  71. 34 0
      api-v13/database/migrations/2026_10_23_044430_create_reading_dailies_table.php
  72. 31 0
      api-v13/database/migrations/2026_10_24_035732_add_admin_stats_indexes.php
  73. 43 0
      api-v13/database/migrations/2026_10_24_050456_create_agent_feedback_table.php
  74. 37 0
      api-v13/database/migrations/2026_10_24_050457_create_agent_events_table.php
  75. 4 0
      api-v13/documents/tasks.md
  76. 10 0
      api-v13/resources/lang/en/messages.php
  77. 10 0
      api-v13/resources/lang/zh-Hans/messages.php
  78. 2 0
      api-v13/routes/api.php
  79. 29 0
      api-v13/routes/v3/admin.php
  80. 63 0
      api-v13/routes/v3/agent.php

+ 7 - 0
api-v13/.env.example

@@ -79,4 +79,11 @@ JWT_SECRETS_KEY=
 # 运维接口令牌 /api/ops/*
 # 运维接口令牌 /api/ops/*
 APP_OPS_TOKEN=
 APP_OPS_TOKEN=
 
 
+# AI 对话服务(agent-poc backend)调 mint 的服务密钥,backend 那边配同一个值。
+# 保护提问前扣费(POST /v3/agent-charges)与研究过程入库(POST /v3/agent-traces);没配时这两个接口一律 401,
+# AI 对话不扣费、不留记录。生成:openssl rand -hex 32。
+# 只放 mint 与 backend 两处,不能进 runtime / web / mobile:拿到它就能冒充 backend 替任意账号扣费、写提问记录。
+# 泄露后两边一起换。详见 agent-poc/docs/trace.md「部署清单」。
+AGENT_SERVICE_KEY=
+
 OPENSEARCH_SYNONYMS_PATH=""
 OPENSEARCH_SYNONYMS_PATH=""

+ 46 - 0
api-v13/app/Console/Commands/AdjustCredits.php

@@ -0,0 +1,46 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Services\V3\AgentAccount;
+use App\Services\V3\CreditService;
+use Illuminate\Console\Attributes\Description;
+use Illuminate\Console\Attributes\Signature;
+use Illuminate\Console\Command;
+use Illuminate\Support\Str;
+
+/**
+ * 给某个登录用户手工加减 AI 对话积分(积分余额池)。--ref 相同的调整只生效一次。
+ */
+#[Signature('credits:adjust {user : 用户 uuid} {delta : 加减多少积分,可为负} {--reason= : 原因} {--ref= : 调整单号,缺省自动生成}')]
+#[Description('手工加减 AI 对话积分')]
+class AdjustCredits extends Command
+{
+    public function handle(CreditService $credits): int
+    {
+        $user = (string) $this->argument('user');
+        if (! Str::isUuid($user)) {
+            $this->error('user 必须是用户 uuid');
+
+            return self::FAILURE;
+        }
+        $delta = filter_var($this->argument('delta'), FILTER_VALIDATE_INT);
+        if ($delta === false || $delta === 0) {
+            $this->error('delta 必须是非零整数');
+
+            return self::FAILURE;
+        }
+
+        $entry = $credits->adjust(
+            AgentAccount::user($user),
+            $delta,
+            (string) ($this->option('ref') ?: Str::uuid()),
+            $this->option('reason'),
+        );
+        $this->info($entry->wasRecentlyCreated
+            ? "已调整:{$entry->delta}(ref {$entry->ref})"
+            : "ref {$entry->ref} 已经调整过,未重复入账");
+
+        return self::SUCCESS;
+    }
+}

+ 40 - 0
api-v13/app/Console/Commands/SettleCreditActivity.php

@@ -0,0 +1,40 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Services\V3\CreditService;
+use Illuminate\Console\Attributes\Description;
+use Illuminate\Console\Attributes\Signature;
+use Illuminate\Console\Command;
+
+/**
+ * 把登录用户的读经、编辑时长结算成 AI 对话积分。由 ops 每天跑一次(多跑无妨)。
+ *
+ * 不带参数:从积分上线日(config mint.credits.earn_since)到昨天,补齐所有漏结算的「用户 + 日」——
+ * 从没结算过的、或在那天活动结束前就结算了的(见 CreditService::settleMissing)。所以任务漏跑
+ * 不管几天,下次一跑就补上。带 --date:只重算那一天的所有用户。
+ *
+ * 用户查额度 / 提问时已经会顺带结算今天和昨天。可重复执行,结果覆盖、不会重复入账。
+ */
+#[Signature('credits:settle-activity {--date= : 只重算这一天(UTC,Y-m-d);不给就补齐上线以来所有漏结算的日子}')]
+#[Description('把读经、编辑时长结算成 AI 对话积分(默认补齐上线以来所有漏结算的日子)')]
+class SettleCreditActivity extends Command
+{
+    public function handle(CreditService $credits): int
+    {
+        if ($this->option('date')) {
+            $day = now('UTC')->parse((string) $this->option('date'))->startOfDay();
+            $users = $credits->settleDay($day);
+            $this->info("{$day->toDateString()}:结算了 {$users} 位用户。");
+
+            return self::SUCCESS;
+        }
+
+        $since = now('UTC')->parse((string) config('mint.credits.earn_since'))->startOfDay();
+        $until = now('UTC')->subDay()->startOfDay();
+        ['pairs' => $pairs, 'users' => $users] = $credits->settleMissing($since, $until);
+        $this->info("{$since->toDateString()} ~ {$until->toDateString()}:补结算了 {$users} 位用户的 {$pairs} 个「用户 + 日」。");
+
+        return self::SUCCESS;
+    }
+}

+ 36 - 0
api-v13/app/Http/Controllers/V3/AdminAgentFeedbackController.php

@@ -0,0 +1,36 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\IndexAdminAgentFeedbackRequest;
+use App\Http\Resources\V3\AdminAgentFeedbackResource;
+use App\Services\V3\AgentFeedbackService;
+
+/**
+ * 管理员审阅用户对 AI 回答的评价(仅 root / administrator)。新资源,没有 v2 前身。
+ */
+class AdminAgentFeedbackController extends Controller
+{
+    public function __construct(private readonly AgentFeedbackService $feedback) {}
+
+    /**
+     * 列出评价
+     *
+     * 最新的在前,带对应提问的摘要与自动质量指标,便于判断问题在哪。不含账号身份。
+     *
+     * @queryParam filter[rating] string 1 赞 / -1 踩。Enum: 1,-1
+     * @queryParam filter[tag] string 按标签 / 原因筛
+     * @queryParam filter[has_comment] boolean 只看带文字说明的
+     * @queryParam from string 起始日(UTC,Y-m-d)
+     * @queryParam to string 结束日(UTC,Y-m-d,含当天)
+     * @queryParam page integer 页码。Default: 1
+     * @queryParam per_page integer 每页数量,最大 100。Default: 20
+     */
+    public function index(IndexAdminAgentFeedbackRequest $request)
+    {
+        return AdminAgentFeedbackResource::collection(
+            $this->feedback->review($request->validated(), $request->integer('per_page', 20))
+        );
+    }
+}

+ 83 - 0
api-v13/app/Http/Controllers/V3/AdminAgentRunController.php

@@ -0,0 +1,83 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\IndexAdminAgentDigestRequest;
+use App\Http\Requests\V3\IndexAdminAgentRunRequest;
+use App\Http\Resources\V3\AdminAgentRunResource;
+use App\Http\Resources\V3\BaseResource;
+use App\Services\V3\AgentStatsService;
+use App\Services\V3\StatsRange;
+
+/**
+ * 管理员查阅 AI 对话的提问与研究过程(仅 root / administrator)。新资源,没有 v2 前身。
+ *
+ * 也是评测脚本从库里抽题的读接口(只抽 improve=true 的)。
+ */
+class AdminAgentRunController extends Controller
+{
+    public function __construct(private readonly AgentStatsService $stats) {}
+
+    /**
+     * 列出提问
+     *
+     * 最新的在前。提问原文对管理员可见;游客只显示设备匿名 id 与 IP。
+     *
+     * @queryParam filter[status] string 运行结果。Enum: ok,error,cancelled,denied
+     * @queryParam filter[route] string 研究路径:question 一般问题 / term 术语与词 / passage 阅读页提问 / chat 闲聊。Enum: question,term,passage,chat
+     * @queryParam filter[account_type] string 账号类型。Enum: user,guest
+     * @queryParam filter[client] string 客户端。Enum: mobile,web
+     * @queryParam filter[improve] boolean 是否允许用于改进回答
+     * @queryParam filter[q] string 按提问原文模糊搜索
+     * @queryParam page integer 页码。Default: 1
+     * @queryParam per_page integer 每页数量,最大 100。Default: 20
+     */
+    public function index(IndexAdminAgentRunRequest $request)
+    {
+        return AdminAgentRunResource::collection(
+            $this->stats->listRuns($request->validated(), $request->integer('per_page', 20))
+        );
+    }
+
+    /**
+     * 分析用的精简导出
+     *
+     * 区间内允许用于改进回答(improve=true)的提问,最早的在前。不带任何身份(账号、设备、IP)。
+     * 每条给:问题、路由与把握度、检索词、状态与耗时、工具调用序列、用户评价、隐式信号计数、
+     * 同一会话里下一次提问隔了几秒;`full=true` 时再带回答、证据全文与引用,供 agent 评估回答质量
+     * (服务端不做质量评估)。给 wikipali 插件的 `admin digest` 与分析技能用。
+     *
+     * @queryParam from string 起始日(UTC,Y-m-d)。Default: 今天往前 29 天
+     * @queryParam to string 结束日(UTC,Y-m-d,含当天)。Default: 今天
+     * @queryParam full boolean 是否带回答、证据全文与引用(此时 limit 最大 200)。Default: false
+     * @queryParam limit integer 最多多少条,最大 2000(full 时 200)。Default: 500(full 时 100)
+     *
+     * @meta has_more boolean 区间内是否还有更多(超出 limit)
+     */
+    public function digest(IndexAdminAgentDigestRequest $request)
+    {
+        [$from, $to] = StatsRange::resolve($request->validated());
+        $full = $request->boolean('full');
+        $digest = $this->stats->digest($from, $to, $request->integer('limit', $full ? 100 : 500), $full);
+
+        return BaseResource::collection($digest['items'])->additional(['meta' => [
+            'from' => $from->toDateString(),
+            'to' => $to->toDateString(),
+            'count' => count($digest['items']),
+            'has_more' => $digest['has_more'],
+        ]]);
+    }
+
+    /**
+     * 查看一次提问的研究过程
+     *
+     * 带回答、给作答 LLM 的证据全文、计划、引用与全部步骤(LLM / 工具调用、节点事件)。
+     *
+     * @urlParam run string required AG-UI runId(uuid)
+     */
+    public function show(string $run)
+    {
+        return AdminAgentRunResource::make($this->stats->showRun($run));
+    }
+}

+ 34 - 0
api-v13/app/Http/Controllers/V3/AdminAgentStatsController.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\ShowAdminStatsRequest;
+use App\Http\Resources\V3\AdminAgentStatsResource;
+use App\Services\V3\AgentStatsService;
+use App\Services\V3\StatsRange;
+
+/**
+ * 管理后台 AI 对话统计(单例资源,仅 root / administrator)。新资源,没有 v2 前身。
+ */
+class AdminAgentStatsController extends Controller
+{
+    public function __construct(private readonly AgentStatsService $stats) {}
+
+    /**
+     * AI 对话统计
+     *
+     * 一次返回整页:指标(含上一同长区间作对比)、每日按研究路径的提问数与耗时分位数、
+     * 客户端分布、工具调用 Top、积分流水。结果缓存 10 分钟。
+     *
+     * @queryParam from string 起始日(UTC,Y-m-d)。Default: 今天往前 29 天
+     * @queryParam to string 结束日(UTC,Y-m-d,含当天)。Default: 今天
+     * @queryParam account_type string 账号类型。Enum: all,user,guest。Default: all
+     */
+    public function __invoke(ShowAdminStatsRequest $request)
+    {
+        [$from, $to] = StatsRange::resolve($request->validated());
+
+        return AdminAgentStatsResource::make($this->stats->stats($from, $to, $request->validated('account_type', 'all')));
+    }
+}

+ 36 - 0
api-v13/app/Http/Controllers/V3/AdminReadingStatsController.php

@@ -0,0 +1,36 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\ShowAdminStatsRequest;
+use App\Http\Resources\V3\AdminReadingStatsResource;
+use App\Services\V3\ReadingStatsService;
+use App\Services\V3\StatsRange;
+
+/**
+ * 管理后台阅读统计(单例资源,仅 root / administrator)。新资源,没有 v2 前身。
+ */
+class AdminReadingStatsController extends Controller
+{
+    public function __construct(private readonly ReadingStatsService $stats) {}
+
+    /**
+     * 阅读统计
+     *
+     * 一次返回整页:指标(含上一同长区间作对比)、日活 / 月活、每日序列、热门章节、
+     * 三藏与根本·义注·复注分布、读经时长分布、读经积分。结果缓存 10 分钟。
+     * 口径:活跃读者来自阅读记录(recents,只有登录用户);读经时长只有 App;
+     * 章节浏览(views)含游客与搜索引擎爬虫。
+     *
+     * @queryParam from string 起始日(UTC,Y-m-d)。Default: 今天往前 29 天
+     * @queryParam to string 结束日(UTC,Y-m-d,含当天)。Default: 今天
+     * @queryParam client string 客户端。Enum: all,web,mobile。Default: all
+     */
+    public function __invoke(ShowAdminStatsRequest $request)
+    {
+        [$from, $to] = StatsRange::resolve($request->validated());
+
+        return AdminReadingStatsResource::make($this->stats->stats($from, $to, $request->validated('client', 'all')));
+    }
+}

+ 61 - 0
api-v13/app/Http/Controllers/V3/AgentChargeController.php

@@ -0,0 +1,61 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\StoreAgentChargeRequest;
+use App\Http\Resources\V3\AgentChargeResource;
+use App\Services\V3\AgentAccountService;
+use App\Services\V3\CreditService;
+
+/**
+ * AI 对话的提问扣费。只给 agent 服务调(`auth.agent-service`),不对客户端开放。
+ *
+ * 新资源,没有 v2 前身。
+ */
+class AgentChargeController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(
+        private readonly AgentAccountService $accounts,
+        private readonly CreditService $credits,
+    ) {}
+
+    /**
+     * 为一次提问扣费(幂等)
+     *
+     * 一次提问开始前由 agent 服务调用。先扣今日赠送,不够再扣积分余额;合计不够返回 402
+     * (`type` 为 quota-exceeded,扩展字段 `reason`:insufficient 积分不足 / ip_cap 游客同 IP 超上限,
+     * 另带 `cost`、`free_remaining`、`earned_balance`)。
+     *
+     * 账号口径与 `POST /v3/agent-traces` 相同:Bearer 是透传的终端用户 token,
+     * 无效或缺省按游客算,此时 `device_id` 必填。按 run_id 幂等:首次 201,重复 200。
+     * 服务端出错、回答没生成时,写研究过程那一步会自动退回。
+     *
+     * @responseStatus 201 首次扣费。响应体与 200 同形
+     * @responseStatus 402 额度不足或游客同 IP 超上限
+     * @responseStatus 403 thread_id 已经属于别的账号
+     *
+     * @bodyParam run_id string required AG-UI runId(uuid)
+     * @bodyParam thread_id string AG-UI threadId(uuid)。已经属于别的账号时 403,不扣费
+     * @bodyParam deep boolean 是否深度思考(价格不同)。Default: false
+     * @bodyParam device_id string 设备匿名 id(uuid)。游客必填
+     * @bodyParam client_ip string 客户端 IP(runtime 写入)。游客必填,没有就 422;只对游客用于同 IP 上限
+     */
+    public function store(StoreAgentChargeRequest $request)
+    {
+        $data = $request->validated();
+        $account = $this->accounts->resolve($this->currentUserUid($request), $data['device_id'] ?? null);
+        $this->accounts->assertThreadOwnable($account, $data['thread_id'] ?? null);
+        $charge = $this->credits->charge(
+            $account,
+            $data['run_id'],
+            (bool) ($data['deep'] ?? false),
+            $data['client_ip'] ?? null,
+        );
+
+        return AgentChargeResource::make($charge)->response()->setStatusCode($charge['created'] ? 201 : 200);
+    }
+}

+ 34 - 0
api-v13/app/Http/Controllers/V3/AgentEventController.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\StoreAgentEventRequest;
+use App\Http\Resources\V3\AgentEventResource;
+use App\Services\V3\AgentFeedbackService;
+
+/**
+ * AI 回答上的隐式信号(复制、点开引用、重新生成、主动询问显示过)。新资源,没有 v2 前身。
+ */
+class AgentEventController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(private readonly AgentFeedbackService $feedback) {}
+
+    /**
+     * 上报一条隐式信号
+     *
+     * @unauthenticated
+     *
+     * @bodyParam message_id string required AG-UI 回答消息 id
+     * @bodyParam kind string required 信号。Enum: copy,citation_open,regenerate,ask_shown
+     * @bodyParam device_id string 设备匿名 id(uuid)。未登录时必填
+     * @bodyParam client string 客户端。Enum: mobile,web
+     */
+    public function store(StoreAgentEventRequest $request)
+    {
+        return AgentEventResource::make($this->feedback->event($this->currentUserUid($request), $request->validated()));
+    }
+}

+ 66 - 0
api-v13/app/Http/Controllers/V3/AgentFeedbackController.php

@@ -0,0 +1,66 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\DestroyAgentFeedbackRequest;
+use App\Http\Requests\V3\StoreAgentFeedbackRequest;
+use App\Http\Resources\V3\AgentFeedbackResource;
+use App\Services\V3\AgentFeedbackService;
+
+/**
+ * 用户对 AI 回答的评价(点赞 / 点踩)。可选登录:登录用户按账号,游客带设备匿名 id。
+ * 新资源,没有 v2 前身。
+ */
+class AgentFeedbackController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(private readonly AgentFeedbackService $feedback) {}
+
+    /**
+     * 评价一条回答(再次提交即更新)
+     *
+     * 一人对一条回答只留一条:首次 201,更新 200。点赞的 tags 取 accurate / useful_citations / clear / inspiring,
+     * 点踩的 tags 是原因:citation_wrong / missed / off_topic / incorrect / too_long / too_academic / slow / other;
+     * 只有选了 other 时 comment 才会保存。asked=这条是被主动询问问出来的。
+     *
+     * @unauthenticated
+     *
+     * @responseStatus 201 首次评价。响应体与 200 同形
+     *
+     * @bodyParam message_id string required AG-UI 回答消息 id
+     * @bodyParam thread_id string 会话 id(uuid)
+     * @bodyParam rating integer required 1 赞 / -1 踩(只能是这两个值)。
+     * @bodyParam tags array 点赞标签或点踩原因
+     * @bodyParam comment string 选了 other 时的文字说明,最长 1000 字
+     * @bodyParam asked boolean 是否主动询问问出来的
+     * @bodyParam device_id string 设备匿名 id(uuid)。未登录时必填
+     * @bodyParam client string 客户端。Enum: mobile,web
+     */
+    public function store(StoreAgentFeedbackRequest $request)
+    {
+        return AgentFeedbackResource::make($this->feedback->rate($this->currentUserUid($request), $request->validated()));
+    }
+
+    /**
+     * 撤回评价
+     *
+     * 没评价过也返回 204(幂等)。
+     *
+     * @unauthenticated
+     *
+     * @urlParam message string required AG-UI 回答消息 id
+     *
+     * @queryParam device_id string 设备匿名 id(uuid)。未登录时必填
+     *
+     * @responseStatus 204 已撤回,无响应体
+     */
+    public function destroy(DestroyAgentFeedbackRequest $request, string $message)
+    {
+        $this->feedback->retract($this->currentUserUid($request), $message, $request->validated('device_id'));
+
+        return response()->noContent();
+    }
+}

+ 42 - 0
api-v13/app/Http/Controllers/V3/AgentQuotaController.php

@@ -0,0 +1,42 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\ShowAgentQuotaRequest;
+use App\Http\Resources\V3\AgentQuotaResource;
+use App\Services\V3\AgentAccountService;
+use App\Services\V3\CreditService;
+
+/**
+ * 当前账号的 AI 对话额度(单例资源)。web chat 与 mobile 显示「今日剩余 N 次 · 积分 X」用。
+ *
+ * 新资源,没有 v2 前身。
+ */
+class AgentQuotaController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(
+        private readonly AgentAccountService $accounts,
+        private readonly CreditService $credits,
+    ) {}
+
+    /**
+     * 查看我的 AI 对话额度
+     *
+     * 可选登录:带 Bearer 看自己账号;游客带 `device_id`。登录用户读取时会顺带把今天(和昨天)
+     * 的读经、编辑时长结算成积分,所以读完马上就能看到到账。
+     *
+     * @unauthenticated
+     *
+     * @queryParam device_id string 设备匿名 id(uuid)。未登录时必填
+     */
+    public function __invoke(ShowAgentQuotaRequest $request)
+    {
+        return AgentQuotaResource::make($this->credits->quota(
+            $this->accounts->resolve($this->currentUserUid($request), $request->validated('device_id'))
+        ));
+    }
+}

+ 51 - 0
api-v13/app/Http/Controllers/V3/AgentTraceController.php

@@ -0,0 +1,51 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\StoreAgentTraceRequest;
+use App\Http\Resources\V3\AgentTraceResource;
+use App\Services\V3\AgentTraceService;
+
+/**
+ * AI 对话的研究过程入库。只给 agent 服务调(`auth.agent-service`),不对客户端开放。
+ *
+ * 新资源,没有 v2 前身。
+ */
+class AgentTraceController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(private readonly AgentTraceService $traces) {}
+
+    /**
+     * 写入一次提问的研究过程(幂等)
+     *
+     * 请求头 `X-Agent-Service-Key` 证明调用方是 agent 服务;`Authorization: Bearer`
+     * 是 agent 透传的终端用户 token(可选):有效的人类 token 记到账号下,
+     * 没有 / 失效 / 是模型 token 都记为游客——此时 `device_id` 必填,并记 `client_ip`。
+     * token 失效不拒绝,照样入库。
+     *
+     * 按 run_id 幂等:首次写入 201,重复提交返回已有记录 200,步骤不会重复写。
+     *
+     * @responseStatus 201 首次写入。响应体与 200 同形
+     * @responseStatus 403 thread_id 已经属于别的账号
+     *
+     * @bodyParam run_id string required AG-UI runId(uuid)
+     * @bodyParam thread_id string required AG-UI threadId(uuid)
+     * @bodyParam device_id string 设备匿名 id(uuid)。游客必填,登录用户忽略
+     * @bodyParam client_ip string 客户端 IP。只对游客记录
+     * @bodyParam client string 客户端。Enum: mobile,web
+     * @bodyParam question string required 用户的提问
+     * @bodyParam status string required 运行结果(denied=额度不足被拦下)。Enum: ok,error,cancelled,denied
+     * @bodyParam improve boolean 用户是否允许用于改进回答(提问那一刻的开关)。Default: true
+     * @bodyParam steps array 每一步(LLM 调用、工具调用、节点事件),最多 500 条
+     */
+    public function store(StoreAgentTraceRequest $request)
+    {
+        return AgentTraceResource::make(
+            $this->traces->record($this->currentUserUid($request), $request->validated())
+        );
+    }
+}

+ 30 - 0
api-v13/app/Http/Controllers/V3/CreditPolicyController.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Controller;
+use App\Http\Resources\V3\CreditPolicyResource;
+use App\Services\V3\CreditService;
+
+/**
+ * AI 对话积分策略(单例资源,公开)。
+ *
+ * 新资源,没有 v2 前身。策略写在 `config('mint.credits.policy')`,只有当前生效的一版,历史看 git。
+ */
+class CreditPolicyController extends Controller
+{
+    public function __construct(private readonly CreditService $credits) {}
+
+    /**
+     * 查看当前的积分策略
+     *
+     * 每天赠送多少、每次提问多少钱、读经和编辑怎么换积分。`version` 是生效日(YYYYMMDD),
+     * 也记在每笔积分流水里。「一天」按 UTC 算。
+     *
+     * @unauthenticated
+     */
+    public function __invoke()
+    {
+        return CreditPolicyResource::make($this->credits->policy());
+    }
+}

+ 49 - 0
api-v13/app/Http/Controllers/V3/MeAgentThreadArchiveController.php

@@ -0,0 +1,49 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Resources\V3\AgentThreadResource;
+use App\Services\V3\AgentThreadService;
+use Illuminate\Http\Request;
+
+/**
+ * 会话的存档状态(单例子资源 `/archive`)。PUT 存档,DELETE 取消存档,都幂等。
+ *
+ * 存档目前只是分组。
+ */
+class MeAgentThreadArchiveController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(private readonly AgentThreadService $threads) {}
+
+    /**
+     * 存档会话
+     *
+     * 重复存档保留第一次的存档时间。返回更新后的会话。
+     *
+     * @urlParam thread string required AG-UI threadId(uuid)
+     */
+    public function update(Request $request, string $thread)
+    {
+        return AgentThreadResource::make(
+            $this->threads->setArchived($this->currentUser($request)['user_uid'], $thread, true)
+        );
+    }
+
+    /**
+     * 取消存档
+     *
+     * 返回更新后的会话(`archived_at` 为 null)。
+     *
+     * @urlParam thread string required AG-UI threadId(uuid)
+     */
+    public function destroy(Request $request, string $thread)
+    {
+        return AgentThreadResource::make(
+            $this->threads->setArchived($this->currentUser($request)['user_uid'], $thread, false)
+        );
+    }
+}

+ 89 - 0
api-v13/app/Http/Controllers/V3/MeAgentThreadController.php

@@ -0,0 +1,89 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\IndexMeAgentThreadRequest;
+use App\Http\Requests\V3\UpdateMeAgentThreadRequest;
+use App\Http\Resources\V3\AgentThreadResource;
+use App\Services\V3\AgentThreadService;
+use Illuminate\Http\Request;
+
+/**
+ * 当前登录用户的 AI 对话会话历史(web chat 与 mobile 共用)。
+ *
+ * 游客没有历史接口:设备 id 不是秘密,不能凭它读别人的提问。
+ * `{thread}` 是 AG-UI threadId;别人的会话与不存在的一样回 404。
+ *
+ * 新资源,没有 v2 前身(v2 的 `chats` / `chat-messages` 是另一套、未启用的表)。
+ */
+class MeAgentThreadController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(private readonly AgentThreadService $threads) {}
+
+    /**
+     * 列出我的会话
+     *
+     * 最近提问的在前,不含已删除的。
+     *
+     * @queryParam filter[archived] boolean 只看已存档(true)或未存档(false)的;不传则全部
+     * @queryParam page integer 页码。Default: 1
+     * @queryParam per_page integer 每页数量,最大 100。Default: 30
+     */
+    public function index(IndexMeAgentThreadRequest $request)
+    {
+        return AgentThreadResource::collection($this->threads->listForUser(
+            $this->currentUser($request)['user_uid'],
+            $request->validated(),
+            $request->integer('per_page', 30),
+        ));
+    }
+
+    /**
+     * 查看一个会话
+     *
+     * 带全部可见的问答轮次(runs),按提问先后排;被「重新生成」替换掉的轮次不返回。
+     *
+     * @urlParam thread string required AG-UI threadId(uuid)
+     */
+    public function show(Request $request, string $thread)
+    {
+        return AgentThreadResource::make(
+            $this->threads->showForUser($this->currentUser($request)['user_uid'], $thread)
+        );
+    }
+
+    /**
+     * 修改会话(目前只有标题)
+     *
+     * @urlParam thread string required AG-UI threadId(uuid)
+     *
+     * @bodyParam title string 会话标题,1–255 字
+     */
+    public function update(UpdateMeAgentThreadRequest $request, string $thread)
+    {
+        return AgentThreadResource::make($this->threads->update(
+            $this->currentUser($request)['user_uid'],
+            $thread,
+            $request->validated(),
+        ));
+    }
+
+    /**
+     * 删除会话
+     *
+     * 软删:会话连同它的问答一起从我的历史里消失,之后任何接口都读不到;服务器上的数据永久保留(防滥用、改进回答)。
+     * 返回软删后的会话本身(200,`deleted_at` 非空),不是 204。
+     *
+     * @urlParam thread string required AG-UI threadId(uuid)
+     */
+    public function destroy(Request $request, string $thread)
+    {
+        return AgentThreadResource::make(
+            $this->threads->hide($this->currentUser($request)['user_uid'], $thread)
+        );
+    }
+}

+ 42 - 0
api-v13/app/Http/Controllers/V3/MeReadingTimeController.php

@@ -0,0 +1,42 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\StoreMeReadingTimeRequest;
+use App\Http\Resources\V3\ReadingTimeResource;
+use App\Services\V3\ReadingTimeService;
+
+/**
+ * 当前登录用户的读经时长上报。读经时长按积分策略换成 AI 对话积分(游客不计)。
+ *
+ * 新资源,没有 v2 前身。
+ */
+class MeReadingTimeController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(private readonly ReadingTimeService $readingTime) {}
+
+    /**
+     * 上报一段读经时长
+     *
+     * 客户端在阅读器前台、且最近有滚动或翻页时计时,每 5 分钟或切后台时上报一次。
+     * 服务端按墙钟时间核减(当天计入的不超过距上次上报经过的时间),单日不超过 24 小时;
+     * 断网补报可带 `day`,最多 2 天前。返回这一天累计计入的秒数。
+     *
+     * @bodyParam seconds integer required 这段的读经秒数,1–900
+     * @bodyParam day string 归属的 UTC 日(Y-m-d),缺省为今天。断网补报用
+     */
+    public function store(StoreMeReadingTimeRequest $request)
+    {
+        $data = $request->validated();
+
+        return ReadingTimeResource::make($this->readingTime->report(
+            $this->currentUser($request)['user_uid'],
+            (int) $data['seconds'],
+            $data['day'] ?? null,
+        ));
+    }
+}

+ 47 - 0
api-v13/app/Http/Middleware/V3/AuthenticateAdmin.php

@@ -0,0 +1,47 @@
+<?php
+
+namespace App\Http\Middleware\V3;
+
+use App\Models\UserInfo;
+use Closure;
+use Illuminate\Auth\Access\AuthorizationException;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+/**
+ * v3 管理员闸:只放行 root 与 administrator。必须排在 `auth.v3` 之后(用户已解好放在
+ * request attributes 里),所以「没登录」是 401、「登录了但不是管理员」是 403。
+ *
+ * 角色口径与 v2 一致:root 账号(config('mint.admin.root_uuid'))固定是 root;
+ * 其余看 user_infos.role(JSON 数组)里有没有 administrator / root。
+ *
+ * 别名 `auth.v3.admin`(在 bootstrap/app.php 注册)。
+ */
+class AuthenticateAdmin
+{
+    public const ROLES = ['root', 'administrator'];
+
+    /**
+     * @throws AuthorizationException 不是管理员
+     */
+    public function handle(Request $request, Closure $next): Response
+    {
+        $uid = $request->attributes->get(Authenticate::USER)['user_uid'] ?? null;
+
+        if (! $uid || ! $this->isAdmin($uid)) {
+            throw new AuthorizationException;
+        }
+
+        return $next($request);
+    }
+
+    private function isAdmin(string $uid): bool
+    {
+        if ($uid === config('mint.admin.root_uuid')) {
+            return true;
+        }
+        $roles = json_decode((string) UserInfo::where('userid', $uid)->value('role'), true);
+
+        return is_array($roles) && array_intersect(self::ROLES, $roles) !== [];
+    }
+}

+ 40 - 0
api-v13/app/Http/Middleware/V3/AuthenticateAgentService.php

@@ -0,0 +1,40 @@
+<?php
+
+namespace App\Http\Middleware\V3;
+
+use App\Services\V3\AgentTraceService;
+use Closure;
+use Illuminate\Auth\AuthenticationException;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+/**
+ * v3 服务间鉴权:只放行 AI 对话服务(agent-poc backend)。
+ *
+ * 请求头 `X-Agent-Service-Key` 与 config('mint.app.agent_service_key')(.env 的
+ * AGENT_SERVICE_KEY)比对。密钥没配时一律拒绝,不会因为两边都是空串而放行。
+ *
+ * 它只证明「这是 agent 服务」;终端用户是谁另由 bearer(agent 透传的用户 token)
+ * 决定,见 {@see AgentTraceService::record()}。
+ *
+ * 别名 `auth.agent-service`(在 bootstrap/app.php 注册)。
+ */
+class AuthenticateAgentService
+{
+    public const HEADER = 'X-Agent-Service-Key';
+
+    /**
+     * @throws AuthenticationException 密钥缺失或不匹配
+     */
+    public function handle(Request $request, Closure $next): Response
+    {
+        $expected = (string) config('mint.app.agent_service_key');
+        $given = (string) $request->header(self::HEADER, '');
+
+        if ($expected === '' || $given === '' || ! hash_equals($expected, $given)) {
+            throw new AuthenticationException;
+        }
+
+        return $next($request);
+    }
+}

+ 26 - 0
api-v13/app/Http/Requests/V3/DestroyAgentFeedbackRequest.php

@@ -0,0 +1,26 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `DELETE /v3/agent-feedback/{message}` 的入参:游客带设备匿名 id。
+ */
+class DestroyAgentFeedbackRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'device_id' => ['nullable', 'uuid'],
+        ];
+    }
+}

+ 34 - 0
api-v13/app/Http/Requests/V3/IndexAdminAgentDigestRequest.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `GET /v3/admin/agent-runs/digest` 的入参:分析用的精简导出。
+ */
+class IndexAdminAgentDigestRequest extends FormRequest
+{
+    public const MAX_LIMIT = 2000;
+
+    /** 带回答与证据全文时每条可达几万字,上限收紧 */
+    public const MAX_LIMIT_FULL = 200;
+
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'from' => ['sometimes', 'date_format:Y-m-d'],
+            'to' => ['sometimes', 'date_format:Y-m-d', 'after_or_equal:from'],
+            'full' => ['sometimes', 'boolean'],
+            'limit' => ['sometimes', 'integer', 'min:1', 'max:'.($this->boolean('full') ? self::MAX_LIMIT_FULL : self::MAX_LIMIT)],
+        ];
+    }
+}

+ 34 - 0
api-v13/app/Http/Requests/V3/IndexAdminAgentFeedbackRequest.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use App\Models\AgentFeedback;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+/**
+ * `GET /v3/admin/agent-feedback` 的入参:管理员审阅用户评价。
+ */
+class IndexAdminAgentFeedbackRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'filter.rating' => ['sometimes', 'string', 'in:1,-1'],
+            'filter.tag' => ['sometimes', Rule::in([...AgentFeedback::UP_TAGS, ...AgentFeedback::DOWN_REASONS])],
+            'filter.has_comment' => ['sometimes', 'in:true,false,1,0'],
+            'from' => ['sometimes', 'date_format:Y-m-d'],
+            'to' => ['sometimes', 'date_format:Y-m-d'],
+            'page' => ['integer', 'min:1'],
+            'per_page' => ['integer', 'min:1', 'max:100'],
+        ];
+    }
+}

+ 35 - 0
api-v13/app/Http/Requests/V3/IndexAdminAgentRunRequest.php

@@ -0,0 +1,35 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use App\Models\AgentRun;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+/**
+ * `GET /v3/admin/agent-runs` 的入参:管理员查阅提问列表。
+ */
+class IndexAdminAgentRunRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'filter.status' => ['sometimes', Rule::in(AgentRun::STATUSES)],
+            'filter.route' => ['sometimes', Rule::in(AgentRun::ROUTES)],
+            'filter.account_type' => ['sometimes', 'in:user,guest'],
+            'filter.client' => ['sometimes', 'in:mobile,web'],
+            'filter.improve' => ['sometimes', 'in:true,false,1,0'],
+            'filter.q' => ['sometimes', 'string', 'max:200'],
+            'page' => ['integer', 'min:1'],
+            'per_page' => ['integer', 'min:1', 'max:100'],
+        ];
+    }
+}

+ 32 - 0
api-v13/app/Http/Requests/V3/IndexMeAgentThreadRequest.php

@@ -0,0 +1,32 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `GET /v3/me/agent-threads` 的入参:当前用户自己的 AI 对话会话列表。
+ */
+class IndexMeAgentThreadRequest extends FormRequest
+{
+    /**
+     * 登录检查由 auth.v3 中间件做:authorize() 返回 false 会渲染成 403,
+     * 而「没登录」应该是 401。
+     */
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'filter.archived' => ['sometimes', 'in:true,false,1,0'],
+            'page' => ['integer', 'min:1'],
+            'per_page' => ['integer', 'min:1', 'max:100'],
+        ];
+    }
+}

+ 32 - 0
api-v13/app/Http/Requests/V3/ShowAdminStatsRequest.php

@@ -0,0 +1,32 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * 管理后台统计(`/v3/admin/reading-stats`、`/v3/admin/agent-stats`)的共同入参:
+ * UTC 日的闭区间 [from, to],缺省近 30 天,最长 366 天。
+ */
+class ShowAdminStatsRequest extends FormRequest
+{
+    public const MAX_DAYS = 366;
+
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'from' => ['sometimes', 'date_format:Y-m-d'],
+            'to' => ['sometimes', 'date_format:Y-m-d', 'after_or_equal:from'],
+            'client' => ['sometimes', 'in:all,web,mobile'],
+            'account_type' => ['sometimes', 'in:all,user,guest'],
+        ];
+    }
+}

+ 26 - 0
api-v13/app/Http/Requests/V3/ShowAgentQuotaRequest.php

@@ -0,0 +1,26 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `GET /v3/agent-quota` 的入参。登录用户靠 bearer,游客带设备匿名 id。
+ */
+class ShowAgentQuotaRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'device_id' => ['nullable', 'uuid'],
+        ];
+    }
+}

+ 30 - 0
api-v13/app/Http/Requests/V3/StoreAgentChargeRequest.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `POST /v3/agent-charges` 的入参:agent 服务在一次提问开始前为它扣费。
+ */
+class StoreAgentChargeRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'run_id' => ['required', 'uuid'],
+            'thread_id' => ['nullable', 'uuid'],
+            'deep' => ['boolean'],
+            'device_id' => ['nullable', 'uuid'],
+            'client_ip' => ['nullable', 'ip'],
+        ];
+    }
+}

+ 32 - 0
api-v13/app/Http/Requests/V3/StoreAgentEventRequest.php

@@ -0,0 +1,32 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use App\Models\AgentEvent;
+use App\Models\AgentThread;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+/**
+ * `POST /v3/agent-events` 的入参:AI 回答上的一条隐式信号。
+ */
+class StoreAgentEventRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'message_id' => ['required', 'string', 'max:64', 'regex:/^[A-Za-z0-9_\-]+$/'],
+            'kind' => ['required', Rule::in(AgentEvent::KINDS)],
+            'device_id' => ['nullable', 'uuid'],
+            'client' => ['nullable', Rule::in(AgentThread::CLIENTS)],
+        ];
+    }
+}

+ 37 - 0
api-v13/app/Http/Requests/V3/StoreAgentFeedbackRequest.php

@@ -0,0 +1,37 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use App\Models\AgentFeedback;
+use App\Models\AgentThread;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+/**
+ * `POST /v3/agent-feedback` 的入参:对一条 AI 回答点赞 / 点踩。
+ */
+class StoreAgentFeedbackRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'message_id' => ['required', 'string', 'max:64', 'regex:/^[A-Za-z0-9_\-]+$/'],
+            'thread_id' => ['nullable', 'uuid'],
+            'rating' => ['required', 'integer', Rule::in([1, -1])],
+            'tags' => ['nullable', 'array', 'max:8'],
+            'tags.*' => ['string', Rule::in([...AgentFeedback::UP_TAGS, ...AgentFeedback::DOWN_REASONS])],
+            'comment' => ['nullable', 'string', 'max:1000'],
+            'asked' => ['boolean'],
+            'device_id' => ['nullable', 'uuid'],
+            'client' => ['nullable', Rule::in(AgentThread::CLIENTS)],
+        ];
+    }
+}

+ 83 - 0
api-v13/app/Http/Requests/V3/StoreAgentTraceRequest.php

@@ -0,0 +1,83 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use App\Models\AgentRun;
+use App\Models\AgentThread;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+/**
+ * `POST /v3/agent-traces` 的入参:一次提问(AG-UI run)的研究过程,连同全部步骤。
+ *
+ * 由 agent 服务在一次运行结束后发来。长文本的上限按「一次运行里最多会有多少」
+ * 留余量:证据全文给作答 LLM,深度思考时几万字也正常;单步结果 agent 端已截断到 8k。
+ */
+class StoreAgentTraceRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'run_id' => ['required', 'uuid'],
+            'thread_id' => ['required', 'uuid'],
+            'device_id' => ['nullable', 'uuid'],
+            'client_ip' => ['nullable', 'ip'],
+            'client' => ['nullable', 'string', Rule::in(AgentThread::CLIENTS)],
+            'app_version' => ['nullable', 'string', 'max:32'],
+            'locale' => ['nullable', 'string', 'max:16'],
+
+            'question' => ['required', 'string', 'max:20000'],
+            'passage' => ['nullable', 'array'],
+            'deep' => ['boolean'],
+            'improve' => ['boolean'],
+
+            'route' => ['nullable', 'string', 'max:32'],
+            'route_raw' => ['nullable', 'string', 'max:32'],
+            'confidence' => ['nullable', 'numeric'],
+            'plan' => ['nullable', 'array'],
+            'evidence' => ['nullable', 'string', 'max:400000'],
+            'answer' => ['nullable', 'string', 'max:200000'],
+            'citations' => ['nullable', 'array', 'max:200'],
+
+            'model' => ['nullable', 'string', 'max:64'],
+            'prompt_version' => ['nullable', 'string', 'max:64'],
+            'llm_calls' => ['integer', 'min:0', 'max:65535'],
+            'tool_calls' => ['integer', 'min:0', 'max:65535'],
+            'retries' => ['integer', 'min:0', 'max:65535'],
+            'tokens_in' => ['nullable', 'integer', 'min:0'],
+            'tokens_out' => ['nullable', 'integer', 'min:0'],
+            'latency_ms' => ['nullable', 'integer', 'min:0'],
+            'status' => ['required', 'string', Rule::in(AgentRun::STATUSES)],
+            'error' => ['nullable', 'string', 'max:20000'],
+
+            'user_message_id' => ['nullable', 'string', 'max:64'],
+            'assistant_message_id' => ['nullable', 'string', 'max:64'],
+            'replaces_run_id' => ['nullable', 'uuid'],
+            // 「重新生成」时被替换那条回答的 AG-UI 消息 id;服务端在同一会话里换算成 replaces_run_id
+            'replaces_message_id' => ['nullable', 'string', 'max:64'],
+            'started_at' => ['nullable', 'date'],
+
+            'steps' => ['array', 'max:500'],
+            'steps.*.seq' => ['required', 'integer', 'min:0', 'max:65535', 'distinct'],
+            // 不限定取值:backend 新加的步骤类型照样入库(不认识的记警告),不能因此整条被拒
+            'steps.*.kind' => ['required', 'string', 'max:16'],
+            'steps.*.name' => ['nullable', 'string', 'max:128'],
+            'steps.*.args' => ['nullable', 'array'],
+            'steps.*.result' => ['nullable', 'string', 'max:20000'],
+            'steps.*.result_chars' => ['nullable', 'integer', 'min:0'],
+            'steps.*.tokens_in' => ['nullable', 'integer', 'min:0'],
+            'steps.*.tokens_out' => ['nullable', 'integer', 'min:0'],
+            'steps.*.ms' => ['nullable', 'integer', 'min:0'],
+            'steps.*.error' => ['nullable', 'string', 'max:20000'],
+            'steps.*.started_at' => ['nullable', 'date'],
+        ];
+    }
+}

+ 27 - 0
api-v13/app/Http/Requests/V3/StoreMeReadingTimeRequest.php

@@ -0,0 +1,27 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `POST /v3/me/reading-time` 的入参:一段读经时长。客户端每 5 分钟或切后台时报一次。
+ */
+class StoreMeReadingTimeRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'seconds' => ['required', 'integer', 'min:1', 'max:900'],
+            'day' => ['nullable', 'date_format:Y-m-d'],
+        ];
+    }
+}

+ 26 - 0
api-v13/app/Http/Requests/V3/UpdateMeAgentThreadRequest.php

@@ -0,0 +1,26 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `PATCH /v3/me/agent-threads/{thread}` 的入参:局部更新,目前只有标题可改。
+ */
+class UpdateMeAgentThreadRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'title' => ['sometimes', 'string', 'min:1', 'max:255'],
+        ];
+    }
+}

+ 53 - 0
api-v13/app/Http/Resources/V3/AdminAgentFeedbackResource.php

@@ -0,0 +1,53 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use Illuminate\Http\Request;
+
+/**
+ * 管理员审阅的一条评价,带对应提问的摘要(提问还没入库时 run_id 等为空)。
+ * 不给账号身份,只给账号类型。
+ */
+class AdminAgentFeedbackResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     message_id: string,
+     *     rating: int,
+     *     tags: array<int, string>,
+     *     comment: string|null,
+     *     asked: bool,
+     *     client: string|null,
+     *     account_type: string,
+     *     updated_at: string,
+     *     run_id: string|null,
+     *     question: string|null,
+     *     route: 'question'|'term'|'passage'|'chat'|null,
+     *     status: string|null,
+     *     deep: bool|null,
+     *     latency_ms: int|null
+     * }
+     */
+    public function toArray($request): array
+    {
+        $r = $this->resource;
+
+        return [
+            'message_id' => $r->message_id,
+            'rating' => (int) $r->rating,
+            'tags' => $r->tags,
+            'comment' => $r->comment,
+            'asked' => (bool) $r->asked,
+            'client' => $r->client,
+            'account_type' => $r->account_type,
+            'updated_at' => $r->updated_at,
+            'run_id' => $r->run_id,
+            'question' => $r->question,
+            'route' => $r->route,
+            'status' => $r->status,
+            'deep' => $r->deep === null ? null : (bool) $r->deep,
+            'latency_ms' => $r->latency_ms === null ? null : (int) $r->latency_ms,
+        ];
+    }
+}

+ 105 - 0
api-v13/app/Http/Resources/V3/AdminAgentRunResource.php

@@ -0,0 +1,105 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Http\Resources\Concerns\ResolvesActor;
+use App\Models\AgentRun;
+use Illuminate\Http\Request;
+
+/**
+ * 管理员看到的一次提问。列表里只给摘要;详情(show)另带回答、证据、计划、引用与全部步骤。
+ *
+ * 游客只有设备匿名 id 与 IP;提问原文对 root / administrator 可见。**本类不查库**:
+ * thread、user、steps 由 Service 预加载。
+ *
+ * @mixin AgentRun
+ */
+class AdminAgentRunResource extends BaseResource
+{
+    use ResolvesActor;
+
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     run_id: string,
+     *     thread_id: string|null,
+     *     thread_title: string|null,
+     *     account_type: 'user'|'guest',
+     *     user: array{id: string, nickName: string, userName: string, realName: string, sn: int, avatar: string|null, roles: array|null}|null,
+     *     device_id: string|null,
+     *     client_ip: string|null,
+     *     client: string|null,
+     *     app_version: string|null,
+     *     question: string,
+     *     route: 'question'|'term'|'passage'|'chat'|null,
+     *     deep: bool,
+     *     improve: bool,
+     *     status: string,
+     *     latency_ms: int|null,
+     *     tokens_in: int|null,
+     *     tokens_out: int|null,
+     *     llm_calls: int,
+     *     tool_calls: int,
+     *     started_at: string|null,
+     *     answer?: string|null,
+     *     evidence?: string|null,
+     *     plan?: object|null,
+     *     passage?: object|null,
+     *     citations?: array<int, object>|null,
+     *     error?: string|null,
+     *     model?: string|null,
+     *     prompt_version?: string|null,
+     *     steps?: array<int, array{seq: int, kind: string, name: string|null, args: object|null, result: string|null, result_chars: int|null, tokens_in: int|null, tokens_out: int|null, ms: int|null, error: string|null}>
+     * }
+     */
+    public function toArray($request): array
+    {
+        $detail = $this->relationLoaded('steps');
+
+        return [
+            'run_id' => $this->run_id,
+            'thread_id' => $this->thread?->thread_id,
+            'thread_title' => $this->thread?->title,
+            'account_type' => $this->account_type,
+            // 只有登录用户才查得到人;游客的 account_id 是设备 id,不能拿去当用户 uid
+            'user' => $this->account_type === 'user' ? $this->actor($this->user) : null,
+            'device_id' => $this->account_type === 'guest' ? $this->account_id : null,
+            'client_ip' => $this->client_ip,
+            'client' => $this->client,
+            'app_version' => $this->app_version,
+            'question' => $this->question,
+            'route' => $this->route,
+            'deep' => $this->deep,
+            'improve' => $this->improve,
+            'status' => $this->status,
+            'latency_ms' => $this->latency_ms,
+            'tokens_in' => $this->tokens_in,
+            'tokens_out' => $this->tokens_out,
+            'llm_calls' => $this->llm_calls,
+            'tool_calls' => $this->tool_calls,
+            'started_at' => $this->started_at,
+            $this->mergeWhen($detail, fn () => [
+                'answer' => $this->answer,
+                'evidence' => $this->evidence,
+                'plan' => $this->plan,
+                'passage' => $this->passage,
+                'citations' => $this->citations,
+                'error' => $this->error,
+                'model' => $this->model,
+                'prompt_version' => $this->prompt_version,
+                'steps' => $this->steps->map(fn ($s) => [
+                    'seq' => $s->seq,
+                    'kind' => $s->kind,
+                    'name' => $s->name,
+                    'args' => $s->args,
+                    'result' => $s->result,
+                    'result_chars' => $s->result_chars,
+                    'tokens_in' => $s->tokens_in,
+                    'tokens_out' => $s->tokens_out,
+                    'ms' => $s->ms,
+                    'error' => $s->error,
+                ])->all(),
+            ]),
+        ];
+    }
+}

+ 30 - 0
api-v13/app/Http/Resources/V3/AdminAgentStatsResource.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Services\V3\AgentStatsService;
+use Illuminate\Http\Request;
+
+/**
+ * 管理后台 AI 对话统计(一次返回整页数据)。口径见 {@see AgentStatsService}。
+ */
+class AdminAgentStatsResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     range: array{from: string, to: string, account_type: string},
+     *     summary: array{runs: int, deep: int, passage: int, denied: int, errors: int, cancelled: int, unchecked: int, improve: int, askers: int, askers_user: int, askers_guest: int, latency_p50_ms: int|null, latency_p95_ms: int|null, tokens_in: int, tokens_out: int, feedback_up: int, feedback_down: int, feedback_asked: int},
+     *     previous: array{runs: int, deep: int, passage: int, denied: int, errors: int, cancelled: int, unchecked: int, improve: int, askers: int, askers_user: int, askers_guest: int, latency_p50_ms: int|null, latency_p95_ms: int|null, tokens_in: int, tokens_out: int, feedback_up: int, feedback_down: int, feedback_asked: int},
+     *     daily: array<int, array{date: string, question: int, term: int, passage: int, chat: int, none: int, denied: int, errors: int, latency_p50_ms: int|null, latency_p95_ms: int|null, feedback_up: int, feedback_down: int}>,
+     *     clients: array<int, array{client: string, runs: int}>,
+     *     tools: array<int, array{name: string, calls: int, errors: int, avg_ms: int}>,
+     *     feedback_reasons: array<int, array{reason: string, count: int}>,
+     *     credits: array{spent_free: int, spent_earned: int, refunded: int, earned_reading: int, earned_editing: int, adjusted: int}
+     * }
+     */
+    public function toArray($request): array
+    {
+        return $this->resource;
+    }
+}

+ 34 - 0
api-v13/app/Http/Resources/V3/AdminReadingStatsResource.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Services\V3\ReadingStatsService;
+use Illuminate\Http\Request;
+
+/**
+ * 管理后台阅读统计(一次返回整页数据)。口径见 {@see ReadingStatsService}。
+ *
+ * client=web 时读经时长相关字段为 null / 空(Web 没有计时);client=mobile 时章节浏览为 null。
+ */
+class AdminReadingStatsResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     range: array{from: string, to: string, client: string},
+     *     summary: array{active_readers: int, chapters_opened: int, reading_seconds: int|null, reading_users: int|null, page_views: int|null, dict_lookups: int},
+     *     previous: array{active_readers: int, chapters_opened: int, reading_seconds: int|null, reading_users: int|null, page_views: int|null, dict_lookups: int},
+     *     sticky: array{dau: int, mau: int},
+     *     daily: array<int, array{date: string, readers_web: int, readers_mobile: int, reading_minutes: int, page_views: int, dict_lookups: int}>,
+     *     top_chapters: array<int, array{article_id: string, book: int, paragraph: int, title: string, collection: string|null, readers: int, records: int}>,
+     *     pitaka_share: array<int, array{tag: string, records: int}>,
+     *     layer_share: array<int, array{tag: string, records: int}>,
+     *     duration_buckets: array<int, array{bucket: string, user_days: int}>,
+     *     reading_credits: array{credits: int, users: int, capped_user_days: int, clamped_ratio: float}|null
+     * }
+     */
+    public function toArray($request): array
+    {
+        return $this->resource;
+    }
+}

+ 36 - 0
api-v13/app/Http/Resources/V3/AgentChargeResource.php

@@ -0,0 +1,36 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use Illuminate\Http\Request;
+
+/**
+ * 一次提问的扣费结果。剩余额度服务端才算得出来、调用方当场要用,所以随结果返回。
+ */
+class AgentChargeResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     run_id: string,
+     *     cost: int,
+     *     charged_free: int,
+     *     charged_earned: int,
+     *     free_remaining: int,
+     *     earned_balance: int,
+     *     policy_version: int
+     * }
+     */
+    public function toArray($request): array
+    {
+        return [
+            'run_id' => $this->resource['run_id'],
+            'cost' => $this->resource['cost'],
+            'charged_free' => $this->resource['charged_free'],
+            'charged_earned' => $this->resource['charged_earned'],
+            'free_remaining' => $this->resource['free_remaining'],
+            'earned_balance' => $this->resource['earned_balance'],
+            'policy_version' => $this->resource['policy_version'],
+        ];
+    }
+}

+ 27 - 0
api-v13/app/Http/Resources/V3/AgentEventResource.php

@@ -0,0 +1,27 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Models\AgentEvent;
+use Illuminate\Http\Request;
+
+/**
+ * 一条隐式信号的回执。
+ *
+ * @mixin AgentEvent
+ */
+class AgentEventResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{message_id: string, kind: string, created_at: string}
+     */
+    public function toArray($request): array
+    {
+        return [
+            'message_id' => $this->message_id,
+            'kind' => $this->kind,
+            'created_at' => $this->created_at,
+        ];
+    }
+}

+ 30 - 0
api-v13/app/Http/Resources/V3/AgentFeedbackResource.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Models\AgentFeedback;
+use Illuminate\Http\Request;
+
+/**
+ * 我对一条 AI 回答的评价。
+ *
+ * @mixin AgentFeedback
+ */
+class AgentFeedbackResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{message_id: string, rating: int, tags: array<int, string>, comment: string|null, asked: bool, updated_at: string}
+     */
+    public function toArray($request): array
+    {
+        return [
+            'message_id' => $this->message_id,
+            'rating' => $this->rating,
+            'tags' => $this->tags ?? [],
+            'comment' => $this->comment,
+            'asked' => $this->asked,
+            'updated_at' => $this->updated_at,
+        ];
+    }
+}

+ 34 - 0
api-v13/app/Http/Resources/V3/AgentQuotaResource.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use Illuminate\Http\Request;
+
+/**
+ * 当前账号的 AI 对话额度概况:今日赠送、积分余额、两种提问的价格、今天赚了多少、赚取规则。
+ *
+ * earn 只对登录用户给出(游客读经不给积分)。
+ */
+class AgentQuotaResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     account_type: string,
+     *     day: string,
+     *     resets_at: string,
+     *     policy_version: int,
+     *     daily_free: int,
+     *     free_used: int,
+     *     free_remaining: int,
+     *     earned_balance: int,
+     *     cost: array{normal: int, deep: int},
+     *     earned_today: array{reading: int, editing: int},
+     *     earn: object
+     * }
+     */
+    public function toArray($request): array
+    {
+        return $this->resource;
+    }
+}

+ 45 - 0
api-v13/app/Http/Resources/V3/AgentThreadResource.php

@@ -0,0 +1,45 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Models\AgentThread;
+use Illuminate\Http\Request;
+
+/**
+ * 我的一个 AI 对话会话。列表里不带 runs,详情里带全部可见的问答轮次。
+ *
+ * deleted_at 只在删除接口的响应里非空(软删后返回的就是这条记录本身)。
+ *
+ * @mixin AgentThread
+ */
+class AgentThreadResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     thread_id: string,
+     *     title: string,
+     *     client: string|null,
+     *     archived_at: string|null,
+     *     last_run_at: string,
+     *     created_at: string,
+     *     updated_at: string,
+     *     deleted_at: string|null,
+     *     runs?: array<int, array{run_id: string, question: string, answer: string|null, citations: array<int, object>|null, deep: bool, status: string, user_message_id: string|null, assistant_message_id: string|null, created_at: string}>
+     * }
+     */
+    public function toArray($request): array
+    {
+        return [
+            'thread_id' => $this->thread_id,
+            'title' => $this->title,
+            'client' => $this->client,
+            'archived_at' => $this->archived_at,
+            'last_run_at' => $this->last_run_at,
+            'created_at' => $this->created_at,
+            'updated_at' => $this->updated_at,
+            'deleted_at' => $this->deleted_at,
+            'runs' => AgentThreadRunResource::collection($this->whenLoaded('runs')),
+        ];
+    }
+}

+ 47 - 0
api-v13/app/Http/Resources/V3/AgentThreadRunResource.php

@@ -0,0 +1,47 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Models\AgentRun;
+use Illuminate\Http\Request;
+
+/**
+ * 会话历史里的一轮问答:用户看得见的那部分。
+ *
+ * 研究过程(路由、计划、证据、步骤)不在这里——那是改进回答与防滥用用的,
+ * 不回给终端用户。user_message_id / assistant_message_id 是 AG-UI 消息 id,
+ * 续聊时客户端用它们把旧消息原样回灌给 agent。
+ *
+ * @mixin AgentRun
+ */
+class AgentThreadRunResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     run_id: string,
+     *     question: string,
+     *     answer: string|null,
+     *     citations: array<int, object>|null,
+     *     deep: bool,
+     *     status: string,
+     *     user_message_id: string|null,
+     *     assistant_message_id: string|null,
+     *     created_at: string
+     * }
+     */
+    public function toArray($request): array
+    {
+        return [
+            'run_id' => $this->run_id,
+            'question' => $this->question,
+            'answer' => $this->answer,
+            'citations' => $this->citations,
+            'deep' => $this->deep,
+            'status' => $this->status,
+            'user_message_id' => $this->user_message_id,
+            'assistant_message_id' => $this->assistant_message_id,
+            'created_at' => $this->started_at ?? $this->created_at,
+        ];
+    }
+}

+ 33 - 0
api-v13/app/Http/Resources/V3/AgentTraceResource.php

@@ -0,0 +1,33 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Models\AgentRun;
+use Illuminate\Http\Request;
+
+/**
+ * 写入研究过程后的回执:只回定位用的键,不把证据、回答这些大字段原样吐回去。
+ *
+ * @mixin AgentRun
+ */
+class AgentTraceResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     run_id: string,
+     *     thread_id: string,
+     *     account_type: 'user'|'guest',
+     *     created_at: string
+     * }
+     */
+    public function toArray($request): array
+    {
+        return [
+            'run_id' => $this->run_id,
+            'thread_id' => $this->thread->thread_id,
+            'account_type' => $this->account_type,
+            'created_at' => $this->created_at,
+        ];
+    }
+}

+ 39 - 0
api-v13/app/Http/Resources/V3/CreditPolicyResource.php

@@ -0,0 +1,39 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use Illuminate\Http\Request;
+
+/**
+ * 当前生效的 AI 对话积分策略(`config('mint.credits.policy')`,公开)。
+ */
+class CreditPolicyResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     version: int,
+     *     day_timezone: string,
+     *     daily_free: array{guest: int, user: int},
+     *     cost: array{normal: int, deep: int},
+     *     guest_ip_daily_cap: int|null,
+     *     earn: array{
+     *         reading: array{credits_per_minute: int, daily_cap: int|null},
+     *         editing: array{credits_per_minute: int, daily_cap: int|null}
+     *     }
+     * }
+     */
+    public function toArray($request): array
+    {
+        $rules = $this->resource['rules'];
+
+        return [
+            'version' => $this->resource['version'],
+            'day_timezone' => 'UTC',
+            'daily_free' => $rules['daily_free'],
+            'cost' => $rules['cost'],
+            'guest_ip_daily_cap' => $rules['guest_ip_daily_cap'] ?? null,
+            'earn' => $rules['earn'],
+        ];
+    }
+}

+ 27 - 0
api-v13/app/Http/Resources/V3/ReadingTimeResource.php

@@ -0,0 +1,27 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Models\ReadingDaily;
+use Illuminate\Http\Request;
+
+/**
+ * 某一天(UTC)累计计入的读经时长。
+ *
+ * @mixin ReadingDaily
+ */
+class ReadingTimeResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{day: string, seconds: int, updated_at: string}
+     */
+    public function toArray($request): array
+    {
+        return [
+            'day' => $this->day->toDateString(),
+            'seconds' => (int) $this->seconds,
+            'updated_at' => $this->updated_at,
+        ];
+    }
+}

+ 20 - 0
api-v13/app/Models/AgentEvent.php

@@ -0,0 +1,20 @@
+<?php
+
+namespace App\Models;
+
+use App\Models\Concerns\OwnedByAgentAccount;
+use Illuminate\Database\Eloquent\Model;
+
+/**
+ * AI 回答上的隐式信号(复制、点开引用、重新生成、主动询问显示过)。
+ */
+class AgentEvent extends Model
+{
+    use OwnedByAgentAccount;
+
+    public const KINDS = ['copy', 'citation_open', 'regenerate', 'ask_shown'];
+
+    public const UPDATED_AT = null;
+
+    protected $guarded = ['id'];
+}

+ 30 - 0
api-v13/app/Models/AgentFeedback.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace App\Models;
+
+use App\Models\Concerns\OwnedByAgentAccount;
+use Illuminate\Database\Eloquent\Model;
+
+/**
+ * 用户对一条 AI 回答的评价(按 AG-UI 回答消息 id)。一人一条,可改可撤回。
+ */
+class AgentFeedback extends Model
+{
+    use OwnedByAgentAccount;
+
+    /** 点赞可选的标签。 */
+    public const UP_TAGS = ['accurate', 'useful_citations', 'clear', 'inspiring'];
+
+    /** 点踩的原因。other 带一段文字说明(comment)。 */
+    public const DOWN_REASONS = ['citation_wrong', 'missed', 'off_topic', 'incorrect', 'too_long', 'too_academic', 'slow', 'other'];
+
+    protected $table = 'agent_feedback';
+
+    protected $guarded = ['id'];
+
+    protected $casts = [
+        'tags' => 'array',
+        'asked' => 'boolean',
+        'rating' => 'integer',
+    ];
+}

+ 98 - 0
api-v13/app/Models/AgentRun.php

@@ -0,0 +1,98 @@
+<?php
+
+namespace App\Models;
+
+use App\Models\Concerns\OwnedByAgentAccount;
+use App\Services\V3\AgentThreadService;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\HasMany;
+use Illuminate\Database\Eloquent\SoftDeletes;
+
+/**
+ * AI 对话的一次提问(AG-UI run)及其研究过程汇总。
+ *
+ * 软删除:随会话一起软删(用户删除会话,见 {@see AgentThreadService::hide()}),
+ * 软删后任何接口都读不到(将来分享对话也一样),数据永久保留。用 `DB::table('agent_runs')` 查时要自己加
+ * `whereNull('deleted_at')`。
+ */
+class AgentRun extends Model
+{
+    use HasFactory, OwnedByAgentAccount, SoftDeletes;
+
+    /**
+     * denied:额度不足、没有作答——照样入库,防滥用要看得到被拦下的提问。
+     *
+     * @var list<string>
+     */
+    public const STATUSES = ['ok', 'error', 'cancelled', 'denied'];
+
+    /**
+     * 研究路径(agent-poc `backend/routing.py` 的路由结果):question 一般问题、term 术语 / 词、
+     * passage 阅读页提问、chat 闲聊;还没路由就结束(额度拦截)时为 null。
+     *
+     * 唯一来源:Resource 的 `@return` 与控制器的 `@queryParam … Enum:` 里写的是同一组字面量(OpenAPI 据此出枚举,
+     * 前端画图用),由 tests/Feature/AgentRouteEnumTest.php 守住一致;backend 的离线测试拿 OpenAPI 规格核对
+     * routing.py 会产生的路由。入库时不认识的路由照样存、只记警告,不丢研究过程。
+     *
+     * @var list<string>
+     */
+    public const ROUTES = ['question', 'term', 'passage', 'chat'];
+
+    protected $guarded = ['id'];
+
+    protected $casts = [
+        'passage' => 'array',
+        'plan' => 'array',
+        'citations' => 'array',
+        'deep' => 'boolean',
+        'improve' => 'boolean',
+        'confidence' => 'float',
+        'started_at' => 'datetime',
+    ];
+
+    /**
+     * @return BelongsTo<AgentThread, $this>
+     */
+    public function thread(): BelongsTo
+    {
+        return $this->belongsTo(AgentThread::class, 'agent_thread_id')->withTrashed();
+    }
+
+    /**
+     * 提问的登录用户(游客为空)。uuid 列对 user_infos.userid,预加载用 UserService::eagerLoadActor() 的列白名单。
+     *
+     * @return BelongsTo<UserInfo, $this>
+     */
+    public function user(): BelongsTo
+    {
+        // 只对 account_type = user 有意义:游客的 account_id 是设备 id,碰巧与某个用户 uid 相同也不能当成他
+        return $this->belongsTo(UserInfo::class, 'account_id', 'userid');
+    }
+
+    /**
+     * @return HasMany<AgentRunStep, $this>
+     */
+    public function steps(): HasMany
+    {
+        return $this->hasMany(AgentRunStep::class)->orderBy('seq');
+    }
+
+    /**
+     * 只留用户看得见的那一轮:被「重新生成」替换掉的旧轮次不算。
+     *
+     * @param  Builder<AgentRun>  $query
+     */
+    public function scopeVisible(Builder $query): void
+    {
+        $query->whereNotExists(function ($sub) {
+            $sub->selectRaw('1')
+                ->from('agent_runs as newer')
+                ->whereNull('newer.deleted_at')
+                ->whereColumn('newer.agent_thread_id', 'agent_runs.agent_thread_id')
+                ->whereColumn('newer.replaces_run_id', 'agent_runs.run_id');
+        });
+    }
+}

+ 33 - 0
api-v13/app/Models/AgentRunStep.php

@@ -0,0 +1,33 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\SoftDeletes;
+
+/**
+ * 一次提问里的一步(LLM 调用、工具调用或节点事件)。
+ *
+ * 软删除:随所属提问一起软删,数据永久保留。
+ */
+class AgentRunStep extends Model
+{
+    use SoftDeletes;
+
+    /**
+     * 已知的步骤类型。入库时不认识的类型照样存(只记警告,见 AgentTraceService::record),
+     * 免得 backend 新加一种步骤就整条研究过程被拒。
+     *
+     * @var list<string>
+     */
+    public const KINDS = ['llm', 'tool', 'route', 'plan', 'retry', 'judge', 'passage', 'answer', 'budget', 'event'];
+
+    public $timestamps = false;
+
+    protected $guarded = ['id'];
+
+    protected $casts = [
+        'args' => 'array',
+        'started_at' => 'datetime',
+    ];
+}

+ 48 - 0
api-v13/app/Models/AgentThread.php

@@ -0,0 +1,48 @@
+<?php
+
+namespace App\Models;
+
+use App\Models\Concerns\OwnedByAgentAccount;
+use App\Services\V3\AgentAccountService;
+use App\Services\V3\AgentThreadService;
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\HasMany;
+use Illuminate\Database\Eloquent\SoftDeletes;
+
+/**
+ * AI 对话的一个会话(AG-UI thread)。
+ *
+ * 归属由 account_type(user / guest)+ account_id(用户 uuid / 设备匿名 uuid)表达,按账号查询走
+ * `ownedBy()`({@see OwnedByAgentAccount})。
+ * thread_id(AG-UI threadId)由客户端生成、全局唯一,属于别的账号就拒绝写入(403,
+ * {@see AgentAccountService::assertThreadOwnable()})。游客登录 / 退出后
+ * 客户端换新的 threadId——游客会话不并入账号。
+ *
+ * 软删除=用户在历史里删掉了它:对用户隐藏,它的提问与步骤一起软删({@see AgentThreadService::hide()}),
+ * 数据永久保留。外键不级联:数据库层面不做任何真删除。
+ */
+class AgentThread extends Model
+{
+    use HasFactory, OwnedByAgentAccount, SoftDeletes;
+
+    public const CLIENTS = ['mobile', 'web'];
+
+    /**
+     * 客户端能改的只有 title(UpdateMeAgentThreadRequest 只放行它);其余列由 Service 写。
+     */
+    protected $guarded = ['id'];
+
+    protected $casts = [
+        'archived_at' => 'datetime',
+        'last_run_at' => 'datetime',
+    ];
+
+    /**
+     * @return HasMany<AgentRun, $this>
+     */
+    public function runs(): HasMany
+    {
+        return $this->hasMany(AgentRun::class);
+    }
+}

+ 38 - 0
api-v13/app/Models/Concerns/OwnedByAgentAccount.php

@@ -0,0 +1,38 @@
+<?php
+
+namespace App\Models\Concerns;
+
+use App\Services\V3\AgentAccount;
+use Illuminate\Contracts\Database\Eloquent\Builder;
+
+/**
+ * 带 `account_type` + `account_id` 两列(AI 对话 / 积分的账号)的模型。
+ *
+ * 按账号查询只准用 {@see scopeOwnedBy()}:两列一起比,游客把设备 id 填成某个用户的 uid 也冒充不了他。
+ *
+ * @property string $account_type user / guest
+ * @property string $account_id 用户 uuid 或设备匿名 uuid
+ */
+trait OwnedByAgentAccount
+{
+    public function scopeOwnedBy(Builder $query, AgentAccount $account): void
+    {
+        $query->where($this->qualifyColumn('account_type'), $account->type)
+            ->where($this->qualifyColumn('account_id'), $account->id);
+    }
+
+    public function isOwnedBy(AgentAccount $account): bool
+    {
+        return $this->account_type === $account->type && $this->account_id === $account->id;
+    }
+
+    /**
+     * 这一行的账号。
+     */
+    public function account(): AgentAccount
+    {
+        return $this->account_type === 'user'
+            ? AgentAccount::user($this->account_id)
+            : AgentAccount::guest($this->account_id);
+    }
+}

+ 28 - 0
api-v13/app/Models/CreditLedgerEntry.php

@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Models;
+
+use App\Models\Concerns\OwnedByAgentAccount;
+use App\Services\V3\CreditService;
+use Illuminate\Database\Eloquent\Model;
+
+/**
+ * 积分流水的一条。余额 = 流水汇总,见 {@see CreditService}。
+ */
+class CreditLedgerEntry extends Model
+{
+    use OwnedByAgentAccount;
+
+    public const KINDS = ['earn', 'spend', 'refund', 'adjust'];
+
+    public const BUCKETS = ['free', 'earned'];
+
+    protected $table = 'credit_ledger';
+
+    protected $guarded = ['id'];
+
+    protected $casts = [
+        'day' => 'date:Y-m-d',
+        'delta' => 'integer',
+    ];
+}

+ 18 - 0
api-v13/app/Models/ReadingDaily.php

@@ -0,0 +1,18 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Model;
+
+/**
+ * 登录用户某一天(UTC)的读经时长。
+ */
+class ReadingDaily extends Model
+{
+    protected $guarded = ['id'];
+
+    protected $casts = [
+        'day' => 'date:Y-m-d',
+        'last_report_at' => 'datetime',
+    ];
+}

+ 67 - 0
api-v13/app/Services/V3/AgentAccount.php

@@ -0,0 +1,67 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Models\Concerns\OwnedByAgentAccount;
+
+/**
+ * AI 对话与积分里的「账号」:谁在提问、额度和积分算谁的。由 {@see AgentAccountService::resolve()} 得出。
+ *
+ * - 登录用户:type = user,id = 用户 uuid(user_infos.userid);
+ * - 游客:type = guest,id = 设备匿名 uuid(客户端生成)。
+ *
+ * 落库是两列 `account_type` + `account_id`。**两列必须一起用**:设备 id 是客户端自己填的,
+ * 可以故意填成某个用户的 uid,只按 account_id 查就会把游客认成那个用户。
+ * 所以按账号查询一律走模型的 `ownedBy()` scope({@see OwnedByAgentAccount}),
+ * 写入一律用 {@see columns()},不要手写 `where('account_id', …)`。
+ */
+final readonly class AgentAccount
+{
+    public const TYPES = ['user', 'guest'];
+
+    /**
+     * @param  'user'|'guest'  $type
+     */
+    private function __construct(public string $type, public string $id) {}
+
+    public static function user(string $userUid): self
+    {
+        return new self('user', $userUid);
+    }
+
+    public static function guest(string $deviceId): self
+    {
+        return new self('guest', $deviceId);
+    }
+
+    public function isUser(): bool
+    {
+        return $this->type === 'user';
+    }
+
+    /**
+     * 登录用户的 uuid;游客为 null。
+     */
+    public function userUid(): ?string
+    {
+        return $this->isUser() ? $this->id : null;
+    }
+
+    /**
+     * 写库用的两列。
+     *
+     * @return array{account_type: string, account_id: string}
+     */
+    public function columns(): array
+    {
+        return ['account_type' => $this->type, 'account_id' => $this->id];
+    }
+
+    /**
+     * 同一账号的唯一字符串(advisory lock 之类需要一个键的地方用)。
+     */
+    public function key(): string
+    {
+        return $this->type.':'.$this->id;
+    }
+}

+ 66 - 0
api-v13/app/Services/V3/AgentAccountService.php

@@ -0,0 +1,66 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Models\AgentThread;
+use App\Models\AiModel;
+use Illuminate\Support\Str;
+use Illuminate\Validation\ValidationException;
+
+/**
+ * AI 对话里「这次提问算谁的」:研究过程入库、额度、积分共用同一套口径。
+ *
+ * - 有效的人类 token → 登录用户(type user,id = 用户 uuid);
+ * - 没有 token、token 失效、或是 AI 模型 token → 游客(type guest,id = 设备匿名 uuid),
+ *   必须带设备匿名 id。
+ *
+ * 结果是 {@see AgentAccount},落库是 account_type + account_id 两列。
+ *
+ * 模型 token 也能通过 JWT 校验,但对话归属、额度都只认人类账号。
+ */
+class AgentAccountService
+{
+    /**
+     * @throws ValidationException 游客没带 device_id
+     */
+    public function resolve(?string $bearerUid, ?string $deviceId): AgentAccount
+    {
+        $userUid = $this->humanUid($bearerUid);
+        if ($userUid) {
+            return AgentAccount::user($userUid);
+        }
+        if (! $deviceId) {
+            throw ValidationException::withMessages([
+                'device_id' => __('messages.agent_device_required'),
+            ]);
+        }
+
+        return AgentAccount::guest($deviceId);
+    }
+
+    /**
+     * 会话 id(AG-UI threadId)由客户端生成、全局唯一。已经属于别的账号的 id 不准再用:
+     * 扣费时就拦下(不跑、不扣),入库时再兜一次。同账号的已删除会话不算别人的。
+     *
+     * 游客登录(或退出)后客户端会换一个新的 threadId,所以这里不会误伤正常用户。
+     */
+    public function assertThreadOwnable(AgentAccount $account, ?string $threadId): void
+    {
+        if (! $threadId) {
+            return;
+        }
+        $thread = AgentThread::withTrashed()->where('thread_id', $threadId)->first(['account_type', 'account_id']);
+        if ($thread !== null && ! $thread->isOwnedBy($account)) {
+            abort(403, __('messages.agent_thread_forbidden'));
+        }
+    }
+
+    private function humanUid(?string $uid): ?string
+    {
+        if (! $uid || ! Str::isUuid($uid)) {
+            return null;
+        }
+
+        return AiModel::where('uid', $uid)->exists() ? null : $uid;
+    }
+}

+ 123 - 0
api-v13/app/Services/V3/AgentFeedbackService.php

@@ -0,0 +1,123 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Models\AgentEvent;
+use App\Models\AgentFeedback;
+use App\Models\AgentRun;
+use Illuminate\Contracts\Pagination\LengthAwarePaginator;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Validation\ValidationException;
+
+/**
+ * AI 回答的用户评价与隐式信号。
+ *
+ * 一人对一条回答只留一条评价:登录用户按账号、游客按设备匿名 id(同研究过程入库的口径,
+ * 见 {@see AgentAccountService})。再点就是更新,可撤回。评价挂在 AG-UI 回答消息 id 上,
+ * 不要求那次提问已经入库。
+ *
+ * 评价即同意把这次问答用于改进(agent_runs.improve 置为 true),见 {@see rate()}。
+ */
+class AgentFeedbackService
+{
+    public function __construct(private readonly AgentAccountService $accounts) {}
+
+    /**
+     * 写入或更新评价。
+     *
+     * @param  array{message_id: string, thread_id?: string|null, rating: int, tags?: list<string>|null, comment?: string|null, asked?: bool, device_id?: string|null, client?: string|null}  $data
+     *
+     * @throws ValidationException 标签与评分不配套,或游客没带 device_id
+     */
+    public function rate(?string $bearerUid, array $data): AgentFeedback
+    {
+        $account = $this->accounts->resolve($bearerUid, $data['device_id'] ?? null);
+        $tags = array_values(array_unique($data['tags'] ?? []));
+        $allowed = $data['rating'] > 0 ? AgentFeedback::UP_TAGS : AgentFeedback::DOWN_REASONS;
+        if (array_diff($tags, $allowed) !== []) {
+            throw ValidationException::withMessages(['tags' => __('messages.agent_feedback_tags')]);
+        }
+        // 文字说明只跟「其他」走
+        $comment = in_array('other', $tags, true) ? (trim((string) ($data['comment'] ?? '')) ?: null) : null;
+
+        $feedback = AgentFeedback::firstOrNew([...$account->columns(), 'message_id' => $data['message_id']]);
+        $feedback->fill([
+            'thread_id' => $data['thread_id'] ?? $feedback->thread_id,
+            'rating' => $data['rating'] > 0 ? 1 : -1,
+            'tags' => $tags ?: null,
+            'comment' => $comment,
+            // 一旦是被主动询问问出来的,就一直算
+            'asked' => $feedback->asked || (bool) ($data['asked'] ?? false),
+            'client' => $data['client'] ?? $feedback->client,
+        ])->save();
+
+        // 评价=同意把这次问答用于改进:客户端在「用于改进」关着时先弹窗征得同意,
+        // 不同意就不让评价。所以这条提问即使当时记的是 improve=false,也改成 true(只改本人自己的提问)
+        AgentRun::where('assistant_message_id', $data['message_id'])
+            ->where('improve', false)
+            ->whereHas('thread', fn ($q) => $q->ownedBy($account))
+            ->update(['improve' => true]);
+
+        return $feedback;
+    }
+
+    /**
+     * 撤回评价。没评价过也算成功(幂等)。
+     *
+     * @throws ValidationException 游客没带 device_id
+     */
+    public function retract(?string $bearerUid, string $messageId, ?string $deviceId): void
+    {
+        $account = $this->accounts->resolve($bearerUid, $deviceId);
+        AgentFeedback::ownedBy($account)->where('message_id', $messageId)->delete();
+    }
+
+    /**
+     * 记一条隐式信号。
+     *
+     * @param  array{message_id: string, kind: string, device_id?: string|null, client?: string|null}  $data
+     */
+    public function event(?string $bearerUid, array $data): AgentEvent
+    {
+        $account = $this->accounts->resolve($bearerUid, $data['device_id'] ?? null);
+
+        return AgentEvent::create([
+            ...$account->columns(),
+            'message_id' => $data['message_id'],
+            'kind' => $data['kind'],
+            'client' => $data['client'] ?? null,
+        ]);
+    }
+
+    /**
+     * 管理员审阅:评价列表,带对应提问的摘要(问题、路由、状态、质量指标)。最新的在前。
+     *
+     * @param  array{filter?: array{rating?: string, tag?: string, has_comment?: bool|string}, from?: string, to?: string}  $filters
+     * @return LengthAwarePaginator<int, object>
+     */
+    public function review(array $filters, int $perPage): LengthAwarePaginator
+    {
+        $f = $filters['filter'] ?? [];
+
+        return DB::table('agent_feedback as f')
+            // 软删的提问读不到:评价还在,但不再带出那次问答
+            ->leftJoin('agent_runs as r', fn ($j) => $j->on('r.assistant_message_id', '=', 'f.message_id')->whereNull('r.deleted_at'))
+            ->select([
+                'f.id', 'f.message_id', 'f.rating', 'f.tags', 'f.comment', 'f.asked', 'f.client', 'f.created_at', 'f.updated_at',
+                'f.account_type', 'r.run_id', 'r.question', 'r.route', 'r.status', 'r.deep', 'r.latency_ms',
+            ])
+            ->when(isset($f['rating']), fn ($q) => $q->where('f.rating', (int) $f['rating'] > 0 ? 1 : -1))
+            ->when($f['tag'] ?? null, fn ($q, $tag) => $q->whereRaw('jsonb_exists(f.tags, ?)', [$tag]))
+            ->when(isset($f['has_comment']) && filter_var($f['has_comment'], FILTER_VALIDATE_BOOLEAN), fn ($q) => $q->whereNotNull('f.comment'))
+            ->when($filters['from'] ?? null, fn ($q, $d) => $q->where('f.updated_at', '>=', $d))
+            ->when($filters['to'] ?? null, fn ($q, $d) => $q->where('f.updated_at', '<', now('UTC')->parse($d)->addDay()))
+            ->orderByDesc('f.updated_at')
+            ->orderByDesc('f.id')
+            ->paginate($perPage)
+            ->through(function ($row) {
+                $row->tags = $row->tags ? json_decode($row->tags, true) : [];
+
+                return $row;
+            });
+    }
+}

+ 331 - 0
api-v13/app/Services/V3/AgentStatsService.php

@@ -0,0 +1,331 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Models\AgentRun;
+use App\Services\UserService;
+use Carbon\CarbonImmutable;
+use Illuminate\Contracts\Pagination\LengthAwarePaginator;
+use Illuminate\Database\Eloquent\ModelNotFoundException;
+use Illuminate\Database\Query\Builder;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\DB;
+
+/**
+ * 管理后台「AI 对话统计」与研究过程查阅。时间范围按 UTC 日,闭区间 [from, to],
+ * 以提问开始时间 started_at 为准(入库时总会填,缺省取入库时刻)。
+ *
+ * 数据来源:agent_runs(一次提问)、agent_threads(account_type + account_id = 谁问的)、agent_run_steps(工具调用)、
+ * credit_ledger(积分流水)。设计见 agent-poc 仓库 docs/trace.md、credits.md。
+ *
+ * 统计结果缓存 10 分钟;提问列表与详情不缓存。
+ */
+class AgentStatsService
+{
+    private const CACHE_SECONDS = 600;
+
+    /**
+     * @param  'all'|'user'|'guest'  $accountType
+     * @return array<string, mixed>
+     */
+    public function stats(CarbonImmutable $from, CarbonImmutable $to, string $accountType): array
+    {
+        $key = "admin:agent-stats:{$from->toDateString()}:{$to->toDateString()}:{$accountType}";
+
+        return Cache::remember($key, self::CACHE_SECONDS, function () use ($from, $to, $accountType) {
+            $days = $from->diffInDays($to) + 1;
+            $prevTo = $from->subDay();
+            $prevFrom = $prevTo->subDays($days - 1);
+
+            return [
+                'range' => ['from' => $from->toDateString(), 'to' => $to->toDateString(), 'account_type' => $accountType],
+                'summary' => $this->summary($from, $to, $accountType),
+                'previous' => $this->summary($prevFrom, $prevTo, $accountType),
+                'daily' => $this->daily($from, $to, $accountType),
+                'clients' => $this->runs($from, $to, $accountType)
+                    ->selectRaw("coalesce(r.client, 'unknown') as client, count(*) as runs")->groupByRaw('1')
+                    ->orderByDesc('runs')->get()->map(fn ($r) => ['client' => $r->client, 'runs' => (int) $r->runs])->all(),
+                'tools' => $this->tools($from, $to, $accountType),
+                'feedback_reasons' => $this->feedbackReasons($from, $to, $accountType),
+                'credits' => $this->creditFlows($from, $to, $accountType),
+            ];
+        });
+    }
+
+    /**
+     * @return array<string, int|float|null>
+     */
+    private function summary(CarbonImmutable $from, CarbonImmutable $to, string $accountType): array
+    {
+        $row = $this->runs($from, $to, $accountType)
+            ->selectRaw('count(*) as runs')
+            ->selectRaw('count(*) filter (where r.deep) as deep')
+            ->selectRaw("count(*) filter (where r.route = 'passage') as passage")
+            ->selectRaw("count(*) filter (where r.status = 'denied') as denied")
+            ->selectRaw("count(*) filter (where r.status = 'error') as errors")
+            ->selectRaw("count(*) filter (where r.status = 'cancelled') as cancelled")
+            ->selectRaw('count(*) filter (where r.improve) as improve')
+            // 账号=两列一起:用户 uid 与设备 id 可能相同,只数 account_id 会把两人算成一个
+            ->selectRaw('count(distinct (t.account_type, t.account_id)) as askers')
+            ->selectRaw("count(distinct t.account_id) filter (where t.account_type = 'user') as askers_user")
+            ->selectRaw("count(distinct t.account_id) filter (where t.account_type = 'guest') as askers_guest")
+            ->selectRaw("percentile_cont(0.5) within group (order by r.latency_ms) filter (where r.status = 'ok') as p50")
+            ->selectRaw("percentile_cont(0.95) within group (order by r.latency_ms) filter (where r.status = 'ok') as p95")
+            ->selectRaw('coalesce(sum(r.tokens_in), 0) as tokens_in, coalesce(sum(r.tokens_out), 0) as tokens_out')
+            ->first();
+
+        $feedback = $this->runs($from, $to, $accountType)
+            ->join('agent_feedback as f', 'f.message_id', '=', 'r.assistant_message_id')
+            ->selectRaw('count(*) filter (where f.rating > 0) as up, count(*) filter (where f.rating < 0) as down')
+            ->selectRaw('count(*) filter (where f.asked) as asked')
+            ->first();
+
+        $unchecked = $this->runs($from, $to, $accountType)
+            ->join('agent_run_steps as s', fn ($j) => $j->on('s.agent_run_id', '=', 'r.id')->whereNull('s.deleted_at'))
+            ->where('s.kind', 'event')->where('s.name', 'quota')
+            ->whereRaw("s.args->>'result' = 'unchecked'")
+            ->count();
+
+        return [
+            'runs' => (int) $row->runs,
+            'deep' => (int) $row->deep,
+            'passage' => (int) $row->passage,
+            'denied' => (int) $row->denied,
+            'errors' => (int) $row->errors,
+            'cancelled' => (int) $row->cancelled,
+            'unchecked' => $unchecked,
+            'improve' => (int) $row->improve,
+            'askers' => (int) $row->askers,
+            'askers_user' => (int) $row->askers_user,
+            'askers_guest' => (int) $row->askers_guest,
+            'latency_p50_ms' => $row->p50 !== null ? (int) round((float) $row->p50) : null,
+            'latency_p95_ms' => $row->p95 !== null ? (int) round((float) $row->p95) : null,
+            'tokens_in' => (int) $row->tokens_in,
+            'tokens_out' => (int) $row->tokens_out,
+            'feedback_up' => (int) $feedback->up,
+            'feedback_down' => (int) $feedback->down,
+            'feedback_asked' => (int) $feedback->asked,
+        ];
+    }
+
+    /**
+     * 点踩原因分布(区间内提问收到的点踩)。
+     *
+     * @return list<array{reason: string, count: int}>
+     */
+    private function feedbackReasons(CarbonImmutable $from, CarbonImmutable $to, string $accountType): array
+    {
+        return $this->runs($from, $to, $accountType)
+            ->join('agent_feedback as f', 'f.message_id', '=', 'r.assistant_message_id')
+            ->where('f.rating', '<', 0)
+            ->crossJoin(DB::raw("jsonb_array_elements_text(coalesce(f.tags, '[]'::jsonb)) as tag(reason)"))
+            ->selectRaw('tag.reason as reason, count(*) as n')
+            ->groupBy('tag.reason')->orderByDesc('n')->get()
+            ->map(fn ($r) => ['reason' => $r->reason, 'count' => (int) $r->n])->all();
+    }
+
+    /**
+     * 每天一行:按研究路径的提问数、拦截 / 出错数、耗时分位数。没有数据的日子补 0。
+     *
+     * @return list<array<string, int|string|null>>
+     */
+    private function daily(CarbonImmutable $from, CarbonImmutable $to, string $accountType): array
+    {
+        $byRoute = $this->runs($from, $to, $accountType)
+            ->selectRaw("date({$this->time()}) as d, coalesce(r.route, 'none') as route, count(*) as n")
+            ->groupByRaw('1, 2')->get();
+        $other = $this->runs($from, $to, $accountType)
+            ->selectRaw("date({$this->time()}) as d")
+            ->selectRaw("count(*) filter (where r.status = 'denied') as denied")
+            ->selectRaw("count(*) filter (where r.status = 'error') as errors")
+            ->selectRaw("percentile_cont(0.5) within group (order by r.latency_ms) filter (where r.status = 'ok') as p50")
+            ->selectRaw("percentile_cont(0.95) within group (order by r.latency_ms) filter (where r.status = 'ok') as p95")
+            ->groupByRaw('1')->get()->keyBy(fn ($r) => substr((string) $r->d, 0, 10));
+        $votes = $this->runs($from, $to, $accountType)
+            ->join('agent_feedback as f', 'f.message_id', '=', 'r.assistant_message_id')
+            ->selectRaw("date({$this->time()}) as d, count(*) filter (where f.rating > 0) as up, count(*) filter (where f.rating < 0) as down")
+            ->groupByRaw('1')->get()->keyBy(fn ($r) => substr((string) $r->d, 0, 10));
+
+        $rows = [];
+        for ($day = $from; $day->lte($to); $day = $day->addDay()) {
+            $d = $day->toDateString();
+            $rows[$d] = ['date' => $d] + array_fill_keys([...AgentRun::ROUTES, 'none'], 0) + [
+                'denied' => (int) ($other[$d]->denied ?? 0),
+                'errors' => (int) ($other[$d]->errors ?? 0),
+                'latency_p50_ms' => isset($other[$d]) && $other[$d]->p50 !== null ? (int) round((float) $other[$d]->p50) : null,
+                'latency_p95_ms' => isset($other[$d]) && $other[$d]->p95 !== null ? (int) round((float) $other[$d]->p95) : null,
+                'feedback_up' => (int) ($votes[$d]->up ?? 0),
+                'feedback_down' => (int) ($votes[$d]->down ?? 0),
+            ];
+        }
+        foreach ($byRoute as $row) {
+            $d = substr((string) $row->d, 0, 10);
+            $route = in_array($row->route, AgentRun::ROUTES, true) ? $row->route : 'none';
+            if (isset($rows[$d])) {
+                $rows[$d][$route] += (int) $row->n;
+            }
+        }
+
+        return array_values($rows);
+    }
+
+    /**
+     * @return list<array{name: string, calls: int, errors: int, avg_ms: int}>
+     */
+    private function tools(CarbonImmutable $from, CarbonImmutable $to, string $accountType): array
+    {
+        return $this->runs($from, $to, $accountType)
+            ->join('agent_run_steps as s', fn ($j) => $j->on('s.agent_run_id', '=', 'r.id')->whereNull('s.deleted_at'))
+            ->where('s.kind', 'tool')
+            ->selectRaw("coalesce(s.name, '?') as name, count(*) as calls, count(*) filter (where s.error is not null) as errors, coalesce(avg(s.ms), 0) as avg_ms")
+            ->groupByRaw('1')->orderByDesc('calls')->limit(10)->get()
+            ->map(fn ($r) => ['name' => $r->name, 'calls' => (int) $r->calls, 'errors' => (int) $r->errors, 'avg_ms' => (int) round((float) $r->avg_ms)])
+            ->all();
+    }
+
+    /**
+     * 区间内的积分流水:赠送 / 积分消耗、退回、读经 / 编辑发放、手工调整(正负分开记)。
+     *
+     * @return array<string, int>
+     */
+    private function creditFlows(CarbonImmutable $from, CarbonImmutable $to, string $accountType): array
+    {
+        $row = DB::table('credit_ledger')
+            ->whereBetween('day', [$from->toDateString(), $to->toDateString()])
+            ->when($accountType !== 'all', fn ($q) => $q->where('account_type', $accountType))
+            ->selectRaw("coalesce(-sum(delta) filter (where kind = 'spend' and bucket = 'free'), 0) as spent_free")
+            ->selectRaw("coalesce(-sum(delta) filter (where kind = 'spend' and bucket = 'earned'), 0) as spent_earned")
+            ->selectRaw("coalesce(sum(delta) filter (where kind = 'refund'), 0) as refunded")
+            ->selectRaw("coalesce(sum(delta) filter (where kind = 'earn' and source = 'reading'), 0) as earned_reading")
+            ->selectRaw("coalesce(sum(delta) filter (where kind = 'earn' and source = 'editing'), 0) as earned_editing")
+            ->selectRaw("coalesce(sum(delta) filter (where kind = 'adjust'), 0) as adjusted")
+            ->first();
+
+        return array_map('intval', (array) $row);
+    }
+
+    /**
+     * 提问列表(管理员查阅),最新的在前。
+     *
+     * @param  array{filter?: array{status?: string, route?: string, account_type?: string, client?: string, improve?: bool|string, q?: string}}  $filters
+     * @return LengthAwarePaginator<int, AgentRun>
+     */
+    public function listRuns(array $filters, int $perPage): LengthAwarePaginator
+    {
+        $f = $filters['filter'] ?? [];
+
+        return AgentRun::query()
+            ->with(['thread:id,thread_id,account_type,account_id,title', UserService::eagerLoadActor()[0]])
+            ->when($f['status'] ?? null, fn ($q, $v) => $q->where('status', $v))
+            ->when($f['route'] ?? null, fn ($q, $v) => $q->where('route', $v))
+            ->when($f['client'] ?? null, fn ($q, $v) => $q->where('client', $v))
+            ->when($f['account_type'] ?? null, fn ($q, $v) => $q->where('account_type', $v))
+            ->when(isset($f['improve']), fn ($q) => $q->where('improve', filter_var($f['improve'], FILTER_VALIDATE_BOOLEAN)))
+            ->when($f['q'] ?? null, fn ($q, $v) => $q->where('question', 'ilike', '%'.addcslashes($v, '%_\\').'%'))
+            ->orderByDesc('id')
+            ->paginate($perPage);
+    }
+
+    /**
+     * 分析用的精简导出:区间内**允许用于改进回答**(improve=true)的提问,最早的在前,最多 $limit 条。
+     *
+     * 不带任何身份(账号、设备、IP)。每条只给分析要用的:问题、路由与把握度、计划里的检索词、
+     * 状态与耗时、工具调用序列(名称 / 耗时 / 结果字数 / 是否出错)、用户评价、隐式信号计数,
+     * 以及同一会话里下一次提问隔了几秒(短间隔常是「没答到点子上、换个说法再问」)。
+     * `$full` 时再带回答、证据全文与引用——回答质量由 agent 拉去评估,服务端不做。
+     *
+     * @return array{items: list<array<string, mixed>>, has_more: bool}
+     */
+    public function digest(CarbonImmutable $from, CarbonImmutable $to, int $limit, bool $full = false): array
+    {
+        $rows = $this->runs($from, $to, 'all')
+            ->where('r.improve', true)
+            ->select(['r.id', 'r.run_id', 'r.started_at', 'r.question', 'r.route', 'r.route_raw', 'r.confidence', 'r.deep', 'r.status',
+                'r.latency_ms', 'r.plan', 'r.passage', 'r.retries', 'r.llm_calls', 'r.tool_calls', 'r.tokens_in', 'r.tokens_out',
+                'r.client', 'r.assistant_message_id'])
+            ->when($full, fn ($q) => $q->addSelect(['r.answer', 'r.evidence', 'r.citations']))
+            ->selectRaw('extract(epoch from (lead(r.started_at) over (partition by r.agent_thread_id order by r.started_at) - r.started_at)) as next_after')
+            ->orderBy('r.started_at')->orderBy('r.id')
+            ->limit($limit + 1)
+            ->get();
+        $hasMore = $rows->count() > $limit;
+        $rows = $rows->take($limit);
+
+        $ids = $rows->pluck('id');
+        $messages = $rows->pluck('assistant_message_id')->filter()->values();
+        $steps = DB::table('agent_run_steps')->whereIn('agent_run_id', $ids)->whereNull('deleted_at')->where('kind', 'tool')
+            ->orderBy('seq')->get(['agent_run_id', 'name', 'ms', 'result_chars', 'error'])->groupBy('agent_run_id');
+        $feedback = DB::table('agent_feedback')->whereIn('message_id', $messages)
+            ->get(['message_id', 'rating', 'tags', 'comment', 'asked'])->groupBy('message_id');
+        $events = DB::table('agent_events')->whereIn('message_id', $messages)
+            ->selectRaw('message_id, kind, count(*) as n')->groupBy('message_id', 'kind')->get()->groupBy('message_id');
+
+        $items = $rows->map(function ($r) use ($steps, $feedback, $events, $full) {
+            $plan = $r->plan ? json_decode($r->plan, true) : [];
+            $passage = $r->passage ? json_decode($r->passage, true) : null;
+
+            return [
+                'run_id' => $r->run_id,
+                'started_at' => $r->started_at,
+                'question' => $r->question,
+                'route' => $r->route,
+                'route_raw' => $r->route_raw,
+                'confidence' => $r->confidence === null ? null : round((float) $r->confidence, 2),
+                'deep' => (bool) $r->deep,
+                'from_reader' => $passage !== null,
+                'client' => $r->client,
+                'status' => $r->status,
+                'latency_ms' => $r->latency_ms === null ? null : (int) $r->latency_ms,
+                'lemmas' => $plan['lemmas'] ?? [],
+                'keywords' => array_map(fn ($k) => is_array($k) ? trim(($k['lemma'] ?? '').'|'.($k['tags'] ?? ''), '|') : $k, $plan['keywords'] ?? []),
+                'retries' => (int) $r->retries,
+                'llm_calls' => (int) $r->llm_calls,
+                'tokens' => (int) $r->tokens_in + (int) $r->tokens_out,
+                'tools' => ($steps[$r->id] ?? collect())->map(fn ($s) => [
+                    'name' => $s->name, 'ms' => $s->ms === null ? null : (int) $s->ms,
+                    'chars' => $s->result_chars === null ? null : (int) $s->result_chars, 'error' => $s->error !== null,
+                ])->values()->all(),
+                'feedback' => ($feedback[$r->assistant_message_id] ?? collect())->map(fn ($f) => [
+                    'rating' => (int) $f->rating, 'tags' => $f->tags ? json_decode($f->tags, true) : [],
+                    'comment' => $f->comment, 'asked' => (bool) $f->asked,
+                ])->values()->all(),
+                'events' => ($events[$r->assistant_message_id] ?? collect())->mapWithKeys(fn ($e) => [$e->kind => (int) $e->n])->all(),
+                'next_question_after_s' => $r->next_after === null ? null : (int) round((float) $r->next_after),
+                // 给 agent 评估回答质量用:回答、给作答模型的证据全文、引用
+                ...($full ? [
+                    'answer' => $r->answer,
+                    'evidence' => $r->evidence,
+                    'citations' => $r->citations ? json_decode($r->citations, true) : [],
+                ] : []),
+            ];
+        })->values()->all();
+
+        return ['items' => $items, 'has_more' => $hasMore];
+    }
+
+    /**
+     * 一次提问的完整研究过程(含全部步骤)。
+     *
+     * @throws ModelNotFoundException
+     */
+    public function showRun(string $runId): AgentRun
+    {
+        return AgentRun::with(['thread', 'steps', UserService::eagerLoadActor()[0]])->where('run_id', $runId)->firstOrFail();
+    }
+
+    private function runs(CarbonImmutable $from, CarbonImmutable $to, string $accountType): Builder
+    {
+        // 软删的提问(用户删了会话)不计入任何统计
+        return DB::table('agent_runs as r')
+            ->whereNull('r.deleted_at')
+            ->join('agent_threads as t', 't.id', '=', 'r.agent_thread_id')
+            ->whereRaw("{$this->time()} >= ?", [$from->startOfDay()])
+            ->whereRaw("{$this->time()} < ?", [$to->addDay()->startOfDay()])
+            ->when($accountType !== 'all', fn ($q) => $q->where('r.account_type', $accountType));
+    }
+
+    private function time(): string
+    {
+        return 'r.started_at';
+    }
+}

+ 103 - 0
api-v13/app/Services/V3/AgentThreadService.php

@@ -0,0 +1,103 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Models\AgentRun;
+use App\Models\AgentRunStep;
+use App\Models\AgentThread;
+use Illuminate\Contracts\Pagination\LengthAwarePaginator;
+use Illuminate\Database\Eloquent\ModelNotFoundException;
+use Illuminate\Support\Facades\DB;
+
+/**
+ * 登录用户的 AI 对话会话历史:列表、详情、改名、存档、删除。
+ *
+ * 只认登录用户的账号(account_type = user)——游客没有历史接口(设备 id 不是秘密,不能凭它读)。
+ * 别人的会话与不存在的会话一样回 404,不暴露「这个 thread 有主」。
+ */
+class AgentThreadService
+{
+    /**
+     * 我的会话列表,最近提问的在前。用户删除过的不列。
+     *
+     * @param  array{filter?: array{archived?: bool|string}}  $filters
+     * @return LengthAwarePaginator<int, AgentThread>
+     */
+    public function listForUser(string $userUid, array $filters, int $perPage): LengthAwarePaginator
+    {
+        $archived = $filters['filter']['archived'] ?? null;
+
+        return AgentThread::ownedBy(AgentAccount::user($userUid))
+            ->when($archived !== null, fn ($q) => filter_var($archived, FILTER_VALIDATE_BOOLEAN)
+                ? $q->whereNotNull('archived_at')
+                : $q->whereNull('archived_at'))
+            ->orderByDesc('last_run_at')
+            ->orderByDesc('id')
+            ->paginate($perPage);
+    }
+
+    /**
+     * 一个会话及其全部可见的问答轮次(被「重新生成」替换掉的不算),按提问先后排。
+     */
+    public function showForUser(string $userUid, string $threadId): AgentThread
+    {
+        return $this->findForUser($userUid, $threadId)->load([
+            'runs' => fn ($q) => $q->visible()->orderBy('started_at')->orderBy('id'),
+        ]);
+    }
+
+    /**
+     * @param  array{title?: string}  $data
+     */
+    public function update(string $userUid, string $threadId, array $data): AgentThread
+    {
+        $thread = $this->findForUser($userUid, $threadId);
+        $thread->fill($data)->save();
+
+        return $thread;
+    }
+
+    /**
+     * 存档 / 取消存档。重复存档保留第一次的时间。
+     */
+    public function setArchived(string $userUid, string $threadId, bool $archived): AgentThread
+    {
+        $thread = $this->findForUser($userUid, $threadId);
+        if ($archived && $thread->archived_at === null) {
+            $thread->archived_at = now();
+        } elseif (! $archived) {
+            $thread->archived_at = null;
+        }
+        $thread->save();
+
+        return $thread;
+    }
+
+    /**
+     * 删除=软删会话,连同它的提问与步骤一起软删:之后任何接口(含将来的分享)都读不到,
+     * 数据永久保留(研究过程要留着防滥用、改进回答)。
+     */
+    public function hide(string $userUid, string $threadId): AgentThread
+    {
+        $thread = $this->findForUser($userUid, $threadId);
+
+        DB::transaction(function () use ($thread) {
+            $runIds = AgentRun::where('agent_thread_id', $thread->id)->pluck('id');
+            AgentRunStep::whereIn('agent_run_id', $runIds)->delete();
+            AgentRun::whereIn('id', $runIds)->delete();
+            $thread->delete();
+        });
+
+        return $thread;
+    }
+
+    /**
+     * @throws ModelNotFoundException 不存在、不是我的、或已删除 → 404
+     */
+    private function findForUser(string $userUid, string $threadId): AgentThread
+    {
+        return AgentThread::ownedBy(AgentAccount::user($userUid))
+            ->where('thread_id', $threadId)
+            ->firstOrFail();
+    }
+}

+ 139 - 0
api-v13/app/Services/V3/AgentTraceService.php

@@ -0,0 +1,139 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Http\Requests\V3\StoreAgentTraceRequest;
+use App\Models\AgentFeedback;
+use App\Models\AgentRun;
+use App\Models\AgentRunStep;
+use App\Models\AgentThread;
+use Illuminate\Support\Arr;
+use Illuminate\Support\Carbon;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Validation\ValidationException;
+
+/**
+ * AI 对话的研究过程入库与清理。
+ *
+ * 写入方是 agent 服务(服务密钥鉴权),终端用户由它透传的 bearer 决定:
+ * 有效的人类 token → 记到账号下;没有 / 失效 / 是模型 token → 记为游客,
+ * 只认设备匿名 id,并记客户端 IP。token 失效也照记不拒——这批记录要用来防滥用,
+ * 不能因为用户登录过期就丢。
+ */
+class AgentTraceService
+{
+    /**
+     * 会话标题取第一句提问的前多少个字。
+     */
+    private const TITLE_LENGTH = 60;
+
+    public function __construct(
+        private readonly AgentAccountService $accounts,
+        private readonly CreditService $credits,
+    ) {}
+
+    /**
+     * 写入一次提问(幂等)。
+     *
+     * run_id 已存在时原样返回已有的那条(`wasRecentlyCreated` 为 false → 200),
+     * agent 端补发同一条不会写出第二份。status=error 且没有回答时退回这次的扣费。
+     *
+     * @param  array<string, mixed>  $data  {@see StoreAgentTraceRequest} 校验过的入参
+     *
+     * @throws ValidationException 游客没带 device_id
+     */
+    public function record(?string $bearerUid, array $data): AgentRun
+    {
+        $account = $this->accounts->resolve($bearerUid, $data['device_id'] ?? null);
+        $startedAt = isset($data['started_at']) ? Carbon::parse($data['started_at']) : now();
+
+        return DB::transaction(function () use ($data, $account, $startedAt) {
+            // 已删除(软删)的提问也算存在:补发同一条不会重建出一份来
+            $existing = AgentRun::withTrashed()->with('thread')->where('run_id', $data['run_id'])->first();
+            if ($existing) {
+                return $existing;
+            }
+
+            $thread = AgentThread::withTrashed()->createOrFirst(
+                ['thread_id' => $data['thread_id']],
+                [
+                    ...$account->columns(),
+                    'title' => $this->titleOf($data['question']),
+                    'client' => $data['client'] ?? null,
+                    'last_run_at' => $startedAt,
+                ],
+            );
+            // threadId 全局唯一:别的账号的会话不准往里写(扣费时已拦过,这里兜底)
+            if (! $thread->isOwnedBy($account)) {
+                abort(403, __('messages.agent_thread_forbidden'));
+            }
+            if ($thread->last_run_at === null || $thread->last_run_at->lt($startedAt)) {
+                $thread->last_run_at = $startedAt;
+                $thread->save();
+            }
+
+            // 评价先于研究过程到达时:评价了就是同意用于改进(客户端评价前已征得同意)
+            if (! ($data['improve'] ?? true) && ! empty($data['assistant_message_id'])
+                && AgentFeedback::ownedBy($account)->where('message_id', $data['assistant_message_id'])->exists()) {
+                $data['improve'] = true;
+            }
+
+            // 重新生成:客户端只知道被替换那条回答的消息 id,在同一会话里换算成那一轮的 run_id。
+            // 会话历史回放时被替换的那一轮不再返回(AgentRun::scopeVisible)
+            if (empty($data['replaces_run_id']) && ! empty($data['replaces_message_id'])) {
+                $data['replaces_run_id'] = AgentRun::where('agent_thread_id', $thread->id)
+                    ->where('assistant_message_id', $data['replaces_message_id'])
+                    ->value('run_id');
+            }
+
+            $run = AgentRun::withTrashed()->createOrFirst(['run_id' => $data['run_id']], [
+                ...Arr::except($data, ['run_id', 'thread_id', 'device_id', 'client_ip', 'steps', 'replaces_message_id']),
+                'agent_thread_id' => $thread->id,
+                ...$account->columns(),
+                'client_ip' => $account->isUser() ? null : ($data['client_ip'] ?? null),
+                'started_at' => $startedAt,
+            ]);
+
+            if ($run->wasRecentlyCreated) {
+                $this->warnUnknown($run->run_id, $data);
+            }
+            if ($run->wasRecentlyCreated && ! empty($data['steps'])) {
+                $run->steps()->createMany($data['steps']);
+            }
+            // 服务端出错、回答没生成 → 退回这次的扣费。用户自己中途取消(cancelled)照扣
+            if ($run->wasRecentlyCreated && $run->status === 'error' && blank($run->answer)) {
+                $this->credits->refundRun($run->run_id);
+            }
+
+            return $run->setRelation('thread', $thread);
+        });
+    }
+
+    /**
+     * backend 送来了 mint 还不认识的路由或步骤类型:照样入库,记一条警告提醒同步枚举
+     * (AgentRun::ROUTES / AgentRunStep::KINDS,以及 OpenAPI 与前端)。
+     *
+     * @param  array<string, mixed>  $data
+     */
+    private function warnUnknown(string $runId, array $data): void
+    {
+        $route = $data['route'] ?? null;
+        if ($route !== null && ! in_array($route, AgentRun::ROUTES, true)) {
+            Log::warning('agent trace: unknown route', ['run_id' => $runId, 'route' => $route]);
+        }
+        $kinds = array_diff(array_unique(array_column($data['steps'] ?? [], 'kind')), AgentRunStep::KINDS);
+        if ($kinds !== []) {
+            Log::warning('agent trace: unknown step kinds', ['run_id' => $runId, 'kinds' => array_values($kinds)]);
+        }
+    }
+
+    private function titleOf(string $question): string
+    {
+        $flat = trim((string) preg_replace('/\s+/u', ' ', $question));
+
+        return mb_strlen($flat) > self::TITLE_LENGTH
+            ? mb_substr($flat, 0, self::TITLE_LENGTH).'…'
+            : $flat;
+    }
+}

+ 411 - 0
api-v13/app/Services/V3/CreditService.php

@@ -0,0 +1,411 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Exceptions\BusinessException;
+use App\Models\CreditLedgerEntry;
+use App\Models\ReadingDaily;
+use App\Models\UserInfo;
+use App\Models\UserOperationDaily;
+use Carbon\CarbonInterface;
+use Illuminate\Support\Arr;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Validation\ValidationException;
+
+/**
+ * AI 对话的额度与积分。
+ *
+ * 两个池子:
+ * - **每日赠送池**(bucket=free):每个 UTC 日按策略送一份,当天用完不累积。赠送本身不入账,
+ *   「今天还剩多少」= 赠送额 − 当天 free 流水的消耗;
+ * - **积分余额**(bucket=earned):读经、编辑时长赚来的,加上手工调整,不过期。
+ *
+ * 每次提问先扣赠送池,不够再扣积分余额;两者合计不够就拒绝(402)。
+ * 规则全部来自当前生效的策略 `config('mint.credits.policy')`(公开:`GET /v3/credit-policy`),
+ * 字段说明见 agent-poc 仓库 docs/credits.md。
+ */
+class CreditService
+{
+    /**
+     * 当前生效的策略。version 是生效日(YYYYMMDD),记进每笔流水。
+     *
+     * @return array{version: int, rules: array<string, mixed>}
+     */
+    public function policy(): array
+    {
+        $policy = config('mint.credits.policy');
+
+        return ['version' => (int) $policy['version'], 'rules' => Arr::except($policy, 'version')];
+    }
+
+    /**
+     * 某个账号此刻的额度概况。登录用户会先把今天(和昨天)的读经 / 编辑时长结算成积分。
+     *
+     * @return array{account_type: string, day: string, resets_at: string, policy_version: int, daily_free: int, free_used: int, free_remaining: int, earned_balance: int, cost: array{normal: int, deep: int}, earned_today: array{reading: int, editing: int}, earn: array<string, mixed>}
+     */
+    public function quota(AgentAccount $account): array
+    {
+        $today = $this->today();
+        if ($account->isUser()) {
+            $this->settleRecent($account->id);
+        }
+        $rules = $this->policy()['rules'];
+        $dailyFree = (int) ($rules['daily_free'][$account->type] ?? 0);
+        $freeUsed = $this->freeUsed($account, $today);
+
+        return [
+            'account_type' => $account->type,
+            'day' => $today->toDateString(),
+            'resets_at' => $today->copy()->addDay()->toIso8601ZuluString(),
+            'policy_version' => $this->policy()['version'],
+            'daily_free' => $dailyFree,
+            'free_used' => $freeUsed,
+            'free_remaining' => max(0, $dailyFree - $freeUsed),
+            'earned_balance' => $this->earnedBalance($account),
+            'cost' => ['normal' => (int) $rules['cost']['normal'], 'deep' => (int) $rules['cost']['deep']],
+            'earned_today' => [
+                'reading' => $this->earnedOn($account, 'reading', $today),
+                'editing' => $this->earnedOn($account, 'editing', $today),
+            ],
+            'earn' => $account->isUser() ? $rules['earn'] : [],
+        ];
+    }
+
+    /**
+     * 为一次提问扣费(按 run_id 幂等)。先扣赠送池,再扣积分余额。
+     *
+     * @return array{run_id: string, created: bool, cost: int, charged_free: int, charged_earned: int, free_remaining: int, earned_balance: int, policy_version: int}
+     *
+     * @throws BusinessException 402:额度不足或游客同 IP 超上限
+     */
+    public function charge(AgentAccount $account, string $runId, bool $deep, ?string $clientIp): array
+    {
+        if ($account->isUser()) {
+            $this->settleRecent($account->id);
+        }
+        // 游客的同 IP 每日上限靠 IP:拿不到 IP 就不让问,否则上限形同虚设(伪造设备 id 就能无限领赠送额度)
+        if (! $account->isUser() && blank($clientIp)) {
+            throw ValidationException::withMessages(['client_ip' => __('messages.agent_client_ip_required')]);
+        }
+        $today = $this->today();
+        ['version' => $version, 'rules' => $rules] = $this->policy();
+        $clientIp = $account->isUser() ? null : $clientIp;
+
+        return DB::transaction(function () use ($account, $runId, $deep, $clientIp, $today, $version, $rules) {
+            // 同一账号的扣费串行化,避免并发的两次提问都看到「还够」
+            DB::select('select pg_advisory_xact_lock(hashtext(?))', [$account->key()]);
+
+            $existing = CreditLedgerEntry::ownedBy($account)
+                ->where('source', 'agent_run')->where('ref', $runId)->where('kind', 'spend')->get();
+            $dailyFree = (int) ($rules['daily_free'][$account->type] ?? 0);
+            if ($existing->isNotEmpty()) {
+                return $this->chargeResult($account, $runId, false, $existing, $dailyFree, $today, $version);
+            }
+
+            $cost = (int) ($deep ? $rules['cost']['deep'] : $rules['cost']['normal']);
+            $freeRemaining = max(0, $dailyFree - $this->freeUsed($account, $today));
+            $balance = $this->earnedBalance($account);
+
+            $ipCap = $rules['guest_ip_daily_cap'] ?? null;
+            if ($clientIp && $ipCap !== null && $this->ipSpent($clientIp, $today) + $cost > (int) $ipCap) {
+                throw $this->exhausted('ip_cap', $cost, $freeRemaining, $balance);
+            }
+            if ($freeRemaining + $balance < $cost) {
+                // 游客读经不给积分,提示登录;登录用户提示读经
+                throw $this->exhausted('insufficient', $cost, $freeRemaining, $balance, $account->type);
+            }
+
+            $fromFree = min($cost, $freeRemaining);
+            $rows = collect(['free' => $fromFree, 'earned' => $cost - $fromFree])
+                ->filter(fn (int $amount) => $amount > 0)
+                ->map(fn (int $amount, string $bucket) => CreditLedgerEntry::create([
+                    ...$account->columns(),
+                    'delta' => -$amount,
+                    'kind' => 'spend',
+                    'bucket' => $bucket,
+                    'source' => 'agent_run',
+                    'ref' => $runId,
+                    'day' => $today->toDateString(),
+                    'policy_version' => $version,
+                    'client_ip' => $clientIp,
+                    'note' => $deep ? 'deep' : null,
+                ]))->values();
+
+            return $this->chargeResult($account, $runId, true, $rows, $dailyFree, $today, $version);
+        });
+    }
+
+    /**
+     * 退回某次提问的扣费(服务端出错、回答没生成)。按原消耗逐池退回,day 沿用原消耗那天。
+     * 没扣过费就什么都不做;重复退款不会退两次。
+     */
+    public function refundRun(string $runId): void
+    {
+        $spends = CreditLedgerEntry::where('source', 'agent_run')->where('ref', $runId)->where('kind', 'spend')->get();
+        foreach ($spends as $spend) {
+            CreditLedgerEntry::createOrFirst([
+                'account_type' => $spend->account_type,
+                'account_id' => $spend->account_id,
+                'source' => 'agent_run',
+                'ref' => $runId,
+                'kind' => 'refund',
+                'bucket' => $spend->bucket,
+            ], [
+                'delta' => -$spend->delta,
+                'day' => $spend->day->toDateString(),
+                'policy_version' => $spend->policy_version,
+                'client_ip' => $spend->client_ip,
+            ]);
+        }
+    }
+
+    /**
+     * 把某个登录用户某一天的读经、编辑时长结算成积分(可重复执行,结果覆盖)。
+     *
+     * @return array{reading: int, editing: int}
+     */
+    public function settle(string $userUid, CarbonInterface $day): array
+    {
+        ['version' => $version, 'rules' => $rules] = $this->policy();
+        $account = AgentAccount::user($userUid);
+        $userSn = UserInfo::where('userid', $userUid)->value('id');
+
+        $readingSeconds = (int) ReadingDaily::where('user_uid', $userUid)->where('day', $day->toDateString())->value('seconds');
+        $editingMs = $userSn === null ? 0 : (int) UserOperationDaily::where('user_id', $userSn)
+            ->whereBetween('date_int', $this->editingWindow($day))
+            ->sum('duration');
+
+        $amounts = [
+            'reading' => $this->earnAmount($rules['earn']['reading'] ?? null, intdiv($readingSeconds, 60)),
+            'editing' => $this->earnAmount($rules['earn']['editing'] ?? null, intdiv($editingMs, 60_000)),
+        ];
+        foreach ($amounts as $source => $amount) {
+            $keys = [...$account->columns(), 'source' => $source, 'ref' => $day->toDateString(), 'kind' => 'earn', 'bucket' => 'earned'];
+            if ($amount > 0 || CreditLedgerEntry::where($keys)->exists()) {
+                $entry = CreditLedgerEntry::updateOrCreate($keys, [
+                    'delta' => $amount,
+                    'day' => $day->toDateString(),
+                    'policy_version' => $version,
+                ]);
+                // updated_at=最后一次结算的时间:数额没变也要记下「结算过了」,
+                // 否则当天中途结算的那笔永远被 settleMissing 当成没结清
+                if (! $entry->wasRecentlyCreated && ! $entry->wasChanged()) {
+                    $entry->touch();
+                }
+            }
+        }
+
+        return $amounts;
+    }
+
+    /**
+     * 结算某一天所有有活动的登录用户,返回人数。供每日命令使用。
+     */
+    /**
+     * 补齐漏结算的日子:从 $since 到 $until(UTC 日,含两端),找出有活动却没结清的「用户 + 日」重新结算。
+     * 结算任务漏跑几天都能补上,工作量只跟漏掉的量有关。
+     *
+     * 算「没结清」的两种情况(只看至少 1 分钟的活动,不足 1 分钟本来就不给积分):
+     * - 账单里没有那天这个来源的积分;
+     * - 有,但最后一次结算早于那天的活动结束——读经按 UTC 日,到次日 0 点;编辑按客户端本地日
+     *   (见 editingWindow),最晚到次日 12:00 UTC。之后又攒的时长要补上。
+     *
+     * 补算用当前生效的策略(历史策略不保留,见 config mint.credits.policy)。
+     *
+     * @return array{pairs: int, users: int}
+     */
+    public function settleMissing(CarbonInterface $since, CarbonInterface $until): array
+    {
+        $since = $since->copy()->startOfDay();
+        $until = $until->copy()->startOfDay();
+
+        // 有至少 1 分钟活动的「用户 + 日」,以及那天活动结束的时刻
+        $activity = [];
+        ReadingDaily::whereBetween('day', [$since->toDateString(), $until->toDateString()])
+            ->where('seconds', '>=', 60)
+            ->get(['user_uid', 'day'])
+            ->each(function (ReadingDaily $row) use (&$activity) {
+                $day = $row->day->toDateString();
+                $activity["{$row->user_uid}|{$day}"]['reading'] = $row->day->copy()->addDay();
+            });
+        UserOperationDaily::join('user_infos', 'user_infos.id', '=', 'user_operation_dailies.user_id')
+            ->whereBetween('user_operation_dailies.date_int', [$this->editingWindow($since)[0], $this->editingWindow($until)[1]])
+            ->selectRaw("user_infos.userid as user_uid, (to_timestamp((user_operation_dailies.date_int + 43200000) / 1000.0) at time zone 'UTC')::date as local_day")
+            ->groupByRaw('1, 2')
+            ->havingRaw('sum(user_operation_dailies.duration) >= 60000')
+            ->get()
+            ->each(function ($row) use (&$activity) {
+                $day = substr((string) $row->local_day, 0, 10);
+                $activity["{$row->user_uid}|{$day}"]['editing'] = now('UTC')->parse($day)->addDay()->addHours(12);
+            });
+        if ($activity === []) {
+            return ['pairs' => 0, 'users' => 0];
+        }
+
+        // 已有的积分及其最后结算时间
+        $settled = CreditLedgerEntry::where('account_type', 'user')
+            ->whereIn('source', ['reading', 'editing'])
+            ->where('kind', 'earn')
+            ->whereBetween('day', [$since->toDateString(), $until->toDateString()])
+            ->get(['account_id', 'source', 'ref', 'updated_at'])
+            ->mapWithKeys(fn (CreditLedgerEntry $e) => ["{$e->account_id}|{$e->ref}|{$e->source}" => $e->updated_at]);
+
+        $pairs = 0;
+        $users = [];
+        foreach ($activity as $key => $sources) {
+            $missing = false;
+            foreach ($sources as $source => $closesAt) {
+                $at = $settled["{$key}|{$source}"] ?? null;
+                if ($at === null || $at->lt($closesAt)) {
+                    $missing = true;
+                }
+            }
+            if (! $missing) {
+                continue;
+            }
+            [$userUid, $day] = explode('|', $key);
+            $this->settle($userUid, now('UTC')->parse($day)->startOfDay());
+            $pairs++;
+            $users[$userUid] = true;
+        }
+
+        return ['pairs' => $pairs, 'users' => count($users)];
+    }
+
+    public function settleDay(CarbonInterface $day): int
+    {
+        $fromReading = ReadingDaily::where('day', $day->toDateString())->distinct()->pluck('user_uid');
+        $editorSns = UserOperationDaily::whereBetween('date_int', $this->editingWindow($day))->distinct()->pluck('user_id');
+        $fromEditing = UserInfo::whereIn('id', $editorSns)->pluck('userid');
+
+        $users = $fromReading->merge($fromEditing)->unique()->values();
+        foreach ($users as $userUid) {
+            $this->settle((string) $userUid, $day);
+        }
+
+        return $users->count();
+    }
+
+    /**
+     * 手工加减积分(积分余额池)。ref 由调用方给,同一 ref 只生效一次。
+     */
+    public function adjust(AgentAccount $account, int $delta, string $ref, ?string $note): CreditLedgerEntry
+    {
+        return CreditLedgerEntry::createOrFirst([
+            ...$account->columns(),
+            'source' => 'admin',
+            'ref' => $ref,
+            'kind' => 'adjust',
+            'bucket' => 'earned',
+        ], [
+            'delta' => $delta,
+            'day' => $this->today()->toDateString(),
+            'policy_version' => $this->policy()['version'],
+            'note' => $note,
+        ]);
+    }
+
+    /**
+     * 今天和昨天都结算一次:昨天深夜的活动在每日命令跑之前也能及时到账。
+     */
+    private function settleRecent(string $userUid): void
+    {
+        $today = $this->today();
+        $this->settle($userUid, $today);
+        $this->settle($userUid, $today->copy()->subDay());
+    }
+
+    /**
+     * @param  array{credits_per_minute?: int, daily_cap?: int|null}|null  $rule
+     */
+    private function earnAmount(?array $rule, int $minutes): int
+    {
+        if (! $rule) {
+            return 0;
+        }
+        $amount = $minutes * (int) ($rule['credits_per_minute'] ?? 0);
+        $cap = $rule['daily_cap'] ?? null;
+
+        return $cap === null ? $amount : min($amount, (int) $cap);
+    }
+
+    /**
+     * user_operation_dailies.date_int 是「客户端本地日的零点」的毫秒时间戳(随客户端时区漂移)。
+     * 加 12 小时再落到 UTC 日,就是那个本地日的日期——对 UTC−12 到 UTC+12 都成立,
+     * 且每行只落进一天,不会重复计。
+     *
+     * @return array{0: int, 1: int}
+     */
+    private function editingWindow(CarbonInterface $day): array
+    {
+        $start = $day->copy()->startOfDay()->getTimestampMs() - 12 * 3600 * 1000;
+
+        return [$start, $start + 24 * 3600 * 1000 - 1];
+    }
+
+    private function today(): CarbonInterface
+    {
+        return now('UTC')->startOfDay();
+    }
+
+    private function freeUsed(AgentAccount $account, CarbonInterface $day): int
+    {
+        return -(int) CreditLedgerEntry::ownedBy($account)
+            ->where('bucket', 'free')->where('day', $day->toDateString())->sum('delta');
+    }
+
+    private function earnedBalance(AgentAccount $account): int
+    {
+        return (int) CreditLedgerEntry::ownedBy($account)->where('bucket', 'earned')->sum('delta');
+    }
+
+    private function earnedOn(AgentAccount $account, string $source, CarbonInterface $day): int
+    {
+        return (int) CreditLedgerEntry::ownedBy($account)->where('source', $source)
+            ->where('kind', 'earn')->where('day', $day->toDateString())->sum('delta');
+    }
+
+    /**
+     * 同一 IP 下所有游客当天的净消耗(退回的不算)。
+     */
+    private function ipSpent(string $clientIp, CarbonInterface $day): int
+    {
+        return -(int) CreditLedgerEntry::where('client_ip', $clientIp)->where('day', $day->toDateString())
+            ->where('account_type', 'guest')->whereIn('kind', ['spend', 'refund'])->sum('delta');
+    }
+
+    /**
+     * @param  Collection<int, CreditLedgerEntry>  $rows
+     * @return array{run_id: string, created: bool, cost: int, charged_free: int, charged_earned: int, free_remaining: int, earned_balance: int, policy_version: int}
+     */
+    private function chargeResult(AgentAccount $account, string $runId, bool $created, $rows, int $dailyFree, CarbonInterface $today, int $version): array
+    {
+        $free = -(int) $rows->where('bucket', 'free')->sum('delta');
+        $earned = -(int) $rows->where('bucket', 'earned')->sum('delta');
+
+        return [
+            'run_id' => $runId,
+            'created' => $created,
+            'cost' => $free + $earned,
+            'charged_free' => $free,
+            'charged_earned' => $earned,
+            'free_remaining' => max(0, $dailyFree - $this->freeUsed($account, $today)),
+            'earned_balance' => $this->earnedBalance($account),
+            'policy_version' => $version,
+        ];
+    }
+
+    private function exhausted(string $reason, int $cost, int $freeRemaining, int $balance, string $accountType = 'guest'): BusinessException
+    {
+        $key = $reason === 'insufficient' ? "agent_quota_insufficient_{$accountType}" : "agent_quota_{$reason}";
+
+        return new BusinessException(
+            __("messages.{$key}"),
+            402,
+            'quota-exceeded',
+            ['reason' => $reason, 'cost' => $cost, 'free_remaining' => $freeRemaining, 'earned_balance' => $balance],
+            'Quota Exceeded',
+        );
+    }
+}

+ 280 - 0
api-v13/app/Services/V3/ReadingStatsService.php

@@ -0,0 +1,280 @@
+<?php
+
+namespace App\Services\V3;
+
+use Carbon\CarbonImmutable;
+use Illuminate\Database\Query\Builder;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\DB;
+
+/**
+ * 管理后台「阅读统计」。时间范围按 UTC 日,闭区间 [from, to]。
+ *
+ * 数据来源与口径(也写在 dashboard-v6 统计页每张卡片下方):
+ * - **活跃读者**:阅读记录 `recents` 在区间内有更新的去重登录用户。recents 是按(用户, 章节)upsert 的,
+ *   只记最后一次,所以「打开章节」是「区间内有更新的阅读记录数」,不是逐次打开数。
+ * - **客户端**:recents.param 里 `client=mobile` 或 `mode=reading`(mobile 的写法;网页写 read / edit / wbw)
+ *   算 App,其余算 Web。
+ * - **读经时长**:`reading_dailies`,只有 App 登录用户上报;Web 没有计时。
+ * - **章节浏览**:`views` 在区间内有更新的行(访客 × 章节),含游客与搜索引擎爬虫,只做趋势参考。
+ * - **查词**:`user_operation_logs` 里的 dict_lookup(v2 接口的登录用户请求)。
+ *
+ * 结果缓存 10 分钟。
+ */
+class ReadingStatsService
+{
+    private const CACHE_SECONDS = 600;
+
+    public const PITAKA_TAGS = ['sutta', 'vinaya', 'abhidhamma', 'añña'];
+
+    public const LAYER_TAGS = ['mūla', 'aṭṭhakathā', 'ṭīkā'];
+
+    public function __construct(private readonly CreditService $credits) {}
+
+    /**
+     * @param  'all'|'web'|'mobile'  $client
+     * @return array<string, mixed>
+     */
+    public function stats(CarbonImmutable $from, CarbonImmutable $to, string $client): array
+    {
+        $key = "admin:reading-stats:{$from->toDateString()}:{$to->toDateString()}:{$client}";
+
+        return Cache::remember($key, self::CACHE_SECONDS, function () use ($from, $to, $client) {
+            $days = $from->diffInDays($to) + 1;
+            $prevTo = $from->subDay();
+            $prevFrom = $prevTo->subDays($days - 1);
+
+            return [
+                'range' => ['from' => $from->toDateString(), 'to' => $to->toDateString(), 'client' => $client],
+                'summary' => $this->summary($from, $to, $client),
+                'previous' => $this->summary($prevFrom, $prevTo, $client),
+                'sticky' => $this->sticky($to, $client),
+                'daily' => $this->daily($from, $to, $client),
+                'top_chapters' => $this->topChapters($from, $to, $client),
+                'pitaka_share' => $this->share($from, $to, $client, self::PITAKA_TAGS),
+                'layer_share' => $this->share($from, $to, $client, self::LAYER_TAGS),
+                'duration_buckets' => $client === 'web' ? [] : $this->durationBuckets($from, $to),
+                'reading_credits' => $client === 'web' ? null : $this->readingCredits($from, $to),
+            ];
+        });
+    }
+
+    /**
+     * @return array{active_readers: int, chapters_opened: int, reading_seconds: int|null, reading_users: int|null, page_views: int|null, dict_lookups: int}
+     */
+    private function summary(CarbonImmutable $from, CarbonImmutable $to, string $client): array
+    {
+        $recents = $this->recents($from, $to, $client);
+        $reading = $client === 'web' ? null : DB::table('reading_dailies')
+            ->whereBetween('day', [$from->toDateString(), $to->toDateString()])
+            ->selectRaw('coalesce(sum(seconds), 0) as seconds, count(distinct user_uid) as users')->first();
+
+        return [
+            'active_readers' => (int) (clone $recents)->distinct()->count('user_uid'),
+            'chapters_opened' => (int) (clone $recents)->count(),
+            'reading_seconds' => $reading ? (int) $reading->seconds : null,
+            'reading_users' => $reading ? (int) $reading->users : null,
+            'page_views' => $client === 'mobile' ? null : (int) $this->between(DB::table('views'), 'updated_at', $from, $to)->count(),
+            'dict_lookups' => (int) $this->between(DB::table('user_operation_logs'), 'created_at', $from, $to)
+                ->where('op_type', 'dict_lookup')->count(),
+        ];
+    }
+
+    /**
+     * 日活 / 月活(以区间最后一天为准)。
+     *
+     * @return array{dau: int, mau: int}
+     */
+    private function sticky(CarbonImmutable $to, string $client): array
+    {
+        return [
+            'dau' => (int) $this->recents($to, $to, $client)->distinct()->count('user_uid'),
+            'mau' => (int) $this->recents($to->subDays(29), $to, $client)->distinct()->count('user_uid'),
+        ];
+    }
+
+    /**
+     * 每天一行:Web / App 活跃读者、读经分钟、章节浏览、查词。没有数据的日子补 0。
+     *
+     * @return list<array{date: string, readers_web: int, readers_mobile: int, reading_minutes: int, page_views: int, dict_lookups: int}>
+     */
+    private function daily(CarbonImmutable $from, CarbonImmutable $to, string $client): array
+    {
+        $readers = $this->recents($from, $to, $client)
+            ->selectRaw('date(updated_at) as d, '.$this->clientExpr().' as c, count(distinct user_uid) as n')
+            ->groupByRaw('1, 2')->get();
+        $minutes = DB::table('reading_dailies')->whereBetween('day', [$from->toDateString(), $to->toDateString()])
+            ->selectRaw('day as d, sum(seconds) as s')->groupBy('day')->pluck('s', 'd');
+        $views = $this->between(DB::table('views'), 'updated_at', $from, $to)
+            ->selectRaw('date(updated_at) as d, count(*) as n')->groupByRaw('1')->pluck('n', 'd');
+        $lookups = $this->between(DB::table('user_operation_logs'), 'created_at', $from, $to)->where('op_type', 'dict_lookup')
+            ->selectRaw('date(created_at) as d, count(*) as n')->groupByRaw('1')->pluck('n', 'd');
+
+        $rows = [];
+        for ($day = $from; $day->lte($to); $day = $day->addDay()) {
+            $d = $day->toDateString();
+            $rows[$d] = [
+                'date' => $d,
+                'readers_web' => 0,
+                'readers_mobile' => 0,
+                'reading_minutes' => $client === 'web' ? 0 : intdiv((int) ($minutes[$d] ?? 0), 60),
+                'page_views' => $client === 'mobile' ? 0 : (int) ($views[$d] ?? 0),
+                'dict_lookups' => (int) ($lookups[$d] ?? 0),
+            ];
+        }
+        foreach ($readers as $row) {
+            $d = substr((string) $row->d, 0, 10);
+            if (isset($rows[$d])) {
+                $rows[$d]['readers_'.$row->c] = (int) $row->n;
+            }
+        }
+
+        return array_values($rows);
+    }
+
+    /**
+     * 热门章节:区间内阅读记录最多的章节(按去重读者数)。
+     *
+     * @return list<array{article_id: string, book: int, paragraph: int, title: string, collection: string|null, readers: int, records: int}>
+     */
+    private function topChapters(CarbonImmutable $from, CarbonImmutable $to, string $client, int $limit = 10): array
+    {
+        $top = $this->recents($from, $to, $client)
+            ->where('type', 'chapter')
+            ->selectRaw('article_id, count(distinct user_uid) as readers, count(*) as records')
+            ->groupBy('article_id')->orderByDesc('readers')->orderByDesc('records')->limit($limit)->get();
+
+        return $top->map(function ($row) {
+            [$book, $para] = array_map('intval', explode('-', $row->article_id) + [0, 0]);
+            $text = DB::table('pali_texts')->where('book', $book)->where('paragraph', $para)->first(['toc', 'path']);
+            $path = $text ? json_decode((string) $text->path, true) : [];
+            $title = $text && trim((string) $text->toc) !== '' ? trim((string) $text->toc) : (end($path)['title'] ?? $row->article_id);
+
+            return [
+                'article_id' => $row->article_id,
+                'book' => $book,
+                'paragraph' => $para,
+                'title' => $title,
+                'collection' => $path[0]['title'] ?? null,
+                'readers' => (int) $row->readers,
+                'records' => (int) $row->records,
+            ];
+        })->all();
+    }
+
+    /**
+     * 阅读记录按书的分类标签(三藏 / 根本·义注·复注)分组计数。一本书属于哪一类是固定的,
+     * 标签挂在 pali_texts 的章节行上(tag_maps.table_name = pali_texts),按书取第一个命中的标签。
+     *
+     * @param  list<string>  $tags
+     * @return list<array{tag: string, records: int}>
+     */
+    private function share(CarbonImmutable $from, CarbonImmutable $to, string $client, array $tags): array
+    {
+        $bookTag = $this->bookTags($tags);
+        $counts = [];
+        $rows = $this->recents($from, $to, $client)->where('type', 'chapter')
+            ->selectRaw("split_part(article_id, '-', 1) as book, count(*) as n")->groupByRaw('1')->get();
+        foreach ($rows as $row) {
+            $tag = $bookTag[(int) $row->book] ?? 'other';
+            $counts[$tag] = ($counts[$tag] ?? 0) + (int) $row->n;
+        }
+        arsort($counts);
+
+        return array_map(fn ($tag, $n) => ['tag' => $tag, 'records' => $n], array_keys($counts), $counts);
+    }
+
+    /**
+     * 书 → 标签。目录结构很少变,缓存一天。
+     *
+     * @param  list<string>  $tags
+     * @return array<int, string>
+     */
+    private function bookTags(array $tags): array
+    {
+        return Cache::remember('admin:book-tags:'.md5(implode(',', $tags)), 86400, fn () => DB::table('tag_maps as m')
+            ->join('pali_texts as p', 'p.uid', '=', 'm.anchor_id')
+            ->join('tags as t', 't.id', '=', 'm.tag_id')
+            ->where('m.table_name', 'pali_texts')
+            ->whereIn('t.name', $tags)
+            ->selectRaw('p.book, min(t.name) as tag')
+            ->groupBy('p.book')
+            ->pluck('tag', 'book')
+            ->mapWithKeys(fn ($tag, $book) => [(int) $book => (string) $tag])
+            ->all());
+    }
+
+    /**
+     * 单日读经时长分布(人·天)。
+     *
+     * @return list<array{bucket: string, user_days: int}>
+     */
+    private function durationBuckets(CarbonImmutable $from, CarbonImmutable $to): array
+    {
+        $row = DB::table('reading_dailies')->whereBetween('day', [$from->toDateString(), $to->toDateString()])
+            ->selectRaw('count(*) filter (where seconds < 300) as b1')
+            ->selectRaw('count(*) filter (where seconds >= 300 and seconds < 900) as b2')
+            ->selectRaw('count(*) filter (where seconds >= 900 and seconds < 1800) as b3')
+            ->selectRaw('count(*) filter (where seconds >= 1800 and seconds < 3600) as b4')
+            ->selectRaw('count(*) filter (where seconds >= 3600) as b5')
+            ->first();
+
+        return [
+            ['bucket' => '<5', 'user_days' => (int) $row->b1],
+            ['bucket' => '5-15', 'user_days' => (int) $row->b2],
+            ['bucket' => '15-30', 'user_days' => (int) $row->b3],
+            ['bucket' => '30-60', 'user_days' => (int) $row->b4],
+            ['bucket' => '>60', 'user_days' => (int) $row->b5],
+        ];
+    }
+
+    /**
+     * 读经积分发放:总额、获积分人数、达到每日上限的人·天、服务端按墙钟核减掉的比例。
+     *
+     * @return array{credits: int, users: int, capped_user_days: int, clamped_ratio: float}
+     */
+    private function readingCredits(CarbonImmutable $from, CarbonImmutable $to): array
+    {
+        $cap = $this->credits->policy()['rules']['earn']['reading']['daily_cap'] ?? null;
+        $earn = DB::table('credit_ledger')->where('account_type', 'user')->where('source', 'reading')->where('kind', 'earn')
+            ->whereBetween('day', [$from->toDateString(), $to->toDateString()])
+            ->selectRaw('coalesce(sum(delta), 0) as credits, count(distinct account_id) as users')
+            ->when($cap !== null, fn ($q) => $q->selectRaw('count(*) filter (where delta >= ?) as capped', [(int) $cap]))
+            ->when($cap === null, fn ($q) => $q->selectRaw('0 as capped'))
+            ->first();
+        $seconds = DB::table('reading_dailies')->whereBetween('day', [$from->toDateString(), $to->toDateString()])
+            ->selectRaw('coalesce(sum(seconds), 0) as kept, coalesce(sum(seconds_reported), 0) as reported')->first();
+
+        return [
+            'credits' => (int) $earn->credits,
+            'users' => (int) $earn->users,
+            'capped_user_days' => (int) $earn->capped,
+            'clamped_ratio' => (int) $seconds->reported > 0
+                ? round(1 - (int) $seconds->kept / (int) $seconds->reported, 4)
+                : 0.0,
+        ];
+    }
+
+    private function recents(CarbonImmutable $from, CarbonImmutable $to, string $client): Builder
+    {
+        $query = $this->between(DB::table('recents'), 'updated_at', $from, $to);
+        if ($client !== 'all') {
+            $query->whereRaw($this->clientExpr().' = ?', [$client]);
+        }
+
+        return $query;
+    }
+
+    private function clientExpr(): string
+    {
+        return "(case when param->>'client' = 'mobile' or param->>'mode' = 'reading' then 'mobile' else 'web' end)";
+    }
+
+    /**
+     * 闭区间的 UTC 日 → 半开的时间区间 [from 00:00, to+1 00:00)。
+     */
+    private function between(Builder $query, string $column, CarbonImmutable $from, CarbonImmutable $to): Builder
+    {
+        return $query->where($column, '>=', $from->startOfDay())->where($column, '<', $to->addDay()->startOfDay());
+    }
+}

+ 58 - 0
api-v13/app/Services/V3/ReadingTimeService.php

@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Models\ReadingDaily;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Validation\ValidationException;
+
+/**
+ * 登录用户读经时长的上报与核减。读经时长按策略换积分(见 {@see CreditService::settle()})。
+ *
+ * 时长是客户端自报的,服务端只做两道核减:
+ * - 当天的上报,计入的秒数不超过「距上次上报过去的时间 + 30 秒余量」——
+ *   多台设备同时报、或者一次报个大数,都只按墙钟时间算;
+ * - 单日累计不超过 24 小时。
+ * 断网补报允许最多 2 天前,补报的那几天不做墙钟核减(换积分时每天另有上限)。
+ */
+class ReadingTimeService
+{
+    private const SLACK_SECONDS = 30;
+
+    private const BACKFILL_DAYS = 2;
+
+    /**
+     * @throws ValidationException day 早于补报期限或在未来
+     */
+    public function report(string $userUid, int $seconds, ?string $day): ReadingDaily
+    {
+        $today = now('UTC')->startOfDay();
+        $target = $day ? now('UTC')->parse($day)->startOfDay() : $today;
+        if ($target->gt($today) || $target->lt($today->copy()->subDays(self::BACKFILL_DAYS))) {
+            throw ValidationException::withMessages(['day' => __('messages.reading_time_day_out_of_range')]);
+        }
+        $isToday = $target->equalTo($today);
+
+        return DB::transaction(function () use ($userUid, $seconds, $target, $isToday) {
+            ReadingDaily::createOrFirst(['user_uid' => $userUid, 'day' => $target->toDateString()]);
+            $row = ReadingDaily::where('user_uid', $userUid)->where('day', $target->toDateString())
+                ->lockForUpdate()->firstOrFail();
+
+            $allowed = $seconds;
+            if ($isToday && $row->last_report_at) {
+                $elapsed = (int) $row->last_report_at->diffInSeconds(now(), true);
+                $allowed = min($allowed, $elapsed + self::SLACK_SECONDS);
+            }
+            $allowed = max(0, min($allowed, 86400 - (int) $row->seconds));
+
+            $row->seconds_reported = (int) $row->seconds_reported + $seconds;
+            $row->seconds = (int) $row->seconds + $allowed;
+            if ($isToday) {
+                $row->last_report_at = now();
+            }
+            $row->save();
+
+            return $row;
+        });
+    }
+}

+ 34 - 0
api-v13/app/Services/V3/StatsRange.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Services\V3;
+
+use Carbon\CarbonImmutable;
+use Illuminate\Validation\ValidationException;
+
+/**
+ * 管理后台统计的时间范围:UTC 日的闭区间 [from, to]。缺省近 30 天(到今天),最长 366 天。
+ */
+class StatsRange
+{
+    public const DEFAULT_DAYS = 30;
+
+    public const MAX_DAYS = 366;
+
+    /**
+     * @param  array{from?: string, to?: string}  $input
+     * @return array{0: CarbonImmutable, 1: CarbonImmutable}
+     *
+     * @throws ValidationException 区间超过 366 天
+     */
+    public static function resolve(array $input): array
+    {
+        $to = isset($input['to']) ? CarbonImmutable::parse($input['to'], 'UTC')->startOfDay() : CarbonImmutable::now('UTC')->startOfDay();
+        $from = isset($input['from']) ? CarbonImmutable::parse($input['from'], 'UTC')->startOfDay() : $to->subDays(self::DEFAULT_DAYS - 1);
+
+        if ($from->gt($to) || $from->diffInDays($to) + 1 > self::MAX_DAYS) {
+            throw ValidationException::withMessages(['from' => __('messages.stats_range_too_long', ['days' => self::MAX_DAYS])]);
+        }
+
+        return [$from, $to];
+    }
+}

+ 6 - 0
api-v13/bootstrap/app.php

@@ -6,6 +6,8 @@ use App\Http\Middleware\OpsToken;
 use App\Http\Middleware\SetLocale;
 use App\Http\Middleware\SetLocale;
 use App\Http\Middleware\UserOperation;
 use App\Http\Middleware\UserOperation;
 use App\Http\Middleware\V3\Authenticate as V3Authenticate;
 use App\Http\Middleware\V3\Authenticate as V3Authenticate;
+use App\Http\Middleware\V3\AuthenticateAdmin;
+use App\Http\Middleware\V3\AuthenticateAgentService;
 use Illuminate\Auth\AuthenticationException;
 use Illuminate\Auth\AuthenticationException;
 use Illuminate\Foundation\Application;
 use Illuminate\Foundation\Application;
 use Illuminate\Foundation\Configuration\Exceptions;
 use Illuminate\Foundation\Configuration\Exceptions;
@@ -43,6 +45,10 @@ return Application::configure(basePath: dirname(__DIR__))
             // v3 的登录闸。只认 bearer,未登录在进控制器前就 401——
             // v3 的登录闸。只认 bearer,未登录在进控制器前就 401——
             // 所以「未登录 + 参数非法」得到的是 401 而不是 422
             // 所以「未登录 + 参数非法」得到的是 401 而不是 422
             'auth.v3' => V3Authenticate::class,
             'auth.v3' => V3Authenticate::class,
+            // 服务间鉴权:只放行 AI 对话服务(X-Agent-Service-Key)
+            'auth.agent-service' => AuthenticateAgentService::class,
+            // 管理员闸:排在 auth.v3 之后,非 root / administrator 一律 403
+            'auth.v3.admin' => AuthenticateAdmin::class,
         ]);
         ]);
     })
     })
     ->withExceptions(function (Exceptions $exceptions): void {
     ->withExceptions(function (Exceptions $exceptions): void {

+ 37 - 0
api-v13/config/mint.php

@@ -11,6 +11,14 @@ return [
         |--------------------------------------------------------------------------
         |--------------------------------------------------------------------------
         */
         */
         'ops_token' => env('APP_OPS_TOKEN', ''),
         'ops_token' => env('APP_OPS_TOKEN', ''),
+        /*
+        |--------------------------------------------------------------------------
+        | AI 对话服务(agent-poc backend)的服务密钥,通过 X-Agent-Service-Key 传递。
+        | 提问前扣费(POST /api/v3/agent-charges)与研究过程入库(POST /api/v3/agent-traces)只认它;
+        | 为空则这两个接口一律拒绝。
+        |--------------------------------------------------------------------------
+        */
+        'agent_service_key' => env('AGENT_SERVICE_KEY', ''),
 
 
     ],
     ],
     'languages' => [
     'languages' => [
@@ -24,6 +32,35 @@ return [
         'lo' => 'ພາສາລາວ',
         'lo' => 'ພາສາລາວ',
     ],
     ],
     'default_language' => 'en',
     'default_language' => 'en',
+
+    /*
+    |--------------------------------------------------------------------------
+    | AI 对话积分策略(公开:GET /v3/credit-policy)
+    |--------------------------------------------------------------------------
+    |
+    | 只放当前生效的一版,历史看 git。改规则就改这里,并把 version 改成生效日
+    | (UTC,YYYYMMDD)——它会记进每笔积分流水(credit_ledger.policy_version)。
+    | 「一天」一律按 UTC 算,每天 0 点(UTC)重置赠送额度。字段说明见 agent-poc 仓库 docs/credits.md。
+    |
+    */
+    'credits' => [
+        // 积分功能上线日(UTC):从这天起的读经 / 编辑时长才换积分;结算任务补发漏掉的日子时也从这天查起
+        'earn_since' => '2026-10-23',
+        'policy' => [
+            'version' => 20261023,
+            // 每天赠送的额度(不累积到第二天)
+            'daily_free' => ['guest' => 100, 'user' => 500],
+            // 每次提问的价格:普通 / 深度思考
+            'cost' => ['normal' => 10, 'deep' => 30],
+            // 同一 IP 下所有游客每天合计最多消耗多少(防刷),null 为不限
+            'guest_ip_daily_cap' => 500,
+            // 登录用户读经、编辑时长换积分;daily_cap 为 null 不设上限。积分不过期
+            'earn' => [
+                'reading' => ['credits_per_minute' => 1, 'daily_cap' => 100],
+                'editing' => ['credits_per_minute' => 5, 'daily_cap' => null],
+            ],
+        ],
+    ],
     'library' => [
     'library' => [
         'list_min_progress' => env('LIBRARY_LIST_MIN_PROGRESS', 0.5),
         'list_min_progress' => env('LIBRARY_LIST_MIN_PROGRESS', 0.5),
     ],
     ],

+ 39 - 0
api-v13/database/factories/AgentRunFactory.php

@@ -0,0 +1,39 @@
+<?php
+
+namespace Database\Factories;
+
+use App\Models\AgentRun;
+use App\Models\AgentThread;
+use Illuminate\Database\Eloquent\Factories\Factory;
+use Illuminate\Support\Str;
+
+/**
+ * @extends Factory<AgentRun>
+ */
+class AgentRunFactory extends Factory
+{
+    protected $model = AgentRun::class;
+
+    /**
+     * 归属字段(user_uid / device_id)跟随所属会话。
+     *
+     * @return array<string, mixed>
+     */
+    public function definition(): array
+    {
+        return [
+            'run_id' => (string) Str::uuid(),
+            'agent_thread_id' => AgentThread::factory(),
+            // 账号与所属会话一致
+            'account_type' => fn (array $attrs) => AgentThread::find($attrs['agent_thread_id'])?->account_type,
+            'account_id' => fn (array $attrs) => AgentThread::find($attrs['agent_thread_id'])?->account_id,
+            'question' => fake()->sentence().'?',
+            'answer' => fake()->paragraph(),
+            'deep' => false,
+            'improve' => true,
+            'status' => 'ok',
+            'user_message_id' => (string) Str::uuid(),
+            'assistant_message_id' => (string) Str::uuid(),
+        ];
+    }
+}

+ 54 - 0
api-v13/database/factories/AgentThreadFactory.php

@@ -0,0 +1,54 @@
+<?php
+
+namespace Database\Factories;
+
+use App\Models\AgentThread;
+use App\Services\V3\AgentAccount;
+use Illuminate\Database\Eloquent\Factories\Factory;
+use Illuminate\Support\Str;
+
+/**
+ * @extends Factory<AgentThread>
+ */
+class AgentThreadFactory extends Factory
+{
+    protected $model = AgentThread::class;
+
+    /**
+     * 默认是游客会话;登录用户的会话用 {@see self::forUser()}。
+     *
+     * @return array<string, mixed>
+     */
+    public function definition(): array
+    {
+        return [
+            'thread_id' => (string) Str::uuid(),
+            'account_type' => 'guest',
+            'account_id' => (string) Str::uuid(),
+            'title' => fake()->sentence(4),
+            'client' => 'mobile',
+            'last_run_at' => now(),
+        ];
+    }
+
+    public function archived(): static
+    {
+        return $this->state(fn () => ['archived_at' => now()]);
+    }
+
+    /**
+     * 登录用户的会话。
+     */
+    public function forUser(string $userUid): static
+    {
+        return $this->state(AgentAccount::user($userUid)->columns());
+    }
+
+    /**
+     * 某台设备上游客的会话。
+     */
+    public function forGuest(string $deviceId): static
+    {
+        return $this->state(AgentAccount::guest($deviceId)->columns());
+    }
+}

+ 40 - 0
api-v13/database/migrations/2026_10_23_043455_create_agent_threads_table.php

@@ -0,0 +1,40 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * AI 对话的会话(一个 AG-UI thread)。研究过程入库与会话历史共用,设计见
+ * agent-poc 仓库 docs/trace.md。
+ *
+ * 归属用 account_type(user / guest)+ account_id(用户 uuid / 设备匿名 uuid)两列表达,查询时两列一起用。
+ * thread_id 由客户端生成、
+ * 全局唯一:已属于别的账号的 id 再来一律 403。游客登录 / 退出后客户端换新的 threadId,
+ * 游客会话不并入账号。
+ */
+return new class extends Migration
+{
+    public function up(): void
+    {
+        Schema::create('agent_threads', function (Blueprint $table) {
+            $table->id();
+            $table->uuid('thread_id')->unique()->comment('AG-UI threadId,客户端生成;全局唯一,被别的账号占用时拒绝(403)');
+            $table->string('account_type', 8)->comment('账号类型:user(登录用户)/ guest(游客)');
+            $table->uuid('account_id')->comment('账号 id:登录用户 uuid 或游客设备匿名 uuid;必须与 account_type 一起用(设备 id 由客户端填,可能与某个用户 uid 相同)');
+            $table->string('title')->comment('会话标题,默认取第一句提问');
+            $table->string('client', 16)->nullable()->comment('mobile / web');
+            $table->timestamp('archived_at')->nullable()->comment('用户存档时间');
+            $table->timestamp('last_run_at')->index()->comment('最近一次提问时间,游客按它过期');
+            $table->timestamps();
+            $table->softDeletes()->comment('用户删除=对用户隐藏(提问、步骤随之软删),数据永久保留');
+
+            $table->index(['account_id', 'account_type', 'last_run_at']);
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::dropIfExists('agent_threads');
+    }
+};

+ 72 - 0
api-v13/database/migrations/2026_10_23_043456_create_agent_runs_table.php

@@ -0,0 +1,72 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * AI 对话的一次提问(一个 AG-UI run):问题、路由、计划、给作答 LLM 的证据、回答。
+ *
+ * 会话历史也从这里读:question / answer / citations 就是用户看得见的那一轮问答,
+ * user_message_id / assistant_message_id 是 AG-UI 消息 id,续聊时客户端用它们
+ * 把旧消息原样回灌给 agent。
+ */
+return new class extends Migration
+{
+    public function up(): void
+    {
+        Schema::create('agent_runs', function (Blueprint $table) {
+            $table->id();
+            $table->uuid('run_id')->unique()->comment('AG-UI runId');
+            $table->foreignId('agent_thread_id')->comment('所属会话 agent_threads.id')->constrained('agent_threads');
+            $table->string('account_type', 8)->comment('提问者账号类型(与所属会话相同,冗余存一份供统计筛选):user(登录用户)/ guest(游客)');
+            $table->uuid('account_id')->comment('账号 id:登录用户 uuid 或游客设备匿名 uuid;必须与 account_type 一起用(设备 id 由客户端填,可能与某个用户 uid 相同)');
+            $table->ipAddress('client_ip')->nullable()->comment('客户端 IP,只记游客');
+            $table->string('client', 16)->nullable()->comment('mobile / web');
+            $table->string('app_version', 32)->nullable()->comment('客户端版本号');
+            $table->string('locale', 16)->nullable()->comment('客户端界面语言');
+
+            $table->text('question')->comment('用户提问原文');
+            $table->jsonb('passage')->nullable()->comment('阅读页提问带的段落上下文');
+            $table->boolean('deep')->default(false)->comment('深度思考');
+            $table->boolean('improve')->default(true)->comment('用户是否允许用于改进回答(提问那一刻的开关)');
+
+            $table->string('route', 32)->nullable()->comment('实际走的路由');
+            $table->string('route_raw', 32)->nullable()->comment('路由器原始判断');
+            $table->float('confidence')->nullable()->comment('路由器判断的置信度');
+            $table->jsonb('plan')->nullable()->comment('lemmas / hypothesis 等');
+            $table->text('evidence')->nullable()->comment('给作答 LLM 的证据全文');
+            $table->text('answer')->nullable()->comment('回答全文');
+            $table->jsonb('citations')->nullable()->comment('回答引用的出处列表');
+
+            $table->string('model', 64)->nullable()->comment('作答 LLM 的模型名');
+            $table->string('prompt_version', 64)->nullable()->comment('提示词版本哈希');
+            $table->unsignedSmallInteger('llm_calls')->default(0)->comment('LLM 调用次数');
+            $table->unsignedSmallInteger('tool_calls')->default(0)->comment('工具调用次数');
+            $table->unsignedSmallInteger('retries')->default(0)->comment('重试次数');
+            $table->unsignedInteger('tokens_in')->nullable()->comment('输入 token 总数');
+            $table->unsignedInteger('tokens_out')->nullable()->comment('输出 token 总数');
+            $table->unsignedInteger('latency_ms')->nullable()->comment('总耗时(毫秒)');
+            $table->string('status', 16)->comment('ok / error / cancelled / denied');
+            $table->text('error')->nullable()->comment('出错时的错误信息');
+
+            $table->string('user_message_id', 64)->nullable()->comment('AG-UI 用户消息 id');
+            $table->string('assistant_message_id', 64)->nullable()->index()->comment('AG-UI 回答消息 id');
+            $table->uuid('replaces_run_id')->nullable()->comment('重新生成时被替换的那一轮');
+
+            $table->timestamp('started_at')->nullable()->index()->comment('开始处理这次提问的时间');
+            $table->timestamps();
+            $table->softDeletes()->comment('随会话一起软删(用户删除会话);软删后任何接口都读不到,数据永久保留');
+
+            $table->index(['agent_thread_id', 'created_at']);
+            $table->index(['account_id', 'account_type']);
+            $table->index(['account_type', 'started_at']);
+            $table->index(['client_ip', 'created_at']);
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::dropIfExists('agent_runs');
+    }
+};

+ 39 - 0
api-v13/database/migrations/2026_10_23_043457_create_agent_run_steps_table.php

@@ -0,0 +1,39 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * 一次提问里的每一步:LLM 调用、工具调用,以及路由 / 计划 / 补查 / judge 等节点事件。
+ * 结果由 agent 端截断到 8k 再送来,原长记在 result_chars。
+ */
+return new class extends Migration
+{
+    public function up(): void
+    {
+        Schema::create('agent_run_steps', function (Blueprint $table) {
+            $table->id();
+            $table->foreignId('agent_run_id')->comment('所属提问 agent_runs.id')->constrained('agent_runs');
+            $table->unsignedSmallInteger('seq')->comment('本次提问内的步骤序号');
+            $table->string('kind', 16)->comment('llm / tool / route / plan / retry / judge / passage / answer …');
+            $table->string('name', 128)->nullable()->comment('模型名或工具名');
+            $table->jsonb('args')->nullable()->comment('调用参数');
+            $table->text('result')->nullable()->comment('调用结果,agent 端截断到 8k');
+            $table->unsignedInteger('result_chars')->nullable()->comment('截断前结果的字符数');
+            $table->unsignedInteger('tokens_in')->nullable()->comment('本步输入 token 数');
+            $table->unsignedInteger('tokens_out')->nullable()->comment('本步输出 token 数');
+            $table->unsignedInteger('ms')->nullable()->comment('本步耗时(毫秒)');
+            $table->text('error')->nullable()->comment('本步的错误信息');
+            $table->timestamp('started_at')->nullable()->comment('本步开始时间');
+            $table->softDeletes()->comment('随所属提问一起软删;数据永久保留');
+
+            $table->unique(['agent_run_id', 'seq']);
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::dropIfExists('agent_run_steps');
+    }
+};

+ 46 - 0
api-v13/database/migrations/2026_10_23_044429_create_credit_ledger_table.php

@@ -0,0 +1,46 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * 积分流水:唯一的账本。余额由流水汇总,不另存。
+ *
+ * - bucket=free:每日赠送池的消耗与退回(赠送本身不入账,用 day 汇总当天用了多少);
+ * - bucket=earned:赚来的积分(earn)、提问消耗(spend)、退回(refund)、手工调整(adjust)。
+ *
+ * day 是这条流水归属的 UTC 日:消耗记当天,退回沿用原消耗的那天,赚取记活动发生的那天。
+ * 唯一键 (account_id, account_type, source, ref, kind, bucket) 让扣费、退款、结算都能安全重放。
+ */
+return new class extends Migration
+{
+    public function up(): void
+    {
+        Schema::create('credit_ledger', function (Blueprint $table) {
+            $table->id();
+            $table->string('account_type', 8)->comment('账号类型:user(登录用户)/ guest(游客)');
+            $table->uuid('account_id')->comment('账号 id:登录用户 uuid 或游客设备匿名 uuid;必须与 account_type 一起用(设备 id 由客户端填,可能与某个用户 uid 相同)');
+            $table->integer('delta')->comment('正数入账,负数扣减');
+            $table->string('kind', 16)->comment('earn / spend / refund / adjust');
+            $table->string('bucket', 16)->comment('free / earned');
+            $table->string('source', 32)->comment('reading / editing / agent_run / admin');
+            $table->string('ref', 128)->comment('run_id、日期或调整单号');
+            $table->date('day')->comment('归属的 UTC 日');
+            $table->unsignedInteger('policy_version')->comment('记账时生效的积分策略版本(config mint.credits.policy.version,生效日 YYYYMMDD)');
+            $table->ipAddress('client_ip')->nullable()->comment('游客消耗时的客户端 IP,用于同 IP 每日上限');
+            $table->string('note')->nullable()->comment('备注');
+            $table->timestamps();
+
+            $table->unique(['account_id', 'account_type', 'source', 'ref', 'kind', 'bucket']);
+            $table->index(['account_id', 'account_type', 'bucket', 'day']);
+            $table->index(['client_ip', 'day']);
+            $table->index(['source', 'day']);
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::dropIfExists('credit_ledger');
+    }
+};

+ 34 - 0
api-v13/database/migrations/2026_10_23_044430_create_reading_dailies_table.php

@@ -0,0 +1,34 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * 登录用户每天的读经时长(客户端上报、服务端核减后累加),用来换积分。
+ *
+ * 与 user_operation_dailies(编辑时长,由 v2 中间件按请求累计)是两回事:
+ * 读经发生在 App 阅读器里,走 v3,不经过那个中间件。
+ */
+return new class extends Migration
+{
+    public function up(): void
+    {
+        Schema::create('reading_dailies', function (Blueprint $table) {
+            $table->id();
+            $table->uuid('user_uid')->comment('用户 uuid');
+            $table->date('day')->comment('UTC 日');
+            $table->unsignedInteger('seconds_reported')->default(0)->comment('客户端报上来的总秒数');
+            $table->unsignedInteger('seconds')->default(0)->comment('核减后计入的秒数');
+            $table->timestamp('last_report_at')->nullable()->comment('最近一次上报时间');
+            $table->timestamps();
+
+            $table->unique(['user_uid', 'day']);
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::dropIfExists('reading_dailies');
+    }
+};

+ 31 - 0
api-v13/database/migrations/2026_10_24_035732_add_admin_stats_indexes.php

@@ -0,0 +1,31 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * 管理后台统计(/v3/admin/reading-stats、/v3/admin/agent-stats)按时间范围查询用的索引。
+ */
+return new class extends Migration
+{
+    public function up(): void
+    {
+        Schema::table('user_operation_logs', function (Blueprint $table) {
+            $table->index(['op_type', 'created_at']);
+        });
+        Schema::table('views', function (Blueprint $table) {
+            $table->index('updated_at');
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::table('user_operation_logs', function (Blueprint $table) {
+            $table->dropIndex(['op_type', 'created_at']);
+        });
+        Schema::table('views', function (Blueprint $table) {
+            $table->dropIndex(['updated_at']);
+        });
+    }
+};

+ 43 - 0
api-v13/database/migrations/2026_10_24_050456_create_agent_feedback_table.php

@@ -0,0 +1,43 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * 用户对 AI 回答的评价(点赞 / 点踩)。一人对一条回答只留一条,再点就是更新,可撤回(删除)。
+ *
+ * 键是 AG-UI 的回答消息 id(客户端手里只有它;研究过程是回答结束后异步入库的,
+ * 用户点得快时那次提问可能还没进库)。读的时候按 agent_runs.assistant_message_id 对回提问。
+ *
+ * tags:点赞是可选标签(accurate / useful_citations / clear / inspiring),
+ * 点踩是原因(citation_wrong / missed / off_topic / incorrect / too_long / too_academic / slow / other)。
+ * comment 只在选了 other 时填。asked=这条是主动询问(不是用户自己点)问出来的。
+ */
+return new class extends Migration
+{
+    public function up(): void
+    {
+        Schema::create('agent_feedback', function (Blueprint $table) {
+            $table->id();
+            $table->string('account_type', 8)->comment('账号类型:user(登录用户)/ guest(游客)');
+            $table->uuid('account_id')->comment('账号 id:登录用户 uuid 或游客设备匿名 uuid;必须与 account_type 一起用(设备 id 由客户端填,可能与某个用户 uid 相同)');
+            $table->string('message_id', 64)->index()->comment('AG-UI 回答消息 id');
+            $table->uuid('thread_id')->nullable()->comment('AG-UI threadId');
+            $table->smallInteger('rating')->comment('1 赞 / -1 踩');
+            $table->jsonb('tags')->nullable()->comment('点赞的标签或点踩的原因,取值见类注释');
+            $table->text('comment')->nullable()->comment('补充说明,只在选了 other 时填');
+            $table->boolean('asked')->default(false)->comment('主动询问问出来的');
+            $table->string('client', 16)->nullable()->comment('mobile / web');
+            $table->timestamps();
+
+            $table->unique(['account_id', 'account_type', 'message_id']);
+            $table->index(['rating', 'created_at']);
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::dropIfExists('agent_feedback');
+    }
+};

+ 37 - 0
api-v13/database/migrations/2026_10_24_050457_create_agent_events_table.php

@@ -0,0 +1,37 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * AI 回答上的隐式信号:用户不用评价,客户端自动上报。
+ *
+ * kind:copy(复制回答)/ citation_open(点开引用)/ regenerate(重新生成)/ ask_shown(主动询问显示过)。
+ * 中途停止已记在 agent_runs.status=cancelled;「换个说法再问」由分析时按同一会话的提问间隔推出来,不单独上报。
+ * 操作记录性质,按 message_id 挂到回答上,随游客保留期一起清理。
+ */
+return new class extends Migration
+{
+    public function up(): void
+    {
+        Schema::create('agent_events', function (Blueprint $table) {
+            $table->id();
+            $table->string('account_type', 8)->comment('账号类型:user(登录用户)/ guest(游客)');
+            $table->uuid('account_id')->comment('账号 id:登录用户 uuid 或游客设备匿名 uuid;必须与 account_type 一起用(设备 id 由客户端填,可能与某个用户 uid 相同)');
+            $table->string('message_id', 64)->comment('AG-UI 回答消息 id');
+            $table->string('kind', 32)->comment('copy / citation_open / regenerate / ask_shown');
+            $table->string('client', 16)->nullable()->comment('mobile / web');
+            $table->timestamp('created_at')->useCurrent()->comment('上报时间');
+
+            $table->index(['account_id', 'account_type']);
+            $table->index(['message_id', 'kind']);
+            $table->index(['kind', 'created_at']);
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::dropIfExists('agent_events');
+    }
+};

+ 4 - 0
api-v13/documents/tasks.md

@@ -59,6 +59,10 @@ php artisan upgrade:community.term zh-Hans
 # 导出离线数据
 # 导出离线数据
 php artisan export:offline lzma
 php artisan export:offline lzma
 
 
+# AI 对话积分:把读经、编辑时长结算成积分。补齐上线以来所有漏结算的日子,
+# 漏跑几天都没关系,下次跑会补上;可重复执行,不会重复入账
+php artisan credits:settle-activity
+
 ```
 ```
 
 
 ## weekly
 ## weekly

+ 10 - 0
api-v13/resources/lang/en/messages.php

@@ -43,4 +43,14 @@ return [
     'agent_grant_invalid' => 'The agent grant is invalid, expired or revoked.',
     'agent_grant_invalid' => 'The agent grant is invalid, expired or revoked.',
     'agent_grant_scope' => 'The agent grant does not cover this content.',
     'agent_grant_scope' => 'The agent grant does not cover this content.',
 
 
+    'agent_device_required' => 'Guests must send a device_id.',
+    'agent_client_ip_required' => 'Guests must come with a client IP.',
+    'agent_thread_forbidden' => 'This conversation belongs to another account. Start a new conversation.',
+    'agent_quota_insufficient_user' => 'Not enough credits for this question today. Reading the texts earns more credits.',
+    'agent_quota_insufficient_guest' => 'You have used today\'s free questions. Sign in to get more each day.',
+    'agent_quota_ip_cap' => 'Too many questions from this network today. Please sign in to continue.',
+    'reading_time_day_out_of_range' => 'Reading time can only be reported for today or the past 2 days.',
+    'stats_range_too_long' => 'The date range can be at most :days days.',
+    'agent_feedback_tags' => 'These tags do not match the rating.',
+
 ];
 ];

+ 10 - 0
api-v13/resources/lang/zh-Hans/messages.php

@@ -43,4 +43,14 @@ return [
     'agent_grant_invalid' => '写入授权无效、已过期或已撤销。',
     'agent_grant_invalid' => '写入授权无效、已过期或已撤销。',
     'agent_grant_scope' => '写入授权不覆盖这条内容。',
     'agent_grant_scope' => '写入授权不覆盖这条内容。',
 
 
+    'agent_device_required' => '未登录时必须带 device_id。',
+    'agent_client_ip_required' => '未登录时必须带客户端 IP。',
+    'agent_thread_forbidden' => '这个会话属于别的账号,请新开一个会话。',
+    'agent_quota_insufficient_user' => '今天的积分不够这次提问了。读经可以赚取积分。',
+    'agent_quota_insufficient_guest' => '今天的免费提问次数用完了。登录后每天有更多次数。',
+    'agent_quota_ip_cap' => '今天同一网络下的提问太多了,请登录后继续。',
+    'reading_time_day_out_of_range' => '读经时长只能上报今天或 2 天内的。',
+    'stats_range_too_long' => '时间范围最多 :days 天。',
+    'agent_feedback_tags' => '标签和评价不配套。',
+
 ];
 ];

+ 2 - 0
api-v13/routes/api.php

@@ -356,4 +356,6 @@ Route::prefix('v3')->as('v3.')->middleware(NegotiateLocale::class)->group(functi
     require __DIR__.'/v3/channel.php';
     require __DIR__.'/v3/channel.php';
     require __DIR__.'/v3/interaction.php';
     require __DIR__.'/v3/interaction.php';
     require __DIR__.'/v3/auth.php';
     require __DIR__.'/v3/auth.php';
+    require __DIR__.'/v3/agent.php';
+    require __DIR__.'/v3/admin.php';
 });
 });

+ 29 - 0
api-v13/routes/v3/admin.php

@@ -0,0 +1,29 @@
+<?php
+
+/*
+|--------------------------------------------------------------------------
+| v3 · admin —— 管理后台(仅 root / administrator)
+|--------------------------------------------------------------------------
+|
+| 由 routes/api.php 的 v3 组 require 进来,前缀已在那边加好。
+| 整组先过 auth.v3(没登录 401)再过 auth.v3.admin(不是管理员 403)。
+|
+*/
+
+use App\Http\Controllers\V3\AdminAgentFeedbackController;
+use App\Http\Controllers\V3\AdminAgentRunController;
+use App\Http\Controllers\V3\AdminAgentStatsController;
+use App\Http\Controllers\V3\AdminReadingStatsController;
+use Illuminate\Support\Facades\Route;
+
+Route::prefix('admin')->as('admin.')->middleware(['auth.v3', 'auth.v3.admin'])->group(function () {
+    Route::get('reading-stats', AdminReadingStatsController::class)->name('reading-stats');
+    Route::get('agent-stats', AdminAgentStatsController::class)->name('agent-stats');
+
+    Route::get('agent-feedback', [AdminAgentFeedbackController::class, 'index'])->name('agent-feedback.index');
+
+    // digest 是字面量段,写在 {run} 之前
+    Route::get('agent-runs/digest', [AdminAgentRunController::class, 'digest'])->name('agent-runs.digest');
+    Route::get('agent-runs', [AdminAgentRunController::class, 'index'])->name('agent-runs.index');
+    Route::get('agent-runs/{run}', [AdminAgentRunController::class, 'show'])->name('agent-runs.show')->whereUuid('run');
+});

+ 63 - 0
api-v13/routes/v3/agent.php

@@ -0,0 +1,63 @@
+<?php
+
+/*
+|--------------------------------------------------------------------------
+| v3 · agent —— AI 对话(研究过程入库、会话历史)
+|--------------------------------------------------------------------------
+|
+| 由 routes/api.php 的 v3 组 require 进来,前缀已在那边加好。
+|
+| 额度 / 积分(agent-charges、agent-quota、credit-policy、reading-time)也在这里。
+|
+*/
+
+use App\Http\Controllers\V3\AgentChargeController;
+use App\Http\Controllers\V3\AgentEventController;
+use App\Http\Controllers\V3\AgentFeedbackController;
+use App\Http\Controllers\V3\AgentQuotaController;
+use App\Http\Controllers\V3\AgentTraceController;
+use App\Http\Controllers\V3\CreditPolicyController;
+use App\Http\Controllers\V3\MeAgentThreadArchiveController;
+use App\Http\Controllers\V3\MeAgentThreadController;
+use App\Http\Controllers\V3\MeReadingTimeController;
+use Illuminate\Support\Facades\Route;
+
+// 研究过程入库:服务间接口,只认 agent 服务密钥;终端用户由透传的 bearer 决定
+Route::post('agent-traces', [AgentTraceController::class, 'store'])
+    ->middleware('auth.agent-service');
+
+// 提问扣费:服务间接口,同上
+Route::post('agent-charges', [AgentChargeController::class, 'store'])
+    ->middleware('auth.agent-service');
+
+// 额度(单例):可选登录,游客带 device_id
+Route::get('agent-quota', AgentQuotaController::class);
+
+// 积分策略(单例):公开
+Route::get('credit-policy', CreditPolicyController::class);
+
+// 回答评价与隐式信号:可选登录(游客带 device_id),限流防刷
+Route::post('agent-feedback', [AgentFeedbackController::class, 'store'])->middleware('throttle:60,1');
+Route::delete('agent-feedback/{message}', [AgentFeedbackController::class, 'destroy'])
+    ->middleware('throttle:60,1')
+    ->where('message', '[A-Za-z0-9_\-]{1,64}');
+Route::post('agent-events', [AgentEventController::class, 'store'])->middleware('throttle:120,1');
+
+// 我的会话历史 / 读经时长:全线登录
+Route::prefix('me')->as('me.')->middleware('auth.v3')->group(function () {
+    // 单例子资源 archive 是字面量段,写在 apiResource 之前
+    Route::put('agent-threads/{thread}/archive', [MeAgentThreadArchiveController::class, 'update'])
+        ->whereUuid('thread');
+    Route::delete('agent-threads/{thread}/archive', [MeAgentThreadArchiveController::class, 'destroy'])
+        ->whereUuid('thread');
+
+    // 只注册 PATCH,不注册 PUT:v3 的更新只做局部更新(v3-resource skill 硬规范第 10 条)
+    Route::apiResource('agent-threads', MeAgentThreadController::class)
+        ->only(['index', 'show', 'destroy'])
+        ->parameters(['agent-threads' => 'thread'])
+        ->whereUuid('thread');
+    Route::patch('agent-threads/{thread}', [MeAgentThreadController::class, 'update'])
+        ->whereUuid('thread');
+
+    Route::post('reading-time', [MeReadingTimeController::class, 'store']);
+});