@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.
Files changed (120) hide show
  1. package/README.md +42 -2
  2. package/dist/bin/a2a.js +3 -2
  3. package/dist/bin/acp-service.js +0 -0
  4. package/dist/src/a2a/executor.d.ts +2 -0
  5. package/dist/src/a2a/executor.js +96 -18
  6. package/dist/src/a2a/gateway.d.ts +407 -14
  7. package/dist/src/a2a/gateway.js +719 -37
  8. package/dist/src/a2a/index.d.ts +9 -1
  9. package/dist/src/a2a/index.js +5 -0
  10. package/dist/src/a2a/lease.d.ts +13 -0
  11. package/dist/src/a2a/lease.js +149 -0
  12. package/dist/src/a2a/notices.d.ts +24 -0
  13. package/dist/src/a2a/notices.js +56 -0
  14. package/dist/src/a2a/preflight.d.ts +52 -0
  15. package/dist/src/a2a/preflight.js +153 -0
  16. package/dist/src/a2a/request-id.d.ts +2 -0
  17. package/dist/src/a2a/request-id.js +6 -0
  18. package/dist/src/a2a/result-metadata.d.ts +59 -0
  19. package/dist/src/a2a/result-metadata.js +156 -0
  20. package/dist/src/a2a/server.js +43 -1
  21. package/dist/src/a2a/session-delivery.d.ts +69 -0
  22. package/dist/src/a2a/session-delivery.js +260 -0
  23. package/dist/src/a2a/session-hosts.d.ts +34 -0
  24. package/dist/src/a2a/session-hosts.js +211 -0
  25. package/dist/src/a2a/store.d.ts +4 -6
  26. package/dist/src/a2a/store.js +17 -115
  27. package/dist/src/a2a/types.d.ts +42 -0
  28. package/dist/src/acp-connection.d.ts +2 -1
  29. package/dist/src/acp-connection.js +52 -9
  30. package/dist/src/bridge.js +38 -39
  31. package/dist/src/execution/delivery-progress.d.ts +108 -0
  32. package/dist/src/execution/delivery-progress.js +57 -0
  33. package/dist/src/execution/ledger.d.ts +235 -0
  34. package/dist/src/execution/ledger.js +396 -0
  35. package/dist/src/execution/ppt-delivery.d.ts +231 -0
  36. package/dist/src/execution/ppt-delivery.js +625 -0
  37. package/dist/src/execution/targets.d.ts +349 -0
  38. package/dist/src/execution/targets.js +428 -0
  39. package/package.json +13 -13
  40. package/skills/acp-service/SKILL.md +9 -2
  41. package/skills/acp-service/references/a2a.md +72 -4
  42. package/vendor/dsh/README.md +12 -2
  43. package/vendor/dsh/a2a-executor.d.ts +9 -2
  44. package/vendor/dsh/a2a-executor.js +84 -16
  45. package/vendor/dsh/a2a.d.ts +2 -1
  46. package/vendor/dsh/a2a.js +10 -5
  47. package/vendor/dsh/adapter.d.ts +3 -1
  48. package/vendor/dsh/adapter.js +144 -16
  49. package/vendor/dsh/client.js +11 -3
  50. package/vendor/dsh/diagnostics.d.ts +42 -0
  51. package/vendor/dsh/diagnostics.js +176 -0
  52. package/vendor/dsh/index.d.ts +1 -0
  53. package/vendor/dsh/index.js +16 -4
  54. package/vendor/runtime/dist/{agent-registry-CMg8LHKY.js → agent-registry-R7A3MSpr.js} +9 -1
  55. package/vendor/runtime/dist/agent-registry-R7A3MSpr.js.map +1 -0
  56. package/vendor/runtime/dist/agent-registry.d.ts +1 -0
  57. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  58. package/vendor/runtime/dist/agent-registry.js +1 -2
  59. package/vendor/runtime/dist/{cli-DUHyAADv.js → cli-DeOpE2Xz.js} +4 -4
  60. package/vendor/runtime/dist/{cli-DUHyAADv.js.map → cli-DeOpE2Xz.js.map} +1 -1
  61. package/vendor/runtime/dist/cli.d.ts +2 -1
  62. package/vendor/runtime/dist/cli.js +10 -10
  63. package/vendor/runtime/dist/cli.js.map +1 -1
  64. package/vendor/runtime/dist/{client-DjkWknf7.d.ts → client-VQsqcIOJ.d.ts} +2 -2
  65. package/vendor/runtime/dist/{client-DjkWknf7.d.ts.map → client-VQsqcIOJ.d.ts.map} +1 -1
  66. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  67. package/vendor/runtime/dist/docs-site/CLI.html +833 -0
  68. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  69. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  70. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  71. package/vendor/runtime/dist/docs-site/config.html +450 -0
  72. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  73. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  74. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  75. package/vendor/runtime/dist/docs-site/flows.html +498 -0
  76. package/vendor/runtime/dist/docs-site/index.html +367 -0
  77. package/vendor/runtime/dist/docs-site/install.html +386 -0
  78. package/vendor/runtime/dist/docs-site/llms.txt +36 -0
  79. package/vendor/runtime/dist/docs-site/output-formats.html +407 -0
  80. package/vendor/runtime/dist/docs-site/permissions.html +422 -0
  81. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  82. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  83. package/vendor/runtime/dist/docs-site/releasing.html +341 -0
  84. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  85. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
  86. package/vendor/runtime/dist/docs-site/safe-errors.html +323 -0
  87. package/vendor/runtime/dist/docs-site/session-control.html +408 -0
  88. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  89. package/vendor/runtime/dist/docs-site/sessions.html +488 -0
  90. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  91. package/vendor/runtime/dist/{flows-CiJSCy4D.js → flows-oaBGn31w.js} +5 -5
  92. package/vendor/runtime/dist/{flows-CiJSCy4D.js.map → flows-oaBGn31w.js.map} +1 -1
  93. package/vendor/runtime/dist/flows.d.ts +2 -2
  94. package/vendor/runtime/dist/flows.d.ts.map +1 -1
  95. package/vendor/runtime/dist/flows.js +1 -2
  96. package/vendor/runtime/dist/{invocation-options-BlIySxIw.js → invocation-options-CUDEE8vW.js} +5 -5
  97. package/vendor/runtime/dist/{invocation-options-BlIySxIw.js.map → invocation-options-CUDEE8vW.js.map} +1 -1
  98. package/vendor/runtime/dist/{ipc-BlljKR2b.js → ipc-BQQpcEdP.js} +356 -20
  99. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +1 -0
  100. package/vendor/runtime/dist/{output-BzXQKArM.js → output-CFv3jcOQ.js} +86 -22
  101. package/vendor/runtime/dist/output-CFv3jcOQ.js.map +1 -0
  102. package/vendor/runtime/dist/{queue-owner-runtime-DSFdsS_y.js → queue-owner-runtime-DvMJiGbP.js} +86 -27
  103. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +1 -0
  104. package/vendor/runtime/dist/runtime.d.ts +28 -15
  105. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  106. package/vendor/runtime/dist/runtime.js +131 -63
  107. package/vendor/runtime/dist/runtime.js.map +1 -1
  108. package/vendor/runtime/dist/{session-options-ORCchZGk.d.ts → session-options-NjpFwf-c.d.ts} +22 -2
  109. package/vendor/runtime/dist/session-options-NjpFwf-c.d.ts.map +1 -0
  110. package/vendor/runtime/dist/{session-watch-BiBTBMz4.js → session-watch-Di-wIdCH.js} +4 -4
  111. package/vendor/runtime/dist/{session-watch-BiBTBMz4.js.map → session-watch-Di-wIdCH.js.map} +1 -1
  112. package/vendor/runtime/dist/{watch-iYiP-lOo.js → watch-CIpoMaWD.js} +2 -2
  113. package/vendor/runtime/dist/{watch-iYiP-lOo.js.map → watch-CIpoMaWD.js.map} +1 -1
  114. package/vendor/runtime/package.json +1 -1
  115. package/vendor/runtime/skills/acpx/SKILL.md +8 -2
  116. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +0 -1
  117. package/vendor/runtime/dist/ipc-BlljKR2b.js.map +0 -1
  118. package/vendor/runtime/dist/output-BzXQKArM.js.map +0 -1
  119. package/vendor/runtime/dist/queue-owner-runtime-DSFdsS_y.js.map +0 -1
  120. package/vendor/runtime/dist/session-options-ORCchZGk.d.ts.map +0 -1
