@1agents/acp-service 0.8.0 → 0.8.2

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 (120) hide show
  1. package/README.md +42 -2
  2. package/dist/bin/a2a.js +3 -2
  3. package/dist/bin/acp-service.js +0 -0
  4. package/dist/src/a2a/executor.d.ts +2 -0
  5. package/dist/src/a2a/executor.js +96 -18
  6. package/dist/src/a2a/gateway.d.ts +407 -14
  7. package/dist/src/a2a/gateway.js +719 -37
  8. package/dist/src/a2a/index.d.ts +9 -1
  9. package/dist/src/a2a/index.js +5 -0
  10. package/dist/src/a2a/lease.d.ts +13 -0
  11. package/dist/src/a2a/lease.js +149 -0
  12. package/dist/src/a2a/notices.d.ts +24 -0
  13. package/dist/src/a2a/notices.js +56 -0
  14. package/dist/src/a2a/preflight.d.ts +52 -0
  15. package/dist/src/a2a/preflight.js +153 -0
  16. package/dist/src/a2a/request-id.d.ts +2 -0
  17. package/dist/src/a2a/request-id.js +6 -0
  18. package/dist/src/a2a/result-metadata.d.ts +59 -0
  19. package/dist/src/a2a/result-metadata.js +156 -0
  20. package/dist/src/a2a/server.js +43 -1
  21. package/dist/src/a2a/session-delivery.d.ts +69 -0
  22. package/dist/src/a2a/session-delivery.js +260 -0
  23. package/dist/src/a2a/session-hosts.d.ts +34 -0
  24. package/dist/src/a2a/session-hosts.js +211 -0
  25. package/dist/src/a2a/store.d.ts +4 -6
  26. package/dist/src/a2a/store.js +17 -115
  27. package/dist/src/a2a/types.d.ts +42 -0
  28. package/dist/src/acp-connection.d.ts +2 -1
  29. package/dist/src/acp-connection.js +52 -9
  30. package/dist/src/bridge.js +38 -39
  31. package/dist/src/execution/delivery-progress.d.ts +108 -0
  32. package/dist/src/execution/delivery-progress.js +57 -0
  33. package/dist/src/execution/ledger.d.ts +235 -0
  34. package/dist/src/execution/ledger.js +396 -0
  35. package/dist/src/execution/ppt-delivery.d.ts +231 -0
  36. package/dist/src/execution/ppt-delivery.js +625 -0
  37. package/dist/src/execution/targets.d.ts +349 -0
  38. package/dist/src/execution/targets.js +428 -0
  39. package/package.json +13 -13
  40. package/skills/acp-service/SKILL.md +9 -2
  41. package/skills/acp-service/references/a2a.md +72 -4
  42. package/vendor/dsh/README.md +12 -2
  43. package/vendor/dsh/a2a-executor.d.ts +9 -2
  44. package/vendor/dsh/a2a-executor.js +84 -16
  45. package/vendor/dsh/a2a.d.ts +2 -1
  46. package/vendor/dsh/a2a.js +10 -5
  47. package/vendor/dsh/adapter.d.ts +3 -1
  48. package/vendor/dsh/adapter.js +144 -16
  49. package/vendor/dsh/client.js +11 -3
  50. package/vendor/dsh/diagnostics.d.ts +42 -0
  51. package/vendor/dsh/diagnostics.js +176 -0
  52. package/vendor/dsh/index.d.ts +1 -0
  53. package/vendor/dsh/index.js +16 -4
  54. package/vendor/runtime/dist/{agent-registry-CMg8LHKY.js → agent-registry-R7A3MSpr.js} +9 -1
  55. package/vendor/runtime/dist/agent-registry-R7A3MSpr.js.map +1 -0
  56. package/vendor/runtime/dist/agent-registry.d.ts +1 -0
  57. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  58. package/vendor/runtime/dist/agent-registry.js +1 -2
  59. package/vendor/runtime/dist/{cli-DUHyAADv.js → cli-DeOpE2Xz.js} +4 -4
  60. package/vendor/runtime/dist/{cli-DUHyAADv.js.map → cli-DeOpE2Xz.js.map} +1 -1
  61. package/vendor/runtime/dist/cli.d.ts +2 -1
  62. package/vendor/runtime/dist/cli.js +10 -10
  63. package/vendor/runtime/dist/cli.js.map +1 -1
  64. package/vendor/runtime/dist/{client-DjkWknf7.d.ts → client-VQsqcIOJ.d.ts} +2 -2
  65. package/vendor/runtime/dist/{client-DjkWknf7.d.ts.map → client-VQsqcIOJ.d.ts.map} +1 -1
  66. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  67. package/vendor/runtime/dist/docs-site/CLI.html +833 -0
  68. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  69. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  70. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  71. package/vendor/runtime/dist/docs-site/config.html +450 -0
  72. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  73. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  74. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  75. package/vendor/runtime/dist/docs-site/flows.html +498 -0
  76. package/vendor/runtime/dist/docs-site/index.html +367 -0
  77. package/vendor/runtime/dist/docs-site/install.html +386 -0
  78. package/vendor/runtime/dist/docs-site/llms.txt +36 -0
  79. package/vendor/runtime/dist/docs-site/output-formats.html +407 -0
  80. package/vendor/runtime/dist/docs-site/permissions.html +422 -0
  81. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  82. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  83. package/vendor/runtime/dist/docs-site/releasing.html +341 -0
  84. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  85. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
  86. package/vendor/runtime/dist/docs-site/safe-errors.html +323 -0
  87. package/vendor/runtime/dist/docs-site/session-control.html +408 -0
  88. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  89. package/vendor/runtime/dist/docs-site/sessions.html +488 -0
  90. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  91. package/vendor/runtime/dist/{flows-CiJSCy4D.js → flows-oaBGn31w.js} +5 -5
  92. package/vendor/runtime/dist/{flows-CiJSCy4D.js.map → flows-oaBGn31w.js.map} +1 -1
  93. package/vendor/runtime/dist/flows.d.ts +2 -2
  94. package/vendor/runtime/dist/flows.d.ts.map +1 -1
  95. package/vendor/runtime/dist/flows.js +1 -2
  96. package/vendor/runtime/dist/{invocation-options-BlIySxIw.js → invocation-options-CUDEE8vW.js} +5 -5
  97. package/vendor/runtime/dist/{invocation-options-BlIySxIw.js.map → invocation-options-CUDEE8vW.js.map} +1 -1
  98. package/vendor/runtime/dist/{ipc-BlljKR2b.js → ipc-BQQpcEdP.js} +356 -20
  99. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +1 -0
  100. package/vendor/runtime/dist/{output-BzXQKArM.js → output-CFv3jcOQ.js} +86 -22
  101. package/vendor/runtime/dist/output-CFv3jcOQ.js.map +1 -0
  102. package/vendor/runtime/dist/{queue-owner-runtime-DSFdsS_y.js → queue-owner-runtime-DvMJiGbP.js} +86 -27
  103. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +1 -0
  104. package/vendor/runtime/dist/runtime.d.ts +28 -15
  105. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  106. package/vendor/runtime/dist/runtime.js +131 -63
  107. package/vendor/runtime/dist/runtime.js.map +1 -1
  108. package/vendor/runtime/dist/{session-options-ORCchZGk.d.ts → session-options-NjpFwf-c.d.ts} +22 -2
  109. package/vendor/runtime/dist/session-options-NjpFwf-c.d.ts.map +1 -0
  110. package/vendor/runtime/dist/{session-watch-BiBTBMz4.js → session-watch-Di-wIdCH.js} +4 -4
  111. package/vendor/runtime/dist/{session-watch-BiBTBMz4.js.map → session-watch-Di-wIdCH.js.map} +1 -1
  112. package/vendor/runtime/dist/{watch-iYiP-lOo.js → watch-CIpoMaWD.js} +2 -2
  113. package/vendor/runtime/dist/{watch-iYiP-lOo.js.map → watch-CIpoMaWD.js.map} +1 -1
  114. package/vendor/runtime/package.json +1 -1
  115. package/vendor/runtime/skills/acpx/SKILL.md +8 -2
  116. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +0 -1
  117. package/vendor/runtime/dist/ipc-BlljKR2b.js.map +0 -1
  118. package/vendor/runtime/dist/output-BzXQKArM.js.map +0 -1
  119. package/vendor/runtime/dist/queue-owner-runtime-DSFdsS_y.js.map +0 -1
  120. package/vendor/runtime/dist/session-options-ORCchZGk.d.ts.map +0 -1
@@ -5,10 +5,19 @@ import http from 'node:http';
5
5
  import path from 'node:path';
6
6
  import { CancelTaskRequest, GetTaskRequest, SendMessageRequest, Task } from '@a2a-js/sdk';
7
7
  import { ClientFactory, DefaultAgentCardResolver, JsonRpcTransportFactory } from '@a2a-js/sdk/client';
8
- import { reportAndHoldRegistration } from '@1agents/dreammate-node/client';
8
+ import { reportAndHoldRegistration, reportToAgent } from '@1agents/dreammate-node/client';
9
9
  import { z } from 'zod';
10
10
  import { FileA2AStore } from './store.js';
11
11
  import { A2AAutomation, automationConfigSchema, createAutomationServer } from './automation.js';
