@1agents/acp-service 0.8.0 → 0.8.2
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 +42 -2
- package/dist/bin/a2a.js +3 -2
- package/dist/bin/acp-service.js +0 -0
- package/dist/src/a2a/executor.d.ts +2 -0
- package/dist/src/a2a/executor.js +96 -18
- package/dist/src/a2a/gateway.d.ts +407 -14
- package/dist/src/a2a/gateway.js +719 -37
- package/dist/src/a2a/index.d.ts +9 -1
- package/dist/src/a2a/index.js +5 -0
- package/dist/src/a2a/lease.d.ts +13 -0
- package/dist/src/a2a/lease.js +149 -0
- package/dist/src/a2a/notices.d.ts +24 -0
- package/dist/src/a2a/notices.js +56 -0
- package/dist/src/a2a/preflight.d.ts +52 -0
- package/dist/src/a2a/preflight.js +153 -0
- package/dist/src/a2a/request-id.d.ts +2 -0
- package/dist/src/a2a/request-id.js +6 -0
- package/dist/src/a2a/result-metadata.d.ts +59 -0
- package/dist/src/a2a/result-metadata.js +156 -0
- package/dist/src/a2a/server.js +43 -1
- package/dist/src/a2a/session-delivery.d.ts +69 -0
- package/dist/src/a2a/session-delivery.js +260 -0
- package/dist/src/a2a/session-hosts.d.ts +34 -0
- package/dist/src/a2a/session-hosts.js +211 -0
- package/dist/src/a2a/store.d.ts +4 -6
- package/dist/src/a2a/store.js +17 -115
- package/dist/src/a2a/types.d.ts +42 -0
- package/dist/src/acp-connection.d.ts +2 -1
- package/dist/src/acp-connection.js +52 -9
- package/dist/src/bridge.js +38 -39
- package/dist/src/execution/delivery-progress.d.ts +108 -0
- package/dist/src/execution/delivery-progress.js +57 -0
- package/dist/src/execution/ledger.d.ts +235 -0
- package/dist/src/execution/ledger.js +396 -0
- package/dist/src/execution/ppt-delivery.d.ts +231 -0
- package/dist/src/execution/ppt-delivery.js +625 -0
- package/dist/src/execution/targets.d.ts +349 -0
- package/dist/src/execution/targets.js +428 -0
- package/package.json +13 -13
- package/skills/acp-service/SKILL.md +9 -2
- package/skills/acp-service/references/a2a.md +72 -4
- package/vendor/dsh/README.md +12 -2
- package/vendor/dsh/a2a-executor.d.ts +9 -2
- package/vendor/dsh/a2a-executor.js +84 -16
- package/vendor/dsh/a2a.d.ts +2 -1
- package/vendor/dsh/a2a.js +10 -5
- package/vendor/dsh/adapter.d.ts +3 -1
- package/vendor/dsh/adapter.js +144 -16
- package/vendor/dsh/client.js +11 -3
- package/vendor/dsh/diagnostics.d.ts +42 -0
- package/vendor/dsh/diagnostics.js +176 -0
- package/vendor/dsh/index.d.ts +1 -0
- package/vendor/dsh/index.js +16 -4
- package/vendor/runtime/dist/{agent-registry-CMg8LHKY.js → agent-registry-R7A3MSpr.js} +9 -1
- package/vendor/runtime/dist/agent-registry-R7A3MSpr.js.map +1 -0
- package/vendor/runtime/dist/agent-registry.d.ts +1 -0
- package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
- package/vendor/runtime/dist/agent-registry.js +1 -2
- package/vendor/runtime/dist/{cli-DUHyAADv.js → cli-DeOpE2Xz.js} +4 -4
- package/vendor/runtime/dist/{cli-DUHyAADv.js.map → cli-DeOpE2Xz.js.map} +1 -1
- package/vendor/runtime/dist/cli.d.ts +2 -1
- package/vendor/runtime/dist/cli.js +10 -10
- package/vendor/runtime/dist/cli.js.map +1 -1
- package/vendor/runtime/dist/{client-DjkWknf7.d.ts → client-VQsqcIOJ.d.ts} +2 -2
- package/vendor/runtime/dist/{client-DjkWknf7.d.ts.map → client-VQsqcIOJ.d.ts.map} +1 -1
- package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
- package/vendor/runtime/dist/docs-site/CLI.html +833 -0
- package/vendor/runtime/dist/docs-site/VISION.html +415 -0
- package/vendor/runtime/dist/docs-site/agents.html +391 -0
- package/vendor/runtime/dist/docs-site/compare.html +359 -0
- package/vendor/runtime/dist/docs-site/config.html +450 -0
- package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
- package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
- package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
- package/vendor/runtime/dist/docs-site/flows.html +498 -0
- package/vendor/runtime/dist/docs-site/index.html +367 -0
- package/vendor/runtime/dist/docs-site/install.html +386 -0
- package/vendor/runtime/dist/docs-site/llms.txt +36 -0
- package/vendor/runtime/dist/docs-site/output-formats.html +407 -0
- package/vendor/runtime/dist/docs-site/permissions.html +422 -0
- package/vendor/runtime/dist/docs-site/prompting.html +460 -0
- package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
- package/vendor/runtime/dist/docs-site/releasing.html +341 -0
- package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
- package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
- package/vendor/runtime/dist/docs-site/safe-errors.html +323 -0
- package/vendor/runtime/dist/docs-site/session-control.html +408 -0
- package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
- package/vendor/runtime/dist/docs-site/sessions.html +488 -0
- package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
- package/vendor/runtime/dist/{flows-CiJSCy4D.js → flows-oaBGn31w.js} +5 -5
- package/vendor/runtime/dist/{flows-CiJSCy4D.js.map → flows-oaBGn31w.js.map} +1 -1
- package/vendor/runtime/dist/flows.d.ts +2 -2
- package/vendor/runtime/dist/flows.d.ts.map +1 -1
- package/vendor/runtime/dist/flows.js +1 -2
- package/vendor/runtime/dist/{invocation-options-BlIySxIw.js → invocation-options-CUDEE8vW.js} +5 -5
- package/vendor/runtime/dist/{invocation-options-BlIySxIw.js.map → invocation-options-CUDEE8vW.js.map} +1 -1
- package/vendor/runtime/dist/{ipc-BlljKR2b.js → ipc-BQQpcEdP.js} +356 -20
- package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +1 -0
- package/vendor/runtime/dist/{output-BzXQKArM.js → output-CFv3jcOQ.js} +86 -22
- package/vendor/runtime/dist/output-CFv3jcOQ.js.map +1 -0
- package/vendor/runtime/dist/{queue-owner-runtime-DSFdsS_y.js → queue-owner-runtime-DvMJiGbP.js} +86 -27
- package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +1 -0
- package/vendor/runtime/dist/runtime.d.ts +28 -15
- package/vendor/runtime/dist/runtime.d.ts.map +1 -1
- package/vendor/runtime/dist/runtime.js +131 -63
- package/vendor/runtime/dist/runtime.js.map +1 -1
- package/vendor/runtime/dist/{session-options-ORCchZGk.d.ts → session-options-NjpFwf-c.d.ts} +22 -2
- package/vendor/runtime/dist/session-options-NjpFwf-c.d.ts.map +1 -0
- package/vendor/runtime/dist/{session-watch-BiBTBMz4.js → session-watch-Di-wIdCH.js} +4 -4
- package/vendor/runtime/dist/{session-watch-BiBTBMz4.js.map → session-watch-Di-wIdCH.js.map} +1 -1
- package/vendor/runtime/dist/{watch-iYiP-lOo.js → watch-CIpoMaWD.js} +2 -2
- package/vendor/runtime/dist/{watch-iYiP-lOo.js.map → watch-CIpoMaWD.js.map} +1 -1
- package/vendor/runtime/package.json +1 -1
- package/vendor/runtime/skills/acpx/SKILL.md +8 -2
- package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +0 -1
- package/vendor/runtime/dist/ipc-BlljKR2b.js.map +0 -1
- package/vendor/runtime/dist/output-BzXQKArM.js.map +0 -1
- package/vendor/runtime/dist/queue-owner-runtime-DSFdsS_y.js.map +0 -1
- package/vendor/runtime/dist/session-options-ORCchZGk.d.ts.map +0 -1
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/** Host-authored task identity and verified artifact receipts; model text is not an authority. */
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { lstat, open, realpath, rename, unlink } from 'node:fs/promises';
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
const identifier = z.string().trim().min(1).max(512);
|
|
8
|
+
const absolutePath = z.string().min(1).max(8192).refine(value => isAbsolute(value) && !value.includes('\0'), 'Expected an absolute path');
|
|
9
|
+
export const a2aResultContractSchema = z.object({
|
|
10
|
+
jobId: identifier,
|
|
11
|
+
parentTaskId: identifier.optional(),
|
|
12
|
+
parentSessionId: identifier.optional(),
|
|
13
|
+
originSessionId: identifier.optional(),
|
|
14
|
+
artifactManifestPath: absolutePath.optional(),
|
|
15
|
+
}).strict();
|
|
16
|
+
const artifactSchema = z.object({
|
|
17
|
+
path: absolutePath,
|
|
18
|
+
url: z.string().url().refine(value => {
|
|
19
|
+
const url = new URL(value);
|
|
20
|
+
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password;
|
|
21
|
+
}, 'Artifact URL must use HTTP(S) without credentials').optional(),
|
|
22
|
+
mediaType: z.string().min(1).max(256).optional(),
|
|
23
|
+
}).strict();
|
|
24
|
+
const manifestSchema = z.object({ artifacts: z.array(artifactSchema).max(128) }).strict();
|
|
25
|
+
export class A2AResultValidationError extends Error {
|
|
26
|
+
code;
|
|
27
|
+
constructor(code) {
|
|
28
|
+
super(`A2A result validation failed: ${code}`);
|
|
29
|
+
this.code = code;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function within(root, path) {
|
|
33
|
+
const rel = relative(root, path);
|
|
34
|
+
return rel !== '' && !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
|
|
35
|
+
}
|
|
36
|
+
/** Resolve aliases such as /tmp once, then reject symlinks below the admitted job root. */
|
|
37
|
+
async function scopedFile(root, path) {
|
|
38
|
+
const canonical = await realpath(path);
|
|
39
|
+
if (!within(root, canonical))
|
|
40
|
+
throw new A2AResultValidationError('artifact-outside-job-directory');
|
|
41
|
+
// A symlink pointing back into the scope is rejected too: the receipt describes a real file.
|
|
42
|
+
let current = path;
|
|
43
|
+
for (;;) {
|
|
44
|
+
if ((await lstat(current)).isSymbolicLink())
|
|
45
|
+
throw new A2AResultValidationError('artifact-symlink');
|
|
46
|
+
if (await realpath(dirname(current)) === root)
|
|
47
|
+
break;
|
|
48
|
+
const parent = dirname(current);
|
|
49
|
+
if (parent === current)
|
|
50
|
+
throw new A2AResultValidationError('artifact-outside-job-directory');
|
|
51
|
+
current = parent;
|
|
52
|
+
}
|
|
53
|
+
return canonical;
|
|
54
|
+
}
|
|
55
|
+
async function verifiedArtifacts(root, manifestPath) {
|
|
56
|
+
const manifestFile = await scopedFile(root, manifestPath);
|
|
57
|
+
const manifest = await open(manifestFile, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
58
|
+
let source;
|
|
59
|
+
try {
|
|
60
|
+
const info = await manifest.stat();
|
|
61
|
+
if (!info.isFile() || info.size > 1024 * 1024)
|
|
62
|
+
throw new A2AResultValidationError('invalid-artifact-manifest');
|
|
63
|
+
source = JSON.parse(await manifest.readFile('utf8'));
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
await manifest.close();
|
|
67
|
+
}
|
|
68
|
+
const parsed = manifestSchema.safeParse(source);
|
|
69
|
+
if (!parsed.success)
|
|
70
|
+
throw new A2AResultValidationError('invalid-artifact-manifest');
|
|
71
|
+
const output = [];
|
|
72
|
+
const seen = new Set();
|
|
73
|
+
for (const item of parsed.data.artifacts) {
|
|
74
|
+
const path = await scopedFile(root, item.path);
|
|
75
|
+
if (seen.has(path))
|
|
76
|
+
throw new A2AResultValidationError('duplicate-artifact');
|
|
77
|
+
seen.add(path);
|
|
78
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
79
|
+
try {
|
|
80
|
+
const before = await file.stat();
|
|
81
|
+
if (!before.isFile())
|
|
82
|
+
throw new A2AResultValidationError('artifact-is-not-a-file');
|
|
83
|
+
const hash = createHash('sha256');
|
|
84
|
+
for await (const chunk of file.createReadStream({ autoClose: false }))
|
|
85
|
+
hash.update(chunk);
|
|
86
|
+
const after = await file.stat();
|
|
87
|
+
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
|
|
88
|
+
throw new A2AResultValidationError('artifact-changed-during-verification');
|
|
89
|
+
}
|
|
90
|
+
output.push({ path, size: after.size, sha256: hash.digest('hex'),
|
|
91
|
+
...(item.url ? { url: item.url } : {}), ...(item.mediaType ? { mediaType: item.mediaType } : {}) });
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
await file.close();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return output;
|
|
98
|
+
}
|
|
99
|
+
/** Produce identities even for an admission failure; artifact checks only run after completed execution. */
|
|
100
|
+
export async function createA2AResultMetadata(input) {
|
|
101
|
+
const { target, contract } = input;
|
|
102
|
+
const metadata = {
|
|
103
|
+
version: 1, producer: '1agents/a2a-host', taskId: input.taskId, contextId: input.contextId,
|
|
104
|
+
requestId: input.requestId, ...(target ? { sessionId: target.sessionId, cwd: target.cwd,
|
|
105
|
+
...(target.agentPreset ? { agentPreset: target.agentPreset } : {}) } : {}),
|
|
106
|
+
startedAt: input.startedAt, finishedAt: new Date().toISOString(), outcome: input.outcome,
|
|
107
|
+
...(contract ? { lineage: { ...contract, source: 'caller-declared' } } : {}),
|
|
108
|
+
...(target?.preflight || input.preflight ? { preflight: target?.preflight ?? input.preflight } : {}), artifacts: [],
|
|
109
|
+
validation: input.validationCode ? { status: 'failed', code: input.validationCode } : { status: 'not-requested' },
|
|
110
|
+
};
|
|
111
|
+
if (contract?.artifactManifestPath && input.outcome === 'completed' && !input.validationCode) {
|
|
112
|
+
const root = target?.preflight?.ok && target.preflight.jobDirectory;
|
|
113
|
+
if (!root)
|
|
114
|
+
throw new A2AResultValidationError('artifact-job-directory-not-admitted');
|
|
115
|
+
if (await realpath(root) !== root)
|
|
116
|
+
throw new A2AResultValidationError('job-directory-changed');
|
|
117
|
+
try {
|
|
118
|
+
metadata.artifacts = await verifiedArtifacts(root, contract.artifactManifestPath);
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (error instanceof A2AResultValidationError)
|
|
122
|
+
throw error;
|
|
123
|
+
throw new A2AResultValidationError('artifact-manifest-or-file-unavailable');
|
|
124
|
+
}
|
|
125
|
+
metadata.validation = { status: 'passed' };
|
|
126
|
+
}
|
|
127
|
+
return metadata;
|
|
128
|
+
}
|
|
129
|
+
/** A system sidecar is optional for legacy callers, but mandatory when an admitted job is specified. */
|
|
130
|
+
export async function saveA2AResultMetadata(metadata, target) {
|
|
131
|
+
const root = target?.preflight?.ok && target.preflight.jobDirectory;
|
|
132
|
+
if (!root)
|
|
133
|
+
return;
|
|
134
|
+
if (await realpath(root) !== root || !(await lstat(root)).isDirectory())
|
|
135
|
+
throw new A2AResultValidationError('job-directory-changed');
|
|
136
|
+
const filename = `result-metadata.${encodeURIComponent(metadata.taskId)}.json`;
|
|
137
|
+
if (basename(filename) !== filename)
|
|
138
|
+
throw new A2AResultValidationError('invalid-task-id');
|
|
139
|
+
const destination = join(root, filename);
|
|
140
|
+
const temporary = join(root, `.result-${randomUUID()}.tmp`);
|
|
141
|
+
metadata.recordPath = destination;
|
|
142
|
+
let file;
|
|
143
|
+
try {
|
|
144
|
+
file = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
145
|
+
await file.writeFile(JSON.stringify(metadata, null, 2) + '\n');
|
|
146
|
+
await file.sync();
|
|
147
|
+
await file.close();
|
|
148
|
+
file = undefined;
|
|
149
|
+
// rename replaces a pre-existing symlink itself rather than following it.
|
|
150
|
+
await rename(temporary, destination);
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
await file?.close();
|
|
154
|
+
await unlink(temporary).catch(() => { });
|
|
155
|
+
}
|
|
156
|
+
}
|
package/dist/src/a2a/server.js
CHANGED
|
@@ -4,7 +4,11 @@ import { AgentCard, SSE_HEADERS, TaskState, formatSSEEvent } from '@a2a-js/sdk';
|
|
|
4
4
|
import { PushNotificationNotSupportedError, RequestMalformedError, UnsupportedOperationError } from '@a2a-js/sdk/errors';
|
|
5
5
|
import { DefaultExecutionEventBusManager, DefaultRequestHandler, JsonRpcTransportHandler, ServerCallContext, V1PushNotificationSerializer, resolveUserScope, validateVersion } from '@a2a-js/sdk/server';
|
|
6
6
|
import { A2ASessionExecutor, parseA2AInput } from './executor.js';
|
|
7
|
+
import { Role } from '@a2a-js/sdk';
|
|
8
|
+
import { toSafeError } from '@1agents/acp-service/runtime';
|
|
9
|
+
import { a2aRequestId } from './request-id.js';
|
|
7
10
|
import { FileA2AStore } from './store.js';
|
|
11
|
+
import { a2aPreflightInputSchema } from './preflight.js';
|
|
8
12
|
function allowedCallback(config, origins) {
|
|
9
13
|
if (!origins.size)
|
|
10
14
|
throw new PushNotificationNotSupportedError('Configure pushNotificationOrigins to enable webhooks');
|
|
@@ -191,7 +195,16 @@ export async function createA2AServer(options) {
|
|
|
191
195
|
skills: [{ id: 'dsh-session', name: 'DSH session task', description: 'Create or resume a session using metadata.1agents.cwd, workspace and agentPreset; retain contextId to continue collaboration.', tags: ['dsh', 'project', 'role', 'async'] }] });
|
|
192
196
|
const store = new FileA2AStore(options.stateDirectory);
|
|
193
197
|
try {
|
|
194
|
-
await store.recoverInterrupted()
|
|
198
|
+
await store.recoverInterrupted(async (task, context) => {
|
|
199
|
+
const message = task.history.findLast(message => message.role === Role.ROLE_USER);
|
|
200
|
+
const target = store.loadTarget(task.contextId, context);
|
|
201
|
+
if (!message || !target)
|
|
202
|
+
return;
|
|
203
|
+
const requestId = a2aRequestId(task.id, message.messageId);
|
|
204
|
+
const recovered = await options.backend.recover?.(target, { requestId });
|
|
205
|
+
return toSafeError(recovered, { origin: 'a2a', operationId: requestId,
|
|
206
|
+
outcomeUnknown: recovered === undefined });
|
|
207
|
+
});
|
|
195
208
|
}
|
|
196
209
|
catch (error) {
|
|
197
210
|
store.close();
|
|
@@ -231,6 +244,35 @@ export async function createA2AServer(options) {
|
|
|
231
244
|
res.end();
|
|
232
245
|
return;
|
|
233
246
|
}
|
|
247
|
+
// A host extension with the same credential boundary as execution. Probing
|
|
248
|
+
// does not allocate a Task, context or session and never enters the model.
|
|
249
|
+
if (req.url === `${path}/preflight`) {
|
|
250
|
+
if (!options.backend.preflight) {
|
|
251
|
+
res.writeHead(501, { 'Content-Type': 'application/json' });
|
|
252
|
+
res.end(JSON.stringify({ error: 'Host preflight is not supported' }));
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
const chunks = [];
|
|
257
|
+
let size = 0;
|
|
258
|
+
for await (const chunk of req) {
|
|
259
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
260
|
+
size += buffer.length;
|
|
261
|
+
if (size > 65536)
|
|
262
|
+
throw new Error('Preflight body exceeds 64 KiB');
|
|
263
|
+
chunks.push(buffer);
|
|
264
|
+
}
|
|
265
|
+
const input = a2aPreflightInputSchema.parse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
266
|
+
const report = await options.backend.preflight(input);
|
|
267
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
268
|
+
res.end(JSON.stringify(report));
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
272
|
+
res.end(JSON.stringify({ error: 'Invalid preflight request' }));
|
|
273
|
+
}
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
234
276
|
res.setHeader('A2A-Version', '1.0');
|
|
235
277
|
let id = null;
|
|
236
278
|
try {
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { type SessionHost } from './session-hosts.js';
|
|
3
|
+
export declare const sessionOriginSchema: z.ZodObject<{
|
|
4
|
+
originSessionId: z.ZodString;
|
|
5
|
+
}, z.core.$strict>;
|
|
6
|
+
export declare const sessionBindSchema: z.ZodObject<{
|
|
7
|
+
originSessionId: z.ZodString;
|
|
8
|
+
host: z.ZodString;
|
|
9
|
+
sessionId: z.ZodString;
|
|
10
|
+
}, z.core.$strict>;
|
|
11
|
+
export declare const sessionMessageSchema: z.ZodObject<{
|
|
12
|
+
originSessionId: z.ZodString;
|
|
13
|
+
messageId: z.ZodString;
|
|
14
|
+
}, z.core.$strict>;
|
|
15
|
+
export declare const sessionSendSchema: z.ZodObject<{
|
|
16
|
+
originSessionId: z.ZodString;
|
|
17
|
+
messageId: z.ZodString;
|
|
18
|
+
text: z.ZodString;
|
|
19
|
+
}, z.core.$strict>;
|
|
20
|
+
export declare const sessionResolveSchema: z.ZodObject<{
|
|
21
|
+
originSessionId: z.ZodString;
|
|
22
|
+
messageId: z.ZodString;
|
|
23
|
+
accepted: z.ZodBoolean;
|
|
24
|
+
note: z.ZodString;
|
|
25
|
+
hostReceiptId: z.ZodOptional<z.ZodString>;
|
|
26
|
+
}, z.core.$strict>;
|
|
27
|
+
export interface SessionBinding {
|
|
28
|
+
originSessionId: string;
|
|
29
|
+
host: string;
|
|
30
|
+
sessionId: string;
|
|
31
|
+
createdAt: string;
|
|
32
|
+
}
|
|
33
|
+
export type SessionDeliveryStatus = 'pending' | 'dispatching' | 'retrying' | 'accepted' | 'unknown' | 'rejected';
|
|
34
|
+
export interface SessionDeliveryReceipt extends SessionBinding {
|
|
35
|
+
messageId: string;
|
|
36
|
+
status: SessionDeliveryStatus;
|
|
37
|
+
attempts: number;
|
|
38
|
+
updatedAt: string;
|
|
39
|
+
nextAttemptAt?: string;
|
|
40
|
+
hostReceiptId?: string;
|
|
41
|
+
error?: string;
|
|
42
|
+
processedAt?: string;
|
|
43
|
+
resolutionNote?: string;
|
|
44
|
+
}
|
|
45
|
+
/** Owned by the gateway's single-writer storage lease. */
|
|
46
|
+
export declare class SessionDelivery {
|
|
47
|
+
private readonly hosts;
|
|
48
|
+
private readonly file;
|
|
49
|
+
private readonly state;
|
|
50
|
+
private readonly controller;
|
|
51
|
+
private pumping?;
|
|
52
|
+
private closed;
|
|
53
|
+
private storageFailed;
|
|
54
|
+
constructor(directory: string, hosts: Record<string, SessionHost>);
|
|
55
|
+
private save;
|
|
56
|
+
get healthy(): boolean;
|
|
57
|
+
private requireWritable;
|
|
58
|
+
hasBinding(originSessionId: string): boolean;
|
|
59
|
+
hasDelivery(originSessionId: string, messageId: string): boolean;
|
|
60
|
+
bind(input: z.output<typeof sessionBindSchema>): SessionBinding;
|
|
61
|
+
enqueue(input: z.output<typeof sessionSendSchema>): SessionDeliveryReceipt;
|
|
62
|
+
get(input: z.output<typeof sessionMessageSchema>): SessionDeliveryReceipt;
|
|
63
|
+
private find;
|
|
64
|
+
resolve(input: z.output<typeof sessionResolveSchema>): SessionDeliveryReceipt;
|
|
65
|
+
acknowledgeNotice(originSessionId: string, noticeId: string): void;
|
|
66
|
+
acknowledgeMessage(originSessionId: string, messageId: string): void;
|
|
67
|
+
reconcile(): Promise<void>;
|
|
68
|
+
close(): Promise<void>;
|
|
69
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/** Durable admission to host-owned conversation queues; acceptance is not business completion. */
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { deliverSessionMessage, SessionDeliveryError } from './session-hosts.js';
|
|
7
|
+
const id = z.string().trim().min(1).max(512);
|
|
8
|
+
export const sessionOriginSchema = z.object({ originSessionId: id }).strict();
|
|
9
|
+
export const sessionBindSchema = sessionOriginSchema.extend({ host: id, sessionId: id }).strict();
|
|
10
|
+
export const sessionMessageSchema = sessionOriginSchema.extend({ messageId: id }).strict();
|
|
11
|
+
export const sessionSendSchema = sessionMessageSchema.extend({ text: z.string().min(1).max(256 * 1024).refine(value => Boolean(value.trim())) }).strict();
|
|
12
|
+
export const sessionResolveSchema = sessionMessageSchema.extend({ accepted: z.boolean(), note: id, hostReceiptId: id.optional() }).strict();
|
|
13
|
+
const bindingSchema = sessionBindSchema.extend({ createdAt: id, hostFingerprint: id }).strict();
|
|
14
|
+
const deliverySchema = bindingSchema.extend({
|
|
15
|
+
messageId: id, text: sessionSendSchema.shape.text,
|
|
16
|
+
status: z.enum(['pending', 'dispatching', 'retrying', 'accepted', 'unknown', 'rejected']),
|
|
17
|
+
attempts: z.number().int().nonnegative(), updatedAt: id,
|
|
18
|
+
nextAttemptAt: id.optional(), hostReceiptId: id.optional(), error: id.optional(),
|
|
19
|
+
processedAt: id.optional(), resolutionNote: id.optional(),
|
|
20
|
+
}).strict();
|
|
21
|
+
const stateSchema = z.object({ version: z.literal(1), bindings: z.array(bindingSchema), deliveries: z.array(deliverySchema) }).strict();
|
|
22
|
+
/** Credentials may rotate; a host alias must never silently redirect saved messages. */
|
|
23
|
+
function fingerprint(host) {
|
|
24
|
+
const { headers, timeoutMs, ...locator } = host;
|
|
25
|
+
return createHash('sha256').update(JSON.stringify(Object.fromEntries(Object.entries(locator).sort(([a], [b]) => a.localeCompare(b))))).digest('hex');
|
|
26
|
+
}
|
|
27
|
+
function receipt(delivery) {
|
|
28
|
+
const { text, hostFingerprint, ...view } = delivery;
|
|
29
|
+
return { ...view };
|
|
30
|
+
}
|
|
31
|
+
/** Owned by the gateway's single-writer storage lease. */
|
|
32
|
+
export class SessionDelivery {
|
|
33
|
+
hosts;
|
|
34
|
+
file;
|
|
35
|
+
state;
|
|
36
|
+
controller = new AbortController();
|
|
37
|
+
pumping;
|
|
38
|
+
closed = false;
|
|
39
|
+
storageFailed = false;
|
|
40
|
+
constructor(directory, hosts) {
|
|
41
|
+
this.hosts = hosts;
|
|
42
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
43
|
+
this.file = path.join(directory, 'session-delivery.json');
|
|
44
|
+
try {
|
|
45
|
+
this.state = stateSchema.parse(JSON.parse(readFileSync(this.file, 'utf8')));
|
|
46
|
+
const origins = new Set(), messages = new Set();
|
|
47
|
+
for (const binding of this.state.bindings) {
|
|
48
|
+
if (origins.has(binding.originSessionId))
|
|
49
|
+
throw new Error('Duplicate session binding');
|
|
50
|
+
origins.add(binding.originSessionId);
|
|
51
|
+
}
|
|
52
|
+
for (const delivery of this.state.deliveries) {
|
|
53
|
+
const key = JSON.stringify([delivery.originSessionId, delivery.messageId]);
|
|
54
|
+
if (messages.has(key))
|
|
55
|
+
throw new Error('Duplicate session delivery');
|
|
56
|
+
messages.add(key);
|
|
57
|
+
const binding = this.state.bindings.find(value => value.originSessionId === delivery.originSessionId);
|
|
58
|
+
if (!binding || binding.host !== delivery.host || binding.sessionId !== delivery.sessionId || binding.hostFingerprint !== delivery.hostFingerprint)
|
|
59
|
+
throw new Error('Session delivery binding mismatch');
|
|
60
|
+
if (delivery.status === 'dispatching') {
|
|
61
|
+
delivery.status = 'unknown';
|
|
62
|
+
delivery.error = 'Gateway restarted during host admission; verify the host before resolving';
|
|
63
|
+
delivery.updatedAt = new Date().toISOString();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
this.save();
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (error.code !== 'ENOENT')
|
|
70
|
+
throw error;
|
|
71
|
+
this.state = { version: 1, bindings: [], deliveries: [] };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
save() {
|
|
75
|
+
if (this.storageFailed)
|
|
76
|
+
throw new Error('Session delivery storage is unavailable; repair storage and restart the gateway');
|
|
77
|
+
const temporary = `${this.file}.${randomUUID()}.tmp`;
|
|
78
|
+
try {
|
|
79
|
+
const fd = openSync(temporary, 'wx', 0o600);
|
|
80
|
+
try {
|
|
81
|
+
writeFileSync(fd, JSON.stringify(this.state));
|
|
82
|
+
fsyncSync(fd);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
closeSync(fd);
|
|
86
|
+
}
|
|
87
|
+
renameSync(temporary, this.file);
|
|
88
|
+
const dir = openSync(path.dirname(this.file), 'r');
|
|
89
|
+
try {
|
|
90
|
+
fsyncSync(dir);
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
closeSync(dir);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
this.storageFailed = true;
|
|
98
|
+
throw new Error('Session delivery storage is unavailable; repair storage and restart the gateway');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
get healthy() { return !this.storageFailed; }
|
|
102
|
+
requireWritable() {
|
|
103
|
+
if (this.closed)
|
|
104
|
+
throw new Error('Session delivery is closed');
|
|
105
|
+
if (this.storageFailed)
|
|
106
|
+
throw new Error('Session delivery storage is unavailable; repair storage and restart the gateway');
|
|
107
|
+
}
|
|
108
|
+
hasBinding(originSessionId) { return this.state.bindings.some(value => value.originSessionId === originSessionId); }
|
|
109
|
+
hasDelivery(originSessionId, messageId) {
|
|
110
|
+
return this.state.deliveries.some(value => value.originSessionId === originSessionId && value.messageId === messageId);
|
|
111
|
+
}
|
|
112
|
+
bind(input) {
|
|
113
|
+
this.requireWritable();
|
|
114
|
+
const host = this.hosts[input.host];
|
|
115
|
+
if (!host)
|
|
116
|
+
throw new Error('Unknown session host');
|
|
117
|
+
if (host.kind === 'codex' && !z.uuid().safeParse(input.sessionId).success)
|
|
118
|
+
throw new Error('Codex session ID must be a thread UUID');
|
|
119
|
+
const previous = this.state.bindings.find(value => value.originSessionId === input.originSessionId);
|
|
120
|
+
if (previous) {
|
|
121
|
+
if (previous.host !== input.host || previous.sessionId !== input.sessionId || previous.hostFingerprint !== fingerprint(host))
|
|
122
|
+
throw new Error('Origin session is already bound to a different host or session');
|
|
123
|
+
const { hostFingerprint, ...view } = previous;
|
|
124
|
+
return { ...view };
|
|
125
|
+
}
|
|
126
|
+
const binding = { ...input, hostFingerprint: fingerprint(host), createdAt: new Date().toISOString() };
|
|
127
|
+
this.state.bindings.push(binding);
|
|
128
|
+
try {
|
|
129
|
+
this.save();
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
this.state.bindings.pop();
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
const { hostFingerprint, ...view } = binding;
|
|
136
|
+
return view;
|
|
137
|
+
}
|
|
138
|
+
enqueue(input) {
|
|
139
|
+
this.requireWritable();
|
|
140
|
+
const previous = this.state.deliveries.find(value => value.originSessionId === input.originSessionId && value.messageId === input.messageId);
|
|
141
|
+
if (previous) {
|
|
142
|
+
if (previous.text !== input.text)
|
|
143
|
+
throw new Error('Message ID was already used for different content');
|
|
144
|
+
return receipt(previous);
|
|
145
|
+
}
|
|
146
|
+
const binding = this.state.bindings.find(value => value.originSessionId === input.originSessionId);
|
|
147
|
+
if (!binding)
|
|
148
|
+
throw new Error('Origin session is not bound');
|
|
149
|
+
const now = new Date().toISOString();
|
|
150
|
+
const delivery = { ...binding, messageId: input.messageId, text: input.text, createdAt: now, updatedAt: now, attempts: 0, status: 'pending' };
|
|
151
|
+
this.state.deliveries.push(delivery);
|
|
152
|
+
try {
|
|
153
|
+
this.save();
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
this.state.deliveries.pop();
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
return receipt(delivery);
|
|
160
|
+
}
|
|
161
|
+
get(input) { this.requireWritable(); return receipt(this.find(input)); }
|
|
162
|
+
find(input) {
|
|
163
|
+
const delivery = this.state.deliveries.find(value => value.originSessionId === input.originSessionId && value.messageId === input.messageId);
|
|
164
|
+
if (!delivery)
|
|
165
|
+
throw new Error('Delivery not found for this origin session');
|
|
166
|
+
return delivery;
|
|
167
|
+
}
|
|
168
|
+
resolve(input) {
|
|
169
|
+
this.requireWritable();
|
|
170
|
+
const delivery = this.find(input);
|
|
171
|
+
if (!['unknown', 'rejected'].includes(delivery.status))
|
|
172
|
+
throw new Error('Only unknown or rejected host admission can be resolved');
|
|
173
|
+
delivery.status = input.accepted ? 'accepted' : 'pending';
|
|
174
|
+
delivery.resolutionNote = input.note;
|
|
175
|
+
if (input.hostReceiptId)
|
|
176
|
+
delivery.hostReceiptId = input.hostReceiptId;
|
|
177
|
+
delivery.updatedAt = new Date().toISOString();
|
|
178
|
+
delete delivery.error;
|
|
179
|
+
delete delivery.nextAttemptAt;
|
|
180
|
+
this.save();
|
|
181
|
+
return receipt(delivery);
|
|
182
|
+
}
|
|
183
|
+
acknowledgeNotice(originSessionId, noticeId) {
|
|
184
|
+
this.acknowledgeMessage(originSessionId, `a2a-notice:${noticeId}`);
|
|
185
|
+
}
|
|
186
|
+
acknowledgeMessage(originSessionId, messageId) {
|
|
187
|
+
this.requireWritable();
|
|
188
|
+
const delivery = this.state.deliveries.find(value => value.originSessionId === originSessionId && value.messageId === messageId);
|
|
189
|
+
if (delivery && !delivery.processedAt) {
|
|
190
|
+
delivery.processedAt = new Date().toISOString();
|
|
191
|
+
delivery.updatedAt = delivery.processedAt;
|
|
192
|
+
this.save();
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
async reconcile() {
|
|
196
|
+
if (this.closed || this.storageFailed)
|
|
197
|
+
return;
|
|
198
|
+
if (this.pumping)
|
|
199
|
+
return this.pumping;
|
|
200
|
+
const run = async () => {
|
|
201
|
+
const origins = new Set(this.state.deliveries.map(value => value.originSessionId));
|
|
202
|
+
await Promise.allSettled([...origins].map(async (origin) => {
|
|
203
|
+
if (this.closed || this.storageFailed)
|
|
204
|
+
return;
|
|
205
|
+
// The first unresolved admission holds later messages in FIFO order.
|
|
206
|
+
const delivery = this.state.deliveries.find(value => value.originSessionId === origin && value.status !== 'accepted' && !value.processedAt);
|
|
207
|
+
if (!delivery || ['unknown', 'rejected', 'dispatching'].includes(delivery.status))
|
|
208
|
+
return;
|
|
209
|
+
if (delivery.nextAttemptAt && Date.parse(delivery.nextAttemptAt) > Date.now())
|
|
210
|
+
return;
|
|
211
|
+
const host = this.hosts[delivery.host];
|
|
212
|
+
if (!host || fingerprint(host) !== delivery.hostFingerprint) {
|
|
213
|
+
delivery.status = 'unknown';
|
|
214
|
+
delivery.error = 'Saved host configuration is missing or its destination changed';
|
|
215
|
+
delivery.updatedAt = new Date().toISOString();
|
|
216
|
+
this.save();
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
delivery.status = 'dispatching';
|
|
220
|
+
delivery.attempts++;
|
|
221
|
+
delivery.updatedAt = new Date().toISOString();
|
|
222
|
+
delete delivery.nextAttemptAt;
|
|
223
|
+
this.save();
|
|
224
|
+
try {
|
|
225
|
+
// Host deduplication must preserve the ledger's origin/message scope.
|
|
226
|
+
const hostMessageId = `1agents-session:${createHash('sha256').update(JSON.stringify([delivery.originSessionId, delivery.messageId])).digest('hex')}`;
|
|
227
|
+
const result = await deliverSessionMessage(host, { sessionId: delivery.sessionId, messageId: hostMessageId, text: delivery.text }, this.controller.signal);
|
|
228
|
+
delivery.status = 'accepted';
|
|
229
|
+
delivery.hostReceiptId = result.hostReceiptId;
|
|
230
|
+
delete delivery.error;
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
if (error instanceof SessionDeliveryError && error.retryable && !error.outcomeUnknown) {
|
|
234
|
+
delivery.status = 'retrying';
|
|
235
|
+
delivery.nextAttemptAt = new Date(Date.now() + Math.min(60_000, 1000 * 2 ** Math.min(delivery.attempts - 1, 6))).toISOString();
|
|
236
|
+
}
|
|
237
|
+
else
|
|
238
|
+
delivery.status = error instanceof SessionDeliveryError && !error.outcomeUnknown ? 'rejected' : 'unknown';
|
|
239
|
+
delivery.error = error instanceof SessionDeliveryError ? error.message : 'Host admission failed; verify delivery before retrying';
|
|
240
|
+
}
|
|
241
|
+
delivery.updatedAt = new Date().toISOString();
|
|
242
|
+
this.save();
|
|
243
|
+
}));
|
|
244
|
+
};
|
|
245
|
+
this.pumping = run();
|
|
246
|
+
try {
|
|
247
|
+
await this.pumping;
|
|
248
|
+
}
|
|
249
|
+
finally {
|
|
250
|
+
this.pumping = undefined;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
async close() {
|
|
254
|
+
if (this.closed)
|
|
255
|
+
return;
|
|
256
|
+
this.closed = true;
|
|
257
|
+
this.controller.abort();
|
|
258
|
+
await this.pumping;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const sessionHostSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
3
|
+
kind: z.ZodLiteral<"codex">;
|
|
4
|
+
executable: z.ZodDefault<z.ZodString>;
|
|
5
|
+
remote: z.ZodOptional<z.ZodString>;
|
|
6
|
+
remoteAuthTokenEnv: z.ZodOptional<z.ZodString>;
|
|
7
|
+
cwd: z.ZodOptional<z.ZodString>;
|
|
8
|
+
timeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
9
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
10
|
+
kind: z.ZodLiteral<"dsh">;
|
|
11
|
+
url: z.ZodString;
|
|
12
|
+
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
13
|
+
timeoutMs: z.ZodDefault<z.ZodNumber>;
|
|
14
|
+
}, z.core.$strict>], "kind">;
|
|
15
|
+
export type SessionHost = z.output<typeof sessionHostSchema>;
|
|
16
|
+
/** Safe delivery failure; an unknown host outcome must never be retried automatically. */
|
|
17
|
+
export declare class SessionDeliveryError extends Error {
|
|
18
|
+
readonly retryable: boolean;
|
|
19
|
+
readonly outcomeUnknown: boolean;
|
|
20
|
+
constructor(message: string, options: {
|
|
21
|
+
retryable: boolean;
|
|
22
|
+
outcomeUnknown: boolean;
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
type Message = {
|
|
26
|
+
sessionId: string;
|
|
27
|
+
messageId: string;
|
|
28
|
+
text: string;
|
|
29
|
+
};
|
|
30
|
+
/** Queue one message without starting a new host session or changing its configuration. */
|
|
31
|
+
export declare function deliverSessionMessage(host: SessionHost, input: Message, signal?: AbortSignal): Promise<{
|
|
32
|
+
hostReceiptId?: string;
|
|
33
|
+
}>;
|
|
34
|
+
export {};
|