@1agents/acp-service 0.8.3 → 0.9.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 (75) hide show
  1. package/README.md +6 -0
  2. package/dist/bin/a2a.js +10 -2
  3. package/dist/bin/acp-service.js +6 -0
  4. package/dist/bin/roles.d.ts +1 -0
  5. package/dist/bin/roles.js +24 -0
  6. package/dist/src/a2a/executor.d.ts +16 -1
  7. package/dist/src/a2a/executor.js +205 -19
  8. package/dist/src/a2a/gateway.d.ts +77 -0
  9. package/dist/src/a2a/gateway.js +349 -27
  10. package/dist/src/a2a/index.d.ts +7 -1
  11. package/dist/src/a2a/index.js +4 -0
  12. package/dist/src/a2a/result-metadata.d.ts +3 -0
  13. package/dist/src/a2a/result-metadata.js +2 -1
  14. package/dist/src/a2a/server.js +2 -1
  15. package/dist/src/a2a/store.js +7 -1
  16. package/dist/src/a2a/types.d.ts +32 -1
  17. package/dist/src/a2a/types.js +11 -1
  18. package/dist/src/acp-connection.js +93 -12
  19. package/dist/src/bridge.js +127 -4
  20. package/dist/src/capacity-lifecycle.d.ts +5 -0
  21. package/dist/src/capacity-lifecycle.js +57 -0
  22. package/dist/src/capacity-queue.d.ts +23 -0
  23. package/dist/src/capacity-queue.js +251 -0
  24. package/dist/src/capacity.d.ts +76 -0
  25. package/dist/src/capacity.js +377 -0
  26. package/dist/src/execution/human-review.d.ts +103 -0
  27. package/dist/src/execution/human-review.js +87 -0
  28. package/dist/src/execution/ledger.d.ts +5 -0
  29. package/dist/src/execution/ledger.js +39 -8
  30. package/dist/src/execution/ppt-delivery.d.ts +36 -3
  31. package/dist/src/execution/ppt-delivery.js +243 -53
  32. package/dist/src/execution/project-discovery.d.ts +56 -0
  33. package/dist/src/execution/project-discovery.js +429 -0
  34. package/dist/src/execution/report-review.d.ts +60 -0
  35. package/dist/src/execution/report-review.js +173 -0
  36. package/dist/src/execution/targets.d.ts +5 -0
  37. package/dist/src/execution/targets.js +1 -0
  38. package/dist/src/execution/workbench.d.ts +131 -0
  39. package/dist/src/execution/workbench.js +265 -0
  40. package/dist/src/index.d.ts +4 -0
  41. package/dist/src/index.js +3 -0
  42. package/dist/src/roles/index.d.ts +1 -0
  43. package/dist/src/roles/index.js +1 -0
  44. package/dist/src/roles/skills.d.ts +71 -0
  45. package/dist/src/roles/skills.js +427 -0
  46. package/package.json +5 -1
  47. package/skills/acp-service/SKILL.md +21 -7
  48. package/skills/acp-service/references/a2a.md +9 -5
  49. package/skills/acp-service/references/async-caller.md +48 -0
  50. package/skills/acp-service/references/roles-and-tasks.md +120 -0
  51. package/skills/acp-service/scripts/a2a-caller.py +242 -0
  52. package/vendor/dsh/README.md +2 -0
  53. package/vendor/dsh/a2a-executor.d.ts +4 -1
  54. package/vendor/dsh/a2a-executor.js +46 -2
  55. package/vendor/dsh/adapter.d.ts +10 -0
  56. package/vendor/dsh/adapter.js +67 -3
  57. package/vendor/dsh/index.js +2 -1
  58. package/vendor/runtime/dist/{cli-DeOpE2Xz.js → cli-DXmYwv3U.js} +4 -4
  59. package/vendor/runtime/dist/{cli-DeOpE2Xz.js.map → cli-DXmYwv3U.js.map} +1 -1
  60. package/vendor/runtime/dist/cli.js +7 -7
  61. package/vendor/runtime/dist/client-VQsqcIOJ.d.ts.map +1 -1
  62. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +1 -0
  63. package/vendor/runtime/dist/{flows-oaBGn31w.js → flows-DJ17ajbw.js} +3 -3
  64. package/vendor/runtime/dist/{flows-oaBGn31w.js.map → flows-DJ17ajbw.js.map} +1 -1
  65. package/vendor/runtime/dist/flows.js +1 -1
  66. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js → invocation-options-PBfCgrdi.js} +3 -3
  67. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js.map → invocation-options-PBfCgrdi.js.map} +1 -1
  68. package/vendor/runtime/dist/{output-CFv3jcOQ.js → output-B3MDn7kv.js} +2 -2
  69. package/vendor/runtime/dist/{output-CFv3jcOQ.js.map → output-B3MDn7kv.js.map} +1 -1
  70. package/vendor/runtime/dist/{queue-owner-runtime-DvMJiGbP.js → queue-owner-runtime-DXCVngwU.js} +15 -8
  71. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +1 -0
  72. package/vendor/runtime/dist/runtime.js +1 -1
  73. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js → session-watch-DURyCw31.js} +2 -2
  74. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js.map → session-watch-DURyCw31.js.map} +1 -1
  75. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +0 -1
@@ -15,9 +15,13 @@ import { artifactLinks, formatNotice } from './notices.js';
15
15
  import { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema } from './preflight.js';
16
16
  import { a2aResultContractSchema } from './result-metadata.js';
17
17
  import { TargetDirectory, TARGET_METHODS } from '../execution/targets.js';
18
+ import { ProjectRoleDiscovery, DISCOVERY_METHODS, projectDiscoveryConfigSchema } from '../execution/project-discovery.js';
18
19
  import { deliveryProgress, deliveryException } from '../execution/delivery-progress.js';
19
20
  import { JobLedger } from '../execution/ledger.js';
20
- import { createPptDeliveryRun, recoverPptDeliveryRun, assertPptDeliveryRecoverable, advancePptDelivery, pptDeliveryInputSchema, pptDeliveryPolicySchema } from '../execution/ppt-delivery.js';
21
+ import { decideHumanReview, HumanReviewError, humanReviewDecisionSchema } from '../execution/human-review.js';
22
+ import { workbenchSnapshot, listWorkbenchTasks, getWorkbenchTask } from '../execution/workbench.js';
23
+ import { createPptDeliveryRun, recoverPptDeliveryRun, assertPptDeliveryRecoverable, advancePptDelivery, pptDeliveryInputSchema, pptDeliveryPolicySchema, pptDeliveryRecoveryInputSchema, scriptDirectory, scriptRevisionName } from '../execution/ppt-delivery.js';
24
+ import { advanceReportReview, createReportReviewRun, reportBindingDigest, reportRevision, reportReviewInputSchema, reportReviewPolicySchema } from '../execution/report-review.js';
21
25
  const string = z.string().trim().min(1).max(512);
