@pi-unipi/background-tasks 2.6.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 (116) hide show
  1. package/README.md +87 -0
  2. package/extensions/anthropic-attribution.ts +1 -0
  3. package/extensions/delegate-child.ts +1 -0
  4. package/extensions/fusion-child.ts +1 -0
  5. package/package.json +40 -0
  6. package/src/__tests__/anthropic-attribution.test.ts +195 -0
  7. package/src/__tests__/config.test.ts +137 -0
  8. package/src/__tests__/core.test.ts +493 -0
  9. package/src/__tests__/delegate-artifacts.test.ts +528 -0
  10. package/src/__tests__/delegate-budget.test.ts +456 -0
  11. package/src/__tests__/delegate-launch.test.ts +676 -0
  12. package/src/__tests__/delegate-result-package.test.ts +350 -0
  13. package/src/__tests__/delegate-seed.test.ts +392 -0
  14. package/src/__tests__/durable-fs.test.ts +559 -0
  15. package/src/__tests__/extension-api.test.ts +579 -0
  16. package/src/__tests__/fusion-artifacts.test.ts +1039 -0
  17. package/src/__tests__/fusion-budget.test.ts +1356 -0
  18. package/src/__tests__/fusion-claude-cache.test.ts +320 -0
  19. package/src/__tests__/fusion-config.test.ts +335 -0
  20. package/src/__tests__/fusion-context-prompts.test.ts +670 -0
  21. package/src/__tests__/fusion-evaluation.test.ts +315 -0
  22. package/src/__tests__/fusion-extraction-equivalence.test.ts +58 -0
  23. package/src/__tests__/fusion-golden-bytes.test.ts +35 -0
  24. package/src/__tests__/fusion-high-cardinality.test.ts +192 -0
  25. package/src/__tests__/fusion-model-selector.test.ts +205 -0
  26. package/src/__tests__/fusion-orchestrator.test.ts +1194 -0
  27. package/src/__tests__/fusion-rpc.test.ts +369 -0
  28. package/src/__tests__/fusion-sdk.test.ts +1226 -0
  29. package/src/__tests__/fusion-v5-core.test.ts +219 -0
  30. package/src/__tests__/fusion-validate-orchestrator.test.ts +240 -0
  31. package/src/__tests__/fusion-web-fetch.test.ts +485 -0
  32. package/src/__tests__/fusion-workflows.test.ts +59 -0
  33. package/src/__tests__/helpers/delegate-deterministic-seed.ts +109 -0
  34. package/src/__tests__/helpers/delegate-seed-subprocess.ts +10 -0
  35. package/src/__tests__/helpers/fusion-canonical-subprocess.ts +21 -0
  36. package/src/__tests__/helpers/fusion-canonical.ts +140 -0
  37. package/src/__tests__/helpers/fusion-fake-pi.ts +279 -0
  38. package/src/__tests__/helpers/fusion-golden-corpus.ts +500 -0
  39. package/src/__tests__/helpers/fusion-high-cardinality.ts +140 -0
  40. package/src/__tests__/helpers/normalize.ts +22 -0
  41. package/src/__tests__/helpers/pi-hook-contract-evidence.json +18 -0
  42. package/src/__tests__/pi-launch.test.ts +202 -0
  43. package/src/__tests__/registry.test.ts +1580 -0
  44. package/src/__tests__/scripted-provider/delegate-ambient-provider.test.ts +130 -0
  45. package/src/__tests__/scripted-provider/delegate-child-guard.test.ts +631 -0
  46. package/src/__tests__/scripted-provider/delegate-guard-provider.ts +403 -0
  47. package/src/__tests__/scripted-provider/follow-up.test.ts +448 -0
  48. package/src/__tests__/scripted-provider/fusion-output-recovery.test.ts +132 -0
  49. package/src/__tests__/scripted-provider/fusion-reason.test.ts +310 -0
  50. package/src/__tests__/scripted-provider/fusion-runtime-guard.test.ts +163 -0
  51. package/src/__tests__/scripted-provider/hook-contract-provider.ts +179 -0
  52. package/src/__tests__/scripted-provider/hook-probe-a.ts +3 -0
  53. package/src/__tests__/scripted-provider/hook-probe-b.ts +3 -0
  54. package/src/__tests__/scripted-provider/hook-probe-extension.ts +126 -0
  55. package/src/__tests__/scripted-provider/output-recovery-provider.ts +153 -0
  56. package/src/__tests__/scripted-provider/pi-hook-contract-evidence.json +18 -0
  57. package/src/__tests__/scripted-provider/pi-hook-contract.test.ts +477 -0
  58. package/src/__tests__/scripted-provider/runtime-guard-probe.ts +28 -0
  59. package/src/__tests__/scripted-provider/runtime-guard-provider.ts +49 -0
  60. package/src/__tests__/scripted-provider/scripted-provider-extension.ts +408 -0
  61. package/src/__tests__/task-manager.test.ts +479 -0
  62. package/src/__tests__/windows-taskkill.test.ts +161 -0
  63. package/src/anthropic-attribution-path.ts +21 -0
  64. package/src/anthropic-attribution.ts +1983 -0
  65. package/src/attested-pi-run.ts +612 -0
  66. package/src/child-process.ts +55 -0
  67. package/src/common.ts +8 -0
  68. package/src/config.ts +292 -0
  69. package/src/context-parent-snapshot.ts +142 -0
  70. package/src/context-token-budget.ts +903 -0
  71. package/src/context-visible-conversation-v2.ts +551 -0
  72. package/src/delegate/artifacts.ts +487 -0
  73. package/src/delegate/budget.ts +415 -0
  74. package/src/delegate/hook-contract-evidence.json +18 -0
  75. package/src/delegate/hook-contract.ts +154 -0
  76. package/src/delegate/launch.ts +497 -0
  77. package/src/delegate/result-package.ts +459 -0
  78. package/src/delegate/runner.ts +449 -0
  79. package/src/delegate/seed.ts +423 -0
  80. package/src/delegate/types.ts +323 -0
  81. package/src/delegate-child-extension.ts +978 -0
  82. package/src/delegate-extension.ts +806 -0
  83. package/src/durable-fs.ts +386 -0
  84. package/src/extension-api.ts +548 -0
  85. package/src/fixtures/delegate-context-incident.json +17 -0
  86. package/src/fixtures/fusion-golden-bytes.json +310 -0
  87. package/src/fixtures/fusion-validate-golden-bytes.json +282 -0
  88. package/src/fusion/artifacts.ts +967 -0
  89. package/src/fusion/budget.ts +1162 -0
  90. package/src/fusion/child-protocol.ts +305 -0
  91. package/src/fusion/claude-cache.ts +207 -0
  92. package/src/fusion/clean-context.ts +91 -0
  93. package/src/fusion/config.ts +449 -0
  94. package/src/fusion/context.ts +265 -0
  95. package/src/fusion/evaluation.ts +800 -0
  96. package/src/fusion/orchestrator.ts +1288 -0
  97. package/src/fusion/output-contract.ts +34 -0
  98. package/src/fusion/pi-child.ts +2373 -0
  99. package/src/fusion/prompts.ts +345 -0
  100. package/src/fusion/result-package.ts +959 -0
  101. package/src/fusion/source-policy.ts +257 -0
  102. package/src/fusion/types.ts +1139 -0
  103. package/src/fusion/web-fetch.ts +1060 -0
  104. package/src/fusion/workflows.ts +184 -0
  105. package/src/fusion-child-extension.ts +1052 -0
  106. package/src/fusion-extension.ts +1293 -0
  107. package/src/index.ts +295 -0
  108. package/src/pi-launch.ts +225 -0
  109. package/src/registry.ts +2424 -0
  110. package/src/settings-overlay.ts +208 -0
  111. package/src/task-manager.ts +774 -0
  112. package/src/tools.ts +530 -0
  113. package/src/turndown.d.ts +15 -0
  114. package/src/types.ts +963 -0
  115. package/src/ui/fusion-model-selector.ts +322 -0
  116. package/src/windows-taskkill.ts +250 -0
