@1agents/acp-service 0.5.4 → 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.
package/README.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  ACP Agent Runtime Service for Codex, Grok Build, Claude Code and other Agents supported by its embedded 1ACP runtime. Version 0.2 uses **ACP v1 JSON-RPC 2.0 over WebSocket**. Each connection selects one Agent; each session keeps that Agent and its workspace when reconnected.
4
4
 
5
+ ## Bundled usage skill
6
+
7
+ [ACP Service skill](skills/acp-service/SKILL.md) is distributed in this npm package and maintained with the source. It covers entry-point selection, ACP CLI/WebSocket sessions, DSH presets and native model controls, A2A delegation, task queries and the durable completion inbox. Detailed examples are included in its `references/` directory.
8
+
9
+ ```sh
10
+ acp-service --skill list
11
+ acp-service --skill show acp-service
12
+ acp-service --skill export acp-service > acp-service-skill.tar
13
+ # Install the complete skill in the current project when wanted:
14
+ acp-service --skill install acp-service --agent codex --scope repo
15
+ ```
16
+
17
+ The existing embedded `acpx` runtime skill remains available. The new skill and its references can also be read directly from `skills/acp-service/` after installation. A source build containing these files must be installed before using them; an older published package may not include this skill or the A2A gateway.
18
+
5
19
  ## Run
6
20
 
7
21
  Requires Node.js 22.13 or later. Version 0.5 includes the 1ACP runtime, CLI, service, DSH plugin, browser controls, skills and licenses; installing a separate `@scottzx/1acp` package is unnecessary. The runtime and service retain their respective ACP SDK versions.
@@ -49,6 +63,81 @@ DSH reads the package's bundle patch and browser metadata; the CLI uses its `bin
49
63
 
50
64
  The plugin starts or reuses a local service when activated. See [DSH plugin usage](vendor/dsh/README.md) for presets, browser controls, configuration and lifecycle. Before migrating, stop DSH and remove `@1agents/dsh-acp`, then add the unified package; keep session bindings and preserve custom row configuration. Plugin and preset IDs are unchanged.
51
65
 
