bailinghub 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/README.en.md +8 -7
  2. package/README.md +7 -7
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_AUTH_API.en.md +112 -1
  5. package/docs/AGENT_AUTH_API.md +99 -1
  6. package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
  7. package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
  8. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
  9. package/docs/AGENT_CLIENT_RUNTIME_API.md +38 -1
  10. package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
  11. package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
  12. package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
  13. package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
  14. package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
  15. package/docs/AGENT_SYSTEM_INFO.md +97 -0
  16. package/docs/AGENT_TASK_CONTROL.en.md +25 -0
  17. package/docs/AGENT_TASK_CONTROL.md +94 -0
  18. package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
  19. package/docs/CHANGELOG.en.md +24 -1
  20. package/docs/CHANGELOG.md +24 -1
  21. package/docs/COMPATIBILITY.en.md +2 -0
  22. package/docs/CONTRACT.en.md +2 -0
  23. package/docs/CONTRACT.md +2 -0
  24. package/docs/GENERATED_ARTIFACTS.en.md +46 -0
  25. package/docs/GENERATED_ARTIFACTS.md +108 -0
  26. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  27. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  28. package/docs/INVOCATION_RECEIPTS.md +111 -0
  29. package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
  30. package/docs/LOCAL_AGENT_SETUP.md +116 -0
  31. package/docs/README.en.md +9 -0
  32. package/docs/README.md +9 -0
  33. package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
  34. package/docs/RELEASE_NOTES_NEXT.md +3 -0
  35. package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
  36. package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
  37. package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
  38. package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
  39. package/docs/SDK.en.md +31 -0
  40. package/docs/TOOL_RATE_LIMITS.md +50 -0
  41. package/docs/UPGRADE_v0.8.0.en.md +71 -0
  42. package/docs/UPGRADE_v0.8.0.md +73 -0
  43. package/docs/user-guide/conversations.en.md +4 -2
  44. package/docs/user-guide/conversations.md +4 -2
  45. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +2 -0
  46. package/package.json +1 -1
  47. package/schemas/config/route.schema.json +16 -2
  48. package/schemas/config/tool-provider.schema.json +2 -1
  49. package/scripts/check-doc-links.mjs +2 -0
  50. package/scripts/check-image-tags.sh +1 -1
  51. package/scripts/check-release-consistency.test.mjs +2 -2
  52. package/scripts/e2e-console.mjs +32 -2
  53. package/scripts/install.sh +1 -1
  54. package/scripts/publish-images.sh +1 -1
  55. package/scripts/release-audit.mjs +2 -0
  56. package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
  57. package/scripts/sdk-runtime-test.mjs +5 -2
  58. package/scripts/verify-github-repo.mjs +2 -0
  59. package/sdk/php/README.md +29 -0
  60. package/sdk/php/src/AgentAuth.php +100 -4
  61. package/sdk/php/src/HubClient.php +2 -1
  62. package/sdk/php7/README.md +31 -0
  63. package/sdk/php7/src/AgentAuth.php +99 -4
  64. package/sdk/php7/src/HubClient.php +2 -1
  65. package/sql/058_agent_conversation_member_bindings.sql +9 -0
  66. package/sql/059_agent_subject_display.sql +5 -0
  67. package/sql/060_agent_artifacts.sql +11 -0
  68. package/sql/061_tool_rate_limit_policies.sql +3 -0
  69. package/sql/062_agent_task_control.sql +92 -0
  70. package/sql/README.en.md +15 -0
  71. package/sql/README.md +25 -0
  72. package/src/adapters/storage/object-storage.ts +15 -3
  73. package/src/adapters/storage/oss-signature.test.ts +40 -0
  74. package/src/adapters/storage/oss-signature.ts +21 -0
  75. package/src/app/agent-artifacts.test.ts +165 -0
  76. package/src/app/agent-artifacts.ts +85 -0
  77. package/src/app/agent-client-runtime.test.ts +76 -1
  78. package/src/app/agent-client-runtime.ts +13 -0
  79. package/src/app/agent-conversation-audit.ts +20 -0
  80. package/src/app/agent-invocation-snapshot.ts +35 -0
  81. package/src/app/agent-system-info.ts +41 -0
  82. package/src/app/agent-task-control.ts +187 -0
  83. package/src/app/agent-task-runtime.ts +68 -0
  84. package/src/app/agent-tool-invocations.test.ts +329 -1
  85. package/src/app/agent-tool-invocations.ts +239 -14
  86. package/src/app/agent-tool-job.test.ts +11 -1
  87. package/src/app/agent-tool-job.ts +8 -1
  88. package/src/app/builtin-tools.ts +4 -0
  89. package/src/app/oss-edition.ts +1 -0
  90. package/src/app/tool-approvals.ts +4 -0
  91. package/src/app/tool-assembly.ts +5 -0
  92. package/src/core/config/agent-setup.ts +37 -0
  93. package/src/core/config/artifact-config.ts +15 -0
  94. package/src/core/config/client-agent-setup.ts +25 -0
  95. package/src/core/config/config-codec.ts +3 -1
  96. package/src/core/config/config-models.ts +11 -1
  97. package/src/core/config/config-schema.test.ts +11 -0
  98. package/src/core/config/route-config.test.ts +28 -0
  99. package/src/core/config/route-config.ts +44 -4
  100. package/src/core/contracts/agent-subject-display.test.ts +19 -0
  101. package/src/core/contracts/agent-subject-display.ts +36 -0
  102. package/src/core/contracts/tool-rate-limits.test.ts +59 -0
  103. package/src/core/contracts/tool-rate-limits.ts +48 -0
  104. package/src/core/contracts/tools.ts +122 -43
  105. package/src/core/contracts/types.ts +18 -1
  106. package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
  107. package/src/core/runtime/agent-conversation-audit.ts +39 -0
  108. package/src/core/runtime/agent-task-control.test.ts +114 -0
  109. package/src/core/runtime/agent-task-control.ts +227 -0
  110. package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -0
  111. package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
  112. package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
  113. package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
  114. package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
  115. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
  116. package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
  117. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
  118. package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
  119. package/src/infrastructure/config/config-agent-task-control-journal-mysql.test.ts +315 -0
  120. package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
  121. package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
  122. package/src/infrastructure/config/config-client-repository.ts +21 -0
  123. package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
  124. package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -0
  125. package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
  126. package/src/infrastructure/config/config-route-repository.ts +24 -0
  127. package/src/infrastructure/config/config-storage-bucket-repository.ts +2 -2
  128. package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
  129. package/src/infrastructure/config/configstore.ts +16 -4
  130. package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
  131. package/src/routes/admin-access.ts +37 -0
  132. package/src/routes/admin-agent-clients.ts +11 -0
  133. package/src/routes/admin-agent-setup.test.ts +130 -0
  134. package/src/routes/admin-agent-setup.ts +68 -0
  135. package/src/routes/admin-agent-tasks.ts +32 -0
  136. package/src/routes/admin-client-agent-setup.test.ts +93 -0
  137. package/src/routes/admin-dispatch-config.ts +2 -0
  138. package/src/routes/admin-tool-providers.test.ts +22 -0
  139. package/src/routes/admin-tool-providers.ts +9 -1
  140. package/src/routes/admin.ts +3 -0
  141. package/src/routes/agent-api.test.ts +76 -0
  142. package/src/routes/agent-api.ts +49 -1
  143. package/src/routes/agent-artifacts.ts +29 -0
  144. package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
  145. package/src/routes/agent-auth-lifecycle.test.ts +193 -0
  146. package/src/routes/agent-auth.test.ts +1 -1
  147. package/src/routes/agent-auth.ts +206 -16
  148. package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
  149. package/src/routes/agent-conversation-audit.ts +8 -2
  150. package/src/routes/agent-subject-display-http.test.ts +145 -0
  151. package/src/routes/agent-system-info.test.ts +132 -0
  152. package/src/routes/agent-task-control-http-mysql.test.ts +246 -0
  153. package/src/routes/private.ts +1 -0
  154. package/src/routes/run.ts +2 -1
  155. package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
  156. package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
  157. package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
  158. package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
  159. package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
  160. package/web/connect/bailing-connect-php.tgz +0 -0
  161. package/web/connect/bailing-connect-php7.tgz +0 -0
  162. package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-BRCR3O0P.js} +1 -1
  163. package/web/console/assets/AgentClients-Bf7sUUs_.js +1 -0
  164. package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
  165. package/web/console/assets/AgentTasks--bqL_QKg.js +2 -0
  166. package/web/console/assets/AgentTasks-C8ox3TyS.css +1 -0
  167. package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-BIbZvInm.js} +1 -1
  168. package/web/console/assets/{Audit-CIRqOCnL.js → Audit-KyPSmBdZ.js} +1 -1
  169. package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-Sv5DU2G6.js} +1 -1
  170. package/web/console/assets/{Channels-CApxH2TB.js → Channels-B9n4fbxg.js} +1 -1
  171. package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-xsOCUXi_.js} +1 -1
  172. package/web/console/assets/Clients-CI3DBDHf.js +3 -0
  173. package/web/console/assets/Clients-CSHIsaWU.css +1 -0
  174. package/web/console/assets/{Cost-BbhlQFP8.js → Cost-JgNXQPlN.js} +1 -1
  175. package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-B5UUUdt0.js} +1 -1
  176. package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-BMGciWQb.js} +1 -1
  177. package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CRbboOCZ.js} +1 -1
  178. package/web/console/assets/{Kb-DLZSAFWP.js → Kb-CgLNGjRp.js} +1 -1
  179. package/web/console/assets/{Login-DiTjPWmN.js → Login-C52JmXzx.js} +1 -1
  180. package/web/console/assets/{Projects-CXcVCgCD.js → Projects-CDOvHPVS.js} +1 -1
  181. package/web/console/assets/Routes-DkMIjMQA.css +1 -0
  182. package/web/console/assets/Routes-X9vHLpKW.js +124 -0
  183. package/web/console/assets/Runs-CvGTV8I-.css +1 -0
  184. package/web/console/assets/Runs-DYNDXsqk.js +3 -0
  185. package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-B91P6i1x.js} +1 -1
  186. package/web/console/assets/Shell-Bj6C8Hgo.css +1 -0
  187. package/web/console/assets/Shell-BsRa7bQQ.js +1 -0
  188. package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
  189. package/web/console/assets/StorageBuckets-DkuDM0oX.js +1 -0
  190. package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-B7Mqj3k1.js} +1 -1
  191. package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-Db93b6dc.js} +1 -1
  192. package/web/console/assets/{Targets-CZmDcjsE.js → Targets-CuuIYeZO.js} +1 -1
  193. package/web/console/assets/Tools-CHiqz9XZ.js +2 -0
  194. package/web/console/assets/Tools-DU8ei6sd.css +1 -0
  195. package/web/console/assets/index-UGvfF3Xr.js +2 -0
  196. package/web/console/assets/{request-r7GHVJzw.js → request-DeGya810.js} +1 -1
  197. package/web/console/assets/{schema-BVn_hB7M.js → schema-BqlqLw1R.js} +1 -1
  198. package/web/console/index.html +1 -1
  199. package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
  200. package/web-admin/scripts/subject-display-ui.mjs +78 -0
  201. package/web-admin/src/components/AgentSetupPanel.vue +275 -0
  202. package/web-admin/src/components/ClientConversations.vue +21 -4
  203. package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
  204. package/web-admin/src/components/conversation-audit.ts +20 -0
  205. package/web-admin/src/layout/Shell.vue +1 -1
  206. package/web-admin/src/pages/AgentClients.vue +99 -23
  207. package/web-admin/src/pages/AgentTasks.vue +281 -0
  208. package/web-admin/src/pages/Clients.vue +4 -1
  209. package/web-admin/src/pages/Routes.vue +10 -1
  210. package/web-admin/src/pages/StorageBuckets.vue +6 -6
  211. package/web-admin/src/pages/Tools.vue +53 -4
  212. package/web-admin/src/router.ts +2 -0
  213. package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
  214. package/web-admin/tests/conversation-audit.test.mjs +63 -1
  215. package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
  216. package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
  217. package/web/console/assets/Clients-BSA1rlTB.js +0 -3
  218. package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
  219. package/web/console/assets/Routes-CXGl9SMM.css +0 -1
  220. package/web/console/assets/Routes-DN9_d9Po.js +0 -124
  221. package/web/console/assets/Runs-Cwbe6thL.js +0 -3
  222. package/web/console/assets/Runs-D8UmjP5G.css +0 -1
  223. package/web/console/assets/Shell-BEqpONiy.js +0 -1
  224. package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
  225. package/web/console/assets/StorageBuckets-CkORbYXY.js +0 -1
  226. package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
  227. package/web/console/assets/Tools-A20oaMaQ.css +0 -1
  228. package/web/console/assets/Tools-CIHInlHL.js +0 -2
  229. package/web/console/assets/index-BkLbd7Cc.js +0 -2
