@1agents/acp-service 0.8.1 → 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.
Files changed (103) hide show
  1. package/README.md +37 -2
  2. package/dist/bin/a2a.js +3 -2
  3. package/dist/src/a2a/executor.d.ts +2 -0
  4. package/dist/src/a2a/executor.js +63 -10
  5. package/dist/src/a2a/gateway.d.ts +407 -14
  6. package/dist/src/a2a/gateway.js +719 -37
  7. package/dist/src/a2a/index.d.ts +8 -1
  8. package/dist/src/a2a/index.js +4 -0
  9. package/dist/src/a2a/notices.d.ts +24 -0
  10. package/dist/src/a2a/notices.js +56 -0
  11. package/dist/src/a2a/preflight.d.ts +52 -0
  12. package/dist/src/a2a/preflight.js +153 -0
  13. package/dist/src/a2a/result-metadata.d.ts +59 -0
  14. package/dist/src/a2a/result-metadata.js +156 -0
  15. package/dist/src/a2a/server.js +30 -0
  16. package/dist/src/a2a/session-delivery.d.ts +69 -0
  17. package/dist/src/a2a/session-delivery.js +260 -0
  18. package/dist/src/a2a/session-hosts.d.ts +34 -0
  19. package/dist/src/a2a/session-hosts.js +211 -0
  20. package/dist/src/a2a/store.js +3 -1
  21. package/dist/src/a2a/types.d.ts +33 -0
  22. package/dist/src/execution/delivery-progress.d.ts +108 -0
  23. package/dist/src/execution/delivery-progress.js +57 -0
  24. package/dist/src/execution/ledger.d.ts +235 -0
  25. package/dist/src/execution/ledger.js +396 -0
  26. package/dist/src/execution/ppt-delivery.d.ts +231 -0
  27. package/dist/src/execution/ppt-delivery.js +625 -0
  28. package/dist/src/execution/targets.d.ts +349 -0
  29. package/dist/src/execution/targets.js +428 -0
  30. package/package.json +11 -12
  31. package/skills/acp-service/SKILL.md +9 -2
  32. package/skills/acp-service/references/a2a.md +72 -4
  33. package/vendor/dsh/a2a-executor.d.ts +2 -1
  34. package/vendor/dsh/a2a-executor.js +28 -1
  35. package/vendor/dsh/a2a.js +1 -0
  36. package/vendor/dsh/client.js +11 -3
  37. package/vendor/runtime/dist/{agent-registry-CMg8LHKY.js → agent-registry-R7A3MSpr.js} +9 -1
  38. package/vendor/runtime/dist/agent-registry-R7A3MSpr.js.map +1 -0
  39. package/vendor/runtime/dist/agent-registry.d.ts +1 -0
  40. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  41. package/vendor/runtime/dist/agent-registry.js +1 -2
  42. package/vendor/runtime/dist/{cli-Bdzplbpj.js → cli-DeOpE2Xz.js} +4 -4
  43. package/vendor/runtime/dist/{cli-Bdzplbpj.js.map → cli-DeOpE2Xz.js.map} +1 -1
  44. package/vendor/runtime/dist/cli.d.ts +2 -1
  45. package/vendor/runtime/dist/cli.js +10 -10
  46. package/vendor/runtime/dist/cli.js.map +1 -1
  47. package/vendor/runtime/dist/{client-BXOiB0ND.d.ts → client-VQsqcIOJ.d.ts} +2 -2
  48. package/vendor/runtime/dist/{client-BXOiB0ND.d.ts.map → client-VQsqcIOJ.d.ts.map} +1 -1
  49. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  50. package/vendor/runtime/dist/docs-site/CLI.html +833 -0
  51. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  52. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  53. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  54. package/vendor/runtime/dist/docs-site/config.html +450 -0
  55. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  56. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  57. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  58. package/vendor/runtime/dist/docs-site/flows.html +498 -0
  59. package/vendor/runtime/dist/docs-site/index.html +367 -0
  60. package/vendor/runtime/dist/docs-site/install.html +386 -0
  61. package/vendor/runtime/dist/docs-site/llms.txt +36 -0
  62. package/vendor/runtime/dist/docs-site/output-formats.html +407 -0
  63. package/vendor/runtime/dist/docs-site/permissions.html +422 -0
  64. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  65. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  66. package/vendor/runtime/dist/docs-site/releasing.html +341 -0
  67. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  68. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
  69. package/vendor/runtime/dist/docs-site/safe-errors.html +323 -0
  70. package/vendor/runtime/dist/docs-site/session-control.html +408 -0
  71. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  72. package/vendor/runtime/dist/docs-site/sessions.html +488 -0
  73. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  74. package/vendor/runtime/dist/{flows-BKlAuzM8.js → flows-oaBGn31w.js} +5 -5
  75. package/vendor/runtime/dist/{flows-BKlAuzM8.js.map → flows-oaBGn31w.js.map} +1 -1
  76. package/vendor/runtime/dist/flows.d.ts +2 -2
  77. package/vendor/runtime/dist/flows.d.ts.map +1 -1
  78. package/vendor/runtime/dist/flows.js +1 -2
  79. package/vendor/runtime/dist/{invocation-options-DMy77sEU.js → invocation-options-CUDEE8vW.js} +5 -5
  80. package/vendor/runtime/dist/{invocation-options-DMy77sEU.js.map → invocation-options-CUDEE8vW.js.map} +1 -1
  81. package/vendor/runtime/dist/{ipc-CLv2iL89.js → ipc-BQQpcEdP.js} +98 -20
  82. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +1 -0
  83. package/vendor/runtime/dist/{output-I-t-v55D.js → output-CFv3jcOQ.js} +86 -22
  84. package/vendor/runtime/dist/output-CFv3jcOQ.js.map +1 -0
  85. package/vendor/runtime/dist/{queue-owner-runtime-RN3uSid0.js → queue-owner-runtime-DvMJiGbP.js} +86 -27
  86. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +1 -0
  87. package/vendor/runtime/dist/runtime.d.ts +5 -2
  88. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  89. package/vendor/runtime/dist/runtime.js +77 -29
  90. package/vendor/runtime/dist/runtime.js.map +1 -1
  91. package/vendor/runtime/dist/{session-options-DNnDfiUt.d.ts → session-options-NjpFwf-c.d.ts} +5 -1
  92. package/vendor/runtime/dist/session-options-NjpFwf-c.d.ts.map +1 -0
  93. package/vendor/runtime/dist/{session-watch-CmHbH0jS.js → session-watch-Di-wIdCH.js} +4 -4
  94. package/vendor/runtime/dist/{session-watch-CmHbH0jS.js.map → session-watch-Di-wIdCH.js.map} +1 -1
  95. package/vendor/runtime/dist/{watch-BE-kKa7o.js → watch-CIpoMaWD.js} +2 -2
  96. package/vendor/runtime/dist/{watch-BE-kKa7o.js.map → watch-CIpoMaWD.js.map} +1 -1
  97. package/vendor/runtime/package.json +1 -1
  98. package/vendor/runtime/skills/acpx/SKILL.md +7 -2
  99. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +0 -1
  100. package/vendor/runtime/dist/ipc-CLv2iL89.js.map +0 -1
  101. package/vendor/runtime/dist/output-I-t-v55D.js.map +0 -1
  102. package/vendor/runtime/dist/queue-owner-runtime-RN3uSid0.js.map +0 -1
  103. package/vendor/runtime/dist/session-options-DNnDfiUt.d.ts.map +0 -1
