@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,151 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { A2AAutomation } from './automation.js';
|
|
3
|
+
declare const configSchema: z.ZodObject<{
|
|
4
|
+
stateDirectory: z.ZodString;
|
|
5
|
+
port: z.ZodDefault<z.ZodNumber>;
|
|
6
|
+
remotes: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
7
|
+
url: z.ZodString;
|
|
8
|
+
token: z.ZodString;
|
|
9
|
+
}, z.core.$strict>>;
|
|
10
|
+
callback: z.ZodOptional<z.ZodObject<{
|
|
11
|
+
host: z.ZodString;
|
|
12
|
+
port: z.ZodNumber;
|
|
13
|
+
url: z.ZodString;
|
|
14
|
+
token: z.ZodString;
|
|
15
|
+
}, z.core.$strict>>;
|
|
16
|
+
notificationTargets: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
17
|
+
url: z.ZodString;
|
|
18
|
+
token: z.ZodString;
|
|
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>>;
|
|
32
|
+
pollIntervalMs: z.ZodDefault<z.ZodNumber>;
|
|
33
|
+
}, z.core.$strict>;
|
|
34
|
+
export type A2AGatewayConfig = z.input<typeof configSchema>;
|
|
35
|
+
type Config = z.output<typeof configSchema>;
|
|
36
|
+
export declare const REMOTE_AGENT_METHODS: {
|
|
37
|
+
remote_agent_spawn: {
|
|
38
|
+
description: string;
|
|
39
|
+
parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
40
|
+
remote: z.ZodString;
|
|
41
|
+
prompt: z.ZodString;
|
|
42
|
+
cwd: z.ZodString;
|
|
43
|
+
agentPreset: z.ZodOptional<z.ZodString>;
|
|
44
|
+
notificationTarget: z.ZodOptional<z.ZodString>;
|
|
45
|
+
title: z.ZodOptional<z.ZodString>;
|
|
46
|
+
originSessionId: z.ZodString;
|
|
47
|
+
}, z.core.$strict>>;
|
|
48
|
+
};
|
|
49
|
+
remote_agent_get: {
|
|
50
|
+
description: string;
|
|
51
|
+
parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
52
|
+
remote: z.ZodString;
|
|
53
|
+
taskId: z.ZodString;
|
|
54
|
+
originSessionId: z.ZodString;
|
|
55
|
+
}, z.core.$strict>>;
|
|
56
|
+
};
|
|
57
|
+
remote_agent_cancel: {
|
|
58
|
+
description: string;
|
|
59
|
+
parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
60
|
+
remote: z.ZodString;
|
|
61
|
+
taskId: z.ZodString;
|
|
62
|
+
originSessionId: z.ZodString;
|
|
63
|
+
}, z.core.$strict>>;
|
|
64
|
+
};
|
|
65
|
+
remote_agent_message: {
|
|
66
|
+
description: string;
|
|
67
|
+
parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
68
|
+
prompt: z.ZodString;
|
|
69
|
+
remote: z.ZodString;
|
|
70
|
+
taskId: z.ZodString;
|
|
71
|
+
originSessionId: z.ZodString;
|
|
72
|
+
}, z.core.$strict>>;
|
|
73
|
+
};
|
|
74
|
+
remote_agent_list: {
|
|
75
|
+
description: string;
|
|
76
|
+
parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
77
|
+
originSessionId: z.ZodString;
|
|
78
|
+
}, z.core.$strict>>;
|
|
79
|
+
};
|
|
80
|
+
remote_agent_inbox: {
|
|
81
|
+
description: string;
|
|
82
|
+
parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
83
|
+
originSessionId: z.ZodString;
|
|
84
|
+
}, z.core.$strict>>;
|
|
85
|
+
};
|
|
86
|
+
remote_agent_ack: {
|
|
87
|
+
description: string;
|
|
88
|
+
parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
|
|
89
|
+
noticeId: z.ZodString;
|
|
90
|
+
originSessionId: z.ZodString;
|
|
91
|
+
}, z.core.$strict>>;
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
export interface RemoteAgentNotice {
|
|
95
|
+
noticeId: string;
|
|
96
|
+
originSessionId: string;
|
|
97
|
+
remote: string;
|
|
98
|
+
taskId: string;
|
|
99
|
+
contextId: string;
|
|
100
|
+
cwd: string;
|
|
101
|
+
agentPreset?: string;
|
|
102
|
+
title?: string;
|
|
103
|
+
state: string;
|
|
104
|
+
result: string;
|
|
105
|
+
createdAt: string;
|
|
106
|
+
}
|
|
107
|
+
export declare class RemoteAgentGateway {
|
|
108
|
+
readonly config: Config;
|
|
109
|
+
readonly automation?: A2AAutomation;
|
|
110
|
+
private readonly lease;
|
|
111
|
+
private readonly stateFile;
|
|
112
|
+
private readonly state;
|
|
113
|
+
private readonly clients;
|
|
114
|
+
private readonly refreshing;
|
|
115
|
+
private readonly delivering;
|
|
116
|
+
private readonly controllers;
|
|
117
|
+
private readonly operations;
|
|
118
|
+
private reconciling?;
|
|
119
|
+
private readonly timer;
|
|
120
|
+
private closed;
|
|
121
|
+
constructor(input: A2AGatewayConfig);
|
|
122
|
+
private save;
|
|
123
|
+
private client;
|
|
124
|
+
private auth;
|
|
125
|
+
private job;
|
|
126
|
+
private view;
|
|
127
|
+
private accept;
|
|
128
|
+
private update;
|
|
129
|
+
private refresh;
|
|
130
|
+
reconcile(): Promise<void>;
|
|
131
|
+
private deliver;
|
|
132
|
+
invoke(method: string, params: unknown): Promise<unknown>;
|
|
133
|
+
private invokeMethod;
|
|
134
|
+
/** Push events are hints. GetTask remains authoritative, including after missed callbacks. */
|
|
135
|
+
receivePush(event: unknown): Promise<void>;
|
|
136
|
+
close(): Promise<void>;
|
|
137
|
+
}
|
|
138
|
+
export declare function serveA2AGateway(input: A2AGatewayConfig, options?: {
|
|
139
|
+
report?: boolean;
|
|
140
|
+
}): Promise<{
|
|
141
|
+
gateway: RemoteAgentGateway;
|
|
142
|
+
port: number;
|
|
143
|
+
callbackPort: number | undefined;
|
|
144
|
+
automationPort: number | undefined;
|
|
145
|
+
registration: {
|
|
146
|
+
ok: boolean;
|
|
147
|
+
reason?: string;
|
|
148
|
+
} | undefined;
|
|
149
|
+
close: () => Promise<void>;
|
|
150
|
+
}>;
|
|
151
|
+
export {};
|
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
/** Main-agent tools backed by standard A2A, with a durable completion inbox. */
|
|
2
|
+
import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import http from 'node:http';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { CancelTaskRequest, GetTaskRequest, SendMessageRequest, Task } from '@a2a-js/sdk';
|
|
7
|
+
import { ClientFactory, DefaultAgentCardResolver, JsonRpcTransportFactory } from '@a2a-js/sdk/client';
|
|
8
|
+
import { reportAndHoldRegistration } from '@1agents/dreammate-node/client';
|
|
9
|
+
import { z } from 'zod';
|
|
10
|
+
import { FileA2AStore } from './store.js';
|
|
11
|
+
import { A2AAutomation, automationConfigSchema, createAutomationServer } from './automation.js';
|
|
12
|
+
const string = z.string().trim().min(1).max(512);
|
|
13
|
+
const endpoint = z.string().url().refine(value => {
|
|
14
|
+
const url = new URL(value);
|
|
15
|
+
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password;
|
|
16
|
+
}, 'Expected an HTTP(S) URL without embedded credentials');
|
|
17
|
+
const configSchema = z.object({
|
|
18
|
+
stateDirectory: string,
|
|
19
|
+
port: z.number().int().min(0).max(65535).default(36814),
|
|
20
|
+
remotes: z.record(string, z.object({ url: endpoint, token: string }).strict()),
|
|
21
|
+
callback: z.object({ host: string, port: z.number().int().min(0).max(65535), url: endpoint, token: string }).strict().optional(),
|
|
22
|
+
notificationTargets: z.record(string, z.object({ url: endpoint, token: string }).strict()).default({}),
|
|
23
|
+
automation: automationConfigSchema.optional(),
|
|
24
|
+
pollIntervalMs: z.number().int().min(50).max(60_000).default(3000),
|
|
25
|
+
}).strict().superRefine((config, ctx) => {
|
|
26
|
+
for (const [id, schedule] of Object.entries(config.automation?.schedules ?? {})) {
|
|
27
|
+
if (!Object.hasOwn(config.remotes, schedule.remote))
|
|
28
|
+
ctx.addIssue({ code: 'custom', path: ['automation', 'schedules', id, 'remote'], message: 'Unknown automation remote' });
|
|
29
|
+
if (schedule.notificationTarget && !Object.hasOwn(config.notificationTargets, schedule.notificationTarget))
|
|
30
|
+
ctx.addIssue({ code: 'custom', path: ['automation', 'schedules', id, 'notificationTarget'], message: 'Unknown automation notificationTarget' });
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
const originFields = { originSessionId: string };
|
|
34
|
+
const taskFields = { ...originFields, remote: string, taskId: string };
|
|
35
|
+
const prompt = z.string().min(1).max(256 * 1024).refine(value => Boolean(value.trim()), 'Prompt must contain text');
|
|
36
|
+
const spawnSchema = z.object({ ...originFields, remote: string, prompt,
|
|
37
|
+
cwd: string.refine(value => path.posix.isAbsolute(value), 'cwd must be an absolute remote path'),
|
|
38
|
+
agentPreset: string.optional(), notificationTarget: string.optional(), title: string.optional(),
|
|
39
|
+
}).strict();
|
|
40
|
+
const taskSchema = z.object(taskFields).strict();
|
|
41
|
+
const messageSchema = z.object({ ...taskFields, prompt }).strict();
|
|
42
|
+
const inboxSchema = z.object(originFields).strict();
|
|
43
|
+
const ackSchema = z.object({ ...originFields, noticeId: string }).strict();
|
|
44
|
+
export const REMOTE_AGENT_METHODS = {
|
|
45
|
+
remote_agent_spawn: { description: '在配置的远端 DSH 工作目录中派发独立任务,立即返回 taskId。prompt 必须包含完整上下文。cwd 是远端绝对路径;每次 spawn 创建新会话。完成事件进入 originSessionId 的持久收件箱。', parameters: z.toJSONSchema(spawnSchema) },
|
|
46
|
+
remote_agent_get: { description: '查询当前主会话派发的远端任务。离线时返回缓存与 stale 标记,离线不等于任务失败。', parameters: z.toJSONSchema(taskSchema) },
|
|
47
|
+
remote_agent_cancel: { description: '取消指定远端任务,只取消这项任务自己的执行。', parameters: z.toJSONSchema(taskSchema) },
|
|
48
|
+
remote_agent_message: { description: '向同一个远端 DSH 会话发送后续指令,返回新 taskId,复用 contextId 与 cwd。', parameters: z.toJSONSchema(messageSchema) },
|
|
49
|
+
remote_agent_list: { description: '列出当前主会话派发的远端任务。', parameters: z.toJSONSchema(inboxSchema) },
|
|
50
|
+
remote_agent_inbox: { description: '读取当前主会话未确认的完成或需要输入通知。读取不删除;处理后调用 remote_agent_ack。', parameters: z.toJSONSchema(inboxSchema) },
|
|
51
|
+
remote_agent_ack: { description: '确认主会话已处理指定通知。noticeId 稳定,重复确认安全。', parameters: z.toJSONSchema(ackSchema) },
|
|
52
|
+
};
|
|
53
|
+
const terminal = new Set(['TASK_STATE_COMPLETED', 'TASK_STATE_FAILED', 'TASK_STATE_CANCELED', 'TASK_STATE_REJECTED']);
|
|
54
|
+
const actionable = new Set([...terminal, 'TASK_STATE_INPUT_REQUIRED', 'TASK_STATE_AUTH_REQUIRED']);
|
|
55
|
+
const wire = (task) => Task.toJSON(task);
|
|
56
|
+
const taskState = (job) => wire(Task.fromJSON(job.task)).status?.state ?? 'TASK_STATE_UNSPECIFIED';
|
|
57
|
+
const resultText = (task) => task.artifacts.flatMap(artifact => artifact.parts
|
|
58
|
+
.filter(part => part.content?.$case === 'text').map(part => part.content.value)).join('\n') ||
|
|
59
|
+
task.status?.message?.parts.filter(part => part.content?.$case === 'text').map(part => part.content.value).join('\n') || '';
|
|
60
|
+
function atomicJson(file, value) {
|
|
61
|
+
const temp = `${file}.${randomUUID()}.tmp`;
|
|
62
|
+
const fd = openSync(temp, 'wx', 0o600);
|
|
63
|
+
try {
|
|
64
|
+
writeFileSync(fd, JSON.stringify(value));
|
|
65
|
+
fsyncSync(fd);
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
closeSync(fd);
|
|
69
|
+
}
|
|
70
|
+
renameSync(temp, file);
|
|
71
|
+
const dir = openSync(path.dirname(file), 'r');
|
|
72
|
+
try {
|
|
73
|
+
fsyncSync(dir);
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
closeSync(dir);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export class RemoteAgentGateway {
|
|
80
|
+
config;
|
|
81
|
+
automation;
|
|
82
|
+
lease;
|
|
83
|
+
stateFile;
|
|
84
|
+
state;
|
|
85
|
+
clients = new Map();
|
|
86
|
+
refreshing = new Map();
|
|
87
|
+
delivering = new Set();
|
|
88
|
+
controllers = new Set();
|
|
89
|
+
operations = new Set();
|
|
90
|
+
reconciling;
|
|
91
|
+
timer;
|
|
92
|
+
closed = false;
|
|
93
|
+
constructor(input) {
|
|
94
|
+
this.config = configSchema.parse(input);
|
|
95
|
+
if (!path.isAbsolute(this.config.stateDirectory))
|
|
96
|
+
throw new Error('stateDirectory must be absolute');
|
|
97
|
+
mkdirSync(this.config.stateDirectory, { recursive: true, mode: 0o700 });
|
|
98
|
+
// Reuse the A2A store's tested single-owner lease, in a separate empty
|
|
99
|
+
// directory: local restarts must never mark remote executions failed.
|
|
100
|
+
this.lease = new FileA2AStore(path.join(this.config.stateDirectory, 'lease'));
|
|
101
|
+
this.stateFile = path.join(this.config.stateDirectory, 'gateway.json');
|
|
102
|
+
try {
|
|
103
|
+
this.state = JSON.parse(readFileSync(this.stateFile, 'utf8'));
|
|
104
|
+
if (this.state.version !== 1 || !Array.isArray(this.state.jobs) || !Array.isArray(this.state.notices))
|
|
105
|
+
throw new Error('Invalid gateway state');
|
|
106
|
+
for (const job of this.state.jobs) {
|
|
107
|
+
string.parse(job.originSessionId);
|
|
108
|
+
string.parse(job.remote);
|
|
109
|
+
string.parse(job.taskId);
|
|
110
|
+
if (Task.fromJSON(job.task).id !== job.taskId)
|
|
111
|
+
throw new Error('Invalid gateway task ID');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
if (error.code !== 'ENOENT') {
|
|
116
|
+
this.lease.close();
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
this.state = { version: 1, jobs: [], notices: [] };
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
if (this.config.automation)
|
|
123
|
+
this.automation = new A2AAutomation(this, this.config.automation);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
this.lease.close();
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
this.timer = setInterval(() => { void this.reconcile(); }, this.config.pollIntervalMs);
|
|
130
|
+
this.timer.unref();
|
|
131
|
+
void this.reconcile();
|
|
132
|
+
}
|
|
133
|
+
save() { atomicJson(this.stateFile, this.state); }
|
|
134
|
+
client(remote) {
|
|
135
|
+
const config = this.config.remotes[remote];
|
|
136
|
+
if (!config)
|
|
137
|
+
throw new Error(`Unknown remote: ${remote}`);
|
|
138
|
+
let pending = this.clients.get(remote);
|
|
139
|
+
if (!pending) {
|
|
140
|
+
const fetchImpl = async (input, init) => {
|
|
141
|
+
if (this.closed)
|
|
142
|
+
throw new Error('Gateway is closed');
|
|
143
|
+
const url = new URL(input instanceof Request ? input.url : String(input));
|
|
144
|
+
if (url.origin !== new URL(config.url).origin)
|
|
145
|
+
throw new Error('Agent Card endpoint must use the configured remote origin');
|
|
146
|
+
const controller = new AbortController();
|
|
147
|
+
this.controllers.add(controller);
|
|
148
|
+
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(10_000), ...(init?.signal ? [init.signal] : [])]);
|
|
149
|
+
try {
|
|
150
|
+
return await fetch(input, { ...init, signal, redirect: 'error' });
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
this.controllers.delete(controller);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
pending = new ClientFactory({ transports: [new JsonRpcTransportFactory({ fetchImpl })],
|
|
157
|
+
cardResolver: new DefaultAgentCardResolver({ fetchImpl }), clientConfig: { polling: true } }).createFromUrl(config.url);
|
|
158
|
+
this.clients.set(remote, pending);
|
|
159
|
+
void pending.catch(() => { if (this.clients.get(remote) === pending)
|
|
160
|
+
this.clients.delete(remote); });
|
|
161
|
+
}
|
|
162
|
+
return pending;
|
|
163
|
+
}
|
|
164
|
+
auth(remote) { return { serviceParameters: { Authorization: `Bearer ${this.config.remotes[remote].token}` } }; }
|
|
165
|
+
job(params) {
|
|
166
|
+
const job = this.state.jobs.find(value => value.remote === params.remote && value.taskId === params.taskId && value.originSessionId === params.originSessionId);
|
|
167
|
+
if (!job)
|
|
168
|
+
throw new Error('Task not found for this origin session');
|
|
169
|
+
return job;
|
|
170
|
+
}
|
|
171
|
+
view(job) {
|
|
172
|
+
const task = Task.fromJSON(job.task);
|
|
173
|
+
return { remote: job.remote, taskId: job.taskId, contextId: job.contextId, originSessionId: job.originSessionId,
|
|
174
|
+
cwd: job.cwd, agentPreset: job.agentPreset, sessionId: task.metadata?.['1agents']?.sessionId,
|
|
175
|
+
state: taskState(job), result: resultText(task), checkedAt: job.checkedAt, stale: Boolean(job.stale) };
|
|
176
|
+
}
|
|
177
|
+
accept(task, fields) {
|
|
178
|
+
const target = task.metadata?.['1agents'];
|
|
179
|
+
const job = { ...fields, taskId: task.id, contextId: task.contextId, task: wire(task), checkedAt: new Date().toISOString(),
|
|
180
|
+
cwd: typeof target?.cwd === 'string' ? target.cwd : fields.cwd,
|
|
181
|
+
agentPreset: typeof target?.agentPreset === 'string' ? target.agentPreset : fields.agentPreset };
|
|
182
|
+
this.state.jobs.push(job);
|
|
183
|
+
this.update(job, task);
|
|
184
|
+
return job;
|
|
185
|
+
}
|
|
186
|
+
update(job, task) {
|
|
187
|
+
if (task.id !== job.taskId || task.contextId !== job.contextId)
|
|
188
|
+
throw new Error('Remote returned a different task');
|
|
189
|
+
const previous = Task.fromJSON(job.task);
|
|
190
|
+
if ((terminal.has(taskState(job)) && !terminal.has(wire(task).status?.state)) ||
|
|
191
|
+
Date.parse(previous.status?.timestamp ?? '') > Date.parse(task.status?.timestamp ?? ''))
|
|
192
|
+
return;
|
|
193
|
+
job.task = wire(task);
|
|
194
|
+
job.checkedAt = new Date().toISOString();
|
|
195
|
+
job.stale = false;
|
|
196
|
+
const state = taskState(job);
|
|
197
|
+
if (actionable.has(state)) {
|
|
198
|
+
const noticeId = createHash('sha256').update(JSON.stringify([job.remote, job.taskId, state, task.status?.timestamp])).digest('hex');
|
|
199
|
+
if (!this.state.notices.some(value => value.notice.noticeId === noticeId))
|
|
200
|
+
this.state.notices.push({ target: job.notificationTarget,
|
|
201
|
+
notice: { noticeId, originSessionId: job.originSessionId, remote: job.remote, taskId: job.taskId, contextId: job.contextId,
|
|
202
|
+
cwd: job.cwd, agentPreset: job.agentPreset, title: job.title, state, result: resultText(task), createdAt: new Date().toISOString() } });
|
|
203
|
+
}
|
|
204
|
+
this.save();
|
|
205
|
+
}
|
|
206
|
+
async refresh(job) {
|
|
207
|
+
const key = `${job.remote}:${job.taskId}`;
|
|
208
|
+
const previous = this.refreshing.get(key);
|
|
209
|
+
if (previous)
|
|
210
|
+
return previous;
|
|
211
|
+
const pending = (async () => {
|
|
212
|
+
try {
|
|
213
|
+
const client = await this.client(job.remote);
|
|
214
|
+
this.update(job, await client.getTask(GetTaskRequest.fromJSON({ id: job.taskId }), this.auth(job.remote)));
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
job.stale = true;
|
|
218
|
+
this.save();
|
|
219
|
+
}
|
|
220
|
+
})();
|
|
221
|
+
this.refreshing.set(key, pending);
|
|
222
|
+
try {
|
|
223
|
+
await pending;
|
|
224
|
+
}
|
|
225
|
+
finally {
|
|
226
|
+
this.refreshing.delete(key);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
async reconcile() {
|
|
230
|
+
if (this.closed)
|
|
231
|
+
return;
|
|
232
|
+
if (this.reconciling)
|
|
233
|
+
return this.reconciling;
|
|
234
|
+
const pending = (async () => {
|
|
235
|
+
await Promise.allSettled(this.state.jobs.filter(job => !terminal.has(taskState(job))).map(job => this.refresh(job)));
|
|
236
|
+
if (this.closed)
|
|
237
|
+
return;
|
|
238
|
+
await Promise.allSettled(this.state.notices.filter(record => record.target && !record.delivered && !record.acknowledged).map(record => this.deliver(record)));
|
|
239
|
+
await this.automation?.reconcileAcknowledgements();
|
|
240
|
+
})();
|
|
241
|
+
this.reconciling = pending;
|
|
242
|
+
try {
|
|
243
|
+
await pending;
|
|
244
|
+
}
|
|
245
|
+
finally {
|
|
246
|
+
this.reconciling = undefined;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async deliver(record) {
|
|
250
|
+
const id = record.notice.noticeId;
|
|
251
|
+
const target = this.config.notificationTargets[record.target];
|
|
252
|
+
if (!target || this.delivering.has(id))
|
|
253
|
+
return;
|
|
254
|
+
this.delivering.add(id);
|
|
255
|
+
const controller = new AbortController();
|
|
256
|
+
this.controllers.add(controller);
|
|
257
|
+
try {
|
|
258
|
+
const response = await fetch(target.url, { method: 'POST', redirect: 'error', signal: AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]),
|
|
259
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${target.token}`, 'Idempotency-Key': id }, body: JSON.stringify(record.notice) });
|
|
260
|
+
await response.body?.cancel();
|
|
261
|
+
if (response.ok) {
|
|
262
|
+
record.delivered = true;
|
|
263
|
+
this.save();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
catch { /* Durable outbox retries on the next tick, with the same ID. */ }
|
|
267
|
+
finally {
|
|
268
|
+
this.controllers.delete(controller);
|
|
269
|
+
this.delivering.delete(id);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
async invoke(method, params) {
|
|
273
|
+
if (this.closed)
|
|
274
|
+
throw new Error('Gateway is closed');
|
|
275
|
+
const operation = this.invokeMethod(method, params);
|
|
276
|
+
this.operations.add(operation);
|
|
277
|
+
try {
|
|
278
|
+
return await operation;
|
|
279
|
+
}
|
|
280
|
+
finally {
|
|
281
|
+
this.operations.delete(operation);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
async invokeMethod(method, params) {
|
|
285
|
+
if (method === 'remote_agent_spawn') {
|
|
286
|
+
const input = spawnSchema.parse(params);
|
|
287
|
+
if (input.notificationTarget && !this.config.notificationTargets[input.notificationTarget])
|
|
288
|
+
throw new Error('Unknown notificationTarget');
|
|
289
|
+
const client = await this.client(input.remote);
|
|
290
|
+
const task = await client.sendMessage(SendMessageRequest.fromJSON({ message: { messageId: randomUUID(), role: 'ROLE_USER', parts: [{ text: input.prompt }] },
|
|
291
|
+
metadata: { '1agents': { cwd: input.cwd, ...(input.agentPreset ? { agentPreset: input.agentPreset } : {}) } },
|
|
292
|
+
configuration: { returnImmediately: true, ...(this.config.callback ? { taskPushNotificationConfig: { url: this.config.callback.url,
|
|
293
|
+
authentication: { scheme: 'Bearer', credentials: this.config.callback.token } } } : {}) } }), this.auth(input.remote));
|
|
294
|
+
if (!('id' in task))
|
|
295
|
+
throw new Error('Remote did not return an A2A Task');
|
|
296
|
+
return this.view(this.accept(task, { remote: input.remote, originSessionId: input.originSessionId, cwd: input.cwd, agentPreset: input.agentPreset, title: input.title, notificationTarget: input.notificationTarget }));
|
|
297
|
+
}
|
|
298
|
+
if (method === 'remote_agent_get' || method === 'remote_agent_cancel') {
|
|
299
|
+
const job = this.job(taskSchema.parse(params));
|
|
300
|
+
if (method === 'remote_agent_cancel') {
|
|
301
|
+
const client = await this.client(job.remote);
|
|
302
|
+
this.update(job, await client.cancelTask(CancelTaskRequest.fromJSON({ id: job.taskId }), this.auth(job.remote)));
|
|
303
|
+
}
|
|
304
|
+
else
|
|
305
|
+
await this.refresh(job);
|
|
306
|
+
return this.view(job);
|
|
307
|
+
}
|
|
308
|
+
if (method === 'remote_agent_message') {
|
|
309
|
+
const input = messageSchema.parse(params), previous = this.job(input);
|
|
310
|
+
const client = await this.client(input.remote);
|
|
311
|
+
const task = await client.sendMessage(SendMessageRequest.fromJSON({ message: { messageId: randomUUID(), role: 'ROLE_USER', contextId: previous.contextId, parts: [{ text: input.prompt }] },
|
|
312
|
+
configuration: { returnImmediately: true, ...(this.config.callback ? { taskPushNotificationConfig: { url: this.config.callback.url,
|
|
313
|
+
authentication: { scheme: 'Bearer', credentials: this.config.callback.token } } } : {}) } }), this.auth(input.remote));
|
|
314
|
+
if (!('id' in task))
|
|
315
|
+
throw new Error('Remote did not return an A2A Task');
|
|
316
|
+
return this.view(this.accept(task, { remote: previous.remote, originSessionId: previous.originSessionId, cwd: previous.cwd, agentPreset: previous.agentPreset,
|
|
317
|
+
title: previous.title, notificationTarget: previous.notificationTarget }));
|
|
318
|
+
}
|
|
319
|
+
if (method === 'remote_agent_list' || method === 'remote_agent_inbox') {
|
|
320
|
+
const { originSessionId } = inboxSchema.parse(params);
|
|
321
|
+
return method === 'remote_agent_list' ? { tasks: this.state.jobs.filter(job => job.originSessionId === originSessionId).map(job => this.view(job)) } :
|
|
322
|
+
{ notices: this.state.notices.filter(record => record.notice.originSessionId === originSessionId && !record.acknowledged).map(record => record.notice) };
|
|
323
|
+
}
|
|
324
|
+
if (method === 'remote_agent_ack') {
|
|
325
|
+
const input = ackSchema.parse(params);
|
|
326
|
+
const notice = this.state.notices.find(record => record.notice.originSessionId === input.originSessionId && record.notice.noticeId === input.noticeId);
|
|
327
|
+
if (!notice)
|
|
328
|
+
throw new Error('Notice not found for this origin session');
|
|
329
|
+
notice.acknowledged = true;
|
|
330
|
+
this.save();
|
|
331
|
+
return { acknowledged: true, noticeId: input.noticeId };
|
|
332
|
+
}
|
|
333
|
+
throw new Error(`Unknown method: ${method}`);
|
|
334
|
+
}
|
|
335
|
+
/** Push events are hints. GetTask remains authoritative, including after missed callbacks. */
|
|
336
|
+
async receivePush(event) {
|
|
337
|
+
const value = z.object({ task: z.object({ id: string }).passthrough().optional(), statusUpdate: z.object({ taskId: string }).passthrough().optional(),
|
|
338
|
+
artifactUpdate: z.object({ taskId: string }).passthrough().optional() }).passthrough().parse(event);
|
|
339
|
+
const taskId = value.task?.id ?? value.statusUpdate?.taskId ?? value.artifactUpdate?.taskId;
|
|
340
|
+
if (!taskId)
|
|
341
|
+
throw new Error('Missing A2A event task ID');
|
|
342
|
+
await Promise.allSettled(this.state.jobs.filter(job => job.taskId === taskId).map(job => this.refresh(job)));
|
|
343
|
+
}
|
|
344
|
+
async close() {
|
|
345
|
+
if (this.closed)
|
|
346
|
+
return;
|
|
347
|
+
this.closed = true;
|
|
348
|
+
clearInterval(this.timer);
|
|
349
|
+
for (const controller of this.controllers)
|
|
350
|
+
controller.abort();
|
|
351
|
+
await Promise.allSettled([...this.refreshing.values(), ...this.operations, ...(this.reconciling ? [this.reconciling] : [])]);
|
|
352
|
+
// Delivery promises release their controllers after abort; HTTP requests
|
|
353
|
+
// may have already succeeded, so any retry keeps the stable notice ID.
|
|
354
|
+
this.lease.close();
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
async function body(req) {
|
|
358
|
+
let length = 0;
|
|
359
|
+
const chunks = [];
|
|
360
|
+
for await (const data of req) {
|
|
361
|
+
length += data.length;
|
|
362
|
+
if (length > 1024 * 1024)
|
|
363
|
+
throw new Error('Request body too large');
|
|
364
|
+
chunks.push(Buffer.from(data));
|
|
365
|
+
}
|
|
366
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
367
|
+
}
|
|
368
|
+
function json(res, status, data) {
|
|
369
|
+
res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
370
|
+
res.end(JSON.stringify(data));
|
|
371
|
+
}
|
|
372
|
+
function authenticated(req, token) {
|
|
373
|
+
const expected = Buffer.from(`Bearer ${token}`), supplied = Buffer.from(req.headers.authorization ?? '');
|
|
374
|
+
return supplied.length === expected.length && timingSafeEqual(supplied, expected);
|
|
375
|
+
}
|
|
376
|
+
async function listen(server, port, host) {
|
|
377
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
|
|
378
|
+
return server.address().port;
|
|
379
|
+
}
|
|
380
|
+
async function stop(server) {
|
|
381
|
+
server.closeIdleConnections();
|
|
382
|
+
await new Promise(resolve => server.close(() => resolve()));
|
|
383
|
+
}
|
|
384
|
+
export async function serveA2AGateway(input, options = {}) {
|
|
385
|
+
const gateway = new RemoteAgentGateway(input);
|
|
386
|
+
const server = http.createServer((req, res) => {
|
|
387
|
+
void (async () => {
|
|
388
|
+
try {
|
|
389
|
+
if (req.method === 'GET' && req.url === '/health')
|
|
390
|
+
return json(res, 200, { status: 'ok', service: 'a2a-gateway', remotes: Object.keys(gateway.config.remotes) });
|
|
391
|
+
if (req.method !== 'POST' || req.url !== '/invoke')
|
|
392
|
+
return json(res, 404, { error: 'No route' });
|
|
393
|
+
// Local tools are trusted. The separate tailnet receiver below never exposes /invoke.
|
|
394
|
+
if (req.headers.origin)
|
|
395
|
+
return json(res, 403, { error: 'Browser-origin invocation is not allowed' });
|
|
396
|
+
const request = z.object({ method: string.optional(), capability: string.optional(), params: z.unknown() }).parse(await body(req));
|
|
397
|
+
return json(res, 200, await gateway.invoke(request.method ?? request.capability ?? '', request.params));
|
|
398
|
+
}
|
|
399
|
+
catch (error) {
|
|
400
|
+
json(res, 400, { error: error instanceof z.ZodError ? 'Invalid method parameters' : error instanceof Error ? error.message : 'Invocation failed' });
|
|
401
|
+
}
|
|
402
|
+
})();
|
|
403
|
+
});
|
|
404
|
+
let receiver;
|
|
405
|
+
let callbackPort;
|
|
406
|
+
let automationServer;
|
|
407
|
+
let automationPort;
|
|
408
|
+
try {
|
|
409
|
+
const port = await listen(server, gateway.config.port, '127.0.0.1');
|
|
410
|
+
if (gateway.config.callback) {
|
|
411
|
+
const callback = gateway.config.callback;
|
|
412
|
+
receiver = http.createServer((req, res) => {
|
|
413
|
+
void (async () => {
|
|
414
|
+
if (!authenticated(req, callback.token))
|
|
415
|
+
return json(res, 401, { error: 'Unauthorized' });
|
|
416
|
+
if (req.method !== 'POST' || req.url !== new URL(callback.url).pathname)
|
|
417
|
+
return json(res, 404, { error: 'No route' });
|
|
418
|
+
try {
|
|
419
|
+
const event = await body(req);
|
|
420
|
+
json(res, 202, { accepted: true });
|
|
421
|
+
void gateway.receivePush(event).catch(() => { });
|
|
422
|
+
}
|
|
423
|
+
catch {
|
|
424
|
+
json(res, 400, { error: 'Invalid A2A event' });
|
|
425
|
+
}
|
|
426
|
+
})();
|
|
427
|
+
});
|
|
428
|
+
callbackPort = await listen(receiver, callback.port, callback.host);
|
|
429
|
+
}
|
|
430
|
+
if (gateway.config.automation && gateway.automation) {
|
|
431
|
+
automationServer = createAutomationServer(gateway.automation);
|
|
432
|
+
automationPort = await listen(automationServer, gateway.config.automation.port, gateway.config.automation.host);
|
|
433
|
+
}
|
|
434
|
+
const entry = { id: 'a2a-gateway', name: 'DSH 远端智能体', kind: 'agent_runtime',
|
|
435
|
+
capabilities: Object.keys(REMOTE_AGENT_METHODS), execution: 'http', port, reachability: 'localhost', health: '/health', methods: REMOTE_AGENT_METHODS };
|
|
436
|
+
const registration = options.report === false ? undefined : await reportAndHoldRegistration(entry);
|
|
437
|
+
let closing;
|
|
438
|
+
return { gateway, port, callbackPort, automationPort, registration, close: async () => {
|
|
439
|
+
closing ??= (async () => {
|
|
440
|
+
// Stop accepting requests and drain their ledger writes while this instance
|
|
441
|
+
// still owns the storage lease. Automation continuations and its admission
|
|
442
|
+
// queue can outlive the gateway operation they awaited.
|
|
443
|
+
await Promise.all([stop(server), ...(receiver ? [stop(receiver)] : []), ...(automationServer ? [stop(automationServer)] : [])]);
|
|
444
|
+
await gateway.close();
|
|
445
|
+
})();
|
|
446
|
+
await closing;
|
|
447
|
+
} };
|
|
448
|
+
}
|
|
449
|
+
catch (error) {
|
|
450
|
+
await Promise.all([stop(server), ...(receiver ? [stop(receiver)] : []), ...(automationServer ? [stop(automationServer)] : [])]);
|
|
451
|
+
await gateway.close();
|
|
452
|
+
throw error;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Shared A2A 1.0 server, persistent state and host-independent executor interfaces. */
|
|
2
|
+
export { createA2AServer } from './server.js';
|
|
3
|
+
export type { A2AServerOptions } from './server.js';
|
|
4
|
+
export { FileA2AStore } from './store.js';
|
|
5
|
+
export type { A2ABackend, A2APrepareInput, A2ARunResult, A2ATarget } from './types.js';
|
|
6
|
+
export { RemoteAgentGateway, serveA2AGateway, REMOTE_AGENT_METHODS } from './gateway.js';
|
|
7
|
+
export type { A2AGatewayConfig, RemoteAgentNotice } from './gateway.js';
|
|
8
|
+
export { A2AAutomation } from './automation.js';
|
|
9
|
+
export type { A2AAutomationConfig, AutomationRun, AutomationRunStatus } from './automation.js';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Shared A2A 1.0 server, persistent state and host-independent executor interfaces. */
|
|
2
|
+
export { createA2AServer } from './server.js';
|
|
3
|
+
export { FileA2AStore } from './store.js';
|
|
4
|
+
export { RemoteAgentGateway, serveA2AGateway, REMOTE_AGENT_METHODS } from './gateway.js';
|
|
5
|
+
export { A2AAutomation } from './automation.js';
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { AgentCard } from '@a2a-js/sdk';
|
|
3
|
+
import { type A2AExecutionOptions } from './executor.js';
|
|
4
|
+
import type { A2ABackend } from './types.js';
|
|
5
|
+
/** Remote execution is explicitly enabled with a host-owned bearer credential. */
|
|
6
|
+
export interface A2AServerOptions extends A2AExecutionOptions {
|
|
7
|
+
backend: A2ABackend;
|
|
8
|
+
stateDirectory: string;
|
|
9
|
+
publicUrl: string;
|
|
10
|
+
token: string;
|
|
11
|
+
path?: string;
|
|
12
|
+
/** Webhook destinations must belong to one of these exact HTTP(S) origins. */
|
|
13
|
+
pushNotificationOrigins?: string[];
|
|
14
|
+
}
|
|
15
|
+
/** Create the A2A 1.0 host without opening a port or importing DSH. */
|
|
16
|
+
export declare function createA2AServer(options: A2AServerOptions): Promise<{
|
|
17
|
+
path: string;
|
|
18
|
+
card: AgentCard;
|
|
19
|
+
handler: (request: IncomingMessage, response: ServerResponse) => Promise<void>;
|
|
20
|
+
cardHandler: (request: IncomingMessage, response: ServerResponse) => Promise<void>;
|
|
21
|
+
close: () => Promise<void>;
|
|
22
|
+
}>;
|