@1agents/acp-service 0.8.1 → 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 (103) hide show
  1. package/README.md +37 -2
  2. package/dist/bin/a2a.js +3 -2
  3. package/dist/src/a2a/executor.d.ts +2 -0
  4. package/dist/src/a2a/executor.js +63 -10
  5. package/dist/src/a2a/gateway.d.ts +407 -14
  6. package/dist/src/a2a/gateway.js +719 -37
  7. package/dist/src/a2a/index.d.ts +8 -1
  8. package/dist/src/a2a/index.js +4 -0
  9. package/dist/src/a2a/notices.d.ts +24 -0
  10. package/dist/src/a2a/notices.js +56 -0
  11. package/dist/src/a2a/preflight.d.ts +52 -0
  12. package/dist/src/a2a/preflight.js +153 -0
  13. package/dist/src/a2a/result-metadata.d.ts +59 -0
  14. package/dist/src/a2a/result-metadata.js +156 -0
  15. package/dist/src/a2a/server.js +30 -0
  16. package/dist/src/a2a/session-delivery.d.ts +69 -0
  17. package/dist/src/a2a/session-delivery.js +260 -0
  18. package/dist/src/a2a/session-hosts.d.ts +34 -0
  19. package/dist/src/a2a/session-hosts.js +211 -0
  20. package/dist/src/a2a/store.js +3 -1
  21. package/dist/src/a2a/types.d.ts +33 -0
  22. package/dist/src/execution/delivery-progress.d.ts +108 -0
  23. package/dist/src/execution/delivery-progress.js +57 -0
  24. package/dist/src/execution/ledger.d.ts +235 -0
  25. package/dist/src/execution/ledger.js +396 -0
  26. package/dist/src/execution/ppt-delivery.d.ts +231 -0
  27. package/dist/src/execution/ppt-delivery.js +625 -0
  28. package/dist/src/execution/targets.d.ts +349 -0
  29. package/dist/src/execution/targets.js +428 -0
  30. package/package.json +11 -12
  31. package/skills/acp-service/SKILL.md +9 -2
  32. package/skills/acp-service/references/a2a.md +72 -4
  33. package/vendor/dsh/a2a-executor.d.ts +2 -1
  34. package/vendor/dsh/a2a-executor.js +28 -1
  35. package/vendor/dsh/a2a.js +1 -0
  36. package/vendor/dsh/client.js +11 -3
  37. package/vendor/runtime/dist/{agent-registry-CMg8LHKY.js → agent-registry-R7A3MSpr.js} +9 -1
  38. package/vendor/runtime/dist/agent-registry-R7A3MSpr.js.map +1 -0
  39. package/vendor/runtime/dist/agent-registry.d.ts +1 -0
  40. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  41. package/vendor/runtime/dist/agent-registry.js +1 -2
  42. package/vendor/runtime/dist/{cli-Bdzplbpj.js → cli-DeOpE2Xz.js} +4 -4
  43. package/vendor/runtime/dist/{cli-Bdzplbpj.js.map → cli-DeOpE2Xz.js.map} +1 -1
  44. package/vendor/runtime/dist/cli.d.ts +2 -1
  45. package/vendor/runtime/dist/cli.js +10 -10
  46. package/vendor/runtime/dist/cli.js.map +1 -1
  47. package/vendor/runtime/dist/{client-BXOiB0ND.d.ts → client-VQsqcIOJ.d.ts} +2 -2
  48. package/vendor/runtime/dist/{client-BXOiB0ND.d.ts.map → client-VQsqcIOJ.d.ts.map} +1 -1
  49. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  50. package/vendor/runtime/dist/docs-site/CLI.html +833 -0
  51. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  52. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  53. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  54. package/vendor/runtime/dist/docs-site/config.html +450 -0
  55. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  56. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  57. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  58. package/vendor/runtime/dist/docs-site/flows.html +498 -0
  59. package/vendor/runtime/dist/docs-site/index.html +367 -0
  60. package/vendor/runtime/dist/docs-site/install.html +386 -0
  61. package/vendor/runtime/dist/docs-site/llms.txt +36 -0
  62. package/vendor/runtime/dist/docs-site/output-formats.html +407 -0
  63. package/vendor/runtime/dist/docs-site/permissions.html +422 -0
  64. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  65. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  66. package/vendor/runtime/dist/docs-site/releasing.html +341 -0
  67. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  68. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
  69. package/vendor/runtime/dist/docs-site/safe-errors.html +323 -0
  70. package/vendor/runtime/dist/docs-site/session-control.html +408 -0
  71. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  72. package/vendor/runtime/dist/docs-site/sessions.html +488 -0
  73. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  74. package/vendor/runtime/dist/{flows-BKlAuzM8.js → flows-oaBGn31w.js} +5 -5
  75. package/vendor/runtime/dist/{flows-BKlAuzM8.js.map → flows-oaBGn31w.js.map} +1 -1
  76. package/vendor/runtime/dist/flows.d.ts +2 -2
  77. package/vendor/runtime/dist/flows.d.ts.map +1 -1
  78. package/vendor/runtime/dist/flows.js +1 -2
  79. package/vendor/runtime/dist/{invocation-options-DMy77sEU.js → invocation-options-CUDEE8vW.js} +5 -5
  80. package/vendor/runtime/dist/{invocation-options-DMy77sEU.js.map → invocation-options-CUDEE8vW.js.map} +1 -1
  81. package/vendor/runtime/dist/{ipc-CLv2iL89.js → ipc-BQQpcEdP.js} +98 -20
  82. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +1 -0
  83. package/vendor/runtime/dist/{output-I-t-v55D.js → output-CFv3jcOQ.js} +86 -22
  84. package/vendor/runtime/dist/output-CFv3jcOQ.js.map +1 -0
  85. package/vendor/runtime/dist/{queue-owner-runtime-RN3uSid0.js → queue-owner-runtime-DvMJiGbP.js} +86 -27
  86. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +1 -0
  87. package/vendor/runtime/dist/runtime.d.ts +5 -2
  88. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  89. package/vendor/runtime/dist/runtime.js +77 -29
  90. package/vendor/runtime/dist/runtime.js.map +1 -1
  91. package/vendor/runtime/dist/{session-options-DNnDfiUt.d.ts → session-options-NjpFwf-c.d.ts} +5 -1
  92. package/vendor/runtime/dist/session-options-NjpFwf-c.d.ts.map +1 -0
  93. package/vendor/runtime/dist/{session-watch-CmHbH0jS.js → session-watch-Di-wIdCH.js} +4 -4
  94. package/vendor/runtime/dist/{session-watch-CmHbH0jS.js.map → session-watch-Di-wIdCH.js.map} +1 -1
  95. package/vendor/runtime/dist/{watch-BE-kKa7o.js → watch-CIpoMaWD.js} +2 -2
  96. package/vendor/runtime/dist/{watch-BE-kKa7o.js.map → watch-CIpoMaWD.js.map} +1 -1
  97. package/vendor/runtime/package.json +1 -1
  98. package/vendor/runtime/skills/acpx/SKILL.md +7 -2
  99. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +0 -1
  100. package/vendor/runtime/dist/ipc-CLv2iL89.js.map +0 -1
  101. package/vendor/runtime/dist/output-I-t-v55D.js.map +0 -1
  102. package/vendor/runtime/dist/queue-owner-runtime-RN3uSid0.js.map +0 -1
  103. package/vendor/runtime/dist/session-options-DNnDfiUt.d.ts.map +0 -1