@@ -2,9 +2,16 @@
2
2
  export { createA2AServer } from './server.js';
3
3
  export type { A2AServerOptions } from './server.js';
4
4
  export { FileA2AStore } from './store.js';
5
- export type { A2ABackend, A2APrepareInput, A2ARunResult, A2ATarget } from './types.js';
5
+ export type { A2ABackend, A2APrepareInput, A2ARunResult, A2ATarget, A2APreflightInput, A2APreflightRequirements, A2APreflightReport } from './types.js';
6
+ export { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema, A2APreflightError, runA2APreflight } from './preflight.js';
7
+ export { a2aResultContractSchema, A2AResultValidationError, createA2AResultMetadata, saveA2AResultMetadata } from './result-metadata.js';
8
+ export type { A2AResultContract, A2AVerifiedArtifact, A2AResultMetadata } from './result-metadata.js';
6
9
  export { RemoteAgentGateway, serveA2AGateway, REMOTE_AGENT_METHODS } from './gateway.js';
7
10
  export type { A2AGatewayConfig, RemoteAgentNotice } from './gateway.js';
8
11
  export { A2AAutomation } from './automation.js';
9
12
  export type { A2AAutomationConfig, AutomationRun, AutomationRunStatus } from './automation.js';
10
13
  export { DirectoryLease } from './lease.js';
