bailinghub 0.7.0 → 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 (143) hide show
  1. package/README.en.md +6 -9
  2. package/README.md +6 -9
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
  5. package/docs/AGENT_CLIENT_RUNTIME_API.md +34 -0
  6. package/docs/AGENT_TASK_CONTROL.en.md +25 -0
  7. package/docs/AGENT_TASK_CONTROL.md +94 -0
  8. package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
  9. package/docs/CHANGELOG.en.md +11 -1
  10. package/docs/CHANGELOG.md +11 -1
  11. package/docs/COMPATIBILITY.en.md +2 -0
  12. package/docs/CONTRACT.en.md +2 -0
  13. package/docs/CONTRACT.md +2 -0
  14. package/docs/GENERATED_ARTIFACTS.en.md +46 -0
  15. package/docs/GENERATED_ARTIFACTS.md +108 -0
  16. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  17. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  18. package/docs/INVOCATION_RECEIPTS.md +111 -0
  19. package/docs/README.en.md +3 -0
  20. package/docs/README.md +3 -0
  21. package/docs/RELEASE_NOTES_NEXT.en.md +2 -2
  22. package/docs/RELEASE_NOTES_NEXT.md +2 -2
  23. package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
  24. package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
  25. package/docs/TOOL_RATE_LIMITS.md +50 -0
  26. package/docs/UPGRADE_v0.8.0.en.md +71 -0
  27. package/docs/UPGRADE_v0.8.0.md +73 -0
  28. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +2 -0
  29. package/package.json +1 -1
  30. package/schemas/config/route.schema.json +1 -0
  31. package/schemas/config/tool-provider.schema.json +2 -1
  32. package/scripts/check-doc-links.mjs +1 -0
  33. package/scripts/check-image-tags.sh +1 -1
  34. package/scripts/check-release-consistency.test.mjs +2 -2
  35. package/scripts/e2e-console.mjs +32 -2
  36. package/scripts/install.sh +1 -1
  37. package/scripts/publish-images.sh +1 -1
  38. package/scripts/release-audit.mjs +1 -0
  39. package/scripts/verify-github-repo.mjs +1 -0
  40. package/sql/060_agent_artifacts.sql +11 -0
  41. package/sql/061_tool_rate_limit_policies.sql +3 -0
  42. package/sql/062_agent_task_control.sql +92 -0
  43. package/src/adapters/storage/object-storage.ts +15 -3
  44. package/src/adapters/storage/oss-signature.test.ts +40 -0
  45. package/src/adapters/storage/oss-signature.ts +21 -0
  46. package/src/app/agent-artifacts.test.ts +165 -0
  47. package/src/app/agent-artifacts.ts +85 -0
  48. package/src/app/agent-client-runtime.test.ts +76 -1
  49. package/src/app/agent-client-runtime.ts +13 -0
  50. package/src/app/agent-invocation-snapshot.ts +35 -0
  51. package/src/app/agent-task-control.ts +187 -0
  52. package/src/app/agent-task-runtime.ts +68 -0
  53. package/src/app/agent-tool-invocations.test.ts +329 -1
  54. package/src/app/agent-tool-invocations.ts +223 -10
  55. package/src/app/agent-tool-job.test.ts +11 -1
  56. package/src/app/agent-tool-job.ts +8 -1
  57. package/src/app/builtin-tools.ts +4 -0
  58. package/src/app/oss-edition.ts +1 -0
  59. package/src/app/tool-approvals.ts +4 -0
  60. package/src/app/tool-assembly.ts +5 -0
  61. package/src/core/config/artifact-config.ts +15 -0
  62. package/src/core/config/config-codec.ts +3 -1
  63. package/src/core/config/config-models.ts +11 -1
  64. package/src/core/config/route-config.ts +3 -2
  65. package/src/core/contracts/tool-rate-limits.test.ts +59 -0
  66. package/src/core/contracts/tool-rate-limits.ts +48 -0
  67. package/src/core/contracts/tools.ts +122 -43
  68. package/src/core/contracts/types.ts +3 -1
  69. package/src/core/runtime/agent-task-control.test.ts +114 -0
  70. package/src/core/runtime/agent-task-control.ts +227 -0
  71. package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -0
  72. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
  73. package/src/infrastructure/config/config-agent-task-control-journal-mysql.test.ts +315 -0
  74. package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
  75. package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
  76. package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
  77. package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -0
  78. package/src/infrastructure/config/config-storage-bucket-repository.ts +2 -2
  79. package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
  80. package/src/infrastructure/config/configstore.ts +9 -1
  81. package/src/routes/admin-agent-tasks.ts +32 -0
  82. package/src/routes/admin-tool-providers.test.ts +22 -0
  83. package/src/routes/admin-tool-providers.ts +9 -1
  84. package/src/routes/admin.ts +3 -0
  85. package/src/routes/agent-api.test.ts +76 -0
  86. package/src/routes/agent-api.ts +42 -1
  87. package/src/routes/agent-artifacts.ts +29 -0
  88. package/src/routes/agent-task-control-http-mysql.test.ts +246 -0
  89. package/src/routes/private.ts +1 -0
  90. package/src/routes/run.ts +2 -1
  91. package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
  92. package/web/console/assets/{Accounts-ChL9k-XA.js → Accounts-BRCR3O0P.js} +1 -1
  93. package/web/console/assets/AgentClients-Bf7sUUs_.js +1 -0
  94. package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
  95. package/web/console/assets/AgentTasks--bqL_QKg.js +2 -0
  96. package/web/console/assets/AgentTasks-C8ox3TyS.css +1 -0
  97. package/web/console/assets/{Approvals-Bs6FGbp2.js → Approvals-BIbZvInm.js} +1 -1
  98. package/web/console/assets/{Audit-4WWYhkFM.js → Audit-KyPSmBdZ.js} +1 -1
  99. package/web/console/assets/{BrandLockup-D2GhCipL.js → BrandLockup-Sv5DU2G6.js} +1 -1
  100. package/web/console/assets/{Channels-CmoGpiCJ.js → Channels-B9n4fbxg.js} +1 -1
  101. package/web/console/assets/{ChatEntries-BFRMtwta.js → ChatEntries-xsOCUXi_.js} +1 -1
  102. package/web/console/assets/{Clients-DGkkSXyA.js → Clients-CI3DBDHf.js} +1 -1
  103. package/web/console/assets/{Cost-BmGt0MfS.js → Cost-JgNXQPlN.js} +1 -1
  104. package/web/console/assets/{Credentials-CR-sYINT.js → Credentials-B5UUUdt0.js} +1 -1
  105. package/web/console/assets/{Diagnostics-DAPbKSJp.js → Diagnostics-BMGciWQb.js} +1 -1
  106. package/web/console/assets/{Executors-CgpiT3o8.js → Executors-CRbboOCZ.js} +1 -1
  107. package/web/console/assets/{Kb-Cm9dVSQw.js → Kb-CgLNGjRp.js} +1 -1
  108. package/web/console/assets/{Login-CyUcsTZ_.js → Login-C52JmXzx.js} +1 -1
  109. package/web/console/assets/{Projects-DldFPgWg.js → Projects-CDOvHPVS.js} +1 -1
  110. package/web/console/assets/{Routes-DubfjlBD.js → Routes-X9vHLpKW.js} +1 -1
  111. package/web/console/assets/{Runs-1hxgkuR4.js → Runs-DYNDXsqk.js} +1 -1
  112. package/web/console/assets/{Setup-DBLOnI2_.js → Setup-B91P6i1x.js} +1 -1
  113. package/web/console/assets/Shell-Bj6C8Hgo.css +1 -0
  114. package/web/console/assets/Shell-BsRa7bQQ.js +1 -0
  115. package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
  116. package/web/console/assets/StorageBuckets-DkuDM0oX.js +1 -0
  117. package/web/console/assets/{SystemSettings-cDkudo2y.js → SystemSettings-B7Mqj3k1.js} +1 -1
  118. package/web/console/assets/{SystemStatus-DZd6s8OX.js → SystemStatus-Db93b6dc.js} +1 -1
  119. package/web/console/assets/{Targets-DYNGq1NU.js → Targets-CuuIYeZO.js} +1 -1
  120. package/web/console/assets/Tools-CHiqz9XZ.js +2 -0
  121. package/web/console/assets/Tools-DU8ei6sd.css +1 -0
  122. package/web/console/assets/index-UGvfF3Xr.js +2 -0
  123. package/web/console/assets/{request-B7MLvOqo.js → request-DeGya810.js} +1 -1
  124. package/web/console/assets/{schema-CMuwjYdJ.js → schema-BqlqLw1R.js} +1 -1
  125. package/web/console/index.html +1 -1
  126. package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
  127. package/web-admin/src/components/AgentSetupPanel.vue +13 -0
  128. package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
  129. package/web-admin/src/layout/Shell.vue +1 -1
  130. package/web-admin/src/pages/AgentClients.vue +3 -1
  131. package/web-admin/src/pages/AgentTasks.vue +281 -0
  132. package/web-admin/src/pages/StorageBuckets.vue +6 -6
  133. package/web-admin/src/pages/Tools.vue +53 -4
  134. package/web-admin/src/router.ts +2 -0
  135. package/web/console/assets/AgentClients-Bs7UgVDj.js +0 -1
  136. package/web/console/assets/AgentClients-DkgPTEbq.css +0 -1
  137. package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
  138. package/web/console/assets/Shell-gJ5Vz_E7.js +0 -1
  139. package/web/console/assets/StorageBuckets-DkDW16tj.js +0 -1
  140. package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
  141. package/web/console/assets/Tools-A20oaMaQ.css +0 -1
  142. package/web/console/assets/Tools-DpWM59vV.js +0 -2
  143. package/web/console/assets/index-DGqs28gI.js +0 -2