@@ -2,8 +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';
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,5 +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';
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,13 @@
1
+ /** Reject a live owner; reclaim only uniquely named markers whose process is demonstrably absent. */
2
+ export declare class DirectoryLease {
3
+ private readonly directory;
4
+ private readonly lock;
5
+ private closed;
6
+ constructor(directory: string);
7
+ close(): void;
8
+ private acquireLock;
9
+ private ownerName;
10
+ private ownerPath;
11
+ private removeEmptyLockDirectory;
12
+ private readJson;
13
+ }
@@ -0,0 +1,149 @@
1
+ /** Single-writer directory lease shared by A2A records and plugin diagnostics. */
2
+ import { randomUUID } from 'node:crypto';
3
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
4
+ import { join, resolve } from 'node:path';
5
+ function record(value, label) {
6
+ if (!value || typeof value !== 'object' || Array.isArray(value))
7
+ throw new Error(`Invalid ${label}`);
8
+ return value;
9
+ }
10
+ /** Reject a live owner; reclaim only uniquely named markers whose process is demonstrably absent. */
11
+ export class DirectoryLease {
12
+ directory;
13
+ lock = { pid: process.pid, token: randomUUID() };
14
+ closed = false;
15
+ constructor(directory) {
16
+ this.directory = resolve(directory);
17
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 });
18
+ const stat = lstatSync(this.directory);
19
+ if (!stat.isDirectory() || stat.isSymbolicLink())
20
+ throw new Error('Storage directory must be a real directory');
21
+ this.acquireLock();
22
+ }
23
+ close() {
24
+ if (this.closed)
25
+ return;
26
+ this.closed = true;
27
+ // The owner filename is unique to this instance. Never unlink a shared
28
+ // lock path: another process may have acquired it since our last check.
29
+ const path = this.ownerPath();
30
+ try {
31
+ const lock = this.readJson(path);
32
+ if (lock.token === this.lock.token && lock.pid === this.lock.pid)
33
+ unlinkSync(path);
34
+ }
35
+ catch (error) {
36
+ if (error.code !== 'ENOENT')
37
+ throw error;
38
+ }
39
+ this.removeEmptyLockDirectory();
40
+ }
41
+ acquireLock() {
42
+ const path = join(this.directory, '.lock');
43
+ for (let attempt = 0; attempt < 32; attempt++) {
44
+ try {
45
+ mkdirSync(path, { mode: 0o700 });
46
+ }
47
+ catch (error) {
48
+ if (error.code !== 'EEXIST')
49
+ throw error;
50
+ try {
51
+ const stat = lstatSync(path);
52
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
53
+ throw new Error('Legacy or invalid A2A .lock file; verify no instance is running before removing it');
54
+ }
55
+ const names = readdirSync(path);
56
+ for (const name of names) {
57
+ const lock = record(this.readJson(join(path, name)), 'storage lock');
58
+ if (!Number.isInteger(lock.pid) || lock.pid <= 0 ||
59
+ typeof lock.token !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(lock.token) ||
60
+ name !== `owner-${lock.pid}-${lock.token}.json`) {
61
+ throw new Error('Invalid A2A storage lock; inspect the storage directory before removing it');
62
+ }
63
+ let dead = false;
64
+ try {
65
+ process.kill(lock.pid, 0);
66
+ }
67
+ catch (cause) {
68
+ dead = cause.code === 'ESRCH';
69
+ }
70
+ if (!dead)
71
+ throw new Error('A2A storage directory is already in use by another instance');
72
+ }
73
+ // Only remove the unique filenames observed above. A new live owner
74
+ // can never share them, so a delayed contender cannot delete its lock.
75
+ for (const name of names) {
76
+ try {
77
+ unlinkSync(join(path, name));
78
+ }
79
+ catch (cause) {
80
+ if (cause.code !== 'ENOENT')
81
+ throw cause;
82
+ }
83
+ }
84
+ this.removeEmptyLockDirectory();
85
+ }
86
+ catch (cause) {
87
+ if (cause.code !== 'ENOENT')
88
+ throw cause;
89
+ }
90
+ continue;
91
+ }
92
+ try {
93
+ const fd = openSync(this.ownerPath(), 'wx', 0o600);
94
+ try {
95
+ writeFileSync(fd, JSON.stringify(this.lock));
96
+ fsyncSync(fd);
97
+ }
98
+ finally {
99
+ closeSync(fd);
100
+ }
101
+ // A competing recovery can replace an empty directory between mkdir
102
+ // and marker creation. If both contenders wrote into that replacement,
103
+ // only the sole remaining owner may return a successfully held lock.
104
+ const names = readdirSync(path);
105
+ if (names.length !== 1 || names[0] !== this.ownerName()) {
106
+ throw new Error('A2A storage directory is already in use by another instance');
107
+ }
108
+ return;
109
+ }
110
+ catch (error) {
111
+ try {
112
+ unlinkSync(this.ownerPath());
113
+ }
114
+ catch (cause) {
115
+ if (cause.code !== 'ENOENT')
116
+ throw cause;
117
+ }
118
+ this.removeEmptyLockDirectory();
119
+ if (error.code !== 'ENOENT')
120
+ throw error;
121
+ }
122
+ }
123
+ throw new Error('Could not acquire A2A storage lock');
124
+ }
125
+ ownerName() { return `owner-${this.lock.pid}-${this.lock.token}.json`; }
126
+ ownerPath() { return join(this.directory, '.lock', this.ownerName()); }
127
+ removeEmptyLockDirectory() {
128
+ try {
129
+ rmdirSync(join(this.directory, '.lock'));
130
+ }
131
+ catch (error) {
132
+ // A live marker makes rmdir fail; never recursively remove a lock directory.
133
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code ?? ''))
134
+ throw error;
135
+ }
136
+ }
137
+ readJson(path) {
138
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
139
+ try {
140
+ const stat = fstatSync(fd);
141
+ if (!stat.isFile() || stat.size > 32 * 1024 * 1024)
142
+ throw new Error('Invalid A2A storage file');
143
+ return JSON.parse(readFileSync(fd, 'utf8'));
144
+ }
145
+ finally {
146
+ closeSync(fd);
147
+ }
148
+ }
149
+ }
@@ -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,2 @@
1
+ /** Bind one A2A task's user message, independent of transport connections. */
2
+ export declare function a2aRequestId(taskId: string, messageId: string): string;
@@ -0,0 +1,6 @@
1
+ /** Stable execution identity shared by live admission and read-only restart reconciliation. */
2
+ import { createHash } from 'node:crypto';
3
+ /** Bind one A2A task's user message, independent of transport connections. */
4
+ export function a2aRequestId(taskId, messageId) {
5
+ return `a2a-${createHash('sha256').update(JSON.stringify([taskId, messageId])).digest('hex')}`;
6
+ }
@@ -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>;