@hivemagnus/ardent 3.1.4 → 3.2.1

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 (79) hide show
  1. package/README.md +479 -6
  2. package/dist/a2a-client.d.ts +26 -4
  3. package/dist/a2a-client.js +91 -23
  4. package/dist/a2a-push-inbox.d.ts +2 -0
  5. package/dist/a2a-push-inbox.js +7 -0
  6. package/dist/a2a-push.d.ts +1 -1
  7. package/dist/a2a-push.js +26 -18
  8. package/dist/a2a-server.d.ts +17 -0
  9. package/dist/a2a-server.js +91 -14
  10. package/dist/a2a.d.ts +19 -1
  11. package/dist/a2a.js +197 -27
  12. package/dist/api.d.ts +2 -0
  13. package/dist/api.js +160 -22
  14. package/dist/artifact-manifests.d.ts +344 -5
  15. package/dist/artifact-manifests.js +413 -20
  16. package/dist/artifact-transfer.d.ts +113 -0
  17. package/dist/artifact-transfer.js +517 -0
  18. package/dist/artifacts.d.ts +86 -0
  19. package/dist/artifacts.js +249 -1
  20. package/dist/backend-events.d.ts +2 -1
  21. package/dist/backend-events.js +1 -1
  22. package/dist/channel-catchup.d.ts +67 -0
  23. package/dist/channel-catchup.js +108 -0
  24. package/dist/channels.d.ts +35 -0
  25. package/dist/channels.js +152 -4
  26. package/dist/cli.js +28 -3
  27. package/dist/codex-protocol.d.ts +22 -0
  28. package/dist/codex-protocol.js +19 -0
  29. package/dist/codex.d.ts +32 -3
  30. package/dist/codex.js +91 -17
  31. package/dist/config.d.ts +25 -2
  32. package/dist/config.js +41 -4
  33. package/dist/development.d.ts +6 -6
  34. package/dist/execution-state.d.ts +245 -0
  35. package/dist/execution-state.js +236 -0
  36. package/dist/execution.d.ts +135 -0
  37. package/dist/execution.js +178 -0
  38. package/dist/index.d.ts +7 -4
  39. package/dist/index.js +5 -3
  40. package/dist/job-engine.d.ts +2 -1
  41. package/dist/job-engine.js +33 -4
  42. package/dist/lineage.d.ts +106 -0
  43. package/dist/lineage.js +145 -0
  44. package/dist/llamacpp.d.ts +32 -2
  45. package/dist/llamacpp.js +69 -33
  46. package/dist/mattermost.d.ts +8 -0
  47. package/dist/mattermost.js +250 -36
  48. package/dist/mission-tools.js +41 -5
  49. package/dist/missions.d.ts +5 -1
  50. package/dist/missions.js +10 -5
  51. package/dist/plugin-evidence.js +2 -1
  52. package/dist/plugin-sdk.d.ts +3 -0
  53. package/dist/plugin-sdk.js +3 -0
  54. package/dist/plugins.d.ts +108 -2
  55. package/dist/plugins.js +131 -1
  56. package/dist/preview.d.ts +1 -0
  57. package/dist/preview.js +4 -1
  58. package/dist/recovery.d.ts +155 -0
  59. package/dist/recovery.js +216 -0
  60. package/dist/research.d.ts +1 -1
  61. package/dist/retry.d.ts +143 -0
  62. package/dist/retry.js +127 -0
  63. package/dist/runtime.d.ts +56 -4
  64. package/dist/runtime.js +727 -125
  65. package/dist/store.d.ts +62 -7
  66. package/dist/store.js +86 -15
  67. package/dist/team-artifacts.d.ts +130 -112
  68. package/dist/team-artifacts.js +123 -151
  69. package/dist/team-child.d.ts +4 -1
  70. package/dist/team-child.js +21 -2
  71. package/dist/team-contract.d.ts +1 -1
  72. package/dist/telegram.d.ts +2 -0
  73. package/dist/telegram.js +83 -47
  74. package/dist/tool-scheduler.d.ts +84 -0
  75. package/dist/tool-scheduler.js +226 -0
  76. package/dist/tools.d.ts +78 -4
  77. package/dist/tools.js +34 -7
  78. package/package.json +15 -8
  79. package/profiles/assistant/config.yaml +2 -1