66
+ ## DSH A2A
67
+
68
+ The DSH plugin can expose an **A2A 1.0 JSON-RPC** agent using `@a2a-js/sdk@1.3.0`. The shared implementation is exported from `@1agents/acp-service/a2a`; it accepts an `A2ABackend` and starts no listener itself. This release mounts it on DSH's web server. The standalone `acp-service serve` command continues to expose ACP.
69
+
70
+ A2A is enabled by adding `a2a` to the existing `oneagents-acp` row's configuration. Set `DSH_A2A_TOKEN` in the DSH host's environment before startup, then restart DSH:
71
+
72
+ ```yaml
73
+ config:
74
+ serviceMode: auto
75
+ serviceUrl: http://127.0.0.1:36812
76
+ a2a:
77
+ enabled: true
78
+ publicUrl: http://100.125.201.118:3080
79
+ defaultCwd: /home/scott/projects
80
+ defaultAgentPreset: oneagents-acp-codex
81
+ workspaces:
82
+ demo: /home/scott/projects/demo
83
+ pushNotificationOrigins:
84
+ - http://100.100.100.100:9000
85
+ ```
86
+
87
+ The example URLs and directories must match your execution host and notification receiver. `publicUrl` is the externally reachable DSH origin. `tokenEnv` can select a different environment variable; `token` can be configured directly. A missing bearer token rejects activation. Omitting `a2a`, or setting `enabled: false`, leaves A2A disabled. DSH's UI login credential does not authenticate A2A calls.
88
+
89
+ `GET /.well-known/agent-card.json` provides public discovery. Authenticated clients POST to `/a2a` with `Authorization: Bearer ...`, `A2A-Version: 1.0` and an A2A JSON request. `path` can change the JSON-RPC route. Only protocol 1.0 is advertised; v0.3 requests receive a version error.
90
+
91
+ Submit a text task and return after its DSH session has been created or restored, without waiting for the turn:
92
+
93
+ ```json
94
+ {
95
+ "jsonrpc": "2.0",
96
+ "id": "submit-1",
97
+ "method": "SendMessage",
98
+ "params": {
99
+ "message": {
100
+ "messageId": "message-001",
101
+ "role": "ROLE_USER",
102
+ "parts": [{ "text": "检查这个项目的测试失败原因", "mediaType": "text/plain" }]
103
+ },
104
+ "configuration": { "returnImmediately": true },
105
+ "metadata": { "1agents": { "workspace": "demo", "agentPreset": "oneagents-acp-codex" } }
106
+ }
107
+ }
108
+ ```
109
+
110
+ The standard response contains `result.task.id`, `result.task.contextId` and `result.task.metadata["1agents"]` with `sessionId`, canonical `cwd` and resolved `agentPreset`. Task IDs and DSH session IDs are distinct. Session preparation failures return a failed Task. The default `returnImmediately: false` waits for a terminal or input-required state.
111
+
112
+ Use `metadata["1agents"].cwd` for an absolute existing directory **on the DSH host**, or `workspace` for a configured alias. Supplying both is rejected. Omit location and preset to use host defaults, allowing a fixed-role agent to accept tasks without a project selector. A new context creates a new DSH session; the same directory alone never selects an old session. Retain `message.contextId` for later tasks in that session; cwd and preset cannot change within a saved context. A completed Task cannot be reopened. A Task requiring input can be continued with its `taskId` and a new `messageId`. Active Task follow-up messages are rejected; independent tasks in the same context queue as separate DSH turns.
113
+
114
+ | Method | Behavior |
115
+ | --- | --- |
116
+ | `GetTask`, params `{ "id": "task-id" }` | Current persisted status, history and artifacts. |
117
+ | `ListTasks` | Scoped filtering, pagination and history selection. |
118
+ | `SubscribeToTask`, params `{ "id": "task-id" }` | SSE beginning with the current Task, followed by status/artifact updates. Terminal tasks are queried instead. |
119
+ | `SendStreamingMessage` | Submit and observe through SSE; execution and persistence continue after disconnect. |
120
+ | `CancelTask`, params `{ "id": "task-id" }` | Remove this task's queued prompt or cancel its claimed DSH turn. Other queued prompts remain. |
121
+ | `Create/Get/List/DeleteTaskPushNotificationConfig(s)` | Standard webhook configuration lifecycle. The List method is `ListTaskPushNotificationConfigs`; the other three use the singular form. |
122
+
123
+ For completion notifications, add a receiver whose origin appears in `pushNotificationOrigins`, then include a standard v1 configuration in the send request:
124
+
125
+ ```json
126
+ {
127
+ "returnImmediately": true,
128
+ "taskPushNotificationConfig": {
129
+ "url": "http://100.100.100.100:9000/a2a-events",
130
+ "authentication": { "scheme": "Bearer", "credentials": "receiver-token" }
131
+ }
132
+ }
133
+ ```
134
+
135
+ The receiver gets A2A `StreamResponse` JSON (`application/a2a+json`), including `task`, `artifactUpdate` and `statusUpdate`. Completion is `statusUpdate.status.state: "TASK_STATE_COMPLETED"`; errors and cancellation use their corresponding standard states. Delivery is ordered per scoped task, has a five-second timeout and refuses redirects. Slow or unavailable receivers do not delay task acceptance or execution. Delivery is best effort without retry or a durable outbox; consumers can reconcile with `GetTask`. An empty origin list disables push notifications. The calling system owns waking its main agent after receiving a callback.
136
+
137
+ Tasks, callback configurations and context-to-session mappings live under `<DSH_HOME>/plugins/1agents-acp/a2a` by default (`a2a.stateDirectory` overrides it). Records are scoped by tenant and authenticated host credential, written atomically with restricted permissions, and protected against two live owners of the same directory. The `.lock` directory contains a unique process-owner record; dead owners can be reclaimed without deleting a newly acquired owner's lock. A legacy `.lock` file is rejected and must only be removed after verifying no instance is running. After a host restart, completed results remain queryable, interrupted nonterminal tasks become `TASK_STATE_FAILED`, and a new task with the saved `contextId` restores its DSH session. Interrupted work is never automatically replayed. Plugin unload removes both routes and cancels its own active or queued turns.
138
+
139
+ Verification covers the official A2A client over real HTTP, SSE, callbacks, disconnection and restart, durable storage, and keyless DSH session execution. Run `pnpm --filter @1agents/acp-service test:only` and `pnpm --filter @1agents/dsh-acp test:only` after building. The optional real DSH loop test uses `DSH_SOURCE=/absolute/path/DSH`; package smoke tests verify the installed tarball's shared export and embedded plugin.
140
+
52
141
  ## ACP connections
