@1agents/acp-service 0.10.8 → 0.10.10

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 (94) hide show
  1. package/dist/bin/a2a.js +12 -1
  2. package/dist/src/a2a/gateway.d.ts +268 -2
  3. package/dist/src/a2a/gateway.js +337 -25
  4. package/dist/src/a2a/job-directory.d.ts +5 -0
  5. package/dist/src/a2a/job-directory.js +15 -0
  6. package/dist/src/a2a/preflight.d.ts +38 -0
  7. package/dist/src/a2a/preflight.js +56 -8
  8. package/dist/src/a2a/types.d.ts +8 -0
  9. package/dist/src/execution/case-view.d.ts +109 -0
  10. package/dist/src/execution/case-view.js +125 -0
  11. package/dist/src/execution/cases.d.ts +56 -0
  12. package/dist/src/execution/cases.js +77 -0
  13. package/dist/src/execution/externals.d.ts +83 -0
  14. package/dist/src/execution/externals.js +61 -0
  15. package/dist/src/execution/handoff.d.ts +54 -1
  16. package/dist/src/execution/handoff.js +80 -15
  17. package/dist/src/execution/ledger.d.ts +35 -2
  18. package/dist/src/execution/ledger.js +72 -2
  19. package/dist/src/execution/snapshots.d.ts +28 -0
  20. package/dist/src/execution/snapshots.js +64 -0
  21. package/dist/src/execution/targets.d.ts +63 -0
  22. package/dist/src/execution/targets.js +15 -1
  23. package/dist/src/execution/workbench.d.ts +5 -1
  24. package/dist/src/execution/workbench.js +13 -4
  25. package/dist/workbench-ui/app.css +18 -0
  26. package/dist/workbench-ui/app.js +13 -13
  27. package/package.json +12 -13
  28. package/vendor/dsh/a2a-executor.d.ts +2 -2
  29. package/vendor/dsh/adapter.d.ts +4 -4
  30. package/vendor/dsh/cordis.patch.yml +6 -5
  31. package/vendor/dsh/handoff-executor.d.ts +7 -0
  32. package/vendor/dsh/handoff-executor.js +28 -0
  33. package/vendor/dsh/handoff-spec.d.ts +26 -0
  34. package/vendor/dsh/handoff-spec.js +14 -0
  35. package/vendor/dsh/handoff-tools.d.ts +4 -0
  36. package/vendor/dsh/handoff-tools.js +20 -0
  37. package/vendor/dsh/index.js +8 -0
  38. package/vendor/dsh/review-mcp.js +6 -2
  39. package/vendor/dsh/review.d.ts +3 -0
  40. package/vendor/dsh/review.js +19 -0
  41. package/vendor/dsh/service-process.d.ts +9 -1
  42. package/vendor/dsh/service-process.js +69 -3
  43. package/vendor/dsh/ticket-tools.d.ts +1 -1
  44. package/vendor/runtime/dist/{cli-DXmYwv3U.js → cli-BwanDcOo.js} +4 -4
  45. package/vendor/runtime/dist/{cli-DXmYwv3U.js.map → cli-BwanDcOo.js.map} +1 -1
  46. package/vendor/runtime/dist/cli.js +8 -8
  47. package/vendor/runtime/dist/{client-VQsqcIOJ.d.ts → client-C5zneoBs.d.ts} +3 -1
  48. package/vendor/runtime/dist/{client-VQsqcIOJ.d.ts.map → client-C5zneoBs.d.ts.map} +1 -1
  49. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  50. package/vendor/runtime/dist/docs-site/CLI.html +833 -0
  51. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  52. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  53. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  54. package/vendor/runtime/dist/docs-site/config.html +450 -0
  55. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  56. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  57. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  58. package/vendor/runtime/dist/docs-site/flows.html +498 -0
  59. package/vendor/runtime/dist/docs-site/index.html +367 -0
  60. package/vendor/runtime/dist/docs-site/install.html +386 -0
  61. package/vendor/runtime/dist/docs-site/llms.txt +36 -0
  62. package/vendor/runtime/dist/docs-site/output-formats.html +407 -0
  63. package/vendor/runtime/dist/docs-site/permissions.html +422 -0
  64. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  65. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  66. package/vendor/runtime/dist/docs-site/releasing.html +341 -0
  67. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  68. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +336 -0
  69. package/vendor/runtime/dist/docs-site/safe-errors.html +323 -0
  70. package/vendor/runtime/dist/docs-site/session-control.html +408 -0
  71. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  72. package/vendor/runtime/dist/docs-site/sessions.html +488 -0
  73. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  74. package/vendor/runtime/dist/{flows-DJ17ajbw.js → flows-CzLUHUTS.js} +4 -4
  75. package/vendor/runtime/dist/{flows-DJ17ajbw.js.map → flows-CzLUHUTS.js.map} +1 -1
  76. package/vendor/runtime/dist/flows.d.ts +1 -1
  77. package/vendor/runtime/dist/flows.js +1 -1
  78. package/vendor/runtime/dist/{invocation-options-PBfCgrdi.js → invocation-options-B6pIpdpR.js} +4 -4
  79. package/vendor/runtime/dist/{invocation-options-PBfCgrdi.js.map → invocation-options-B6pIpdpR.js.map} +1 -1
  80. package/vendor/runtime/dist/{ipc-BQQpcEdP.js → ipc-ivLtSAdL.js} +21 -3
  81. package/vendor/runtime/dist/ipc-ivLtSAdL.js.map +1 -0
  82. package/vendor/runtime/dist/{output-B3MDn7kv.js → output-BqKnXXb0.js} +3 -3
  83. package/vendor/runtime/dist/{output-B3MDn7kv.js.map → output-BqKnXXb0.js.map} +1 -1
  84. package/vendor/runtime/dist/{queue-owner-runtime-DXCVngwU.js → queue-owner-runtime-DXJND10J.js} +11 -2
  85. package/vendor/runtime/dist/queue-owner-runtime-DXJND10J.js.map +1 -0
  86. package/vendor/runtime/dist/runtime.d.ts +1 -1
  87. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  88. package/vendor/runtime/dist/runtime.js +3 -3
  89. package/vendor/runtime/dist/{session-watch-DURyCw31.js → session-watch-BHB3_PXm.js} +4 -4
  90. package/vendor/runtime/dist/{session-watch-DURyCw31.js.map → session-watch-BHB3_PXm.js.map} +1 -1
  91. package/vendor/runtime/dist/{watch-CIpoMaWD.js → watch-UjokHUfS.js} +2 -2
  92. package/vendor/runtime/dist/{watch-CIpoMaWD.js.map → watch-UjokHUfS.js.map} +1 -1
  93. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +0 -1
  94. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +0 -1
@@ -1,6 +1,7 @@
1
1
  /** Main-agent tools backed by standard A2A, with a durable completion inbox. */
