@1agents/acp-service 0.5.4 → 0.7.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.
Files changed (40) hide show
  1. package/README.md +180 -9
  2. package/dist/bin/a2a.d.ts +1 -0
  3. package/dist/bin/a2a.js +52 -0
  4. package/dist/bin/acp-service.js +20 -2
  5. package/dist/src/a2a/automation.d.ts +99 -0
  6. package/dist/src/a2a/automation.js +372 -0
  7. package/dist/src/a2a/executor.d.ts +29 -0
  8. package/dist/src/a2a/executor.js +144 -0
  9. package/dist/src/a2a/gateway.d.ts +151 -0
  10. package/dist/src/a2a/gateway.js +454 -0
  11. package/dist/src/a2a/index.d.ts +9 -0
  12. package/dist/src/a2a/index.js +5 -0
  13. package/dist/src/a2a/server.d.ts +22 -0
  14. package/dist/src/a2a/server.js +339 -0
  15. package/dist/src/a2a/store.d.ts +34 -0
  16. package/dist/src/a2a/store.js +468 -0
  17. package/dist/src/a2a/types.d.ts +26 -0
  18. package/dist/src/a2a/types.js +1 -0
  19. package/dist/src/acp-connection.js +3 -2
  20. package/dist/src/bridge.js +18 -3
  21. package/package.json +15 -8
  22. package/skills/acp-service/SKILL.md +90 -0
  23. package/skills/acp-service/agents/openai.yaml +3 -0
  24. package/skills/acp-service/references/a2a.md +183 -0
  25. package/skills/acp-service/references/acp.md +104 -0
  26. package/skills/acp-service/references/dsh.md +61 -0
  27. package/vendor/dsh/README.md +34 -10
  28. package/vendor/dsh/a2a-executor.d.ts +26 -0
  29. package/vendor/dsh/a2a-executor.js +195 -0
  30. package/vendor/dsh/a2a.d.ts +15 -0
  31. package/vendor/dsh/a2a.js +32 -0
  32. package/vendor/dsh/adapter.js +33 -10
  33. package/vendor/dsh/index.d.ts +5 -1
  34. package/vendor/dsh/index.js +3 -0
  35. package/vendor/runtime/dist/docs-site/output-formats.html +4 -1
  36. package/vendor/runtime/dist/runtime.d.ts +8 -0
  37. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  38. package/vendor/runtime/dist/runtime.js +3 -1
  39. package/vendor/runtime/dist/runtime.js.map +1 -1
  40. package/vendor/runtime/skills/acpx/SKILL.md +1 -0