@@ -0,0 +1,517 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { mkdir, open, unlink } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { z } from 'zod';
6
+ import { TaskState } from '@a2a-js/sdk';
7
+ import { ARTIFACT_TRANSFER_ERRORS, ARTIFACT_TRANSFER_V1_MAX_BYTES, ARTIFACT_TRANSFER_V2_MEDIA_TYPE, ARTIFACT_TRANSFER_V2_URN, parseReprDigest } from '@hivemagnus/hive-common/artifact';
8
+ import { responseFailure, RetryStoppedError, retryWithPolicy } from './retry.js';
9
+ import { ArdentA2AClient } from './a2a-client.js';
10
+ import { ARTIFACT_MIME_TYPES, ArtifactManifest11Schema, ArtifactMimeSchema, artifactContentInspector, manifestV11, TeamArtifactManifestSchema } from './artifact-manifests.js';
11
+ import { ArtifactStoreError, hashFileRange } from './artifacts.js';
12
+ import { buildTaskExecution } from './execution.js';
13
+ import { TeamArtifactDescriptorSchema, TeamArtifactDescriptorV2Schema, TeamArtifactRequiresV2Schema } from './team-artifacts.js';
14
+ import { ProvenNoEffectError } from './tools.js';
15
+ const digest = z.string().regex(/^[a-f0-9]{64}$/);
16
+ const identifier = z.string().regex(/^[a-f0-9]{32}$/);
17
+ export const ArtifactImportStateSchema = z.enum(['queued', 'transferring', 'verifying', 'completed', 'failed']);
18
+ /** Ask this profile to pull one artifact a peer exported from one of its A2A tasks. */
19
+ export const ArtifactImportRequestSchema = z.object({
20
+ peer_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/), a2a_task_id: z.string().min(1).max(256), artifact_id: identifier,
21
+ /** A local task to attach the imported artifact to; without one, the import records its own completed task. */
22
+ task_id: z.string().guid().optional()
23
+ }).strict();
24
+ export const ArtifactImportSchema = z.object({
25
+ import_id: identifier, peer_id: z.string(), a2a_task_id: z.string(), artifact_id: identifier, state: ArtifactImportStateSchema,
26
+ received_bytes: z.number().int().min(0), size: z.number().int().min(0).nullable(), sha256: digest.nullable(),
27
+ mime: z.string().nullable(), name: z.string().nullable(), protocol: z.enum(['v1', 'v2']).nullable(), attempts: z.number().int().min(0),
28
+ local_task_id: z.string().nullable(), error: z.object({ code: z.string(), message: z.string() }).strict().optional(),
29
+ created_ms: z.number().int(), updated_ms: z.number().int()
30
+ }).strict();
31
+ /** A transfer outcome. `retryable` failures are transport problems a resumed attempt may get past. */
32
+ export class ArtifactTransferError extends Error {
33
+ code;
34
+ /** What a retryable failure tells the retry policy (a transport error unless a response said otherwise). */
35
+ failure;
36
+ constructor(message, code, retryable = false) {
37
+ super(message);
38
+ this.code = code;
39
+ this.name = 'ArtifactTransferError';
40
+ this.failure = retryable === true ? { network: true } : retryable === false ? undefined : retryable;
41
+ }
42
+ get retryable() { return this.failure !== undefined; }
43
+ }
44
+ const Row = z.object({
45
+ id: identifier, peer_id: z.string(), a2a_task_id: z.string(), artifact_id: identifier, sha256: digest.nullable(), size: z.number().int().nullable(),
46
+ mime: z.string().nullable(), name: z.string().nullable(), received_bytes: z.number().int(), state: ArtifactImportStateSchema,
47
+ partial_path: z.string(), attempts: z.number().int(), error: z.string().nullable(), error_code: z.string().nullable(),
48
+ context_id: z.string().nullable(), protocol: z.enum(['v1', 'v2']).nullable(), content_path: z.string().nullable(),
49
+ manifest_json: z.string().nullable(), manifest_1_0_json: z.string().nullable(), caller: z.string(), local_task_id: z.string().nullable(),
50
+ created_ms: z.number().int(), updated_ms: z.number().int()
51
+ });
52
+ const RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);
53
+ function texts(task) {
54
+ return task.artifacts.flatMap(artifact => artifact.parts.flatMap(part => part.content?.$case === 'text' && typeof part.content.value === 'string' ? [part.content.value] : []));
55
+ }
56
+ function v2Parts(task) {
57
+ return task.artifacts.flatMap(artifact => artifact.parts.flatMap(part => part.content?.$case === 'data' && part.mediaType === ARTIFACT_TRANSFER_V2_MEDIA_TYPE ? [part.content.value] : []));
58
+ }
59
+ function parseEach(values, schema) {
60
+ return values.flatMap(value => { const parsed = schema.safeParse(value); return parsed.success ? [parsed.data] : []; });
61
+ }
62
+ function json(value) { try {
63
+ return JSON.parse(value);
64
+ }
65
+ catch {
66
+ return undefined;
67
+ } }
68
+ /** The transfer-v2 parameters a peer card advertises, or undefined. */
69
+ export function peerTransferV2(card) {
70
+ const extension = card.capabilities?.extensions.find(item => item.uri === ARTIFACT_TRANSFER_V2_URN);
71
+ if (!extension)
72
+ return undefined;
73
+ const params = z.object({ max_bytes: z.number().int().positive().optional() }).passthrough().safeParse(extension.params ?? {});
74
+ return params.success && params.data.max_bytes !== undefined ? { max_bytes: params.data.max_bytes } : {};
75
+ }
76
+ function jsonRpcOrigin(card) {
77
+ const url = card.supportedInterfaces.find(item => item.protocolBinding.toUpperCase() === 'JSONRPC' && item.protocolVersion === '1.0')?.url;
78
+ if (!url)
79
+ throw new ArtifactTransferError('Remote peer has no pinned JSON-RPC origin', 'PEER_UNSUPPORTED');
80
+ return url;
81
+ }
82
+ async function writeAll(file, bytes, position) {
83
+ for (let offset = 0; offset < bytes.byteLength;)
84
+ offset += (await file.write(bytes, offset, bytes.byteLength - offset, position + offset)).bytesWritten;
85
+ }
86
+ /**
87
+ * Resumable pulls of peer artifacts (transfer v2, with the v1 path for older
88
+ * peers up to 2 MiB). Progress lives in `artifact_transfers` and a partial file
89
+ * under `<profile>/artifacts/.partial/<import id>`; a restart re-hashes the
90
+ * retained bytes as a stream and asks the peer for the rest with Range and
91
+ * If-Range. The finished file is verified, renamed into the content store and
92
+ * registered with a manifest 1.1 that records the peer hop.
93
+ */
94
+ export class ArtifactTransfers {
95
+ runtime;
96
+ env;
97
+ options;
98
+ #running = new Map();
99
+ #fetch;
100
+ constructor(runtime, env = process.env, options = {}) {
101
+ this.runtime = runtime;
102
+ this.env = env;
103
+ this.options = options;
104
+ this.#fetch = options.fetch ?? fetch;
105
+ runtime.store.db.exec(`CREATE TABLE IF NOT EXISTS artifact_transfers (
106
+ id TEXT PRIMARY KEY, peer_id TEXT NOT NULL, a2a_task_id TEXT NOT NULL, artifact_id TEXT NOT NULL,
107
+ sha256 TEXT, size INTEGER, mime TEXT, name TEXT, received_bytes INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL,
108
+ partial_path TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, error TEXT, error_code TEXT,
109
+ context_id TEXT, protocol TEXT, content_path TEXT, manifest_json TEXT, manifest_1_0_json TEXT,
110
+ caller TEXT NOT NULL, local_task_id TEXT, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
111
+ UNIQUE(peer_id, a2a_task_id, artifact_id));
112
+ CREATE INDEX IF NOT EXISTS artifact_transfers_state ON artifact_transfers(state, updated_ms);`);
113
+ }
114
+ /**
115
+ * Record an import, or return the existing one for the same peer, task and
116
+ * artifact. A failed import is queued again from what it retained: that is
117
+ * the operator's explicit reissue.
118
+ */
119
+ request(input, caller = 'management') {
120
+ const request = ArtifactImportRequestSchema.parse(input);
121
+ if (request.task_id && !this.runtime.store.get(request.task_id))
122
+ throw new Error('Local task not found');
123
+ const db = this.runtime.store.db;
124
+ return db.transaction(() => {
125
+ const existing = db.prepare('SELECT * FROM artifact_transfers WHERE peer_id=? AND a2a_task_id=? AND artifact_id=?')
126
+ .get(request.peer_id, request.a2a_task_id, request.artifact_id);
127
+ if (existing) {
128
+ const row = Row.parse(existing);
129
+ if (row.state === 'failed')
130
+ db.prepare(`UPDATE artifact_transfers SET state='queued',error=NULL,error_code=NULL,updated_ms=? WHERE id=?`).run(Date.now(), row.id);
131
+ return this.#view(this.#row(row.id));
132
+ }
133
+ const id = randomBytes(16).toString('hex');
134
+ const now = Date.now();
135
+ db.prepare(`INSERT INTO artifact_transfers(id,peer_id,a2a_task_id,artifact_id,state,partial_path,caller,local_task_id,created_ms,updated_ms)
136
+ VALUES (?,?,?,?,'queued',?,?,?,?,?)`).run(id, request.peer_id, request.a2a_task_id, request.artifact_id, join(this.runtime.artifacts.partialDirectory, id), caller, request.task_id ?? null, now, now);
137
+ return this.#view(this.#row(id));
138
+ })();
139
+ }
140
+ /** Record an import and run it in the background. */
141
+ start(input, caller = 'management') {
142
+ const record = this.request(input, caller);
143
+ if (record.state !== 'completed')
144
+ void this.run(record.import_id).catch(() => { });
145
+ return record;
146
+ }
147
+ /** Resume every import a previous process left unfinished. */
148
+ resumePending() {
149
+ const ids = z.array(z.object({ id: identifier })).parse(this.runtime.store.db.prepare(`SELECT id FROM artifact_transfers WHERE state IN ('queued','transferring','verifying') ORDER BY created_ms LIMIT 100`).all()).map(row => row.id);
150
+ for (const id of ids)
151
+ void this.run(id).catch(() => { });
152
+ return ids;
153
+ }
154
+ get(id) {
155
+ if (!identifier.safeParse(id).success)
156
+ return undefined;
157
+ const raw = this.runtime.store.db.prepare('SELECT * FROM artifact_transfers WHERE id=?').get(id);
158
+ return raw ? this.#view(Row.parse(raw)) : undefined;
159
+ }
160
+ list(limit = 50) {
161
+ return this.runtime.store.db.prepare('SELECT * FROM artifact_transfers ORDER BY created_ms DESC LIMIT ?')
162
+ .all(Math.max(1, Math.min(limit, 200))).map(raw => this.#view(Row.parse(raw)));
163
+ }
164
+ /**
165
+ * Run (or resume) an import to its outcome. An abort leaves it resumable.
166
+ * Concurrent calls for one import share a single run.
167
+ */
168
+ run(id, signal) {
169
+ const active = this.#running.get(id);
170
+ if (active)
171
+ return active;
172
+ const running = this.#execute(id, signal).finally(() => this.#running.delete(id));
173
+ this.#running.set(id, running);
174
+ return running;
175
+ }
176
+ async #execute(id, signal) {
177
+ let row = this.#row(id);
178
+ if (row.state === 'completed' || row.state === 'failed')
179
+ return this.#view(row);
180
+ const deadlineMs = Date.now() + (this.options.deadlineMs ?? 30 * 60_000);
181
+ this.#set(id, { state: row.state === 'verifying' ? 'verifying' : 'transferring', attempts: row.attempts + 1 });
182
+ try {
183
+ const policy = this.options.retryPolicy ?? 'artifact_transfer';
184
+ // Every attempt is a read that resumes from the retained bytes, so a repeat is safe by contract.
185
+ const options = { signal, deadlineMs, effect: 'idempotent',
186
+ classify: (error) => error instanceof ArtifactTransferError ? error.failure : undefined,
187
+ onAttempt: (record) => {
188
+ if (record.delayMs !== null)
189
+ this.#set(id, { attempts: this.#row(id).attempts + 1 });
190
+ } };
191
+ row = this.#row(id);
192
+ const resolved = this.#resolvedRow(row) ?? await retryWithPolicy(policy, () => this.#resolve(row), options);
193
+ if (resolved.state !== 'verifying') {
194
+ await retryWithPolicy(policy, () => this.#transferOnce(resolved, signal), options);
195
+ this.#set(id, { state: 'verifying' });
196
+ }
197
+ await this.#finalize(this.#resolvedRow(this.#row(id)) ?? resolved);
198
+ }
199
+ catch (error) {
200
+ // An aborted run (shutdown, or a caller that stopped waiting) stays resumable.
201
+ if (signal?.aborted)
202
+ throw error;
203
+ const failure = error instanceof RetryStoppedError
204
+ ? new ArtifactTransferError(`Transfer interrupted: ${error.message}`, 'TRANSFER_INTERRUPTED')
205
+ : error instanceof ArtifactTransferError ? error
206
+ : error instanceof ProvenNoEffectError ? new ArtifactTransferError(error.message, error.code)
207
+ : error instanceof ArtifactStoreError ? new ArtifactTransferError(error.message, error.code)
208
+ : new ArtifactTransferError(error instanceof Error ? error.message : 'Artifact import failed', 'TRANSFER_FAILED');
209
+ // Bytes that failed verification are never kept; anything else stays for a reissue.
210
+ if ([ARTIFACT_TRANSFER_ERRORS.digestMismatch, ARTIFACT_TRANSFER_ERRORS.gone, 'INVALID_ARTIFACT'].includes(failure.code))
211
+ await this.#discard(id);
212
+ this.#set(id, { state: 'failed', error: failure.message.slice(0, 500), error_code: failure.code });
213
+ }
214
+ return this.#view(this.#row(id));
215
+ }
216
+ /** Resolve the peer's descriptor for the artifact and negotiate the protocol and limit. */
217
+ async #resolve(row) {
218
+ const { card, client, authorization } = await this.#open(row.peer_id);
219
+ let remote;
220
+ try {
221
+ remote = await client.getTask({ tenant: '', id: row.a2a_task_id }, { serviceParameters: { Authorization: authorization, 'A2A-Version': '1.0' } });
222
+ }
223
+ catch (error) {
224
+ throw new ArtifactTransferError(`Remote task is unavailable: ${error instanceof Error ? error.message : 'unknown error'}`, 'PEER_UNAVAILABLE', true);
225
+ }
226
+ if (remote.id !== row.a2a_task_id || remote.status?.state !== TaskState.TASK_STATE_COMPLETED)
227
+ throw new ArtifactTransferError('Remote task receipt is not complete or bound', 'REMOTE_TASK_INCOMPLETE');
228
+ const v2 = peerTransferV2(card);
229
+ const allTexts = texts(remote).map(json);
230
+ const declaredV1 = parseEach(allTexts, TeamArtifactDescriptorSchema).find(item => item.artifact_id === row.artifact_id && item.producer_task_id === remote.id);
231
+ const declaredV2 = parseEach(v2Parts(remote), TeamArtifactDescriptorV2Schema).find(item => item.manifest_1_1.artifact_id === row.artifact_id && item.manifest_1_1.provenance.producer_task_id === remote.id);
232
+ const requiresV2 = parseEach(allTexts, TeamArtifactRequiresV2Schema).find(item => item.artifact_id === row.artifact_id && item.producer_task_id === remote.id);
233
+ let plan;
234
+ if (v2 && declaredV2)
235
+ plan = { protocol: 'v2', manifest: declaredV2.manifest_1_1, manifest10: null, contentPath: declaredV2.content_path };
236
+ else if (declaredV1)
237
+ plan = { protocol: 'v1', manifest: manifestV11(declaredV1.artifact_manifest), manifest10: JSON.stringify(declaredV1.artifact_manifest),
238
+ contentPath: `/team/artifacts/${row.artifact_id}?context=${encodeURIComponent(remote.contextId)}` };
239
+ else if (declaredV2 || requiresV2)
240
+ throw new ArtifactTransferError(`Peer ${row.peer_id} does not advertise ${ARTIFACT_TRANSFER_V2_URN}; ` +
241
+ `artifacts larger than ${ARTIFACT_TRANSFER_V1_MAX_BYTES} bytes need it`, ARTIFACT_TRANSFER_ERRORS.requiresV2);
242
+ else
243
+ throw new ArtifactTransferError('Remote task did not declare this exact artifact', 'ARTIFACT_NOT_DECLARED');
244
+ if (!ArtifactMimeSchema.safeParse(plan.manifest.mime).success)
245
+ throw new ArtifactTransferError(`Artifact media type ${plan.manifest.mime.slice(0, 100)} is not accepted`, 'INVALID_ARTIFACT');
246
+ const limit = Math.min(this.runtime.artifacts.maxBytes, v2?.max_bytes ?? Number.MAX_SAFE_INTEGER);
247
+ if (plan.manifest.size > limit)
248
+ throw new ArtifactTransferError(`Artifact size ${plan.manifest.size} exceeds the negotiated limit of ${limit} bytes`, ARTIFACT_TRANSFER_ERRORS.tooLarge);
249
+ if (plan.manifest.expires_at <= Date.now() / 1000)
250
+ throw new ArtifactTransferError('Remote artifact export has expired', ARTIFACT_TRANSFER_ERRORS.gone);
251
+ this.#set(row.id, { sha256: plan.manifest.sha256, size: plan.manifest.size, mime: plan.manifest.mime, name: plan.manifest.name,
252
+ protocol: plan.protocol, context_id: remote.contextId, content_path: plan.contentPath, manifest_json: JSON.stringify(plan.manifest),
253
+ manifest_1_0_json: plan.manifest10 });
254
+ const resolved = this.#resolvedRow(this.#row(row.id));
255
+ if (!resolved)
256
+ throw new Error('Import descriptor was not recorded');
257
+ return resolved;
258
+ }
259
+ /** One attempt: resume from the retained bytes and append the rest. */
260
+ async #transferOnce(row, signal) {
261
+ const { card, authorization } = await this.#open(row.peer_id);
262
+ const origin = jsonRpcOrigin(card);
263
+ const url = new URL(row.content_path, origin);
264
+ if (url.origin !== new URL(origin).origin || !url.pathname.startsWith('/team/artifacts/'))
265
+ throw new ArtifactTransferError('Artifact path leaves the peer origin', 'PEER_UNSUPPORTED');
266
+ await mkdir(this.runtime.artifacts.partialDirectory, { recursive: true, mode: 0o700 });
267
+ const file = await open(row.partial_path, constants.O_RDWR | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
268
+ let received = 0;
269
+ let committed = 0;
270
+ let writable = true;
271
+ try {
272
+ // Only committed bytes were fsynced; anything after them is discarded.
273
+ const info = await file.stat();
274
+ received = row.protocol === 'v2' ? Math.min(this.#row(row.id).received_bytes, info.size, row.size) : 0;
275
+ await file.truncate(received);
276
+ const hash = await this.#rehash(file, received);
277
+ committed = received;
278
+ this.#commit(row.id, received);
279
+ if (received === row.size) {
280
+ this.#verify(hash, row);
281
+ return;
282
+ }
283
+ const idle = new AbortController();
284
+ const idleMs = this.options.idleTimeoutMs ?? 60_000;
285
+ let timer = setTimeout(() => idle.abort(new Error('Artifact response stalled')), idleMs);
286
+ const headers = { Authorization: authorization };
287
+ if (row.protocol === 'v2') {
288
+ headers.Range = `bytes=${received}-`;
289
+ headers['If-Range'] = `"${row.sha256}"`;
290
+ }
291
+ let response;
292
+ try {
293
+ response = await this.#fetch(url, { redirect: 'manual', headers, signal: signal ? AbortSignal.any([signal, idle.signal]) : idle.signal });
294
+ }
295
+ catch (error) {
296
+ clearTimeout(timer);
297
+ if (signal?.aborted)
298
+ throw error;
299
+ throw new ArtifactTransferError(`Artifact fetch failed: ${error instanceof Error ? error.message : 'network error'}`, 'TRANSFER_INTERRUPTED', true);
300
+ }
301
+ try {
302
+ let hashState = hash;
303
+ if (response.status === 404 || response.status === 410)
304
+ throw new ArtifactTransferError(`Peer no longer serves the artifact (HTTP ${response.status})`, ARTIFACT_TRANSFER_ERRORS.gone);
305
+ if (RETRYABLE_STATUS.has(response.status))
306
+ throw new ArtifactTransferError(`Artifact fetch HTTP ${response.status}`, 'TRANSFER_INTERRUPTED', responseFailure(response));
307
+ if (response.status === 416 && received === row.size) {
308
+ this.#verify(hashState, row);
309
+ return;
310
+ }
311
+ if (response.status !== 200 && response.status !== 206)
312
+ throw new ArtifactTransferError(`Artifact fetch HTTP ${response.status}`, 'TRANSFER_REJECTED');
313
+ this.#checkHeaders(response, row);
314
+ if (response.status === 206) {
315
+ if (row.protocol !== 'v2' || response.headers.get('content-range') !== `bytes ${received}-${row.size - 1}/${row.size}`)
316
+ throw new ArtifactTransferError('Partial response does not continue the retained bytes', 'TRANSFER_REJECTED');
317
+ }
318
+ else if (received > 0) {
319
+ // The peer sent the whole representation (no Range support, or a changed one): start over.
320
+ received = 0;
321
+ committed = 0;
322
+ await file.truncate(0);
323
+ this.#commit(row.id, 0);
324
+ hashState = createHash('sha256');
325
+ }
326
+ const length = Number(response.headers.get('content-length') ?? NaN);
327
+ if (Number.isFinite(length) && length !== row.size - received)
328
+ throw new ArtifactTransferError('Artifact length differs from its descriptor', ARTIFACT_TRANSFER_ERRORS.digestMismatch);
329
+ if (!response.body)
330
+ throw new ArtifactTransferError('Artifact response has no body', 'TRANSFER_INTERRUPTED', true);
331
+ const reader = response.body.getReader();
332
+ const commitBytes = this.options.commitBytes ?? 4 * 1024 * 1024;
333
+ try {
334
+ while (true) {
335
+ let chunk;
336
+ try {
337
+ chunk = await reader.read();
338
+ }
339
+ catch (error) {
340
+ if (signal?.aborted)
341
+ throw error;
342
+ throw new ArtifactTransferError(`Artifact response ended early: ${error instanceof Error ? error.message : 'read error'}`, 'TRANSFER_INTERRUPTED', true);
343
+ }
344
+ if (chunk.done)
345
+ break;
346
+ clearTimeout(timer);
347
+ timer = setTimeout(() => idle.abort(new Error('Artifact response stalled')), idleMs);
348
+ const bytes = chunk.value;
349
+ if (received + bytes.byteLength > row.size)
350
+ throw new ArtifactTransferError('Artifact response exceeds its declared size', ARTIFACT_TRANSFER_ERRORS.digestMismatch);
351
+ writable = false;
352
+ await writeAll(file, bytes, received);
353
+ writable = true;
354
+ hashState.update(bytes);
355
+ received += bytes.byteLength;
356
+ if (received - committed >= commitBytes) {
357
+ await file.sync();
358
+ this.#commit(row.id, received);
359
+ committed = received;
360
+ }
361
+ this.options.onProgress?.({ import_id: row.id, received_bytes: received, size: row.size });
362
+ }
363
+ }
364
+ finally {
365
+ await reader.cancel().catch(() => { });
366
+ }
367
+ if (received !== row.size)
368
+ throw new ArtifactTransferError('Artifact response ended before its declared size', 'TRANSFER_INTERRUPTED', true);
369
+ this.#verify(hashState, row);
370
+ }
371
+ finally {
372
+ clearTimeout(timer);
373
+ }
374
+ }
375
+ finally {
376
+ // Retain what was written: an interrupted attempt resumes from it.
377
+ if (writable && received > committed) {
378
+ await file.sync().catch(() => { });
379
+ this.#commit(row.id, received);
380
+ }
381
+ await file.close().catch(() => { });
382
+ }
383
+ }
384
+ #verify(hash, row) {
385
+ if (hash.digest('hex') !== row.sha256)
386
+ throw new ArtifactTransferError('Received bytes differ from the declared SHA-256', ARTIFACT_TRANSFER_ERRORS.digestMismatch);
387
+ }
388
+ #checkHeaders(response, row) {
389
+ const etag = response.headers.get('etag');
390
+ const repr = parseReprDigest(response.headers.get('repr-digest'));
391
+ const declared = response.headers.get('x-content-sha256');
392
+ if ((etag !== null && etag !== `"${row.sha256}"`) || (repr !== undefined && repr !== row.sha256) || (declared !== null && declared !== row.sha256))
393
+ throw new ArtifactTransferError('Peer serves a different representation than it declared', ARTIFACT_TRANSFER_ERRORS.digestMismatch);
394
+ if (row.protocol === 'v1') {
395
+ if (response.headers.get('x-hermes-task-id') !== row.a2a_task_id ||
396
+ decodeURIComponent(response.headers.get('x-artifact-name') ?? '') !== row.name ||
397
+ response.headers.get('content-type')?.split(';')[0] !== row.mime)
398
+ throw new ArtifactTransferError('Artifact response differs from the task receipt', 'TRANSFER_REJECTED');
399
+ const encoded = response.headers.get('x-hermes-artifact-manifest');
400
+ if (!encoded || encoded.length > 8192)
401
+ throw new ArtifactTransferError('Artifact manifest is missing or oversized', 'TRANSFER_REJECTED');
402
+ const manifest = TeamArtifactManifestSchema.safeParse(json(Buffer.from(encoded, 'base64url').toString('utf8')));
403
+ if (!manifest.success || JSON.stringify(manifest.data) !== row.manifest_1_0_json)
404
+ throw new ArtifactTransferError('Artifact manifest differs from the task receipt', 'TRANSFER_REJECTED');
405
+ }
406
+ }
407
+ async #rehash(file, length) {
408
+ const hash = createHash('sha256');
409
+ if (await hashFileRange(file, hash, 0, length) !== length)
410
+ throw new ArtifactTransferError('Partial file is shorter than its committed bytes', 'TRANSFER_INTERRUPTED', true);
411
+ return hash;
412
+ }
413
+ /** Rename the verified file into the store (or find it there) and register it; safe to repeat. */
414
+ async #finalize(row) {
415
+ await this.#inspect(row);
416
+ try {
417
+ await this.runtime.artifacts.adoptFile(row.partial_path, { sha256: row.sha256, size: row.size });
418
+ }
419
+ catch (error) {
420
+ const missing = error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';
421
+ if (!missing)
422
+ throw error;
423
+ // The partial file is gone and the digest is not stored: transfer again from the start.
424
+ this.#set(row.id, { state: 'transferring', received_bytes: 0 });
425
+ throw new ArtifactTransferError('Verified bytes are no longer retained; reissue the import', 'TRANSFER_INTERRUPTED');
426
+ }
427
+ const manifest = ArtifactManifest11Schema.parse(JSON.parse(row.manifest_json));
428
+ const taskId = row.local_task_id ?? this.#importTask(row, manifest);
429
+ await this.runtime.artifactManifests.registerImported({ taskId, peer: row.peer_id, remoteTaskId: row.a2a_task_id, manifest,
430
+ artifactId: row.id, onRegistered: () => this.#set(row.id, { state: 'completed', received_bytes: row.size, local_task_id: taskId, error: null, error_code: null }) });
431
+ }
432
+ /** Check the verified partial file against its media type before it enters the store. */
433
+ async #inspect(row) {
434
+ const mime = ArtifactMimeSchema.parse(row.mime);
435
+ let file;
436
+ try {
437
+ file = await open(row.partial_path, constants.O_RDONLY | constants.O_NOFOLLOW);
438
+ }
439
+ catch (error) {
440
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
441
+ return;
442
+ throw error;
443
+ }
444
+ try {
445
+ const inspector = artifactContentInspector(mime);
446
+ const binary = ['png', 'jpeg', 'webp', 'pdf', 'docx'].includes(ARTIFACT_MIME_TYPES[mime]);
447
+ await hashFileRange(file, { update: chunk => inspector.write(chunk) }, 0, binary ? Math.min(16, row.size) : row.size);
448
+ inspector.end();
449
+ }
450
+ finally {
451
+ await file.close();
452
+ }
453
+ }
454
+ /** A completed local task that owns an import made without one. Idempotent per import. */
455
+ #importTask(row, manifest) {
456
+ const store = this.runtime.store;
457
+ // Attribution only: the producer's execution, when the manifest names one, becomes the import task's parent.
458
+ const produced = manifest.provenance.execution;
459
+ const context = produced ? { v: 1, root: produced.root, ...(produced.task ? { self: produced.task } : {}) } : undefined;
460
+ return store.db.transaction(() => {
461
+ const task = store.accept({ caller: row.caller, context: 'direct', prompt: `Import artifact ${row.name} from A2A peer ${row.peer_id} task ${row.a2a_task_id}`.slice(0, 16000),
462
+ idempotencyKey: `artifact-import:${row.id}`, backend: this.runtime.config.execution.backend, deadlineMs: Date.now(),
463
+ execution: created => buildTaskExecution(this.runtime.instanceRef, created, { context, source: 'a2a' }) });
464
+ if (task.state === 'queued')
465
+ store.setState(task.id, 'completed', `Imported artifact ${row.name} (sha256 ${row.sha256})`);
466
+ this.#set(row.id, { local_task_id: task.id });
467
+ return task.id;
468
+ })();
469
+ }
470
+ async #discard(id) {
471
+ await unlink(this.#row(id).partial_path).catch(() => { });
472
+ this.#commit(id, 0);
473
+ }
474
+ async #open(peer) {
475
+ try {
476
+ return await new ArdentA2AClient(this.runtime.profileDir, this.runtime.config, this.env).open(peer);
477
+ }
478
+ catch (error) {
479
+ const message = error instanceof Error ? error.message : 'Peer unavailable';
480
+ // Configuration problems are permanent; a peer that does not answer may come back.
481
+ throw new ArtifactTransferError(message, /not configured|credential/i.test(message) ? 'PEER_UNAVAILABLE' : 'PEER_UNREACHABLE', !/not configured|credential/i.test(message));
482
+ }
483
+ }
484
+ #row(id) {
485
+ const raw = this.runtime.store.db.prepare('SELECT * FROM artifact_transfers WHERE id=?').get(id);
486
+ if (!raw)
487
+ throw new Error('Artifact import not found');
488
+ return Row.parse(raw);
489
+ }
490
+ #resolvedRow(row) {
491
+ const { sha256, size, mime, name, protocol, content_path: contentPath, manifest_json: manifestJson } = row;
492
+ if (sha256 === null || size === null || mime === null || name === null || protocol === null || contentPath === null || manifestJson === null)
493
+ return undefined;
494
+ return { ...row, sha256, size, mime, name, protocol, content_path: contentPath, manifest_json: manifestJson };
495
+ }
496
+ #commit(id, received) {
497
+ this.runtime.store.db.prepare('UPDATE artifact_transfers SET received_bytes=?,updated_ms=? WHERE id=?').run(received, Date.now(), id);
498
+ }
499
+ #set(id, fields) {
500
+ const entries = Object.entries(fields);
501
+ if (!entries.length)
502
+ return;
503
+ const allowed = new Set(Object.keys(Row.shape));
504
+ for (const [key] of entries)
505
+ if (!allowed.has(key) || key === 'id')
506
+ throw new Error(`Unknown import field ${key}`);
507
+ this.runtime.store.db.prepare(`UPDATE artifact_transfers SET ${entries.map(([key]) => `${key}=?`).join(',')},updated_ms=? WHERE id=?`)
508
+ .run(...entries.map(([, value]) => value ?? null), Date.now(), id);
509
+ }
510
+ #view(row) {
511
+ return ArtifactImportSchema.parse({ import_id: row.id, peer_id: row.peer_id, a2a_task_id: row.a2a_task_id, artifact_id: row.artifact_id,
512
+ state: row.state, received_bytes: row.received_bytes, size: row.size, sha256: row.sha256, mime: row.mime, name: row.name,
513
+ protocol: row.protocol, attempts: row.attempts, local_task_id: row.local_task_id,
514
+ ...(row.error ? { error: { code: row.error_code ?? 'TRANSFER_FAILED', message: row.error } } : {}),
515
+ created_ms: row.created_ms, updated_ms: row.updated_ms });
516
+ }
517
+ }
@@ -1,3 +1,6 @@
1
+ import { type FileHandle } from 'node:fs/promises';
2
+ import { Readable } from 'node:stream';
3
+ import type { ReadableStream as WebReadableStream } from 'node:stream/web';
1
4
  import { z } from 'zod';