2
2
  import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
3
3
  import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
4
+ import { readFile } from 'node:fs/promises';
4
5
  import http from 'node:http';
5
6
  import path from 'node:path';
6
7
  import { setTimeout as delay } from 'node:timers/promises';
@@ -16,7 +17,7 @@ import { artifactLinks, formatNotice } from './notices.js';
16
17
  import { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema } from './preflight.js';
17
18
  import { a2aResultContractSchema } from './result-metadata.js';
18
19
  import { ARTIFACT_CONTENT_LIMIT } from './artifact-content.js';
19
- import { artifactInstructions, defaultJobDirectory, defaultManifestPath, spaceInstructions } from './job-directory.js';
20
+ import { artifactInstructions, defaultJobDirectory, defaultManifestPath, snapshotInstructions, spaceInstructions } from './job-directory.js';
20
21
  import { WORKBENCH_UI_PATH, WorkbenchUi } from './workbench-ui.js';
21
22
  import { notifyDesktop } from './desktop-notify.js';
22
23
  import { isAcpAgentPreset, legacyLifecycle, normalizeLifecycle, oneShotShouldClose, sessionLifecycleSchema } from './session-lifecycle.js';
@@ -27,12 +28,16 @@ import { ProjectRoleDiscovery, DISCOVERY_METHODS, projectDiscoveryConfigSchema }
27
28
  import { deliveryProgress, deliveryException } from '../execution/delivery-progress.js';
28
29
  import { JobLedger } from '../execution/ledger.js';
29
30
  import { invokeTicket, reopenForContinue, TICKET_METHODS } from '../execution/ticket.js';
30
- import { continueByConvention, HANDOFF_METHODS, invokeHandoff } from '../execution/handoff.js';
31
+ import { continueByConvention, decideHandoff, HANDOFF_METHODS, invokeHandoff, offerConvention, proposeByFact } from '../execution/handoff.js';
31
32
  import { rolePublicationDirectory } from '../execution/spaces.js';
33
+ import { caseOpenSchema, CaseError, openCase, projectCase, requireCase } from '../execution/cases.js';
34
+ import { factRecordSchema, factSatisfied, receiptRecordSchema, recordFact, recordReceipt } from '../execution/externals.js';
35
+ import { SnapshotError, SnapshotStore } from '../execution/snapshots.js';
32
36
  import { decideHumanReview, HumanReviewError, humanReviewDecisionSchema } from '../execution/human-review.js';
33
37
  import { answerProcessRequest, createProcessRequest, expireProcessRequest, processRequestAnswerSchema, processRequestCreateSchema, processRequestSchema, ProcessRequestError, projectProcessRequest, sameProcessRequest } from '../execution/process-request.js';
34
38
  import { chatItems, pageChat } from '../execution/workbench-chat.js';
35
39
  import { workbenchSnapshot, listWorkbenchTasks, listWorkbenchAgents, getWorkbenchTask } from '../execution/workbench.js';
40
+ import { workbenchCases } from '../execution/case-view.js';
36
41
  import { AgentRegistry, AgentRegistryError, readDevelopment } from '../execution/agent-registry.js';
37
42
  import { agentNamePattern, listAgentFiles } from '../execution/agent-files.js';
38
43
  import { createPptDeliveryRun, recoverPptDeliveryRun, assertPptDeliveryRecoverable, advancePptDelivery, pptDeliveryInputSchema, pptDeliveryPolicySchema, pptDeliveryRecoveryInputSchema, scriptDirectory, scriptRevisionName } from '../execution/ppt-delivery.js';