@@ -0,0 +1,468 @@
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';
3
+ import { isAbsolute, join, resolve } from 'node:path';
4
+ import { Message, Role, Task, TaskPushNotificationConfig, TaskState } from '@a2a-js/sdk';
5
+ import { InMemoryTaskStore, resolveUserScope, ServerCallContext, } from '@a2a-js/sdk/server';
6
+ import { RequestMalformedError } from '@a2a-js/sdk/errors';
7
+ const terminalStates = new Set([
8
+ TaskState.TASK_STATE_COMPLETED, TaskState.TASK_STATE_FAILED,
9
+ TaskState.TASK_STATE_CANCELED, TaskState.TASK_STATE_REJECTED,
10
+ ]);
11
+ const maxRecordSize = 32 * 1024 * 1024;
12
+ function record(value, label) {
13
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
14
+ throw new Error(`Invalid A2A ${label}: expected an object`);
15
+ }
16
+ return value;
17
+ }
18
+ function text(value, label, allowEmpty = false) {
19
+ if (typeof value !== 'string' || (!allowEmpty && !value) || value.includes('\0')) {
20
+ throw new Error(`Invalid A2A ${label}: expected a${allowEmpty ? '' : ' non-empty'} string`);
21
+ }
22
+ return value;
23
+ }
24
+ function scopeOf(context) {
25
+ return { tenant: text(context.tenant ?? '', 'tenant', true), owner: text(resolveUserScope(context), 'owner') };
26
+ }
27
+ function key(scope, id) {
28
+ return JSON.stringify([scope.tenant, scope.owner, id]);
29
+ }
30
+ function fileName(kind, scope, id) {
31
+ const hash = createHash('sha256').update(JSON.stringify([kind, scope.tenant, scope.owner, id])).digest('hex');
32
+ return `${kind}-${hash}.json`;
33
+ }
34
+ function contextOf(scope) {
35
+ return new ServerCallContext({
36
+ tenant: scope.tenant || undefined,
37
+ user: { isAuthenticated: true, userName: scope.owner },
38
+ });
39
+ }
40
+ function parseTask(value) {
41
+ const source = record(value, 'task');
42
+ text(source.id, 'task ID');
43
+ text(source.contextId, 'context ID');
44
+ const status = record(source.status, 'task status');
45
+ if (status.timestamp !== undefined && (typeof status.timestamp !== 'string' || !Number.isFinite(Date.parse(status.timestamp))))
46
+ throw new Error('Invalid A2A task status timestamp');
47
+ for (const field of ['history', 'artifacts']) {
48
+ if (source[field] !== undefined && !Array.isArray(source[field])) {
49
+ throw new Error(`Invalid A2A task ${field}`);
50
+ }
51
+ }
52
+ const task = Task.fromJSON(source);
53
+ if (!task.status || task.status.state < 0 || task.status.state > TaskState.TASK_STATE_AUTH_REQUIRED) {
54
+ throw new Error('Invalid A2A task state');
55
+ }
56
+ for (const message of task.history) {
57
+ text(message.messageId, 'message ID');
58
+ if (message.role !== Role.ROLE_USER && message.role !== Role.ROLE_AGENT) {
59
+ throw new Error('Invalid A2A history message role');
60
+ }
61
+ }
62
+ for (const artifact of task.artifacts)
63
+ text(artifact.artifactId, 'artifact ID');
64
+ return task;
65
+ }
66
+ function parseTarget(value) {
67
+ const source = record(value, 'target');
68
+ const sessionId = text(source.sessionId, 'session ID');
69
+ const cwd = text(source.cwd, 'working directory');
70
+ if (!isAbsolute(cwd))
71
+ throw new Error('Invalid A2A working directory: expected an absolute path');
72
+ const agentPreset = source.agentPreset === undefined ? undefined : text(source.agentPreset, 'agent preset');
73
+ return { sessionId, cwd, ...(agentPreset === undefined ? {} : { agentPreset }) };
74
+ }
75
+ function validatePushUrl(value) {
76
+ const url = text(value, 'push URL');
77
+ let parsed;
78
+ try {
79
+ parsed = new URL(url);
80
+ }
81
+ catch {
82
+ throw new Error('Invalid A2A push URL');
83
+ }
84
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) {
85
+ throw new Error('A2A push URL must use HTTP(S) without embedded credentials');
86
+ }
87
+ return url;
88
+ }
89
+ function parsePush(value, taskId, scope) {
90
+ if (!Array.isArray(value))
91
+ throw new Error('Invalid A2A push configurations');
92
+ const ids = new Set();
93
+ return value.map(entry => {
94
+ const source = record(entry, 'push configuration');
95
+ if (source.wireVersion !== '1.0' && source.wireVersion !== '0.3') {
96
+ throw new Error('Invalid A2A push wire version');
97
+ }
98
+ const wire = record(source.config, 'push configuration');
99
+ text(wire.id, 'push configuration ID');
100
+ if (text(wire.taskId, 'push task ID') !== taskId)
101
+ throw new Error('A2A push task ID mismatch');
102
+ if (wire.tenant !== undefined && text(wire.tenant, 'push tenant', true) !== scope.tenant) {
103
+ throw new Error('A2A push tenant mismatch');
104
+ }
105
+ validatePushUrl(wire.url);
106
+ if (wire.token !== undefined)
107
+ text(wire.token, 'push token', true);
108
+ if (wire.authentication !== undefined) {
109
+ const authentication = record(wire.authentication, 'push authentication');
110
+ if (authentication.scheme !== undefined)
111
+ text(authentication.scheme, 'push authentication scheme', true);
112
+ if (authentication.credentials !== undefined)
113
+ text(authentication.credentials, 'push authentication credentials', true);
114
+ }
115
+ const config = TaskPushNotificationConfig.fromJSON(wire);
116
+ if (ids.has(config.id))
117
+ throw new Error('Duplicate A2A push configuration ID');
118
+ ids.add(config.id);
119
+ return { config, wireVersion: source.wireVersion };
120
+ });
121
+ }
122
+ /**
123
+ * A single-process, durable store shared by A2A transports and DSH hosts.
124
+ * Resource IDs never become paths; each record is keyed by tenant and SDK owner.
125
+ * The exclusive lock rejects a second live instance using the same directory.
126
+ */
127
+ export class FileA2AStore {
128
+ taskStore;
129
+ pushStore;
130
+ directory;
131
+ lock = { pid: process.pid, token: randomUUID() };
132
+ memory = new InMemoryTaskStore();
133
+ tasks = new Map();
134
+ pushes = new Map();
135
+ targets = new Map();
136
+ ready;
137
+ closed = false;
138
+ constructor(directory) {
139
+ this.directory = resolve(directory);
140
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 });
141
+ const stat = lstatSync(this.directory);
142
+ if (!stat.isDirectory() || stat.isSymbolicLink())
143
+ throw new Error('A2A storage directory must be a real directory');
144
+ chmodSync(this.directory, 0o700);
145
+ this.acquireLock();
146
+ try {
147
+ const loads = [];
148
+ for (const name of readdirSync(this.directory)) {
149
+ if (!/^(task|push|target)-[a-f0-9]{64}\.json$/.test(name))
150
+ continue;
151
+ const envelope = this.readEnvelope(name);
152
+ const { kind, scope, id, value } = envelope;
153
+ if (kind === 'task') {
154
+ const task = parseTask(value);
155
+ if (task.id !== id)
156
+ throw new Error('A2A stored task ID mismatch');
157
+ this.tasks.set(key(scope, id), { scope, task });
158
+ loads.push(this.memory.save(task, contextOf(scope)));
159
+ }
160
+ else if (kind === 'push') {
161
+ this.pushes.set(key(scope, id), parsePush(value, id, scope));
162
+ }
163
+ else {
164
+ this.targets.set(key(scope, id), parseTarget(value));
165
+ }
166
+ }
167
+ this.ready = Promise.all(loads);
168
+ }
169
+ catch (error) {
170
+ this.close();
171
+ throw error;
172
+ }
173
+ this.taskStore = {
174
+ save: async (task, context) => {
175
+ this.assertOpen();
176
+ const scope = scopeOf(context);
177
+ // Roundtrip through JSON as well as the SDK codec so cached metadata
178
+ // cannot retain references owned by the caller or non-JSON values.
179
+ const normalized = parseTask(JSON.parse(JSON.stringify(Task.toJSON(task))));
180
+ this.writeEnvelope('task', scope, normalized.id, Task.toJSON(normalized));
181
+ this.tasks.set(key(scope, normalized.id), { scope, task: normalized });
182
+ await this.ready;
183
+ await this.memory.save(normalized, context);
184
+ },
185
+ load: async (id, context) => {
186
+ this.assertOpen();
187
+ text(id, 'task ID');
188
+ scopeOf(context);
189
+ await this.ready;
190
+ return this.memory.load(id, context);
191
+ },
192
+ list: async (params, context) => {
193
+ this.assertOpen();
194
+ scopeOf(context);
195
+ await this.ready;
196
+ const result = await this.memory.list(params, context);
197
+ // SDK pagination/filtering stays authoritative; its current list omits
198
+ // historyLength, which the protocol also applies to each returned task.
199
+ if (params.historyLength !== undefined) {
200
+ if (!Number.isInteger(params.historyLength) || params.historyLength < 0) {
201
+ throw new RequestMalformedError('historyLength must be a non-negative integer');
202
+ }
203
+ for (const task of result.tasks) {
204
+ task.history = params.historyLength === 0 ? [] : task.history.slice(-params.historyLength);
205
+ }
206
+ }
207
+ return result;
208
+ },
209
+ };
210
+ this.pushStore = {
211
+ save: async (taskId, context, supplied) => {
212
+ this.assertOpen();
213
+ text(taskId, 'task ID');
214
+ const scope = scopeOf(context);
215
+ if (supplied.taskId && supplied.taskId !== taskId)
216
+ throw new RequestMalformedError('Push task ID mismatch');
217
+ if (supplied.tenant && supplied.tenant !== scope.tenant)
218
+ throw new RequestMalformedError('Push tenant mismatch');
219
+ try {
220
+ validatePushUrl(supplied.url);
221
+ }
222
+ catch (error) {
223
+ throw new RequestMalformedError(error.message);
224
+ }
225
+ const wireVersion = context.requestedVersion;
226
+ if (wireVersion !== '1.0' && wireVersion !== '0.3') {
227
+ throw new RequestMalformedError('Unsupported push wire version');
228
+ }
229
+ if (!supplied.id)
230
+ supplied.id = randomUUID();
231
+ const config = TaskPushNotificationConfig.fromJSON(TaskPushNotificationConfig.toJSON({
232
+ ...supplied, taskId, tenant: scope.tenant,
233
+ }));
234
+ const current = [...(this.pushes.get(key(scope, taskId)) ?? [])].filter(entry => entry.config.id !== config.id);
235
+ current.push({ config, wireVersion });
236
+ const serialized = current.map(entry => ({
237
+ config: TaskPushNotificationConfig.toJSON(entry.config), wireVersion: entry.wireVersion,
238
+ }));
239
+ const entries = parsePush(serialized, taskId, scope);
240
+ this.writeEnvelope('push', scope, taskId, serialized);
241
+ this.pushes.set(key(scope, taskId), entries);
242
+ },
243
+ load: async (taskId, context) => this.loadPush(taskId, context).map(entry => entry.config),
244
+ loadWithMetadata: async (taskId, context) => this.loadPush(taskId, context),
245
+ delete: async (taskId, context, configId) => {
246
+ this.assertOpen();
247
+ text(taskId, 'task ID');
248
+ const scope = scopeOf(context);
249
+ // Match the SDK default: omitted configId refers to the task ID.
250
+ const entries = (this.pushes.get(key(scope, taskId)) ?? [])
251
+ .filter(entry => entry.config.id !== (configId ?? taskId));
252
+ this.writeEnvelope('push', scope, taskId, entries.map(entry => ({
253
+ config: TaskPushNotificationConfig.toJSON(entry.config), wireVersion: entry.wireVersion,
254
+ })));
255
+ this.pushes.set(key(scope, taskId), entries);
256
+ },
257
+ };
258
+ }
259
+ loadTarget(contextId, context) {
260
+ this.assertOpen();
261
+ text(contextId, 'context ID');
262
+ const target = this.targets.get(key(scopeOf(context), contextId));
263
+ return target && structuredClone(target);
264
+ }
265
+ saveTarget(contextId, target, context) {
266
+ this.assertOpen();
267
+ text(contextId, 'context ID');
268
+ const scope = scopeOf(context);
269
+ const normalized = parseTarget(target);
270
+ this.writeEnvelope('target', scope, contextId, normalized);
271
+ this.targets.set(key(scope, contextId), normalized);
272
+ }
273
+ /** Persist failure for interrupted executions. A restart never reruns work. */
274
+ async recoverInterrupted() {
275
+ this.assertOpen();
276
+ await this.ready;
277
+ for (const { scope, task } of [...this.tasks.values()]) {
278
+ if (task.status && terminalStates.has(task.status.state))
279
+ continue;
280
+ const message = Message.fromJSON({
281
+ messageId: randomUUID(), contextId: task.contextId, taskId: task.id,
282
+ role: 'ROLE_AGENT',
283
+ parts: [{ text: 'Execution was interrupted by an A2A service restart and was not restarted.' }],
284
+ });
285
+ await this.taskStore.save({
286
+ ...task,
287
+ status: { state: TaskState.TASK_STATE_FAILED, timestamp: new Date().toISOString(), message },
288
+ history: [...task.history, message],
289
+ }, contextOf(scope));
290
+ }
291
+ }
292
+ close() {
293
+ if (this.closed)
294
+ return;
295
+ 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();
309
+ }
310
+ loadPush(taskId, context) {
311
+ this.assertOpen();
312
+ text(taskId, 'task ID');
313
+ return structuredClone(this.pushes.get(key(scopeOf(context), taskId)) ?? []);
314
+ }
315
+ assertOpen() {
316
+ if (this.closed)
317
+ throw new Error('A2A store is closed');
318
+ }
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
+ readJson(path) {
416
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
417
+ try {
418
+ const stat = fstatSync(fd);
419
+ if (!stat.isFile() || stat.size > maxRecordSize)
420
+ throw new Error('Invalid A2A storage file');
421
+ return JSON.parse(readFileSync(fd, 'utf8'));
422
+ }
423
+ finally {
424
+ closeSync(fd);
425
+ }
426
+ }
427
+ readEnvelope(name) {
428
+ const path = join(this.directory, name);
429
+ const source = record(this.readJson(path), 'storage record');
430
+ if (source.version !== 1 || !['task', 'push', 'target'].includes(source.kind)) {
431
+ throw new Error('Invalid A2A storage record version or kind');
432
+ }
433
+ const rawScope = record(source.scope, 'stored scope');
434
+ const scope = { tenant: text(rawScope.tenant, 'stored tenant', true), owner: text(rawScope.owner, 'stored owner') };
435
+ const id = text(source.id, 'stored resource ID');
436
+ const kind = source.kind;
437
+ if (fileName(kind, scope, id) !== name)
438
+ throw new Error('A2A storage record filename does not match its scope');
439
+ chmodSync(path, 0o600);
440
+ return { version: 1, kind, scope, id, value: source.value };
441
+ }
442
+ writeEnvelope(kind, scope, id, value) {
443
+ const envelope = { version: 1, kind, scope, id, value };
444
+ const data = JSON.stringify(envelope) + '\n';
445
+ if (Buffer.byteLength(data) > maxRecordSize)
446
+ throw new Error('A2A storage record is too large');
447
+ const temporary = join(this.directory, `.tmp-${randomUUID()}`);
448
+ const destination = join(this.directory, fileName(kind, scope, id));
449
+ try {
450
+ const fd = openSync(temporary, 'wx', 0o600);
451
+ try {
452
+ writeFileSync(fd, data);
453
+ fsyncSync(fd);
454
+ }
455
+ finally {
456
+ closeSync(fd);
457
+ }
458
+ renameSync(temporary, destination);
459
+ }
460
+ catch (error) {
461
+ try {
462
+ unlinkSync(temporary);
463
+ }
464
+ catch { /* Nothing to remove after rename. */ }
465
+ throw error;
466
+ }
467
+ }
468
+ }
@@ -0,0 +1,26 @@
1
+ /** Execution interfaces shared by DSH and future standalone A2A hosts. */
2
+ export interface A2ATarget {
3
+ sessionId: string;
4
+ cwd: string;
5
+ agentPreset?: string;
6
+ }
7
+ /** Omitted location and preset reuse a saved context or the host defaults. */
8
+ export interface A2APrepareInput {
9
+ sessionId?: string;
10
+ cwd?: string;
11
+ agentPreset?: string;
12
+ }
13
+ /** A single DSH turn's output, without transport or host dependencies. */
14
+ export interface A2ARunResult {
15
+ text: string;
16
+ outcome: 'completed' | 'failed' | 'input-required';
17
+ detail?: string;
18
+ }
19
+ /** Implementations own session admission, execution and precise cancellation. */
20
+ export interface A2ABackend {
21
+ prepare(input: A2APrepareInput): Promise<A2ATarget>;
22
+ run(target: A2ATarget, prompt: string, options: {
23
+ requestId: string;
24
+ signal: AbortSignal;
25
+ }): Promise<A2ARunResult>;
26
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -107,7 +107,7 @@ function envelope(value) {
107
107
  function updateFor(event, toolUpdate = false) {
108
108
  const common = { _meta: envelope(event) };
109
109
  switch (event.event) {
110
- case 'text_delta': return { ...common, sessionUpdate: event.type === 'thought' ? 'agent_thought_chunk' : 'agent_message_chunk', content: { type: 'text', text: event.text || '' } };
110
+ case 'text_delta': return { ...common, ...(event.messageId ? { messageId: event.messageId } : {}), sessionUpdate: event.type === 'thought' ? 'agent_thought_chunk' : 'agent_message_chunk', content: { type: 'text', text: event.text || '' } };
111
111
  case 'tool_call': {
112
112
  const fields = { ...common, toolCallId: event.toolCallId, title: event.title ?? event.toolName, status: event.status,
113
113
  kind: event.kind, rawInput: event.arguments, rawOutput: event.rawOutput, content: event.content, locations: event.locations };
@@ -271,7 +271,8 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
271
271
  const terminal = (event.event === 'turn_state' && ['completed', 'failed', 'cancelled'].includes(event.status)) || event.event === 'done' || event.event === 'turn_terminal' || (event.event === 'error' && event.terminal !== false && event.scope === 'turn');
272
272
  if (terminal) {
273
273
  if (summary && event.event !== 'turn_state') {
274
- event = { ...event, responsePolicy: 'summary', resultText: event.finalAnswer || answers.get(sessionId) || '', summary: event.finalAnswer || answers.get(sessionId) || event.summary, sessionRef: { sessionId, turnId: event.turnId } };
274
+ const finalAnswer = event.finalAnswer ?? event.resultText ?? answers.get(sessionId) ?? event.summary ?? '';
275
+ event = { ...event, responsePolicy: 'summary', resultText: finalAnswer, summary: finalAnswer, sessionRef: { sessionId, turnId: event.turnId } };
275
276
  if (extensions)
276
277
  notify(`${EXT}events/turn_complete`, { ...event, event: undefined });
277
278
  }
@@ -936,6 +936,7 @@ function sendSummaryTerminal(ws, session, sessionId, payload) {
936
936
  status: payload.status,
937
937
  responsePolicy: "summary",
938
938
  resultText,
939
+ finalAnswer: resultText,
939
940
  sessionRef,
940
941
  completedAt: new Date().toISOString(),
941
942
  ...(payload.error ? { error: payload.error } : {}),
@@ -946,6 +947,7 @@ function sendSummaryTerminal(ws, session, sessionId, payload) {
946
947
  status: payload.status,
947
948
  responsePolicy: "summary",
948
949
  resultText,
950
+ finalAnswer: resultText,
949
951
  sessionRef,
950
952
  summary: resultText ||
951
953
  (payload.status === "failed"
@@ -2438,6 +2440,8 @@ async function runPromptTurn(session, sessionId, promptItem) {
2438
2440
  session.activeTurn = turn;
2439
2441
  let terminalSent = false;
2440
2442
  let accumulatedAnswer = "";
2443
+ let hasMessagePhase = false;
2444
+ let finalAnswer = "";
2441
2445
  void (async () => {
2442
2446
  try {
2443
2447
  for await (const event of turn.events) {
@@ -2445,6 +2449,11 @@ async function runPromptTurn(session, sessionId, promptItem) {
2445
2449
  const streamType = event.stream || "output";
2446
2450
  if (streamType === "output") {
2447
2451
  accumulatedAnswer += event.text || "";
2452
+ if (event.messagePhase === "commentary" || event.messagePhase === "final_answer") {
2453
+ hasMessagePhase = true;
2454
+ if (event.messagePhase === "final_answer")
2455
+ finalAnswer += event.text || "";
2456
+ }
2448
2457
  }
2449
2458
  }
2450
2459
  else if (event.type === "status" &&
@@ -2471,6 +2480,8 @@ async function runPromptTurn(session, sessionId, promptItem) {
2471
2480
  text: event.text,
2472
2481
  type: event.stream || "output",
2473
2482
  ...(event.agentTurnId ? { agentTurnId: event.agentTurnId } : {}),
2483
+ ...(event.messageId ? { messageId: event.messageId } : {}),
2484
+ ...(event.messagePhase ? { messagePhase: event.messagePhase } : {}),
2474
2485
  });
2475
2486
  }
2476
2487
  else if (event.type === "tool_call") {
@@ -2592,7 +2603,10 @@ async function runPromptTurn(session, sessionId, promptItem) {
2592
2603
  console.log(`[acpx-server] Turn finished for session: ${sessionId}. Status: ${result.status}`);
2593
2604
  const currentSession = activeSessions.get(sessionId);
2594
2605
  const targetWs = currentSession ? currentSession.ws : null;
2595
- const finalResultText = result.finalAnswer || accumulatedAnswer || "";
2606
+ // An explicit terminal answer is authoritative, including an empty one.
2607
+ // Otherwise select only final-answer phases, while retaining every message
2608
+ // in the execution log. Unphased agents keep their legacy stream fallback.
2609
+ const finalResultText = result.finalAnswer ?? (hasMessagePhase ? finalAnswer : accumulatedAnswer);
2596
2610
  const journalTerminal = turn.hostTurnId
2597
2611
  ? await turnJournal.record({
2598
2612
  sessionId,
@@ -2601,7 +2615,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2601
2615
  status: result.status,
2602
2616
  promptText: promptItem.text,
2603
2617
  agentType: currentSession?.agentType || session.agentType,
2604
- finalAnswer: result.finalAnswer || finalResultText || undefined,
2618
+ finalAnswer: finalResultText,
2605
2619
  errorCode: result.status === "failed" ? result.error?.code || "ACP_PROMPT_FAILED" : undefined,
2606
2620
  errorText: result.status === "failed" ? result.error?.message : undefined,
2607
2621
  runtimeRecordId: currentSession?.handle?.acpxRecordId || session.handle?.acpxRecordId || sessionId,
@@ -2637,7 +2651,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2637
2651
  status: result.status,
2638
2652
  journalSequence: journalTerminal.turn.lastEventSeq,
2639
2653
  stopReason: result.stopReason || (result.status === "failed" ? "runtime_error" : undefined),
2640
- ...(result.finalAnswer ? { finalAnswer: result.finalAnswer } : {}),
2654
+ finalAnswer: finalResultText,
2641
2655
  runtimeRequestId: result.runtimeRequestId || requestId,
2642
2656
  promptMessageId: result.promptMessageId || requestId,
2643
2657
  completedAt: new Date().toISOString(),
@@ -2681,6 +2695,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2681
2695
  event: "done",
2682
2696
  sessionId,
2683
2697
  stopReason: result.stopReason,
2698
+ finalAnswer: finalResultText,
2684
2699
  summary,
2685
2700
  ...(stopped ? { stopped: true } : {}),
2686
2701
  }));
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "@1agents/acp-service",
3
- "version": "0.5.4",
4
- "description": "ACP runtime, CLI, HTTP/WebSocket service and DeepSeek Harness plugin in one package.",
3
+ "version": "0.7.0",
4
+ "description": "ACP runtime, CLI, HTTP/WebSocket service and DeepSeek Harness ACP/A2A plugins in one package.",
5
5
  "keywords": [
6
6
  "dreammate",
7
7
  "acp",
8
8
  "agent-runtime",
9
9
  "claude-code",
10
10
  "grok",
11
- "codex"
11
+ "codex",
12
+ "a2a"
12
13
  ],
13
14
  "license": "MIT",
14
15
  "repository": {
@@ -59,7 +60,11 @@
59
60
  "import": "./vendor/dsh/imports.js"
60
61
  },
61
62
  "./client": "./vendor/dsh/client.js",
62
- "./cordis.patch.yml": "./vendor/dsh/cordis.patch.yml"
63
+ "./cordis.patch.yml": "./vendor/dsh/cordis.patch.yml",
64
+ "./a2a": {
65
+ "types": "./dist/src/a2a/index.d.ts",
66
+ "import": "./dist/src/a2a/index.js"
67
+ }
63
68
  },
64
69
  "bin": {
65
70
  "acp-service": "dist/bin/acp-service.js"
@@ -67,28 +72,30 @@
67
72
  "files": [
68
73
  "dist",
69
74
  "README.md",
75
+ "skills",
70
76
  "vendor"
71
77
  ],
72
78
  "engines": {
73
79
  "node": ">=22.13.0"
74
80
  },
75
81
  "dependencies": {
82
+ "@1agents/acp-runtime-sdk": "npm:@agentclientprotocol/sdk@^1.5.0",
76
83
  "@1agents/dreammate-network": "^0.3.1",
77
84
  "@1agents/dreammate-node": "^0.4.0",
85
+ "@a2a-js/sdk": "1.3.0",
78
86
  "@agentclientprotocol/sdk": "1.4.0",
79
- "ws": "^8.18.0",
80
- "@1agents/acp-runtime-sdk": "npm:@agentclientprotocol/sdk@^1.5.0",
81
87
  "@openclaw/fs-safe": "^0.20.0",
82
88
  "commander": "^15.0.0",
83
89
  "skillflag": "^0.2.1",
84
90
  "tsx": "^4.23.15",
91
+ "ws": "^8.18.0",
85
92
  "zod": "^4.6.5"
86
93
  },
87
94
  "devDependencies": {
95
+ "@scottzx/1acp": "0.16.0",
88
96
  "@types/node": "^22.10.2",
89
97
  "@types/ws": "^8.5.14",
90
- "typescript": "^5.7.2",
91
- "@scottzx/1acp": "0.16.0"
98
+ "typescript": "^5.7.2"
92
99
  },
93
100
  "dsh": {
94
101
  "bundle": {