14
+ export { SessionDelivery } from './session-delivery.js';
15
+ export type { SessionBinding, SessionDeliveryReceipt, SessionDeliveryStatus } from './session-delivery.js';
16
+ export { sessionHostSchema, deliverSessionMessage, SessionDeliveryError } from './session-hosts.js';
17
+ export type { SessionHost } from './session-hosts.js';
@@ -1,6 +1,10 @@
1
1
  /** Shared A2A 1.0 server, persistent state and host-independent executor interfaces. */
2
2
  export { createA2AServer } from './server.js';
3
3
  export { FileA2AStore } from './store.js';
4
+ export { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema, A2APreflightError, runA2APreflight } from './preflight.js';
5
+ export { a2aResultContractSchema, A2AResultValidationError, createA2AResultMetadata, saveA2AResultMetadata } from './result-metadata.js';
4
6
  export { RemoteAgentGateway, serveA2AGateway, REMOTE_AGENT_METHODS } from './gateway.js';
5
7
  export { A2AAutomation } from './automation.js';
6
8
  export { DirectoryLease } from './lease.js';
9
+ export { SessionDelivery } from './session-delivery.js';
10
+ export { sessionHostSchema, deliverSessionMessage, SessionDeliveryError } from './session-hosts.js';
@@ -0,0 +1,24 @@
1
+ /** Human-readable task results, with machine-readable acknowledgement locators at the end. */
2
+ import type { Task } from '@a2a-js/sdk';
3
+ export interface ArtifactLink {
4
+ name: string;
5
+ url: string;
6
+ mediaType?: string;
7
+ }
8
+ export interface RemoteAgentNotice {
9
+ noticeId: string;
10
+ originSessionId: string;
11
+ remote: string;
12
+ taskId: string;
13
+ contextId: string;
14
+ cwd: string;
15
+ agentPreset?: string;
16
+ title?: string;
17
+ state: string;
18
+ result: string;
19
+ artifactLinks?: ArtifactLink[];
20
+ createdAt: string;
21
+ }
22
+ /** Only explicit URL parts become attachment links; text and its Markdown links stay intact. */
23
+ export declare function artifactLinks(task: Task): ArtifactLink[];
24
+ export declare function formatNotice(notice: RemoteAgentNotice): string;
@@ -0,0 +1,56 @@
1
+ /** Only explicit URL parts become attachment links; text and its Markdown links stay intact. */
2
+ export function artifactLinks(task) {
3
+ const seen = new Set();
4
+ return task.artifacts.flatMap(artifact => artifact.parts.flatMap(part => {
5
+ if (part.content?.$case !== 'url')
6
+ return [];
7
+ const url = part.content.value;
8
+ try {
9
+ const parsed = new URL(url);
10
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || seen.has(url))
11
+ return [];
12
+ }
13
+ catch {
14
+ return [];
15
+ }
16
+ seen.add(url);
17
+ return [{ name: part.filename || artifact.name || '产物', url, ...(part.mediaType ? { mediaType: part.mediaType } : {}) }];
18
+ }));
19
+ }
20
+ function excerpt(text, bytes) {
21
+ return Buffer.from(text).subarray(0, bytes).toString('utf8').replace(/\uFFFD$/u, '');
22
+ }
23
+ const labels = {
24
+ TASK_STATE_COMPLETED: '任务已完成', TASK_STATE_FAILED: '任务失败', TASK_STATE_CANCELED: '任务已取消',
25
+ TASK_STATE_REJECTED: '任务被拒绝', TASK_STATE_INPUT_REQUIRED: '任务需要补充输入', TASK_STATE_AUTH_REQUIRED: '任务需要授权',
26
+ };
27
+ export function formatNotice(notice) {
28
+ const text = notice.result.trim();
29
+ const body = Buffer.byteLength(text) > 48 * 1024
30
+ ? `${excerpt(text, 48 * 1024)}\n\n(正文较长,以上为节选;完整答复可通过 remote_agent_get 或 remote_agent_inbox 查询。)`
31
+ : text || '远端尚未提供答复正文,可查询任务详情。';
32
+ const links = [];
33
+ let remaining = 8 * 1024;
34
+ for (const link of notice.artifactLinks ?? []) {
35
+ // Encode Markdown delimiters without changing the link's destination.
36
+ const name = excerpt(link.name, 256).replace(/[\r\n]/g, ' ').replace(/[\\[\]]/g, '\\$&');
37
+ const url = link.url.replace(/[<>\s]/g, char => encodeURIComponent(char));
38
+ const line = `- [${name}](<${url}>)`;
39
+ const bytes = Buffer.byteLength(line) + 1;
40
+ if (bytes > remaining) {
41
+ links.push('(更多产物链接请通过 remote_agent_get 或 remote_agent_inbox 查询。)');
42
+ break;
43
+ }
44
+ links.push(line);
45
+ remaining -= bytes;
46
+ }
47
+ return [
48
+ `[A2A任务通知] ${labels[notice.state] ?? notice.state}`,
49
+ ...(notice.title ? [notice.title] : []), '', body,
50
+ ...(links.length ? ['', '产物链接:', ...links] : []), '',
51
+ '以上正文和链接为远端任务结果。可通过 a2a-gateway 的 remote_agent_get 或 remote_agent_inbox 核验状态与完整结果。请在原任务授权范围内处理,保存处理结论后调用 remote_agent_ack。',
52
+ '', '---', '任务定位信息:',
53
+ JSON.stringify({ noticeId: notice.noticeId, originSessionId: notice.originSessionId, remote: notice.remote,
54
+ taskId: notice.taskId, contextId: notice.contextId, state: notice.state }),
55
+ ].join('\n');
56
+ }
@@ -0,0 +1,52 @@
1
+ import { z } from 'zod';
2
+ import type { A2APreflightInput, A2APreflightReport } from './types.js';
3
+ export declare const a2aPreflightRequirementsSchema: z.ZodObject<{
4
+ allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
5
+ jobDirectory: z.ZodOptional<z.ZodString>;
6
+ requiredFiles: z.ZodOptional<z.ZodArray<z.ZodString>>;
7
+ python: z.ZodOptional<z.ZodObject<{
8
+ executable: z.ZodString;
9
+ modules: z.ZodArray<z.ZodString>;
10
+ }, z.core.$strict>>;
11
+ node: z.ZodOptional<z.ZodObject<{
12
+ executable: z.ZodString;
13
+ modules: z.ZodOptional<z.ZodArray<z.ZodString>>;
14
+ moduleRoot: z.ZodOptional<z.ZodString>;
15
+ }, z.core.$strict>>;
16
+ }, z.core.$strict>;
17
+ export declare const a2aPreflightInputSchema: z.ZodObject<{
18
+ allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
19
+ jobDirectory: z.ZodOptional<z.ZodString>;
20
+ requiredFiles: z.ZodOptional<z.ZodArray<z.ZodString>>;
21
+ python: z.ZodOptional<z.ZodObject<{
22
+ executable: z.ZodString;
23
+ modules: z.ZodArray<z.ZodString>;
24
+ }, z.core.$strict>>;
25
+ node: z.ZodOptional<z.ZodObject<{
26
+ executable: z.ZodString;
27
+ modules: z.ZodOptional<z.ZodArray<z.ZodString>>;
28
+ moduleRoot: z.ZodOptional<z.ZodString>;
29
+ }, z.core.$strict>>;
30
+ cwd: z.ZodString;
31
+ }, z.core.$strict>;
32
+ export declare const a2aPreflightReportSchema: z.ZodObject<{
33
+ ok: z.ZodBoolean;
34
+ checkedAt: z.ZodString;
35
+ cwd: z.ZodString;
36
+ jobDirectory: z.ZodOptional<z.ZodString>;
37
+ checks: z.ZodArray<z.ZodObject<{
38
+ id: z.ZodString;
39
+ ok: z.ZodBoolean;
40
+ detail: z.ZodOptional<z.ZodString>;
41
+ }, z.core.$strict>>;
42
+ }, z.core.$strict>;
43
+ export declare class A2APreflightError extends Error {
44
+ readonly report: A2APreflightReport;
45
+ constructor(report: A2APreflightReport);
46
+ }
47
+ /** Enforce an explicitly supplied cwd allowlist against host realpaths and access permissions.
48
+ * This is an admission check, not an OS sandbox or a restriction on every file the agent can read.
49
+ * Match DSH workspace-write roots: the real project and platform temporary directories.
50
+ * A successful OS write alone cannot establish that the agent sandbox admits it.
51
+ */
52
+ export declare function runA2APreflight(raw: A2APreflightInput): Promise<A2APreflightReport>;
@@ -0,0 +1,153 @@
1
+ /** Host-side admission checks; never starts an agent or invokes a shell. */
2
+ import { execFile } from 'node:child_process';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { constants } from 'node:fs';
5
+ import { access, open, realpath, stat, unlink } from 'node:fs/promises';
6
+ import { tmpdir } from 'node:os';
7
+ import { isAbsolute, join, relative, sep } from 'node:path';
8
+ import { promisify } from 'node:util';
9
+ import { z } from 'zod';
10
+ const absolutePath = z.string().min(1).max(4096).refine(value => isAbsolute(value) && !value.includes('\0'), 'Expected an absolute host path');
11
+ const pythonModule = z.string().regex(/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/).max(200);
12
+ const nodeModule = z.string().regex(/^(?:@[A-Za-z0-9_.-]+\/)?[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/).max(200);
13
+ export const a2aPreflightRequirementsSchema = z.object({
14
+ allowedDirectories: z.array(absolutePath).min(1).max(100).optional(),
15
+ jobDirectory: absolutePath.optional(),
16
+ requiredFiles: z.array(absolutePath).max(64).optional(),
17
+ python: z.object({ executable: absolutePath, modules: z.array(pythonModule).max(32) }).strict().optional(),
18
+ node: z.object({ executable: absolutePath, modules: z.array(nodeModule).max(32).optional(), moduleRoot: absolutePath.optional() }).strict().optional(),
19
+ }).strict();
20
+ export const a2aPreflightInputSchema = a2aPreflightRequirementsSchema.extend({ cwd: absolutePath }).strict();
21
+ export const a2aPreflightReportSchema = z.object({
22
+ ok: z.boolean(), checkedAt: z.string(), cwd: absolutePath, jobDirectory: absolutePath.optional(),
23
+ checks: z.array(z.object({ id: z.string(), ok: z.boolean(), detail: z.string().optional() }).strict()),
24
+ }).strict();
25
+ export class A2APreflightError extends Error {
26
+ report;
27
+ constructor(report) {
28
+ super(`A2A preflight failed: ${report.checks.filter(check => !check.ok).map(check => `${check.id}: ${check.detail}`).join('; ')}`);
29
+ this.report = report;
30
+ this.name = 'A2APreflightError';
31
+ }
32
+ }
33
+ const execute = promisify(execFile);
34
+ const within = (root, path) => {
35
+ const tail = relative(root, path);
36
+ return tail === '' || (!tail.startsWith(`..${sep}`) && tail !== '..' && !isAbsolute(tail));
37
+ };
38
+ const failure = (error) => error instanceof Error ? error.message.slice(0, 400) : 'Host check failed';
39
+ /** Enforce an explicitly supplied cwd allowlist against host realpaths and access permissions.
40
+ * This is an admission check, not an OS sandbox or a restriction on every file the agent can read.
41
+ * Match DSH workspace-write roots: the real project and platform temporary directories.
42
+ * A successful OS write alone cannot establish that the agent sandbox admits it.
43
+ */
44
+ export async function runA2APreflight(raw) {
45
+ const input = a2aPreflightInputSchema.parse(raw);
46
+ const report = { ok: true, checkedAt: new Date().toISOString(), cwd: input.cwd, checks: [] };
47
+ const check = async (id, action) => {
48
+ try {
49
+ const detail = await action();
50
+ report.checks.push({ id, ok: true, ...(detail === undefined ? {} : { detail }) });
51
+ return true;
52
+ }
53
+ catch (error) {
54
+ report.checks.push({ id, ok: false, detail: failure(error) });
55
+ report.ok = false;
56
+ return false;
57
+ }
58
+ };
59
+ const cwdOk = await check('cwd', async () => {
60
+ report.cwd = await realpath(input.cwd);
61
+ if (!(await stat(report.cwd)).isDirectory())
62
+ throw new Error('A2A cwd must point to a directory on the host');
63
+ if (input.allowedDirectories)
64
+ await access(report.cwd, constants.R_OK | constants.X_OK);
65
+ return report.cwd;
66
+ });
67
+ if (input.allowedDirectories) {
68
+ const allowedRoots = [];
69
+ let rootsOk = true;
70
+ for (const [index, root] of input.allowedDirectories.entries()) {
71
+ const rootOk = await check(`allowedDirectory.${index}`, async () => {
72
+ const actual = await realpath(root);
73
+ if (!(await stat(actual)).isDirectory())
74
+ throw new Error('Allowed root must already exist and be a directory');
75
+ await access(actual, constants.R_OK | constants.X_OK);
76
+ allowedRoots.push(actual);
77
+ return actual;
78
+ });
79
+ rootsOk = rootOk && rootsOk;
80
+ }
81
+ const scopeOk = await check('allowedDirectories', async () => {
82
+ if (!cwdOk)
83
+ throw new Error('Cannot validate allowed directories without an accessible cwd');
84
+ if (!rootsOk)
85
+ throw new Error('Every configured allowed directory must exist and be accessible');
86
+ if (!allowedRoots.some(root => within(root, report.cwd)))
87
+ throw new Error('Real cwd is outside allowedDirectories (including symlink escapes)');
88
+ return `real cwd ${report.cwd} is within configured real roots`;
89
+ });
90
+ // Do not run dependency executables or a write probe after the admission policy has rejected this cwd.
91
+ if (!scopeOk)
92
+ return report;
93
+ }
94
+ if (input.jobDirectory)
95
+ await check('jobDirectory', async () => {
96
+ if (!cwdOk)
97
+ throw new Error('Cannot validate writable scope without a valid cwd');
98
+ const directory = await realpath(input.jobDirectory);
99
+ if (!(await stat(directory)).isDirectory())
100
+ throw new Error('jobDirectory must already exist and be a directory');
101
+ const temporaryRoots = await Promise.all(['/tmp', tmpdir()].map(path => realpath(path).catch(() => undefined)));
102
+ if (![report.cwd, ...temporaryRoots.filter((path) => path !== undefined)].some(root => within(root, directory))) {
103
+ throw new Error('jobDirectory is outside the DSH workspace-write roots (cwd or platform temporary directories)');
104
+ }
105
+ const probe = join(directory, `.a2a-preflight-${randomUUID()}`);
106
+ const handle = await open(probe, 'wx', 0o600);
107
+ try {
108
+ await handle.writeFile('a2a preflight\n');
109
+ await handle.sync();
110
+ }
111
+ finally {
112
+ await handle.close();
113
+ await unlink(probe);
114
+ }
115
+ report.jobDirectory = directory;
116
+ return directory;
117
+ });
118
+ for (const [index, file] of (input.requiredFiles ?? []).entries())
119
+ await check(`requiredFile.${index}`, async () => {
120
+ const actual = await realpath(file);
121
+ if (!(await stat(actual)).isFile())
122
+ throw new Error('Required input is not a regular file');
123
+ const handle = await open(actual, 'r');
124
+ await handle.close();
125
+ return actual;
126
+ });
127
+ if (input.python)
128
+ await check('python', async () => {
129
+ const executable = await realpath(input.python.executable);
130
+ const code = 'import importlib.util,json,sys; names=json.loads(sys.argv[1]); print(json.dumps({"version":sys.version.split()[0],"modules":{name:importlib.util.find_spec(name) is not None for name in names}}))';
131
+ const { stdout } = await execute(executable, ['-I', '-c', code, JSON.stringify(input.python.modules)], { timeout: 5000, maxBuffer: 65536, ...(cwdOk ? { cwd: report.cwd } : {}) });
132
+ const result = JSON.parse(stdout);
133
+ const missing = input.python.modules.filter(name => result.modules[name] !== true);
134
+ if (missing.length)
135
+ throw new Error(`Missing Python modules: ${missing.join(', ')}`);
136
+ return `${executable}; Python ${result.version}; modules=${input.python.modules.join(',')}`;
137
+ });
138
+ if (input.node)
139
+ await check('node', async () => {
140
+ const executable = await realpath(input.node.executable);
141
+ const moduleRoot = await realpath(input.node.moduleRoot ?? report.cwd);
142
+ if (!(await stat(moduleRoot)).isDirectory())
143
+ throw new Error('Node moduleRoot must be a directory');
144
+ const code = 'const {createRequire}=require("node:module");const path=require("node:path");const req=createRequire(path.join(process.argv[1],"__a2a_preflight__.cjs"));const names=JSON.parse(process.argv[2]);console.log(JSON.stringify({version:process.version,modules:Object.fromEntries(names.map(name=>{try{return[name,req.resolve(name)]}catch{return[name,null]}}))}));';
145
+ const { stdout } = await execute(executable, ['--input-type=commonjs', '-e', code, moduleRoot, JSON.stringify(input.node.modules ?? [])], { timeout: 5000, maxBuffer: 65536, ...(cwdOk ? { cwd: report.cwd } : {}) });
146
+ const result = JSON.parse(stdout);
147
+ const missing = (input.node.modules ?? []).filter(name => typeof result.modules[name] !== 'string');
148
+ if (missing.length)
149
+ throw new Error(`Missing Node modules: ${missing.join(', ')}`);
150
+ return `${executable}; Node ${result.version}; modules=${(input.node.modules ?? []).join(',')}`;
151
+ });
152
+ return report;
153
+ }
@@ -0,0 +1,59 @@
1
+ import { z } from 'zod';
2
+ import type { A2APreflightReport, A2ATarget } from './types.js';
3
+ export declare const a2aResultContractSchema: z.ZodObject<{
4
+ jobId: z.ZodString;
5
+ parentTaskId: z.ZodOptional<z.ZodString>;
6
+ parentSessionId: z.ZodOptional<z.ZodString>;
7
+ originSessionId: z.ZodOptional<z.ZodString>;
8
+ artifactManifestPath: z.ZodOptional<z.ZodString>;
9
+ }, z.core.$strict>;
10
+ export type A2AResultContract = z.infer<typeof a2aResultContractSchema>;
11
+ export interface A2AVerifiedArtifact {
12
+ path: string;
13
+ size: number;
14
+ sha256: string;
15
+ url?: string;
16
+ mediaType?: string;
17
+ }
18
+ export interface A2AResultMetadata {
19
+ version: 1;
20
+ producer: '1agents/a2a-host';
21
+ taskId: string;
22
+ contextId: string;
23
+ requestId: string;
24
+ sessionId?: string;
25
+ cwd?: string;
26
+ agentPreset?: string;
27
+ startedAt: string;
28
+ finishedAt: string;
29
+ outcome: 'completed' | 'failed' | 'input-required' | 'canceled';
30
+ /** These associations are declared by the authenticated caller, not independently proven by this host. */
31
+ lineage?: A2AResultContract & {
32
+ source: 'caller-declared';
33
+ };
34
+ preflight?: A2APreflightReport;
35
+ artifacts: A2AVerifiedArtifact[];
36
+ validation: {
37
+ status: 'not-requested' | 'passed' | 'failed';
38
+ code?: string;
39
+ };
40
+ recordPath?: string;
41
+ }
42
+ export declare class A2AResultValidationError extends Error {
43
+ readonly code: string;
44
+ constructor(code: string);
45
+ }
46
+ /** Produce identities even for an admission failure; artifact checks only run after completed execution. */
47
+ export declare function createA2AResultMetadata(input: {
48
+ taskId: string;
49
+ contextId: string;
50
+ requestId: string;
51
+ startedAt: string;
52
+ outcome: A2AResultMetadata['outcome'];
53
+ target?: A2ATarget;
54
+ contract?: A2AResultContract;
55
+ validationCode?: string;
56
+ preflight?: A2APreflightReport;
57
+ }): Promise<A2AResultMetadata>;
58
+ /** A system sidecar is optional for legacy callers, but mandatory when an admitted job is specified. */
59
+ export declare function saveA2AResultMetadata(metadata: A2AResultMetadata, target?: A2ATarget): Promise<void>;
@@ -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
+ }
@@ -8,6 +8,7 @@ import { Role } from '@a2a-js/sdk';
8
8
  import { toSafeError } from '@1agents/acp-service/runtime';
9
9
  import { a2aRequestId } from './request-id.js';
10
10
  import { FileA2AStore } from './store.js';
11
+ import { a2aPreflightInputSchema } from './preflight.js';
11
12
  function allowedCallback(config, origins) {
12
13
  if (!origins.size)
13
14
  throw new PushNotificationNotSupportedError('Configure pushNotificationOrigins to enable webhooks');
@@ -243,6 +244,35 @@ export async function createA2AServer(options) {
243
244
  res.end();
244
245
  return;
245
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
+ }
246
276
  res.setHeader('A2A-Version', '1.0');
247
277
  let id = null;
248
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
+ }