@@ -54,7 +59,10 @@ const configSchema = z.object({
54
59
  pollIntervalMs: z.number().int().min(50).max(60_000).default(3000),
55
60
  pptDelivery: pptDeliveryPolicySchema.optional(),
56
61
  reportReview: reportReviewPolicySchema.optional(),
57
- workbench: z.object({ /** Omit on a trusted network: the page opens without login and the API needs no bearer. */ token: string.optional(), reviewerId: string.default('local-owner'), reviewerName: string.optional(), publicBaseUrl: endpoint.optional(),
62
+ workbench: z.object({ /** Omit on a trusted network: the page opens without login and the API needs no bearer. */ token: string.optional(), reviewerId: string.default('local-owner'), reviewerName: string.optional(),
63
+ /** Who may decide each gate. A gate with nobody named falls back to the reviewer. */
64
+ gateReviewers: z.object({ handoff: string.optional(), publish: string.optional(), acceptance: string.optional() }).strict().optional(),
65
+ publicBaseUrl: endpoint.optional(),
58
66
  /** Shared with a host that serves this page itself (DSH). Over the bearer API, only its relayed page requests may publish or decide reviews. */
59
67
  pageRelaySecret: z.string().min(32).optional(),
60
68
  allowedOrigins: z.array(string).optional(),
@@ -86,8 +94,9 @@ const configSchema = z.object({
86
94
  }
87
95
  });
88
96
  const originFields = { originSessionId: string };
89
- /** Who acted: a person, or a coach agent naming its session. */
90
- const actorSchema = z.object({ kind: z.enum(['person', 'coach']), agent: string.optional(), sessionId: string.optional() }).strict();
97
+ /** Who acted: a person, or a coach agent naming its session. A person also carries the reviewer's id. */
98
+ const actorSchema = z.object({ kind: z.enum(['person', 'coach']), id: string.optional(), agent: string.optional(), sessionId: string.optional(),
99
+ via: z.enum(['page', 'relay']).optional() }).strict();
91
100
  const taskFields = { ...originFields, remote: string, taskId: string };
92
101
  const prompt = z.string().min(1).max(256 * 1024).refine(value => Boolean(value.trim()), 'Prompt must contain text');
93
102
  const spawnSchema = z.object({ ...originFields, remote: string, prompt,
@@ -122,6 +131,7 @@ const executionReviewSchema = executionJobSchema.extend({ attemptId: string, res
122
131
  const workbenchContinueSchema = z.object({ prompt: string }).strict();
123
132
  const workbenchAcceptSchema = z.object({ note: string.optional() }).strict();
124
133
  const executionUnwatchSchema = executionJobSchema.extend({ reason: string }).strict();
134
+ const caseGetSchema = z.object({ originSessionId: string, caseId: string }).strict();
125
135
  /** The coach answers an executor's process request: the same answer as the workbench page, naming who decided and why. */
126
136
  const processAnswerSchema = executionJobSchema.extend({ requestId: string, clientRequestId: string,
127
137
  outcome: z.enum(['accepted', 'cancelled', 'approved', 'rejected', 'abandoned']), note: string.optional(), stopTask: z.literal(true).optional(),
@@ -142,6 +152,8 @@ const EXECUTION_METHODS = {
142
152
  execution_process_answer: { description: '回答任务上的一条过程请求,和工作台页面同一记录;decidedBy 写明是人还是教练(教练写明所在的智能体会话),note 写理由。', parameters: z.toJSONSchema(processAnswerSchema) },
143
153
  execution_inbox: { description: '读取领域交付任务的完成/需决策通知;旧A2A收件箱保持原合同。', parameters: z.toJSONSchema(inboxSchema) },
144
154
  execution_ack: { description: '确认已处理领域交付通知,不修改业务验收或执行状态。', parameters: z.toJSONSchema(ackSchema) },
155
+ case_open: { description: '开一件事:写下目标,登记进账本。之后 handoff_space、handoff_offer 和带 caseId 的提交都只能引用已存在的一件事,不会隐式创建。', parameters: z.toJSONSchema(caseOpenSchema) },
156
+ case_get: { description: '读取一件事:目标、共享产物空间、其下的任务、交接、约定和待确认。不派单,不决定。', parameters: z.toJSONSchema(caseGetSchema) },
145
157
  ...TICKET_METHODS,
146
158
  ...HANDOFF_METHODS,
147
159
  };
@@ -215,6 +227,7 @@ export class RemoteAgentGateway {
215
227
  ledger;
216
228
  lease;
217
229
  stateFile;
230
+ snapshots;
218
231
  state;
219
232
  clients = new Map();
220
233
  probeCards = new Map();
@@ -246,6 +259,7 @@ export class RemoteAgentGateway {
246
259
  // directory: local restarts must never mark remote executions failed.
247
260
  this.lease = new FileA2AStore(path.join(this.config.stateDirectory, 'lease'));
248
261
  this.stateFile = path.join(this.config.stateDirectory, 'gateway.json');
262
+ this.snapshots = new SnapshotStore(path.join(this.config.stateDirectory, 'handoff-snapshots'));
249
263
  try {
250
264
  this.state = JSON.parse(readFileSync(this.stateFile, 'utf8'));
251
265
  if (![1, 2].includes(this.state.version) || !Array.isArray(this.state.jobs) || !Array.isArray(this.state.notices))
@@ -365,15 +379,48 @@ export class RemoteAgentGateway {
365
379
  const delivery = this.state.pptDeliveries?.runs[attempt.attemptId];
366
380
  const report = this.state.reportReviews?.[attempt.attemptId];
367
381
  return { ...view, ...(delivery ? { deliveryProgress: deliveryProgress(delivery) } : {}),
382
+ ...(this.state.artifactSpaceRefusals?.[jobId] ? { artifactSpaceRefusal: this.state.artifactSpaceRefusals[jobId] } : {}),
368
383
  ...(report ? { reportProgress: { stage: report.stage, phase: report.phase, reportPath: report.reportPath, fileCheck: report.fileCheck, humanReview: report.humanReviews.at(-1) } } : {}),
369
384
  ...(this.state.executionCancellations?.[attempt.attemptId] ? { cancellation: structuredClone(this.state.executionCancellations[attempt.attemptId]) } : {}), attemptId: attempt.attemptId, submissionStatus: attempt.submissionStatus,
370
385
  backendRunRef: attempt.backendRunRef, phase: attempt.phase, stale: attempt.stale,
371
386
  resultSummary: view.result?.resultSummary, artifactLinks: view.result?.artifactLinks ?? [],
372
- resultDigest: view.result?.resultDigest, resultRevision: view.result?.resultRevision,
387
+ resultDigest: view.result?.resultDigest, resultRevision: view.result?.resultRevision ?? view.resultRevision,
373
388
  ...(raw ? { remote: raw.remote, taskId: raw.taskId, contextId: raw.contextId,
374
389
  sessionId: Task.fromJSON(raw.task).metadata?.['1agents']?.sessionId,
375
390
  resultMetadata: Task.fromJSON(raw.task).metadata?.['1agents']?.result } : {}) };
376
391
  }
392
+ /**
393
+ * Freeze the bytes a handoff talks about. The files are copied into the gateway's snapshot store and addressed
394
+ * by their digest, so a later round of the source job cannot change what an accepted handoff points at.
395
+ */
396
+ async freezeHandoff(handoff) {
397
+ if (handoff.snapshots)
398
+ return handoff.snapshots;
399
+ const attempt = this.ledger.getAttempt(handoff.fromAttemptId);
400
+ const files = [];
401
+ for (const raw of attempt.result?.resultArtifacts ?? []) {
402
+ const artifact = raw;
403
+ if (!artifact.sha256 || !artifact.path)
404
+ continue;
405
+ const bytes = await this.artifactBytes(handoff.fromJobId, artifact);
406
+ files.push({ digest: artifact.sha256, name: path.basename(artifact.path),
407
+ ...(artifact.mediaType ? { mediaType: artifact.mediaType } : {}), bytes });
408
+ }
409
+ const snapshots = await this.snapshots.freeze({ caseId: handoff.caseId, handoffId: handoff.handoffId, files });
410
+ const origin = this.ledger.originOf(handoff.fromJobId);
411
+ if (origin)
412
+ this.ledger.commitHandoff(origin, { ...handoff, snapshots, updatedAt: new Date().toISOString() }, 'handoff.snapshots_frozen');
413
+ return snapshots;
414
+ }
415
+ /** The verified bytes of one artifact: the local copy when it still matches, otherwise the host's own copy. */
416
+ async artifactBytes(jobId, artifact) {
417
+ if (!artifact.path || !artifact.sha256)
418
+ throw new Error('This artifact has no verified receipt');
419
+ const local = await readFile(artifact.path).catch(() => undefined);
420
+ if (local && createHash('sha256').update(local).digest('hex') === artifact.sha256)
421
+ return local;
422
+ return (await this.workbenchArtifact(jobId, artifact.sha256)).content;
423
+ }
377
424
  async submitExecution(input, options = {}) {
378
425
  if (input.handoffId) {
379
426
  const handoff = this.ledger.findHandoff(input.originSessionId, input.handoffId);
@@ -385,11 +432,22 @@ export class RemoteAgentGateway {
385
432
  throw new Error('Handoff purpose does not match');
386
433
  if (input.caseId && input.caseId !== handoff.caseId)
387
434
  throw new Error('Handoff case does not match');
435
+ // The accepted version is the one the handoff names. Another version needs a new proposal.
436
+ if (input.resultRevision && input.resultRevision !== handoff.artifactRevision)
437
+ throw new Error('Handoff version does not match; propose the new version instead');
388
438
  if (handoff.status === 'taken' && handoff.childJobId)
389
439
  return this.ledgerView(input.originSessionId, handoff.childJobId);
390
- input = { ...input, purpose: handoff.purpose, caseId: handoff.caseId, resultRevision: input.resultRevision ?? handoff.artifactRevision,
391
- parentJobRef: { sourceId: this.ledger.sourceId, jobId: handoff.fromJobId }, parentAttemptId: handoff.fromAttemptId };
392
- }
440
+ const frozen = handoff.snapshots ?? [];
441
+ const snapshot = { caseId: handoff.caseId, handoffId: handoff.handoffId, revision: handoff.artifactRevision, digest: handoff.artifactDigest,
442
+ files: frozen.map(item => ({ digest: item.digest, name: item.name, size: item.size,
443
+ ...(item.mediaType ? { mediaType: item.mediaType } : {}), path: this.snapshots.absolutePath(item.storedPath) })) };
444
+ input = { ...input, purpose: handoff.purpose, caseId: handoff.caseId, resultRevision: handoff.artifactRevision,
445
+ parentJobRef: { sourceId: this.ledger.sourceId, jobId: handoff.fromJobId }, parentAttemptId: handoff.fromAttemptId,
446
+ ...(frozen.length ? { input: { ...input.input, handoffSnapshot: snapshot } } : {}) };
447
+ }
448
+ // A task may only join a thing that exists; it never creates one by naming it.
449
+ if (input.caseId)
450
+ requireCase(this.ledger, input.originSessionId, input.caseId);
393
451
  const replay = this.ledger.replay({ ...input, requestDigestInput: options.requestDigestInput, jobId: options.jobId, operation: options.jobId ? 'continue' : 'submit', targetSnapshot: { targetId: input.targetId } });
394
452
  if (replay)
395
453
  return { ...this.ledgerView(input.originSessionId, replay.job.jobId), attemptId: replay.attempt.attemptId, requestedAttempt: replay.attempt };
@@ -451,6 +509,8 @@ export class RemoteAgentGateway {
451
509
  throw new Error('provider and model apply only to standard presets; oneagents-acp-* presets switch models through session/set_config_option');
452
510
  const preflight = fields.preflight === undefined ? undefined : a2aPreflightRequirementsSchema.parse(fields.preflight);
453
511
  const declaredRequirements = resolved.directoryPolicy ? { ...preflight, allowedDirectories: resolved.directoryPolicy.allowedDirectories } : preflight;
512
+ // The sandbox profile travels with the requirements: the host provisions the environment the target names.
513
+ const sandboxed = resolved.sandbox ? { ...declaredRequirements, sandbox: resolved.sandbox } : declaredRequirements;
454
514
  const declaredContract = fields.resultContract === undefined ? undefined : a2aResultContractSchema.parse(fields.resultContract);
455
515
  const declaredResult = declaredContract && options.notificationOrigin ? { ...declaredContract, jobId: job.jobId } : declaredContract;
456
516
  // Unless the caller declared its own artifact location, every task gets <cwd>/.1agents/jobs/<jobId>/ and a
@@ -458,7 +518,7 @@ export class RemoteAgentGateway {
458
518
  let artifacts = !declaredResult?.artifactManifestPath && !declaredRequirements?.jobDirectory && resolved.cwd
459
519
  ? { directory: defaultJobDirectory(resolved.cwd, job.jobId), manifest: defaultManifestPath(resolved.cwd, job.jobId, attempt.attemptId) } : undefined;
460
520
  const withArtifacts = (declared, add) => artifacts ? add(artifacts) : declared;
461
- let requirements = withArtifacts(declaredRequirements, found => ({ ...declaredRequirements, jobDirectory: found.directory }));
521
+ let requirements = withArtifacts(sandboxed, found => ({ ...sandboxed, jobDirectory: found.directory }));
462
522
  let resultContract = withArtifacts(declaredResult, found => ({ ...(declaredResult ?? { jobId: job.jobId }), artifactManifestPath: found.manifest }));
463
523
  const boundRole = resolved.target.binding.loadRole ? resolved.target.binding.roleId : undefined;
464
524
  const explicitRole = resolved.target.kind === 'agent_host' && fields.roleId !== undefined ? string.parse(fields.roleId) : undefined;
@@ -471,7 +531,7 @@ export class RemoteAgentGateway {
471
531
  if (!artifacts)
472
532
  throw error;
473
533
  artifacts = undefined;
474
- requirements = declaredRequirements;
534
+ requirements = sandboxed;
475
535
  resultContract = declaredResult;
476
536
  await this.checkDispatch(resolved.remote, resolved.cwd, requirements, resolved.endpoint);
477
537
  }
@@ -484,7 +544,17 @@ export class RemoteAgentGateway {
484
544
  await this.checkDispatch(resolved.remote, resolved.cwd, { ...requirements, ...optional }, resolved.endpoint);
485
545
  requirements = { ...requirements, ...optional };
486
546
  }
487
- catch { /* A refused shared space or role directory does not block the task's own job directory. */ }
547
+ catch (error) {
548
+ // A refused shared space must not block the task's own directory, but it must not vanish
549
+ // either: without the admission the agent cannot write there, and the caller would see a
550
+ // task that ran and silently ignored the space it was given.
551
+ const detail = error instanceof Error ? error.message : String(error);
552
+ const which = caseSpace ? `shared artifact space ${caseSpace.root}` : `role publication ${publication}`;
553
+ this.state.artifactSpaceRefusals = { ...(this.state.artifactSpaceRefusals ?? {}),
554
+ [job.jobId]: { at: new Date().toISOString(), path: caseSpace?.root ?? publication ?? '', reason: detail.slice(0, 500) } };
555
+ this.save();
556
+ console.error(`[a2a-gateway] ${which} refused for job ${job.jobId}: ${detail}`);
557
+ }
488
558
  }
489
559
  const client = await this.client(resolved.remote, resolved.endpoint);
490
560
  // Target changes/disable during asynchronous preflight must win before sending.
@@ -498,7 +568,8 @@ export class RemoteAgentGateway {
498
568
  const task = await client.sendMessage(SendMessageRequest.fromJSON({ message: { messageId: attempt.attemptId, role: 'ROLE_USER',
499
569
  ...(options.previous ? { contextId: options.previous.contextId } : {}), parts: [{ text: prompt.parse(fields.prompt) + (artifacts ? artifactInstructions(artifacts.directory, artifacts.manifest) : '')
500
570
  + spaceInstructions({ originSessionId: input.originSessionId, jobId: job.jobId, attemptId: attempt.attemptId, caseId: job.caseId,
501
- artifactSpace: requirements?.artifactSpace, rolePublication: requirements?.rolePublication }) }] },
571
+ artifactSpace: requirements?.artifactSpace, rolePublication: requirements?.rolePublication })
572
+ + snapshotInstructions(input.input?.handoffSnapshot) }] },
502
573
  metadata: { '1agents': { ...(!options.previous ? { cwd: resolved.cwd, ...(resolved.agentPreset ? { agentPreset: resolved.agentPreset } : {}),
503
574
  ...(resolved.target.binding.agentFile ? { agentFile: resolved.target.binding.agentFile } : {}) } : {}),
504
575
  ...(explicitRole ? { roleId: explicitRole } : !options.previous && boundRole ? { roleId: boundRole } : {}),
@@ -983,16 +1054,38 @@ export class RemoteAgentGateway {
983
1054
  await this.invoke('execution_continue', { originSessionId: task.originSessionId, jobId, input: { prompt }, initiatedBy: { kind: 'person' } });
984
1055
  return this.workbenchTask(jobId);
985
1056
  }
986
- /** A person marks the task's current result as read (已阅). */
987
- acceptWorkbenchTask(jobId, note) {
1057
+ /** A person marks the task's current result as read (已阅). This is the acceptance the conventions wait for. */
1058
+ acceptWorkbenchTask(jobId, note, via = 'page') {
988
1059
  const task = this.workbenchTask(jobId);
989
1060
  if (!task.canAccept)
990
1061
  throw new Error('只有已完成、还没有结论的任务可以标记已阅。');
1062
+ // A gate belongs to the person it names; the page may not decide it for someone else.
1063
+ const reviewer = this.gateReviewer('acceptance');
1064
+ if (reviewer !== this.config.workbench.reviewerId)
1065
+ throw new Error(`这道验收关口的负责人是 ${reviewer}。`);
991
1066
  const result = this.ledger.getAttempt(task.currentAttemptId).result;
992
1067
  this.ledger.acceptance(task.originSessionId, jobId, { attemptId: task.currentAttemptId, resultRevision: result.resultRevision, resultDigest: result.resultDigest,
993
- reviewStatus: 'accepted', ...(note ? { note } : {}), decidedBy: { kind: 'person' } });
1068
+ reviewStatus: 'accepted', ...(note ? { note } : {}), decidedBy: { kind: 'person', id: reviewer, via } });
1069
+ // Same rule as the A2A acceptance: an accepted result makes the one convention that waited for it hold.
1070
+ // This only records the edge; opening the next task stays a separate, explicit submit.
1071
+ continueByConvention(this.ledger, task.originSessionId, jobId);
1072
+ this.noticeDecision(task.title ?? jobId, `验收通过(${via === 'page' ? '网关页面' : '宿主转发'})`, result.resultRevision, result.resultDigest);
994
1073
  return this.workbenchTask(jobId);
995
1074
  }
1075
+ /**
1076
+ * Tell the person a decision was written in their name.
1077
+ *
1078
+ * The gateway cannot prove a click happened: a caller that runs as the same user can read the relay
1079
+ * secret and post the same request a page would. The banner is the check that does not depend on
1080
+ * that secret — if the person did not just decide this, they see it now instead of at review time.
1081
+ */
1082
+ noticeDecision(title, what, revision, digest) {
1083
+ const config = this.config.workbench;
1084
+ if (!config?.desktopNotifications)
1085
+ return;
1086
+ const version = revision ? `版本 ${revision}${digest ? `(${digest.slice(0, 8)})` : ''}` : '';
1087
+ notifyDesktop(`工作台决定 · ${title}`.slice(0, 120), [what, version, '若不是你本人操作,请立即核对'].filter(Boolean).join(';').slice(0, 240), config.publicBaseUrl);
1088
+ }
996
1089
  async workbenchArtifact(jobId, sha256) {
997
1090
  this.workbenchTask(jobId);
998
1091
  for (const raw of this.state.jobs) {
@@ -1288,6 +1381,20 @@ export class RemoteAgentGateway {
1288
1381
  }
1289
1382
  if (method === 'execution_submit')
1290
1383
  return this.submitExecution(executionSubmitSchema.parse(params));
1384
+ if (method === 'case_open') {
1385
+ const input = caseOpenSchema.parse(params);
1386
+ // This channel is an agent's. It may not write that a person opened the case.
1387
+ if (input.createdBy?.kind === 'person')
1388
+ throw new Error('A person opens a case on the workbench page, not through this channel');
1389
+ return openCase(this.ledger, input);
1390
+ }
1391
+ if (method === 'case_get') {
1392
+ const input = caseGetSchema.parse(params);
1393
+ const record = projectCase(this.ledger, input.originSessionId, input.caseId);
1394
+ if (!record)
1395
+ throw new Error('No such case');
1396
+ return record;
1397
+ }
1291
1398
  if (method === 'execution_continue') {
1292
1399
  const input = executionContinueSchema.parse(params), job = this.ledger.get(input.originSessionId, input.jobId);
1293
1400
  const replay = this.ledger.replay({ originSessionId: input.originSessionId, jobId: job.jobId,
@@ -1373,8 +1480,14 @@ export class RemoteAgentGateway {
1373
1480
  continueByConvention(this.ledger, originSessionId, jobId);
1374
1481
  return recorded;
1375
1482
  }
1376
- if (Object.hasOwn(HANDOFF_METHODS, method))
1377
- return invokeHandoff(this.ledger, method, params);
1483
+ if (Object.hasOwn(HANDOFF_METHODS, method)) {
1484
+ const result = invokeHandoff(this.ledger, method, params);
1485
+ // The bytes a handoff talks about are frozen once, so a later round of the source job cannot change them.
1486
+ if ((method === 'handoff_propose' || method === 'handoff_decide') && result && typeof result === 'object' && 'handoffId' in result) {
1487
+ await this.freezeHandoff(result);
1488
+ }
1489
+ return result;
1490
+ }
1378
1491
  if (Object.hasOwn(TICKET_METHODS, method)) {
1379
1492
  const ticket = invokeTicket(this.ledger, method, params);
1380
1493
  const body = params && typeof params === 'object' ? params : {};
@@ -1530,14 +1643,17 @@ export class RemoteAgentGateway {
1530
1643
  throw new Error('Missing A2A event task ID');
1531
1644
  await Promise.allSettled(this.state.jobs.filter(job => job.taskId === taskId).map(job => this.refresh(job)));
1532
1645
  }
1533
- workbenchProjection() {
1646
+ workbenchSource() {
1534
1647
  const config = this.config.workbench;
1535
1648
  if (!config)
1536
1649
  throw new Error('Workbench is not configured');
1537
1650
  const runs = Object.values(this.state.pptDeliveries.runs);
1538
1651
  const reportRuns = Object.values(this.state.reportReviews ?? {});
1539
- return workbenchSnapshot({ ledger: this.ledger.snapshot(), runs, reportRuns, reviews: [...runs.flatMap(run => run.humanReviews ?? []), ...reportRuns.flatMap(run => run.humanReviews)],
1540
- processRequests: this.state.processRequests ?? [], actorId: config.reviewerId, ...(config.allowedOrigins ? { allowedOrigins: config.allowedOrigins } : {}) });
1652
+ return { ledger: this.ledger.snapshot(), runs, reportRuns, reviews: [...runs.flatMap(run => run.humanReviews ?? []), ...reportRuns.flatMap(run => run.humanReviews)],
1653
+ processRequests: this.state.processRequests ?? [], actorId: config.reviewerId, ...(config.allowedOrigins ? { allowedOrigins: config.allowedOrigins } : {}) };
1654
+ }
1655
+ workbenchProjection() {
1656
+ return workbenchSnapshot(this.workbenchSource());
1541
1657
  }
1542
1658
  workbench(operation) {
1543
1659
  const run = this.workbenchQueue.then(operation);
@@ -1561,6 +1677,127 @@ export class RemoteAgentGateway {
1561
1677
  this.save();
1562
1678
  }
1563
1679
  workbenchList(query = {}) { return listWorkbenchTasks(this.workbenchProjection(), query); }
1680
+ /** Who may decide each gate. A gate with nobody named belongs to the reviewer. */
1681
+ gateReviewer(gate) {
1682
+ const config = this.config.workbench;
1683
+ return config.gateReviewers?.[gate] ?? config.reviewerId;
1684
+ }
1685
+ /** The gates and their people, so the page can show who may press which button. */
1686
+ gateReviewers() {
1687
+ return { handoff: this.gateReviewer('handoff'), publish: this.gateReviewer('publish'), acceptance: this.gateReviewer('acceptance') };
1688
+ }
1689
+ /** One thing is the first screen of the workbench: the cases this scope can see. */
1690
+ workbenchCaseList(query = {}) {
1691
+ const { list } = workbenchCases(this.workbenchSource(), this.workbenchProjection());
1692
+ const offset = Math.max(0, Math.trunc(query.offset ?? 0)), limit = Math.min(200, Math.max(1, Math.trunc(query.limit ?? 50)));
1693
+ return { ...list, items: list.items.slice(offset, offset + limit), offset, limit,
1694
+ origins: [...new Set(list.items.map(item => item.originSessionId))], reviewers: this.gateReviewers() };
1695
+ }
1696
+ workbenchCaseDetails() { return workbenchCases(this.workbenchSource(), this.workbenchProjection()).details; }
1697
+ /** One case, in the scope this page may see. */
1698
+ workbenchCase(caseId, originSessionId) {
1699
+ const details = this.workbenchCaseDetails();
1700
+ const found = Object.values(details).find(item => item.caseId === caseId && (!originSessionId || item.originSessionId === originSessionId));
1701
+ if (!found)
1702
+ throw new Error('Case not found in authorized scope');
1703
+ return { ...structuredClone(found), reviewers: this.gateReviewers() };
1704
+ }
1705
+ /** Open a thing from the page. The page's reviewer is its creator. */
1706
+ openWorkbenchCase(input) {
1707
+ return this.workbench(async () => {
1708
+ const config = this.config.workbench;
1709
+ const parsed = z.object({ originSessionId: string, caseId: string.optional(), goal: z.string().trim().min(1).max(4000),
1710
+ title: z.string().trim().min(1).max(200).optional() }).strict().parse(input);
1711
+ return openCase(this.ledger, { ...parsed, createdBy: { kind: 'person', id: config.reviewerId } });
1712
+ });
1713
+ }
1714
+ /** Register a convention on a case, from the page. It states what may follow; it dispatches nothing. */
1715
+ async registerWorkbenchConvention(caseId, input) {
1716
+ return this.workbench(async () => {
1717
+ const scope = this.workbenchCase(caseId);
1718
+ const parsed = z.object({ fromPurpose: string.optional(), fromTargetId: string.optional(), toTargetId: string, toPurpose: string,
1719
+ when: z.enum(['acceptance_accepted', 'ticket_closed', 'fact_reached']), requireHuman: z.boolean().optional(),
1720
+ condition: z.object({ metric: string, operator: z.enum(['gte', 'lte', 'gt', 'lt']), value: z.number().finite() }).strict().optional() }).strict().parse(input);
1721
+ return offerConvention(this.ledger, { originSessionId: scope.originSessionId, caseId, ...parsed });
1722
+ });
1723
+ }
1724
+ /**
1725
+ * Accept or reject a handoff proposal. Only a person on the workbench page does this; the decision carries the
1726
+ * configured reviewer, and the bytes are frozen before the decision is written down.
1727
+ */
1728
+ async decideWorkbenchHandoff(caseId, handoffId, input, via = 'page') {
1729
+ return this.workbench(async () => {
1730
+ const config = this.config.workbench;
1731
+ const scope = this.workbenchCase(caseId);
1732
+ const decision = z.object({ decision: z.enum(['accept', 'reject']), note: z.string().trim().max(4000).optional() }).strict().parse(input);
1733
+ // A gate belongs to the person it names; the page may not decide it for someone else.
1734
+ const reviewer = this.gateReviewer('handoff');
1735
+ if (reviewer !== config.reviewerId)
1736
+ throw new Error(`这道交接关口的负责人是 ${reviewer}。`);
1737
+ const edge = scope.edges.find(item => item.handoffId === handoffId);
1738
+ if (!edge)
1739
+ throw new Error('Handoff not found in this case');
1740
+ const handoff = this.ledger.findHandoff(scope.originSessionId, handoffId);
1741
+ if (!handoff)
1742
+ throw new Error('Handoff not found');
1743
+ // Freeze first: a decision that cannot deliver the bytes is not written down.
1744
+ if (decision.decision === 'accept')
1745
+ await this.freezeHandoff(handoff);
1746
+ const decided = decideHandoff(this.ledger, { originSessionId: scope.originSessionId, handoffId,
1747
+ decision: decision.decision, ...(decision.note ? { note: decision.note } : {}),
1748
+ decidedBy: { kind: 'person', id: reviewer, via } }, { allowPerson: true, reviewerId: reviewer });
1749
+ this.noticeDecision(`${scope.title ?? scope.caseId} · 交接`, `${decision.decision === 'accept' ? '已接受' : '已拒绝'}交给 ${handoff.toTargetId}(${via === 'page' ? '网关页面' : '宿主转发'})`, handoff.artifactRevision, handoff.artifactDigest);
1750
+ return { handoff: decided, case: this.workbenchCase(caseId) };
1751
+ });
1752
+ }
1753
+ /** Record that these bytes went out through a channel. Only a caller holding a credential may write this. */
1754
+ async recordWorkbenchReceipt(caseId, input, actor) {
1755
+ return this.workbench(async () => {
1756
+ // Publishing is a gate: a person who is not named for it may not register a receipt.
1757
+ const reviewer = this.gateReviewer('publish');
1758
+ if (actor.kind === 'person' && actor.id !== reviewer)
1759
+ throw new Error(`登记发布回执的负责人是 ${reviewer}。`);
1760
+ const scope = this.workbenchCase(caseId);
1761
+ const parsed = receiptRecordSchema.omit({ originSessionId: true, caseId: true, recordedBy: true }).parse(input);
1762
+ return recordReceipt(this.ledger, { ...parsed, originSessionId: scope.originSessionId, caseId, recordedBy: actor });
1763
+ });
1764
+ }
1765
+ /** Record a measured number. The gateway compares it with the case's thresholds and only proposes. */
1766
+ async recordWorkbenchFact(caseId, input, actor) {
1767
+ return this.workbench(async () => {
1768
+ const scope = this.workbenchCase(caseId);
1769
+ const parsed = factRecordSchema.omit({ originSessionId: true, caseId: true, recordedBy: true }).parse(input);
1770
+ const fact = recordFact(this.ledger, { ...parsed, originSessionId: scope.originSessionId, caseId, recordedBy: actor });
1771
+ const proposals = this.factProposals(scope.originSessionId, caseId);
1772
+ return { fact, proposals };
1773
+ });
1774
+ }
1775
+ /** A threshold that has been reached proposes the next hop. It never decides it and never dispatches. */
1776
+ factProposals(originSessionId, caseId) {
1777
+ const facts = this.ledger.factsFor(originSessionId, caseId);
1778
+ const rules = this.ledger.conventionsFor(originSessionId).filter(rule => rule.caseId === caseId && rule.when === 'fact_reached' && rule.condition);
1779
+ const proposals = [];
1780
+ for (const rule of rules) {
1781
+ const reached = facts.some(fact => fact.metric === rule.condition.metric
1782
+ && factSatisfied(fact.value, rule.condition.operator, rule.condition.value));
1783
+ if (!reached)
1784
+ continue;
1785
+ const proposal = proposeByFact(this.ledger, originSessionId, caseId, rule, `事实达到约定条件:${rule.condition.metric} ${rule.condition.operator} ${rule.condition.value}`);
1786
+ if (proposal)
1787
+ proposals.push(proposal);
1788
+ }
1789
+ return proposals;
1790
+ }
1791
+ /** The frozen bytes of an accepted handoff. The digest is checked again on every read. */
1792
+ async workbenchCaseArtifact(caseId, handoffId, digest) {
1793
+ const scope = this.workbenchCase(caseId);
1794
+ const edge = scope.edges.find(item => item.handoffId === handoffId);
1795
+ const snapshot = edge?.snapshots?.find(item => item.digest === digest);
1796
+ if (!snapshot)
1797
+ throw new WorkbenchArtifactError(404, 'artifact-not-found');
1798
+ const content = await this.snapshots.read(snapshot.storedPath, digest);
1799
+ return { content, name: snapshot.name, ...(snapshot.mediaType ? { mediaType: snapshot.mediaType } : {}) };
1800
+ }
1564
1801
  workbenchAgents() {
1565
1802
  const residents = this.targets.listTargets().filter(target => target.kind === 'resident_agent').map(target => ({
1566
1803
  targetId: target.targetId, name: target.name, ...(target.binding.roleId ? { roleId: target.binding.roleId } : {}),
@@ -1628,7 +1865,13 @@ export class RemoteAgentGateway {
1628
1865
  }
1629
1866
  createWorkbenchAgent(input) { return this.workbench(async () => ({ draft: this.agents.create(input), ...this.workbenchAgents() })); }
1630
1867
  updateWorkbenchAgent(agentId, input) { return this.workbench(async () => ({ draft: this.agents.update(agentId, input), ...this.workbenchAgents() })); }
1631
- publishWorkbenchAgent(agentId, input) { return this.workbench(async () => ({ release: this.agents.publish(agentId, input), ...this.workbenchAgents() })); }
1868
+ async publishWorkbenchAgent(agentId, input) {
1869
+ // Publishing is a gate too: it belongs to the person it names.
1870
+ const reviewer = this.gateReviewer('publish');
1871
+ if (reviewer !== this.config.workbench.reviewerId)
1872
+ throw new Error(`发布放行的负责人是 ${reviewer}。`);
1873
+ return this.workbench(async () => ({ release: this.agents.publish(agentId, input), ...this.workbenchAgents() }));
1874
+ }
1632
1875
  workbenchTask(jobId) { return getWorkbenchTask(this.workbenchProjection(), jobId); }
1633
1876
  /** Read-only transcript from the stored A2A history of the job's attempts; the same scope check as the task detail. */
1634
1877
  workbenchChat(jobId, query = {}) {
@@ -2062,8 +2305,9 @@ function authenticated(req, token) {
2062
2305
  const expected = Buffer.from(`Bearer ${token}`), supplied = Buffer.from(req.headers.authorization ?? '');
2063
2306
  return supplied.length === expected.length && timingSafeEqual(supplied, expected);
2064
2307
  }
2065
- /** Publishing and review decisions are a person's acts, made on the workbench page. */
2066
- const PAGE_ONLY_ROUTES = [/^\/workbench\/agents\/[^/]+\/publish$/, /^\/workbench\/tasks\/[^/]+\/reviews\/[^/]+\/decisions$/, /^\/workbench\/tasks\/[^/]+\/continue$/, /^\/workbench\/tasks\/[^/]+\/acceptance$/];
2308
+ /** Publishing, review decisions and handoff decisions are a person's acts, made on the workbench page. */
2309
+ const PAGE_ONLY_ROUTES = [/^\/workbench\/agents\/[^/]+\/publish$/, /^\/workbench\/tasks\/[^/]+\/reviews\/[^/]+\/decisions$/, /^\/workbench\/tasks\/[^/]+\/continue$/, /^\/workbench\/tasks\/[^/]+\/acceptance$/,
2310
+ /^\/workbench\/cases\/[^/]+\/handoffs\/[^/]+\/decisions$/];
2067
2311
  function relayedFromPage(req, secret) {
2068
2312
  if (!secret)
2069
2313
  return false;
@@ -2161,6 +2405,74 @@ export async function serveA2AGateway(input, options = {}) {
2161
2405
  limit: z.coerce.number().int().min(1).max(200).optional(), offset: z.coerce.number().int().min(0).optional() }).strict().parse(Object.fromEntries(url.searchParams));
2162
2406
  return json(res, 200, gateway.workbenchList(query));
2163
2407
  }
2408
+ if (pathname === '/workbench/cases') {
2409
+ if (req.method === 'GET') {
2410
+ const query = z.object({ limit: z.coerce.number().int().min(1).max(200).optional(), offset: z.coerce.number().int().min(0).optional() }).strict().parse(Object.fromEntries(url.searchParams));
2411
+ return json(res, 200, gateway.workbenchCaseList(query));
2412
+ }
2413
+ if (req.method === 'POST') {
2414
+ if (url.search)
2415
+ return json(res, 400, { error: 'Invalid workbench parameters' });
2416
+ try {
2417
+ return json(res, 200, await gateway.openWorkbenchCase(await body(req)));
2418
+ }
2419
+ catch (error) {
2420
+ if (error instanceof CaseError)
2421
+ return json(res, error.code === 'conflict' ? 409 : error.code === 'not_found' ? 404 : 400, { error: error.code, message: error.message });
2422
+ if (error instanceof z.ZodError)
2423
+ return json(res, 400, { error: 'Invalid workbench parameters' });
2424
+ throw error;
2425
+ }
2426
+ }
2427
+ return json(res, 405, { error: 'Method not allowed' });
2428
+ }
2429
+ const caseRoute = /^\/workbench\/cases\/([^/]+)(.*)$/.exec(pathname);
2430
+ if (caseRoute) {
2431
+ const caseId = decodeURIComponent(caseRoute[1]), rest = caseRoute[2] ?? '';
2432
+ const handoffDecision = /^\/handoffs\/([^/]+)\/decisions$/.exec(rest);
2433
+ const handoffArtifact = /^\/handoffs\/([^/]+)\/artifacts\/([a-f0-9]{64})$/.exec(rest);
2434
+ try {
2435
+ if (rest === '' && req.method === 'GET')
2436
+ return json(res, 200, gateway.workbenchCase(caseId));
2437
+ if (rest === '/conventions' && req.method === 'POST')
2438
+ return json(res, 200, await gateway.registerWorkbenchConvention(caseId, await body(req)));
2439
+ // A page writes as the person on it; a bearer call is the application holding the workbench credential.
2440
+ const writer = page ? { kind: 'person', id: gateway.config.workbench.reviewerId }
2441
+ : { kind: 'application', agent: 'workbench-api' };
2442
+ if (rest === '/receipts' && req.method === 'POST')
2443
+ return json(res, 200, await gateway.recordWorkbenchReceipt(caseId, await body(req), writer));
2444
+ if (rest === '/facts' && req.method === 'POST')
2445
+ return json(res, 200, await gateway.recordWorkbenchFact(caseId, await body(req), writer));
2446
+ if (handoffDecision && req.method === 'POST') {
2447
+ // Only a person on the page decides a handoff; the A2A channel may not write that a person agreed.
2448
+ if (!page && !relayedFromPage(req, gateway.config.workbench.pageRelaySecret))
2449
+ return json(res, 403, { error: 'page_action_required', message: '交接的接受和拒绝只能由人在工作台页面发起。' });
2450
+ return json(res, 200, await gateway.decideWorkbenchHandoff(caseId, decodeURIComponent(handoffDecision[1]), await body(req), page ? 'page' : 'relay'));
2451
+ }
2452
+ if (handoffArtifact && req.method === 'GET') {
2453
+ if (url.search)
2454
+ return json(res, 404, { error: 'No workbench route' });
2455
+ const file = await gateway.workbenchCaseArtifact(caseId, decodeURIComponent(handoffArtifact[1]), handoffArtifact[2]);
2456
+ res.writeHead(200, { 'Content-Type': artifactContentType(file.name, file.mediaType), 'Content-Length': file.content.length,
2457
+ 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, max-age=3600',
2458
+ 'Content-Disposition': `inline; filename*=UTF-8''${encodeURIComponent(file.name)}`,
2459
+ 'Content-Security-Policy': "sandbox; default-src 'none'; img-src 'self' data:; media-src 'self'; style-src 'unsafe-inline'; frame-ancestors 'self'" });
2460
+ return void res.end(file.content);
2461
+ }
2462
+ return json(res, 404, { error: 'No workbench route' });
2463
+ }
2464
+ catch (error) {
2465
+ if (error instanceof WorkbenchArtifactError)
2466
+ return json(res, error.status, { error: error.code });
2467
+ if (error instanceof CaseError)
2468
+ return json(res, error.code === 'conflict' ? 409 : error.code === 'not_found' ? 404 : 400, { error: error.code, message: error.message });
2469
+ if (error instanceof z.ZodError)
2470
+ return json(res, 400, { error: 'Invalid workbench parameters' });
2471
+ if (error instanceof SnapshotError)
2472
+ return json(res, error.code === 'changed' ? 409 : 404, { error: error.code, message: error.message });
2473
+ return json(res, 404, { error: error instanceof Error ? error.message : 'Case not found' });
2474
+ }
2475
+ }
2164
2476
  if (pathname === '/workbench/agents/register-path') {
2165
2477
  if (req.method !== 'POST')
2166
2478
  return json(res, 405, { error: 'Method not allowed' });
@@ -2267,7 +2579,7 @@ export async function serveA2AGateway(input, options = {}) {
2267
2579
  const { note } = workbenchAcceptSchema.parse(await body(req));
2268
2580
  gateway.workbenchTask(jobId);
2269
2581
  try {
2270
- return json(res, 200, gateway.acceptWorkbenchTask(jobId, note));
2582
+ return json(res, 200, gateway.acceptWorkbenchTask(jobId, note, page ? 'page' : 'relay'));
2271
2583
  }
2272
2584
  catch (error) {
2273
2585
  return json(res, 409, { error: 'accept_refused', message: error instanceof Error ? error.message : String(error) });
@@ -13,3 +13,8 @@ export declare function spaceInstructions(input: {
13
13
  artifactSpace?: string;
14
14
  rolePublication?: string;
15
15
  }): string;
16
+ /**
17
+ * The frozen bytes of an accepted handoff. The next task reads these files, not the source task's directory:
18
+ * the source may run another round later, and that must not change what this handoff delivered.
19
+ */
20
+ export declare function snapshotInstructions(snapshot: unknown): string;
@@ -30,3 +30,18 @@ export function spaceInstructions(input) {
30
30
  lines.push(`这件事的 caseId 是 ${input.caseId}。交给另一个角色时调用 handoff_propose(originSessionId=${input.originSessionId},jobId=${input.jobId},attemptId=${input.attemptId}),只提议,不派下一单。`);
31
31
  return `\n\n---\n[空间]\n${lines.join('\n')}`;
32
32
  }
33
+ /**
34
+ * The frozen bytes of an accepted handoff. The next task reads these files, not the source task's directory:
35
+ * the source may run another round later, and that must not change what this handoff delivered.
36
+ */
37
+ export function snapshotInstructions(snapshot) {
38
+ if (!snapshot || typeof snapshot !== 'object')
39
+ return '';
40
+ const value = snapshot;
41
+ const files = value.files ?? [];
42
+ if (!files.length)
43
+ return '';
44
+ const lines = files.map(file => `- ${file.name ?? '产物'} sha256=${file.digest ?? ''} 路径 ${file.path ?? ''}`);
45
+ return `\n\n---\n[交接快照] 这次交接接受的版本是 ${value.revision ?? ''}(digest ${value.digest ?? ''})。以下文件已按 digest 冻结,是这一版的确切字节:\n${lines.join('\n')}\n`
46
+ + '读这些文件,不要去读来源任务的目录;来源任务之后可能再跑一轮,那一轮的字节不属于这次交接。';
47
+ }