@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
package/README.md CHANGED
@@ -296,7 +296,7 @@ correlation and completion-processing claims. See the repository's
296
296
  [integration guide](https://github.com/scottzx/1acp/blob/main/docs/activepieces-automation.md) and
297
297
  [configuration examples](https://github.com/scottzx/1acp/tree/main/examples/activepieces).
298
298
 
299
- The same package includes `acp-service a2a gateway --config /absolute/gateway.json` and exports `RemoteAgentGateway` / `serveA2AGateway` from `@1agents/acp-service/a2a`. The gateway calls the standard A2A 1.0 SendMessage, GetTask and CancelTask APIs. It registers seven HTTP methods with the local DreamMate node; an existing `dreammate_invoke` client can use them immediately without another MCP server.
299
+ The same package includes `acp-service a2a gateway --config /absolute/gateway.json` and exports `RemoteAgentGateway` / `serveA2AGateway` from `@1agents/acp-service/a2a`. The gateway calls the standard A2A 1.0 SendMessage, GetTask and CancelTask APIs. Its seven `remote_agent_*` methods register with the local DreamMate node; an existing `dreammate_invoke` client can use them without another MCP server. This source change also adds four optional `session_*` delivery methods described below; installed older versions must be updated before using them.
300
300
 
301
301
  Create a private configuration file (`chmod 600`):
302
302
 
@@ -334,9 +334,49 @@ The returned `taskId` is available before execution finishes. `cwd` is an existi
334
334
 
335
335
  CLI callers use the same methods: pipe a JSON parameters object to `acp-service a2a invoke remote_agent_spawn` (or any method above). The gateway runs independently of the caller. A durable inbox, stable notice IDs, restart reconciliation and GetTask polling recover completions when a push event is missed. Offline queries return the cached task with `stale: true`; loss of connectivity never becomes a fabricated task failure. An ambiguous failed SendMessage is not automatically resubmitted, since A2A message IDs alone do not guarantee exactly-once task admission.
336
336
 
337
- To wake a main-agent host, configure `notificationTargets` as a map of trusted target names to `{ "url": "...", "token": "..." }` and pass a target name as `notificationTarget` to spawn. Completion or input-required notices carry `originSessionId`, `taskId`, `contextId`, state and result. Deliveries use bearer authentication and a stable `Idempotency-Key`, retry after a failed response or gateway restart, and remain in the inbox until acknowledged. The receiving host must persist/deduplicate the notice and inject it into the named parent session (for example Phonetic's `async_task_notice`). A successful HTTP response means the receiver accepted the notice, not that the main model ran. Codex's ordinary MCP tool connection alone does not implement that host adapter; this gateway does not claim automatic Codex turn wake-up.
337
+ The existing webhook path uses `notificationTargets`, a map of trusted target names to `{ "url": "...", "token": "..." }`, and a `notificationTarget` name on spawn. Completion or input-required notices carry `originSessionId`, `taskId`, `contextId`, state and result. Delivery uses bearer authentication and a stable `Idempotency-Key`. Failed delivery retries after reconciliation or restart; any successful HTTP response stops webhook retries, while the notice remains in the inbox until acknowledged. The receiver must durably accept and deduplicate the notice before responding, then own injection into the parent session. HTTP success does not prove that the main model ran.
338
+
339
+ ### Existing-session delivery — new in this source change
340
+
341
+ The gateway now has an optional durable delivery layer for existing Codex and DSH sessions. This change has not been deployed or exercised against real user sessions. Configure named `sessionHosts`, then bind an `originSessionId` with `session_bind`. The Codex adapter runs native `codex queue --thread=<UUID> --message=<text>` without a shell; the DSH adapter sends the host's Web Remote envelope to `/api/session/prompt` in `queue` mode with a stable request ID. These adapters use the hosts' existing queues and do not require a new HTTP receiver.
342
+
343
+ | Method | Parameters and behavior |
344
+ | --- | --- |
345
+ | `session_bind` | `originSessionId, host, sessionId`; fixes the origin to an existing session on a configured host; the same binding is repeatable, a different target is rejected |
346
+ | `session_send` | `originSessionId, messageId, text`; persists the message and immediately returns a delivery receipt; a repeated ID must have identical text; the `a2a-notice:` prefix is reserved |
347
+ | `session_delivery_get` | `originSessionId, messageId`; reads the delivery receipt |
348
+ | `session_delivery_resolve` | `originSessionId, messageId, accepted, note`, optional `hostReceiptId`; resolves only `unknown/rejected` after checking host acceptance and addressing rejection; false requires evidence of nonacceptance and returns the message to pending |
349
+
350
+ Use the same methods through `acp-service a2a invoke <method>` or DreamMate. Receipts contain `originSessionId`, `messageId`, `host`, `sessionId`, `status`, `attempts`, `createdAt`, `updatedAt`, and optional `nextAttemptAt`, `hostReceiptId`, `error`, `processedAt`, `resolutionNote`. Per-origin FIFO delivery moves through `pending`, `dispatching`, `retrying`, `accepted`, `unknown`, or `rejected`. Ambiguous acceptance becomes `unknown`; a definite rejection without automatic recovery becomes `rejected`. Both block later deliveries for that origin and require explicit resolution. A bare DSH HTTP 429/503 does not prove nonacceptance; retry requires an explicit RPC rejection with the matching rpcId and `result.ok: false`. DSH's stable request ID helps deduplication but does not establish exactly-once delivery or processing.
351
+
352
+ Host transport IDs are derived deterministically as `sha256([originSessionId, messageId])`, preventing same-named messages from different origins from sharing a DSH requestId/rpcId. Public methods continue to use the original messageId; `hostReceiptId` comes from the actual host receipt. If delivery storage fails, further delivery stops and health returns HTTP 503. Repair storage and restart the gateway to recover from durable records; do not resume from uncertain in-memory state. Persisted dispatching records still require unknown-admission reconciliation after restart.
353
+
354
+ New A2A notices snapshot their delivery route. An already bound origin uses session delivery, ahead of the legacy webhook, with message ID `a2a-notice:<noticeId>`. The queued notice identifies the task and tells the parent to retrieve its full result through `remote_agent_get` or `remote_agent_inbox`. Unbound origins keep the existing webhook/inbox path; adding a binding later does not migrate old notices. `accepted` means accepted into the host queue, not model execution or business completion. Notices stay in the inbox until `remote_agent_ack`; acknowledgement records `processedAt` on the corresponding delivery and prevents a pending notice from being sent later. There is no automatic business acknowledgement.
355
+
356
+ Codex hosts support `executable`, `remote`, `cwd`, `timeoutMs`, and `remoteAuthTokenEnv`; DSH hosts support an origin `url`, protected `headers`, and `timeoutMs`. Keep real DSH Cookie/Authorization values and remote credentials in the private gateway configuration or designated environment, never tool arguments, message text, receipts, or logs. Host authentication is distinct from the remote A2A bearer token. Ordinary MCP access alone still does not supply a binding or configure the host. See the [session delivery guide](https://github.com/scottzx/1acp/blob/main/docs/session-delivery.md) for configuration and recovery.
338
357
 
339
358
 
340
359
  ## 0.8.0 — DreamMate dependency transition
341
360
 
342
361
  The public service now targets dreammate-node ^0.15.0 and dreammate-network ^0.5.0. The runtime and DSH plugin remain embedded in this one public package. Update consuming DSH profiles and service installations from the lockfile; do not substitute the older standalone dsh-acp release. This change does not alter stored agent sessions or configured credentials.
362
+
363
+
364
+ ## 0.8.1 — preserve deployed diagnostics and cancellation fixes
365
+
366
+ Includes the already deployed c055869 branch: structured error provenance, confirmed/unconfirmed cancellation handling, journal ownership, and persisted current-turn diagnostics. This avoids regressing the ERP pilot during the DreamMate 0.15 dependency migration.
367
+
368
+
369
+ ## 统一任务入口与 PPT 交付角色(本地 P0/P1)
370
+
371
+ A2A 网关增加版本化执行目标目录和任务台账。父任务与子任务都是独立任务;`jobId` 表示工作,`attemptId` 表示一次明确派发、继续或返工。`executionStatus` 展示当前执行轮次,同时列出历史在途/未决轮次。目标探测只读,不调用模型;固定角色拒绝覆盖 cwd/preset,目录范围在执行端用 realpath 复核。
372
+
373
+ - `execution_connection_*` / `execution_target_*` 管理人工登记的连接和三类目标;管理入口只对可信本机开放,DreamMate 报备注明 local-only。
374
+ - `execution_submit` 接收 `originSessionId/targetId/input/clientRequestId?`,远端派发前持久化任务与执行轮次;重复请求返回原轮次,未知受理不能盲目重派。
375
+ - `execution_get/list/events` 查询来源范围内的状态、结果、父子引用和事件;`execution_continue` 显式创建新执行轮次,保留原后端上下文。
376
+ - `remote_agent_*` 保留原参数、Task 和通知/ack,返回附加 jobId/attemptId;旧 Task 各迁移为独立任务,不按 context 合并。
377
+ - 可选 `binding.driver=ppt_delivery` 使用独立领域模块推进项目脚本、制作、确定性校验、独立事实/逐页视觉复核及有限返工。父任务等待时仍为 working;它不把阶段调度加入通用台账。
378
+ - `execution_inbox/ack` 处理领域交付通知,`execution_review` 独立记录绑定具体轮次、结果版本与 digest 的业务接受。角色通知使用独立 `execution-notice:` 标识,不伪造远端 A2A Task。
379
+
380
+ 状态为 gateway.json v2,首次升级前备份。执行端和网关应使用同一冻结完整安装包;角色策略与人工目标配置保存在受保护部署目录,公共样例见 [PPT 交付说明](../../examples/ppt-beautifier/delivery-README.md)。网关周期向 Node 重报备,Node 暂时不可用不影响直接调用。
381
+
382
+ 本阶段不实现 AP 执行 Provider、AP 投影或通用 DAG 引擎;workflow 可登记但执行明确返回 unsupported。未知受理保持待核对;领域父任务 input_required 后本版本不自动恢复,需要明确处理,不能把超时当作远端已停止。目录策略是执行准入检查,不是操作系统沙箱。通知入队不等于主会话已实际唤醒,真实闭环需另存新轮次证据。
package/dist/bin/a2a.js CHANGED
@@ -16,8 +16,9 @@ export async function runA2ACli(args) {
16
16
 
17
17
  invoke reads a JSON parameters object from stdin. Credentials stay in the
18
18
  gateway config file (chmod 600), outside tool arguments. Remote cwd is absolute.
19
- Methods: remote_agent_spawn, remote_agent_get, remote_agent_message,
20
- remote_agent_cancel, remote_agent_list, remote_agent_inbox, remote_agent_ack`);
19
+ Methods: remote_agent_preflight, remote_agent_spawn, remote_agent_get, remote_agent_message,
20
+ remote_agent_cancel, remote_agent_list, remote_agent_inbox, remote_agent_ack,
21
+ session_bind, session_send, session_delivery_get, session_delivery_resolve`);
21
22
  return;
22
23
  }
23
24
  if (args[0] === 'gateway') {
File without changes
@@ -2,6 +2,7 @@ import { type SendMessageRequest } from '@a2a-js/sdk';
2
2
  import { type AgentExecutor, type ExecutionEventBus, type RequestContext } from '@a2a-js/sdk/server';
3
3
  import type { FileA2AStore } from './store.js';
4
4
  import type { A2ABackend, A2APrepareInput } from './types.js';
5
+ import { type A2AResultContract } from './result-metadata.js';
5
6
  export interface A2AExecutionOptions {
6
7
  defaultCwd?: string;
7
8
  defaultAgentPreset?: string;
@@ -11,6 +12,7 @@ export interface A2AExecutionOptions {
11
12
  export declare function parseA2AInput(request: SendMessageRequest, options: A2AExecutionOptions): {
12
13
  prompt: string;
13
14
  input: A2APrepareInput;
15
+ resultContract?: A2AResultContract;
14
16
  };
15
17
  /** SDK owns the execution lifetime; an HTTP disconnect never aborts this signal. */
16
18
  export declare class A2ASessionExecutor implements AgentExecutor {
@@ -1,8 +1,22 @@
1
1
  /** Official A2A executor with durable DSH context bindings and independent turns. */
2
- import { createHash, randomUUID } from 'node:crypto';
2
+ import { randomUUID } from 'node:crypto';
3
3
  import { Role, Task, TaskState, Message } from '@a2a-js/sdk';
4
4
  import { ContentTypeNotSupportedError, RequestMalformedError, UnsupportedOperationError } from '@a2a-js/sdk/errors';
5
5
  import { AgentEvent, resolveUserScope } from '@a2a-js/sdk/server';
6
+ import { a2aRequestId } from './request-id.js';
7
+ import { toSafeError } from '@1agents/acp-service/runtime';
8
+ import { A2APreflightError, a2aPreflightRequirementsSchema } from './preflight.js';
9
+ import { a2aResultContractSchema, A2AResultValidationError, createA2AResultMetadata, saveA2AResultMetadata } from './result-metadata.js';
10
+ const FAILURE_MESSAGES = {
11
+ 'missing-final-answer': 'DSH completed the task without a final answer; ACP final-answer metadata contained no final output',
12
+ 'max-tokens': 'DSH reached the model output token limit',
13
+ forked: 'DSH task turn was closed by a session fork',
14
+ 'unsupported-ending': 'DSH returned an unsupported turn ending',
15
+ discarded: 'DSH discarded the queued task before execution',
16
+ disposed: 'DSH session was disposed before the task finished',
17
+ aborted: 'DSH task execution was canceled',
18
+ interrupted: 'DSH task execution was interrupted',
19
+ };
6
20
  /** Validate application metadata before the SDK starts an execution. */
7
21
  export function parseA2AInput(request, options) {
8
22
  const message = request.message;
@@ -19,7 +33,7 @@ export function parseA2AInput(request, options) {
19
33
  throw new RequestMalformedError('metadata.1agents must be an object');
20
34
  const value = (metadata ?? {});
21
35
  for (const key of Object.keys(value))
22
- if (!['cwd', 'agentPreset', 'workspace'].includes(key))
36
+ if (!['cwd', 'agentPreset', 'workspace', 'preflight', 'resultContract'].includes(key))
23
37
  throw new RequestMalformedError(`Unknown metadata.1agents field: ${key}`);
24
38
  for (const key of ['cwd', 'agentPreset', 'workspace']) {
25
39
  if (value[key] !== undefined && (typeof value[key] !== 'string' || !value[key].trim()))
@@ -33,7 +47,15 @@ export function parseA2AInput(request, options) {
33
47
  if (!cwd)
34
48
  throw new RequestMalformedError(`Unknown workspace: ${value.workspace}`);
35
49
  }
36
- return { prompt, input: { cwd, agentPreset: value.agentPreset } };
50
+ const preflight = value.preflight === undefined ? undefined : a2aPreflightRequirementsSchema.safeParse(value.preflight);
51
+ if (preflight && !preflight.success)
52
+ throw new RequestMalformedError('Invalid preflight requirements');
53
+ const resultContract = value.resultContract === undefined ? undefined : a2aResultContractSchema.safeParse(value.resultContract);
54
+ if (resultContract && !resultContract.success)
55
+ throw new RequestMalformedError('Invalid result contract');
56
+ return { prompt, input: { cwd, agentPreset: value.agentPreset,
57
+ ...(preflight?.success ? { preflight: preflight.data } : {}) },
58
+ ...(resultContract?.success ? { resultContract: resultContract.data } : {}) };
37
59
  }
38
60
  /** SDK owns the execution lifetime; an HTTP disconnect never aborts this signal. */
39
61
  export class A2ASessionExecutor {
@@ -61,27 +83,40 @@ export class A2ASessionExecutor {
61
83
  const done = new Promise(resolve => { finish = resolve; });
62
84
  this.active.set(context.taskId, { controller, done });
63
85
  let published = false;
64
- const status = (state, text) => {
86
+ let target;
87
+ let returnedError;
88
+ let returnedFailureMessage;
89
+ const startedAt = new Date().toISOString();
90
+ let resultContract;
91
+ let resultMetadata;
92
+ // DSH deduplicates prompts by rpcId across the whole session. A Task can
93
+ // have several input-required turns, each with its own message identity.
94
+ const requestId = a2aRequestId(context.taskId, context.userMessage.messageId);
95
+ const status = (state, text, error) => {
65
96
  bus.publish(AgentEvent.statusUpdate({ taskId: context.taskId, contextId: context.contextId,
66
97
  status: { state, timestamp: new Date().toISOString(), message: text ? Message.fromJSON({
67
98
  messageId: randomUUID(), role: 'ROLE_AGENT', contextId: context.contextId, taskId: context.taskId, parts: [{ text }],
68
- }) : undefined }, metadata: undefined }));
99
+ }) : undefined }, metadata: error || resultMetadata ? { '1agents': {
100
+ ...target, ...(resultMetadata ? { result: resultMetadata } : {}), ...(error ? { error } : {}),
101
+ } } : undefined }));
69
102
  };
70
103
  try {
71
- const { prompt, input } = parseA2AInput(context.request, this.options);
104
+ const parsed = parseA2AInput(context.request, this.options);
105
+ const { prompt, input } = parsed;
106
+ resultContract = parsed.resultContract;
72
107
  const key = JSON.stringify([context.context.tenant ?? '', resolveUserScope(context.context), context.contextId]);
73
108
  const previous = this.preparing.get(key) ?? Promise.resolve();
74
109
  let unlock;
75
110
  const lock = new Promise(resolve => { unlock = resolve; });
76
111
  this.preparing.set(key, lock);
77
- let target;
78
112
  try {
79
113
  await previous;
80
114
  controller.signal.throwIfAborted();
81
115
  const saved = this.store.loadTarget(context.contextId, context.context);
82
116
  target = await this.backend.prepare({ sessionId: saved?.sessionId,
83
117
  cwd: input.cwd ?? saved?.cwd ?? this.options.defaultCwd,
84
- agentPreset: input.agentPreset ?? saved?.agentPreset ?? this.options.defaultAgentPreset });
118
+ agentPreset: input.agentPreset ?? saved?.agentPreset ?? this.options.defaultAgentPreset,
119
+ ...(input.preflight ? { preflight: input.preflight } : {}) });
85
120
  this.store.saveTarget(context.contextId, target, context.context);
86
121
  }
87
122
  finally {
@@ -96,25 +131,59 @@ export class A2ASessionExecutor {
96
131
  published = true;
97
132
  controller.signal.throwIfAborted();
98
133
  status(TaskState.TASK_STATE_WORKING);
99
- // DSH deduplicates prompts by rpcId across the whole session. A Task can
100
- // have several input-required turns, each with its own message identity.
101
- const requestId = `a2a-${createHash('sha256').update(JSON.stringify([context.taskId, context.userMessage.messageId])).digest('hex')}`;
102
134
  const result = await this.backend.run(target, prompt, { requestId, signal: controller.signal });
135
+ returnedError = result.outcome === 'failed' && result.error !== undefined
136
+ ? toSafeError(result.error, { origin: 'a2a', operationId: requestId }) : undefined;
137
+ returnedFailureMessage = result.outcome === 'failed' && typeof result.failureReason === 'string' && Object.hasOwn(FAILURE_MESSAGES, result.failureReason)
138
+ ? FAILURE_MESSAGES[result.failureReason] : undefined;
103
139
  controller.signal.throwIfAborted();
140
+ // Publish the final answer first so failed artifact validation remains diagnosable.
104
141
  if (result.text)
105
142
  bus.publish(AgentEvent.artifactUpdate({ taskId: context.taskId, contextId: context.contextId,
106
143
  artifact: { artifactId: `${context.taskId}-${randomUUID()}`, name: 'DSH response', description: '',
107
144
  parts: [{ content: { $case: 'text', value: result.text }, mediaType: 'text/plain', filename: '', metadata: undefined }], metadata: undefined, extensions: [] },
108
145
  append: false, lastChunk: true, metadata: undefined }));
146
+ resultMetadata = await createA2AResultMetadata({ taskId: context.taskId, contextId: context.contextId,
147
+ requestId, startedAt, outcome: result.outcome, target, contract: resultContract });
148
+ await saveA2AResultMetadata(resultMetadata, target);
149
+ if (resultMetadata.artifacts.some(artifact => artifact.url)) {
150
+ bus.publish(AgentEvent.artifactUpdate({ taskId: context.taskId, contextId: context.contextId,
151
+ artifact: { artifactId: `${context.taskId}-verified-artifacts`, name: 'Verified artifacts', description: '',
152
+ parts: resultMetadata.artifacts.filter(artifact => artifact.url).map(artifact => ({
153
+ content: { $case: 'url', value: artifact.url }, mediaType: artifact.mediaType ?? 'application/octet-stream',
154
+ filename: '', metadata: { sha256: artifact.sha256, size: artifact.size },
155
+ })), metadata: { verifiedBy: '1agents/a2a-host' }, extensions: [] },
156
+ append: false, lastChunk: true, metadata: undefined }));
157
+ }
109
158
  if (result.outcome === 'input-required')
110
- this.awaitingInput.set(context.taskId, context.contextId);
111
- status(result.outcome === 'completed' ? TaskState.TASK_STATE_COMPLETED : result.outcome === 'input-required' ? TaskState.TASK_STATE_INPUT_REQUIRED : TaskState.TASK_STATE_FAILED, result.detail);
159
+ this.awaitingInput.set(context.taskId, {
160
+ contextId: context.contextId, target, result: resultMetadata,
161
+ });
162
+ const error = result.outcome === 'failed'
163
+ ? toSafeError(returnedError, { origin: 'a2a', operationId: requestId }) : undefined;
164
+ status(result.outcome === 'completed' ? TaskState.TASK_STATE_COMPLETED : result.outcome === 'input-required' ? TaskState.TASK_STATE_INPUT_REQUIRED : TaskState.TASK_STATE_FAILED, returnedFailureMessage ?? error?.message ?? result.detail, error);
112
165
  }
113
166
  catch (error) {
114
167
  if (!published)
115
168
  bus.publish(AgentEvent.task(Task.fromJSON({ id: context.taskId, contextId: context.contextId,
116
169
  status: { state: 'TASK_STATE_SUBMITTED', timestamp: new Date().toISOString() } })));
117
- status(controller.signal.aborted ? TaskState.TASK_STATE_CANCELED : TaskState.TASK_STATE_FAILED, error instanceof Error ? error.message : String(error));
170
+ const projected = controller.signal.aborted && returnedError ? returnedError : toSafeError(error, { origin: 'a2a', operationId: requestId });
171
+ const cancellationOnly = controller.signal.aborted && !returnedError && error === controller.signal.reason;
172
+ const safe = toSafeError(cancellationOnly ? new DOMException('A2A task canceled', 'AbortError') : projected, {
173
+ origin: 'a2a', operationId: requestId, outcomeUnknown: projected.outcomeUnknown,
174
+ });
175
+ resultMetadata = await createA2AResultMetadata({ taskId: context.taskId, contextId: context.contextId,
176
+ requestId, startedAt, outcome: controller.signal.aborted ? 'canceled' : 'failed', target, contract: resultContract,
177
+ validationCode: error instanceof A2AResultValidationError ? error.code : undefined,
178
+ ...(error instanceof A2APreflightError ? { preflight: error.report } : {}) });
179
+ try {
180
+ await saveA2AResultMetadata(resultMetadata, target);
181
+ }
182
+ catch {
183
+ resultMetadata.validation = { status: 'failed', code: 'result-record-write-failed' };
184
+ delete resultMetadata.recordPath;
185
+ }
186
+ status(controller.signal.aborted ? TaskState.TASK_STATE_CANCELED : TaskState.TASK_STATE_FAILED, returnedFailureMessage ?? safe.message, safe);
118
187
  }
119
188
  finally {
120
189
  this.active.delete(context.taskId);
@@ -124,12 +193,21 @@ export class A2ASessionExecutor {
124
193
  async cancelTask(taskId, bus) {
125
194
  const execution = this.active.get(taskId);
126
195
  if (!execution) {
127
- const contextId = this.awaitingInput.get(taskId);
128
- if (!contextId)
196
+ const pending = this.awaitingInput.get(taskId);
197
+ if (!pending)
129
198
  throw new UnsupportedOperationError('No active execution for this task');
130
199
  this.awaitingInput.delete(taskId);
131
- bus.publish(AgentEvent.statusUpdate({ taskId, contextId,
132
- status: { state: TaskState.TASK_STATE_CANCELED, timestamp: new Date().toISOString(), message: undefined }, metadata: undefined }));
200
+ const result = { ...pending.result, finishedAt: new Date().toISOString(), outcome: 'canceled' };
201
+ try {
202
+ await saveA2AResultMetadata(result, pending.target);
203
+ }
204
+ catch {
205
+ result.validation = { status: 'failed', code: 'result-record-write-failed' };
206
+ delete result.recordPath;
207
+ }
208
+ bus.publish(AgentEvent.statusUpdate({ taskId, contextId: pending.contextId,
209
+ status: { state: TaskState.TASK_STATE_CANCELED, timestamp: result.finishedAt, message: undefined },
210
+ metadata: { '1agents': { ...pending.target, result } } }));
133
211
  return;
134
212
  }
135
213
  execution.controller.abort(new Error('A2A task canceled'));