@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,449 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { canonicalJson } from '../attested-pi-run.js';
4
+ import { replaceFileDurable } from '../durable-fs.js';
5
+ import { resolveAnthropicAttributionExtensionPath } from '../anthropic-attribution-path.js';
6
+ import { join } from 'node:path';
7
+ import { DelegateArtifactStore, discardDelegateArtifactRoot } from './artifacts.js';
8
+ import {
9
+ buildDelegateChildArgv,
10
+ delegateChildEnv,
11
+ ensureDelegateChildSessionDir,
12
+ preflightDelegateLaunch,
13
+ resolveDelegateChildExtensionPath,
14
+ type DelegatePreflightInput,
15
+ type DelegatePreflightResult,
16
+ } from './launch.js';
17
+ import {
18
+ DELEGATE_INLINE_ANSWER_BYTES,
19
+ } from './budget.js';
20
+ import { verifyDelegateResultPackage, type VerifiedDelegateResult } from './result-package.js';
21
+ import {
22
+ DelegateError,
23
+ type DelegateAutoDeliverMode,
24
+ type DelegateExtensionMode,
25
+ type DelegateResultPackageV1,
26
+ } from './types.js';
27
+ import type { DelegateTaskFacts, DelegateTaskOutcome } from '../types.js';
28
+
29
+ /**
30
+ * Delegate launch preparation and terminal evaluation.
31
+ *
32
+ * Separated from the background-task registry so the ordering property that
33
+ * matters most — preflight refusals create nothing — is testable without
34
+ * spawning anything.
35
+ */
36
+
37
+ export interface PreparedDelegateLaunch {
38
+ preflight: DelegatePreflightResult;
39
+ store: DelegateArtifactStore;
40
+ argv: readonly string[];
41
+ env: NodeJS.ProcessEnv;
42
+ facts: DelegateTaskFacts;
43
+ childSessionDirAbs: string;
44
+ seedPathAbs: string;
45
+ /** Exact prompt bytes delivered to the child over stdin. */
46
+ stdinBytes: Buffer;
47
+ }
48
+
49
+ export interface PrepareDelegateLaunchInput extends DelegatePreflightInput {
50
+ cwd: string;
51
+ sessionId: string | undefined;
52
+ autoDeliver: DelegateAutoDeliverMode;
53
+ extensionMode: DelegateExtensionMode;
54
+ childExtensionPath?: string | undefined;
55
+ attributionExtensionPath?: string | undefined;
56
+ env?: NodeJS.ProcessEnv | undefined;
57
+ now?: (() => Date) | undefined;
58
+ }
59
+
60
+ /**
61
+ * Prepare a delegate launch.
62
+ *
63
+ * Preflight runs first and completes entirely before the artifact directory is
64
+ * created, so every admission refusal leaves zero children AND zero artifacts.
65
+ * When a step after directory creation fails, the partially created directory
66
+ * is removed, so a refused launch never leaves a half-formed run behind.
67
+ */
68
+ export async function prepareDelegateLaunch(
69
+ input: PrepareDelegateLaunchInput,
70
+ ): Promise<PreparedDelegateLaunch> {
71
+ // Resolve the guard extension before anything is created: a package missing
72
+ // its child guard must refuse rather than spawn an unguarded child.
73
+ const childExtensionPath =
74
+ input.childExtensionPath ?? resolveDelegateChildExtensionPath();
75
+ let attributionExtensionPath: string | undefined;
76
+ if (input.route.provider === 'anthropic') {
77
+ try {
78
+ attributionExtensionPath =
79
+ input.attributionExtensionPath ?? resolveAnthropicAttributionExtensionPath();
80
+ } catch (error) {
81
+ throw new DelegateError(
82
+ `Anthropic delegate attribution extension could not be resolved: ${error instanceof Error ? error.message : String(error)}`,
83
+ {
84
+ code: 'delegate_isolation_unsupported',
85
+ childCreated: false,
86
+ remediation: ['Reinstall the package; Anthropic delegates require attribution.'],
87
+ },
88
+ );
89
+ }
90
+ }
91
+
92
+ const preflight = preflightDelegateLaunch(input);
93
+
94
+ const store = await DelegateArtifactStore.create({
95
+ cwd: input.cwd,
96
+ taskId: preflight.taskId,
97
+ launchNonce: preflight.launchNonce,
98
+ sessionId: input.sessionId,
99
+ childSessionId: preflight.childSessionId,
100
+ childSessionDir: '',
101
+ extensionMode: input.extensionMode,
102
+ route: input.route,
103
+ limits: preflight.limits,
104
+ seedSha256: preflight.seed.sha256,
105
+ ...(input.now === undefined ? {} : { now: input.now }),
106
+ });
107
+
108
+ try {
109
+ const seedRef = await store.writeSeed(preflight.seed.serialized);
110
+ // The persisted seed bytes are the bytes the child reads. Nothing
111
+ // re-serializes them between here and the child, and the child verifies the
112
+ // hash before its first model call.
113
+ if (seedRef.sha256 !== preflight.seed.sha256) {
114
+ throw new DelegateError(
115
+ 'delegate seed hash changed between construction and persistence',
116
+ {
117
+ code: 'seed_persist_failed',
118
+ childCreated: false,
119
+ taskId: preflight.taskId,
120
+ artifactDir: store.artifactDir,
121
+ },
122
+ );
123
+ }
124
+ await store.writeLedger(preflight.seed.ledger);
125
+ await store.writeBudgetPlan(preflight.plan);
126
+ const childSessionDirAbs = await ensureDelegateChildSessionDir(store.artifactDirAbs);
127
+ const seedPathAbs = join(store.artifactDirAbs, 'seed.json');
128
+ const argv = buildDelegateChildArgv({
129
+ route: input.route,
130
+ capability: input.capability,
131
+ extensionMode: input.extensionMode,
132
+ childSessionId: preflight.childSessionId,
133
+ childSessionDir: childSessionDirAbs,
134
+ childExtensionPath,
135
+ attributionExtensionPath,
136
+ systemPrompt: preflight.childSystemPrompt,
137
+ });
138
+ const env = delegateChildEnv(
139
+ {
140
+ artifactDirAbs: store.artifactDirAbs,
141
+ seedPathAbs,
142
+ seedSha256: preflight.seed.sha256,
143
+ taskId: preflight.taskId,
144
+ launchNonce: preflight.launchNonce,
145
+ },
146
+ input.env ?? process.env,
147
+ );
148
+ const facts: DelegateTaskFacts = {
149
+ taskId: preflight.taskId,
150
+ launchNonce: preflight.launchNonce,
151
+ artifactDir: store.artifactDir,
152
+ artifactDirAbs: store.artifactDirAbs,
153
+ seedSha256: preflight.seed.sha256,
154
+ childSessionId: preflight.childSessionId,
155
+ route: {
156
+ provider: input.route.provider,
157
+ model: input.route.model,
158
+ qualifiedId: input.route.qualified_id,
159
+ },
160
+ budget: {
161
+ family: preflight.plan.route.family,
162
+ rate_source: preflight.plan.route.rate_source,
163
+ conservative_rate_source: preflight.plan.conservative_estimate.rateSource,
164
+ },
165
+ extensionMode: input.extensionMode,
166
+ autoDeliver: input.autoDeliver,
167
+ };
168
+ const stdinBytes = Buffer.from(preflight.childPrompt, 'utf8');
169
+ // The persisted prompt bytes must equal the bytes sent to the child, so the
170
+ // artifact is evidence of what the child actually received.
171
+ await store.writeChildPrompt(stdinBytes);
172
+ return {
173
+ preflight,
174
+ store,
175
+ argv,
176
+ env,
177
+ facts,
178
+ childSessionDirAbs,
179
+ seedPathAbs,
180
+ stdinBytes,
181
+ };
182
+ } catch (error) {
183
+ // A failure after directory creation must not leave a half-formed run.
184
+ await discardDelegateArtifactRoot(store.artifactDirAbs);
185
+ throw error;
186
+ }
187
+ }
188
+
189
+ export interface DelegateTerminalEvaluation {
190
+ outcome: DelegateTaskOutcome;
191
+ result?: VerifiedDelegateResult | undefined;
192
+ error?: DelegateError | undefined;
193
+ }
194
+
195
+ export interface EvaluateDelegateTerminalInput {
196
+ artifactDirAbs: string;
197
+ taskId: string;
198
+ launchNonce: string;
199
+ seedSha256: string;
200
+ route: { provider: string; model: string };
201
+ /** Terminal status observed by the background task registry. */
202
+ taskStatus: 'completed' | 'failed' | 'killed';
203
+ taskError: string | undefined;
204
+ /** Real merged child output owned by the background-task registry. */
205
+ taskOutputPath?: string | undefined;
206
+ taskOutputAbsPath?: string | undefined;
207
+ }
208
+
209
+ /**
210
+ * Evaluate a finished delegate child.
211
+ *
212
+ * The committed result package is the sole answer data plane. Its presence under
213
+ * its final name is the success signal; its absence means no answer was
214
+ * accepted, whatever the process exit code happened to be. A child that exits 0
215
+ * without committing is a typed `child_exited_without_commit`, never a silent
216
+ * empty success.
217
+ */
218
+ export async function evaluateDelegateTerminal(
219
+ input: EvaluateDelegateTerminalInput,
220
+ ): Promise<DelegateTerminalEvaluation> {
221
+ const evaluation = await adjudicateDelegateTerminal(input);
222
+ // Record the parent's adjudicated view separately from the child-written
223
+ // result package, so neither writer can overwrite the other's claim.
224
+ try {
225
+ await replaceFileDurable(
226
+ join(input.artifactDirAbs, 'outcome.json'),
227
+ `${canonicalJson({
228
+ schema_version: 'pi-background-tasks.delegate-outcome.v1',
229
+ task_id: input.taskId,
230
+ launch_nonce: input.launchNonce,
231
+ observed_task_status: input.taskStatus,
232
+ outcome: evaluation.outcome,
233
+ error_code: evaluation.error?.code ?? null,
234
+ })}\n`,
235
+ );
236
+ } catch {
237
+ // Failing to record the adjudication must not change the adjudication
238
+ // itself, which is returned to the caller either way.
239
+ }
240
+ return evaluation;
241
+ }
242
+
243
+ async function adjudicateDelegateTerminal(
244
+ input: EvaluateDelegateTerminalInput,
245
+ ): Promise<DelegateTerminalEvaluation> {
246
+ const resultPath = join(input.artifactDirAbs, 'result.json');
247
+ const terminalPath = join(input.artifactDirAbs, 'child-terminal.json');
248
+ if (!existsSync(resultPath)) {
249
+ const recorded = existsSync(terminalPath)
250
+ ? await readChildTerminal(terminalPath)
251
+ : undefined;
252
+ const cancelled = input.taskStatus === 'killed';
253
+ const code = recorded?.code ?? (cancelled ? 'child_cancelled' : 'child_exited_without_commit');
254
+ const detail =
255
+ recorded?.message ??
256
+ input.taskError ??
257
+ 'the delegate child exited without committing a result package';
258
+ const preserved = ['seed.json', 'budget-plan.json', 'child-terminal.json', 'runtime-budget.json']
259
+ .filter((name) => existsSync(join(input.artifactDirAbs, name)));
260
+ if (
261
+ input.taskOutputPath !== undefined &&
262
+ input.taskOutputAbsPath !== undefined &&
263
+ existsSync(input.taskOutputAbsPath)
264
+ ) {
265
+ preserved.push(input.taskOutputPath);
266
+ }
267
+ const diagnosticTargets = preserved.filter(
268
+ (name) => name === 'child-terminal.json' || name === 'runtime-budget.json' || name === input.taskOutputPath,
269
+ );
270
+ const diagnostic = diagnosticTargets.length === 0
271
+ ? 'No child terminal record or merged task output exists; inspect the preserved launch artifacts listed above.'
272
+ : `Inspect the preserved diagnostic evidence: ${diagnosticTargets.join(', ')}.`;
273
+ const error = new DelegateError(
274
+ `bg_delegate produced no committed answer: ${detail}`,
275
+ {
276
+ code: isDelegateErrorCode(code) ? code : 'child_exited_without_commit',
277
+ childCreated: true,
278
+ taskId: input.taskId,
279
+ artifactDir: input.artifactDirAbs,
280
+ preserved,
281
+ remediation: [
282
+ diagnostic,
283
+ 'No partial answer is returned; nothing was truncated to look like success.',
284
+ ],
285
+ },
286
+ );
287
+ const outcome: DelegateTaskOutcome = {
288
+ status: cancelled ? 'cancelled' : 'failed',
289
+ errorCode: error.code,
290
+ };
291
+ return { outcome, error };
292
+ }
293
+
294
+ let raw: string;
295
+ try {
296
+ raw = await readFile(resultPath, 'utf8');
297
+ } catch (error) {
298
+ const failure = new DelegateError(
299
+ `bg_delegate could not read its committed result package: ${error instanceof Error ? error.message : String(error)}`,
300
+ {
301
+ code: 'artifact_read_failed',
302
+ childCreated: true,
303
+ taskId: input.taskId,
304
+ artifactDir: input.artifactDirAbs,
305
+ },
306
+ );
307
+ return { outcome: { status: 'failed', errorCode: failure.code }, error: failure };
308
+ }
309
+
310
+ try {
311
+ const verified = verifyDelegateResultPackage(raw, {
312
+ taskId: input.taskId,
313
+ launchNonce: input.launchNonce,
314
+ seedSha256: input.seedSha256,
315
+ route: input.route,
316
+ });
317
+ return {
318
+ outcome: {
319
+ status: 'committed',
320
+ answerBytes: verified.package.answer.byte_length,
321
+ answerSha256: verified.package.answer.sha256,
322
+ turns: verified.package.turns,
323
+ toolCalls: verified.package.tool_calls,
324
+ },
325
+ result: verified,
326
+ };
327
+ } catch (error) {
328
+ if (error instanceof DelegateError) {
329
+ return { outcome: { status: 'failed', errorCode: error.code }, error };
330
+ }
331
+ throw error;
332
+ }
333
+ }
334
+
335
+ interface ChildTerminalRecord {
336
+ code: string;
337
+ message: string;
338
+ }
339
+
340
+ async function readChildTerminal(path: string): Promise<ChildTerminalRecord | undefined> {
341
+ try {
342
+ const parsed: unknown = JSON.parse(await readFile(path, 'utf8'));
343
+ if (typeof parsed !== 'object' || parsed === null) return undefined;
344
+ const code: unknown = Reflect.get(parsed, 'code');
345
+ const message: unknown = Reflect.get(parsed, 'message');
346
+ if (typeof code !== 'string' || typeof message !== 'string') return undefined;
347
+ return { code, message };
348
+ } catch {
349
+ // A missing or malformed child-terminal record must not mask the primary
350
+ // "no committed answer" failure, which is reported by the caller either way.
351
+ return undefined;
352
+ }
353
+ }
354
+
355
+ const DELEGATE_ERROR_CODE_SET = new Set<string>([
356
+ 'delegate_hook_contract_unsupported',
357
+ 'delegate_isolation_unsupported',
358
+ 'route_unresolved',
359
+ 'route_capacity_unknown',
360
+ 'seed_projection_failed',
361
+ 'seed_budget_exceeded',
362
+ 'seed_persist_failed',
363
+ 'invalid_arguments',
364
+ 'child_spawn_failed',
365
+ 'child_startup_failed',
366
+ 'child_timeout',
367
+ 'child_cancelled',
368
+ 'child_turn_limit',
369
+ 'child_tool_call_limit',
370
+ 'child_exited_without_commit',
371
+ 'provider_context_budget_exhausted',
372
+ 'aggregate_tool_output_cap',
373
+ 'child_model_output_limit',
374
+ 'child_capture_limit',
375
+ 'child_result_invalid',
376
+ 'child_result_encoding_invalid',
377
+ 'route_attestation_missing',
378
+ 'route_mismatch',
379
+ 'seed_hash_mismatch',
380
+ 'answer_hash_mismatch',
381
+ 'artifact_spill_failed',
382
+ 'artifact_read_failed',
383
+ 'artifact_error',
384
+ 'result_not_ready',
385
+ 'result_unavailable',
386
+ 'result_too_large_for_inline',
387
+ 'task_unknown',
388
+ ]);
389
+
390
+ function isDelegateErrorCode(value: string): value is DelegateError['code'] {
391
+ return DELEGATE_ERROR_CODE_SET.has(value);
392
+ }
393
+
394
+ export interface DelegateInlineDecision {
395
+ mode: 'inline' | 'artifact';
396
+ reason: string;
397
+ }
398
+
399
+ /**
400
+ * Decide inline versus artifact delivery.
401
+ *
402
+ * The cap is applied to the exact serialized answer bytes. An answer over the
403
+ * cap degrades to an artifact reference explicitly and is never shortened to
404
+ * fit.
405
+ */
406
+ export function decideDelegateDelivery(
407
+ answerBytes: number,
408
+ requested: 'inline' | 'artifact' | undefined,
409
+ cap = DELEGATE_INLINE_ANSWER_BYTES,
410
+ ): DelegateInlineDecision {
411
+ if (requested === 'artifact') {
412
+ return { mode: 'artifact', reason: 'artifact delivery was requested explicitly' };
413
+ }
414
+ if (answerBytes <= cap) {
415
+ return {
416
+ mode: 'inline',
417
+ reason: `the answer is ${String(answerBytes)} bytes, within the ${String(cap)}-byte inline cap`,
418
+ };
419
+ }
420
+ return {
421
+ mode: 'artifact',
422
+ reason: `the answer is ${String(answerBytes)} bytes, over the ${String(cap)}-byte inline cap`,
423
+ };
424
+ }
425
+
426
+ /** Raised when inline delivery was explicitly requested for an oversized answer. */
427
+ export function inlineTooLarge(
428
+ taskId: string,
429
+ artifactDir: string,
430
+ answerBytes: number,
431
+ cap = DELEGATE_INLINE_ANSWER_BYTES,
432
+ ): DelegateError {
433
+ return new DelegateError(
434
+ `bg_result cannot return this answer inline: it is ${String(answerBytes)} bytes, over the ${String(cap)}-byte inline cap. The complete verified answer is preserved at ${join(artifactDir, 'result.json')}. It is not truncated to fit.`,
435
+ {
436
+ code: 'result_too_large_for_inline',
437
+ childCreated: true,
438
+ taskId,
439
+ artifactDir,
440
+ preserved: [join(artifactDir, 'result.json')],
441
+ remediation: [
442
+ 'Call bg_result with delivery:"artifact" to receive the verified metadata plus the artifact reference.',
443
+ 'Read the answer from the artifact path directly if the full text is required.',
444
+ ],
445
+ },
446
+ );
447
+ }
448
+
449
+ export type { DelegateResultPackageV1 };