53
142
 
54
143
  Connect to `ws://127.0.0.1:36812/agents/codex`, `/agents/grok-build`, `/agents/claude`, or another registered Agent name. `/` selects Codex. Each WebSocket text message contains one UTF-8 JSON-RPC object. Batch messages and the former `action/event` envelopes are rejected. WebSocket is a custom transport permitted by ACP, not the standard stdio transport.
@@ -164,3 +253,45 @@ Tests use the official ACP SDK over real WebSockets, cover session lifecycle and
164
253
  Discovery checks PATH, `~/.local/bin`, `~/.grok/bin`, and installed adapter package launch files. A registered native ACP command is ready when its executable exists. Adapter-backed harnesses are ready when the adapter is installed, or when their native CLI and `npx` are installed; the latter uses the runtime's existing adapter download behavior when a session launches. Having `npx` or `uvx` alone does not expose uninstalled harnesses. Scanning neither executes agents nor downloads packages, and readiness does not verify credentials or model access. Detection-only frameworks remain in the inventory with `chat_ready: false`.
165
254
 
166
255
  The service launcher uses the same local command resolution, including absolute paths to user-local binaries. The catalog originates from 1agents_app's former Go detector; consumers no longer probe their own host or maintain separate detection tables. `discoverAgents()` is also exported for embedded service consumers and includes local executable paths; the HTTP response omits these paths.