@@ -0,0 +1,68 @@
1
+ import type { ToolRuntimeDeps } from '../core/contracts/tools';
2
+ import type { Job } from '../core/contracts/types';
3
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
4
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
5
+ import { AgentTaskControlError, taskAssert, taskDigest, taskUuid, type AgentControlledTask } from '../core/runtime/agent-task-control';
6
+ import { isAgentToolInvocationJob } from './agent-tool-job';
7
+ import { assertAgentLegacyTaskAllowedFor } from './agent-task-control';
8
+
9
+ /** Only an original runtime run can supply a task. Model arguments and arbitrary job metadata cannot enroll one. */
10
+ export async function taskRuntimeFor(config: ConfigStoreContract | null, state: RuntimeStateStore, job: Job): Promise<{
11
+ task: AgentControlledTask | null;
12
+ taskControl?: ToolRuntimeDeps['taskControl'];
13
+ beforeDispatch?: () => Promise<void>;
14
+ }> {
15
+ const hasBinding = Boolean(job.metadata.agent_task_binding || job.metadata.agent_task_id);
16
+ if (!job.agent_session_id) { taskAssert(!hasBinding, 'TASK_BINDING_CONFLICT'); return { task: null }; }
17
+ const repo = config?.agentTaskControl;
18
+ if (!repo || !await repo.supportsTaskControl()) {
19
+ taskAssert(!hasBinding, 'TASK_UNSUPPORTED');
20
+ return { task: null };
21
+ }
22
+ const task = isAgentToolInvocationJob(job) ? await repo.findTaskForRun(job.session_id!, job.agent_session_id) : null;
23
+ if (!task) {
24
+ taskAssert(!hasBinding, 'TASK_BINDING_CONFLICT');
25
+ await assertAgentLegacyTaskAllowedFor(config, job.agent_session_id);
26
+ return { task: null, beforeDispatch: () => assertAgentLegacyTaskAllowedFor(config, job.agent_session_id!) };
27
+ }
28
+ taskAssert(isAgentToolInvocationJob(job), 'TASK_UNSUPPORTED');
29
+ const sessionId = taskUuid(job.agent_session_id);
30
+ const invocationId = taskDigest(job.metadata.agent_invocation_id);
31
+ const runId = taskUuid(job.session_id);
32
+ let permitId: string | null = null;
33
+ return { task, taskControl: {
34
+ async prepare(input) {
35
+ taskAssert(input.tool === job.metadata.agent_tool && input.argsHash === job.metadata.agent_args_hash, 'TASK_INVOCATION_CONFLICT');
36
+ const contract = { schema_version: 'bailing.agent-task-tool-contract.v1', readonly: input.readonly,
37
+ approval_required: input.approvalRequired, args_hash: input.argsHash,
38
+ execution_fingerprint: taskDigest(job.metadata.agent_execution_fingerprint) };
39
+ await repo.freezeInvocationContract(job.job_id, contract);
40
+ await repo.reserveInvocation({ taskId: task.taskId, sessionId, invocationId, runId, jobId: job.job_id,
41
+ tool: input.tool, argsHash: input.argsHash, executionFingerprint: taskDigest(job.metadata.agent_execution_fingerprint),
42
+ readonly: input.readonly, approvalRequired: input.approvalRequired });
43
+ },
44
+ async grant(input) {
45
+ taskAssert(input.tool === job.metadata.agent_tool && input.argsHash === job.metadata.agent_args_hash, 'TASK_INVOCATION_CONFLICT');
46
+ const result = await repo.grantDispatchPermit({ taskId: task.taskId, sessionId, invocationId, retryOriginal: true,
47
+ ...(input.approvalId === undefined ? {} : { approvalId: input.approvalId }),
48
+ journal: { scope: input.scope, idempotencyKey: input.idempotencyKey } }).catch((error: unknown) => {
49
+ if (error instanceof AgentTaskControlError) throw error;
50
+ throw new AgentTaskControlError('TASK_DISPATCH_UNCERTAIN');
51
+ });
52
+ if (result.fresh) { taskAssert(result.invocation.permitId, 'TASK_RECORD_INVALID'); permitId = result.invocation.permitId; }
53
+ return result.fresh;
54
+ },
55
+ async settle(outcome, response, evidenceDegraded) {
56
+ taskAssert(permitId, 'TASK_PERMIT_CONFLICT');
57
+ await repo.settlePermit({ taskId: task.taskId, sessionId, invocationId, permitId, outcome,
58
+ terminal: outcome === 'confirmed_dispatched', ...(response ? { response } : {}),
59
+ ...(evidenceDegraded ? { evidenceDegraded: true } : {}) });
60
+ },
61
+ } };
62
+ }
63
+
64
+ /** Legacy model/builtin jobs must not bypass an enrolled Session's task gate. */
65
+ export async function assertTaskLegacyJobAllowedFor(config: ConfigStoreContract | null, job: Job): Promise<void> {
66
+ taskAssert(!job.metadata.agent_task_binding && !job.metadata.agent_task_id, 'TASK_UNSUPPORTED');
67
+ if (job.agent_session_id) await assertAgentLegacyTaskAllowedFor(config, job.agent_session_id);
68
+ }
@@ -1,6 +1,7 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { createServer, type Server } from 'node:http';
3
3
  import test from 'node:test';
