@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.
- package/README.md +180 -9
- package/dist/bin/a2a.d.ts +1 -0
- package/dist/bin/a2a.js +52 -0
- package/dist/bin/acp-service.js +20 -2
- package/dist/src/a2a/automation.d.ts +99 -0
- package/dist/src/a2a/automation.js +372 -0
- package/dist/src/a2a/executor.d.ts +29 -0
- package/dist/src/a2a/executor.js +144 -0
- package/dist/src/a2a/gateway.d.ts +151 -0
- package/dist/src/a2a/gateway.js +454 -0
- package/dist/src/a2a/index.d.ts +9 -0
- package/dist/src/a2a/index.js +5 -0
- package/dist/src/a2a/server.d.ts +22 -0
- package/dist/src/a2a/server.js +339 -0
- package/dist/src/a2a/store.d.ts +34 -0
- package/dist/src/a2a/store.js +468 -0
- package/dist/src/a2a/types.d.ts +26 -0
- package/dist/src/a2a/types.js +1 -0
- package/dist/src/acp-connection.js +3 -2
- package/dist/src/bridge.js +18 -3
- package/package.json +15 -8
- package/skills/acp-service/SKILL.md +90 -0
- package/skills/acp-service/agents/openai.yaml +3 -0
- package/skills/acp-service/references/a2a.md +183 -0
- package/skills/acp-service/references/acp.md +104 -0
- package/skills/acp-service/references/dsh.md +61 -0
- package/vendor/dsh/README.md +34 -10
- package/vendor/dsh/a2a-executor.d.ts +26 -0
- package/vendor/dsh/a2a-executor.js +195 -0
- package/vendor/dsh/a2a.d.ts +15 -0
- package/vendor/dsh/a2a.js +32 -0
- package/vendor/dsh/adapter.js +33 -10
- package/vendor/dsh/index.d.ts +5 -1
- package/vendor/dsh/index.js +3 -0
- package/vendor/runtime/dist/docs-site/output-formats.html +4 -1
- package/vendor/runtime/dist/runtime.d.ts +8 -0
- package/vendor/runtime/dist/runtime.d.ts.map +1 -1
- package/vendor/runtime/dist/runtime.js +3 -1
- package/vendor/runtime/dist/runtime.js.map +1 -1
- package/vendor/runtime/skills/acpx/SKILL.md +1 -0
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|