256
+
257
+ ## Remote DSH tools and completion inbox
258
+
259
+ The same package includes `acp-service a2a gateway --config /absolute/gateway.json` and exports `RemoteAgentGateway` / `serveA2AGateway` from `@1agents/acp-service/a2a`. The gateway calls the standard A2A 1.0 SendMessage, GetTask and CancelTask APIs. It registers seven HTTP methods with the local DreamMate node; an existing `dreammate_invoke` client can use them immediately without another MCP server.
260
+
261
+ Create a private configuration file (`chmod 600`):
262
+
263
+ ```json
264
+ {
265
+ "stateDirectory": "/absolute/private/a2a-state",
266
+ "port": 36814,
267
+ "remotes": {
268
+ "wsl-dsh": { "url": "http://your-tailnet-host:3080", "token": "protected-DSH-A2A-token" }
269
+ },
270
+ "callback": {
271
+ "host": "your-local-tailnet-IP",
272
+ "port": 36815,
273
+ "url": "http://your-local-tailnet-IP:36815/a2a-events",
274
+ "token": "separate-protected-callback-token"
275
+ }
276
+ }
277
+ ```
278
+
279
+ The callback is optional; configure its exact origin in DSH `a2a.pushNotificationOrigins`. The tool listener binds only `127.0.0.1`; the separate authenticated callback listener exposes only the configured event path. Browser Origin requests cannot invoke local tools. Credentials stay in configuration, outside prompts and tool parameters. Local DreamMate clients are trusted; `originSessionId` is a routing identifier, not a remote authentication credential.
280
+
281
+ Discover `a2a-gateway`, inspect `remote_agent_spawn`, then call it with:
282
+
283
+ ```json
284
+ {
285
+ "remote": "wsl-dsh",
286
+ "originSessionId": "stable-parent-session-id",
287
+ "cwd": "/home/scott/project",
288
+ "agentPreset": "oneagents-acp-codex",
289
+ "prompt": "Read the project README and report its purpose. Do not change files."
290
+ }
291
+ ```
292
+
293
+ The returned `taskId` is available before execution finishes. `cwd` is an existing absolute path **on WSL**. Every spawn creates a new A2A context / DSH session even when cwd matches. `remote_agent_message` takes the previous task ID and prompt, creates a new task in the same context, and keeps that DSH session. `remote_agent_get` / `remote_agent_cancel` take `remote`, `originSessionId`, and `taskId`. `remote_agent_list` and `remote_agent_inbox` take only `originSessionId`; after handling a notice, confirm it with `remote_agent_ack` and its `noticeId`.
294
+
295
+ CLI callers use the same methods: pipe a JSON parameters object to `acp-service a2a invoke remote_agent_spawn` (or any method above). The gateway runs independently of the caller. A durable inbox, stable notice IDs, restart reconciliation and GetTask polling recover completions when a push event is missed. Offline queries return the cached task with `stale: true`; loss of connectivity never becomes a fabricated task failure. An ambiguous failed SendMessage is not automatically resubmitted, since A2A message IDs alone do not guarantee exactly-once task admission.
296
+
297
+ To wake a main-agent host, configure `notificationTargets` as a map of trusted target names to `{ "url": "...", "token": "..." }` and pass a target name as `notificationTarget` to spawn. Completion or input-required notices carry `originSessionId`, `taskId`, `contextId`, state and result. Deliveries use bearer authentication and a stable `Idempotency-Key`, retry after a failed response or gateway restart, and remain in the inbox until acknowledged. The receiving host must persist/deduplicate the notice and inject it into the named parent session (for example Phonetic's `async_task_notice`). A successful HTTP response means the receiver accepted the notice, not that the main model ran. Codex's ordinary MCP tool connection alone does not implement that host adapter; this gateway does not claim automatic Codex turn wake-up.
@@ -0,0 +1 @@
1
+ export declare function runA2ACli(args: string[]): Promise<void>;
@@ -0,0 +1,50 @@
1
+ import fs from 'node:fs';
2
+ import { serveA2AGateway } from '../src/a2a/gateway.js';
3
+ export async function runA2ACli(args) {
4
+ const flag = (name) => {
5
+ const index = args.indexOf(name);
6
+ if (index < 0)
7
+ return undefined;
8
+ if (!args[index + 1] || args[index + 1].startsWith('--'))
9
+ throw new Error(`Missing value for ${name}`);
10
+ return args[index + 1];
11
+ };
12
+ if (!args.length || args.includes('--help') || args.includes('-h')) {
13
+ console.log(`Usage:
14
+ acp-service a2a gateway --config <file> [--no-report]
15
+ acp-service a2a invoke <method> [--url http://127.0.0.1:36814]
16
+
17
+ invoke reads a JSON parameters object from stdin. Credentials stay in the
18
+ gateway config file (chmod 600), outside tool arguments. Remote cwd is absolute.
19
+ Methods: remote_agent_spawn, remote_agent_get, remote_agent_message,
20
+ remote_agent_cancel, remote_agent_list, remote_agent_inbox, remote_agent_ack`);
21
+ return;
22
+ }
23
+ if (args[0] === 'gateway') {
24
+ const file = flag('--config');
25
+ if (!file)
26
+ throw new Error('gateway requires --config <file>');
27
+ const stat = fs.statSync(file);
28
+ if (process.platform !== 'win32' && (stat.mode & 0o077))
29
+ throw new Error('Gateway config contains credentials; set chmod 600');
30
+ const config = JSON.parse(fs.readFileSync(file, 'utf8'));
31
+ const host = await serveA2AGateway(config, { report: !args.includes('--no-report') });
32
+ console.log(`a2a-gateway listening on http://127.0.0.1:${host.port}; registration=${host.registration?.ok ?? false}`);
33
+ const stop = () => { void host.close().then(() => { process.exitCode = 0; }); };
34
+ process.once('SIGINT', stop);
35
+ process.once('SIGTERM', stop);
36
+ return;
37
+ }
38
+ if (args[0] === 'invoke' && args[1] && !args[1].startsWith('--')) {
39
+ const url = new URL('/invoke', flag('--url') ?? 'http://127.0.0.1:36814');
40
+ const params = JSON.parse(fs.readFileSync(0, 'utf8'));
41
+ const response = await fetch(url, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(15_000),
42
+ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ method: args[1], params }) });
43
+ const data = await response.json();
44
+ console.log(JSON.stringify(data, null, 2));
45
+ if (!response.ok)
46
+ process.exitCode = 1;
47
+ return;
48
+ }
49
+ throw new Error('Unknown A2A command; run acp-service a2a --help');
50
+ }
@@ -1,9 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFileSync, spawn } from 'node:child_process';
3
3
  import { createRequire } from 'node:module';
4
+ import path from 'node:path';
4
5
  import fs from 'node:fs';
5
- import { serveAcpService } from '../src/server.js';
6
- import { attachProcessSignalHandlers } from '../src/bridge.js';
7
6
  const require = createRequire(import.meta.url);
8
7
  const rawArgs = process.argv.slice(2);
9
8
  const invokedBin = 'acp-service';