2
5
  export declare const ArtifactSchema: z.ZodObject<{
3
6
  id: z.ZodString;
@@ -11,6 +14,59 @@ export type Artifact = z.infer<typeof ArtifactSchema>;
11
14
  export declare const ARTIFACT_DEFAULT_MAX_BYTES: number;
12
15
  /** Largest per-artifact limit a profile may configure; also the bound on reading a stored artifact. */
13
16
  export declare const ARTIFACT_MAX_BYTES_LIMIT: number;
17
+ /** A stored artifact's identity and size, without reading its bytes. */
18
+ export type ArtifactStat = {
19
+ id: string;
20
+ sha256: string;
21
+ size: number;
22
+ };
23
+ /** An inclusive byte range; both ends default to the whole artifact. */
24
+ export type ArtifactReadRange = {
25
+ start?: number | undefined;
26
+ end?: number | undefined;
27
+ };
28
+ /** A stream over stored bytes. `start` and `end` are the inclusive offsets it yields. */
29
+ export type ArtifactRead = {
30
+ stream: Readable;
31
+ size: number;
32
+ sha256: string;
33
+ start: number;
34
+ end: number;
35
+ };
36
+ /**
37
+ * Sees every byte `putStream` stores, in order, before the file becomes visible.
38
+ * Throwing from `write` or `end` refuses the artifact; nothing is stored.
39
+ */
40
+ export type ArtifactInspector = {
41
+ write(chunk: Uint8Array): void;
42
+ end(): void;
43
+ };
44
+ export type ArtifactSource = Readable | AsyncIterable<Uint8Array> | WebReadableStream<Uint8Array>;
45
+ export type ArtifactPutStreamOptions = {
46
+ name: string;
47
+ mediaType: string;
48
+ /** Refuse the artifact unless its bytes hash to this lowercase hex SHA-256. */
49
+ expectedSha256?: string | undefined;
50
+ /** Refuse the artifact unless it has exactly this many bytes. */
51
+ expectedSize?: number | undefined;
52
+ /** A tighter per-call bound; never above the store's own limit. */
53
+ maxBytes?: number | undefined;
54
+ inspect?: ArtifactInspector | undefined;
55
+ signal?: AbortSignal | undefined;
56
+ };
57
+ /** Codes on errors that `putStream`, `openRead` and `adoptFile` throw for refused input. */
58
+ export type ArtifactStoreErrorCode = 'INVALID_ARTIFACT' | 'ARTIFACT_TOO_LARGE' | 'SIZE_MISMATCH' | 'DIGEST_MISMATCH' | 'RANGE_NOT_SATISFIABLE' | 'NOT_FOUND';
59
+ export declare class ArtifactStoreError extends Error {
60
+ readonly code: ArtifactStoreErrorCode;
61
+ constructor(message: string, code: ArtifactStoreErrorCode);
62
+ }
63
+ /**
64
+ * Feed `length` bytes of an open file from `start` to `hash` through one
65
+ * reused buffer, so hashing a large file allocates nothing per chunk.
66
+ */
67
+ export declare function hashFileRange(file: FileHandle, hash: {
68
+ update(data: Uint8Array): unknown;
69
+ }, start: number, length: number): Promise<number>;
14
70
  export declare function formatBytes(bytes: number): string;
15
71
  export declare class ArtifactStore {
16
72
  readonly directory: string;
@@ -19,5 +75,35 @@ export declare class ArtifactStore {
19
75
  put(name: string, mediaType: string, bytes: Uint8Array): Promise<Artifact>;
20
76
  /** Remove stored bytes. Callers must prove nothing else still references them. */
21
77
  delete(id: string): Promise<void>;
78
+ /** Where resumable transfers keep their partial files; inside the store so a finished file is one rename away. */
79
+ get partialDirectory(): string;
80
+ /** Size of a stored artifact, or undefined when it is absent. Never follows a symbolic link. */
81
+ stat(id: string): Promise<ArtifactStat | undefined>;
82
+ /**
83
+ * Stream stored bytes, optionally one inclusive range. With `verify`, a read
84
+ * of the whole artifact checks the digest as it streams and fails before the
85
+ * final chunk when the bytes differ. A partial read is never verified.
86
+ */
87
+ openRead(id: string, range?: ArtifactReadRange, options?: {
88
+ verify?: boolean;
89
+ }): Promise<ArtifactRead>;
90
+ /** Hash stored bytes as a stream; throws when they differ from their ID. Returns the size. */
91
+ verify(id: string): Promise<number>;
92
+ /**
93
+ * Store bytes from a stream without holding them in memory: a private
94
+ * temporary file, an incremental SHA-256, a size bound, fsync, then an atomic
95
+ * rename to the digest. Every refusal happens before the rename.
96
+ */
97
+ putStream(source: ArtifactSource, options: ArtifactPutStreamOptions): Promise<Artifact>;
98
+ /**
99
+ * Move a complete file (for example a finished transfer's partial file on the
100
+ * same file system) into the store under its digest. The bytes are hashed
101
+ * again first. If the digest is already stored, the file is discarded, so a
102
+ * repeated call is harmless.
103
+ */
104
+ adoptFile(path: string, expected: {
105
+ sha256: string;
106
+ size: number;
107
+ }): Promise<ArtifactStat>;
22
108
  get(id: string): Promise<Uint8Array>;
23
109
  }