4
+ import { LocalSlidingWindowRateLimiter } from '../core/contracts/tools';
4
5
  import type { AppConfig } from '../core/config/config';
5
6
  import type { ToolExecutionJournalEntry } from '../core/contracts/tools';
6
7
  import type { AgentSession, Client, Job, Route, ToolApproval, ToolProvider } from '../core/contracts/types';
@@ -10,6 +11,7 @@ import type { AgentClientRunRecord } from '../infrastructure/config/config-agent
10
11
  import {
11
12
  AgentToolApiError,
12
13
  invokeAgentToolFor,
14
+ inspectAgentToolInvocationFor,
13
15
  listAgentToolsFor,
14
16
  resumeAgentToolFor,
15
17
  type AgentToolAuthContext,
@@ -179,9 +181,10 @@ function fixture(baseUrl: string) {
179
181
  deps,
180
182
  state,
181
183
  approvals,
184
+ calls,
182
185
  setRoute: (value: Route) => { currentRoute = value; },
183
186
  setSpec: (value: string) => { currentSpec = value; },
184
- setToolRateLimited: (value: boolean) => { toolRateLimited = value; },
187
+ setToolRateLimited: (value: boolean) => { toolRateLimited = value; provider.tool_rate_limits = { default: { mode: 'custom', count: 120, window: '1h' }, overrides: {} }; },
185
188
  setRuntimeRun: (value: AgentClientRunRecord | null) => { runtimeRun = value; },
186
189
  };
187
190
  }