@@ -54,9 +53,12 @@ function printUnifiedHelp(binName) {
54
53
  .replace(/^Usage:\s+acpx/m, `Usage: ${binName}`)
55
54
  .replace(/Headless CLI client for the Agent Client Protocol/, 'Headless CLI client & DreamMate Network runtime service for the Agent Client Protocol (ACP)');
56
55
  const serverCommands = `Commands:
56
+ a2a gateway --config <file> Start persistent remote-agent tools and completion inbox
57
+ a2a invoke <method> Invoke local remote-agent tools (JSON params on stdin)
57
58
  serve [options] Start DreamMate Network ACP runtime daemon (HTTP + WS)`;
58
59
  help = help.replace(/^Commands:/m, serverCommands);
59
60
  const serverOptions = `Options:
61
+ --skill <action> List, show, export or install bundled agent skills
60
62
  --port, -p <n> Server listen port (for serve, default: 36812)
61
63
  --host <ip> Server bind IP (for serve, default: 0.0.0.0)
62
64
  --no-report Do not report to local dreammate-node (36908)`;
@@ -103,6 +105,8 @@ function parseServerArgs(args) {
103
105
  return options;
104
106
  }
105
107
  async function runServer(options) {
108
+ const { serveAcpService } = await import('../src/server.js');
109
+ const { attachProcessSignalHandlers } = await import('../src/bridge.js');
106
110
  attachProcessSignalHandlers();
107
111
  try {
108
112
  await serveAcpService(options);
@@ -113,6 +117,20 @@ async function runServer(options) {
113
117
  }
114
118
  }
115
119
  async function main() {
120
+ if (rawArgs.includes('--skill')) {
121
+ const { maybeHandleSkillflag } = await import('skillflag');
122
+ const packageRoot = path.dirname(require.resolve('@1agents/acp-service/package.json'));
123
+ await maybeHandleSkillflag(process.argv, {
124
+ skillsRoot: [path.join(packageRoot, 'skills'), path.join(packageRoot, 'vendor/runtime/skills')],
125
+ includeBundledSkill: false,
126
+ });
127
+ return;
128
+ }
129
+ if (rawArgs[0] === 'a2a') {
130
+ const { runA2ACli } = await import('./a2a.js');
131
+ await runA2ACli(rawArgs.slice(1));
132
+ return;
133
+ }
116
134
  const isServe = rawArgs[0] === 'serve' || rawArgs[0] === 'run';
117
135
  const hasServerExplicitFlag = rawArgs[0] === '--port' ||
118
136
  rawArgs[0] === '-p' ||
@@ -0,0 +1,29 @@
1
+ import { type SendMessageRequest } from '@a2a-js/sdk';
2
+ import { type AgentExecutor, type ExecutionEventBus, type RequestContext } from '@a2a-js/sdk/server';
3
+ import type { FileA2AStore } from './store.js';
4
+ import type { A2ABackend, A2APrepareInput } from './types.js';
5
+ export interface A2AExecutionOptions {
6
+ defaultCwd?: string;
7
+ defaultAgentPreset?: string;
8
+ workspaces?: Record<string, string>;
9
+ }
10
+ /** Validate application metadata before the SDK starts an execution. */
11
+ export declare function parseA2AInput(request: SendMessageRequest, options: A2AExecutionOptions): {
12
+ prompt: string;
13
+ input: A2APrepareInput;
14
+ };
15
+ /** SDK owns the execution lifetime; an HTTP disconnect never aborts this signal. */
16
+ export declare class A2ASessionExecutor implements AgentExecutor {
17
+ private readonly backend;
18
+ private readonly store;
19
+ private readonly options;
20
+ private readonly active;
21
+ private readonly awaitingInput;
22
+ private readonly preparing;
23
+ private stopped;
24
+ constructor(backend: A2ABackend, store: FileA2AStore, options: A2AExecutionOptions);
25
+ isRunning(taskId: string): boolean;
26
+ execute(context: RequestContext, bus: ExecutionEventBus): Promise<void>;
27
+ cancelTask(taskId: string, bus: ExecutionEventBus): Promise<void>;
28
+ close(): Promise<void>;
29
+ }
@@ -0,0 +1,144 @@
1
+ /** Official A2A executor with durable DSH context bindings and independent turns. */
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { Role, Task, TaskState, Message } from '@a2a-js/sdk';
4
+ import { ContentTypeNotSupportedError, RequestMalformedError, UnsupportedOperationError } from '@a2a-js/sdk/errors';
5
+ import { AgentEvent, resolveUserScope } from '@a2a-js/sdk/server';
6
+ /** Validate application metadata before the SDK starts an execution. */
7
+ export function parseA2AInput(request, options) {
8
+ const message = request.message;
9
+ if (!message?.messageId.trim() || message.role !== Role.ROLE_USER)
10
+ throw new RequestMalformedError('A user message with messageId is required');
11
+ if (!message.parts.length || message.parts.some(part => part.content?.$case !== 'text' || (part.mediaType && part.mediaType !== 'text/plain'))) {
12
+ throw new ContentTypeNotSupportedError('DSH A2A accepts text/plain parts');
13
+ }
14
+ const prompt = message.parts.map(part => part.content?.value).join('\n');
15
+ if (!prompt.trim())
16
+ throw new RequestMalformedError('Prompt must contain text');
17
+ const metadata = request.metadata?.['1agents'];
18
+ if (metadata !== undefined && (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)))
19
+ throw new RequestMalformedError('metadata.1agents must be an object');
20
+ const value = (metadata ?? {});
21
+ for (const key of Object.keys(value))
22
+ if (!['cwd', 'agentPreset', 'workspace'].includes(key))
23
+ throw new RequestMalformedError(`Unknown metadata.1agents field: ${key}`);
24
+ for (const key of ['cwd', 'agentPreset', 'workspace']) {
25
+ if (value[key] !== undefined && (typeof value[key] !== 'string' || !value[key].trim()))
26
+ throw new RequestMalformedError(`${key} must be a nonempty string`);
27
+ }
28
+ if (value.cwd && value.workspace)
29
+ throw new RequestMalformedError('Use cwd or workspace, not both');
30
+ let cwd = value.cwd;
31
+ if (value.workspace) {
32
+ cwd = options.workspaces?.[value.workspace];
33
+ if (!cwd)
34
+ throw new RequestMalformedError(`Unknown workspace: ${value.workspace}`);
35
+ }
36
+ return { prompt, input: { cwd, agentPreset: value.agentPreset } };
37
+ }
38
+ /** SDK owns the execution lifetime; an HTTP disconnect never aborts this signal. */
39
+ export class A2ASessionExecutor {
40
+ backend;
41
+ store;
42
+ options;
43
+ active = new Map();
44
+ awaitingInput = new Map();
45
+ preparing = new Map();
46
+ stopped = false;
47
+ constructor(backend, store, options) {
48
+ this.backend = backend;
49
+ this.store = store;
50
+ this.options = options;
51
+ }
52
+ isRunning(taskId) { return this.active.has(taskId); }
53
+ async execute(context, bus) {
54
+ if (this.stopped)
55
+ throw new UnsupportedOperationError('A2A host is stopping');
56
+ if (this.active.has(context.taskId))
57
+ throw new UnsupportedOperationError('This task already has an active execution');
58
+ const controller = new AbortController();
59
+ this.awaitingInput.delete(context.taskId);
60
+ let finish;
61
+ const done = new Promise(resolve => { finish = resolve; });
62
+ this.active.set(context.taskId, { controller, done });
63
+ let published = false;
64
+ const status = (state, text) => {
65
+ bus.publish(AgentEvent.statusUpdate({ taskId: context.taskId, contextId: context.contextId,
66
+ status: { state, timestamp: new Date().toISOString(), message: text ? Message.fromJSON({
67
+ messageId: randomUUID(), role: 'ROLE_AGENT', contextId: context.contextId, taskId: context.taskId, parts: [{ text }],
68
+ }) : undefined }, metadata: undefined }));
69
+ };
70
+ try {
71
+ const { prompt, input } = parseA2AInput(context.request, this.options);
72
+ const key = JSON.stringify([context.context.tenant ?? '', resolveUserScope(context.context), context.contextId]);
73
+ const previous = this.preparing.get(key) ?? Promise.resolve();
74
+ let unlock;
75
+ const lock = new Promise(resolve => { unlock = resolve; });
76
+ this.preparing.set(key, lock);
77
+ let target;
78
+ try {
79
+ await previous;
80
+ controller.signal.throwIfAborted();
81
+ const saved = this.store.loadTarget(context.contextId, context.context);
82
+ target = await this.backend.prepare({ sessionId: saved?.sessionId,
83
+ cwd: input.cwd ?? saved?.cwd ?? this.options.defaultCwd,
84
+ agentPreset: input.agentPreset ?? saved?.agentPreset ?? this.options.defaultAgentPreset });
85
+ this.store.saveTarget(context.contextId, target, context.context);
86
+ }
87
+ finally {
88
+ unlock();
89
+ if (this.preparing.get(key) === lock)
90
+ this.preparing.delete(key);
91
+ }
92
+ const task = Task.fromJSON({ ...Task.toJSON(context.task ?? Task.fromJSON({ id: context.taskId, contextId: context.contextId })),
93
+ status: { state: 'TASK_STATE_SUBMITTED', timestamp: new Date().toISOString() },
94
+ metadata: { ...context.task?.metadata, '1agents': target } });
95
+ bus.publish(AgentEvent.task(task));
96
+ published = true;
97
+ controller.signal.throwIfAborted();
98
+ status(TaskState.TASK_STATE_WORKING);
99
+ // DSH deduplicates prompts by rpcId across the whole session. A Task can
100
+ // have several input-required turns, each with its own message identity.
101
+ const requestId = `a2a-${createHash('sha256').update(JSON.stringify([context.taskId, context.userMessage.messageId])).digest('hex')}`;
102
+ const result = await this.backend.run(target, prompt, { requestId, signal: controller.signal });
103
+ controller.signal.throwIfAborted();
104
+ if (result.text)
105
+ bus.publish(AgentEvent.artifactUpdate({ taskId: context.taskId, contextId: context.contextId,
106
+ artifact: { artifactId: `${context.taskId}-${randomUUID()}`, name: 'DSH response', description: '',
107
+ parts: [{ content: { $case: 'text', value: result.text }, mediaType: 'text/plain', filename: '', metadata: undefined }], metadata: undefined, extensions: [] },
108
+ append: false, lastChunk: true, metadata: undefined }));
109
+ if (result.outcome === 'input-required')
110
+ this.awaitingInput.set(context.taskId, context.contextId);
111
+ status(result.outcome === 'completed' ? TaskState.TASK_STATE_COMPLETED : result.outcome === 'input-required' ? TaskState.TASK_STATE_INPUT_REQUIRED : TaskState.TASK_STATE_FAILED, result.detail);
112
+ }
113
+ catch (error) {
114
+ if (!published)
115
+ bus.publish(AgentEvent.task(Task.fromJSON({ id: context.taskId, contextId: context.contextId,
116
+ status: { state: 'TASK_STATE_SUBMITTED', timestamp: new Date().toISOString() } })));
117
+ status(controller.signal.aborted ? TaskState.TASK_STATE_CANCELED : TaskState.TASK_STATE_FAILED, error instanceof Error ? error.message : String(error));
118
+ }
119
+ finally {
120
+ this.active.delete(context.taskId);
121
+ finish();
122
+ }
123
+ }
124
+ async cancelTask(taskId, bus) {
125
+ const execution = this.active.get(taskId);
126
+ if (!execution) {
127
+ const contextId = this.awaitingInput.get(taskId);
128
+ if (!contextId)
129
+ throw new UnsupportedOperationError('No active execution for this task');
130
+ this.awaitingInput.delete(taskId);
131
+ bus.publish(AgentEvent.statusUpdate({ taskId, contextId,
132
+ status: { state: TaskState.TASK_STATE_CANCELED, timestamp: new Date().toISOString(), message: undefined }, metadata: undefined }));
133
+ return;
134
+ }
135
+ execution.controller.abort(new Error('A2A task canceled'));
136
+ await execution.done;
137
+ }
138
+ async close() {
139
+ this.stopped = true;
140
+ for (const execution of this.active.values())
141
+ execution.controller.abort(new Error('A2A host stopped'));
142
+ await Promise.all([...this.active.values()].map(execution => execution.done));
143
+ }
144
+ }
@@ -0,0 +1,136 @@
1
+ import { z } from 'zod';
2
+ declare const configSchema: z.ZodObject<{
3
+ stateDirectory: z.ZodString;
4
+ port: z.ZodDefault<z.ZodNumber>;
5
+ remotes: z.ZodRecord<z.ZodString, z.ZodObject<{
6
+ url: z.ZodString;
7
+ token: z.ZodString;
8
+ }, z.core.$strict>>;
9
+ callback: z.ZodOptional<z.ZodObject<{
10
+ host: z.ZodString;
11
+ port: z.ZodNumber;
12
+ url: z.ZodString;
13
+ token: z.ZodString;
14
+ }, z.core.$strict>>;
15
+ notificationTargets: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
16
+ url: z.ZodString;
17
+ token: z.ZodString;
18
+ }, z.core.$strict>>>;
19
+ pollIntervalMs: z.ZodDefault<z.ZodNumber>;
20
+ }, z.core.$strict>;
21
+ export type A2AGatewayConfig = z.input<typeof configSchema>;
22
+ type Config = z.output<typeof configSchema>;
23
+ export declare const REMOTE_AGENT_METHODS: {
24
+ remote_agent_spawn: {
25
+ description: string;
26
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
27
+ remote: z.ZodString;
28
+ prompt: z.ZodString;
29
+ cwd: z.ZodString;
30
+ agentPreset: z.ZodOptional<z.ZodString>;
31
+ notificationTarget: z.ZodOptional<z.ZodString>;
32
+ title: z.ZodOptional<z.ZodString>;
33
+ originSessionId: z.ZodString;
34
+ }, z.core.$strict>>;
35
+ };
36
+ remote_agent_get: {
37
+ description: string;
38
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
39
+ remote: z.ZodString;
40
+ taskId: z.ZodString;
41
+ originSessionId: z.ZodString;
42
+ }, z.core.$strict>>;
43
+ };
44
+ remote_agent_cancel: {
45
+ description: string;
46
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
47
+ remote: z.ZodString;
48
+ taskId: z.ZodString;
49
+ originSessionId: z.ZodString;
50
+ }, z.core.$strict>>;
51
+ };
52
+ remote_agent_message: {
53
+ description: string;
54
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
55
+ prompt: z.ZodString;
56
+ remote: z.ZodString;
57
+ taskId: z.ZodString;
58
+ originSessionId: z.ZodString;
59
+ }, z.core.$strict>>;
60
+ };
61
+ remote_agent_list: {
62
+ description: string;
63
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
64
+ originSessionId: z.ZodString;
65
+ }, z.core.$strict>>;
66
+ };
67
+ remote_agent_inbox: {
68
+ description: string;
69
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
70
+ originSessionId: z.ZodString;
71
+ }, z.core.$strict>>;
72
+ };
73
+ remote_agent_ack: {
74
+ description: string;
75
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
76
+ noticeId: z.ZodString;
77
+ originSessionId: z.ZodString;
78
+ }, z.core.$strict>>;
79
+ };
80
+ };
81
+ export interface RemoteAgentNotice {
82
+ noticeId: string;
83
+ originSessionId: string;
84
+ remote: string;
85
+ taskId: string;
86
+ contextId: string;
87
+ cwd: string;
88
+ agentPreset?: string;
89
+ title?: string;
90
+ state: string;
91
+ result: string;
92
+ createdAt: string;
93
+ }
94
+ export declare class RemoteAgentGateway {
95
+ readonly config: Config;
96
+ private readonly lease;
97
+ private readonly stateFile;
98
+ private readonly state;
99
+ private readonly clients;
100
+ private readonly refreshing;
101
+ private readonly delivering;
102
+ private readonly controllers;
103
+ private readonly operations;
104
+ private reconciling?;
105
+ private readonly timer;
106
+ private closed;
107
+ constructor(input: A2AGatewayConfig);
108
+ private save;
109
+ private client;
110
+ private auth;
111
+ private job;
112
+ private view;
113
+ private accept;
114
+ private update;
115
+ private refresh;
116
+ reconcile(): Promise<void>;
117
+ private deliver;
118
+ invoke(method: string, params: unknown): Promise<unknown>;
119
+ private invokeMethod;
120
+ /** Push events are hints. GetTask remains authoritative, including after missed callbacks. */
121
+ receivePush(event: unknown): Promise<void>;
122
+ close(): Promise<void>;
123
+ }
124
+ export declare function serveA2AGateway(input: A2AGatewayConfig, options?: {
125
+ report?: boolean;
126
+ }): Promise<{
127
+ gateway: RemoteAgentGateway;
128
+ port: number;
129
+ callbackPort: number | undefined;
130
+ registration: {
131
+ ok: boolean;
132
+ reason?: string;
133
+ } | undefined;
134
+ close: () => Promise<void>;
135
+ }>;
136
+ export {};