@@ -0,0 +1,260 @@
1
+ /** Durable admission to host-owned conversation queues; acceptance is not business completion. */
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { z } from 'zod';
6
+ import { deliverSessionMessage, SessionDeliveryError } from './session-hosts.js';
7
+ const id = z.string().trim().min(1).max(512);
8
+ export const sessionOriginSchema = z.object({ originSessionId: id }).strict();
9
+ export const sessionBindSchema = sessionOriginSchema.extend({ host: id, sessionId: id }).strict();
10
+ export const sessionMessageSchema = sessionOriginSchema.extend({ messageId: id }).strict();
11
+ export const sessionSendSchema = sessionMessageSchema.extend({ text: z.string().min(1).max(256 * 1024).refine(value => Boolean(value.trim())) }).strict();
12
+ export const sessionResolveSchema = sessionMessageSchema.extend({ accepted: z.boolean(), note: id, hostReceiptId: id.optional() }).strict();
13
+ const bindingSchema = sessionBindSchema.extend({ createdAt: id, hostFingerprint: id }).strict();
14
+ const deliverySchema = bindingSchema.extend({
15
+ messageId: id, text: sessionSendSchema.shape.text,
16
+ status: z.enum(['pending', 'dispatching', 'retrying', 'accepted', 'unknown', 'rejected']),
17
+ attempts: z.number().int().nonnegative(), updatedAt: id,
18
+ nextAttemptAt: id.optional(), hostReceiptId: id.optional(), error: id.optional(),
19
+ processedAt: id.optional(), resolutionNote: id.optional(),
20
+ }).strict();
21
+ const stateSchema = z.object({ version: z.literal(1), bindings: z.array(bindingSchema), deliveries: z.array(deliverySchema) }).strict();
22
+ /** Credentials may rotate; a host alias must never silently redirect saved messages. */
23
+ function fingerprint(host) {
24
+ const { headers, timeoutMs, ...locator } = host;
25
+ return createHash('sha256').update(JSON.stringify(Object.fromEntries(Object.entries(locator).sort(([a], [b]) => a.localeCompare(b))))).digest('hex');
26
+ }
27
+ function receipt(delivery) {
28
+ const { text, hostFingerprint, ...view } = delivery;
29
+ return { ...view };
30
+ }
31
+ /** Owned by the gateway's single-writer storage lease. */
32
+ export class SessionDelivery {
33
+ hosts;
34
+ file;
35
+ state;
36
+ controller = new AbortController();
37
+ pumping;
38
+ closed = false;
39
+ storageFailed = false;
40
+ constructor(directory, hosts) {
41
+ this.hosts = hosts;
42
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
43
+ this.file = path.join(directory, 'session-delivery.json');
44
+ try {
45
+ this.state = stateSchema.parse(JSON.parse(readFileSync(this.file, 'utf8')));
46
+ const origins = new Set(), messages = new Set();
47
+ for (const binding of this.state.bindings) {
48
+ if (origins.has(binding.originSessionId))
49
+ throw new Error('Duplicate session binding');
50
+ origins.add(binding.originSessionId);
51
+ }
52
+ for (const delivery of this.state.deliveries) {
53
+ const key = JSON.stringify([delivery.originSessionId, delivery.messageId]);
54
+ if (messages.has(key))
55
+ throw new Error('Duplicate session delivery');
56
+ messages.add(key);
57
+ const binding = this.state.bindings.find(value => value.originSessionId === delivery.originSessionId);
58
+ if (!binding || binding.host !== delivery.host || binding.sessionId !== delivery.sessionId || binding.hostFingerprint !== delivery.hostFingerprint)
59
+ throw new Error('Session delivery binding mismatch');
60
+ if (delivery.status === 'dispatching') {
61
+ delivery.status = 'unknown';
62
+ delivery.error = 'Gateway restarted during host admission; verify the host before resolving';
63
+ delivery.updatedAt = new Date().toISOString();
64
+ }
65
+ }
66
+ this.save();
67
+ }
68
+ catch (error) {
69
+ if (error.code !== 'ENOENT')
70
+ throw error;
71
+ this.state = { version: 1, bindings: [], deliveries: [] };
72
+ }
73
+ }
74
+ save() {
75
+ if (this.storageFailed)
76
+ throw new Error('Session delivery storage is unavailable; repair storage and restart the gateway');
77
+ const temporary = `${this.file}.${randomUUID()}.tmp`;
78
+ try {
79
+ const fd = openSync(temporary, 'wx', 0o600);
80
+ try {
81
+ writeFileSync(fd, JSON.stringify(this.state));
82
+ fsyncSync(fd);
83
+ }
84
+ finally {
85
+ closeSync(fd);
86
+ }
87
+ renameSync(temporary, this.file);
88
+ const dir = openSync(path.dirname(this.file), 'r');
89
+ try {
90
+ fsyncSync(dir);
91
+ }
92
+ finally {
93
+ closeSync(dir);
94
+ }
95
+ }
96
+ catch {
97
+ this.storageFailed = true;
98
+ throw new Error('Session delivery storage is unavailable; repair storage and restart the gateway');
99
+ }
100
+ }
101
+ get healthy() { return !this.storageFailed; }
102
+ requireWritable() {
103
+ if (this.closed)
104
+ throw new Error('Session delivery is closed');
105
+ if (this.storageFailed)
106
+ throw new Error('Session delivery storage is unavailable; repair storage and restart the gateway');
107
+ }
108
+ hasBinding(originSessionId) { return this.state.bindings.some(value => value.originSessionId === originSessionId); }
109
+ hasDelivery(originSessionId, messageId) {
110
+ return this.state.deliveries.some(value => value.originSessionId === originSessionId && value.messageId === messageId);
111
+ }
112
+ bind(input) {
113
+ this.requireWritable();
114
+ const host = this.hosts[input.host];
115
+ if (!host)
116
+ throw new Error('Unknown session host');
117
+ if (host.kind === 'codex' && !z.uuid().safeParse(input.sessionId).success)
118
+ throw new Error('Codex session ID must be a thread UUID');
119
+ const previous = this.state.bindings.find(value => value.originSessionId === input.originSessionId);
120
+ if (previous) {
121
+ if (previous.host !== input.host || previous.sessionId !== input.sessionId || previous.hostFingerprint !== fingerprint(host))
122
+ throw new Error('Origin session is already bound to a different host or session');
123
+ const { hostFingerprint, ...view } = previous;
124
+ return { ...view };
125
+ }
126
+ const binding = { ...input, hostFingerprint: fingerprint(host), createdAt: new Date().toISOString() };
127
+ this.state.bindings.push(binding);
128
+ try {
129
+ this.save();
130
+ }
131
+ catch (error) {
132
+ this.state.bindings.pop();
133
+ throw error;
134
+ }
135
+ const { hostFingerprint, ...view } = binding;
136
+ return view;
137
+ }
138
+ enqueue(input) {
139
+ this.requireWritable();
140
+ const previous = this.state.deliveries.find(value => value.originSessionId === input.originSessionId && value.messageId === input.messageId);
141
+ if (previous) {
142
+ if (previous.text !== input.text)
143
+ throw new Error('Message ID was already used for different content');
144
+ return receipt(previous);
145
+ }
146
+ const binding = this.state.bindings.find(value => value.originSessionId === input.originSessionId);
147
+ if (!binding)
148
+ throw new Error('Origin session is not bound');
149
+ const now = new Date().toISOString();
150
+ const delivery = { ...binding, messageId: input.messageId, text: input.text, createdAt: now, updatedAt: now, attempts: 0, status: 'pending' };
151
+ this.state.deliveries.push(delivery);
152
+ try {
153
+ this.save();
154
+ }
155
+ catch (error) {
156
+ this.state.deliveries.pop();
157
+ throw error;
158
+ }
159
+ return receipt(delivery);
160
+ }
161
+ get(input) { this.requireWritable(); return receipt(this.find(input)); }
162
+ find(input) {
163
+ const delivery = this.state.deliveries.find(value => value.originSessionId === input.originSessionId && value.messageId === input.messageId);
164
+ if (!delivery)
165
+ throw new Error('Delivery not found for this origin session');
166
+ return delivery;
167
+ }
168
+ resolve(input) {
169
+ this.requireWritable();
170
+ const delivery = this.find(input);
171
+ if (!['unknown', 'rejected'].includes(delivery.status))
172
+ throw new Error('Only unknown or rejected host admission can be resolved');
173
+ delivery.status = input.accepted ? 'accepted' : 'pending';
174
+ delivery.resolutionNote = input.note;
175
+ if (input.hostReceiptId)
176
+ delivery.hostReceiptId = input.hostReceiptId;
177
+ delivery.updatedAt = new Date().toISOString();
178
+ delete delivery.error;
179
+ delete delivery.nextAttemptAt;
180
+ this.save();
181
+ return receipt(delivery);
182
+ }
183
+ acknowledgeNotice(originSessionId, noticeId) {
184
+ this.acknowledgeMessage(originSessionId, `a2a-notice:${noticeId}`);
185
+ }
186
+ acknowledgeMessage(originSessionId, messageId) {
187
+ this.requireWritable();
188
+ const delivery = this.state.deliveries.find(value => value.originSessionId === originSessionId && value.messageId === messageId);
189
+ if (delivery && !delivery.processedAt) {
190
+ delivery.processedAt = new Date().toISOString();
191
+ delivery.updatedAt = delivery.processedAt;
192
+ this.save();
193
+ }
194
+ }
195
+ async reconcile() {
196
+ if (this.closed || this.storageFailed)
197
+ return;
198
+ if (this.pumping)
199
+ return this.pumping;
200
+ const run = async () => {
201
+ const origins = new Set(this.state.deliveries.map(value => value.originSessionId));
202
+ await Promise.allSettled([...origins].map(async (origin) => {
203
+ if (this.closed || this.storageFailed)
204
+ return;
205
+ // The first unresolved admission holds later messages in FIFO order.
206
+ const delivery = this.state.deliveries.find(value => value.originSessionId === origin && value.status !== 'accepted' && !value.processedAt);
207
+ if (!delivery || ['unknown', 'rejected', 'dispatching'].includes(delivery.status))
208
+ return;
209
+ if (delivery.nextAttemptAt && Date.parse(delivery.nextAttemptAt) > Date.now())
210
+ return;
211
+ const host = this.hosts[delivery.host];
212
+ if (!host || fingerprint(host) !== delivery.hostFingerprint) {
213
+ delivery.status = 'unknown';
214
+ delivery.error = 'Saved host configuration is missing or its destination changed';
215
+ delivery.updatedAt = new Date().toISOString();
216
+ this.save();
217
+ return;
218
+ }
219
+ delivery.status = 'dispatching';
220
+ delivery.attempts++;
221
+ delivery.updatedAt = new Date().toISOString();
222
+ delete delivery.nextAttemptAt;
223
+ this.save();
224
+ try {
225
+ // Host deduplication must preserve the ledger's origin/message scope.
226
+ const hostMessageId = `1agents-session:${createHash('sha256').update(JSON.stringify([delivery.originSessionId, delivery.messageId])).digest('hex')}`;
227
+ const result = await deliverSessionMessage(host, { sessionId: delivery.sessionId, messageId: hostMessageId, text: delivery.text }, this.controller.signal);
228
+ delivery.status = 'accepted';
229
+ delivery.hostReceiptId = result.hostReceiptId;
230
+ delete delivery.error;
231
+ }
232
+ catch (error) {
233
+ if (error instanceof SessionDeliveryError && error.retryable && !error.outcomeUnknown) {
234
+ delivery.status = 'retrying';
235
+ delivery.nextAttemptAt = new Date(Date.now() + Math.min(60_000, 1000 * 2 ** Math.min(delivery.attempts - 1, 6))).toISOString();
236
+ }
237
+ else
238
+ delivery.status = error instanceof SessionDeliveryError && !error.outcomeUnknown ? 'rejected' : 'unknown';
239
+ delivery.error = error instanceof SessionDeliveryError ? error.message : 'Host admission failed; verify delivery before retrying';
240
+ }
241
+ delivery.updatedAt = new Date().toISOString();
242
+ this.save();
243
+ }));
244
+ };
245
+ this.pumping = run();
246
+ try {
247
+ await this.pumping;
248
+ }
249
+ finally {
250
+ this.pumping = undefined;
251
+ }
252
+ }
253
+ async close() {
254
+ if (this.closed)
255
+ return;
256
+ this.closed = true;
257
+ this.controller.abort();
258
+ await this.pumping;
259
+ }
260
+ }
@@ -0,0 +1,34 @@
1
+ import { z } from 'zod';
2
+ export declare const sessionHostSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
3
+ kind: z.ZodLiteral<"codex">;
4
+ executable: z.ZodDefault<z.ZodString>;
5
+ remote: z.ZodOptional<z.ZodString>;
6
+ remoteAuthTokenEnv: z.ZodOptional<z.ZodString>;
7
+ cwd: z.ZodOptional<z.ZodString>;
8
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
9
+ }, z.core.$strict>, z.ZodObject<{
10
+ kind: z.ZodLiteral<"dsh">;
11
+ url: z.ZodString;
12
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
13
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
14
+ }, z.core.$strict>], "kind">;
15
+ export type SessionHost = z.output<typeof sessionHostSchema>;
16
+ /** Safe delivery failure; an unknown host outcome must never be retried automatically. */
17
+ export declare class SessionDeliveryError extends Error {
18
+ readonly retryable: boolean;
19
+ readonly outcomeUnknown: boolean;
20
+ constructor(message: string, options: {
21
+ retryable: boolean;
22
+ outcomeUnknown: boolean;
23
+ });
24
+ }
25
+ type Message = {
26
+ sessionId: string;
27
+ messageId: string;
28
+ text: string;
29
+ };
30
+ /** Queue one message without starting a new host session or changing its configuration. */
31
+ export declare function deliverSessionMessage(host: SessionHost, input: Message, signal?: AbortSignal): Promise<{
32
+ hostReceiptId?: string;
33
+ }>;
34
+ export {};
@@ -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
+ }
@@ -6,6 +6,7 @@ import { InMemoryTaskStore, resolveUserScope, ServerCallContext, } from '@a2a-js
6
6
  import { RequestMalformedError } from '@a2a-js/sdk/errors';