@@ -0,0 +1,487 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { chmod, mkdir, open, readFile, rename, rm } from 'node:fs/promises';
4
+ import { basename, isAbsolute, join, relative, sep } from 'node:path';
5
+ import { canonicalJson } from '../attested-pi-run.js';
6
+ import { sanitizePathSegment } from '../types.js';
7
+ import { replaceFileDurable, writeFileDurable } from '../durable-fs.js';
8
+ import {
9
+ DELEGATE_MANIFEST_SCHEMA_VERSION,
10
+ DELEGATE_RECEIPT_SCHEMA_VERSION,
11
+ DelegateError,
12
+ type DelegateExtensionMode,
13
+ type DelegateLimits,
14
+ type DelegatePinnedRoute,
15
+ type DelegateSpillReceipt,
16
+ } from './types.js';
17
+ import {
18
+ DELEGATE_RESULT_PACKAGE_FILENAME,
19
+ serializeDelegateResultPackage,
20
+ } from './result-package.js';
21
+ import type { DelegateResultPackageV1 } from './types.js';
22
+ import type { DelegateAdmissionPlanV1 } from './budget.js';
23
+
24
+ /**
25
+ * Durable delegate artifacts.
26
+ *
27
+ * The commit discipline is the same everywhere: write to a same-directory
28
+ * temporary file, fsync it, rename it into place, then fsync the directory on
29
+ * POSIX. A file present under its final name is complete. A partially written
30
+ * file never appears under a final name, so a crash or a full disk cannot leave
31
+ * a truncated artifact that looks whole.
32
+ *
33
+ * `result.json` is the commit point for the whole run. It is written by the
34
+ * CHILD, so `manifest.state` deliberately records only what the PARENT knows at
35
+ * launch time and is never used to decide success. The parent's adjudicated view
36
+ * is written separately as `outcome.json` once the run is evaluated, so the two
37
+ * writers never race over one field and no artifact can claim a state its writer
38
+ * did not observe.
39
+ */
40
+
41
+ export const DELEGATE_ARTIFACT_NAMES = {
42
+ seed: 'seed.json',
43
+ ledger: 'context-omission-ledger.json',
44
+ budgetPlan: 'budget-plan.json',
45
+ manifest: 'manifest.json',
46
+ outcome: 'outcome.json',
47
+ result: DELEGATE_RESULT_PACKAGE_FILENAME,
48
+ childPrompt: 'child-prompt.txt',
49
+ runtimeBudget: 'runtime-budget.json',
50
+ error: 'error.json',
51
+ } as const;
52
+
53
+ /** Spilled tool payloads live in their own subdirectory so they cannot collide with control artifacts. */
54
+ export const DELEGATE_SPILL_DIRNAME = 'spill';
55
+
56
+ export interface DelegateArtifactRef {
57
+ path: string;
58
+ byte_length: number;
59
+ sha256: string;
60
+ }
61
+
62
+ export interface DelegateManifestV1 {
63
+ schema_version: typeof DELEGATE_MANIFEST_SCHEMA_VERSION;
64
+ task_id: string;
65
+ launch_nonce: string;
66
+ created_at: string;
67
+ updated_at: string;
68
+ cwd: string;
69
+ child_session_id: string;
70
+ child_session_dir: string;
71
+ extension_mode: DelegateExtensionMode;
72
+ route: DelegatePinnedRoute;
73
+ limits: DelegateLimits;
74
+ seed_sha256: string;
75
+ state: DelegateManifestState;
76
+ error?: string;
77
+ artifacts: Readonly<Record<string, DelegateArtifactRef>>;
78
+ }
79
+
80
+ export const DELEGATE_MANIFEST_STATES = [
81
+ 'launched',
82
+ 'running',
83
+ 'committed',
84
+ 'failed',
85
+ 'cancelled',
86
+ ] as const;
87
+ export type DelegateManifestState = (typeof DELEGATE_MANIFEST_STATES)[number];
88
+
89
+ function sha256Bytes(bytes: Buffer): string {
90
+ return createHash('sha256').update(bytes).digest('hex');
91
+ }
92
+
93
+ function pathInside(parent: string, child: string): boolean {
94
+ const rel = relative(parent, child);
95
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel) && !rel.split(sep).includes('..'));
96
+ }
97
+
98
+ function artifactError(message: string, cause?: unknown): DelegateError {
99
+ const suffix = cause === undefined ? '' : `: ${cause instanceof Error ? cause.message : String(cause)}`;
100
+ return new DelegateError(`${message}${suffix}`, {
101
+ code: 'artifact_error',
102
+ childCreated: true,
103
+ remediation: [
104
+ 'The delegate artifact directory could not be written. Check free disk space and directory permissions.',
105
+ ],
106
+ });
107
+ }
108
+
109
+ export interface CreateDelegateArtifactStoreOptions {
110
+ cwd: string;
111
+ taskId: string;
112
+ launchNonce: string;
113
+ sessionId?: string | undefined;
114
+ childSessionId: string;
115
+ childSessionDir: string;
116
+ extensionMode: DelegateExtensionMode;
117
+ route: DelegatePinnedRoute;
118
+ limits: DelegateLimits;
119
+ seedSha256: string;
120
+ now?: () => Date;
121
+ }
122
+
123
+ export class DelegateArtifactStore {
124
+ private readonly rootAbs: string;
125
+ private readonly rootDisplay: string;
126
+ private readonly spillAbs: string;
127
+ private readonly now: () => Date;
128
+ private manifest: DelegateManifestV1;
129
+ private writeChain: Promise<void> = Promise.resolve();
130
+ private totalSpilledBytes = 0;
131
+
132
+ private constructor(
133
+ rootAbs: string,
134
+ rootDisplay: string,
135
+ now: () => Date,
136
+ manifest: DelegateManifestV1,
137
+ ) {
138
+ this.rootAbs = rootAbs;
139
+ this.rootDisplay = rootDisplay;
140
+ this.spillAbs = join(rootAbs, DELEGATE_SPILL_DIRNAME);
141
+ this.now = now;
142
+ this.manifest = manifest;
143
+ }
144
+
145
+ /**
146
+ * Create the artifact root with exclusive semantics.
147
+ *
148
+ * The directory name embeds the task id, which is cryptographically random, so
149
+ * two delegates launched in the same assistant message cannot collide. The
150
+ * directory is created with `recursive: false` so a pre-existing directory is
151
+ * a loud failure rather than a silent reuse.
152
+ */
153
+ static async create(
154
+ options: CreateDelegateArtifactStoreOptions,
155
+ ): Promise<DelegateArtifactStore> {
156
+ const sessionSegment = sanitizePathSegment(
157
+ options.sessionId ?? `session-${String(process.pid)}`,
158
+ );
159
+ // USER DECISION (2026-08-21): durable delegate artifacts live under the
160
+ // workspace .unipi/ dir (our convention), not .pi/ and not tmp.
161
+ const runDirName = `${sessionSegment}-${String(process.pid)}`;
162
+ const parentAbs = join(options.cwd, '.unipi', 'delegate', runDirName);
163
+ const rootAbs = join(parentAbs, options.taskId);
164
+ const rootDisplay = join('.unipi', 'delegate', runDirName, options.taskId);
165
+ try {
166
+ await mkdir(parentAbs, { recursive: true, mode: 0o700 });
167
+ await mkdir(rootAbs, { recursive: false, mode: 0o700 });
168
+ await chmod(rootAbs, 0o700);
169
+ await mkdir(join(rootAbs, DELEGATE_SPILL_DIRNAME), { recursive: false, mode: 0o700 });
170
+ } catch (error) {
171
+ throw artifactError(`could not create delegate artifact directory ${rootDisplay}`, error);
172
+ }
173
+ const timestamp = (options.now ?? (() => new Date()))().toISOString();
174
+ const manifest: DelegateManifestV1 = {
175
+ schema_version: DELEGATE_MANIFEST_SCHEMA_VERSION,
176
+ task_id: options.taskId,
177
+ launch_nonce: options.launchNonce,
178
+ created_at: timestamp,
179
+ updated_at: timestamp,
180
+ cwd: options.cwd,
181
+ child_session_id: options.childSessionId,
182
+ child_session_dir: options.childSessionDir,
183
+ extension_mode: options.extensionMode,
184
+ route: options.route,
185
+ limits: options.limits,
186
+ seed_sha256: options.seedSha256,
187
+ state: 'launched',
188
+ artifacts: {},
189
+ };
190
+ const store = new DelegateArtifactStore(
191
+ rootAbs,
192
+ rootDisplay,
193
+ options.now ?? (() => new Date()),
194
+ manifest,
195
+ );
196
+ await store.persistManifest();
197
+ return store;
198
+ }
199
+
200
+ get artifactDir(): string {
201
+ return this.rootDisplay;
202
+ }
203
+
204
+ get artifactDirAbs(): string {
205
+ return this.rootAbs;
206
+ }
207
+
208
+ get spillDirAbs(): string {
209
+ return this.spillAbs;
210
+ }
211
+
212
+ get resultPathAbs(): string {
213
+ return join(this.rootAbs, DELEGATE_ARTIFACT_NAMES.result);
214
+ }
215
+
216
+ snapshot(): DelegateManifestV1 {
217
+ return { ...this.manifest, artifacts: { ...this.manifest.artifacts } };
218
+ }
219
+
220
+ async writeSeed(serialized: string): Promise<DelegateArtifactRef> {
221
+ return this.write(DELEGATE_ARTIFACT_NAMES.seed, serialized);
222
+ }
223
+
224
+ /** Persist the exact prompt bytes handed to the child over stdin. */
225
+ async writeChildPrompt(bytes: Buffer): Promise<DelegateArtifactRef> {
226
+ return this.write(DELEGATE_ARTIFACT_NAMES.childPrompt, bytes);
227
+ }
228
+
229
+ async writeLedger(ledger: unknown): Promise<DelegateArtifactRef> {
230
+ return this.write(DELEGATE_ARTIFACT_NAMES.ledger, `${canonicalJson(ledger)}\n`);
231
+ }
232
+
233
+ async writeBudgetPlan(plan: DelegateAdmissionPlanV1): Promise<DelegateArtifactRef> {
234
+ return this.write(DELEGATE_ARTIFACT_NAMES.budgetPlan, `${canonicalJson(plan)}\n`);
235
+ }
236
+
237
+ /** Commit the run. The rename performed here is the single success point. */
238
+ async commitResult(pkg: DelegateResultPackageV1): Promise<DelegateArtifactRef> {
239
+ const ref = await this.write(
240
+ DELEGATE_ARTIFACT_NAMES.result,
241
+ serializeDelegateResultPackage(pkg),
242
+ );
243
+ await this.setState('committed');
244
+ return ref;
245
+ }
246
+
247
+ async readCommittedResult(): Promise<string> {
248
+ try {
249
+ return await readFile(this.resultPathAbs, 'utf8');
250
+ } catch (error) {
251
+ const diagnosticNames = [
252
+ DELEGATE_ARTIFACT_NAMES.error,
253
+ DELEGATE_ARTIFACT_NAMES.outcome,
254
+ DELEGATE_ARTIFACT_NAMES.runtimeBudget,
255
+ DELEGATE_ARTIFACT_NAMES.manifest,
256
+ ].filter((name) => existsSync(join(this.rootAbs, name)));
257
+ throw new DelegateError(
258
+ `delegate result package could not be read at ${join(this.rootDisplay, DELEGATE_ARTIFACT_NAMES.result)}; no committed answer is available (${error instanceof Error ? error.message : String(error)})`,
259
+ {
260
+ code: 'result_unavailable',
261
+ childCreated: true,
262
+ taskId: this.manifest.task_id,
263
+ artifactDir: this.rootDisplay,
264
+ preserved: diagnosticNames,
265
+ remediation: diagnosticNames.length === 0
266
+ ? ['No diagnostic control artifact exists; inspect the background task merged output if one was created.']
267
+ : [`Inspect the existing delegate control artifacts: ${diagnosticNames.join(', ')}.`],
268
+ },
269
+ );
270
+ }
271
+ }
272
+
273
+ async writeError(state: 'failed' | 'cancelled', message: string): Promise<void> {
274
+ await this.write(
275
+ DELEGATE_ARTIFACT_NAMES.error,
276
+ `${canonicalJson({ state, error: message })}\n`,
277
+ );
278
+ await this.setState(state, message);
279
+ }
280
+
281
+ async setState(state: DelegateManifestState, error?: string): Promise<void> {
282
+ await this.update((manifest) => {
283
+ manifest.state = state;
284
+ if (error !== undefined) manifest.error = error;
285
+ });
286
+ }
287
+
288
+ /**
289
+ * Spill one oversized tool payload.
290
+ *
291
+ * The filename encodes `(turnSequence, sourceCallIndex, toolCallId)` assigned
292
+ * before the tool executed, so a receipt can never be associated with the
293
+ * wrong call when parallel results complete out of order.
294
+ *
295
+ * A spill that cannot be committed is a terminal failure. The original payload
296
+ * is never returned as a fallback and no receipt is emitted for a file that
297
+ * was not committed.
298
+ */
299
+ async spillToolPayload(input: {
300
+ toolName: string;
301
+ toolCallId: string;
302
+ turnSequence: number;
303
+ sourceCallIndex: number;
304
+ payload: Buffer;
305
+ maxTotalBytes: number;
306
+ }): Promise<DelegateSpillReceipt> {
307
+ const nextTotal = this.totalSpilledBytes + input.payload.length;
308
+ if (nextTotal > input.maxTotalBytes) {
309
+ throw new DelegateError(
310
+ `delegate aggregate tool output would reach ${String(nextTotal)} bytes, exceeding the ${String(input.maxTotalBytes)}-byte cap for one run`,
311
+ {
312
+ code: 'aggregate_tool_output_cap',
313
+ childCreated: true,
314
+ taskId: this.manifest.task_id,
315
+ artifactDir: this.rootDisplay,
316
+ preserved: [this.rootDisplay],
317
+ remediation: [
318
+ 'The delegate read more tool output than one run is allowed to accumulate. Narrow the investigation prompt or raise the cap deliberately.',
319
+ ],
320
+ },
321
+ );
322
+ }
323
+ const safeCallId = sanitizePathSegment(input.toolCallId).slice(0, 64);
324
+ const name = `t${String(input.turnSequence).padStart(4, '0')}-c${String(
325
+ input.sourceCallIndex,
326
+ ).padStart(4, '0')}-${safeCallId}.bin`;
327
+ const absPath = join(this.spillAbs, name);
328
+ if (!pathInside(this.spillAbs, absPath)) {
329
+ throw artifactError(`delegate spill path escapes the artifact directory: ${name}`);
330
+ }
331
+ try {
332
+ await this.durableReplace(absPath, input.payload);
333
+ } catch (error) {
334
+ throw new DelegateError(
335
+ `delegate could not durably spill a ${String(input.payload.length)}-byte tool result; the payload is not forwarded and no receipt is emitted`,
336
+ {
337
+ code: 'artifact_spill_failed',
338
+ childCreated: true,
339
+ taskId: this.manifest.task_id,
340
+ artifactDir: this.rootDisplay,
341
+ preserved: [this.rootDisplay],
342
+ remediation: [
343
+ `Underlying cause: ${error instanceof Error ? error.message : String(error)}`,
344
+ 'Check free disk space and permissions on the delegate artifact directory.',
345
+ ],
346
+ },
347
+ );
348
+ }
349
+ this.totalSpilledBytes = nextTotal;
350
+ return {
351
+ schema_version: DELEGATE_RECEIPT_SCHEMA_VERSION,
352
+ artifact: join(DELEGATE_SPILL_DIRNAME, name),
353
+ tool_name: input.toolName,
354
+ tool_call_id: input.toolCallId,
355
+ turn_sequence: input.turnSequence,
356
+ source_call_index: input.sourceCallIndex,
357
+ byte_length: input.payload.length,
358
+ sha256: sha256Bytes(input.payload),
359
+ content_format: 'opaque_bytes',
360
+ };
361
+ }
362
+
363
+ /**
364
+ * Read an exact byte range from a spilled artifact.
365
+ *
366
+ * Returns exactly the requested range or fails. It never returns a shorter
367
+ * range than requested, and it never clamps the request to what happens to be
368
+ * available: a request past end-of-file is a loud error naming the real size.
369
+ */
370
+ async readSpillRange(
371
+ relativePath: string,
372
+ offset: number,
373
+ length: number,
374
+ ): Promise<{ bytes: Buffer; totalBytes: number }> {
375
+ if (!Number.isSafeInteger(offset) || offset < 0)
376
+ throw this.readFailure(relativePath, 'offset must be a non-negative integer');
377
+ if (!Number.isSafeInteger(length) || length <= 0)
378
+ throw this.readFailure(relativePath, 'length must be a positive integer');
379
+ const absPath = join(this.rootAbs, relativePath);
380
+ if (!pathInside(this.rootAbs, absPath))
381
+ throw this.readFailure(relativePath, 'path escapes the delegate artifact directory');
382
+ let handle: Awaited<ReturnType<typeof open>>;
383
+ try {
384
+ handle = await open(absPath, 'r');
385
+ } catch (error) {
386
+ throw this.readFailure(
387
+ relativePath,
388
+ `cannot open artifact: ${error instanceof Error ? error.message : String(error)}`,
389
+ );
390
+ }
391
+ try {
392
+ const stats = await handle.stat();
393
+ const totalBytes = stats.size;
394
+ if (offset + length > totalBytes) {
395
+ throw this.readFailure(
396
+ relativePath,
397
+ `requested bytes ${String(offset)}..${String(offset + length)} exceed the artifact size of ${String(totalBytes)} bytes; the read is refused rather than silently shortened`,
398
+ );
399
+ }
400
+ const buffer = Buffer.alloc(length);
401
+ const { bytesRead } = await handle.read(buffer, 0, length, offset);
402
+ if (bytesRead !== length) {
403
+ throw this.readFailure(
404
+ relativePath,
405
+ `read returned ${String(bytesRead)} of ${String(length)} requested bytes`,
406
+ );
407
+ }
408
+ return { bytes: buffer, totalBytes };
409
+ } finally {
410
+ await handle.close();
411
+ }
412
+ }
413
+
414
+ private readFailure(relativePath: string, reason: string): DelegateError {
415
+ return new DelegateError(`delegate artifact read failed for ${relativePath}: ${reason}`, {
416
+ code: 'artifact_read_failed',
417
+ childCreated: true,
418
+ taskId: this.manifest.task_id,
419
+ artifactDir: this.rootDisplay,
420
+ });
421
+ }
422
+
423
+ private async durableReplace(absPath: string, data: Buffer | string): Promise<void> {
424
+ await replaceFileDurable(absPath, data);
425
+ }
426
+
427
+ private async write(name: string, data: Buffer | string): Promise<DelegateArtifactRef> {
428
+ const absPath = join(this.rootAbs, name);
429
+ if (name.length === 0 || name.includes('/') || name.includes('\\'))
430
+ throw artifactError(`invalid delegate artifact name: ${name}`);
431
+ if (!pathInside(this.rootAbs, absPath))
432
+ throw artifactError(`delegate artifact path escapes the run directory: ${name}`);
433
+ const bytes = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8');
434
+ try {
435
+ await this.durableReplace(absPath, data);
436
+ } catch (error) {
437
+ throw artifactError(`could not durably write delegate artifact ${name}`, error);
438
+ }
439
+ const ref: DelegateArtifactRef = {
440
+ path: basename(absPath),
441
+ byte_length: bytes.length,
442
+ sha256: sha256Bytes(bytes),
443
+ };
444
+ await this.update((manifest) => {
445
+ manifest.artifacts = { ...manifest.artifacts, [name]: ref };
446
+ });
447
+ return ref;
448
+ }
449
+
450
+ private async persistManifest(): Promise<void> {
451
+ const absPath = join(this.rootAbs, DELEGATE_ARTIFACT_NAMES.manifest);
452
+ try {
453
+ await this.durableReplace(absPath, `${canonicalJson(this.snapshot())}\n`);
454
+ } catch (error) {
455
+ throw artifactError('could not durably write the delegate manifest', error);
456
+ }
457
+ }
458
+
459
+ private async update(mutator: (manifest: DelegateManifestV1) => void): Promise<void> {
460
+ const apply = async () => {
461
+ mutator(this.manifest);
462
+ this.manifest.updated_at = this.now().toISOString();
463
+ await this.persistManifest();
464
+ };
465
+ const next = this.writeChain.then(apply, apply);
466
+ this.writeChain = next.catch(() => undefined);
467
+ await next;
468
+ }
469
+ }
470
+
471
+ /** Best-effort removal of an artifact root that must not be left half-created. */
472
+ export async function discardDelegateArtifactRoot(rootAbs: string): Promise<void> {
473
+ await rm(rootAbs, { recursive: true, force: true });
474
+ }
475
+
476
+ /** Exposed so tests can prove control artifacts are written durably, not streamed. */
477
+ export async function writeDelegateArtifactDirect(
478
+ absPath: string,
479
+ data: Buffer | string,
480
+ ): Promise<void> {
481
+ await writeFileDurable(absPath, data);
482
+ }
483
+
484
+ /** Exposed for recovery flows that must rename a staged package into place. */
485
+ export async function renameIntoPlace(source: string, target: string): Promise<void> {
486
+ await rename(source, target);
487
+ }