@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
@@ -0,0 +1,211 @@
1
+ /** Deliver identified messages to existing Codex and DSH host sessions. */
2
+ import { spawn } from 'node:child_process';
3
+ import path from 'node:path';
4
+ import { z } from 'zod';
5
+ const value = z.string().min(1).max(4096).refine(text => !text.includes('\0'), 'NUL is not allowed');
6
+ const timeoutMs = z.number().int().min(1).max(300_000).default(15_000);
7
+ const httpOrigin = z.string().url().refine(text => {
8
+ try {
9
+ const url = new URL(text);
10
+ return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password
11
+ && url.pathname === '/' && !url.search && !url.hash;
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ }, 'Expected an HTTP(S) origin without credentials, path, query or fragment');
17
+ const remote = value.refine(text => {
18
+ try {
19
+ const url = new URL(text);
20
+ return ['ws:', 'wss:', 'unix:'].includes(url.protocol) && !url.username && !url.password && !url.hash;
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ }, 'Expected a WebSocket or Unix socket endpoint');
26
+ const headerName = z.string().regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/);
27
+ const headerValue = z.string().refine(text => !/[\r\n\0]/.test(text), 'Invalid header value');
28
+ export const sessionHostSchema = z.discriminatedUnion('kind', [
29
+ z.object({
30
+ kind: z.literal('codex'), executable: value.default('codex'), remote: remote.optional(),
31
+ remoteAuthTokenEnv: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(256).optional(),
32
+ cwd: value.refine(text => path.isAbsolute(text), 'cwd must be absolute').optional(), timeoutMs,
33
+ }).strict(),
34
+ z.object({
35
+ kind: z.literal('dsh'), url: httpOrigin,
36
+ headers: z.record(headerName, headerValue).optional(), timeoutMs,
37
+ }).strict(),
38
+ ]).superRefine((host, ctx) => {
39
+ if (host.kind === 'codex' && host.remoteAuthTokenEnv && !host.remote) {
40
+ ctx.addIssue({ code: 'custom', path: ['remoteAuthTokenEnv'], message: 'remoteAuthTokenEnv requires remote' });
41
+ }
42
+ });
43
+ /** Safe delivery failure; an unknown host outcome must never be retried automatically. */
44
+ export class SessionDeliveryError extends Error {
45
+ retryable;
46
+ outcomeUnknown;
47
+ constructor(message, options) {
48
+ super(message);
49
+ this.name = 'SessionDeliveryError';
50
+ this.retryable = options.retryable;
51
+ this.outcomeUnknown = options.outcomeUnknown;
52
+ }
53
+ }
54
+ const messageSchema = z.object({ sessionId: value, messageId: value, text: z.string().min(1).refine(text => !text.includes('\0')) });
55
+ const uuid = '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}';
56
+ const uuidPattern = new RegExp(`^${uuid}$`, 'i');
57
+ const queuedPattern = new RegExp(`^Queued message (${uuid}) for thread (${uuid})\\.?$`, 'i');
58
+ const maxReplyBytes = 64 * 1024;
59
+ function startupFailure(error) {
60
+ const code = error?.code;
61
+ return new SessionDeliveryError('Codex queue could not start.', {
62
+ retryable: code !== 'E2BIG' && code !== 'EINVAL', outcomeUnknown: false,
63
+ });
64
+ }
65
+ /** Queue one message without starting a new host session or changing its configuration. */
66
+ export async function deliverSessionMessage(host, input, signal) {
67
+ if (!messageSchema.safeParse(input).success) {
68
+ throw new SessionDeliveryError('Invalid session message.', { retryable: false, outcomeUnknown: false });
69
+ }
70
+ if (host.kind === 'codex' && !uuidPattern.test(input.sessionId)) {
71
+ throw new SessionDeliveryError('Codex target must be a thread UUID.', { retryable: false, outcomeUnknown: false });
72
+ }
73
+ if (signal?.aborted) {
74
+ throw new SessionDeliveryError('Session delivery cancelled before dispatch.', { retryable: true, outcomeUnknown: false });
75
+ }
76
+ return host.kind === 'codex' ? deliverCodex(host, input, signal) : deliverDsh(host, input, signal);
77
+ }
78
+ function deliverCodex(host, input, signal) {
79
+ return new Promise((resolve, reject) => {
80
+ const args = ['queue', `--thread=${input.sessionId}`, `--message=${input.text}`];
81
+ if (host.remote)
82
+ args.push(`--remote=${host.remote}`);
83
+ if (host.remoteAuthTokenEnv)
84
+ args.push(`--remote-auth-token-env=${host.remoteAuthTokenEnv}`);
85
+ let child;
86
+ try {
87
+ child = spawn(host.executable, args, { cwd: host.cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
88
+ }
89
+ catch (error) {
90
+ reject(startupFailure(error));
91
+ return;
92
+ }
93
+ let started = child.pid !== undefined;
94
+ let settled = false;
95
+ let bytes = 0;
96
+ const output = [];
97
+ const finish = (error, receipt) => {
98
+ if (settled)
99
+ return;
100
+ settled = true;
101
+ clearTimeout(timer);
102
+ signal?.removeEventListener('abort', abort);
103
+ if (error)
104
+ reject(error);
105
+ else
106
+ resolve({ hostReceiptId: receipt });
107
+ };
108
+ const fail = (message) => {
109
+ finish(new SessionDeliveryError(message, { retryable: !started, outcomeUnknown: started }));
110
+ child.kill('SIGKILL');
111
+ };
112
+ const abort = () => fail('Codex queue delivery cancelled; acceptance could not be confirmed.');
113
+ const timer = setTimeout(() => fail('Codex queue timed out; acceptance could not be confirmed.'), host.timeoutMs);
114
+ child.once('spawn', () => { started = true; });
115
+ child.once('error', error => {
116
+ if (!started)
117
+ finish(startupFailure(error));
118
+ else
119
+ fail('Codex queue failed; acceptance could not be confirmed.');
120
+ });
121
+ child.stdout.on('data', (chunk) => {
122
+ bytes += chunk.length;
123
+ if (bytes > maxReplyBytes) {
124
+ fail('Codex queue returned an invalid delivery receipt.');
125
+ return;
126
+ }
127
+ output.push(chunk);
128
+ });
129
+ // Drain diagnostics without retaining or exposing provider output or credentials.
130
+ child.stderr.resume();
131
+ child.once('close', code => {
132
+ if (settled)
133
+ return;
134
+ const receipts = Buffer.concat(output).toString('utf8').split(/\r?\n/)
135
+ .map(line => queuedPattern.exec(line.trim())).filter(match => match !== null);
136
+ const receipt = receipts.length === 1 ? receipts[0] : undefined;
137
+ const matchesThread = receipt && receipt[2].toLowerCase() === input.sessionId.toLowerCase();
138
+ if (code !== 0 || !receipt || !matchesThread) {
139
+ fail('Codex queue failed; acceptance could not be confirmed.');
140
+ return;
141
+ }
142
+ finish(undefined, receipt[1]);
143
+ });
144
+ signal?.addEventListener('abort', abort, { once: true });
145
+ if (signal?.aborted)
146
+ abort();
147
+ });
148
+ }
149
+ const dshReplySchema = z.object({
150
+ type: z.literal('server-response'), rpcId: z.string(),
151
+ result: z.discriminatedUnion('ok', [
152
+ z.object({ ok: z.literal(true), value: z.object({ accepted: z.literal(true) }) }),
153
+ z.object({ ok: z.literal(false) }),
154
+ ]),
155
+ });
156
+ async function deliverDsh(host, input, signal) {
157
+ const deadline = AbortSignal.timeout(host.timeoutMs);
158
+ try {
159
+ const headers = new Headers(host.headers);
160
+ headers.set('Content-Type', 'application/json');
161
+ const response = await fetch(new URL('/api/session/prompt', host.url), {
162
+ method: 'POST', headers, redirect: 'manual',
163
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
164
+ body: JSON.stringify({
165
+ type: 'client-request', rpcId: input.messageId, method: 'session/prompt',
166
+ payload: { args: { request: {
167
+ requestId: input.messageId, sessionId: input.sessionId, mode: 'queue',
168
+ content: [{ type: 'text', text: input.text }],
169
+ } } },
170
+ }),
171
+ });
172
+ const raw = await readDshReply(response);
173
+ const parsed = dshReplySchema.safeParse(raw);
174
+ if (!parsed.success || parsed.data.rpcId !== input.messageId) {
175
+ throw new SessionDeliveryError('DSH returned an invalid delivery receipt.', { retryable: false, outcomeUnknown: true });
176
+ }
177
+ if (!parsed.data.result.ok) {
178
+ const retryable = response.status === 429 || response.status === 503;
179
+ throw new SessionDeliveryError('DSH rejected the session message.', { retryable, outcomeUnknown: false });
180
+ }
181
+ if (!response.ok) {
182
+ throw new SessionDeliveryError('DSH returned an invalid delivery receipt.', { retryable: false, outcomeUnknown: true });
183
+ }
184
+ return { hostReceiptId: parsed.data.rpcId };
185
+ }
186
+ catch (error) {
187
+ if (error instanceof SessionDeliveryError)
188
+ throw error;
189
+ // Request IDs help deduplicate ordinary retries, but do not prove admission after a lost response or host restart.
190
+ throw new SessionDeliveryError('DSH delivery could not be confirmed.', { retryable: false, outcomeUnknown: true });
191
+ }
192
+ }
193
+ async function readDshReply(response) {
194
+ if (!response.body)
195
+ return undefined;
196
+ const chunks = [];
197
+ let bytes = 0;
198
+ for await (const chunk of response.body) {
199
+ bytes += chunk.byteLength;
200
+ if (bytes > maxReplyBytes) {
201
+ throw new SessionDeliveryError('DSH returned an invalid delivery receipt.', { retryable: false, outcomeUnknown: true });
202
+ }
203
+ chunks.push(chunk);
204
+ }
205
+ try {
206
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
207
+ }
208
+ catch {
209
+ return undefined;
210
+ }
211
+ }
@@ -1,4 +1,6 @@
1
+ import { Task } from '@a2a-js/sdk';
1
2
  import { ServerCallContext, type PushNotificationStore, type TaskStore } from '@a2a-js/sdk/server';
3
+ import { type SafeError } from '@1agents/acp-service/runtime';
2
4
  import type { A2ATarget } from './types.js';
3
5
  /**
4
6
  * A single-process, durable store shared by A2A transports and DSH hosts.
@@ -9,7 +11,7 @@ export declare class FileA2AStore {
9
11
  readonly taskStore: TaskStore;
10
12
  readonly pushStore: PushNotificationStore;
11
13
  private readonly directory;
12
- private readonly lock;
14
+ private readonly lease;
13
15
  private readonly memory;
14
16
  private readonly tasks;
15
17
  private readonly pushes;
@@ -20,14 +22,10 @@ export declare class FileA2AStore {
20
22
  loadTarget(contextId: string, context: ServerCallContext): A2ATarget | undefined;
21
23
  saveTarget(contextId: string, target: A2ATarget, context: ServerCallContext): void;
22
24
  /** Persist failure for interrupted executions. A restart never reruns work. */
23
- recoverInterrupted(): Promise<void>;
25
+ recoverInterrupted(recover?: (task: Task, context: ServerCallContext) => Promise<SafeError | undefined>): Promise<void>;
24
26
  close(): void;
25
27
  private loadPush;
26
28
  private assertOpen;
27
- private acquireLock;
28
- private ownerName;
29
- private ownerPath;
30
- private removeEmptyLockDirectory;
31
29
  private readJson;
32
30
  private readEnvelope;
33
31
  private writeEnvelope;
@@ -1,9 +1,12 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { chmodSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync, } from 'node:fs';
2
+ import { chmodSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
3
3
  import { isAbsolute, join, resolve } from 'node:path';
4
4
  import { Message, Role, Task, TaskPushNotificationConfig, TaskState } from '@a2a-js/sdk';
5
5
  import { InMemoryTaskStore, resolveUserScope, ServerCallContext, } from '@a2a-js/sdk/server';
6
6
  import { RequestMalformedError } from '@a2a-js/sdk/errors';
7
+ import { toSafeError } from '@1agents/acp-service/runtime';
8
+ import { DirectoryLease } from './lease.js';
9
+ import { a2aPreflightReportSchema } from './preflight.js';
7
10
  const terminalStates = new Set([
8
11
  TaskState.TASK_STATE_COMPLETED, TaskState.TASK_STATE_FAILED,
9
12
  TaskState.TASK_STATE_CANCELED, TaskState.TASK_STATE_REJECTED,
@@ -70,7 +73,8 @@ function parseTarget(value) {
70
73
  if (!isAbsolute(cwd))
71
74
  throw new Error('Invalid A2A working directory: expected an absolute path');
72
75
  const agentPreset = source.agentPreset === undefined ? undefined : text(source.agentPreset, 'agent preset');
73
- return { sessionId, cwd, ...(agentPreset === undefined ? {} : { agentPreset }) };
76
+ const preflight = source.preflight === undefined ? undefined : a2aPreflightReportSchema.parse(source.preflight);
77
+ return { sessionId, cwd, ...(agentPreset === undefined ? {} : { agentPreset }), ...(preflight === undefined ? {} : { preflight }) };
74
78
  }
75
79
  function validatePushUrl(value) {
76
80
  const url = text(value, 'push URL');
@@ -128,7 +132,7 @@ export class FileA2AStore {
128
132
  taskStore;
129
133
  pushStore;
130
134
  directory;
131
- lock = { pid: process.pid, token: randomUUID() };
135
+ lease;
132
136
  memory = new InMemoryTaskStore();
133
137
  tasks = new Map();
134
138
  pushes = new Map();
@@ -142,7 +146,7 @@ export class FileA2AStore {
142
146
  if (!stat.isDirectory() || stat.isSymbolicLink())
143
147
  throw new Error('A2A storage directory must be a real directory');
144
148
  chmodSync(this.directory, 0o700);
145
- this.acquireLock();
149
+ this.lease = new DirectoryLease(this.directory);
146
150
  try {
147
151
  const loads = [];
148
152
  for (const name of readdirSync(this.directory)) {
@@ -271,19 +275,25 @@ export class FileA2AStore {
271
275
  this.targets.set(key(scope, contextId), normalized);
272
276
  }
273
277
  /** Persist failure for interrupted executions. A restart never reruns work. */
274
- async recoverInterrupted() {
278
+ async recoverInterrupted(recover) {
275
279
  this.assertOpen();
276
280
  await this.ready;
277
281
  for (const { scope, task } of [...this.tasks.values()]) {
278
282
  if (task.status && terminalStates.has(task.status.state))
279
283
  continue;
284
+ const recovered = await recover?.(task, contextOf(scope));
285
+ const previous = task.metadata?.['1agents'];
286
+ const metadata = recovered ? { ...task.metadata, '1agents': {
287
+ ...(previous && typeof previous === 'object' && !Array.isArray(previous) ? previous : {}),
288
+ error: toSafeError(recovered, { origin: 'a2a' }),
289
+ } } : task.metadata;
280
290
  const message = Message.fromJSON({
281
291
  messageId: randomUUID(), contextId: task.contextId, taskId: task.id,
282
292
  role: 'ROLE_AGENT',
283
293
  parts: [{ text: 'Execution was interrupted by an A2A service restart and was not restarted.' }],
284
294
  });
285
295
  await this.taskStore.save({
286
- ...task,
296
+ ...task, metadata,
287
297
  status: { state: TaskState.TASK_STATE_FAILED, timestamp: new Date().toISOString(), message },
288
298
  history: [...task.history, message],
289
299
  }, contextOf(scope));
@@ -293,19 +303,7 @@ export class FileA2AStore {
293
303
  if (this.closed)
294
304
  return;
295
305
  this.closed = true;
296
- // The owner filename is unique to this instance. Never unlink a shared
297
- // lock path: another process may have acquired it since our last check.
298
- const path = this.ownerPath();
299
- try {
300
- const lock = this.readJson(path);
301
- if (lock.token === this.lock.token && lock.pid === this.lock.pid)
302
- unlinkSync(path);
303
- }
304
- catch (error) {
305
- if (error.code !== 'ENOENT')
306
- throw error;
307
- }
308
- this.removeEmptyLockDirectory();
306
+ this.lease.close();
309
307
  }
310
308
  loadPush(taskId, context) {
311
309
  this.assertOpen();
@@ -316,102 +314,6 @@ export class FileA2AStore {
316
314
  if (this.closed)
317
315
  throw new Error('A2A store is closed');
318
316
  }
319
- acquireLock() {
320
- const path = join(this.directory, '.lock');
321
- for (let attempt = 0; attempt < 32; attempt++) {
322
- try {
323
- mkdirSync(path, { mode: 0o700 });
324
- }
325
- catch (error) {
326
- if (error.code !== 'EEXIST')
327
- throw error;
328
- try {
329
- const stat = lstatSync(path);
330
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
331
- throw new Error('Legacy or invalid A2A .lock file; verify no instance is running before removing it');
332
- }
333
- const names = readdirSync(path);
334
- for (const name of names) {
335
- const lock = record(this.readJson(join(path, name)), 'storage lock');
336
- if (!Number.isInteger(lock.pid) || lock.pid <= 0 ||
337
- typeof lock.token !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(lock.token) ||
338
- name !== `owner-${lock.pid}-${lock.token}.json`) {
339
- throw new Error('Invalid A2A storage lock; inspect the storage directory before removing it');
340
- }
341
- let dead = false;
342
- try {
343
- process.kill(lock.pid, 0);
344
- }
345
- catch (cause) {
346
- dead = cause.code === 'ESRCH';
347
- }
348
- if (!dead)
349
- throw new Error('A2A storage directory is already in use by another instance');
350
- }
351
- // Only remove the unique filenames observed above. A new live owner
352
- // can never share them, so a delayed contender cannot delete its lock.
353
- for (const name of names) {
354
- try {
355
- unlinkSync(join(path, name));
356
- }
357
- catch (cause) {
358
- if (cause.code !== 'ENOENT')
359
- throw cause;
360
- }
361
- }
362
- this.removeEmptyLockDirectory();
363
- }
364
- catch (cause) {
365
- if (cause.code !== 'ENOENT')
366
- throw cause;
367
- }
368
- continue;
369
- }
370
- try {
371
- const fd = openSync(this.ownerPath(), 'wx', 0o600);
372
- try {
373
- writeFileSync(fd, JSON.stringify(this.lock));
374
- fsyncSync(fd);
375
- }
376
- finally {
377
- closeSync(fd);
378
- }
379
- // A competing recovery can replace an empty directory between mkdir
380
- // and marker creation. If both contenders wrote into that replacement,
381
- // only the sole remaining owner may return a successfully held lock.
382
- const names = readdirSync(path);
383
- if (names.length !== 1 || names[0] !== this.ownerName()) {
384
- throw new Error('A2A storage directory is already in use by another instance');
385
- }
386
- return;
387
- }
388
- catch (error) {
389
- try {
390
- unlinkSync(this.ownerPath());
391
- }
392
- catch (cause) {
393
- if (cause.code !== 'ENOENT')
394
- throw cause;
395
- }
396
- this.removeEmptyLockDirectory();
397
- if (error.code !== 'ENOENT')
398
- throw error;
399
- }
400
- }
401
- throw new Error('Could not acquire A2A storage lock');
402
- }
403
- ownerName() { return `owner-${this.lock.pid}-${this.lock.token}.json`; }
404
- ownerPath() { return join(this.directory, '.lock', this.ownerName()); }
405
- removeEmptyLockDirectory() {
406
- try {
407
- rmdirSync(join(this.directory, '.lock'));
408
- }
409
- catch (error) {
410
- // A live marker makes rmdir fail; never recursively remove a lock directory.
411
- if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code ?? ''))
412
- throw error;
413
- }
414
- }
415
317
  readJson(path) {
416
318
  const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
417
319
  try {
@@ -1,23 +1,65 @@
1
1
  /** Execution interfaces shared by DSH and future standalone A2A hosts. */
2
+ import type { SafeError } from '@1agents/acp-service/runtime';
3
+ /** Explicit host-side requirements checked without creating an agent session. */
4
+ export interface A2APreflightRequirements {
5
+ allowedDirectories?: string[];
6
+ jobDirectory?: string;
7
+ requiredFiles?: string[];
8
+ python?: {
9
+ executable: string;
10
+ modules: string[];
11
+ };
12
+ node?: {
13
+ executable: string;
14
+ modules?: string[];
15
+ moduleRoot?: string;
16
+ };
17
+ }
18
+ export interface A2APreflightInput extends A2APreflightRequirements {
19
+ cwd: string;
20
+ }
21
+ export interface A2APreflightReport {
22
+ ok: boolean;
23
+ checkedAt: string;
24
+ cwd: string;
25
+ jobDirectory?: string;
26
+ checks: {
27
+ id: string;
28
+ ok: boolean;
29
+ detail?: string;
30
+ }[];
31
+ }
2
32
  export interface A2ATarget {
3
33
  sessionId: string;
4
34
  cwd: string;
5
35
  agentPreset?: string;
36
+ preflight?: A2APreflightReport;
6
37
  }
7
38
  /** Omitted location and preset reuse a saved context or the host defaults. */
8
39
  export interface A2APrepareInput {
9
40
  sessionId?: string;
10
41
  cwd?: string;
11
42
  agentPreset?: string;
43
+ preflight?: A2APreflightRequirements;
12
44
  }
13
45
  /** A single DSH turn's output, without transport or host dependencies. */
14
46
  export interface A2ARunResult {
15
47
  text: string;
16
48
  outcome: 'completed' | 'failed' | 'input-required';
17
49
  detail?: string;
50
+ /** Bounded, safe failure context; execution state is independent of recovery policy. */
51
+ error?: SafeError;
52
+ /** Known host endings select a fixed explanation without forwarding raw detail. */
53
+ failureReason?: 'missing-final-answer' | 'max-tokens' | 'forked' | 'unsupported-ending' | 'discarded' | 'disposed' | 'aborted' | 'interrupted';
18
54
  }
19
55
  /** Implementations own session admission, execution and precise cancellation. */
20
56
  export interface A2ABackend {
57
+ /** Does not allocate a session or submit a model prompt. */
58
+ preflight?(input: A2APreflightInput): Promise<A2APreflightReport>;
59
+ /** Optional read-only reconciliation; never resumes or repeats execution. */
60
+ recover?(target: A2ATarget, options: {
61
+ requestId: string;
62
+ }): Promise<SafeError | undefined>;
21
63
  prepare(input: A2APrepareInput): Promise<A2ATarget>;
22
64
  run(target: A2ATarget, prompt: string, options: {
23
65
  requestId: string;
@@ -15,9 +15,10 @@ export declare function webSocketStream(ws: WebSocket): Stream;
15
15
  /** A runtime subscriber owned by exactly one live ACP connection. */
16
16
  export declare class RuntimePeer {
17
17
  private readonly receive;
18
+ private readonly trustedRuntimeErrors;
18
19
  readyState: number;
19
20
  _acpxReqHost?: string;
20
- constructor(receive: (event: RecordValue) => void);
21
+ constructor(receive: (event: RecordValue) => void, trustedRuntimeErrors?: boolean);
21
22
  send(raw: string): void;
22
23
  command(backend: RuntimeBackend, payload: RecordValue): Promise<RecordValue[]>;
23
24
  }
@@ -4,11 +4,45 @@ import { randomUUID } from 'node:crypto';
4
4
  import { isAbsolute } from 'node:path';
5
5
  import { realpathSync } from 'node:fs';
6
6
  import { agent, RequestError, PROTOCOL_VERSION } from '@agentclientprotocol/sdk';
7
+ import { toSafeError } from '@1agents/acp-service/runtime';
7
8
  import { AcpState } from './acp-state.js';
8
9
  import { dispatchCommand, activeSessions, runtime, loadSessionHistory, readRuntimeRecord } from './bridge.js';
9
10
  const calls = new AsyncLocalStorage();
10
11
  const NS = '1agents';
11
12
  const EXT = '_1agents/';
13
+ /** Error envelopes have a closed projection; provider data never becomes metadata. */
14
+ function safeFailureEvent(event, trustedRuntimeErrors) {
15
+ if (['tool_call', 'tool_call_update', 'tool_result'].includes(event.event)) {
16
+ if (event.error === undefined && event.errorCode === undefined && event.errorText === undefined)
17
+ return event;
18
+ const error = toSafeError(event.error ?? (trustedRuntimeErrors ? { code: event.errorCode, message: event.errorText } : undefined), { origin: 'service' });
19
+ return { ...event,
20
+ ...(event.error !== undefined ? { error } : {}),
21
+ ...(event.errorCode !== undefined ? { errorCode: error.providerCode ?? error.code } : {}),
22
+ ...(event.errorText !== undefined ? { errorText: error.message } : {}),
23
+ };
24
+ }
25
+ const failedTurn = event.status === 'failed' && ['turn_state', 'turn_terminal', 'turn_complete', 'done'].includes(event.event);
26
+ if (!event.error && !failedTurn && event.event !== 'error' && event.event !== 'protocol_error' && event.type !== 'error')
27
+ return event;
28
+ const safe = toSafeError(event.error ?? (trustedRuntimeErrors ? { ...event, code: event.code ?? event.errorCode } : undefined), {
29
+ origin: 'service', operationId: event.runtimeRequestId ?? event.requestId, trustedProjection: trustedRuntimeErrors,
30
+ });
31
+ const value = {};
32
+ for (const key of ['event', 'type', 'sessionId', 'turnId', 'requestId', 'runtimeRequestId', 'promptMessageId',
33
+ 'sequence', 'journalSequence', 'scope', 'terminal', 'status', 'responsePolicy', 'stopReason', 'stopped',
34
+ 'completedAt', 'createdAt', 'updatedAt', 'finalAnswer', 'resultText', 'sessionRef', 'summary']) {
35
+ if (event[key] !== undefined)
36
+ value[key] = event[key];
37
+ }
38
+ if (event.error || event.status === 'failed')
39
+ return { ...value, error: safe, errorCode: safe.providerCode ?? safe.code, errorText: safe.message };
40
+ return { ...value, ...safe, error: safe };
41
+ }
42
+ function failure(error, options) {
43
+ const safe = toSafeError(error, { origin: 'service', ...options });
44
+ return new RequestError(-32000, safe.message, safe);
45
+ }
12
46
  const production = {
13
47
  dispatch: dispatchCommand,
14
48
  get sessions() { return activeSessions; },
@@ -72,13 +106,15 @@ export function webSocketStream(ws) {
72
106
  /** A runtime subscriber owned by exactly one live ACP connection. */
73
107
  export class RuntimePeer {
74
108
  receive;
109
+ trustedRuntimeErrors;
75
110
  readyState = 1;
76
111
  _acpxReqHost;
77
- constructor(receive) {
112
+ constructor(receive, trustedRuntimeErrors = false) {
78
113
  this.receive = receive;
114
+ this.trustedRuntimeErrors = trustedRuntimeErrors;
79
115
  }
80
116
  send(raw) {
81
- const event = JSON.parse(raw);
117
+ const event = safeFailureEvent(JSON.parse(raw), this.trustedRuntimeErrors);
82
118
  const call = calls.getStore();
83
119
  if (call?.active)
84
120
  call.events.push(event);
@@ -90,12 +126,17 @@ export class RuntimePeer {
90
126
  try {
91
127
  await calls.run(call, () => backend.dispatch(this, payload));
92
128
  }
129
+ catch (error) {
130
+ throw failure(error, { operationId: payload.requestId });
131
+ }
93
132
  finally {
94
133
  call.active = false;
95
134
  }
96
- const failure = events.find(e => (e.event === 'error' || e.type === 'error' || e.event === 'protocol_error') && e.scope !== 'turn');
97
- if (failure)
98
- throw new RequestError(-32000, failure.message || 'Runtime command failed', { code: failure.code });
135
+ const failureEvent = events.find(e => (e.event === 'error' || e.type === 'error' || e.event === 'protocol_error') && e.scope !== 'turn');
136
+ if (failureEvent) {
137
+ const safe = toSafeError(failureEvent.error ?? failureEvent, { origin: 'service', operationId: payload.requestId });
138
+ throw new RequestError(-32000, safe.message, safe);
139
+ }
99
140
  return events;
100
141
  }
101
142
  }
@@ -151,7 +192,9 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
151
192
  const interactive = new Map();
152
193
  const answers = new Map();
153
194
  const toolsSeen = new Set();
154
- const peer = new RuntimePeer(receive);
195
+ // The production bridge already projects runtime errors before serialization.
196
+ // Injected backends do not inherit that provenance for self-asserted fields.
197
+ const peer = new RuntimePeer(receive, backend === production);
155
198
  peer._acpxReqHost = req?.headers.host?.split(':')[0];
156
199
  function notify(method, params) {
157
200
  if (!connected)
@@ -160,7 +203,7 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
160
203
  if (!connected)
161
204
  return;
162
205
  for (const pending of prompts.values())
163
- pending.reject(error);
206
+ pending.reject(failure(error, { origin: 'transport', operationId: pending.requestId, outcomeUnknown: true }));
164
207
  prompts.clear();
165
208
  ws.close(1011, 'ACP update delivery failed');
166
209
  });
@@ -284,7 +327,7 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
284
327
  prompts.delete(key);
285
328
  void output.then(() => {
286
329
  if (event.status === 'failed' || event.event === 'error')
287
- pending.reject(new RequestError(-32000, event.error?.message || event.message || 'Turn failed', { code: event.error?.code }));
330
+ pending.reject(failure(event.error ?? event, { operationId: pending.requestId }));
288
331
  else
289
332
  pending.resolve({ stopReason: event.stopped || event.status === 'cancelled' ? 'cancelled' : ['end_turn', 'max_tokens', 'max_turn_requests', 'refusal', 'cancelled'].includes(event.stopReason) ? event.stopReason : 'end_turn', _meta: envelope(event) });
290
333
  });
@@ -509,7 +552,7 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
509
552
  for (const item of interactive.values())
510
553
  item.abort.abort();
511
554
  for (const pending of prompts.values())
512
- pending.reject(new Error('Connection closed; resume the session to observe the retained turn'));
555
+ pending.reject(failure(undefined, { origin: 'transport', operationId: pending.requestId, outcomeUnknown: true }));
513
556
  prompts.clear();
514
557
  });
515
558
  const connection = app.connect(webSocketStream(ws));