22
26
  const endpoint = z.string().url().refine(value => {
23
27
  const url = new URL(value);
@@ -31,9 +35,18 @@ const configSchema = z.object({
31
35
  notificationTargets: z.record(string, z.object({ url: endpoint, token: string }).strict()).default({}),
32
36
  sessionHosts: z.record(string, sessionHostSchema).default({}),
33
37
  automation: automationConfigSchema.optional(),
38
+ projectDiscovery: projectDiscoveryConfigSchema.optional(),
34
39
  pollIntervalMs: z.number().int().min(50).max(60_000).default(3000),
35
40
  pptDelivery: pptDeliveryPolicySchema.optional(),
41
+ reportReview: reportReviewPolicySchema.optional(),
42
+ workbench: z.object({ token: string, reviewerId: string.default('local-owner'), reviewerName: string.optional(), publicBaseUrl: endpoint.optional(),
43
+ allowedOrigins: z.array(string).optional() }).strict().optional(),
36
44
  }).strict().superRefine((config, ctx) => {
45
+ const machineTokens = [...Object.values(config.remotes).map(remote => remote.token), config.callback?.token,
46
+ ...Object.values(config.notificationTargets).map(target => target.token), config.automation?.token];
47
+ if (config.workbench && machineTokens.includes(config.workbench.token)) {
48
+ ctx.addIssue({ code: 'custom', path: ['workbench', 'token'], message: 'Workbench requires a separate credential from agent remotes' });
49
+ }
37
50
  for (const [id, schedule] of Object.entries(config.automation?.schedules ?? {})) {
38
51
  if (!Object.hasOwn(config.remotes, schedule.remote))
39
52
  ctx.addIssue({ code: 'custom', path: ['automation', 'schedules', id, 'remote'], message: 'Unknown automation remote' });
@@ -47,12 +60,13 @@ const prompt = z.string().min(1).max(256 * 1024).refine(value => Boolean(value.t
47
60
  const spawnSchema = z.object({ ...originFields, remote: string, prompt,
48
61
  cwd: string.refine(value => path.posix.isAbsolute(value), 'cwd must be an absolute remote path'),
49
62
  agentPreset: string.optional(), notificationTarget: string.optional(), title: string.optional(),
63
+ roleId: string.optional(), roleLockPath: string.refine(path.isAbsolute).optional(),
50
64
  preflight: a2aPreflightRequirementsSchema.optional(), resultContract: a2aResultContractSchema.optional(),
51
65
  clientRequestId: string.optional(),
52
66
  }).strict();
53
67
  const preflightSchema = a2aPreflightInputSchema.extend({ ...originFields, remote: string }).strict();
54
68
  const taskSchema = z.object(taskFields).strict();
55
- const messageSchema = z.object({ ...taskFields, prompt, clientRequestId: string.optional(), preflight: a2aPreflightRequirementsSchema.optional(), resultContract: a2aResultContractSchema.optional() }).strict();
69
+ const messageSchema = z.object({ ...taskFields, prompt, clientRequestId: string.optional(), roleId: string.optional(), roleLockPath: string.refine(path.isAbsolute).optional(), preflight: a2aPreflightRequirementsSchema.optional(), resultContract: a2aResultContractSchema.optional() }).strict();
56
70
  const inboxSchema = z.object(originFields).strict();
57
71
  const ackSchema = z.object({ ...originFields, noticeId: string }).strict();
58
72
  const executionSubmitSchema = z.object({ ...originFields, targetId: string, input: z.record(z.string(), z.unknown()),
@@ -70,8 +84,9 @@ const executionReviewSchema = executionJobSchema.extend({ attemptId: string, res
70
84
  reviewStatus: z.enum(['pending', 'accepted', 'changes_requested']), note: string.optional() }).strict();
71
85
  const EXECUTION_METHODS = {
72
86
  ...TARGET_METHODS,
73
- execution_submit: { description: '向已登记目标提交任务;派发前持久保存jobId/attemptId和幂等请求。固定角色不接受cwd/preset覆盖。', parameters: z.toJSONSchema(executionSubmitSchema) },
74
- execution_continue: { description: '同任务显式继续或返工,新建执行轮次;旧终态不重新打开,受理未知时禁止新派发。', parameters: z.toJSONSchema(executionContinueSchema) },
87
+ ...DISCOVERY_METHODS,
88
+ execution_submit: { description: '向已登记目标提交任务;派发前持久保存jobId/attemptId和幂等请求。固定角色不接受cwd/preset覆盖。临时报告可用input.reportReview:{fileName},机器文件检查与人工最终通过后父任务才完成。', parameters: z.toJSONSchema(executionSubmitSchema) },
89
+ execution_continue: { description: '同任务显式继续或返工,新建执行轮次;旧终态不重新打开,受理未知/关闭时禁止新派发。PPT仅重试验收用input:{recoveryMode:"review_only",reviewTargetId,sourceSnapshotDirectory?},复用冻结成稿,不派制作。', parameters: z.toJSONSchema(executionContinueSchema) },
75
90
  execution_cancel: { description: '持久关闭任务并取消执行;PPT交付默认级联全部子任务,通用任务可显式cascade=true。未知受理或失联保留未决状态,确认全部停止后才完成关闭。', parameters: z.toJSONSchema(executionCancelSchema) },
76
91
  execution_get: { description: '读取任务、执行轮次、父子关系、交付阶段进度、已有产物及关闭回执;查询进度不唤醒主会话。在途/未决历史单列。', parameters: z.toJSONSchema(executionJobSchema) },
77
92
  execution_list: { description: '按来源范围、目标与状态分页列出统一任务。', parameters: z.toJSONSchema(executionListSchema) },
@@ -126,6 +141,7 @@ export class RemoteAgentGateway {
126
141
  automation;
127
142
  sessions;
128
143
  targets;
144
+ projectDiscovery;
129
145
  ledger;
130
146
  lease;
131
147
  stateFile;
@@ -140,6 +156,7 @@ export class RemoteAgentGateway {
140
156
  advancingDeliveries = new Map();
141
157
  canceling = new Map();
142
158
  reconciling;
159
+ workbenchQueue = Promise.resolve();
143
160
  timer;
144
161
  closed = false;
145
162
  constructor(input) {
@@ -191,10 +208,17 @@ export class RemoteAgentGateway {
191
208
  job.ledgerJobId = migrated.job.jobId;
192
209
  job.attemptId = migrated.attempt.attemptId;
193
210
  }
211
+ // Upgrade cached completed results without contacting the host, dispatching work or creating notices.
212
+ if (job.attemptId && taskState(job) === 'TASK_STATE_COMPLETED') {
213
+ const attempt = this.ledger.getAttempt(job.attemptId);
214
+ if (!attempt.result?.resultRevision || !attempt.result.resultDigest)
215
+ this.ledger.observe(job.attemptId, { ...this.resultObservation(Task.fromJSON(job.task)), checkedAt: job.checkedAt, stale: job.stale ?? false });
216
+ }
194
217
  }
195
218
  this.state.ledger = this.ledger.snapshot();
196
219
  this.state.version = 2;
197
220
  this.state.executionNotices ??= [];
221
+ this.state.reportReviews ??= {};
198
222
  this.state.executionCancellations ??= {};
199
223
  this.state.pptDeliveries ??= { version: 1, runs: {} };
200
224
  for (const run of Object.values(this.state.pptDeliveries.runs)) {
@@ -209,8 +233,13 @@ export class RemoteAgentGateway {
209
233
  this.save();
210
234
  if (this.config.automation)
211
235
  this.automation = new A2AAutomation(this, this.config.automation);
236
+ if (this.config.projectDiscovery) {
237
+ this.projectDiscovery = new ProjectRoleDiscovery({ stateDirectory: path.join(this.config.stateDirectory, 'project-discovery'), config: this.config.projectDiscovery });
238
+ this.projectDiscovery.start();
239
+ }
212
240
  }
213
241
  catch (error) {
242
+ void this.projectDiscovery?.close().catch(() => { });
214
243
  this.lease.close();
215
244
  throw error;
216
245
  }
@@ -233,7 +262,8 @@ export class RemoteAgentGateway {
233
262
  }
234
263
  }
235
264
  targetSnapshot(resolved) {
236
- return { targetId: resolved.target.targetId, configVersion: resolved.configVersion, connectionId: resolved.connection.connectionId,
265
+ return { targetId: resolved.target.targetId, targetKind: resolved.target.kind, targetName: resolved.target.name,
266
+ configVersion: resolved.configVersion, connectionId: resolved.connection.connectionId,
237
267
  connectionVersion: resolved.connectionVersion, provider: resolved.target.binding.driver === 'ppt_delivery' ? 'resident_role' : 'a2a',
238
268
  roleId: resolved.target.binding.roleId, binding: resolved.target.binding, remote: resolved.remote, endpoint: resolved.endpoint, cwd: resolved.cwd,
239
269
  agentPreset: resolved.agentPreset, capabilities: resolved.target.capabilities };
@@ -243,7 +273,9 @@ export class RemoteAgentGateway {
243
273
  const attempt = view.attempts.find(item => item.attemptId === view.currentAttemptId);
244
274
  const raw = this.state.jobs.find(item => item.attemptId === attempt.attemptId);
245
275
  const delivery = this.state.pptDeliveries?.runs[attempt.attemptId];
276
+ const report = this.state.reportReviews?.[attempt.attemptId];
246
277
  return { ...view, ...(delivery ? { deliveryProgress: deliveryProgress(delivery) } : {}),
278
+ ...(report ? { reportProgress: { stage: report.stage, phase: report.phase, reportPath: report.reportPath, fileCheck: report.fileCheck, humanReview: report.humanReviews.at(-1) } } : {}),
247
279
  ...(this.state.executionCancellations?.[attempt.attemptId] ? { cancellation: structuredClone(this.state.executionCancellations[attempt.attemptId]) } : {}), attemptId: attempt.attemptId, submissionStatus: attempt.submissionStatus,
248
280
  backendRunRef: attempt.backendRunRef, phase: attempt.phase, stale: attempt.stale,
249
281
  resultSummary: view.result?.resultSummary, artifactLinks: view.result?.artifactLinks ?? [],
@@ -261,22 +293,38 @@ export class RemoteAgentGateway {
261
293
  if (options.previous && (options.previous.remote !== resolved.remote || (options.previous.remoteEndpoint && options.previous.remoteEndpoint !== resolved.endpoint) || options.previous.cwd !== resolved.cwd || options.previous.agentPreset !== resolved.agentPreset)) {
262
294
  throw new Error('Continue must preserve the original remote, cwd and preset');
263
295
  }
264
- const prepared = this.ledger.prepare({ ...input, requestDigestInput: options.requestDigestInput, jobId: options.jobId, targetSnapshot: this.targetSnapshot(resolved),
296
+ const reportRequest = input.input.reportReview;
297
+ if (reportRequest !== undefined && (options.jobId || resolved.target.kind !== 'agent_host' || !this.config.reportReview || !this.config.workbench))
298
+ throw new Error('Report review requires a new temporary agent_host task and configured report/workbench policy');
299
+ if (reportRequest !== undefined)
300
+ reportReviewInputSchema.parse(reportRequest);
301
+ const prepared = this.ledger.prepare({ ...input, requestDigestInput: options.requestDigestInput, jobId: options.jobId, targetSnapshot: { ...this.targetSnapshot(resolved), ...(reportRequest !== undefined ? { provider: 'report_review', targetKind: 'workflow', driver: 'report_review' } : {}) },
265
302
  operation: options.jobId ? 'continue' : 'submit' });
266
303
  if (prepared.idempotent)
267
304
  return this.ledgerView(input.originSessionId, prepared.job.jobId);
268
305
  const { job, attempt } = prepared;
269
306
  let sent = false;
270
307
  try {
308
+ if (reportRequest !== undefined) {
309
+ const { reportReview: _review, ...authorInput } = resolved.input;
310
+ const run = await createReportReviewRun({ sourceId: this.ledger.sourceId, jobId: job.jobId, attemptId: attempt.attemptId,
311
+ originSessionId: input.originSessionId, title: input.title ?? '项目架构分析报告', targetId: input.targetId, remote: resolved.remote,
312
+ cwd: resolved.cwd, authorInput, reviewerId: this.config.workbench.reviewerId }, this.config.reportReview, reportReviewInputSchema.parse(reportRequest));
313
+ this.state.reportReviews[attempt.attemptId] = run;
314
+ this.ledger.markDispatching(attempt.attemptId);
315
+ this.ledger.accept(attempt.attemptId, { provider: 'report_review', runId: attempt.attemptId }, { executionStatus: 'working', phase: run.phase });
316
+ return this.ledgerView(input.originSessionId, job.jobId);
317
+ }
271
318
  if (resolved.target.binding.driver === 'ppt_delivery') {
272
319
  if (options.jobId && !options.deliveryRecovery)
273
- throw new Error('PPT continuation requires an independently passed recovery checkpoint');
320
+ throw new Error('PPT continuation requires a verified recovery checkpoint');
274
321
  const roleInput = pptDeliveryInputSchema.parse(input.input);
275
322
  if (!this.config.pptDelivery)
276
323
  throw new Error('PPT delivery role policy is not configured');
277
- const run = options.deliveryRecovery ? await recoverPptDeliveryRun(options.deliveryRecovery, attempt.attemptId)
324
+ const run = options.deliveryRecovery ? await recoverPptDeliveryRun(options.deliveryRecovery, attempt.attemptId, options.deliveryRecoveryInput)
278
325
  : await createPptDeliveryRun({ sourceId: this.ledger.sourceId, jobId: job.jobId, attemptId: attempt.attemptId,
279
- originSessionId: input.originSessionId, input: roleInput, policy: this.config.pptDelivery });
326
+ originSessionId: input.originSessionId, input: roleInput, policy: { ...this.config.pptDelivery,
327
+ ...(this.config.workbench ? { humanReviewerId: this.config.workbench.reviewerId } : {}) } });
280
328
  this.state.pptDeliveries.runs[attempt.attemptId] = run;
281
329
  this.ledger.markDispatching(attempt.attemptId);
282
330
  this.ledger.accept(attempt.attemptId, { provider: 'resident_role', runId: attempt.attemptId }, { executionStatus: 'working', phase: 'preparing' });
@@ -287,6 +335,12 @@ export class RemoteAgentGateway {
287
335
  const requirements = resolved.directoryPolicy ? { ...preflight, allowedDirectories: resolved.directoryPolicy.allowedDirectories } : preflight;
288
336
  const declaredContract = fields.resultContract === undefined ? undefined : a2aResultContractSchema.parse(fields.resultContract);
289
337
  const resultContract = declaredContract && options.notificationOrigin ? { ...declaredContract, jobId: job.jobId } : declaredContract;
338
+ const networkRole = resolved.target.binding.skillPolicy === 'network_pinned' ? resolved.target.binding.roleId : undefined;
339
+ if (resolved.target.binding.skillPolicy && !networkRole)
340
+ throw new Error('Network skill policy requires a fixed roleId');
341
+ const explicitRole = resolved.target.kind === 'agent_host' && fields.roleId !== undefined ? string.parse(fields.roleId) : undefined;
342
+ const roleLockPath = fields.roleLockPath === undefined ? undefined
343
+ : z.string().min(1).refine(path.isAbsolute, 'Expected an absolute role lock path').parse(fields.roleLockPath);
290
344
  await this.checkDispatch(resolved.remote, resolved.cwd, requirements, resolved.endpoint);
291
345
  const client = await this.client(resolved.remote, resolved.endpoint);
292
346
  // Target changes/disable during asynchronous preflight must win before sending.
@@ -299,6 +353,7 @@ export class RemoteAgentGateway {
299
353
  const task = await client.sendMessage(SendMessageRequest.fromJSON({ message: { messageId: attempt.attemptId, role: 'ROLE_USER',
300
354
  ...(options.previous ? { contextId: options.previous.contextId } : {}), parts: [{ text: prompt.parse(fields.prompt) }] },
301
355
  metadata: { '1agents': { ...(!options.previous ? { cwd: resolved.cwd, ...(resolved.agentPreset ? { agentPreset: resolved.agentPreset } : {}) } : {}),
356
+ ...(explicitRole ? { roleId: explicitRole } : !options.previous && networkRole ? { roleId: networkRole } : {}), ...(roleLockPath ? { roleLockPath } : {}),
302
357
  ...(requirements ? { preflight: requirements } : {}), ...(resultContract ? { resultContract } : {}) } },
303
358
  configuration: { returnImmediately: true, ...(this.config.callback ? { taskPushNotificationConfig: { url: this.config.callback.url,
304
359
  authentication: { scheme: 'Bearer', credentials: this.config.callback.token } } } : {}) } }), this.auth(resolved.remote));
@@ -383,7 +438,10 @@ export class RemoteAgentGateway {
383
438
  });
384
439
  }
385
440
  executionNotice(run, resultSummary, links) {
386
- const noticeId = createHash('sha256').update(JSON.stringify([run.sourceId, run.jobId, run.attemptId, run.revision, run.executionStatus])).digest('hex');
441
+ const pendingReview = run.executionStatus === 'input_required' && run.phase === 'awaiting_human' && !run.cancellationRequestedAt
442
+ ? run.humanReviews?.find(review => review.status === 'pending' && review.attemptId === run.attemptId && review.revision === scriptRevisionName(run)) : undefined;
443
+ const noticeId = createHash('sha256').update(JSON.stringify([run.sourceId, run.jobId, run.attemptId, run.revision, run.executionStatus,
444
+ ...(pendingReview ? [pendingReview.reviewId] : [])])).digest('hex');
387
445
  if (this.state.executionNotices.some(item => item.noticeId === noticeId))
388
446
  return;
389
447
  if (run.executionStatus !== 'completed') {
@@ -394,13 +452,92 @@ export class RemoteAgentGateway {
394
452
  links = partial.artifacts;
395
453
  }
396
454
  const artifactLinks = links.map(item => ({ url: item.url, mediaType: item.mediaType, sha256: item.sha256, size: item.size }));
397
- const text = `[任务交付通知] ${run.executionStatus === 'completed' ? '任务已完成' : run.executionStatus === 'canceled' ? '任务已取消' : '任务需要处理'}\n${run.input.projectName} PPT\n\n${resultSummary}\n\n` +
455
+ const reviewUrl = this.config.workbench?.publicBaseUrl ? new URL(this.config.workbench.publicBaseUrl) : undefined;
456
+ if (reviewUrl && pendingReview)
457
+ reviewUrl.hash = `acp/tasks/${encodeURIComponent(run.jobId)}?review=${encodeURIComponent(pendingReview.reviewId)}`;
458
+ const reviewEntry = pendingReview ? `\n\n${reviewUrl ? `[打开文字稿审核](${reviewUrl.href})` : '请用户打开 1agents「任务工作台 → 待我确认」。'}\n审核版本:${pendingReview.revision};审核请求:${pendingReview.reviewId}。\n人工决定必须在审核页记录,execution_review 和通知已读均不能替代。` : '';
459
+ const text = `[任务交付通知] ${pendingReview ? '文字稿待人工确认' : run.executionStatus === 'completed' ? '任务已完成' : run.executionStatus === 'canceled' ? '任务已取消' : '任务需要处理'}\n${run.input.projectName} PPT\n\n${resultSummary}\n\n` +
398
460
  artifactLinks.map(item => `[${item.mediaType?.includes('presentation') ? (run.executionStatus === 'completed' ? '最终 PPT' : '已有 PPT(未完成最终验收)') : '预览产物'}](${item.url})`).join('\n') +
461
+ reviewEntry +
399
462
  `\n\n请通过 a2a-gateway 的 execution_get 或 execution_inbox 读取交付回执;业务接受调用 execution_review,通知处理调用 execution_ack,两者分别记录。\n---\n任务定位信息:\n${JSON.stringify({ noticeId, sourceId: run.sourceId, jobId: run.jobId, attemptId: run.attemptId, originSessionId: run.originSessionId })}`;
400
463
  this.state.executionNotices.push({ noticeId, messageId: `execution-notice:${noticeId}`, originSessionId: run.originSessionId,
401
464
  jobId: run.jobId, attemptId: run.attemptId, executionStatus: run.executionStatus, resultSummary, artifactLinks, createdAt: new Date().toISOString(), text });
402
465
  this.save();
403
466
  }
467
+ async advanceReport(run) {
468
+ const existing = this.advancingDeliveries.get(run.attemptId);
469
+ if (existing)
470
+ return existing;
471
+ const operation = advanceReportReview(run, {
472
+ persist: value => { this.state.reportReviews[value.attemptId] = value; this.save(); },
473
+ child: attemptId => this.ledger.getAttempt(attemptId),
474
+ submit: async (value, prompt, previous) => {
475
+ this.assertDispatchOpen(value.originSessionId, value.jobId);
476
+ const prior = previous ? this.state.jobs.find(job => job.attemptId === previous.attemptId) : undefined;
477
+ if (previous && !prior)
478
+ throw new Error('Original report author session is unavailable');
479
+ const result = await this.submitExecution({ originSessionId: value.originSessionId, targetId: value.targetId,
480
+ title: `${value.title}:临时执行`, input: { ...value.authorInput, cwd: value.directory, prompt },
481
+ clientRequestId: `${value.jobId}:${reportRevision(value)}:author`,
482
+ parentJobRef: { sourceId: value.sourceId, jobId: value.jobId }, parentAttemptId: value.attemptId, purpose: 'architecture_report' }, { ...(prior ? { jobId: previous.jobId, previous: prior } : {}), notificationOrigin: `report-review:${value.jobId}` });
483
+ return { jobId: result.jobId, attemptId: result.attemptId };
484
+ },
485
+ update: value => this.updateReport(value),
486
+ });
487
+ this.advancingDeliveries.set(run.attemptId, operation);
488
+ try {
489
+ await operation;
490
+ }
491
+ finally {
492
+ this.advancingDeliveries.delete(run.attemptId);
493
+ }
494
+ }
495
+ updateReport(run) {
496
+ this.ledger.observe(run.attemptId, { executionStatus: run.executionStatus, phase: run.phase, resultSummary: run.resultSummary,
497
+ ...(run.digest ? { resultDigest: run.digest, resultRevision: reportRevision(run), structuredResultRef: {
498
+ reportPath: run.reportPath, snapshotPath: run.snapshotPath, fileCheck: run.fileCheck,
499
+ humanReview: run.humanReviews.at(-1),
500
+ } } : {}) });
501
+ // Only final task outcomes reach the delegator; child completion and human waiting stay in the workbench.
502
+ if (!['completed', 'failed', 'canceled'].includes(run.executionStatus))
503
+ return;
504
+ const noticeId = createHash('sha256').update(JSON.stringify([run.sourceId, run.jobId, run.attemptId, reportRevision(run), run.executionStatus])).digest('hex');
505
+ if (this.state.executionNotices.some(notice => notice.noticeId === noticeId))
506
+ return;
507
+ const text = `[报告任务通知] ${run.executionStatus === 'completed' ? '人工已确认,任务完成' : '任务未完成'}\n${run.title}\n${run.resultSummary ?? ''}\n报告:${run.reportPath}\n请单次读取 execution_get 回执,记录结论后 execution_ack。\n---\n${JSON.stringify({ noticeId, sourceId: run.sourceId, jobId: run.jobId, attemptId: run.attemptId, originSessionId: run.originSessionId })}`;
508
+ this.state.executionNotices.push({ noticeId, messageId: `execution-notice:${noticeId}`, originSessionId: run.originSessionId,
509
+ jobId: run.jobId, attemptId: run.attemptId, executionStatus: run.executionStatus, resultSummary: run.resultSummary ?? '', artifactLinks: [], createdAt: new Date().toISOString(), text });
510
+ this.save();
511
+ }
512
+ async decideReportReview(run, reviewId, input) {
513
+ const review = run.humanReviews.find(item => item.reviewId === reviewId);
514
+ if (!review)
515
+ throw new Error('Review not found in authorized task');
516
+ const decision = humanReviewDecisionSchema.parse(input), replay = review.history.some(item => item.clientRequestId === decision.clientRequestId);
517
+ if (!replay && (this.state.executionCancellations?.[run.attemptId] || ['completed', 'failed', 'canceled'].includes(run.executionStatus)))
518
+ throw new HumanReviewError('already_decided', 'Report task is no longer awaiting a decision');
519
+ let digest = run.digest ?? '';
520
+ if (!replay && decision.action === 'approve') {
521
+ try {
522
+ digest = await reportBindingDigest(run);
523
+ }
524
+ catch {
525
+ throw new HumanReviewError('version_conflict', 'Report bytes changed or are unavailable; this version cannot be approved');
526
+ }
527
+ }
528
+ const config = this.config.workbench;
529
+ const result = decideHumanReview(review, decision, { id: config.reviewerId, displayName: config.reviewerName, source: '1agents-web' }, { attemptId: run.attemptId, revision: reportRevision(run), digest });
530
+ if (!result.idempotent) {
531
+ const next = { ...run, humanReviews: run.humanReviews.map(item => item.reviewId === reviewId ? result.review : item) };
532
+ const reportReviews = { ...this.state.reportReviews, [run.attemptId]: next };
533
+ atomicJson(this.stateFile, { ...this.state, reportReviews });
534
+ this.state.reportReviews = reportReviews;
535
+ }
536
+ const current = this.state.reportReviews[run.attemptId];
537
+ if (current.humanReviews.some(item => item.resume?.status === 'pending'))
538
+ void this.advanceReport(current).catch(() => { });
539
+ return this.workbenchTask(run.jobId);
540
+ }
404
541
  cancellationJobs(origin, jobId, cascade) {
405
542
  const found = new Set();
406
543
  const visit = (id) => {
@@ -421,11 +558,17 @@ export class RemoteAgentGateway {
421
558
  seen.add(jobId);
422
559
  if (Object.values(this.state.executionCancellations ?? {}).some(item => item.jobId === jobId))
423
560
  throw new Error('Job is closing or closed; no further dispatch is allowed');
424
- jobId = this.ledger.get(origin, jobId).parentJobRef?.jobId;
561
+ const job = this.ledger.get(origin, jobId), run = this.state.pptDeliveries?.runs[job.currentAttemptId];
562
+ if (job.executionStatus === 'canceled' || run?.cancellationRequestedAt || run?.executionStatus === 'canceled'
563
+ || run?.humanReviews?.some(review => review.status === 'canceled'))
564
+ throw new Error('Job is closing or closed; no further dispatch is allowed');
565
+ jobId = job.parentJobRef?.jobId;
425
566
  }
426
567
  }
427
568
  async cancelExecution(origin, jobId, cascade) {
428
569
  const job = this.ledger.get(origin, jobId), run = this.state.pptDeliveries.runs[job.currentAttemptId];
570
+ if (this.state.reportReviews?.[job.currentAttemptId] && cascade === false)
571
+ throw new Error('Report cancellation must include its child task');
429
572
  if (run && cascade === false)
430
573
  throw new Error('PPT delivery cancellation must include its child tasks');
431
574
  let record = this.state.executionCancellations[job.currentAttemptId];
@@ -434,7 +577,7 @@ export class RemoteAgentGateway {
434
577
  record.status = 'pending';
435
578
  }
436
579
  if (!record) {
437
- record = { jobId, attemptId: job.currentAttemptId, originSessionId: origin, cascade: cascade ?? Boolean(run),
580
+ record = { jobId, attemptId: job.currentAttemptId, originSessionId: origin, cascade: cascade ?? Boolean(run || this.state.reportReviews?.[job.currentAttemptId]),
438
581
  requestedAt: new Date().toISOString(), status: 'pending', targets: [], diagnostics: [] };
439
582
  this.state.executionCancellations[record.attemptId] = record;
440
583
  }
@@ -445,8 +588,14 @@ export class RemoteAgentGateway {
445
588
  const delivery = this.state.pptDeliveries.runs[attempt.attemptId];
446
589
  if (delivery && !['completed', 'failed', 'canceled'].includes(delivery.executionStatus)) {
447
590
  delivery.cancellationRequestedAt ??= record.requestedAt;
591
+ if (delivery.humanWaitStartedAt) {
592
+ delivery.humanWaitingMs = (delivery.humanWaitingMs ?? 0) + Math.max(0, Date.parse(record.requestedAt) - Date.parse(delivery.humanWaitStartedAt));
593
+ delete delivery.humanWaitStartedAt;
594
+ }
448
595
  delivery.phase = 'canceling_children';
449
596
  delivery.updatedAt = new Date().toISOString();
597
+ delivery.humanReviews = delivery.humanReviews?.map(review => review.status === 'pending'
598
+ ? { ...review, status: 'canceled', updatedAt: delivery.updatedAt } : review);
450
599
  }
451
600
  }
452
601
  }
@@ -478,11 +627,16 @@ export class RemoteAgentGateway {
478
627
  for (const attempt of this.ledger.get(origin, id).attempts)
479
628
  await this.advancingDeliveries.get(attempt.attemptId);
480
629
  }
481
- const ids = this.cancellationJobs(origin, record.jobId, record.cascade), localRuns = [];
630
+ const ids = this.cancellationJobs(origin, record.jobId, record.cascade), localRuns = [], localReports = [];
482
631
  for (const id of ids) {
483
632
  for (const attempt of this.ledger.get(origin, id).attempts) {
484
633
  if (['completed', 'failed', 'canceled', 'rejected'].includes(attempt.executionStatus))
485
634
  continue;
635
+ const report = this.state.reportReviews?.[attempt.attemptId];
636
+ if (report) {
637
+ localReports.push(report);
638
+ continue;
639
+ }
486
640
  const delivery = this.state.pptDeliveries.runs[attempt.attemptId];
487
641
  if (delivery) {
488
642
  if (['completed', 'failed', 'canceled'].includes(delivery.executionStatus)) {
@@ -511,7 +665,7 @@ export class RemoteAgentGateway {
511
665
  }
512
666
  }
513
667
  }
514
- const localIds = new Set(localRuns.map(run => run.attemptId));
668
+ const localIds = new Set([...localRuns, ...localReports].map(run => run.attemptId));
515
669
  const targets = ids.flatMap(id => this.ledger.get(origin, id).attempts).map(attempt => ({ jobId: attempt.jobId, attemptId: attempt.attemptId,
516
670
  executionStatus: attempt.executionStatus, submissionStatus: attempt.submissionStatus }));
517
671
  const unresolved = targets.filter(item => !localIds.has(item.attemptId)
@@ -536,6 +690,15 @@ export class RemoteAgentGateway {
536
690
  this.ledger.observe(run.attemptId, { executionStatus: 'canceled', phase: run.phase, resultSummary: partial.summary, artifactLinks: partial.artifacts });
537
691
  this.executionNotice(run, partial.summary, partial.artifacts);
538
692
  }
693
+ if (!unresolved.length)
694
+ for (const run of localReports) {
695
+ run.executionStatus = 'canceled';
696
+ run.phase = 'user_canceled';
697
+ run.updatedAt = new Date().toISOString();
698
+ run.humanReviews = run.humanReviews.map(review => review.status === 'pending' ? { ...review, status: 'canceled', updatedAt: run.updatedAt } : review);
699
+ this.save();
700
+ this.updateReport(run);
701
+ }
539
702
  record.status = unresolved.length ? 'blocked' : 'completed';
540
703
  record.targets = ids.flatMap(id => this.ledger.get(origin, id).attempts).map(attempt => ({ jobId: attempt.jobId, attemptId: attempt.attemptId,
541
704
  executionStatus: attempt.executionStatus, submissionStatus: attempt.submissionStatus }));
@@ -666,12 +829,20 @@ export class RemoteAgentGateway {
666
829
  }
667
830
  view(job) {
668
831
  const task = Task.fromJSON(job.task);
832
+ const result = job.attemptId ? this.ledger.getAttempt(job.attemptId).result : undefined;
669
833
  return { remote: job.remote, taskId: job.taskId, contextId: job.contextId, originSessionId: job.originSessionId,
670
834
  ...(job.ledgerJobId ? { jobId: job.ledgerJobId, attemptId: job.attemptId, sourceId: this.ledger.sourceId } : {}),
671
835
  cwd: job.cwd, agentPreset: job.agentPreset, sessionId: task.metadata?.['1agents']?.sessionId,
672
836
  preflight: task.metadata?.['1agents']?.preflight, resultMetadata: task.metadata?.['1agents']?.result,
837
+ resultRevision: result?.resultRevision, resultDigest: result?.resultDigest,
673
838
  state: taskState(job), result: resultText(task), artifactLinks: artifactLinks(task), checkedAt: job.checkedAt, stale: Boolean(job.stale) };
674
839
  }
840
+ resultObservation(task) {
841
+ const metadata = task.metadata?.['1agents']?.result;
842
+ return { executionStatus: this.standardState(wire(task).status?.state), providerState: wire(task).status?.state,
843
+ resultSummary: resultText(task), artifactLinks: artifactLinks(task),
844
+ resultArtifacts: metadata?.artifacts ?? [], ...(metadata?.recordPath ? { structuredResultRef: metadata.recordPath } : {}) };
845
+ }
675
846
  accept(task, fields) {
676
847
  const target = task.metadata?.['1agents'];
677
848
  const job = { ...fields, taskId: task.id, contextId: task.contextId, task: wire(task), checkedAt: new Date().toISOString(),
@@ -703,10 +874,7 @@ export class RemoteAgentGateway {
703
874
  });
704
875
  }
705
876
  if (job.attemptId) {
706
- const metadata = task.metadata?.['1agents']?.result;
707
- const observed = { executionStatus: this.standardState(state), providerState: state, stale: false,
708
- resultSummary: resultText(task), artifactLinks: artifactLinks(task),
709
- ...(metadata ? { structuredResultRef: metadata.recordPath } : {}) };
877
+ const observed = { ...this.resultObservation(task), stale: false };
710
878
  if (this.ledger.getAttempt(job.attemptId).submissionStatus !== 'accepted')
711
879
  this.ledger.accept(job.attemptId, { provider: 'a2a', remote: job.remote, endpoint: job.remoteEndpoint, taskId: task.id, contextId: task.contextId, sessionId: task.metadata?.['1agents']?.sessionId }, observed);
712
880
  else
@@ -761,7 +929,7 @@ export class RemoteAgentGateway {
761
929
  break;
762
930
  if (run.cancellationRequestedAt && run.executionStatus !== 'canceled')
763
931
  continue;
764
- if (run.executionStatus === 'working' || run.parentUpdatePending) {
932
+ if (run.executionStatus === 'working' || run.parentUpdatePending || run.humanReviews?.some(review => review.resume?.status === 'pending')) {
765
933
  try {
766
934
  await this.advanceDelivery(run);
767
935
  }
@@ -773,6 +941,21 @@ export class RemoteAgentGateway {
773
941
  if (run.executionStatus !== 'working' && !run.parentUpdatePending)
774
942
  this.executionNotice(run, run.resultSummary ?? this.ledgerView(run.originSessionId, run.jobId).resultSummary ?? run.diagnostics.at(-1) ?? 'PPT delivery requires attention', run.validation?.artifacts ?? []);
775
943
  }
944
+ for (const run of Object.values(this.state.reportReviews ?? {})) {
945
+ if (this.closed)
946
+ break;
947
+ if (this.state.executionCancellations?.[run.attemptId])
948
+ continue;
949
+ if (run.executionStatus === 'working' || run.humanReviews.some(review => review.resume?.status === 'pending') || ['completed', 'failed', 'canceled'].includes(run.executionStatus)) {
950
+ try {
951
+ await this.advanceReport(run);
952
+ }
953
+ catch (error) {
954
+ run.resultSummary = `报告协调器等待处理:${error instanceof Error ? error.message : 'unknown error'}`;
955
+ this.save();
956
+ }
957
+ }
958
+ }
776
959
  // The persisted notice owns its route. Later bindings must not double-deliver old webhooks.
777
960
  if (this.sessions.healthy)
778
961
  for (const record of this.state.notices) {
@@ -846,6 +1029,11 @@ export class RemoteAgentGateway {
846
1029
  }
847
1030
  }
848
1031
  async invokeMethod(method, params) {
1032
+ if (Object.hasOwn(DISCOVERY_METHODS, method)) {
1033
+ if (!this.projectDiscovery)
1034
+ throw new Error('Project discovery is disabled; configure projectDiscovery in the trusted gateway configuration');
1035
+ return this.projectDiscovery.invoke(method, params);
1036
+ }
849
1037
  if (Object.hasOwn(TARGET_METHODS, method)) {
850
1038
  if (method === 'execution_target_probe')
851
1039
  return this.probeTarget(z.object({ targetId: string }).strict().parse(params).targetId);
@@ -863,13 +1051,28 @@ export class RemoteAgentGateway {
863
1051
  const attempt = job.attempts.find(item => item.attemptId === job.currentAttemptId);
864
1052
  if (job.unresolvedAttemptIds.length)
865
1053
  throw new Error('Job has submission_unknown or unresolved attempts; reconcile before continuing');
1054
+ if (this.state.reportReviews?.[attempt.attemptId])
1055
+ throw new Error('Report workflow continues only through its version-bound human review');
866
1056
  const delivery = this.state.pptDeliveries.runs[attempt.attemptId];
867
1057
  if (delivery) {
868
- if (Object.keys(input.input).length)
869
- throw new Error('PPT checkpoint recovery preserves the frozen input; use an empty input object');
1058
+ this.assertDispatchOpen(input.originSessionId, job.jobId);
1059
+ const recovery = Object.keys(input.input).length ? pptDeliveryRecoveryInputSchema.safeParse(input.input) : undefined;
1060
+ if (recovery && !recovery.success)
1061
+ throw new Error('PPT recovery preserves the frozen input; use {} or {recoveryMode:"review_only",reviewTargetId,sourceSnapshotDirectory?}');
1062
+ const recoveryInput = recovery?.data;
870
1063
  if (job.inFlightAttemptIds.length)
871
1064
  throw new Error('PPT parent still has in-flight execution rounds');
872
- assertPptDeliveryRecoverable(delivery);
1065
+ assertPptDeliveryRecoverable(delivery, recoveryInput);
1066
+ if (recoveryInput) {
1067
+ for (const childId of this.cancellationJobs(input.originSessionId, job.jobId, true)) {
1068
+ const child = this.ledger.get(input.originSessionId, childId);
1069
+ if (child.inFlightAttemptIds.length || child.unresolvedAttemptIds.length)
1070
+ throw new Error('PPT recovery has unresolved or running descendants');
1071
+ }
1072
+ const reviewer = this.targets.resolve(recoveryInput.reviewTargetId, { prompt: 'Independent review recovery preflight' });
1073
+ if (reviewer.target.binding.driver === 'ppt_delivery')
1074
+ throw new Error('Independent reviewer must be an A2A execution target');
1075
+ }
873
1076
  const current = this.targets.resolve(job.targetId, attempt.input);
874
1077
  if (!current.target.capabilities?.continue)
875
1078
  throw new Error('PPT target does not enable checkpoint continuation');
@@ -879,7 +1082,7 @@ export class RemoteAgentGateway {
879
1082
  || current.target.binding.driver !== 'ppt_delivery')
880
1083
  throw new Error('PPT checkpoint recovery cannot change its host or role');
881
1084
  return this.submitExecution({ originSessionId: input.originSessionId, targetId: job.targetId, title: job.title,
882
- input: attempt.input, clientRequestId: input.clientRequestId }, { jobId: job.jobId, deliveryRecovery: delivery, requestDigestInput: input.input });
1085
+ input: attempt.input, clientRequestId: input.clientRequestId }, { jobId: job.jobId, deliveryRecovery: delivery, deliveryRecoveryInput: recoveryInput, requestDigestInput: input.input });
883
1086
  }
884
1087
  const previous = this.state.jobs.find(item => item.attemptId === attempt.attemptId);
885
1088
  if (!previous)
@@ -982,6 +1185,7 @@ export class RemoteAgentGateway {
982
1185
  clientRequestId: input.clientRequestId, title: previous.title,
983
1186
  input: { ...(target.kind === 'agent_host' ? { cwd: previous.cwd, ...(previous.agentPreset ? { agentPreset: previous.agentPreset } : {}) } : {}), prompt: input.prompt,
984
1187
  ...(input.preflight ? { preflight: input.preflight } : {}), ...(input.resultContract ? { resultContract: input.resultContract } : {}),
1188
+ ...(input.roleId ? { roleId: input.roleId } : {}), ...(input.roleLockPath ? { roleLockPath: input.roleLockPath } : {}),
985
1189
  ...(previous.notificationTarget ? { notificationTarget: previous.notificationTarget } : {}) } }, { jobId: previous.ledgerJobId, previous });
986
1190
  if ('error' in submitted)
987
1191
  throw new Error(`${submitted.error}; jobId=${submitted.jobId}; attemptId=${submitted.attemptId}`);
@@ -1016,6 +1220,61 @@ export class RemoteAgentGateway {
1016
1220
  throw new Error('Missing A2A event task ID');
1017
1221
  await Promise.allSettled(this.state.jobs.filter(job => job.taskId === taskId).map(job => this.refresh(job)));
1018
1222
  }
1223
+ workbenchProjection() {
1224
+ const config = this.config.workbench;
1225
+ if (!config)
1226
+ throw new Error('Workbench is not configured');
1227
+ const runs = Object.values(this.state.pptDeliveries.runs);
1228
+ const reportRuns = Object.values(this.state.reportReviews ?? {});
1229
+ return workbenchSnapshot({ ledger: this.ledger.snapshot(), runs, reportRuns, reviews: [...runs.flatMap(run => run.humanReviews ?? []), ...reportRuns.flatMap(run => run.humanReviews)],
1230
+ actorId: config.reviewerId, ...(config.allowedOrigins ? { allowedOrigins: config.allowedOrigins } : {}) });
1231
+ }
1232
+ workbenchList(query = {}) { return listWorkbenchTasks(this.workbenchProjection(), query); }
1233
+ workbenchTask(jobId) { return getWorkbenchTask(this.workbenchProjection(), jobId); }
1234
+ /** Only the dedicated HTTP workbench calls this; it is deliberately absent from the agent tool catalogue. */
1235
+ async decideWorkbenchReview(jobId, reviewId, input) {
1236
+ const operation = this.workbenchQueue.then(async () => {
1237
+ if (this.closed)
1238
+ throw new Error('Gateway is closed');
1239
+ const scope = this.workbenchTask(jobId), config = this.config.workbench;
1240
+ await this.advancingDeliveries.get(scope.currentAttemptId);
1241
+ const report = this.state.reportReviews?.[scope.currentAttemptId];
1242
+ if (report)
1243
+ return this.decideReportReview(report, reviewId, input);
1244
+ const run = this.state.pptDeliveries.runs[scope.currentAttemptId];
1245
+ const review = run?.humanReviews?.find(item => item.reviewId === reviewId && item.jobId === jobId);
1246
+ if (!run || !review)
1247
+ throw new Error('Review not found in authorized task');
1248
+ const decision = humanReviewDecisionSchema.parse(input);
1249
+ const replay = review.history.some(item => item.clientRequestId === decision.clientRequestId);
1250
+ if (!replay && (run.cancellationRequestedAt || ['completed', 'failed', 'canceled'].includes(run.executionStatus))) {
1251
+ throw new HumanReviewError('already_decided', 'Task is no longer awaiting a human decision');
1252
+ }
1253
+ let currentDigest = run.scriptDigest ?? '';
1254
+ if (!replay && review.revision === scriptRevisionName(run)) {
1255
+ try {
1256
+ currentDigest = createHash('sha256').update(readFileSync(path.join(scriptDirectory(run), 'slide-script.json'))).digest('hex');
1257
+ }
1258
+ catch {
1259
+ throw new HumanReviewError('version_conflict', 'The reviewed content snapshot is unavailable');
1260
+ }
1261
+ }
1262
+ const result = decideHumanReview(review, decision, { id: config.reviewerId,
1263
+ ...(config.reviewerName ? { displayName: config.reviewerName } : {}), source: '1agents-web' }, { attemptId: scope.currentAttemptId, revision: scriptRevisionName(run), digest: currentDigest });
1264
+ if (!result.idempotent) {
1265
+ const nextRun = { ...run, humanReviews: run.humanReviews.map(item => item.reviewId === reviewId ? result.review : item) };
1266
+ const nextDeliveries = { ...this.state.pptDeliveries, runs: { ...this.state.pptDeliveries.runs, [run.attemptId]: nextRun } };
1267
+ atomicJson(this.stateFile, { ...this.state, pptDeliveries: nextDeliveries });
1268
+ this.state.pptDeliveries = nextDeliveries;
1269
+ }
1270
+ const current = this.state.pptDeliveries.runs[run.attemptId];
1271
+ if (current.humanReviews?.some(item => item.resume?.status === 'pending'))
1272
+ void this.advanceDelivery(current).catch(() => { });
1273
+ return this.workbenchTask(jobId);
1274
+ });
1275
+ this.workbenchQueue = operation.then(() => { }, () => { });
1276
+ return operation;
1277
+ }
1019
1278
  async close() {
1020
1279
  if (this.closed)
1021
1280
  return;
@@ -1023,8 +1282,10 @@ export class RemoteAgentGateway {
1023
1282
  clearInterval(this.timer);
1024
1283
  for (const controller of this.controllers)
1025
1284
  controller.abort();
1285
+ await this.projectDiscovery?.close();
1286
+ await this.workbenchQueue;
1026
1287
  await this.sessions.close();
1027
- await Promise.allSettled([...this.refreshing.values(), ...this.operations, ...(this.reconciling ? [this.reconciling] : [])]);
1288
+ await Promise.allSettled([...this.refreshing.values(), ...this.operations, ...this.advancingDeliveries.values(), ...(this.reconciling ? [this.reconciling] : [])]);
1028
1289
  // Delivery promises release their controllers after abort; HTTP requests
1029
1290
  // may have already succeeded, so any retry keeps the stable notice ID.
1030
1291
  this.lease.close();
@@ -1057,6 +1318,21 @@ async function stop(server) {
1057
1318
  server.closeIdleConnections();
1058
1319
  await new Promise(resolve => server.close(() => resolve()));
1059
1320
  }
1321
+ // The node rejects the whole registration when a method descriptor breaks its
1322
+ // contract, and its HTTP reason hides the offending method. Mirror the rule
1323
+ // here so the operator learns which method to fix.
1324
+ function methodContractViolations(methods) {
1325
+ return Object.entries(methods).flatMap(([name, method]) => {
1326
+ const description = typeof method?.description === 'string' ? method.description.trim() : '';
1327
+ const parameters = method?.parameters;
1328
+ if (!description)
1329
+ return [`method "${name}" requires a non-empty description`];
1330
+ if (!parameters || typeof parameters !== 'object' || parameters.type !== 'object') {
1331
+ return [`method "${name}" parameters must be an object schema with type: "object"`];
1332
+ }
1333
+ return [];
1334
+ });
1335
+ }
1060
1336
  export async function serveA2AGateway(input, options = {}) {
1061
1337
  const gateway = new RemoteAgentGateway(input);
1062
1338
  const server = http.createServer((req, res) => {
@@ -1064,6 +1340,38 @@ export async function serveA2AGateway(input, options = {}) {
1064
1340
  try {
1065
1341
  if (req.method === 'GET' && req.url === '/health')
1066
1342
  return json(res, gateway.sessions.healthy ? 200 : 503, { status: gateway.sessions.healthy ? 'ok' : 'degraded', service: 'a2a-gateway', remotes: Object.keys(gateway.config.remotes), sessionDelivery: gateway.sessions.healthy ? 'ok' : 'storage-unavailable' });
1343
+ const url = new URL(req.url ?? '/', 'http://localhost');
1344
+ if (url.pathname.startsWith('/workbench/')) {
1345
+ if (!gateway.config.workbench)
1346
+ return json(res, 503, { error: 'Workbench is not configured' });
1347
+ if (!authenticated(req, gateway.config.workbench.token))
1348
+ return json(res, 401, { error: 'Unauthorized' });
1349
+ if (req.headers.origin)
1350
+ return json(res, 403, { error: 'Use the authenticated application workbench' });
1351
+ if (req.method === 'GET' && url.pathname === '/workbench/tasks') {
1352
+ const query = z.object({ filter: z.enum(['all', 'pending', 'working', 'failed']).optional(),
1353
+ limit: z.coerce.number().int().min(1).max(200).optional(), offset: z.coerce.number().int().min(0).optional() }).strict().parse(Object.fromEntries(url.searchParams));
1354
+ return json(res, 200, gateway.workbenchList(query));
1355
+ }
1356
+ const route = /^\/workbench\/tasks\/([^/]+)(?:\/reviews\/([^/]+)\/decisions)?$/.exec(url.pathname);
1357
+ if (!route || url.search)
1358
+ return json(res, 404, { error: 'No workbench route' });
1359
+ const jobId = decodeURIComponent(route[1]);
1360
+ try {
1361
+ if (req.method === 'GET' && !route[2])
1362
+ return json(res, 200, gateway.workbenchTask(jobId));
1363
+ if (req.method === 'POST' && route[2])
1364
+ return json(res, 200, await gateway.decideWorkbenchReview(jobId, decodeURIComponent(route[2]), await body(req)));
1365
+ return json(res, 405, { error: 'Method not allowed' });
1366
+ }
1367
+ catch (error) {
1368
+ if (error instanceof HumanReviewError)
1369
+ return json(res, error.code === 'forbidden' ? 403 : 409, { error: error.code, message: error.message });
1370
+ if (error instanceof z.ZodError)
1371
+ return json(res, 400, { error: 'Invalid workbench parameters' });
1372
+ return json(res, 404, { error: error instanceof Error ? error.message : 'Task not found' });
1373
+ }
1374
+ }
1067
1375
  if (req.method !== 'POST' || req.url !== '/invoke')
1068
1376
  return json(res, 404, { error: 'No route' });
1069
1377
  // Local tools are trusted. The separate tailnet receiver below never exposes /invoke.
@@ -1109,16 +1417,30 @@ export async function serveA2AGateway(input, options = {}) {
1109
1417
  }
1110
1418
  const entry = { id: 'a2a-gateway', name: 'DSH 远端智能体', kind: 'agent_runtime',
1111
1419
  capabilities: Object.keys(REMOTE_AGENT_METHODS), execution: 'http', port, reachability: 'localhost', health: '/health', methods: REMOTE_AGENT_METHODS,
1112
- metadata: { local_only_methods: Object.keys(TARGET_METHODS) } };
1420
+ metadata: { local_only_methods: [...Object.keys(TARGET_METHODS), ...Object.keys(DISCOVERY_METHODS)] } };
1421
+ const contractViolations = methodContractViolations(REMOTE_AGENT_METHODS);
1422
+ if (contractViolations.length)
1423
+ console.error(`[a2a-gateway] DreamMate registration contract violated: ${contractViolations.join('; ')}`);
1113
1424
  const registration = options.report === false ? undefined : await reportAndHoldRegistration(entry);
1425
+ if (registration && !registration.ok)
1426
+ console.error(`[a2a-gateway] DreamMate registration failed: ${registration.reason ?? 'unknown reason'}`);
1114
1427
  // Node's directory is ephemeral. Re-report after a Node restart; this never registers new execution targets.
1115
- const reporting = options.report === false ? undefined : setInterval(() => { void reportToAgent(entry).catch(() => { }); }, 15_000);
1428
+ const reporting = options.report === false ? undefined : setInterval(() => {
1429
+ void reportToAgent(entry).then(result => {
1430
+ if (!result.ok)
1431
+ console.error(`[a2a-gateway] DreamMate re-registration failed: ${result.reason ?? 'unknown reason'}`);
1432
+ }).catch(error => {
1433
+ console.error(`[a2a-gateway] DreamMate re-registration error: ${error instanceof Error ? error.message : String(error)}`);
1434
+ });
1435
+ }, 15_000);
1116
1436
  reporting?.unref();
1117
1437
  let closing;
1118
1438
  return { gateway, port, callbackPort, automationPort, registration, close: async () => {
1119
1439
  closing ??= (async () => {
1120
1440
  if (reporting)
1121
1441
  clearInterval(reporting);
1442
+ // Stop the Reader before draining HTTP requests that may be awaiting a scan.
1443
+ await gateway.projectDiscovery?.close();
1122
1444
  // Stop accepting requests and drain their ledger writes while this instance
1123
1445
  // still owns the storage lease. Automation continuations and its admission
1124
1446
  // queue can outlive the gateway operation they awaited.