@1agents/acp-service 0.6.0 → 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.
package/README.md CHANGED
@@ -1,6 +1,46 @@
1
1
  # @1agents/acp-service
2
2
 
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.
3
+ Run persistent Codex, Claude Code, Grok Build and other supported native Agent sessions in DeepSeek Harness (DSH), or use the same package as a standalone CLI and ACP service. DSH exposes the Agent's native models, settings, commands and permission requests; each session keeps its Agent and workspace when reconnected.
4
+
5
+ ## Install in DSH
6
+
7
+ Requires **Node.js 22.13+**, DSH, and the selected native Agent's CLI and credentials on the DSH host. Adapter-backed Agents also require their ACP adapter; the native Codex CLI alone does not provide `codex-acp`.
8
+
9
+ ```sh
10
+ dsh plugin --profile web add @1agents/acp-service@^0.7.0
11
+ ```
12
+
13
+ Restart DSH and check that **`@1agents/acp-service`** is enabled on the Plugins page. Create a session with a discovered **ACP · Agent** preset, choose an existing workspace, then send a text prompt. The plugin starts or reuses its local service automatically. Use your own profile name in place of `web`; from a DSH source checkout, replace `dsh` with `pnpm dsh`.
14
+
15
+ If pnpm reports an ignored transitive `esbuild` build script, follow the package manager's prompt or set that individual package's approval in the profile, then repeat the install. Approve or deny the script according to your policy, and check the bundle's enabled state after a partial install.
16
+
17
+ The pinned [GitHub Release tarball](https://github.com/scottzx/1acp/releases/tag/acp-service-v0.6.0) contains the same published npm artifact:
18
+
19
+ ```sh
20
+ dsh plugin --profile web add https://github.com/scottzx/1acp/releases/download/acp-service-v0.6.0/1agents-acp-service-0.6.0.tgz
21
+ ```
22
+
23
+ `@1agents/session-reader` is optional: install it separately to browse and continue existing Claude, Codex and Grok histories. For presets, native controls, configuration and migration, see the [DSH user guide](https://github.com/scottzx/1acp/blob/main/packages/dsh-plugin/README.md).
24
+
25
+ The CI baseline is **DSH 0.1.7-rc.2**, commit `21638c56315ae6a2b552d6091945d3144c9af32e`. Additional isolated-profile verification used a locally modified DSH tree labeled `0.2.0-rc.1`. The [verification record](https://github.com/scottzx/1acp/blob/main/docs/marketplaces/verification-2026-10-09.md) describes the installed-package, Loader, browser and lifecycle checks and their limits.
26
+
27
+ ### Screenshots
28
+
29
+ ![Discovered ACP Agent presets in DSH](https://raw.githubusercontent.com/scottzx/1acp/main/packages/service/assets/dsh-agent-presets.png)
30
+
31
+ ![Native Codex model and ACP controls](https://raw.githubusercontent.com/scottzx/1acp/main/packages/service/assets/dsh-codex-controls.png)
32
+
33
+ These unmodified screenshots show discovery and native capability loading in that fresh isolated local profile. No model prompt was sent for the UI check. Controls depend on the selected Agent, adapter and account.
34
+
35
+ ## Standalone CLI and service
36
+
37
+ ```sh
38
+ npm install -g @1agents/acp-service@^0.7.0
39
+ acp-service --help
40
+ acp-service serve --host 127.0.0.1 --port 36812 --no-report
41
+ ```
42
+
43
+ The service uses **ACP v1 JSON-RPC 2.0 over WebSocket**. DSH is unnecessary for the standalone entry points. A2A delegation is opt-in and disabled by default; its configuration is documented below. Waking a calling system's main Agent after task completion requires that system's receiving host adapter.
4
44
 
5
45
  ## Bundled usage skill
6
46
 
@@ -14,11 +54,11 @@ acp-service --skill export acp-service > acp-service-skill.tar
14
54
  acp-service --skill install acp-service --agent codex --scope repo
15
55
  ```
16
56
 
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.
57
+ The existing embedded `acpx` runtime skill remains available. The skill and its references can also be read directly from `skills/acp-service/` after installing version 0.6.0 or later.
18
58
 
19
- ## Run
59
+ ## Service development and API
20
60
 
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.
61
+ Version 0.6.0 includes the 1ACP runtime, CLI, service, DSH plugin, browser controls, skills and licenses. The runtime and service retain their respective ACP SDK versions.
22
62
 
23
63
  The runtime's per-session launch argv and transient credentials APIs support Provider Profiles. Public runtime APIs and flow authoring are available as `@1agents/acp-service/runtime` and `@1agents/acp-service/flows`. The `acp-service` command forwards runtime commands alongside its `serve` command.
24
64
 
@@ -51,17 +91,11 @@ HTTP endpoints:
51
91
  - `GET /manifest`: DreamMate service discovery, ACP version, custom transport and Agent endpoint paths. Profiles listed here describe registered launch configurations, not a successful installation/authentication probe.
52
92
  - `GET /services`: current service/session counts.
53
93
 
54
- ## DSH installation
55
-
56
- The same npm package can be installed as a DSH bundle:
57
-
58
- ```sh
59
- pnpm dsh plugin --profile web add @1agents/acp-service
60
- ```
94
+ ## DSH package entry points
61
95
 
62
96
  DSH reads the package's bundle patch and browser metadata; the CLI uses its `bin` entry. There is no installation-time mode switch, and both uses can coexist. The package root retains the service API and exposes Cordis metadata plus a lazy `apply`; merely importing it starts no plugin or process. `/service` is the service API, while `/dsh`, `/dsh/preset` and `/dsh/imports` provide the typed plugin interfaces. DSH host dependencies are supplied by DSH rather than installed with the CLI.
63
97
 
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.
98
+ The plugin starts or reuses a local service when activated. See [DSH plugin usage](https://github.com/scottzx/1acp/blob/main/packages/dsh-plugin/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.
65
99
 
66
100
  ## DSH A2A
67
101
 
@@ -256,6 +290,12 @@ The service launcher uses the same local command resolution, including absolute
256
290
 
257
291
  ## Remote DSH tools and completion inbox
258
292
 
293
+ The optional automation listener supports Activepieces scheduled tasks:
294
+ authenticated occurrence submission, overlap prevention, durable task
295
+ correlation and completion-processing claims. See the repository's
296
+ [integration guide](https://github.com/scottzx/1acp/blob/main/docs/activepieces-automation.md) and
297
+ [configuration examples](https://github.com/scottzx/1acp/tree/main/examples/activepieces).
298
+
259
299
  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
300
 
261
301
  Create a private configuration file (`chmod 600`):
package/dist/bin/a2a.js CHANGED
@@ -30,6 +30,8 @@ Methods: remote_agent_spawn, remote_agent_get, remote_agent_message,
30
30
  const config = JSON.parse(fs.readFileSync(file, 'utf8'));
31
31
  const host = await serveA2AGateway(config, { report: !args.includes('--no-report') });
32
32
  console.log(`a2a-gateway listening on http://127.0.0.1:${host.port}; registration=${host.registration?.ok ?? false}`);
33
+ if (host.automationPort !== undefined)
34
+ console.log(`a2a automation listening on http://${host.gateway.config.automation.host}:${host.automationPort}`);
33
35
  const stop = () => { void host.close().then(() => { process.exitCode = 0; }); };
34
36
  process.once('SIGINT', stop);
35
37
  process.once('SIGTERM', stop);
@@ -0,0 +1,99 @@
1
+ import http from 'node:http';
2
+ import { z } from 'zod';
3
+ import type { RemoteAgentGateway, RemoteAgentNotice } from './gateway.js';
4
+ export declare const automationConfigSchema: z.ZodObject<{
5
+ host: z.ZodDefault<z.ZodString>;
6
+ port: z.ZodDefault<z.ZodNumber>;
7
+ token: z.ZodString;
8
+ schedules: z.ZodRecord<z.ZodString, z.ZodObject<{
9
+ remote: z.ZodString;
10
+ cwd: z.ZodString;
11
+ agentPreset: z.ZodOptional<z.ZodString>;
12
+ notificationTarget: z.ZodOptional<z.ZodString>;
13
+ }, z.core.$strict>>;
14
+ processingLeaseMs: z.ZodDefault<z.ZodNumber>;
15
+ }, z.core.$strict>;
16
+ export type A2AAutomationConfig = z.input<typeof automationConfigSchema>;
17
+ type Config = z.output<typeof automationConfigSchema>;
18
+ export type AutomationRunStatus = 'dispatching' | 'submitted' | 'submission_unknown' | 'skipped' | 'completed' | 'failed' | 'canceled' | 'rejected' | 'input_required' | 'auth_required';
19
+ export interface AutomationRun {
20
+ runId: string;
21
+ occurrenceKey: string;
22
+ originSessionId: string;
23
+ scheduleId: string;
24
+ scheduledFor: string;
25
+ flowRunId?: string;
26
+ businessRef?: string;
27
+ prompt: string;
28
+ remote: string;
29
+ cwd: string;
30
+ agentPreset?: string;
31
+ notificationTarget?: string;
32
+ status: AutomationRunStatus;
33
+ reason?: 'schedule_busy' | 'submission_unconfirmed' | 'ambiguous_submission';
34
+ blockedBy?: string;
35
+ taskId?: string;
36
+ contextId?: string;
37
+ sessionId?: string;
38
+ state?: string;
39
+ result?: string;
40
+ checkedAt?: string;
41
+ stale?: boolean;
42
+ createdAt: string;
43
+ updatedAt: string;
44
+ }
45
+ /** The gateway owns remote polling and delivery; this ledger owns occurrence admission and business acknowledgement. */
46
+ export declare class A2AAutomation {
47
+ private readonly gateway;
48
+ readonly config: Config;
49
+ private readonly file;
50
+ private readonly state;
51
+ private readonly admissions;
52
+ constructor(gateway: RemoteAgentGateway, config: Config);
53
+ private save;
54
+ private run;
55
+ private apply;
56
+ private refresh;
57
+ submit(params: unknown): Promise<{
58
+ run: AutomationRun;
59
+ created: boolean;
60
+ }>;
61
+ list(limit: number): Promise<{
62
+ runs: AutomationRun[];
63
+ }>;
64
+ get(runId: string): Promise<{
65
+ run: AutomationRun;
66
+ }>;
67
+ cancel(runId: string): Promise<{
68
+ run: AutomationRun;
69
+ }>;
70
+ private knownNotice;
71
+ claim(noticeId: string, params: unknown): Promise<{
72
+ claimed: boolean;
73
+ runId: string;
74
+ reason: string;
75
+ leaseUntil?: undefined;
76
+ notice?: undefined;
77
+ } | {
78
+ claimed: boolean;
79
+ runId: string;
80
+ reason: string;
81
+ leaseUntil: string;
82
+ notice?: undefined;
83
+ } | {
84
+ claimed: boolean;
85
+ runId: string;
86
+ notice: RemoteAgentNotice;
87
+ leaseUntil: string;
88
+ reason?: undefined;
89
+ }>;
90
+ ack(noticeId: string, params: unknown): Promise<{
91
+ acknowledged: boolean;
92
+ runId: string;
93
+ noticeId: string;
94
+ }>;
95
+ /** Retry only local inbox acknowledgement after durable business completion, never business effects. */
96
+ reconcileAcknowledgements(): Promise<void>;
97
+ }
98
+ export declare function createAutomationServer(automation: A2AAutomation): http.Server;
99
+ export {};
@@ -0,0 +1,372 @@
1
+ /** Durable scheduled occurrences and business-processing claims over the existing gateway. */
2
+ import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
3
+ import { closeSync, fsyncSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
4
+ import http from 'node:http';
5
+ import path from 'node:path';
6
+ import { z } from 'zod';
7
+ const identifier = z.string().trim().min(1).max(512);
8
+ export const automationConfigSchema = z.object({
9
+ host: identifier.default('127.0.0.1'),
10
+ port: z.number().int().min(0).max(65535).default(36815),
11
+ token: identifier,
12
+ schedules: z.record(identifier, z.object({
13
+ remote: identifier,
14
+ cwd: identifier.refine(value => path.posix.isAbsolute(value), 'cwd must be an absolute remote path'),
15
+ agentPreset: identifier.optional(),
16
+ notificationTarget: identifier.optional(),
17
+ }).strict()),
18
+ processingLeaseMs: z.number().int().min(1).max(24 * 60 * 60 * 1000).default(300_000),
19
+ }).strict();
20
+ const submitSchema = z.object({
21
+ scheduleId: identifier,
22
+ scheduledFor: z.string().datetime({ offset: true }).transform(value => new Date(value).toISOString()),
23
+ flowRunId: identifier.optional(),
24
+ prompt: z.string().min(1).max(256 * 1024).refine(value => Boolean(value.trim()), 'Prompt must contain text'),
25
+ businessRef: identifier.optional(),
26
+ }).strict();
27
+ const processorSchema = z.object({ originSessionId: identifier, processorId: identifier }).strict();
28
+ const taskViewSchema = z.object({
29
+ remote: identifier, originSessionId: identifier, taskId: identifier, contextId: identifier,
30
+ state: identifier, result: z.string(), checkedAt: z.string(), stale: z.boolean(),
31
+ sessionId: z.string().optional(),
32
+ }).passthrough();
33
+ const active = new Set(['dispatching', 'submitted', 'submission_unknown', 'input_required', 'auth_required']);
34
+ const statuses = {
35
+ TASK_STATE_COMPLETED: 'completed', TASK_STATE_FAILED: 'failed', TASK_STATE_CANCELED: 'canceled',
36
+ TASK_STATE_REJECTED: 'rejected', TASK_STATE_INPUT_REQUIRED: 'input_required', TASK_STATE_AUTH_REQUIRED: 'auth_required',
37
+ };
38
+ class HttpError extends Error {
39
+ status;
40
+ constructor(status, message) {
41
+ super(message);
42
+ this.status = status;
43
+ }
44
+ }
45
+ function atomicJson(file, state) {
46
+ const temp = `${file}.${randomUUID()}.tmp`, fd = openSync(temp, 'wx', 0o600);
47
+ try {
48
+ writeFileSync(fd, JSON.stringify(state));
49
+ fsyncSync(fd);
50
+ }
51
+ finally {
52
+ closeSync(fd);
53
+ }
54
+ renameSync(temp, file);
55
+ const directory = openSync(path.dirname(file), 'r');
56
+ try {
57
+ fsyncSync(directory);
58
+ }
59
+ finally {
60
+ closeSync(directory);
61
+ }
62
+ }
63
+ /** The gateway owns remote polling and delivery; this ledger owns occurrence admission and business acknowledgement. */
64
+ export class A2AAutomation {
65
+ gateway;
66
+ config;
67
+ file;
68
+ state;
69
+ admissions = new Map();
70
+ constructor(gateway, config) {
71
+ this.gateway = gateway;
72
+ this.config = config;
73
+ this.file = path.join(gateway.config.stateDirectory, 'automation.json');
74
+ try {
75
+ this.state = JSON.parse(readFileSync(this.file, 'utf8'));
76
+ if (this.state.version !== 1 || !Array.isArray(this.state.runs) || !Array.isArray(this.state.notices))
77
+ throw new Error('Invalid automation state');
78
+ const runIds = new Set(), occurrences = new Set();
79
+ for (const run of this.state.runs) {
80
+ identifier.parse(run.runId);
81
+ identifier.parse(run.remote);
82
+ identifier.refine(value => path.posix.isAbsolute(value)).parse(run.cwd);
83
+ const input = submitSchema.parse({ scheduleId: run.scheduleId, scheduledFor: run.scheduledFor,
84
+ flowRunId: run.flowRunId, prompt: run.prompt, businessRef: run.businessRef });
85
+ const key = createHash('sha256').update(JSON.stringify([input.scheduleId, input.scheduledFor])).digest('hex');
86
+ if (run.occurrenceKey !== key || run.scheduledFor !== input.scheduledFor ||
87
+ !['dispatching', 'submitted', 'submission_unknown', 'skipped', 'completed', 'failed', 'canceled', 'rejected', 'input_required', 'auth_required'].includes(run.status) ||
88
+ run.originSessionId !== `automation:${run.runId}` || runIds.has(run.runId) || occurrences.has(run.occurrenceKey))
89
+ throw new Error('Invalid automation occurrence');
90
+ runIds.add(run.runId);
91
+ occurrences.add(run.occurrenceKey);
92
+ }
93
+ const noticeIds = new Set();
94
+ for (const record of this.state.notices) {
95
+ identifier.parse(record.noticeId);
96
+ identifier.parse(record.processorId);
97
+ z.string().datetime().parse(record.leaseUntil);
98
+ if (record.businessCompletedAt)
99
+ z.string().datetime().parse(record.businessCompletedAt);
100
+ if (record.gatewayAcknowledgedAt)
101
+ z.string().datetime().parse(record.gatewayAcknowledgedAt);
102
+ const run = this.state.runs.find(value => value.runId === record.runId);
103
+ if (!run || run.originSessionId !== record.originSessionId || noticeIds.has(record.noticeId) ||
104
+ record.notice.noticeId !== record.noticeId || record.notice.originSessionId !== record.originSessionId ||
105
+ record.notice.remote !== run.remote || record.notice.taskId !== run.taskId || (record.gatewayAcknowledgedAt && !record.businessCompletedAt))
106
+ throw new Error('Invalid automation processing record');
107
+ noticeIds.add(record.noticeId);
108
+ }
109
+ // A crash may occur after remote acceptance and before either local ledger is saved.
110
+ // Preserve that uncertainty and never turn recovery into a second SendMessage.
111
+ let changed = false;
112
+ for (const run of this.state.runs)
113
+ if (run.status === 'dispatching') {
114
+ run.status = 'submission_unknown';
115
+ run.reason = 'submission_unconfirmed';
116
+ run.updatedAt = new Date().toISOString();
117
+ changed = true;
118
+ }
119
+ if (changed)
120
+ this.save();
121
+ }
122
+ catch (error) {
123
+ if (error.code !== 'ENOENT')
124
+ throw error;
125
+ this.state = { version: 1, runs: [], notices: [] };
126
+ }
127
+ }
128
+ save() { atomicJson(this.file, this.state); }
129
+ run(runId) {
130
+ const run = this.state.runs.find(value => value.runId === runId);
131
+ if (!run)
132
+ throw new HttpError(404, 'Run not found');
133
+ return run;
134
+ }
135
+ apply(run, task) {
136
+ if (task.originSessionId !== run.originSessionId || task.remote !== run.remote || (run.taskId && task.taskId !== run.taskId))
137
+ throw new Error('Gateway task does not match automation run');
138
+ const status = statuses[task.state] ?? 'submitted';
139
+ if (!active.has(run.status) && run.status !== 'skipped' && active.has(status))
140
+ return;
141
+ Object.assign(run, { taskId: task.taskId, contextId: task.contextId, sessionId: task.sessionId,
142
+ state: task.state, result: task.result, checkedAt: task.checkedAt, stale: task.stale,
143
+ status, updatedAt: new Date().toISOString() });
144
+ delete run.reason;
145
+ this.save();
146
+ }
147
+ async refresh(run) {
148
+ if (run.status === 'skipped' || run.status === 'dispatching')
149
+ return;
150
+ if (!run.taskId) {
151
+ const response = await this.gateway.invoke('remote_agent_list', { originSessionId: run.originSessionId });
152
+ const tasks = response.tasks.map(value => taskViewSchema.parse(value)).filter(value => value.remote === run.remote);
153
+ if (tasks.length === 1)
154
+ this.apply(run, tasks[0]);
155
+ else if (tasks.length > 1) {
156
+ run.status = 'submission_unknown';
157
+ run.reason = 'ambiguous_submission';
158
+ this.save();
159
+ }
160
+ }
161
+ if (run.taskId)
162
+ this.apply(run, taskViewSchema.parse(await this.gateway.invoke('remote_agent_get', {
163
+ originSessionId: run.originSessionId, remote: run.remote, taskId: run.taskId,
164
+ })));
165
+ }
166
+ async submit(params) {
167
+ const input = submitSchema.parse(params);
168
+ if (!Object.hasOwn(this.config.schedules, input.scheduleId))
169
+ throw new HttpError(404, 'Unknown schedule');
170
+ const schedule = this.config.schedules[input.scheduleId];
171
+ const occurrenceKey = createHash('sha256').update(JSON.stringify([input.scheduleId, input.scheduledFor])).digest('hex');
172
+ const duplicate = this.state.runs.find(value => value.occurrenceKey === occurrenceKey);
173
+ if (duplicate) {
174
+ await this.refresh(duplicate);
175
+ return { run: duplicate, created: false };
176
+ }
177
+ const previous = this.admissions.get(input.scheduleId) ?? Promise.resolve();
178
+ const pending = previous.catch(() => { }).then(async () => {
179
+ const existing = this.state.runs.find(value => value.occurrenceKey === occurrenceKey);
180
+ if (existing) {
181
+ await this.refresh(existing);
182
+ return { run: existing, created: false };
183
+ }
184
+ // Refresh under the same admission queue: terminal gateway state can release a schedule
185
+ // even if its notification has not yet been processed by Activepieces.
186
+ for (const value of this.state.runs.filter(value => value.scheduleId === input.scheduleId && active.has(value.status)))
187
+ await this.refresh(value);
188
+ const busy = this.state.runs.find(value => value.scheduleId === input.scheduleId && active.has(value.status));
189
+ const runId = randomUUID(), timestamp = new Date().toISOString();
190
+ const run = { ...input, ...schedule, runId, occurrenceKey, originSessionId: `automation:${runId}`,
191
+ status: busy ? 'skipped' : 'dispatching', ...(busy ? { reason: 'schedule_busy', blockedBy: busy.runId } : {}), createdAt: timestamp, updatedAt: timestamp };
192
+ this.state.runs.push(run);
193
+ // Synchronous write and fsync happen before the first remote operation.
194
+ this.save();
195
+ if (!busy) {
196
+ try {
197
+ this.apply(run, taskViewSchema.parse(await this.gateway.invoke('remote_agent_spawn', {
198
+ ...schedule, originSessionId: run.originSessionId, prompt: input.prompt,
199
+ title: `${input.scheduleId} @ ${input.scheduledFor}`.slice(0, 512),
200
+ })));
201
+ }
202
+ catch {
203
+ run.status = 'submission_unknown';
204
+ run.reason = 'submission_unconfirmed';
205
+ run.updatedAt = new Date().toISOString();
206
+ this.save();
207
+ }
208
+ }
209
+ return { run, created: true };
210
+ });
211
+ this.admissions.set(input.scheduleId, pending);
212
+ try {
213
+ return await pending;
214
+ }
215
+ finally {
216
+ if (this.admissions.get(input.scheduleId) === pending)
217
+ this.admissions.delete(input.scheduleId);
218
+ }
219
+ }
220
+ async list(limit) {
221
+ const runs = this.state.runs.slice(-limit).reverse();
222
+ await Promise.all(runs.map(run => this.refresh(run)));
223
+ return { runs };
224
+ }
225
+ async get(runId) {
226
+ const run = this.run(runId);
227
+ await this.refresh(run);
228
+ return { run };
229
+ }
230
+ async cancel(runId) {
231
+ const run = this.run(runId);
232
+ await this.refresh(run);
233
+ if (!run.taskId)
234
+ throw new HttpError(409, 'Run has no confirmed remote task to cancel');
235
+ this.apply(run, taskViewSchema.parse(await this.gateway.invoke('remote_agent_cancel', {
236
+ originSessionId: run.originSessionId, remote: run.remote, taskId: run.taskId,
237
+ })));
238
+ return { run };
239
+ }
240
+ async knownNotice(noticeId, originSessionId) {
241
+ const run = this.state.runs.find(value => value.originSessionId === originSessionId);
242
+ if (!run)
243
+ throw new HttpError(404, 'Notice not found');
244
+ const response = await this.gateway.invoke('remote_agent_inbox', { originSessionId });
245
+ const notice = response.notices.find(value => value.noticeId === noticeId && value.remote === run.remote && (!run.taskId || value.taskId === run.taskId));
246
+ if (!notice)
247
+ throw new HttpError(404, 'Notice not found');
248
+ // A notice can arrive before the submit HTTP response. Adopt the gateway task using the
249
+ // origin correlation first, without accepting untrusted task IDs from a webhook body.
250
+ this.apply(run, { remote: notice.remote, originSessionId, taskId: notice.taskId, contextId: notice.contextId,
251
+ state: notice.state, result: notice.result, checkedAt: notice.createdAt, stale: false });
252
+ return { run, notice };
253
+ }
254
+ async claim(noticeId, params) {
255
+ const input = processorSchema.parse(params);
256
+ const completed = this.state.notices.find(value => value.noticeId === noticeId && value.originSessionId === input.originSessionId && value.businessCompletedAt);
257
+ if (completed)
258
+ return { claimed: false, runId: completed.runId, reason: 'acknowledged' };
259
+ const { run, notice } = await this.knownNotice(noticeId, input.originSessionId);
260
+ let record = this.state.notices.find(value => value.noticeId === noticeId);
261
+ if (record?.businessCompletedAt)
262
+ return { claimed: false, runId: run.runId, reason: 'acknowledged' };
263
+ if (record && record.processorId !== input.processorId && Date.parse(record.leaseUntil) > Date.now())
264
+ return { claimed: false, runId: run.runId, reason: 'processing', leaseUntil: record.leaseUntil };
265
+ const leaseUntil = new Date(Date.now() + this.config.processingLeaseMs).toISOString();
266
+ if (record)
267
+ Object.assign(record, { processorId: input.processorId, leaseUntil });
268
+ else {
269
+ record = { noticeId, originSessionId: input.originSessionId, runId: run.runId, notice, processorId: input.processorId, leaseUntil };
270
+ this.state.notices.push(record);
271
+ }
272
+ this.save();
273
+ return { claimed: true, runId: run.runId, notice, leaseUntil };
274
+ }
275
+ async ack(noticeId, params) {
276
+ const input = processorSchema.parse(params);
277
+ const record = this.state.notices.find(value => value.noticeId === noticeId && value.originSessionId === input.originSessionId);
278
+ if (!record || record.processorId !== input.processorId)
279
+ throw new HttpError(409, 'Notice must be claimed by this processor');
280
+ if (!record.businessCompletedAt) {
281
+ if (Date.parse(record.leaseUntil) <= Date.now())
282
+ throw new HttpError(409, 'Processing claim expired');
283
+ await this.knownNotice(noticeId, input.originSessionId);
284
+ // Recheck after the await: another processor may have acquired an expired lease.
285
+ if (record.processorId !== input.processorId || Date.parse(record.leaseUntil) <= Date.now())
286
+ throw new HttpError(409, 'Processing claim expired');
287
+ record.businessCompletedAt = new Date().toISOString();
288
+ }
289
+ // Retry this write even if an earlier attempt failed after the in-memory mutation.
290
+ // Gateway acknowledgement is safe only after business completion is on disk.
291
+ this.save();
292
+ if (!record.gatewayAcknowledgedAt) {
293
+ try {
294
+ await this.gateway.invoke('remote_agent_ack', { originSessionId: input.originSessionId, noticeId });
295
+ }
296
+ catch {
297
+ throw new HttpError(503, 'Business completion saved; retry acknowledgement');
298
+ }
299
+ record.gatewayAcknowledgedAt = new Date().toISOString();
300
+ this.save();
301
+ }
302
+ return { acknowledged: true, runId: record.runId, noticeId };
303
+ }
304
+ /** Retry only local inbox acknowledgement after durable business completion, never business effects. */
305
+ async reconcileAcknowledgements() {
306
+ for (const record of this.state.notices.filter(value => value.businessCompletedAt && !value.gatewayAcknowledgedAt)) {
307
+ try {
308
+ this.save();
309
+ await this.gateway.invoke('remote_agent_ack', { originSessionId: record.originSessionId, noticeId: record.noticeId });
310
+ record.gatewayAcknowledgedAt = new Date().toISOString();
311
+ this.save();
312
+ }
313
+ catch { /* Keep the completion record; the gateway's existing reconcile tick will retry. */ }
314
+ }
315
+ }
316
+ }
317
+ async function body(req) {
318
+ if (Number(req.headers['content-length']) > 1024 * 1024)
319
+ throw new HttpError(413, 'Request body too large');
320
+ const chunks = [];
321
+ let length = 0;
322
+ for await (const data of req.iterator({ destroyOnReturn: false })) {
323
+ length += data.length;
324
+ if (length > 1024 * 1024)
325
+ throw new HttpError(413, 'Request body too large');
326
+ chunks.push(Buffer.from(data));
327
+ }
328
+ try {
329
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
330
+ }
331
+ catch {
332
+ throw new HttpError(400, 'Invalid JSON body');
333
+ }
334
+ }
335
+ function json(res, status, data) {
336
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
337
+ res.end(JSON.stringify(data));
338
+ }
339
+ export function createAutomationServer(automation) {
340
+ return http.createServer((req, res) => {
341
+ void (async () => {
342
+ try {
343
+ const expected = Buffer.from(`Bearer ${automation.config.token}`), supplied = Buffer.from(req.headers.authorization ?? '');
344
+ if (supplied.length !== expected.length || !timingSafeEqual(supplied, expected))
345
+ throw new HttpError(401, 'Unauthorized');
346
+ if (req.headers.origin !== undefined)
347
+ throw new HttpError(403, 'Browser-origin invocation is not allowed');
348
+ const url = new URL(req.url ?? '/', 'http://automation.local'), pathname = url.pathname;
349
+ if (pathname === '/automation/runs' && req.method === 'POST') {
350
+ const result = await automation.submit(await body(req));
351
+ return json(res, result.created ? 201 : 200, result);
352
+ }
353
+ if (pathname === '/automation/runs' && req.method === 'GET') {
354
+ const limit = z.coerce.number().int().min(1).max(500).parse(url.searchParams.get('limit') ?? 100);
355
+ return json(res, 200, await automation.list(limit));
356
+ }
357
+ const run = /^\/automation\/runs\/([^/]+)(\/cancel)?$/.exec(pathname);
358
+ if (run && req.method === (run[2] ? 'POST' : 'GET'))
359
+ return json(res, 200, await (run[2] ? automation.cancel(run[1]) : automation.get(run[1])));
360
+ const notice = /^\/automation\/notices\/([^/]+)\/(claim|ack)$/.exec(pathname);
361
+ if (notice && req.method === 'POST')
362
+ return json(res, 200, await (notice[2] === 'claim' ? automation.claim(notice[1], await body(req)) : automation.ack(notice[1], await body(req))));
363
+ throw new HttpError(404, 'No route');
364
+ }
365
+ catch (error) {
366
+ if (error instanceof HttpError && error.status === 413)
367
+ res.setHeader('Connection', 'close');
368
+ json(res, error instanceof HttpError ? error.status : error instanceof z.ZodError ? 400 : 500, { error: error instanceof HttpError ? error.message : error instanceof z.ZodError ? 'Invalid automation parameters' : 'Automation operation failed' });
369
+ }
370
+ })();
371
+ });
372
+ }
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import { A2AAutomation } from './automation.js';
2
3
  declare const configSchema: z.ZodObject<{
3
4
  stateDirectory: z.ZodString;
4
5
  port: z.ZodDefault<z.ZodNumber>;
@@ -16,6 +17,18 @@ declare const configSchema: z.ZodObject<{
16
17
  url: z.ZodString;
17
18
  token: z.ZodString;
18
19
  }, z.core.$strict>>>;
20
+ automation: z.ZodOptional<z.ZodObject<{
21
+ host: z.ZodDefault<z.ZodString>;
22
+ port: z.ZodDefault<z.ZodNumber>;
23
+ token: z.ZodString;
24
+ schedules: z.ZodRecord<z.ZodString, z.ZodObject<{
25
+ remote: z.ZodString;
26
+ cwd: z.ZodString;
27
+ agentPreset: z.ZodOptional<z.ZodString>;
28
+ notificationTarget: z.ZodOptional<z.ZodString>;
29
+ }, z.core.$strict>>;
30
+ processingLeaseMs: z.ZodDefault<z.ZodNumber>;
31
+ }, z.core.$strict>>;
19
32
  pollIntervalMs: z.ZodDefault<z.ZodNumber>;
20
33
  }, z.core.$strict>;
21
34
  export type A2AGatewayConfig = z.input<typeof configSchema>;
@@ -93,6 +106,7 @@ export interface RemoteAgentNotice {
93
106
  }
94
107
  export declare class RemoteAgentGateway {
95
108
  readonly config: Config;
109
+ readonly automation?: A2AAutomation;
96
110
  private readonly lease;
97
111
  private readonly stateFile;
98
112
  private readonly state;
@@ -127,6 +141,7 @@ export declare function serveA2AGateway(input: A2AGatewayConfig, options?: {
127
141
  gateway: RemoteAgentGateway;
128
142
  port: number;
129
143
  callbackPort: number | undefined;
144
+ automationPort: number | undefined;
130
145
  registration: {
131
146
  ok: boolean;
132
147
  reason?: string;