12
+ import { sessionHostSchema } from './session-hosts.js';
13
+ import { SessionDelivery, sessionBindSchema, sessionSendSchema, sessionMessageSchema, sessionResolveSchema } from './session-delivery.js';
14
+ import { artifactLinks, formatNotice } from './notices.js';
15
+ import { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema } from './preflight.js';
16
+ import { a2aResultContractSchema } from './result-metadata.js';
17
+ import { TargetDirectory, TARGET_METHODS } from '../execution/targets.js';
18
+ import { deliveryProgress, deliveryException } from '../execution/delivery-progress.js';
19
+ import { JobLedger } from '../execution/ledger.js';
20
+ import { createPptDeliveryRun, recoverPptDeliveryRun, assertPptDeliveryRecoverable, advancePptDelivery, pptDeliveryInputSchema, pptDeliveryPolicySchema } from '../execution/ppt-delivery.js';
12
21
  const string = z.string().trim().min(1).max(512);
13
22
  const endpoint = z.string().url().refine(value => {
14
23
  const url = new URL(value);
@@ -20,8 +29,10 @@ const configSchema = z.object({
20
29
  remotes: z.record(string, z.object({ url: endpoint, token: string }).strict()),
21
30
  callback: z.object({ host: string, port: z.number().int().min(0).max(65535), url: endpoint, token: string }).strict().optional(),
22
31
  notificationTargets: z.record(string, z.object({ url: endpoint, token: string }).strict()).default({}),
32
+ sessionHosts: z.record(string, sessionHostSchema).default({}),
23
33
  automation: automationConfigSchema.optional(),
24
34
  pollIntervalMs: z.number().int().min(50).max(60_000).default(3000),
35
+ pptDelivery: pptDeliveryPolicySchema.optional(),
25
36
  }).strict().superRefine((config, ctx) => {
26
37
  for (const [id, schedule] of Object.entries(config.automation?.schedules ?? {})) {
27
38
  if (!Object.hasOwn(config.remotes, schedule.remote))
@@ -36,12 +47,42 @@ const prompt = z.string().min(1).max(256 * 1024).refine(value => Boolean(value.t
36
47
  const spawnSchema = z.object({ ...originFields, remote: string, prompt,
37
48
  cwd: string.refine(value => path.posix.isAbsolute(value), 'cwd must be an absolute remote path'),
38
49
  agentPreset: string.optional(), notificationTarget: string.optional(), title: string.optional(),
50
+ preflight: a2aPreflightRequirementsSchema.optional(), resultContract: a2aResultContractSchema.optional(),
51
+ clientRequestId: string.optional(),
39
52
  }).strict();
53
+ const preflightSchema = a2aPreflightInputSchema.extend({ ...originFields, remote: string }).strict();
40
54
  const taskSchema = z.object(taskFields).strict();
41
- const messageSchema = z.object({ ...taskFields, prompt }).strict();
55
+ const messageSchema = z.object({ ...taskFields, prompt, clientRequestId: string.optional(), preflight: a2aPreflightRequirementsSchema.optional(), resultContract: a2aResultContractSchema.optional() }).strict();
42
56
  const inboxSchema = z.object(originFields).strict();
43
57
  const ackSchema = z.object({ ...originFields, noticeId: string }).strict();
58
+ const executionSubmitSchema = z.object({ ...originFields, targetId: string, input: z.record(z.string(), z.unknown()),
59
+ clientRequestId: string.optional(), title: string.optional(), parentJobRef: z.object({ sourceId: string, jobId: string }).strict().optional(),
60
+ parentAttemptId: string.optional(), purpose: string.optional(), resultRevision: string.optional(),
61
+ replacesJobRef: z.object({ sourceId: string, jobId: string }).strict().optional() }).strict();
62
+ const executionJobSchema = z.object({ ...originFields, jobId: string }).strict();
63
+ const executionCancelSchema = executionJobSchema.extend({ cascade: z.boolean().optional() }).strict();
64
+ const executionListSchema = z.object({ ...originFields, targetId: string.optional(), executionStatus: string.optional(),
65
+ limit: z.number().int().min(1).max(200).default(50), offset: z.number().int().min(0).default(0) }).strict();
66
+ const executionContinueSchema = executionJobSchema.extend({ input: z.record(z.string(), z.unknown()), clientRequestId: string.optional() }).strict();
67
+ const executionEventsSchema = z.object({ ...originFields, jobId: string.optional(), afterSequence: z.number().int().nonnegative().optional(),
68
+ limit: z.number().int().min(1).max(500).default(100) }).strict();
69
+ const executionReviewSchema = executionJobSchema.extend({ attemptId: string, resultRevision: string, resultDigest: string,
70
+ reviewStatus: z.enum(['pending', 'accepted', 'changes_requested']), note: string.optional() }).strict();
71
+ const EXECUTION_METHODS = {
72
+ ...TARGET_METHODS,
73
+ execution_submit: { description: '向已登记目标提交任务;派发前持久保存jobId/attemptId和幂等请求。固定角色不接受cwd/preset覆盖。', parameters: z.toJSONSchema(executionSubmitSchema) },
74
+ execution_continue: { description: '同任务显式继续或返工,新建执行轮次;旧终态不重新打开,受理未知时禁止新派发。', parameters: z.toJSONSchema(executionContinueSchema) },
75
+ execution_cancel: { description: '持久关闭任务并取消执行;PPT交付默认级联全部子任务,通用任务可显式cascade=true。未知受理或失联保留未决状态,确认全部停止后才完成关闭。', parameters: z.toJSONSchema(executionCancelSchema) },
76
+ execution_get: { description: '读取任务、执行轮次、父子关系、交付阶段进度、已有产物及关闭回执;查询进度不唤醒主会话。在途/未决历史单列。', parameters: z.toJSONSchema(executionJobSchema) },
77
+ execution_list: { description: '按来源范围、目标与状态分页列出统一任务。', parameters: z.toJSONSchema(executionListSchema) },
78
+ execution_events: { description: '读取本来源范围内持久任务事件,不派单。', parameters: z.toJSONSchema(executionEventsSchema) },
79
+ execution_review: { description: '保存绑定当前执行轮次、结果版本和hash的业务接受/退回;不等于通知ack。', parameters: z.toJSONSchema(executionReviewSchema) },
80
+ execution_inbox: { description: '读取领域交付任务的完成/需决策通知;旧A2A收件箱保持原合同。', parameters: z.toJSONSchema(inboxSchema) },
81
+ execution_ack: { description: '确认已处理领域交付通知,不修改业务验收或执行状态。', parameters: z.toJSONSchema(ackSchema) },
82
+ };
44
83
  export const REMOTE_AGENT_METHODS = {
84
+ ...EXECUTION_METHODS,
85
+ remote_agent_preflight: { description: '在执行宿主检查真实 cwd、任务可写目录和指定运行时依赖,不创建会话、不调用模型。ok=false 时修复检查项后再派单;spawn 的 preflight 还会在受理前重检。', parameters: z.toJSONSchema(preflightSchema) },
45
86
  remote_agent_spawn: { description: '在配置的远端 DSH 工作目录中派发独立任务,立即返回 taskId。prompt 必须包含完整上下文。cwd 是远端绝对路径;每次 spawn 创建新会话。完成事件进入 originSessionId 的持久收件箱。', parameters: z.toJSONSchema(spawnSchema) },
46
87
  remote_agent_get: { description: '查询当前主会话派发的远端任务。离线时返回缓存与 stale 标记,离线不等于任务失败。', parameters: z.toJSONSchema(taskSchema) },
47
88
  remote_agent_cancel: { description: '取消指定远端任务,只取消这项任务自己的执行。', parameters: z.toJSONSchema(taskSchema) },
@@ -49,6 +90,10 @@ export const REMOTE_AGENT_METHODS = {
49
90
  remote_agent_list: { description: '列出当前主会话派发的远端任务。', parameters: z.toJSONSchema(inboxSchema) },
50
91
  remote_agent_inbox: { description: '读取当前主会话未确认的完成或需要输入通知。读取不删除;处理后调用 remote_agent_ack。', parameters: z.toJSONSchema(inboxSchema) },
51
92
  remote_agent_ack: { description: '确认主会话已处理指定通知。noticeId 稳定,重复确认安全。', parameters: z.toJSONSchema(ackSchema) },
93
+ session_bind: { description: '将主会话绑定到配置的 Codex 或 DSH 宿主及其已有会话 ID。同一归属不可静默换目标;在派任务前绑定可自动接收其完成通知。', parameters: z.toJSONSchema(sessionBindSchema) },
94
+ session_send: { description: '向已绑定的主会话可靠投递消息。messageId 是稳定幂等键;立即返回持久投递回执,通过 session_delivery_get 查询。accepted 仅表示宿主已接收入队。', parameters: z.toJSONSchema(sessionSendSchema) },
95
+ session_delivery_get: { description: '查询本主会话的消息投递状态。unknown 必须先核实宿主是否已接收,不能盲目重发。', parameters: z.toJSONSchema(sessionMessageSchema) },
96
+ session_delivery_resolve: { description: '核实 unknown 或处理 rejected 投递并记录依据。accepted=true 表示已确认入队;false 仅用于已证实未入队且已处理阻碍后释放重试。note 必填,不等于任务业务处理确认。', parameters: z.toJSONSchema(sessionResolveSchema) },
52
97
  };
53
98
  const terminal = new Set(['TASK_STATE_COMPLETED', 'TASK_STATE_FAILED', 'TASK_STATE_CANCELED', 'TASK_STATE_REJECTED']);
54
99
  const actionable = new Set([...terminal, 'TASK_STATE_INPUT_REQUIRED', 'TASK_STATE_AUTH_REQUIRED']);
@@ -79,14 +124,21 @@ function atomicJson(file, value) {
79
124
  export class RemoteAgentGateway {
80
125
  config;
81
126
  automation;
127
+ sessions;
128
+ targets;
129
+ ledger;
82
130
  lease;
83
131
  stateFile;
84
132
  state;
85
133
  clients = new Map();
134
+ probeCards = new Map();
135
+ probeFailures = new Map();
86
136
  refreshing = new Map();
87
137
  delivering = new Set();
88
138
  controllers = new Set();
89
139
  operations = new Set();
140
+ advancingDeliveries = new Map();
141
+ canceling = new Map();
90
142
  reconciling;
91
143
  timer;
92
144
  closed = false;
@@ -101,7 +153,7 @@ export class RemoteAgentGateway {
101
153
  this.stateFile = path.join(this.config.stateDirectory, 'gateway.json');
102
154
  try {
103
155
  this.state = JSON.parse(readFileSync(this.stateFile, 'utf8'));
104
- if (this.state.version !== 1 || !Array.isArray(this.state.jobs) || !Array.isArray(this.state.notices))
156
+ if (![1, 2].includes(this.state.version) || !Array.isArray(this.state.jobs) || !Array.isArray(this.state.notices))
105
157
  throw new Error('Invalid gateway state');
106
158
  for (const job of this.state.jobs) {
107
159
  string.parse(job.originSessionId);
@@ -119,6 +171,42 @@ export class RemoteAgentGateway {
119
171
  this.state = { version: 1, jobs: [], notices: [] };
120
172
  }
121
173
  try {
174
+ this.sessions = new SessionDelivery(this.config.stateDirectory, this.config.sessionHosts);
175
+ this.targets = new TargetDirectory(this.config.stateDirectory, this.config.remotes);
176
+ this.targets.ensureLegacyRemotes();
177
+ this.ledger = new JobLedger(this.state.ledger, next => {
178
+ atomicJson(this.stateFile, { ...this.state, version: 2, ledger: next });
179
+ this.state.ledger = next;
180
+ this.state.version = 2;
181
+ });
182
+ this.ledger.recoverAfterRestart();
183
+ this.ledger.migrateLegacy(this.state.jobs.filter(job => !job.ledgerJobId).map(job => ({ ...job,
184
+ executionStatus: this.standardState(taskState(job)), providerState: taskState(job), createdAt: null,
185
+ sessionId: Task.fromJSON(job.task).metadata?.['1agents']?.sessionId,
186
+ resultSummary: resultText(Task.fromJSON(job.task)), artifactLinks: artifactLinks(Task.fromJSON(job.task)),
187
+ targetSnapshot: this.legacySnapshot(job) })));
188
+ for (const job of this.state.jobs) {
189
+ const migrated = this.ledger.findByBackend(job.originSessionId, { remote: job.remote, taskId: job.taskId });
190
+ if (!job.ledgerJobId && migrated) {
191
+ job.ledgerJobId = migrated.job.jobId;
192
+ job.attemptId = migrated.attempt.attemptId;
193
+ }
194
+ }
195
+ this.state.ledger = this.ledger.snapshot();
196
+ this.state.version = 2;
197
+ this.state.executionNotices ??= [];
198
+ this.state.executionCancellations ??= {};
199
+ this.state.pptDeliveries ??= { version: 1, runs: {} };
200
+ for (const run of Object.values(this.state.pptDeliveries.runs)) {
201
+ const attempt = this.ledger.getAttempt(run.attemptId);
202
+ if (attempt.submissionStatus === 'prepared')
203
+ this.ledger.markDispatching(attempt.attemptId);
204
+ if (this.ledger.getAttempt(attempt.attemptId).submissionStatus !== 'accepted') {
205
+ // The durable local run is positive admission evidence, never a remote retry.
206
+ this.ledger.accept(attempt.attemptId, { provider: 'resident_role', runId: attempt.attemptId }, { executionStatus: run.executionStatus, phase: run.phase });
207
+ }
208
+ }
209
+ this.save();
122
210
  if (this.config.automation)
123
211
  this.automation = new A2AAutomation(this, this.config.automation);
124
212
  }
@@ -126,16 +214,386 @@ export class RemoteAgentGateway {
126
214
  this.lease.close();
127
215
  throw error;
128
216
  }
129
- this.timer = setInterval(() => { void this.reconcile(); }, this.config.pollIntervalMs);
217
+ this.timer = setInterval(() => { void this.reconcile().catch(() => { }); }, this.config.pollIntervalMs);
130
218
  this.timer.unref();
131
- void this.reconcile();
219
+ void this.reconcile().catch(() => { });
132
220
  }
133
221
  save() { atomicJson(this.stateFile, this.state); }
134
- client(remote) {
135
- const config = this.config.remotes[remote];
136
- if (!config)
222
+ standardState(value) {
223
+ return { TASK_STATE_SUBMITTED: 'submitted', TASK_STATE_WORKING: 'working', TASK_STATE_INPUT_REQUIRED: 'input_required',
224
+ TASK_STATE_AUTH_REQUIRED: 'auth_required', TASK_STATE_COMPLETED: 'completed', TASK_STATE_FAILED: 'failed',
225
+ TASK_STATE_CANCELED: 'canceled', TASK_STATE_REJECTED: 'rejected' }[value] ?? 'unknown';
226
+ }
227
+ legacySnapshot(job) {
228
+ try {
229
+ return this.targetSnapshot(this.targets.resolve(`legacy:${job.remote}`, { cwd: job.cwd, prompt: 'Legacy task migration', ...(job.agentPreset ? { agentPreset: job.agentPreset } : {}) }));
230
+ }
231
+ catch {
232
+ return { targetId: `legacy:${job.remote}`, provider: 'a2a', remote: job.remote, cwd: job.cwd, agentPreset: job.agentPreset, historicalConfigUnknown: true };
233
+ }
234
+ }
235
+ targetSnapshot(resolved) {
236
+ return { targetId: resolved.target.targetId, configVersion: resolved.configVersion, connectionId: resolved.connection.connectionId,
237
+ connectionVersion: resolved.connectionVersion, provider: resolved.target.binding.driver === 'ppt_delivery' ? 'resident_role' : 'a2a',
238
+ roleId: resolved.target.binding.roleId, binding: resolved.target.binding, remote: resolved.remote, endpoint: resolved.endpoint, cwd: resolved.cwd,
239
+ agentPreset: resolved.agentPreset, capabilities: resolved.target.capabilities };
240
+ }
241
+ ledgerView(originSessionId, jobId) {
242
+ const view = this.ledger.get(originSessionId, jobId);
243
+ const attempt = view.attempts.find(item => item.attemptId === view.currentAttemptId);
244
+ const raw = this.state.jobs.find(item => item.attemptId === attempt.attemptId);
245
+ const delivery = this.state.pptDeliveries?.runs[attempt.attemptId];
246
+ return { ...view, ...(delivery ? { deliveryProgress: deliveryProgress(delivery) } : {}),
247
+ ...(this.state.executionCancellations?.[attempt.attemptId] ? { cancellation: structuredClone(this.state.executionCancellations[attempt.attemptId]) } : {}), attemptId: attempt.attemptId, submissionStatus: attempt.submissionStatus,
248
+ backendRunRef: attempt.backendRunRef, phase: attempt.phase, stale: attempt.stale,
249
+ resultSummary: view.result?.resultSummary, artifactLinks: view.result?.artifactLinks ?? [],
250
+ resultDigest: view.result?.resultDigest, resultRevision: view.result?.resultRevision,
251
+ ...(raw ? { remote: raw.remote, taskId: raw.taskId, contextId: raw.contextId,
252
+ sessionId: Task.fromJSON(raw.task).metadata?.['1agents']?.sessionId,
253
+ resultMetadata: Task.fromJSON(raw.task).metadata?.['1agents']?.result } : {}) };
254
+ }
255
+ async submitExecution(input, options = {}) {
256
+ const replay = this.ledger.replay({ ...input, requestDigestInput: options.requestDigestInput, jobId: options.jobId, operation: options.jobId ? 'continue' : 'submit', targetSnapshot: { targetId: input.targetId } });
257
+ if (replay)
258
+ return { ...this.ledgerView(input.originSessionId, replay.job.jobId), attemptId: replay.attempt.attemptId, requestedAttempt: replay.attempt };
259
+ this.assertDispatchOpen(input.originSessionId, options.jobId ?? input.parentJobRef?.jobId);
260
+ const resolved = this.targets.resolve(input.targetId, input.input);
261
+ 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
+ throw new Error('Continue must preserve the original remote, cwd and preset');
263
+ }
264
+ const prepared = this.ledger.prepare({ ...input, requestDigestInput: options.requestDigestInput, jobId: options.jobId, targetSnapshot: this.targetSnapshot(resolved),
265
+ operation: options.jobId ? 'continue' : 'submit' });
266
+ if (prepared.idempotent)
267
+ return this.ledgerView(input.originSessionId, prepared.job.jobId);
268
+ const { job, attempt } = prepared;
269
+ let sent = false;
270
+ try {
271
+ if (resolved.target.binding.driver === 'ppt_delivery') {
272
+ if (options.jobId && !options.deliveryRecovery)
273
+ throw new Error('PPT continuation requires an independently passed recovery checkpoint');
274
+ const roleInput = pptDeliveryInputSchema.parse(input.input);
275
+ if (!this.config.pptDelivery)
276
+ throw new Error('PPT delivery role policy is not configured');
277
+ const run = options.deliveryRecovery ? await recoverPptDeliveryRun(options.deliveryRecovery, attempt.attemptId)
278
+ : await createPptDeliveryRun({ sourceId: this.ledger.sourceId, jobId: job.jobId, attemptId: attempt.attemptId,
279
+ originSessionId: input.originSessionId, input: roleInput, policy: this.config.pptDelivery });
280
+ this.state.pptDeliveries.runs[attempt.attemptId] = run;
281
+ this.ledger.markDispatching(attempt.attemptId);
282
+ this.ledger.accept(attempt.attemptId, { provider: 'resident_role', runId: attempt.attemptId }, { executionStatus: 'working', phase: 'preparing' });
283
+ return this.ledgerView(input.originSessionId, job.jobId);
284
+ }
285
+ const fields = resolved.input;
286
+ const preflight = fields.preflight === undefined ? undefined : a2aPreflightRequirementsSchema.parse(fields.preflight);
287
+ const requirements = resolved.directoryPolicy ? { ...preflight, allowedDirectories: resolved.directoryPolicy.allowedDirectories } : preflight;
288
+ const declaredContract = fields.resultContract === undefined ? undefined : a2aResultContractSchema.parse(fields.resultContract);
289
+ const resultContract = declaredContract && options.notificationOrigin ? { ...declaredContract, jobId: job.jobId } : declaredContract;
290
+ await this.checkDispatch(resolved.remote, resolved.cwd, requirements, resolved.endpoint);
291
+ const client = await this.client(resolved.remote, resolved.endpoint);
292
+ // Target changes/disable during asynchronous preflight must win before sending.
293
+ const fresh = this.targets.resolve(input.targetId, input.input);
294
+ if (fresh.configVersion !== resolved.configVersion || fresh.connectionVersion !== resolved.connectionVersion)
295
+ throw new Error('Execution target changed before dispatch');
296
+ this.assertDispatchOpen(input.originSessionId, options.jobId ?? input.parentJobRef?.jobId);
297
+ this.ledger.markDispatching(attempt.attemptId);
298
+ sent = true;
299
+ const task = await client.sendMessage(SendMessageRequest.fromJSON({ message: { messageId: attempt.attemptId, role: 'ROLE_USER',
300
+ ...(options.previous ? { contextId: options.previous.contextId } : {}), parts: [{ text: prompt.parse(fields.prompt) }] },
301
+ metadata: { '1agents': { ...(!options.previous ? { cwd: resolved.cwd, ...(resolved.agentPreset ? { agentPreset: resolved.agentPreset } : {}) } : {}),
302
+ ...(requirements ? { preflight: requirements } : {}), ...(resultContract ? { resultContract } : {}) } },
303
+ configuration: { returnImmediately: true, ...(this.config.callback ? { taskPushNotificationConfig: { url: this.config.callback.url,
304
+ authentication: { scheme: 'Bearer', credentials: this.config.callback.token } } } : {}) } }), this.auth(resolved.remote));
305
+ if (!('id' in task))
306
+ throw new Error('Remote did not return an A2A Task');
307
+ this.accept(task, { remote: resolved.remote, remoteEndpoint: resolved.endpoint, originSessionId: options.notificationOrigin ?? input.originSessionId, cwd: resolved.cwd,
308
+ agentPreset: resolved.agentPreset, title: input.title ?? (typeof fields.title === 'string' ? fields.title : undefined),
309
+ notificationTarget: typeof fields.notificationTarget === 'string' ? fields.notificationTarget : undefined,
310
+ ledgerJobId: job.jobId, attemptId: attempt.attemptId });
311
+ return this.ledgerView(input.originSessionId, job.jobId);
312
+ }
313
+ catch (error) {
314
+ const diagnostic = error instanceof Error ? error.message : 'Execution dispatch failed';
315
+ if (sent)
316
+ this.ledger.markUnknown(attempt.attemptId, diagnostic);
317
+ else if (this.ledger.getAttempt(attempt.attemptId).submissionStatus !== 'known_not_submitted')
318
+ this.ledger.knownNotSubmitted(attempt.attemptId, { executionStatus: 'rejected', diagnostic });
319
+ return { ...this.ledgerView(input.originSessionId, job.jobId), error: diagnostic };
320
+ }
321
+ }
322
+ childView(origin, jobId) {
323
+ return this.ledgerView(origin, jobId);
324
+ }
325
+ async advanceDelivery(run) {
326
+ const existing = this.advancingDeliveries.get(run.attemptId);
327
+ if (existing)
328
+ return existing;
329
+ const operation = this.advanceDeliveryOnce(run);
330
+ this.advancingDeliveries.set(run.attemptId, operation);
331
+ try {
332
+ await operation;
333
+ }
334
+ finally {
335
+ this.advancingDeliveries.delete(run.attemptId);
336
+ }
337
+ }
338
+ async advanceDeliveryOnce(run) {
339
+ const rootOrigin = run.originSessionId;
340
+ const submitChild = async (request, previous) => {
341
+ if (request.parentJobRef.sourceId !== run.sourceId || request.parentJobRef.jobId !== run.jobId || request.parentAttemptId !== run.attemptId)
342
+ throw new Error('Delivery child parent scope mismatch');
343
+ if (![run.policy.summaryTargetId, run.policy.makerTargetId, run.policy.reviewTargetId, ...Object.values(run.policy.backupTargets ?? {})].includes(request.targetId))
344
+ throw new Error('Delivery child target is outside frozen policy');
345
+ if (this.ledger.get(rootOrigin, run.jobId).currentAttemptId !== run.attemptId)
346
+ throw new Error('Delivery attempt is no longer current');
347
+ const raw = previous ? this.state.jobs.find(item => item.attemptId === previous.attemptId) : undefined;
348
+ if (previous && !raw)
349
+ throw new Error('Previous delivery child has no A2A backend reference');
350
+ const originalChild = previous ? this.ledger.get(rootOrigin, previous.jobId) : undefined;
351
+ if (originalChild && originalChild.parentJobRef?.jobId !== run.jobId)
352
+ throw new Error('Recovered child belongs to another parent');
353
+ // Reusing an existing child never reparents its Job. The new parent round records reuse in its recovery receipt.
354
+ return await this.submitExecution({ ...request, originSessionId: rootOrigin,
355
+ ...(originalChild ? { parentJobRef: originalChild.parentJobRef, parentAttemptId: originalChild.parentAttemptId } : {}) }, { notificationOrigin: request.originSessionId,
356
+ ...(previous ? { jobId: previous.jobId, previous: raw } : {}) });
357
+ };
358
+ await advancePptDelivery(run, {
359
+ persist: async (saved) => { this.state.pptDeliveries.runs[saved.attemptId] = saved; this.save(); },
360
+ submitChild: request => submitChild(request),
361
+ continueChild: request => submitChild(request, request.child),
362
+ getChild: async (child) => this.childView(rootOrigin, child.jobId),
363
+ ackChild: async (child) => {
364
+ const raw = this.state.jobs.find(item => item.attemptId === child.attemptId);
365
+ if (!raw)
366
+ return;
367
+ for (const record of this.state.notices.filter(item => item.notice.taskId === raw.taskId && item.notice.originSessionId === raw.originSessionId))
368
+ record.acknowledged = true;
369
+ this.save();
370
+ },
371
+ updateParent: async (update) => {
372
+ if (run.cancellationRequestedAt)
373
+ return;
374
+ this.ledger.observe(run.attemptId, { executionStatus: update.executionStatus, phase: update.phase,
375
+ ...(update.resultSummary ? { resultSummary: update.resultSummary } : {}),
376
+ ...(update.artifactLinks ? { artifactLinks: update.artifactLinks } : {}),
377
+ ...(update.deliveryReceipt ? { structuredResultRef: update.deliveryReceipt,
378
+ resultDigest: String(update.deliveryReceipt.resultDigest ?? run.validation?.artifactDigest ?? ''), resultRevision: `revision-${run.revision}` } : {}),
379
+ ...(update.error ? { diagnostic: update.error } : {}) });
380
+ if (update.executionStatus !== 'working')
381
+ this.executionNotice(run, update.resultSummary ?? update.error ?? 'PPT delivery requires attention', update.artifactLinks ?? []);
382
+ },
383
+ });
384
+ }
385
+ executionNotice(run, resultSummary, links) {
386
+ const noticeId = createHash('sha256').update(JSON.stringify([run.sourceId, run.jobId, run.attemptId, run.revision, run.executionStatus])).digest('hex');
387
+ if (this.state.executionNotices.some(item => item.noticeId === noticeId))
388
+ return;
389
+ if (run.executionStatus !== 'completed') {
390
+ const partial = deliveryException(run, resultSummary);
391
+ if (!resultSummary.includes('\n\n已完成:'))
392
+ resultSummary = partial.summary;
393
+ if (!links.length)
394
+ links = partial.artifacts;
395
+ }
396
+ 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` +
398
+ artifactLinks.map(item => `[${item.mediaType?.includes('presentation') ? (run.executionStatus === 'completed' ? '最终 PPT' : '已有 PPT(未完成最终验收)') : '预览产物'}](${item.url})`).join('\n') +
399
+ `\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
+ this.state.executionNotices.push({ noticeId, messageId: `execution-notice:${noticeId}`, originSessionId: run.originSessionId,
401
+ jobId: run.jobId, attemptId: run.attemptId, executionStatus: run.executionStatus, resultSummary, artifactLinks, createdAt: new Date().toISOString(), text });
402
+ this.save();
403
+ }
404
+ cancellationJobs(origin, jobId, cascade) {
405
+ const found = new Set();
406
+ const visit = (id) => {
407
+ if (found.has(id))
408
+ return;
409
+ found.add(id);
410
+ const job = this.ledger.get(origin, id);
411
+ if (cascade)
412
+ for (const child of job.children)
413
+ visit(child.jobId);
414
+ };
415
+ visit(jobId);
416
+ return [...found].reverse();
417
+ }
418
+ assertDispatchOpen(origin, jobId) {
419
+ const seen = new Set();
420
+ while (jobId && !seen.has(jobId)) {
421
+ seen.add(jobId);
422
+ if (Object.values(this.state.executionCancellations ?? {}).some(item => item.jobId === jobId))
423
+ throw new Error('Job is closing or closed; no further dispatch is allowed');
424
+ jobId = this.ledger.get(origin, jobId).parentJobRef?.jobId;
425
+ }
426
+ }
427
+ async cancelExecution(origin, jobId, cascade) {
428
+ const job = this.ledger.get(origin, jobId), run = this.state.pptDeliveries.runs[job.currentAttemptId];
429
+ if (run && cascade === false)
430
+ throw new Error('PPT delivery cancellation must include its child tasks');
431
+ let record = this.state.executionCancellations[job.currentAttemptId];
432
+ if (record && cascade === true && !record.cascade) {
433
+ record.cascade = true;
434
+ record.status = 'pending';
435
+ }
436
+ if (!record) {
437
+ record = { jobId, attemptId: job.currentAttemptId, originSessionId: origin, cascade: cascade ?? Boolean(run),
438
+ requestedAt: new Date().toISOString(), status: 'pending', targets: [], diagnostics: [] };
439
+ this.state.executionCancellations[record.attemptId] = record;
440
+ }
441
+ // Close admission synchronously and durably, before waiting for an in-flight submit or contacting a backend.
442
+ for (const id of this.cancellationJobs(origin, jobId, record.cascade)) {
443
+ const view = this.ledger.get(origin, id);
444
+ for (const attempt of view.attempts) {
445
+ const delivery = this.state.pptDeliveries.runs[attempt.attemptId];
446
+ if (delivery && !['completed', 'failed', 'canceled'].includes(delivery.executionStatus)) {
447
+ delivery.cancellationRequestedAt ??= record.requestedAt;
448
+ delivery.phase = 'canceling_children';
449
+ delivery.updatedAt = new Date().toISOString();
450
+ }
451
+ }
452
+ }
453
+ this.save();
454
+ if (!['completed', 'failed', 'canceled', 'rejected'].includes(job.executionStatus))
455
+ this.ledger.requestCancellation(job.currentAttemptId);
456
+ await this.reconcileCancellation(record);
457
+ return this.ledgerView(origin, jobId);
458
+ }
459
+ async reconcileCancellation(record) {
460
+ const existing = this.canceling.get(record.attemptId);
461
+ if (existing)
462
+ return existing;
463
+ const operation = this.performCancellation(record);
464
+ this.canceling.set(record.attemptId, operation);
465
+ try {
466
+ await operation;
467
+ }
468
+ finally {
469
+ this.canceling.delete(record.attemptId);
470
+ }
471
+ }
472
+ async performCancellation(record) {
473
+ if (record.status === 'completed')
474
+ return;
475
+ const origin = record.originSessionId;
476
+ // A send already on the wire may still return a child. Wait for its owner, then enumerate the real ledger again.
477
+ for (const id of this.cancellationJobs(origin, record.jobId, record.cascade)) {
478
+ for (const attempt of this.ledger.get(origin, id).attempts)
479
+ await this.advancingDeliveries.get(attempt.attemptId);
480
+ }
481
+ const ids = this.cancellationJobs(origin, record.jobId, record.cascade), localRuns = [];
482
+ for (const id of ids) {
483
+ for (const attempt of this.ledger.get(origin, id).attempts) {
484
+ if (['completed', 'failed', 'canceled', 'rejected'].includes(attempt.executionStatus))
485
+ continue;
486
+ const delivery = this.state.pptDeliveries.runs[attempt.attemptId];
487
+ if (delivery) {
488
+ if (['completed', 'failed', 'canceled'].includes(delivery.executionStatus)) {
489
+ const partial = deliveryException(delivery, delivery.resultSummary ?? delivery.diagnostics.at(-1) ?? 'Delivery terminated');
490
+ this.ledger.observe(attempt.attemptId, delivery.parentUpdatePending ?? { executionStatus: delivery.executionStatus,
491
+ phase: delivery.phase, resultSummary: partial.summary, artifactLinks: partial.artifacts });
492
+ delete delivery.parentUpdatePending;
493
+ }
494
+ else
495
+ localRuns.push(delivery);
496
+ continue;
497
+ }
498
+ try {
499
+ const raw = this.state.jobs.find(item => item.attemptId === attempt.attemptId);
500
+ if (raw)
501
+ await this.invokeMethod('remote_agent_cancel', { originSessionId: raw.originSessionId, remote: raw.remote, taskId: raw.taskId });
502
+ else if (attempt.submissionStatus === 'prepared')
503
+ this.ledger.knownNotSubmitted(attempt.attemptId, { executionStatus: 'canceled', diagnostic: 'Closed before dispatch' });
504
+ else
505
+ throw new Error(`Cannot confirm backend admission for ${attempt.attemptId}`);
506
+ }
507
+ catch (error) {
508
+ const diagnostic = error instanceof Error ? error.message : 'Cancellation could not be confirmed';
509
+ if (!record.diagnostics.includes(diagnostic))
510
+ record.diagnostics.push(diagnostic);
511
+ }
512
+ }
513
+ }
514
+ const localIds = new Set(localRuns.map(run => run.attemptId));
515
+ const targets = ids.flatMap(id => this.ledger.get(origin, id).attempts).map(attempt => ({ jobId: attempt.jobId, attemptId: attempt.attemptId,
516
+ executionStatus: attempt.executionStatus, submissionStatus: attempt.submissionStatus }));
517
+ const unresolved = targets.filter(item => !localIds.has(item.attemptId)
518
+ && (!['completed', 'failed', 'canceled', 'rejected'].includes(item.executionStatus) || item.submissionStatus === 'submission_unknown'));
519
+ if (!unresolved.length)
520
+ for (const run of localRuns) {
521
+ run.executionStatus = 'canceled';
522
+ run.phase = 'user_canceled';
523
+ run.updatedAt = new Date().toISOString();
524
+ delete run.pending;
525
+ delete run.parentUpdatePending;
526
+ run.transitions.push({ at: run.updatedAt, stage: run.stage, phase: run.phase, reason: 'User closed task; all delegated executions confirmed terminal' });
527
+ for (const item of run.children) {
528
+ const observed = this.ledger.getAttempt(item.child.attemptId);
529
+ item.child.executionStatus = observed.executionStatus;
530
+ item.child.submissionStatus = observed.submissionStatus;
531
+ }
532
+ if (run.currentChild)
533
+ run.currentChild.executionStatus = this.ledger.getAttempt(run.currentChild.attemptId).executionStatus;
534
+ const partial = deliveryException(run, '任务已按用户要求停止;后续派单已关闭,子任务已确认停止。已有产物保留。');
535
+ run.resultSummary = partial.summary;
536
+ this.ledger.observe(run.attemptId, { executionStatus: 'canceled', phase: run.phase, resultSummary: partial.summary, artifactLinks: partial.artifacts });
537
+ this.executionNotice(run, partial.summary, partial.artifacts);
538
+ }
539
+ record.status = unresolved.length ? 'blocked' : 'completed';
540
+ record.targets = ids.flatMap(id => this.ledger.get(origin, id).attempts).map(attempt => ({ jobId: attempt.jobId, attemptId: attempt.attemptId,
541
+ executionStatus: attempt.executionStatus, submissionStatus: attempt.submissionStatus }));
542
+ record.checkedAt = new Date().toISOString();
543
+ if (record.status === 'completed')
544
+ record.completedAt = record.checkedAt;
545
+ this.save();
546
+ }
547
+ async probeTarget(targetId) {
548
+ const target = this.targets.getTarget(targetId), connection = this.targets.getConnection(target.connectionId);
549
+ if (!target.enabled || !connection.enabled || target.kind === 'workflow')
550
+ return this.targets.invoke('execution_target_probe', { targetId });
551
+ const checkedAt = new Date().toISOString(), baseTtl = connection.probePolicy?.ttlMs ?? 60_000;
552
+ const checkedScope = ['agent_card'];
553
+ let connectionStatus = 'reachable';
554
+ let targetStatus = 'ready';
555
+ let reasonCode;
556
+ try {
557
+ const key = `${connection.connectionId}:${connection.connectionVersion}`;
558
+ let probe = this.probeCards.get(key);
559
+ if (!probe || probe.until <= Date.now()) {
560
+ const result = this.client(connection.remote, connection.endpoint).then(client => client.getAgentCard(this.auth(connection.remote)));
561
+ probe = { until: Date.now() + baseTtl, result };
562
+ this.probeCards.set(key, probe);
563
+ }
564
+ await probe.result;
565
+ if (target.binding.cwd) {
566
+ const report = await this.preflight(connection.remote, { cwd: target.binding.cwd,
567
+ ...(target.binding.allowedDirectories ? { allowedDirectories: target.binding.allowedDirectories } : {}) }, connection.endpoint);
568
+ checkedScope.push('cwd_realpath_permissions', ...(target.binding.allowedDirectories ? ['directory_scope'] : []));
569
+ if (!report.ok) {
570
+ targetStatus = 'misconfigured';
571
+ reasonCode = 'remote_preflight_failed';
572
+ }
573
+ }
574
+ }
575
+ catch {
576
+ connectionStatus = 'unreachable';
577
+ targetStatus = 'unavailable';
578
+ reasonCode = 'read_only_probe_failed';
579
+ }
580
+ const failureKey = `${targetId}:${target.configVersion}:${connection.connectionVersion}`;
581
+ const failureCount = targetStatus === 'ready' ? 0 : (this.probeFailures.get(failureKey) ?? 0) + 1;
582
+ this.probeFailures.set(failureKey, failureCount);
583
+ const ttl = targetStatus === 'ready' ? baseTtl : Math.min(600_000, baseTtl * 2 ** Math.min(failureCount, 6));
584
+ const health = { targetId, configVersion: target.configVersion, connectionId: target.connectionId,
585
+ connectionVersion: connection.connectionVersion, checkedAt, validUntil: new Date(Date.now() + ttl).toISOString(), checkedScope,
586
+ connectionStatus, targetStatus, failureCount, ...(reasonCode ? { reasonCode } : {}) };
587
+ this.targets.recordProbe(health);
588
+ return { ...this.targets.invoke('execution_target_probe', { targetId }), performed: true, health,
589
+ unverified: ['arbitrary_task_success', 'model_quota', ...(target.binding.agentPreset ? ['preset_existence'] : [])] };
590
+ }
591
+ client(remote, pinnedEndpoint) {
592
+ const configured = this.config.remotes[remote];
593
+ if (!configured)
137
594
  throw new Error(`Unknown remote: ${remote}`);
138
- let pending = this.clients.get(remote);
595
+ const config = { ...configured, url: pinnedEndpoint ?? configured.url }, key = `${remote}:${config.url}`;
596
+ let pending = this.clients.get(key);
139
597
  if (!pending) {
140
598
  const fetchImpl = async (input, init) => {
141
599
  if (this.closed)
@@ -155,13 +613,51 @@ export class RemoteAgentGateway {
155
613
  };
156
614
  pending = new ClientFactory({ transports: [new JsonRpcTransportFactory({ fetchImpl })],
157
615
  cardResolver: new DefaultAgentCardResolver({ fetchImpl }), clientConfig: { polling: true } }).createFromUrl(config.url);
158
- this.clients.set(remote, pending);
159
- void pending.catch(() => { if (this.clients.get(remote) === pending)
160
- this.clients.delete(remote); });
616
+ this.clients.set(key, pending);
617
+ void pending.catch(() => { if (this.clients.get(key) === pending)
618
+ this.clients.delete(key); });
161
619
  }
162
620
  return pending;
163
621
  }
164
622
  auth(remote) { return { serviceParameters: { Authorization: `Bearer ${this.config.remotes[remote].token}` } }; }
623
+ async preflight(remote, input, pinnedEndpoint) {
624
+ const configured = this.config.remotes[remote];
625
+ const config = configured ? { ...configured, url: pinnedEndpoint ?? configured.url } : undefined;
626
+ if (!config)
627
+ throw new Error(`Unknown remote: ${remote}`);
628
+ const client = await this.client(remote, config.url), card = await client.getAgentCard(this.auth(remote));
629
+ const endpoint = card.supportedInterfaces.find(value => value.protocolBinding === 'JSONRPC')?.url;
630
+ if (!endpoint)
631
+ throw new Error('Remote does not advertise a JSONRPC endpoint');
632
+ const url = new URL(endpoint);
633
+ if (url.origin !== new URL(config.url).origin || url.username || url.password)
634
+ throw new Error('Preflight endpoint must use the configured remote origin');
635
+ url.pathname = `${url.pathname.replace(/\/$/, '')}/preflight`;
636
+ url.search = '';
637
+ url.hash = '';
638
+ const controller = new AbortController();
639
+ this.controllers.add(controller);
640
+ try {
641
+ const response = await fetch(url, { method: 'POST', redirect: 'error',
642
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.token}` },
643
+ body: JSON.stringify(input), signal: AbortSignal.any([controller.signal, AbortSignal.timeout(20_000)]) });
644
+ if (!response.ok) {
645
+ await response.body?.cancel();
646
+ throw new Error(`Remote preflight failed (HTTP ${response.status})`);
647
+ }
648
+ return a2aPreflightReportSchema.parse(await response.json());
649
+ }
650
+ finally {
651
+ this.controllers.delete(controller);
652
+ }
653
+ }
654
+ async checkDispatch(remote, cwd, requirements, pinnedEndpoint) {
655
+ if (!requirements)
656
+ return;
657
+ const report = await this.preflight(remote, { cwd, ...requirements }, pinnedEndpoint);
658
+ if (!report.ok)
659
+ throw new Error(`Remote preflight rejected dispatch: ${report.checks.filter(check => !check.ok).map(check => check.id).join(', ')}`);
660
+ }
165
661
  job(params) {
166
662
  const job = this.state.jobs.find(value => value.remote === params.remote && value.taskId === params.taskId && value.originSessionId === params.originSessionId);
167
663
  if (!job)
@@ -171,8 +667,10 @@ export class RemoteAgentGateway {
171
667
  view(job) {
172
668
  const task = Task.fromJSON(job.task);
173
669
  return { remote: job.remote, taskId: job.taskId, contextId: job.contextId, originSessionId: job.originSessionId,
670
+ ...(job.ledgerJobId ? { jobId: job.ledgerJobId, attemptId: job.attemptId, sourceId: this.ledger.sourceId } : {}),
174
671
  cwd: job.cwd, agentPreset: job.agentPreset, sessionId: task.metadata?.['1agents']?.sessionId,
175
- state: taskState(job), result: resultText(task), checkedAt: job.checkedAt, stale: Boolean(job.stale) };
672
+ preflight: task.metadata?.['1agents']?.preflight, resultMetadata: task.metadata?.['1agents']?.result,
673
+ state: taskState(job), result: resultText(task), artifactLinks: artifactLinks(task), checkedAt: job.checkedAt, stale: Boolean(job.stale) };
176
674
  }
177
675
  accept(task, fields) {
178
676
  const target = task.metadata?.['1agents'];
@@ -197,11 +695,25 @@ export class RemoteAgentGateway {
197
695
  if (actionable.has(state)) {
198
696
  const noticeId = createHash('sha256').update(JSON.stringify([job.remote, job.taskId, state, task.status?.timestamp])).digest('hex');
199
697
  if (!this.state.notices.some(value => value.notice.noticeId === noticeId))
200
- this.state.notices.push({ target: job.notificationTarget,
698
+ this.state.notices.push({
699
+ ...(this.sessions.hasBinding(job.originSessionId) ? { sessionDeliveryId: `a2a-notice:${noticeId}` } : { target: job.notificationTarget }),
201
700
  notice: { noticeId, originSessionId: job.originSessionId, remote: job.remote, taskId: job.taskId, contextId: job.contextId,
202
- cwd: job.cwd, agentPreset: job.agentPreset, title: job.title, state, result: resultText(task), createdAt: new Date().toISOString() } });
701
+ cwd: job.cwd, agentPreset: job.agentPreset, title: job.title, state, result: resultText(task),
702
+ ...(artifactLinks(task).length ? { artifactLinks: artifactLinks(task) } : {}), createdAt: new Date().toISOString() }
703
+ });
203
704
  }
204
- this.save();
705
+ 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 } : {}) };
710
+ if (this.ledger.getAttempt(job.attemptId).submissionStatus !== 'accepted')
711
+ 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
+ else
713
+ this.ledger.observe(job.attemptId, observed);
714
+ }
715
+ else
716
+ this.save();
205
717
  }
206
718
  async refresh(job) {
207
719
  const key = `${job.remote}:${job.taskId}`;
@@ -210,12 +722,15 @@ export class RemoteAgentGateway {
210
722
  return previous;
211
723
  const pending = (async () => {
212
724
  try {
213
- const client = await this.client(job.remote);
725
+ const client = await this.client(job.remote, job.remoteEndpoint);
214
726
  this.update(job, await client.getTask(GetTaskRequest.fromJSON({ id: job.taskId }), this.auth(job.remote)));
215
727
  }
216
728
  catch {
217
729
  job.stale = true;
218
- this.save();
730
+ if (job.attemptId)
731
+ this.ledger.observe(job.attemptId, { stale: true });
732
+ else
733
+ this.save();
219
734
  }
220
735
  })();
221
736
  this.refreshing.set(key, pending);
@@ -232,9 +747,58 @@ export class RemoteAgentGateway {
232
747
  if (this.reconciling)
233
748
  return this.reconciling;
234
749
  const pending = (async () => {
750
+ await Promise.allSettled(this.targets.listTargets().filter(target => target.enabled && target.kind !== 'workflow' && !this.targets.getHealth(target.targetId))
751
+ .map(target => this.probeTarget(target.targetId)));
235
752
  await Promise.allSettled(this.state.jobs.filter(job => !terminal.has(taskState(job))).map(job => this.refresh(job)));
236
753
  if (this.closed)
237
754
  return;
755
+ for (const cancellation of Object.values(this.state.executionCancellations ?? {})) {
756
+ if (cancellation.status !== 'completed')
757
+ await this.reconcileCancellation(cancellation);
758
+ }
759
+ for (const run of Object.values(this.state.pptDeliveries.runs)) {
760
+ if (this.closed)
761
+ break;
762
+ if (run.cancellationRequestedAt && run.executionStatus !== 'canceled')
763
+ continue;
764
+ if (run.executionStatus === 'working' || run.parentUpdatePending) {
765
+ try {
766
+ await this.advanceDelivery(run);
767
+ }
768
+ catch (error) {
769
+ run.diagnostics.push(error instanceof Error ? error.message : 'Delivery reconciliation failed');
770
+ this.save();
771
+ }
772
+ }
773
+ if (run.executionStatus !== 'working' && !run.parentUpdatePending)
774
+ this.executionNotice(run, run.resultSummary ?? this.ledgerView(run.originSessionId, run.jobId).resultSummary ?? run.diagnostics.at(-1) ?? 'PPT delivery requires attention', run.validation?.artifacts ?? []);
775
+ }
776
+ // The persisted notice owns its route. Later bindings must not double-deliver old webhooks.
777
+ if (this.sessions.healthy)
778
+ for (const record of this.state.notices) {
779
+ if (!record.sessionDeliveryId)
780
+ continue;
781
+ if (record.acknowledged) {
782
+ this.sessions.acknowledgeNotice(record.notice.originSessionId, record.notice.noticeId);
783
+ continue;
784
+ }
785
+ const notice = record.notice;
786
+ // Keep already-persisted queue text immutable across notification format upgrades.
787
+ if (this.sessions.hasDelivery(notice.originSessionId, record.sessionDeliveryId))
788
+ continue;
789
+ this.sessions.enqueue({ originSessionId: notice.originSessionId, messageId: record.sessionDeliveryId,
790
+ text: formatNotice(notice) });
791
+ }
792
+ if (this.sessions.healthy)
793
+ await this.sessions.reconcile();
794
+ if (this.sessions.healthy) {
795
+ for (const notice of this.state.executionNotices ?? []) {
796
+ if (!notice.processedAt && this.sessions.hasBinding(notice.originSessionId) && !this.sessions.hasDelivery(notice.originSessionId, notice.messageId)) {
797
+ this.sessions.enqueue({ originSessionId: notice.originSessionId, messageId: notice.messageId, text: notice.text });
798
+ }
799
+ }
800
+ await this.sessions.reconcile();
801
+ }
238
802
  await Promise.allSettled(this.state.notices.filter(record => record.target && !record.delivered && !record.acknowledged).map(record => this.deliver(record)));
239
803
  await this.automation?.reconcileAcknowledgements();
240
804
  })();
@@ -282,23 +846,126 @@ export class RemoteAgentGateway {
282
846
  }
283
847
  }
284
848
  async invokeMethod(method, params) {
849
+ if (Object.hasOwn(TARGET_METHODS, method)) {
850
+ if (method === 'execution_target_probe')
851
+ return this.probeTarget(z.object({ targetId: string }).strict().parse(params).targetId);
852
+ return this.targets.invoke(method, params);
853
+ }
854
+ if (method === 'execution_submit')
855
+ return this.submitExecution(executionSubmitSchema.parse(params));
856
+ if (method === 'execution_continue') {
857
+ const input = executionContinueSchema.parse(params), job = this.ledger.get(input.originSessionId, input.jobId);
858
+ const replay = this.ledger.replay({ originSessionId: input.originSessionId, jobId: job.jobId,
859
+ operation: 'continue', title: job.title, targetSnapshot: { targetId: job.targetId },
860
+ input: input.input, requestDigestInput: input.input, clientRequestId: input.clientRequestId });
861
+ if (replay)
862
+ return { ...this.ledgerView(input.originSessionId, job.jobId), attemptId: replay.attempt.attemptId, requestedAttempt: replay.attempt };
863
+ const attempt = job.attempts.find(item => item.attemptId === job.currentAttemptId);
864
+ if (job.unresolvedAttemptIds.length)
865
+ throw new Error('Job has submission_unknown or unresolved attempts; reconcile before continuing');
866
+ const delivery = this.state.pptDeliveries.runs[attempt.attemptId];
867
+ 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');
870
+ if (job.inFlightAttemptIds.length)
871
+ throw new Error('PPT parent still has in-flight execution rounds');
872
+ assertPptDeliveryRecoverable(delivery);
873
+ const current = this.targets.resolve(job.targetId, attempt.input);
874
+ if (!current.target.capabilities?.continue)
875
+ throw new Error('PPT target does not enable checkpoint continuation');
876
+ const snapshot = attempt.targetSnapshot;
877
+ if (current.remote !== snapshot.remote || current.endpoint !== snapshot.endpoint || current.cwd !== snapshot.cwd
878
+ || current.agentPreset !== snapshot.agentPreset || current.target.binding.roleId !== snapshot.roleId
879
+ || current.target.binding.driver !== 'ppt_delivery')
880
+ throw new Error('PPT checkpoint recovery cannot change its host or role');
881
+ 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 });
883
+ }
884
+ const previous = this.state.jobs.find(item => item.attemptId === attempt.attemptId);
885
+ if (!previous)
886
+ throw new Error('Continue is unsupported for this provider');
887
+ return this.submitExecution({ originSessionId: input.originSessionId, targetId: job.targetId, title: job.title,
888
+ input: { ...attempt.input, ...input.input }, clientRequestId: input.clientRequestId }, { jobId: job.jobId, previous, requestDigestInput: input.input });
889
+ }
890
+ if (method === 'execution_get') {
891
+ const input = executionJobSchema.parse(params), job = this.ledger.get(input.originSessionId, input.jobId);
892
+ const raw = this.state.jobs.find(item => item.attemptId === job.currentAttemptId);
893
+ if (raw)
894
+ await this.refresh(raw);
895
+ return this.ledgerView(input.originSessionId, input.jobId);
896
+ }
897
+ if (method === 'execution_cancel') {
898
+ const input = executionCancelSchema.parse(params);
899
+ return this.cancelExecution(input.originSessionId, input.jobId, input.cascade);
900
+ }
901
+ if (method === 'execution_list') {
902
+ const input = executionListSchema.parse(params);
903
+ const jobs = this.ledger.list(input.originSessionId).filter(job => (!input.targetId || job.targetId === input.targetId) && (!input.executionStatus || job.executionStatus === input.executionStatus));
904
+ return { jobs: jobs.slice(input.offset, input.offset + input.limit), total: jobs.length, offset: input.offset, limit: input.limit };
905
+ }
906
+ if (method === 'execution_events') {
907
+ const input = executionEventsSchema.parse(params);
908
+ const events = this.ledger.events(input.originSessionId, input.jobId, input.afterSequence), page = events.slice(0, input.limit);
909
+ return { sourceId: this.ledger.sourceId, events: page, hasMore: events.length > page.length, nextSequence: page.at(-1)?.sequence };
910
+ }
911
+ if (method === 'execution_review') {
912
+ const { originSessionId, jobId, ...review } = executionReviewSchema.parse(params);
913
+ return this.ledger.acceptance(originSessionId, jobId, review);
914
+ }
915
+ if (method === 'execution_inbox') {
916
+ const { originSessionId } = inboxSchema.parse(params);
917
+ return { notices: this.state.executionNotices.filter(item => item.originSessionId === originSessionId && !item.processedAt)
918
+ .map(({ text: _text, ...notice }) => notice) };
919
+ }
920
+ if (method === 'execution_ack') {
921
+ const input = ackSchema.parse(params), notice = this.state.executionNotices.find(item => item.originSessionId === input.originSessionId && item.noticeId === input.noticeId);
922
+ if (!notice)
923
+ throw new Error('Execution notice not found in origin scope');
924
+ notice.processedAt ??= new Date().toISOString();
925
+ this.save();
926
+ this.sessions.acknowledgeMessage(input.originSessionId, notice.messageId);
927
+ return { acknowledged: true, noticeId: notice.noticeId, processedAt: notice.processedAt };
928
+ }
929
+ if (method === 'remote_agent_preflight') {
930
+ const { remote, originSessionId: _origin, ...input } = preflightSchema.parse(params);
931
+ return this.preflight(remote, input);
932
+ }
933
+ if (method === 'session_bind')
934
+ return this.sessions.bind(sessionBindSchema.parse(params));
935
+ if (method === 'session_send') {
936
+ const input = sessionSendSchema.parse(params);
937
+ if (input.messageId.startsWith('a2a-notice:') || input.messageId.startsWith('execution-notice:'))
938
+ throw new Error('The a2a-notice: and execution-notice: message ID namespaces are reserved for task notifications');
939
+ const result = this.sessions.enqueue(input);
940
+ void this.reconcile().catch(() => { });
941
+ return result;
942
+ }
943
+ if (method === 'session_delivery_get')
944
+ return this.sessions.get(sessionMessageSchema.parse(params));
945
+ if (method === 'session_delivery_resolve') {
946
+ const result = this.sessions.resolve(sessionResolveSchema.parse(params));
947
+ void this.reconcile().catch(() => { });
948
+ return result;
949
+ }
285
950
  if (method === 'remote_agent_spawn') {
286
951
  const input = spawnSchema.parse(params);
287
952
  if (input.notificationTarget && !this.config.notificationTargets[input.notificationTarget])
288
953
  throw new Error('Unknown notificationTarget');
289
- const client = await this.client(input.remote);
290
- const task = await client.sendMessage(SendMessageRequest.fromJSON({ message: { messageId: randomUUID(), role: 'ROLE_USER', parts: [{ text: input.prompt }] },
291
- metadata: { '1agents': { cwd: input.cwd, ...(input.agentPreset ? { agentPreset: input.agentPreset } : {}) } },
292
- configuration: { returnImmediately: true, ...(this.config.callback ? { taskPushNotificationConfig: { url: this.config.callback.url,
293
- authentication: { scheme: 'Bearer', credentials: this.config.callback.token } } } : {}) } }), this.auth(input.remote));
294
- if (!('id' in task))
295
- throw new Error('Remote did not return an A2A Task');
296
- return this.view(this.accept(task, { remote: input.remote, originSessionId: input.originSessionId, cwd: input.cwd, agentPreset: input.agentPreset, title: input.title, notificationTarget: input.notificationTarget }));
954
+ const { originSessionId, remote, clientRequestId, title, ...fields } = input;
955
+ const submitted = await this.submitExecution({ originSessionId, targetId: `legacy:${remote}`, input: fields, clientRequestId, title });
956
+ if ('error' in submitted)
957
+ throw new Error(`${submitted.error}; jobId=${submitted.jobId}; attemptId=${submitted.attemptId}`);
958
+ const raw = this.state.jobs.find(item => item.attemptId === submitted.attemptId);
959
+ if (!raw)
960
+ throw new Error(`Task admission unresolved; jobId=${submitted.jobId}; attemptId=${submitted.attemptId}`);
961
+ return this.view(raw);
297
962
  }
298
963
  if (method === 'remote_agent_get' || method === 'remote_agent_cancel') {
299
964
  const job = this.job(taskSchema.parse(params));
300
965
  if (method === 'remote_agent_cancel') {
301
- const client = await this.client(job.remote);
966
+ if (job.attemptId)
967
+ this.ledger.requestCancellation(job.attemptId);
968
+ const client = await this.client(job.remote, job.remoteEndpoint);
302
969
  this.update(job, await client.cancelTask(CancelTaskRequest.fromJSON({ id: job.taskId }), this.auth(job.remote)));
303
970
  }
304
971
  else
@@ -307,14 +974,21 @@ export class RemoteAgentGateway {
307
974
  }
308
975
  if (method === 'remote_agent_message') {
309
976
  const input = messageSchema.parse(params), previous = this.job(input);
310
- const client = await this.client(input.remote);
311
- const task = await client.sendMessage(SendMessageRequest.fromJSON({ message: { messageId: randomUUID(), role: 'ROLE_USER', contextId: previous.contextId, parts: [{ text: input.prompt }] },
312
- configuration: { returnImmediately: true, ...(this.config.callback ? { taskPushNotificationConfig: { url: this.config.callback.url,
313
- authentication: { scheme: 'Bearer', credentials: this.config.callback.token } } } : {}) } }), this.auth(input.remote));
314
- if (!('id' in task))
315
- throw new Error('Remote did not return an A2A Task');
316
- return this.view(this.accept(task, { remote: previous.remote, originSessionId: previous.originSessionId, cwd: previous.cwd, agentPreset: previous.agentPreset,
317
- title: previous.title, notificationTarget: previous.notificationTarget }));
977
+ if (!previous.ledgerJobId)
978
+ throw new Error('Task has no unified job association');
979
+ const record = this.ledger.get(input.originSessionId, previous.ledgerJobId);
980
+ const target = this.targets.getTarget(record.targetId);
981
+ const submitted = await this.submitExecution({ originSessionId: input.originSessionId, targetId: record.targetId,
982
+ clientRequestId: input.clientRequestId, title: previous.title,
983
+ input: { ...(target.kind === 'agent_host' ? { cwd: previous.cwd, ...(previous.agentPreset ? { agentPreset: previous.agentPreset } : {}) } : {}), prompt: input.prompt,
984
+ ...(input.preflight ? { preflight: input.preflight } : {}), ...(input.resultContract ? { resultContract: input.resultContract } : {}),
985
+ ...(previous.notificationTarget ? { notificationTarget: previous.notificationTarget } : {}) } }, { jobId: previous.ledgerJobId, previous });
986
+ if ('error' in submitted)
987
+ throw new Error(`${submitted.error}; jobId=${submitted.jobId}; attemptId=${submitted.attemptId}`);
988
+ const raw = this.state.jobs.find(item => item.attemptId === submitted.attemptId);
989
+ if (!raw)
990
+ throw new Error(`Task admission unresolved; jobId=${submitted.jobId}; attemptId=${submitted.attemptId}`);
991
+ return this.view(raw);
318
992
  }
319
993
  if (method === 'remote_agent_list' || method === 'remote_agent_inbox') {
320
994
  const { originSessionId } = inboxSchema.parse(params);
@@ -328,6 +1002,7 @@ export class RemoteAgentGateway {
328
1002
  throw new Error('Notice not found for this origin session');
329
1003
  notice.acknowledged = true;
330
1004
  this.save();
1005
+ this.sessions.acknowledgeNotice(input.originSessionId, input.noticeId);
331
1006
  return { acknowledged: true, noticeId: input.noticeId };
332
1007
  }
333
1008
  throw new Error(`Unknown method: ${method}`);
@@ -348,6 +1023,7 @@ export class RemoteAgentGateway {
348
1023
  clearInterval(this.timer);
349
1024
  for (const controller of this.controllers)
350
1025
  controller.abort();
1026
+ await this.sessions.close();
351
1027
  await Promise.allSettled([...this.refreshing.values(), ...this.operations, ...(this.reconciling ? [this.reconciling] : [])]);
352
1028
  // Delivery promises release their controllers after abort; HTTP requests
353
1029
  // may have already succeeded, so any retry keeps the stable notice ID.
@@ -387,7 +1063,7 @@ export async function serveA2AGateway(input, options = {}) {
387
1063
  void (async () => {
388
1064
  try {
389
1065
  if (req.method === 'GET' && req.url === '/health')
390
- return json(res, 200, { status: 'ok', service: 'a2a-gateway', remotes: Object.keys(gateway.config.remotes) });
1066
+ 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' });
391
1067
  if (req.method !== 'POST' || req.url !== '/invoke')
392
1068
  return json(res, 404, { error: 'No route' });
393
1069
  // Local tools are trusted. The separate tailnet receiver below never exposes /invoke.
@@ -432,11 +1108,17 @@ export async function serveA2AGateway(input, options = {}) {
432
1108
  automationPort = await listen(automationServer, gateway.config.automation.port, gateway.config.automation.host);
433
1109
  }
434
1110
  const entry = { id: 'a2a-gateway', name: 'DSH 远端智能体', kind: 'agent_runtime',
435
- capabilities: Object.keys(REMOTE_AGENT_METHODS), execution: 'http', port, reachability: 'localhost', health: '/health', methods: REMOTE_AGENT_METHODS };
1111
+ 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) } };
436
1113
  const registration = options.report === false ? undefined : await reportAndHoldRegistration(entry);
1114
+ // 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);
1116
+ reporting?.unref();
437
1117
  let closing;
438
1118
  return { gateway, port, callbackPort, automationPort, registration, close: async () => {
439
1119
  closing ??= (async () => {
1120
+ if (reporting)
1121
+ clearInterval(reporting);
440
1122
  // Stop accepting requests and drain their ledger writes while this instance
441
1123
  // still owns the storage lease. Automation continuations and its admission
442
1124
  // queue can outlive the gateway operation they awaited.