@1agents/acp-service 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,339 @@
1
+ /** Node HTTP A2A transport reusable by DSH and standalone hosts. */
2
+ import { createHash, timingSafeEqual } from 'node:crypto';
3
+ import { AgentCard, SSE_HEADERS, TaskState, formatSSEEvent } from '@a2a-js/sdk';
4
+ import { PushNotificationNotSupportedError, RequestMalformedError, UnsupportedOperationError } from '@a2a-js/sdk/errors';
5
+ import { DefaultExecutionEventBusManager, DefaultRequestHandler, JsonRpcTransportHandler, ServerCallContext, V1PushNotificationSerializer, resolveUserScope, validateVersion } from '@a2a-js/sdk/server';
6
+ import { A2ASessionExecutor, parseA2AInput } from './executor.js';
7
+ import { FileA2AStore } from './store.js';
8
+ function allowedCallback(config, origins) {
9
+ if (!origins.size)
10
+ throw new PushNotificationNotSupportedError('Configure pushNotificationOrigins to enable webhooks');
11
+ let url;
12
+ try {
13
+ url = new URL(config.url);
14
+ }
15
+ catch {
16
+ throw new RequestMalformedError('Webhook URL must be absolute');
17
+ }
18
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || !origins.has(url.origin))
19
+ throw new RequestMalformedError('Webhook origin is not allowed');
20
+ }
21
+ /** Callback I/O is ordered per scoped task, never awaited by SendMessage. */
22
+ class HttpPushSender {
23
+ store;
24
+ origins;
25
+ chains = new Map();
26
+ controllers = new Set();
27
+ stopped = false;
28
+ constructor(store, origins) {
29
+ this.store = store;
30
+ this.origins = origins;
31
+ }
32
+ send(event, context, task) {
33
+ const payload = event.payload;
34
+ if (!payload || this.stopped)
35
+ return Promise.resolve();
36
+ const taskId = payload.$case === 'task' ? payload.value.id : payload.value.taskId;
37
+ if (!taskId)
38
+ return Promise.resolve();
39
+ const key = JSON.stringify([context.tenant ?? '', resolveUserScope(context), taskId]);
40
+ const snapshot = structuredClone(event);
41
+ const prior = this.chains.get(key) ?? Promise.resolve();
42
+ const pending = prior.catch(() => { }).then(async () => {
43
+ if (this.stopped)
44
+ return;
45
+ const configs = await this.store.pushStore.load(taskId, context);
46
+ const body = new V1PushNotificationSerializer().serialize(snapshot, task);
47
+ await Promise.all(configs.map(async (config) => {
48
+ allowedCallback(config, this.origins);
49
+ const controller = new AbortController();
50
+ this.controllers.add(controller);
51
+ const timeout = setTimeout(() => controller.abort(), 5000);
52
+ try {
53
+ const headers = { 'Content-Type': body.contentType };
54
+ if (config.authentication?.scheme && config.authentication.credentials)
55
+ headers.Authorization = `${config.authentication.scheme} ${config.authentication.credentials}`;
56
+ else if (config.token)
57
+ headers['X-A2A-Notification-Token'] = config.token;
58
+ const response = await fetch(config.url, { method: 'POST', headers, body: body.body, signal: controller.signal, redirect: 'error' });
59
+ await response.body?.cancel();
60
+ if (!response.ok)
61
+ throw new Error(`A2A webhook delivery failed (HTTP ${response.status})`);
62
+ }
63
+ finally {
64
+ clearTimeout(timeout);
65
+ this.controllers.delete(controller);
66
+ }
67
+ }));
68
+ });
69
+ this.chains.set(key, pending);
70
+ const clean = () => { if (this.chains.get(key) === pending)
71
+ this.chains.delete(key); };
72
+ void pending.then(clean, clean);
73
+ return pending;
74
+ }
75
+ async close() {
76
+ this.stopped = true;
77
+ for (const controller of this.controllers)
78
+ controller.abort();
79
+ await Promise.allSettled(this.chains.values());
80
+ }
81
+ }
82
+ /** Reject unsupported input before creating a background task. */
83
+ class HostRequestHandler extends DefaultRequestHandler {
84
+ store;
85
+ executor;
86
+ options;
87
+ origins;
88
+ buses;
89
+ admissions = new Map();
90
+ constructor(card, store, executor, sender, options, origins) {
91
+ const buses = new DefaultExecutionEventBusManager();
92
+ super(card, store.taskStore, executor, buses, store.pushStore, sender);
93
+ this.store = store;
94
+ this.executor = executor;
95
+ this.options = options;
96
+ this.origins = origins;
97
+ this.buses = buses;
98
+ }
99
+ async validate(request, context) {
100
+ parseA2AInput(request, this.options);
101
+ if (request.message?.taskId && this.executor.isRunning(request.message.taskId))
102
+ throw new UnsupportedOperationError('Send a new task in the same context, or wait until this task requires input');
103
+ if (request.message?.taskId) {
104
+ const task = await this.store.taskStore.load(request.message.taskId, context);
105
+ if (task?.history.some(message => message.messageId === request.message?.messageId)) {
106
+ throw new RequestMalformedError('A continued task requires a new messageId');
107
+ }
108
+ }
109
+ if (request.configuration?.taskPushNotificationConfig)
110
+ allowedCallback(request.configuration.taskPushNotificationConfig, this.origins);
111
+ }
112
+ async sendMessage(request, context) {
113
+ const taskId = request.message?.taskId;
114
+ if (!taskId) {
115
+ await this.validate(request, context);
116
+ return super.sendMessage(request, context);
117
+ }
118
+ if (this.executor.isRunning(taskId))
119
+ throw new UnsupportedOperationError('This task already has an active execution');
120
+ const key = JSON.stringify([context.tenant ?? '', resolveUserScope(context), taskId]);
121
+ const previous = this.admissions.get(key) ?? Promise.resolve();
122
+ let unlock;
123
+ const lock = new Promise(resolve => { unlock = resolve; });
124
+ this.admissions.set(key, lock);
125
+ try {
126
+ await previous;
127
+ await this.validate(request, context);
128
+ return await super.sendMessage(request, context);
129
+ }
130
+ finally {
131
+ unlock();
132
+ if (this.admissions.get(key) === lock)
133
+ this.admissions.delete(key);
134
+ }
135
+ }
136
+ async *sendMessageStream(request, context) {
137
+ // The nonblocking SendMessage path keeps a persistence/notification drain
138
+ // alive even after the streaming HTTP consumer disconnects.
139
+ const result = await this.sendMessage({ ...request, configuration: {
140
+ acceptedOutputModes: request.configuration?.acceptedOutputModes ?? [],
141
+ taskPushNotificationConfig: request.configuration?.taskPushNotificationConfig,
142
+ historyLength: request.configuration?.historyLength,
143
+ returnImmediately: true,
144
+ } }, context);
145
+ if ('messageId' in result) {
146
+ yield { payload: { $case: 'message', value: result } };
147
+ return;
148
+ }
149
+ try {
150
+ yield* super.resubscribe({ tenant: request.tenant, id: result.id }, context);
151
+ }
152
+ catch (error) {
153
+ const task = await this.store.taskStore.load(result.id, context);
154
+ if (!(error instanceof UnsupportedOperationError) || !task || ![TaskState.TASK_STATE_COMPLETED, TaskState.TASK_STATE_FAILED, TaskState.TASK_STATE_CANCELED, TaskState.TASK_STATE_REJECTED].includes(task.status?.state ?? TaskState.TASK_STATE_UNSPECIFIED))
155
+ throw error;
156
+ yield { payload: { $case: 'task', value: task } };
157
+ }
158
+ }
159
+ async createTaskPushNotificationConfig(config, context) {
160
+ allowedCallback(config, this.origins);
161
+ return super.createTaskPushNotificationConfig(config, context);
162
+ }
163
+ async cancelTask(request, context) {
164
+ const task = await super.cancelTask(request, context);
165
+ this.buses.cleanupByTaskId(request.id, context);
166
+ return task;
167
+ }
168
+ }
169
+ /** Create the A2A 1.0 host without opening a port or importing DSH. */
170
+ export async function createA2AServer(options) {
171
+ if (!options.token?.trim())
172
+ throw new Error('A2A requires a bearer token');
173
+ const path = options.path ?? '/a2a';
174
+ if (!/^\/[a-z0-9/_-]+$/i.test(path) || path.endsWith('/'))
175
+ throw new Error('Invalid A2A route path');
176
+ const publicUrl = new URL(options.publicUrl);
177
+ if (!['http:', 'https:'].includes(publicUrl.protocol) || publicUrl.username || publicUrl.password || publicUrl.pathname !== '/' || publicUrl.search || publicUrl.hash)
178
+ throw new Error('publicUrl must be an HTTP(S) origin');
179
+ const origins = new Set((options.pushNotificationOrigins ?? []).map(value => {
180
+ const url = new URL(value);
181
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
182
+ throw new Error('pushNotificationOrigins must contain HTTP(S) origins');
183
+ return url.origin;
184
+ }));
185
+ const card = AgentCard.fromJSON({ name: '1agents DSH', description: 'Delegate text tasks to persistent DSH sessions and selected agent presets.', version: '1.0.0',
186
+ supportedInterfaces: [{ url: new URL(path, publicUrl).href, protocolBinding: 'JSONRPC', protocolVersion: '1.0' }],
187
+ capabilities: { streaming: true, pushNotifications: origins.size > 0 },
188
+ securitySchemes: { bearerAuth: { httpAuthSecurityScheme: { scheme: 'bearer' } } },
189
+ securityRequirements: [{ schemes: { bearerAuth: { list: [] } } }],
190
+ defaultInputModes: ['text/plain'], defaultOutputModes: ['text/plain'],
191
+ skills: [{ id: 'dsh-session', name: 'DSH session task', description: 'Create or resume a session using metadata.1agents.cwd, workspace and agentPreset; retain contextId to continue collaboration.', tags: ['dsh', 'project', 'role', 'async'] }] });
192
+ const store = new FileA2AStore(options.stateDirectory);
193
+ try {
194
+ await store.recoverInterrupted();
195
+ }
196
+ catch (error) {
197
+ store.close();
198
+ throw error;
199
+ }
200
+ const executor = new A2ASessionExecutor(options.backend, store, options);
201
+ const sender = new HttpPushSender(store, origins);
202
+ const requestHandler = new HostRequestHandler(card, store, executor, sender, options, origins);
203
+ const transport = new JsonRpcTransportHandler(requestHandler);
204
+ const tokenHash = createHash('sha256').update(options.token).digest();
205
+ const responses = new Set();
206
+ const requests = new Map();
207
+ let stopped = false;
208
+ const cardHandler = async (req, res) => {
209
+ if (req.method !== 'GET') {
210
+ res.writeHead(405, { Allow: 'GET' });
211
+ res.end();
212
+ return;
213
+ }
214
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
215
+ res.end(JSON.stringify(AgentCard.toJSON(card)));
216
+ };
217
+ const serve = async (req, res) => {
218
+ if (stopped) {
219
+ res.writeHead(503);
220
+ res.end();
221
+ return;
222
+ }
223
+ const authorization = req.headers.authorization;
224
+ if (!authorization?.startsWith('Bearer ') || !timingSafeEqual(tokenHash, createHash('sha256').update(authorization.slice(7)).digest())) {
225
+ res.writeHead(401, { 'WWW-Authenticate': 'Bearer', 'Content-Type': 'application/json' });
226
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
227
+ return;
228
+ }
229
+ if (req.method !== 'POST') {
230
+ res.writeHead(405, { Allow: 'POST' });
231
+ res.end();
232
+ return;
233
+ }
234
+ res.setHeader('A2A-Version', '1.0');
235
+ let id = null;
236
+ try {
237
+ const version = req.headers['a2a-version'];
238
+ validateVersion(typeof version === 'string' ? version : '0.3', card, 'JSONRPC');
239
+ let size = 0;
240
+ const chunks = [];
241
+ for await (const chunk of req) {
242
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
243
+ size += buffer.length;
244
+ if (size > 1024 * 1024)
245
+ throw new RequestMalformedError('Request body exceeds 1 MiB');
246
+ chunks.push(buffer);
247
+ }
248
+ const body = Buffer.concat(chunks).toString('utf8');
249
+ let decoded;
250
+ try {
251
+ decoded = JSON.parse(body);
252
+ }
253
+ catch {
254
+ throw new RequestMalformedError('Invalid JSON request');
255
+ }
256
+ if (decoded && typeof decoded === 'object' && !Array.isArray(decoded)) {
257
+ if (typeof decoded.id === 'string' || typeof decoded.id === 'number')
258
+ id = decoded.id;
259
+ const params = decoded.params;
260
+ const config = params?.configuration;
261
+ if (config?.returnImmediately !== undefined && typeof config.returnImmediately !== 'boolean')
262
+ throw new RequestMalformedError('returnImmediately must be boolean');
263
+ if (params?.historyLength !== undefined && (!Number.isSafeInteger(params.historyLength) || params.historyLength < 0))
264
+ throw new RequestMalformedError('historyLength must be a nonnegative integer');
265
+ if (config?.historyLength !== undefined && (!Number.isSafeInteger(config.historyLength) || config.historyLength < 0))
266
+ throw new RequestMalformedError('historyLength must be a nonnegative integer');
267
+ }
268
+ const context = new ServerCallContext({ requestedVersion: '1.0', user: { isAuthenticated: true, userName: 'dsh-a2a' } });
269
+ if (stopped) {
270
+ res.writeHead(503);
271
+ res.end();
272
+ return;
273
+ }
274
+ const result = await transport.handle(body, context);
275
+ if (!(Symbol.asyncIterator in result)) {
276
+ res.writeHead(200, { 'Content-Type': 'application/a2a+json', 'Cache-Control': 'no-store' });
277
+ res.end(JSON.stringify(result));
278
+ return;
279
+ }
280
+ const iterator = result[Symbol.asyncIterator]();
281
+ const first = await iterator.next();
282
+ res.writeHead(200, SSE_HEADERS);
283
+ res.flushHeaders();
284
+ responses.add(res);
285
+ const closed = Symbol('closed');
286
+ let onClose;
287
+ const disconnect = new Promise(resolve => { onClose = () => resolve(closed); res.once('close', onClose); });
288
+ try {
289
+ if (!first.done)
290
+ res.write(formatSSEEvent(first.value));
291
+ while (!first.done && !res.destroyed) {
292
+ const next = await Promise.race([iterator.next(), disconnect]);
293
+ if (next === closed || next.done)
294
+ break;
295
+ res.write(formatSSEEvent(next.value));
296
+ }
297
+ }
298
+ finally {
299
+ res.off('close', onClose);
300
+ responses.delete(res);
301
+ void iterator.return().catch(() => { });
302
+ if (!res.destroyed)
303
+ res.end();
304
+ }
305
+ }
306
+ catch (error) {
307
+ const envelope = { jsonrpc: '2.0', id, error: JsonRpcTransportHandler.mapToJSONRPCError(error) };
308
+ if (res.headersSent) {
309
+ if (!res.destroyed)
310
+ res.end(formatSSEEvent(envelope));
311
+ }
312
+ else {
313
+ res.writeHead(200, { 'Content-Type': 'application/a2a+json' });
314
+ res.end(JSON.stringify(envelope));
315
+ }
316
+ }
317
+ };
318
+ const handler = (req, res) => {
319
+ const pending = serve(req, res);
320
+ requests.set(req, pending);
321
+ const clean = () => { requests.delete(req); };
322
+ void pending.then(clean, clean);
323
+ return pending;
324
+ };
325
+ return { path, card, handler, cardHandler, close: async () => {
326
+ if (stopped)
327
+ return;
328
+ stopped = true;
329
+ for (const res of responses)
330
+ res.destroy();
331
+ for (const req of requests.keys())
332
+ req.destroy();
333
+ await executor.close();
334
+ await Promise.allSettled(requests.values());
335
+ await new Promise(resolve => setImmediate(resolve));
336
+ await sender.close();
337
+ store.close();
338
+ } };
339
+ }
@@ -0,0 +1,34 @@
1
+ import { ServerCallContext, type PushNotificationStore, type TaskStore } from '@a2a-js/sdk/server';
2
+ import type { A2ATarget } from './types.js';
3
+ /**
4
+ * A single-process, durable store shared by A2A transports and DSH hosts.
5
+ * Resource IDs never become paths; each record is keyed by tenant and SDK owner.
6
+ * The exclusive lock rejects a second live instance using the same directory.
7
+ */
8
+ export declare class FileA2AStore {
9
+ readonly taskStore: TaskStore;
10
+ readonly pushStore: PushNotificationStore;
11
+ private readonly directory;
12
+ private readonly lock;
13
+ private readonly memory;
14
+ private readonly tasks;
15
+ private readonly pushes;
16
+ private readonly targets;
17
+ private readonly ready;
18
+ private closed;
19
+ constructor(directory: string);
20
+ loadTarget(contextId: string, context: ServerCallContext): A2ATarget | undefined;
21
+ saveTarget(contextId: string, target: A2ATarget, context: ServerCallContext): void;
22
+ /** Persist failure for interrupted executions. A restart never reruns work. */
23
+ recoverInterrupted(): Promise<void>;
24
+ close(): void;
25
+ private loadPush;
26
+ private assertOpen;
27
+ private acquireLock;
28
+ private ownerName;
29
+ private ownerPath;
30
+ private removeEmptyLockDirectory;
31
+ private readJson;
32
+ private readEnvelope;
33
+ private writeEnvelope;
34
+ }