@@ -197,6 +200,170 @@ function runtimeRun(overrides: Partial<AgentClientRunRecord> = {}): AgentClientR
197
200
  };
198
201
  }
199
202
 
203
+ async function pendingReceiptFixture() {
204
+ const fx = fixture('https://business.invalid');
205
+ fx.setRoute(routeWithForcedApproval());
206
+ fx.setRuntimeRun(runtimeRun());
207
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
208
+ const input = {
209
+ invocation_id: invocationId('a'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
210
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 1, name: 'Synthetic' },
211
+ };
212
+ const result = await invokeAgentToolFor(fx.deps, auth(), input);
213
+ assert.equal(result.state, 'awaiting_approval');
214
+ const job = [...fx.state.jobs.values()][0]!;
215
+ return { ...fx, input, result, job };
216
+ }
217
+
218
+ function forbidReceiptMutations(fx: Awaited<ReturnType<typeof pendingReceiptFixture>>) {
219
+ const snapshot = () => JSON.stringify({ jobs: [...fx.state.jobs], approvals: fx.approvals, calls: [...fx.calls], audits: fx.state.audits });
220
+ const before = snapshot();
221
+ const forbidden = async () => { throw new Error('inspection_attempted_mutation'); };
222
+ fx.state.createJob = forbidden;
223
+ fx.state.updateJob = forbidden;
224
+ fx.state.appendAudit = forbidden;
225
+ fx.state.acquireRuntimeLock = forbidden;
226
+ fx.state.releaseRuntimeLock = forbidden;
227
+ fx.deps.configStore!.approvals.use = forbidden;
228
+ fx.deps.configStore!.approvals.create = forbidden;
229
+ fx.deps.configStore!.rateLimits.consume = forbidden;
230
+ fx.deps.configStore!.toolCalls.reserve = forbidden;
231
+ fx.deps.configStore!.toolCalls.complete = forbidden;
232
+ fx.deps.configStore!.toolCalls.recordResponse = forbidden;
233
+ // Inspection needs no original encrypted arguments or server decryption secret.
234
+ fx.deps.cfg.server.token = 'synthetic-rotated-key';
235
+ return () => assert.equal(snapshot(), before, 'inspection must not alter original execution evidence');
236
+ }
237
+
238
+ test('Agent receipt: approved original remains undispatched across repeated read-only inspections', async () => {
239
+ const fx = await pendingReceiptFixture();
240
+ fx.approvals[0]!.status = 'approved';
241
+ const unchanged = forbidReceiptMutations(fx);
242
+ for (let attempt = 0; attempt < 2; attempt++) {
243
+ const receipt = await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input);
244
+ assert.equal(receipt.schema_version, 'bailing.agent-invocation-receipt.v1');
245
+ assert.equal(receipt.read_only, true);
246
+ assert.equal(receipt.business_operation_performed, false);
247
+ assert.equal(receipt.agent_run_id, AGENT_RUN_ID);
248
+ assert.equal(receipt.invocation_id, fx.input.invocation_id);
249
+ assert.equal(receipt.dispatch_state, 'not_dispatched');
250
+ assert.equal(receipt.journal_state, 'absent');
251
+ assert.deepEqual(receipt.result, fx.result);
252
+ assert.deepEqual(receipt.approval, { status: 'approved', approval_id: 1 });
253
+ assert.equal(fx.approvals[0]!.used_at, undefined);
254
+ }
255
+ unchanged();
256
+ });
257
+
258
+ test('Agent receipt: completed journal supersedes a stale job without persisting or dispatching', async () => {
259
+ const fx = await pendingReceiptFixture();
260
+ fx.calls.set(`${fx.job.job_id}\0staff_edit\0${fx.job.metadata.agent_args_hash}`, {
261
+ state: 'completed', ok: true, status: 200, text: 'Synthetic completion', idempotencyKey: 'synthetic-original-key',
262
+ });
263
+ const unchanged = forbidReceiptMutations(fx);
264
+ const receipt = await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input);
265
+ assert.equal(receipt.result_source, 'journal');
266
+ assert.equal(receipt.journal_state, 'completed');
267
+ assert.equal(receipt.result?.state, 'executed');
268
+ assert.equal(receipt.result?.auto_retry_allowed, false);
269
+ assert.equal(receipt.dispatch_state, 'attempted');
270
+ assert.equal(receipt.result?.text, 'Synthetic completion');
271
+ assert.equal(JSON.stringify(receipt).includes('synthetic-original-key'), false);
272
+ unchanged();
273
+ });
274
+
275
+ test('Agent receipt: unresolved or malformed journal never grants a repeat operation', async (t) => {
276
+ for (const state of ['dispatching', 'response_recorded', 'uncertain', 'evidence_degraded', 'unexpected'] as const) {
277
+ await t.test(state, async () => {
278
+ const fx = await pendingReceiptFixture();
279
+ fx.calls.set(`${fx.job.job_id}\0staff_edit\0${fx.job.metadata.agent_args_hash}`, {
280
+ state, ok: true, status: 200, text: 'Unconfirmed synthetic content', idempotencyKey: 'synthetic-original-key',
281
+ } as ToolExecutionJournalEntry);
282
+ const unchanged = forbidReceiptMutations(fx);
283
+ const receipt = await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input);
284
+ assert.equal(receipt.journal_state, state === 'unexpected' ? 'unknown' : state);
285
+ assert.equal(receipt.result_source, 'journal');
286
+ assert.equal(receipt.result?.state, 'reconciliation_required');
287
+ assert.equal(receipt.result?.auto_retry_allowed, false);
288
+ assert.equal(receipt.business_operation_performed, false);
289
+ assert.equal(JSON.stringify(receipt).includes('Unconfirmed synthetic content'), false);
290
+ unchanged();
291
+ });
292
+ }
293
+ });
294
+
295
+ test('Agent receipt: result JSON is allowlisted and invalid schema stays unknown', async () => {
296
+ const fx = await pendingReceiptFixture();
297
+ fx.job.result = { ...fx.result, private_data: 'synthetic-hidden', rate_limit: {
298
+ level: 'tool', count: 120, window_sec: 3600, scope: 'tool_provider_shared', source: 'override', token: 'synthetic-secret',
299
+ } };
300
+ const receipt = await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input);
301
+ assert.equal(JSON.stringify(receipt).includes('synthetic-hidden'), false);
302
+ assert.equal(JSON.stringify(receipt).includes('synthetic-secret'), false);
303
+ assert.equal(JSON.stringify(receipt).includes('agent_frozen_arguments'), false);
304
+ fx.job.result = { ...fx.result, schema_version: 'unknown-schema' };
305
+ delete fx.job.metadata.agent_dispatch_attempted;
306
+ const unchanged = forbidReceiptMutations(fx);
307
+ const unknown = await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input);
308
+ assert.equal(unknown.result, null);
309
+ assert.equal(unknown.result_source, 'none');
310
+ assert.equal(unknown.dispatch_state, 'unknown');
311
+ unchanged();
312
+ });
313
+
314
+ test('Agent receipt: capability declaration changes do not require historical execution fingerprints', async () => {
315
+ const fx = await pendingReceiptFixture();
316
+ const changed = JSON.parse(spec());
317
+ changed.paths['/staff/edit'].post.summary = 'Updated synthetic description';
318
+ changed.paths['/staff/edit'].post.requestBody.content['application/json'].schema.properties.note = { type: 'string' };
319
+ fx.setSpec(JSON.stringify(changed));
320
+ const unchanged = forbidReceiptMutations(fx);
321
+ assert.equal((await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input)).result?.state, 'awaiting_approval');
322
+ unchanged();
323
+ });
324
+
325
+ test('Agent receipt: current tool revocation still forbids access to original result content', async () => {
326
+ const fx = await pendingReceiptFixture();
327
+ const changed = routeWithForcedApproval();
328
+ changed.tools = { ...changed.tools, agent_direct: { enabled: true, write_tools: [] } };
329
+ fx.setRoute(changed);
330
+ const unchanged = forbidReceiptMutations(fx);
331
+ await assert.rejects(inspectAgentToolInvocationFor(fx.deps, auth(), fx.input),
332
+ (error) => error instanceof AgentToolApiError && error.code === 'capability_changed');
333
+ unchanged();
334
+ });
335
+
336
+ test('Agent receipt: original session, client, principal, route and run bindings cannot be changed', async (t) => {
337
+ for (const drift of ['session', 'client', 'principal', 'tenant', 'on_behalf_of', 'run', 'route', 'thread'] as const) {
338
+ await t.test(drift, async () => {
339
+ const fx = await pendingReceiptFixture();
340
+ const caller = auth();
341
+ if (drift === 'session') caller.session.session_id = '33333333-3333-4333-8333-333333333333';
342
+ if (drift === 'client') caller.client.app_id = 'another-client';
343
+ if (drift === 'principal') caller.session.principal.id = 'another-user';
344
+ if (drift === 'tenant') caller.session.principal.tenant = 'another-tenant';
345
+ if (drift === 'on_behalf_of') caller.session.on_behalf_of = 'another-subject';
346
+ if (drift === 'run') fx.setRuntimeRun(runtimeRun({ session_id: '33333333-3333-4333-8333-333333333333' }));
347
+ if (drift === 'route') fx.setRuntimeRun(runtimeRun({ route_key: 'another-route' }));
348
+ if (drift === 'thread') fx.setRuntimeRun(runtimeRun({ thread_id: 99 }));
349
+ const unchanged = forbidReceiptMutations(fx);
350
+ await assert.rejects(inspectAgentToolInvocationFor(fx.deps, caller, fx.input),
351
+ (error) => error instanceof AgentToolApiError && ['invocation_not_found', 'invocation_conflict', 'agent_run_conflict'].includes(error.code));
352
+ unchanged();
353
+ });
354
+ }
355
+ });
356
+
357
+ test('Agent receipt: absent original or malformed identifier never creates substitute evidence', async () => {
358
+ const fx = await pendingReceiptFixture();
359
+ const unchanged = forbidReceiptMutations(fx);
360
+ await assert.rejects(inspectAgentToolInvocationFor(fx.deps, auth(), { invocation_id: invocationId('b') }),
361
+ (error) => error instanceof AgentToolApiError && error.statusCode === 404 && error.code === 'invocation_not_found');
362
+ await assert.rejects(inspectAgentToolInvocationFor(fx.deps, auth(), { invocation_id: 'bad-id' }),
363
+ (error) => error instanceof AgentToolApiError && error.statusCode === 400);
364
+ unchanged();
365
+ });
366
+
200
367
  test('Agent direct: 本地投影只含只读与精确写工具,写工具默认继承 ACC 审批声明', async (t) => {
201
368
  let businessCalls = 0;
202
369
  const business = createServer(async (req, res) => {
@@ -440,6 +607,167 @@ test('Agent direct: 工具限流不消费批准,同 invocation 可安全重试
440
607
  assert.equal(businessCalls, 1);
441
608
  });
442
609
 
610
+ test('Agent direct: transport uncertainty and lost client receipts resume the original result without redispatch', async (t) => {
611
+ for (const kind of ['readonly', 'idempotent_write', 'non_idempotent_write'] as const) {
612
+ for (const failure of ['fetch_rejected', 'response_body_lost', 'client_receipt_lost'] as const) {
613
+ await t.test(`${kind}: ${failure}`, async (t) => {
614
+ let attempts = 0;
615
+ t.mock.method(globalThis, 'fetch', async () => {
616
+ attempts++;
617
+ if (failure === 'fetch_rejected') throw new TypeError('synthetic transport failure');
618
+ if (failure === 'client_receipt_lost') return new Response('{"ok":true}', { status: 200 });
619
+ return { status: 200, text: async () => { throw new TypeError('synthetic response body loss'); } } as unknown as Response;
620
+ });
621
+ const fx = fixture('https://business.invalid');
622
+ if (kind === 'idempotent_write') {
623
+ const declaration = JSON.parse(spec());
624
+ declaration.paths['/staff/edit'].post['x-agent-capability'].execution = { readonly: false, idempotent: true };
625
+ fx.setSpec(JSON.stringify(declaration));
626
+ }
627
+ const caller = auth();
628
+ const catalog = await listAgentToolsFor(fx.deps, caller, 'tenant-agent');
629
+ const tool = kind === 'readonly' ? 'staff_list' : 'staff_edit';
630
+ const definition = catalog.tools.find((item) => item.name === tool)!;
631
+ assert.equal(definition.readonly, kind === 'readonly');
632
+ assert.equal(definition.idempotent, kind !== 'non_idempotent_write');
633
+ const input = {
634
+ invocation_id: invocationId('a'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
635
+ agent_run_id: AGENT_RUN_ID, tool,
636
+ arguments: kind === 'readonly' ? { keyword: 'Synthetic' } : { id: 1, name: 'Synthetic' },
637
+ };
638
+ // For a lost client receipt the business result is already persisted; the client only
639
+ // retains its invocation ID and must recover it instead of submitting another operation.
640
+ const first = await invokeAgentToolFor(fx.deps, caller, input);
641
+ const confirmed = failure === 'client_receipt_lost';
642
+ assert.equal(first.state, confirmed ? 'executed' : 'reconciliation_required');
643
+ assert.equal(first.auto_retry_allowed, false);
644
+ assert.equal(first.ok, confirmed);
645
+ assert.equal(first.business_status, confirmed ? 200 : undefined, 'only a trusted business response confirms business status');
646
+ assert.equal(attempts, 1);
647
+
648
+ assert.deepEqual(await resumeAgentToolFor(fx.deps, caller, { invocation_id: input.invocation_id }), first);
649
+ assert.deepEqual(await invokeAgentToolFor(fx.deps, caller, input), first);
650
+ assert.equal(attempts, 1, 'resume and same-invocation replay must never dispatch a replacement request');
651
+ assert.equal(fx.state.jobs.size, 1);
652
+
653
+ caller.session.allowed_routes = [];
654
+ await assert.rejects(
655
+ resumeAgentToolFor(fx.deps, caller, { invocation_id: input.invocation_id }),
656
+ (error) => error instanceof AgentToolApiError && error.code === 'route_not_allowed',
657
+ );
658
+ assert.equal(attempts, 1, 'uncertainty never bypasses the current authorization boundary');
659
+ });
660
+ }
661
+ }
662
+ });
663
+
664
+ test('Agent direct: an unapproved rate-limited write resumes its sealed original arguments after restart and lost ACK', async (t) => {
665
+ const received: unknown[] = [];
666
+ const business = createServer(async (req, res) => {
667
+ let raw = ''; for await (const chunk of req) raw += String(chunk);
668
+ received.push(JSON.parse(raw));
669
+ res.writeHead(200, { 'content-type': 'application/json' }); res.end('{"ok":true}');
670
+ });
671
+ const port = await listen(business); t.after(() => close(business));
672
+ const fx = fixture(`http://127.0.0.1:${port}`);
673
+ fx.setToolRateLimited(true);
674
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
675
+ const invocation_id = invocationId('9');
676
+ const limited = await invokeAgentToolFor(fx.deps, auth(), {
677
+ invocation_id, route: 'tenant-agent', capability_revision: catalog.capability_revision,
678
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Synthetic name' },
679
+ });
680
+ assert.equal(limited.state, 'rejected_before_dispatch');
681
+ assert.equal(limited.retry_after_ms, 3_600_000);
682
+ assert.equal(limited.rate_limit?.scope, 'tool_provider_shared');
683
+ assert.equal(received.length, 0);
684
+ assert.equal(fx.approvals.length, 0);
685
+ assert.doesNotMatch(JSON.stringify([...fx.state.jobs.values()]), /Synthetic name/);
686
+ assert.equal((await resumeAgentToolFor(fx.deps, auth(), { invocation_id })).auto_retry_allowed, true);
687
+ // New coordinator, JSON round trip of the persisted jobs, original Session/run/invocation.
688
+ const restarted = fixture(`http://127.0.0.1:${port}`);
689
+ for (const job of fx.state.jobs.values()) await restarted.state.createJob(JSON.parse(JSON.stringify(job)));
690
+ const result = await resumeAgentToolFor(restarted.deps, auth(), { invocation_id });
691
+ assert.equal(result.state, 'executed');
692
+ assert.deepEqual(received, [{ id: 7, name: 'Synthetic name' }]);
693
+ assert.deepEqual(await resumeAgentToolFor(restarted.deps, auth(), { invocation_id }), result);
694
+ assert.equal(received.length, 1);
695
+ assert.ok([...restarted.state.jobs.values()].every((job) => !job.metadata.agent_frozen_arguments));
696
+ });
697
+
698
+ test('Agent direct: the third burst write under 120/hour reaches business; closing Hub tool limits keeps the provider gate', async (t) => {
699
+ let calls = 0;
700
+ t.mock.method(globalThis, 'fetch', async () => { calls++; return new Response('{"ok":true}'); });
701
+ const fx = fixture('https://business.invalid');
702
+ const definition = JSON.parse(spec());
703
+ definition.paths['/staff/edit'].post['x-agent-capability'].execution = { rate_limit: { count: 120, window: '1h' } };
704
+ fx.setSpec(JSON.stringify(definition));
705
+ const limiter = new LocalSlidingWindowRateLimiter(() => 0);
706
+ fx.deps.configStore!.rateLimits.consumeAll = async (gates) => limiter.consumeAll(gates);
707
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
708
+ const invoke = (id: string) => invokeAgentToolFor(fx.deps, auth(), { invocation_id: invocationId(id), route: 'tenant-agent', capability_revision: catalog.capability_revision,
709
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: id } });
710
+ for (const id of ['1', '2', '3']) assert.equal((await invoke(id)).state, 'executed');
711
+ assert.equal(calls, 3);
712
+ const provider = (await fx.deps.configStore!.toolProviders.get('example-business'))!;
713
+ provider.tool_rate_limits = { default: { mode: 'disabled' }, overrides: {} };
714
+ provider.rate_limit_per_min = 1;
715
+ assert.equal((await invoke('4')).state, 'executed');
716
+ const blocked = await invoke('5');
717
+ assert.equal(blocked.rate_limit?.level, 'provider');
718
+ assert.equal(calls, 4);
719
+ provider.rate_limit_per_min = 0;
720
+ assert.equal((await resumeAgentToolFor(fx.deps, auth(), { invocation_id: invocationId('5') })).state, 'executed');
721
+ assert.equal(calls, 5);
722
+ });
723
+
724
+ test('Agent direct: corrupt snapshot and uncertain dispatch fence never replay a write', async (t) => {
725
+ for (const failure of ['corrupt_snapshot', 'rotated_key', 'dispatch_in_progress', 'journal_unavailable'] as const) {
726
+ await t.test(failure, async (t) => {
727
+ let calls = 0;
728
+ t.mock.method(globalThis, 'fetch', async () => { calls++; return new Response('{"ok":true}'); });
729
+ const fx = fixture('https://business.invalid'); fx.setToolRateLimited(true);
730
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
731
+ const invocation_id = invocationId('8');
732
+ await invokeAgentToolFor(fx.deps, auth(), { invocation_id, route: 'tenant-agent', capability_revision: catalog.capability_revision,
733
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Synthetic name' } });
734
+ fx.setToolRateLimited(false);
735
+ const job = [...fx.state.jobs.values()][0]!;
736
+ if (failure === 'corrupt_snapshot') job.metadata.agent_frozen_arguments = 'v1.invalid.snapshot';
737
+ if (failure === 'rotated_key') fx.deps.cfg.server.token = 'rotated-synthetic-key';
738
+ if (failure === 'dispatch_in_progress') {
739
+ job.metadata.agent_dispatch_attempted = true;
740
+ job.result = { ...job.result, state: 'in_progress', auto_retry_allowed: false };
741
+ }
742
+ if (failure === 'journal_unavailable') {
743
+ fx.deps.configStore!.toolCalls.get = async () => { throw new Error('synthetic_storage_unavailable'); };
744
+ await assert.rejects(resumeAgentToolFor(fx.deps, auth(), { invocation_id }), /synthetic_storage_unavailable/);
745
+ } else {
746
+ const result = await resumeAgentToolFor(fx.deps, auth(), { invocation_id });
747
+ assert.equal(result.auto_retry_allowed, false);
748
+ assert.equal(result.state, failure === 'dispatch_in_progress' ? 'reconciliation_required' : 'rejected_before_dispatch');
749
+ }
750
+ assert.equal(calls, 0);
751
+ });
752
+ }
753
+ });
754
+
755
+ test('Agent direct: failure to persist the dispatch fence makes zero business requests and remains recoverable', async (t) => {
756
+ let calls = 0;
757
+ t.mock.method(globalThis, 'fetch', async () => { calls++; return new Response('{"ok":true}'); });
758
+ const fx = fixture('https://business.invalid');
759
+ const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
760
+ const update = t.mock.method(fx.state, 'updateJob', async () => null);
761
+ const invocation_id = invocationId('7');
762
+ await assert.rejects(invokeAgentToolFor(fx.deps, auth(), { invocation_id, route: 'tenant-agent', capability_revision: catalog.capability_revision,
763
+ agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Synthetic' } }),
764
+ (error) => error instanceof AgentToolApiError && error.code === 'invocation_storage_unavailable');
765
+ assert.equal(calls, 0);
766
+ update.mock.restore();
767
+ assert.equal((await resumeAgentToolFor(fx.deps, auth(), { invocation_id })).state, 'executed');
768
+ assert.equal(calls, 1);
769
+ });
770
+
443
771
  test('Agent direct: capability revision 变更、参数漂移和未开启路由均失败关闭', async () => {
444
772
  const fx = fixture('https://business.invalid');
445
773
  const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');