@@ -1,7 +1,9 @@
1
+ import { effectiveToolRateLimit, type RateLimitRequest, type RateLimitDecision } from './tool-rate-limits';
1
2
  // 工具插座运行时治理核心——设计与安全边界见 docs/TOOLS_DESIGN.md
2
3
  // 职责:消费 ToolDefinition → 白名单/主体/审批/限流/审计/签名 → 给大脑可调用的运行时句柄。
3
4
  // 中枢只做 reach(白名单/风险闸/限流/签名/审计);authority(这个人能不能做)永远由业务侧验签后裁决。
4
5
  import { createHash, createHmac } from 'node:crypto';
6
+ import { AgentTaskControlError } from '../runtime/agent-task-control';
5
7
  import type { ToolProvider } from './types';
6
8
  import { schemaAtPath, schemaTypes, valueMatchesSchemaType, type ToolConfirmCondition, type ToolDefinition } from './tool-definition';
7
9
  import { toolSummary } from './tool-definition';
@@ -233,44 +235,39 @@ function modelFacingToolResponse(fullText: string, status: number, truncateBytes
233
235
 
234
236
  // ---- 限流(进程内滑窗,三层:每任务 max_calls 由调用方计数 / 每工具 ACC execution.rate_limit / 工具源总闸)----
235
237
  export class LocalSlidingWindowRateLimiter {
236
- private readonly buckets = new Map<string, number[]>();
238
+ private readonly buckets = new Map<string, { timestamps: number[]; windowMs: number }>();
237
239
  private lastSweepAt = 0;
238
-
239
240
  constructor(private readonly now: () => number = Date.now) {}
240
241
 
241
- consume(key: string, perMin: number): boolean {
242
- if (perMin <= 0) return false;
242
+ consume(key: string, limit: number, windowSec = 60): boolean {
243
+ return this.consumeAll([{ bucket: key, limit, windowSec }]).limited;
244
+ }
245
+ consumeAll(requests: RateLimitRequest[]): RateLimitDecision {
243
246
  const now = this.now();
244
- this.sweep(now);
245
- const timestamps = (this.buckets.get(key) ?? []).filter((timestamp) => now - timestamp < 60_000);
246
- if (timestamps.length >= perMin) {
247
- this.buckets.set(key, timestamps);
248
- return true;
247
+ if (now - this.lastSweepAt >= 60_000) {
248
+ this.lastSweepAt = now;
249
+ for (const [key, bucket] of this.buckets) {
250
+ if (!bucket.timestamps.some((ts) => now - ts < bucket.windowMs)) this.buckets.delete(key);
251
+ }
249
252
  }
250
- timestamps.push(now);
251
- this.buckets.set(key, timestamps);
252
- return false;
253
- }
254
-
255
- bucketCount(): number {
256
- return this.buckets.size;
257
- }
258
-
259
- private sweep(now: number): void {
260
- if (now - this.lastSweepAt < 60_000) return;
261
- this.lastSweepAt = now;
262
- for (const [key, timestamps] of this.buckets) {
263
- const active = timestamps.filter((timestamp) => now - timestamp < 60_000);
264
- if (active.length) this.buckets.set(key, active);
265
- else this.buckets.delete(key);
253
+ const active = requests.filter((r) => r.limit > 0).map((r) => {
254
+ const windowMs = r.windowSec * 1000;
255
+ const timestamps = (this.buckets.get(r.bucket)?.timestamps ?? []).filter((ts) => now - ts < windowMs);
256
+ return { ...r, windowMs, timestamps };
257
+ });
258
+ for (const r of active) {
259
+ if (r.timestamps.length >= r.limit) {
260
+ const expires = r.timestamps[r.timestamps.length - r.limit]! + r.windowMs;
261
+ return { limited: true, bucket: r.bucket, retryAfterMs: Math.max(1, expires - now) };
262
+ }
266
263
  }
264
+ // Check every gate before charging any of them.
265
+ for (const r of active) this.buckets.set(r.bucket, { timestamps: [...r.timestamps, now], windowMs: r.windowMs });
266
+ return { limited: false };
267
267
  }
268
+ bucketCount(): number { return this.buckets.size; }
268
269
  }
269
-
270
270
  const localRateLimiter = new LocalSlidingWindowRateLimiter();
271
- function allowRate(key: string, perMin: number): boolean {
272
- return !localRateLimiter.consume(key, perMin);
273
- }
274
271
 
275
272
  /** 渐进式披露阈值:白名单内工具数 ≤ 此值全量内联(省一次往返);超过则目录+按需取定义(防几百个工具定义灌爆上下文)。 */
276
273
  export const TOOL_INLINE_MAX = 12;
@@ -315,12 +312,22 @@ export type ToolGovernanceState =
315
312
  | 'reconciliation_required';
316
313
 
317
314
  /** 工具调用的受治理结果;旧调用方仍可只读 ok/text/status。 */
315
+ export interface ToolRateLimitFeedback {
316
+ level: 'tool' | 'provider';
317
+ count: number;
318
+ window_sec: number;
319
+ scope: 'tool_provider_shared';
320
+ source: string;
321
+ }
322
+
318
323
  export interface ToolInvokeResult {
319
324
  ok: boolean;
320
325
  text: string;
321
326
  status: number;
322
327
  governance_state?: ToolGovernanceState;
323
328
  auto_retry_allowed?: boolean;
329
+ retry_after_ms?: number;
330
+ rate_limit?: ToolRateLimitFeedback;
324
331
  approval_id?: number;
325
332
  }
326
333
 
@@ -385,6 +392,8 @@ export interface ApprovalDeps {
385
392
  continuationMode?: 'rerun' | 'resume';
386
393
  /** 查"已批准且未消费"的同快照审批单并原子消费;消费成功返回单号,否则 null */
387
394
  consumeApproved(tool: string, hash: string): Promise<number | null>;
395
+ /** Managed tasks only: observation without consuming; final permit transaction consumes it. */
396
+ peekApproved?(tool: string, hash: string): Promise<number | null>;
388
397
  /** 查同快照 pending 单(去重:同一调用别重复开单) */
389
398
  findPending(tool: string, hash: string): Promise<number | null>;
390
399
  /** 查本任务同工具"已批准未消费"单(不限参数)——重跑时大脑参数漂移的纠偏依据 */
@@ -420,6 +429,14 @@ export interface ToolRuntimeDeps {
420
429
  truncateBytes: number; // 工具结果回流截断(默认 8192)
421
430
  approvedNote?: string; // 重跑时已批准调用清单提示
422
431
  approvals?: ApprovalDeps; // 不注入 = high/confirm 一律拦
432
+ /** A trusted assembly supplies these hooks; model parameters cannot create a task or permit. */
433
+ taskControl?: {
434
+ prepare(input: { tool: string; argsHash: string; readonly: boolean; approvalRequired: boolean }): Promise<void>;
435
+ grant(input: { tool: string; argsHash: string; scope: string; idempotencyKey: string; approvalId?: number }): Promise<boolean>;
436
+ settle(outcome: 'unknown' | 'confirmed_dispatched', response?: { ok: boolean; status: number; text: string }, evidenceDegraded?: boolean): Promise<void>;
437
+ };
438
+ /** Recheck sticky task enrollment for legacy Agent/engine/executor entrypoints before outbound I/O. */
439
+ beforeDispatch?: () => Promise<void>;
423
440
  audit(event: string, detail: Record<string, unknown>): Promise<void>; // 写审计;抛错=调用不放行(fail-closed)
424
441
  /** 工具语义检索(装配层注入;不注入 = 不启用检索,退回 progressive):一句意图 → 召回工具名(已是双闸内、按相关度排序)。
425
442
  * 返回 null = 检索运行时不可用(索引/凭证/embedding 临时挂)→ retrieve() 透传 null 让适配器降级。本层不碰 embedding,只收名单。 */
@@ -437,6 +454,7 @@ export interface ToolRuntimeDeps {
437
454
  };
438
455
  /** 集中限速器:返回 true = 已触发限流;不注入时退回进程内滑窗。 */
439
456
  rateLimit?: (bucket: string, limit: number, windowSec: number) => Promise<boolean>;
457
+ rateLimitAll?: (requests: RateLimitRequest[]) => Promise<RateLimitDecision>;
440
458
  }
441
459
 
442
460
  export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
@@ -508,7 +526,7 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
508
526
  // 闸1.8:幂等账本——同 job 内"副作用工具"(非只读、非声明幂等)已执行过的相同调用,重试/崩溃恢复重跑时直接返回上次结果,
509
527
  // 不重复执行(防写操作重复扣款)。放在审批闸之前:否则重跑时已消费的审批单会被当成"无批准"再次触发待审批,把重跑卡死。
510
528
  const sideEffecting = !t.readonly && !t.idempotent;
511
- if (sideEffecting && !d.idempotency) {
529
+ if ((sideEffecting || d.taskControl) && !d.idempotency) {
512
530
  await d.audit('tool_blocked', {
513
531
  tool: name,
514
532
  scope: t.scope,
@@ -520,7 +538,7 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
520
538
  text: `工具 ${name} 会产生业务副作用,但当前运行时未配置持久化执行日志,请求未发出。`,
521
539
  };
522
540
  }
523
- const idemHash = sideEffecting ? argsHash(callArgs) : '';
541
+ const idemHash = sideEffecting || d.taskControl ? argsHash(callArgs) : '';
524
542
  const idemKey = idemHash ? toolCallIdempotencyKey(d.jobId, name, idemHash, d.onBehalfOf) : '';
525
543
  if (idemHash) {
526
544
  let existing: ToolExecutionJournalEntry | null;
@@ -557,19 +575,34 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
557
575
  }
558
576
  // 前置调度闸:任何可重试的限流都必须发生在审批单消费前。
559
577
  // 请求尚未出站,不能把 429 伪装成业务拒绝,也不能白白用掉人工批准。
560
- const toolLimited = d.rateLimit
561
- ? await d.rateLimit(`tool:${d.provider.name}:${name}`, t.rateLimitPerMin, 60)
562
- : !allowRate(`tool:${d.provider.name}:${name}`, t.rateLimitPerMin);
563
- const providerLimited = d.rateLimit
564
- ? await d.rateLimit(`provider:${d.provider.name}`, d.provider.rate_limit_per_min, 60)
565
- : !allowRate(`provider:${d.provider.name}`, d.provider.rate_limit_per_min);
566
- if (toolLimited || providerLimited) {
578
+ const effective = effectiveToolRateLimit(t, d.provider.tool_rate_limits);
579
+ const gates: RateLimitRequest[] = [
580
+ { bucket: `tool:${d.provider.name}:${name}`, limit: effective.enabled ? effective.count : 0, windowSec: effective.window_sec || 60 },
581
+ { bucket: `provider:${d.provider.name}`, limit: d.provider.rate_limit_per_min, windowSec: 60 },
582
+ ].filter((gate) => gate.limit > 0);
583
+ let limitDecision: RateLimitDecision;
584
+ if (d.rateLimitAll) limitDecision = await d.rateLimitAll(gates);
585
+ else if (d.rateLimit) {
586
+ // Compatibility for external runtime assemblers that implement only the legacy single gate callback.
587
+ limitDecision = { limited: false };
588
+ for (const gate of gates) {
589
+ if (await d.rateLimit(gate.bucket, gate.limit, gate.windowSec)) {
590
+ limitDecision = { limited: true, bucket: gate.bucket, retryAfterMs: gate.windowSec * 1000 };
591
+ break;
592
+ }
593
+ }
594
+ } else limitDecision = localRateLimiter.consumeAll(gates);
595
+ if (limitDecision.limited) {
596
+ const gate = gates.find((candidate) => candidate.bucket === limitDecision.bucket) ?? gates[0]!;
597
+ const level = gate.bucket.startsWith('provider:') ? 'provider' : 'tool';
567
598
  return {
568
599
  ok: false,
569
- text: `工具 ${name} 触发限流,稍后使用同一调用标识重试。`,
600
+ text: `工具 ${name} 达到${level === 'tool' ? '单工具' : '工具源总'}限额(该工具源下的用户与会话共享)。调用未派发;等待后通过原 invocation_id 恢复,不要创建新调用。`,
570
601
  status: 429,
571
602
  governance_state: 'rejected_before_dispatch',
572
603
  auto_retry_allowed: true,
604
+ retry_after_ms: limitDecision.retryAfterMs ?? gate.windowSec * 1000,
605
+ rate_limit: { level, count: gate.limit, window_sec: gate.windowSec, scope: 'tool_provider_shared', source: level === 'tool' ? effective.source : 'provider_total' },
573
606
  };
574
607
  }
575
608
  // 闸2:风险闸 + 审批车道(B 方案:先撤再来)。high / confirm-required 的调用:
@@ -583,13 +616,16 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
583
616
  }
584
617
  const confirmHit = confirmCheck.hit;
585
618
  const needsApproval = t.risk === 'high' || t.confirmRequired || !!confirmHit;
619
+ if (d.taskControl) await d.taskControl.prepare({ tool: name, argsHash: argsHash(callArgs),
620
+ readonly: t.readonly, approvalRequired: needsApproval });
586
621
  if (needsApproval) {
587
622
  if (!d.approvals) { // 未接审批车道(理论不发生,server 总会注入):一律拦
588
623
  await d.audit('tool_blocked', { tool: name, scope: t.scope, reason: approvalReason(t, confirmHit) }).catch(() => undefined);
589
624
  return { ok: false, text: `工具 ${name} 属于需人工确认的高风险操作,当前不允许自动执行。请告知用户走人工流程。`, status: 0, governance_state: 'rejected_before_dispatch', auto_retry_allowed: false };
590
625
  }
591
626
  const hash = argsHash(callArgs);
592
- approvalId = await d.approvals.consumeApproved(name, hash);
627
+ if (d.taskControl && !d.approvals.peekApproved) throw new AgentTaskControlError('TASK_UNSUPPORTED');
628
+ approvalId = d.taskControl ? await d.approvals.peekApproved!(name, hash) : await d.approvals.consumeApproved(name, hash);
593
629
  if (approvalId === null) {
594
630
  const pendingId = await d.approvals.findPending(name, hash);
595
631
  if (pendingId !== null) {
@@ -655,7 +691,17 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
655
691
  ...(approvalId !== null ? { approval_id: approvalId } : {}),
656
692
  });
657
693
 
658
- if (idemHash) {
694
+ if (d.beforeDispatch) await d.beforeDispatch();
695
+ if (d.taskControl) {
696
+ const fresh = await d.taskControl.grant({ tool: name, argsHash: idemHash, scope: t.scope,
697
+ idempotencyKey: idemKey, ...(approvalId !== null ? { approvalId } : {}) });
698
+ if (!fresh) {
699
+ const existing = await d.idempotency!.get(name, idemHash);
700
+ if (existing?.state === 'completed') return { ok: existing.ok, text: existing.text, status: existing.status };
701
+ return { ok: false, text: 'The original task invocation already owns a dispatch attempt. Inspect the original invocation; do not replay it.',
702
+ status: 0, governance_state: 'reconciliation_required', auto_retry_allowed: false };
703
+ }
704
+ } else if (idemHash) {
659
705
  let reserved: { inserted: boolean; entry: ToolExecutionJournalEntry };
660
706
  try {
661
707
  reserved = await d.idempotency!.reserve(name, t.scope, idemHash, idemKey);
@@ -722,6 +768,7 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
722
768
  } catch (e) {
723
769
  const error = e instanceof Error && e.name === 'TimeoutError' ? `超时(${timeoutMs}ms)` : String(e);
724
770
  fullText = `调用结果不确定:${error}`;
771
+ if (d.taskControl) await d.taskControl.settle('unknown').catch(() => undefined);
725
772
  if (idemHash) {
726
773
  await d.idempotency!.markUncertain(name, idemHash, error).catch(() => undefined);
727
774
  executionUncertainty = {
@@ -741,12 +788,29 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
741
788
  }).catch(() => undefined);
742
789
  return { ok: false, text: executionUncertainty.message, status: 0, governance_state: 'reconciliation_required', auto_retry_allowed: false };
743
790
  }
791
+ // fetch (including response body consumption) has already been attempted. Readonly or
792
+ // declared-idempotent tools do not use the execution journal, but a missing response
793
+ // still cannot prove that dispatch was rejected. Agent invocations persist this state
794
+ // and resume the original result instead of dispatching a replacement call.
795
+ await d.audit('tool_reconciliation_required', {
796
+ tool: name,
797
+ scope: t.scope,
798
+ state: 'uncertain',
799
+ reason: error,
800
+ }).catch(() => undefined);
801
+ return {
802
+ ok: false,
803
+ text: `工具 ${name} 的请求已尝试发出,但未取得可信响应,执行结果未知。禁止自动重试或新建调用;请恢复原调用,必要时人工核实结果。`,
804
+ status: 0,
805
+ governance_state: 'reconciliation_required',
806
+ auto_retry_allowed: false,
807
+ };
744
808
  }
745
809
  // 回流给模型的:受上下文预算 truncateBytes 截断(与审计留存解耦)
746
810
  const text = modelFacingToolResponse(fullText, status, d.truncateBytes, responseContentType);
747
811
  const ok = status >= 200 && status < 300;
748
812
  const retText = text || `(HTTP ${status} 空响应)`;
749
- if (idemHash) {
813
+ if (idemHash && !d.taskControl) {
750
814
  try {
751
815
  await d.idempotency!.recordResponse(name, idemHash, { ok, status, text: retText });
752
816
  } catch (error) {
@@ -782,6 +846,13 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
782
846
  ...respLog,
783
847
  });
784
848
  } catch (error) {
849
+ if (d.taskControl) {
850
+ await d.taskControl.settle('confirmed_dispatched', { ok, status, text: retText }, true).catch(() => undefined);
851
+ executionUncertainty = { state: 'evidence_degraded', tool: name, scope: t.scope, idempotency_key: idemKey,
852
+ reason: 'The business response was received, but its audit evidence could not be completed.',
853
+ message: 'The original operation may have completed; inspect its original receipt. Do not submit a replacement operation.' };
854
+ return { ok: false, text: executionUncertainty.message, status: 0, governance_state: 'reconciliation_required', auto_retry_allowed: false };
855
+ }
785
856
  if (idemHash) {
786
857
  const reason = `业务响应已收到,但结果审计写入失败:${String(error).slice(0, 300)}`;
787
858
  await d.idempotency!.markEvidenceDegraded(name, idemHash, reason).catch(() => undefined);
@@ -797,7 +868,15 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
797
868
  }
798
869
  throw error;
799
870
  }
800
- if (idemHash) {
871
+ if (d.taskControl) {
872
+ try { await d.taskControl.settle('confirmed_dispatched', { ok, status, text: retText }); }
873
+ catch {
874
+ executionUncertainty = { state: 'uncertain', tool: name, scope: t.scope, idempotency_key: idemKey,
875
+ reason: 'The response was received but task settlement was not confirmed.',
876
+ message: 'Task settlement is unconfirmed. Inspect the original invocation; do not repeat the business operation.' };
877
+ return { ok: false, text: executionUncertainty.message, status: 0, governance_state: 'reconciliation_required', auto_retry_allowed: false };
878
+ }
879
+ } else if (idemHash) {
801
880
  try {
802
881
  await d.idempotency!.complete(name, idemHash);
803
882
  } catch (error) {
@@ -137,6 +137,11 @@ export interface Client {
137
137
  last_used_at?: string;
138
138
  }
139
139
 
140
+ /** Business-supplied presentation only; never a principal, routing or deduplication key. */
141
+ export interface AgentSubjectDisplay {
142
+ name: string;
143
+ }
144
+
140
145
  /** 业务后端在 Agent 授权时提交的可信业务主体。 */
141
146
  export interface AgentBusinessPrincipal {
142
147
  id: string;
@@ -154,6 +159,7 @@ export interface AgentSession {
154
159
  session_id: string;
155
160
  client_app_id: string;
156
161
  device_label: string;
162
+ subject_display?: AgentSubjectDisplay | null;
157
163
  principal: AgentBusinessPrincipal;
158
164
  on_behalf_of: string;
159
165
  allowed_routes: string[];
@@ -255,6 +261,14 @@ export interface ExecutorCapabilities {
255
261
  labels?: string[]; // 部署方自定义标签(可选,便于人识别这台机器的角色)
256
262
  }
257
263
 
264
+ /** 受控产品定位。仅作为描述数据,不授予能力,也不作为模型系统指令。 */
265
+ export interface AgentSystemInfo {
266
+ name: string;
267
+ summary: string;
268
+ domains: string[];
269
+ boundaries: string[];
270
+ }
271
+
258
272
  /** 触发路由:某业务场景 → 发给哪个 target / 哪个项目 / 哪个会话策略 / 哪个能力档 */
259
273
  export interface Route {
260
274
  route_key: string;
@@ -286,6 +300,8 @@ export interface Route {
286
300
  enabled?: boolean;
287
301
  instructions?: string;
288
302
  active_tool_limit?: number;
303
+ system_info?: AgentSystemInfo;
304
+ artifact_upload?: import('../config/artifact-config').AgentArtifactConfig;
289
305
  };
290
306
  budget?: Record<string, unknown>; // 成本预算闸:{window/window_hours, hard_cost_usd?, hard_tokens?, ...}
291
307
  description?: string;
@@ -328,7 +344,7 @@ export interface ChatAppearance {
328
344
  /** 媒体存储登记:聊天上传的图片/语音/附件落盘或落桶取永久 URL。local 开箱即用;业务桶=业务 CDN、加商品零转存。secret_key 不回显。 */
329
345
  export interface StorageBucket {
330
346
  name: string;
331
- kind: 'local' | 'cos' | 'oss' | 's3'; // 当前实现 local/cos
347
+ kind: 'local' | 'cos' | 'oss' | 's3'; // 当前实现 local/cos/oss
332
348
  region: string; // ap-shanghai
333
349
  bucket: string; // 桶名(COS 带 appid 后缀)
334
350
  endpoint?: string; // 自定义 endpoint;留空按 kind+region 拼
@@ -405,6 +421,7 @@ export interface ToolApproval {
405
421
 
406
422
  /** 工具源:业务系统的 Agent 可调接口清单(OpenAPI + x-agent-capability 契约)。secret 用于 v2 调用签名,不回显。 */
407
423
  export interface ToolProvider {
424
+ tool_rate_limits?: import('./tool-rate-limits').ToolRateLimitPolicies;
408
425
  name: string;
409
426
  base_url: string;
410
427
  spec_source: 'url' | 'inline';
@@ -1,6 +1,6 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import test from 'node:test';
3
- import { ConversationAuditError, parseCreateConversationAudit, parseConversationAuditEvents } from './agent-conversation-audit';
3
+ import { ConversationAuditError, parseCreateConversationAudit, parseCreateCrossBindingConversationAudit, parseConversationAuditEvents } from './agent-conversation-audit';
4
4
  import { conversationAuditFixture, AUDIT_SESSION_A } from '../../test-support/agent-conversation-audit-fixture';
5
5
 
6
6
  test('visible text preserves original characters and refuses undeclared reasoning or identity fields', () => {
@@ -36,3 +36,21 @@ test('event batches enforce continuity, unique ids and explicit byte or total-ev
36
36
  Array.from({ length: 5 }, (_, index) => ({ ...event, event_id: `large-${index}`, sequence: index + 1, content: 'a'.repeat(64_000) })),
37
37
  ]) assert.throws(() => parseConversationAuditEvents({ events: batch }), (error: unknown) => error instanceof ConversationAuditError && error.code === 'conversation_audit_limit' && error.statusCode === 413);
38
38
  });
39
+
40
+ test('cross-binding membership is explicit, canonical and cannot reuse one Session for two routes', () => {
41
+ const fx = conversationAuditFixture({ crossBinding: true });
42
+ const input = fx.crossInput();
43
+ assert.deepEqual(parseCreateCrossBindingConversationAudit({ ...input, members: [...input.members].reverse() }), input);
44
+ for (const patch of [
45
+ { schema: 'bailing.agent-conversation-audit-create.v1' },
46
+ { route: 'orders' }, { hub_url: 'https://other-hub.example.com' },
47
+ { member_session_ids: [AUDIT_SESSION_A] }, { members: [] },
48
+ { members: [input.members[0], { ...input.members[0], route: 'inventory' }] },
49
+ { members: [{ ...input.members[0], client_app_id: 'WRONG_CASE' }] },
50
+ { members: [{ ...input.members[0], route: 'auto' }] },
51
+ { members: [{ ...input.members[0], label: 'x'.repeat(129) }] },
52
+ { members: [{ ...input.members[0], access_token: 'never permitted' }] },
53
+ ]) assert.throws(() => parseCreateCrossBindingConversationAudit({ ...input, ...patch }),
54
+ (error: unknown) => error instanceof ConversationAuditError && error.statusCode === 400);
55
+ assert.throws(() => parseCreateConversationAudit(input), 'old v1 must never infer a wider membership');
56
+ });
@@ -6,6 +6,9 @@ import { audienceAllows } from './identity-runtime';
6
6
 
7
7
  export const CONVERSATION_AUDIT_SCHEMA = 'bailing.agent-conversation-audit.v1';
8
8
  export const CONVERSATION_AUDIT_ACK_SCHEMA = 'bailing.agent-conversation-audit-ack.v1';
9
+ export const CONVERSATION_AUDIT_CREATE_V2_SCHEMA = 'bailing.agent-conversation-audit-create.v2';
10
+ export const CONVERSATION_AUDIT_CAPABILITIES_SCHEMA = 'bailing.agent-conversation-audit-capabilities.v1';
11
+ export const CONVERSATION_AUDIT_MEMBER_BINDINGS = 'session-client-route.v1';
9
12
  export const CONVERSATION_AUDIT_MAX_EVENTS = 20_000;
10
13
  export const CONVERSATION_AUDIT_MAX_BYTES = 16 * 1024 * 1024;
11
14
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -24,6 +27,7 @@ export function auditError(code = 'conversation_audit_conflict', status = 409):
24
27
  ? 'The conversation audit is unavailable for this identity.'
25
28
  : status === 403 ? 'The frozen conversation authorization is no longer valid.'
26
29
  : status === 413 ? 'The conversation audit limit was exceeded; no events were truncated or saved.'
30
+ : status === 503 ? 'The conversation audit capability is unavailable.'
27
31
  : 'The conversation audit request conflicts with its frozen membership or event history.');
28
32
  }
29
33
 
@@ -85,6 +89,41 @@ export function parseCreateConversationAudit(value: unknown): CreateConversation
85
89
  };
86
90
  }
87
91
 
92
+ export interface ConversationAuditMemberBindingInput {
93
+ session_id: string;
94
+ client_app_id: string;
95
+ route: string;
96
+ label?: string;
97
+ }
98
+
99
+ export interface CreateCrossBindingConversationAuditInput {
100
+ schema: typeof CONVERSATION_AUDIT_CREATE_V2_SCHEMA;
101
+ client_archive_id: string;
102
+ client_conversation_id: string;
103
+ members: ConversationAuditMemberBindingInput[];
104
+ }
105
+
106
+ /** Explicit opt-in: v1 callers never acquire cross-client or cross-route scope. */
107
+ export function parseCreateCrossBindingConversationAudit(value: unknown): CreateCrossBindingConversationAuditInput {
108
+ fields(value, ['schema', 'client_archive_id', 'client_conversation_id', 'members']);
109
+ if (value.schema !== CONVERSATION_AUDIT_CREATE_V2_SCHEMA || !Array.isArray(value.members) ||
110
+ value.members.length < 1 || value.members.length > 64) invalid();
111
+ const members = value.members.map((raw): ConversationAuditMemberBindingInput => {
112
+ fields(raw, ['session_id', 'client_app_id', 'route'], ['label']);
113
+ if (typeof raw.client_app_id !== 'string' || !/^[a-z0-9][a-z0-9_-]{1,63}$/.test(raw.client_app_id) ||
114
+ typeof raw.route !== 'string' || !/^[a-z0-9][a-z0-9_-]{1,63}$/.test(raw.route) || raw.route === 'auto') invalid();
115
+ return {
116
+ session_id: auditUuid(raw.session_id), client_app_id: raw.client_app_id, route: raw.route,
117
+ ...(raw.label !== undefined ? { label: text(raw.label, 128) } : {}),
118
+ };
119
+ }).sort((a, b) => a.session_id.localeCompare(b.session_id));
120
+ // One session cannot identify two targets, even if both routes are permitted.
121
+ if (new Set(members.map((member) => member.session_id)).size !== members.length) invalid();
122
+ return { schema: CONVERSATION_AUDIT_CREATE_V2_SCHEMA,
123
+ client_archive_id: auditUuid(value.client_archive_id),
124
+ client_conversation_id: identifier(value.client_conversation_id), members };
125
+ }
126
+
88
127
  export type ConversationAuditEventKind = 'turn_start' | 'user_message' | 'assistant_message' | 'run_link' | 'turn_end';
89
128
  export type ConversationAuditTurnStatus = 'running' | 'completed' | 'failed' | 'cancelled';
90
129
  export interface ConversationAuditEventInput {
@@ -0,0 +1,114 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import {
4
+ AgentTaskControlError, agentTaskHash, assertTaskCanDispatch, assertTaskWriteCapacity, compareTaskStrings,
5
+ normalizeAgentTaskMembers, normalizeAgentTaskPolicy, taskText, taskUuid, transitionAgentTask, validateTaskInvocation,
6
+ type AgentControlledTask, type AgentTaskMemberInput,
7
+ } from './agent-task-control';
8
+
9
+ const SESSION = 'abcdefab-abcd-4abc-8abc-abcdefabcdef';
10
+ const TASK = '11111111-1111-4111-8111-111111111111';
11
+ const NOW = '2026-09-16T01:00:00.000Z';
12
+ const policy = () => ({ maxWriteCalls: 2, maxConcurrent: 1, expiresAt: null });
13
+ const member = (sessionId = SESSION): AgentTaskMemberInput => ({ sessionId, clientAppId: 'example-shop',
14
+ route: 'shop', clientConversationId: 'conversation-1', allowedTools: ['product_update', 'product_lookup'] });
15
+ const task = (): AgentControlledTask => ({ taskId: TASK, state: 'active', revision: 3, ledgerSequence: 12,
16
+ policy: policy(), members: [{ ...member(), identityHash: 'a'.repeat(64) }], scopeHash: 'b'.repeat(64),
17
+ writeReserved: 0, writeConsumed: 0, activePermits: 0, createdBy: 'admin-1', createdAt: NOW, updatedAt: NOW });
18
+ const rejectsCode = (work: () => unknown, code: string) => assert.throws(work,
19
+ (error) => error instanceof AgentTaskControlError && error.code === code);
20
+
21
+ test('task policy: no implicit low write limit; zero, bounded and explicitly unlimited remain distinct', () => {
22
+ assert.deepEqual(normalizeAgentTaskPolicy(policy()), policy());
23
+ assert.equal(normalizeAgentTaskPolicy({ ...policy(), maxWriteCalls: 0 }).maxWriteCalls, 0);
24
+ assert.equal(normalizeAgentTaskPolicy({ ...policy(), maxWriteCalls: null }).maxWriteCalls, null);
25
+ for (const invalid of [-1, 0.5, NaN, '120', undefined, Number.MAX_SAFE_INTEGER]) {
26
+ rejectsCode(() => normalizeAgentTaskPolicy({ ...policy(), maxWriteCalls: invalid } as any), 'TASK_INVALID_INPUT');
27
+ }
28
+ for (const invalid of [0, -1, 0.5, '2', null]) {
29
+ rejectsCode(() => normalizeAgentTaskPolicy({ ...policy(), maxConcurrent: invalid } as any), 'TASK_INVALID_INPUT');
30
+ }
31
+ });
32
+
33
+ test('task expiration rejects impossible calendar dates instead of silently extending the deadline', () => {
34
+ for (const expiresAt of ['2026-02-30T12:00:00Z', '2026-02-29T12:00:00Z', '2026-01-01T24:00:00Z',
35
+ '2026-09-16T01:00:00+08:00', '0001-01-01T00:00:00Z', 'invalid']) {
36
+ rejectsCode(() => normalizeAgentTaskPolicy({ ...policy(), expiresAt }), 'TASK_INVALID_INPUT');
37
+ }
38
+ assert.equal(normalizeAgentTaskPolicy({ ...policy(), expiresAt: '2028-02-29T12:00:00.1Z' }).expiresAt,
39
+ '2028-02-29T12:00:00.100Z');
40
+ });
41
+
42
+ test('task members use exact runtime conversation identifiers and independent copies', () => {
43
+ const a = member();
44
+ const b = member('22222222-2222-4222-8222-222222222222');
45
+ const normalized = normalizeAgentTaskMembers([a, b]);
46
+ assert.deepEqual(normalized, normalizeAgentTaskMembers([b, a]));
47
+ assert.deepEqual(normalized.find((item) => item.sessionId === SESSION)!.allowedTools, ['product_lookup', 'product_update']);
48
+ a.allowedTools.push('another_tool'); a.clientConversationId = 'another-conversation';
49
+ assert.equal(normalized.some((item) => item.allowedTools.includes('another_tool')), false);
50
+ for (const clientConversationId of [' conversation-1', 'conversation-1 ', 'é', 'e\u0301', '', 'x\n']) {
51
+ rejectsCode(() => normalizeAgentTaskMembers([{ ...member(), clientConversationId }]), 'TASK_INVALID_INPUT');
52
+ }
53
+ });
54
+
55
+ test('task canonical hashes are independent of locale collation and object insertion order', () => {
56
+ assert.notEqual(compareTaskStrings('é', 'e\u0301'), 0);
57
+ assert.equal(agentTaskHash({ é: 1, 'e\u0301': 2 }), agentTaskHash({ 'e\u0301': 2, é: 1 }));
58
+ assert.notEqual(agentTaskHash({ é: 1 }), agentTaskHash({ 'e\u0301': 1 }));
59
+ });
60
+
61
+ test('task identifiers cannot obtain a second enforcement identity through UUID casing', () => {
62
+ assert.equal(taskUuid(SESSION.toUpperCase()), SESSION);
63
+ assert.equal(normalizeAgentTaskMembers([member(SESSION.toUpperCase())])[0]!.sessionId, SESSION);
64
+ rejectsCode(() => normalizeAgentTaskMembers([member(SESSION), member(SESSION.toUpperCase())]), 'TASK_INVALID_INPUT');
65
+ rejectsCode(() => taskText('\ud800', 128), 'TASK_INVALID_INPUT');
66
+ assert.equal(taskText('admin-😀', 128), 'admin-😀');
67
+ });
68
+
69
+ test('task policy and members reject unsupported limits, unbounded tools and conversation bodies', () => {
70
+ rejectsCode(() => normalizeAgentTaskPolicy({ ...policy(), maxProducts: 10 } as any), 'TASK_INVALID_INPUT');
71
+ rejectsCode(() => normalizeAgentTaskMembers([{ ...member(), accessToken: 'synthetic-credential' } as any]), 'TASK_INVALID_INPUT');
72
+ rejectsCode(() => normalizeAgentTaskMembers([{ ...member(), body: 'Synthetic conversation' } as any]), 'TASK_INVALID_INPUT');
73
+ for (const allowedTools of [[], ['*'], ['product_lookup', 'product_lookup'], ['invalid-tool']]) {
74
+ rejectsCode(() => normalizeAgentTaskMembers([{ ...member(), allowedTools }]), 'TASK_INVALID_INPUT');
75
+ }
76
+ });
77
+
78
+ test('cumulative write availability includes reserved and consumed calls, not only successful calls', () => {
79
+ const current = task(); current.writeReserved = 1; current.writeConsumed = 1;
80
+ rejectsCode(() => assertTaskWriteCapacity(current), 'TASK_WRITE_BUDGET_EXHAUSTED');
81
+ current.writeReserved = 0; assertTaskWriteCapacity(current);
82
+ current.policy.maxWriteCalls = 0;
83
+ rejectsCode(() => assertTaskWriteCapacity(current), 'TASK_WRITE_BUDGET_EXHAUSTED');
84
+ current.policy.maxWriteCalls = null; assertTaskWriteCapacity(current);
85
+ });
86
+
87
+ test('pause, block and cancellation cannot grant new dispatch; expiry does not reset the budget', () => {
88
+ for (const [state, code] of [['paused', 'TASK_PAUSED'], ['blocked', 'TASK_SCOPE_BLOCKED'], ['cancelled', 'TASK_CANCELLED']] as const) {
89
+ rejectsCode(() => assertTaskCanDispatch({ ...task(), state }, NOW), code);
90
+ }
91
+ const current = task(); current.writeConsumed = 1; current.policy.expiresAt = NOW;
92
+ rejectsCode(() => assertTaskCanDispatch(current, NOW), 'TASK_EXPIRED');
93
+ assert.equal(current.writeConsumed, 1);
94
+ current.policy.expiresAt = '2026-09-16T01:00:00.001Z'; assertTaskCanDispatch(current, NOW);
95
+ });
96
+
97
+ test('cancellation is terminal; a blocked task must first be explicitly paused before resume', () => {
98
+ for (const state of ['active', 'paused', 'blocked'] as const) assert.equal(transitionAgentTask(state, 'cancel'), 'cancelled');
99
+ for (const action of ['pause', 'resume', 'cancel'] as const) {
100
+ rejectsCode(() => transitionAgentTask('cancelled', action), 'TASK_CANCELLED');
101
+ }
102
+ rejectsCode(() => transitionAgentTask('blocked', 'resume'), 'TASK_CONTROL_CONFLICT');
103
+ assert.equal(transitionAgentTask(transitionAgentTask('blocked', 'pause'), 'resume'), 'active');
104
+ });
105
+
106
+ test('invocation input requires an explicit trusted read/write classification and exact coordinates', () => {
107
+ const original = { taskId: TASK, sessionId: SESSION, invocationId: 'c'.repeat(64), runId: TASK, jobId: TASK,
108
+ tool: 'product_update', argsHash: 'd'.repeat(64), executionFingerprint: 'e'.repeat(64), readonly: false, approvalRequired: true };
109
+ assert.deepEqual(validateTaskInvocation(original), original);
110
+ rejectsCode(() => validateTaskInvocation({ ...original, readonly: undefined } as any), 'TASK_INVALID_INPUT');
111
+ rejectsCode(() => validateTaskInvocation({ ...original, arguments: { id: 1 } } as any), 'TASK_INVALID_INPUT');
112
+ rejectsCode(() => validateTaskInvocation({ ...original, idempotent: true } as any), 'TASK_INVALID_INPUT');
113
+ rejectsCode(() => validateTaskInvocation({ ...original, invocationId: 'replacement-id' }), 'TASK_INVALID_INPUT');
114
+ });