7
7
  import { toSafeError } from '@1agents/acp-service/runtime';
8
8
  import { DirectoryLease } from './lease.js';
9
+ import { a2aPreflightReportSchema } from './preflight.js';
9
10
  const terminalStates = new Set([
10
11
  TaskState.TASK_STATE_COMPLETED, TaskState.TASK_STATE_FAILED,
11
12
  TaskState.TASK_STATE_CANCELED, TaskState.TASK_STATE_REJECTED,
@@ -72,7 +73,8 @@ function parseTarget(value) {
72
73
  if (!isAbsolute(cwd))
73
74
  throw new Error('Invalid A2A working directory: expected an absolute path');
74
75
  const agentPreset = source.agentPreset === undefined ? undefined : text(source.agentPreset, 'agent preset');
75
- 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 }) };
76
78
  }
77
79
  function validatePushUrl(value) {
78
80
  const url = text(value, 'push URL');
@@ -1,15 +1,46 @@
1
1
  /** Execution interfaces shared by DSH and future standalone A2A hosts. */
2
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
+ }
3
32
  export interface A2ATarget {
4
33
  sessionId: string;
5
34
  cwd: string;
6
35
  agentPreset?: string;
36
+ preflight?: A2APreflightReport;
7
37
  }
8
38
  /** Omitted location and preset reuse a saved context or the host defaults. */
9
39
  export interface A2APrepareInput {
10
40
  sessionId?: string;
11
41
  cwd?: string;
12
42
  agentPreset?: string;
43
+ preflight?: A2APreflightRequirements;
13
44
  }
14
45
  /** A single DSH turn's output, without transport or host dependencies. */
15
46
  export interface A2ARunResult {
@@ -23,6 +54,8 @@ export interface A2ARunResult {
23
54
  }
24
55
  /** Implementations own session admission, execution and precise cancellation. */
25
56
  export interface A2ABackend {
57
+ /** Does not allocate a session or submit a model prompt. */
58
+ preflight?(input: A2APreflightInput): Promise<A2APreflightReport>;
26
59
  /** Optional read-only reconciliation; never resumes or repeats execution. */
27
60
  recover?(target: A2ATarget, options: {
28
61
  requestId: string;