pi-background-tasks 2.5.0 → 2.6.0
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.
- package/BACKGROUND-TASKS-INSTRUCTIONS.md +1 -1
- package/README.md +70 -25
- package/TESTING.md +42 -2
- package/TEST_PLAN.md +7 -4
- package/dist/extensions/anthropic-attribution-child.js +4 -0
- package/dist/extensions/anthropic-attribution-child.js.map +1 -0
- package/dist/extensions/anthropic-attribution.js +107 -0
- package/dist/extensions/anthropic-attribution.js.map +1 -0
- package/dist/extensions/background-tasks.js +2 -0
- package/dist/extensions/background-tasks.js.map +1 -0
- package/dist/extensions/delegate-child.js +2 -0
- package/dist/extensions/delegate-child.js.map +1 -0
- package/dist/extensions/fusion-child.js +2 -0
- package/dist/extensions/fusion-child.js.map +1 -0
- package/dist/package.json +5 -0
- package/dist/src/core/anthropic-attribution-path.js +24 -0
- package/dist/src/core/anthropic-attribution-path.js.map +1 -0
- package/dist/src/core/anthropic-attribution.js +2247 -0
- package/dist/src/core/anthropic-attribution.js.map +1 -0
- package/dist/src/core/attested-pi-contract.js +5 -0
- package/dist/src/core/attested-pi-contract.js.map +1 -0
- package/dist/src/core/attested-pi-run.js +749 -0
- package/dist/src/core/attested-pi-run.js.map +1 -0
- package/dist/src/core/canonical-json.js +19 -0
- package/dist/src/core/canonical-json.js.map +1 -0
- package/dist/src/core/common.js +787 -0
- package/dist/src/core/common.js.map +1 -0
- package/dist/src/core/config.js +78 -0
- package/dist/src/core/config.js.map +1 -0
- package/dist/src/core/context/parent-snapshot.js +75 -0
- package/dist/src/core/context/parent-snapshot.js.map +1 -0
- package/dist/src/core/context/token-budget.js +631 -0
- package/dist/src/core/context/token-budget.js.map +1 -0
- package/dist/src/core/context/visible-conversation-v2.js +390 -0
- package/dist/src/core/context/visible-conversation-v2.js.map +1 -0
- package/dist/src/core/delegate/artifacts.js +357 -0
- package/dist/src/core/delegate/artifacts.js.map +1 -0
- package/dist/src/core/delegate/budget.js +266 -0
- package/dist/src/core/delegate/budget.js.map +1 -0
- package/dist/src/core/delegate/facade-contract.js +7 -0
- package/dist/src/core/delegate/facade-contract.js.map +1 -0
- package/dist/src/core/delegate/hook-contract-evidence.json +18 -0
- package/dist/src/core/delegate/hook-contract.js +124 -0
- package/dist/src/core/delegate/hook-contract.js.map +1 -0
- package/dist/src/core/delegate/launch.js +366 -0
- package/dist/src/core/delegate/launch.js.map +1 -0
- package/dist/src/core/delegate/result-package.js +293 -0
- package/dist/src/core/delegate/result-package.js.map +1 -0
- package/dist/src/core/delegate/runner.js +398 -0
- package/dist/src/core/delegate/runner.js.map +1 -0
- package/dist/src/core/delegate/seed.js +334 -0
- package/dist/src/core/delegate/seed.js.map +1 -0
- package/dist/src/core/delegate/types.js +103 -0
- package/dist/src/core/delegate/types.js.map +1 -0
- package/dist/src/core/durable-fs.js +372 -0
- package/dist/src/core/durable-fs.js.map +1 -0
- package/dist/src/core/extension-api.js +382 -0
- package/dist/src/core/extension-api.js.map +1 -0
- package/dist/src/core/fusion/artifacts.js +654 -0
- package/dist/src/core/fusion/artifacts.js.map +1 -0
- package/dist/src/core/fusion/budget.js +949 -0
- package/dist/src/core/fusion/budget.js.map +1 -0
- package/dist/src/core/fusion/child-protocol.js +176 -0
- package/dist/src/core/fusion/child-protocol.js.map +1 -0
- package/dist/src/core/fusion/claude-cache.js +156 -0
- package/dist/src/core/fusion/claude-cache.js.map +1 -0
- package/dist/src/core/fusion/clean-context.js +64 -0
- package/dist/src/core/fusion/clean-context.js.map +1 -0
- package/dist/src/core/fusion/config.js +349 -0
- package/dist/src/core/fusion/config.js.map +1 -0
- package/dist/src/core/fusion/context.js +184 -0
- package/dist/src/core/fusion/context.js.map +1 -0
- package/dist/src/core/fusion/evaluation.js +696 -0
- package/dist/src/core/fusion/evaluation.js.map +1 -0
- package/dist/src/core/fusion/facade-contract.js +3 -0
- package/dist/src/core/fusion/facade-contract.js.map +1 -0
- package/dist/src/core/fusion/orchestrator.js +867 -0
- package/dist/src/core/fusion/orchestrator.js.map +1 -0
- package/dist/src/core/fusion/output-contract.js +27 -0
- package/dist/src/core/fusion/output-contract.js.map +1 -0
- package/dist/src/core/fusion/pi-child.js +1741 -0
- package/dist/src/core/fusion/pi-child.js.map +1 -0
- package/dist/src/core/fusion/prompts.js +260 -0
- package/dist/src/core/fusion/prompts.js.map +1 -0
- package/dist/src/core/fusion/result-package.js +857 -0
- package/dist/src/core/fusion/result-package.js.map +1 -0
- package/dist/src/core/fusion/source-policy.js +259 -0
- package/dist/src/core/fusion/source-policy.js.map +1 -0
- package/dist/src/core/fusion/types.js +207 -0
- package/dist/src/core/fusion/types.js.map +1 -0
- package/dist/src/core/fusion/web-fetch.js +777 -0
- package/dist/src/core/fusion/web-fetch.js.map +1 -0
- package/dist/src/core/fusion/workflows.js +126 -0
- package/dist/src/core/fusion/workflows.js.map +1 -0
- package/dist/src/core/lazy-module.js +181 -0
- package/dist/src/core/lazy-module.js.map +1 -0
- package/dist/src/core/pi-launch.js +431 -0
- package/dist/src/core/pi-launch.js.map +1 -0
- package/dist/src/core/registry.js +3331 -0
- package/dist/src/core/registry.js.map +1 -0
- package/dist/src/core/reload-shell-owner.js +1396 -0
- package/dist/src/core/reload-shell-owner.js.map +1 -0
- package/dist/src/core/shell-policy.js +80 -0
- package/dist/src/core/shell-policy.js.map +1 -0
- package/dist/src/core/task-durable.js +51 -0
- package/dist/src/core/task-durable.js.map +1 -0
- package/dist/src/core/update-check.js +92 -0
- package/dist/src/core/update-check.js.map +1 -0
- package/dist/src/core/windows-taskkill.js +185 -0
- package/dist/src/core/windows-taskkill.js.map +1 -0
- package/dist/src/delegate-child-extension.js +776 -0
- package/dist/src/delegate-child-extension.js.map +1 -0
- package/dist/src/delegate-extension.js +746 -0
- package/dist/src/delegate-extension.js.map +1 -0
- package/dist/src/extension.js +953 -0
- package/dist/src/extension.js.map +1 -0
- package/dist/src/fusion-child-extension.js +760 -0
- package/dist/src/fusion-child-extension.js.map +1 -0
- package/dist/src/fusion-extension.js +1030 -0
- package/dist/src/fusion-extension.js.map +1 -0
- package/dist/src/ui/background-tasks-manager.js +689 -0
- package/dist/src/ui/background-tasks-manager.js.map +1 -0
- package/dist/src/ui/fusion-model-selector.js +277 -0
- package/dist/src/ui/fusion-model-selector.js.map +1 -0
- package/docs/INDEX.md +35 -33
- package/docs/api/eventbus-v1.md +21 -5
- package/docs/choose-a-workflow.md +2 -0
- package/docs/commands/bg-clear.md +3 -3
- package/docs/commands/bg-update.md +3 -3
- package/docs/commands/bg.md +18 -6
- package/docs/commands/claude-cache.md +4 -4
- package/docs/commands/fusion-models.md +49 -4
- package/docs/commands/fusion.md +3 -3
- package/docs/commands/jobs.md +3 -3
- package/docs/commands/kill.md +3 -3
- package/docs/commands/logs.md +3 -3
- package/docs/commands/task-manager.md +5 -5
- package/docs/concepts/completion-delivery.md +6 -2
- package/docs/getting-started.md +7 -1
- package/docs/manifest.json +228 -42
- package/docs/operations/configuration.md +58 -5
- package/docs/operations/releasing.md +4 -2
- package/docs/operations/testing.md +22 -0
- package/docs/operations/troubleshooting.md +6 -2
- package/docs/read-before-edit.md +44 -31
- package/docs/reference/runtime-contracts.md +87 -51
- package/docs/reference/shortcuts-and-dock.md +28 -14
- package/docs/subsystems/anthropic-attribution.md +23 -11
- package/docs/subsystems/attested-pi-runs.md +12 -7
- package/docs/subsystems/background-task-runtime.md +53 -11
- package/docs/subsystems/child-launch-durability-and-safety.md +28 -9
- package/docs/subsystems/delegation.md +16 -3
- package/docs/subsystems/docs-freshness-gate.md +14 -7
- package/docs/subsystems/fusion.md +36 -11
- package/docs/subsystems/host-ui-and-telemetry.md +22 -9
- package/docs/tools/bg_delegate.md +3 -1
- package/docs/tools/bg_kill.md +3 -1
- package/docs/tools/bg_logs.md +3 -1
- package/docs/tools/bg_result.md +5 -3
- package/docs/tools/bg_run.md +31 -5
- package/docs/tools/bg_run_pi_attested.md +3 -1
- package/docs/tools/bg_status.md +3 -1
- package/docs/tools/fusion_investigate.md +3 -1
- package/docs/tools/fusion_reason.md +3 -1
- package/docs/tools/fusion_research.md +3 -1
- package/docs/tools/fusion_validate.md +3 -1
- package/extensions/anthropic-attribution-child.ts +3 -0
- package/extensions/anthropic-attribution.ts +166 -1
- package/package.json +12 -10
- package/src/core/anthropic-attribution-path.ts +5 -4
- package/src/core/anthropic-attribution.ts +293 -113
- package/src/core/attested-pi-contract.ts +4 -0
- package/src/core/attested-pi-run.ts +468 -81
- package/src/core/canonical-json.ts +21 -0
- package/src/core/common.ts +450 -40
- package/src/core/config.ts +121 -0
- package/src/core/context/visible-conversation-v2.ts +3 -6
- package/src/core/delegate/artifacts.ts +13 -9
- package/src/core/delegate/budget.ts +13 -6
- package/src/core/delegate/facade-contract.ts +6 -0
- package/src/core/delegate/result-package.ts +32 -14
- package/src/core/delegate/runner.ts +129 -58
- package/src/core/delegate/seed.ts +5 -7
- package/src/core/durable-fs.ts +178 -30
- package/src/core/extension-api.ts +36 -8
- package/src/core/fusion/artifacts.ts +17 -16
- package/src/core/fusion/clean-context.ts +8 -5
- package/src/core/fusion/config.ts +2 -1
- package/src/core/fusion/context.ts +2 -6
- package/src/core/fusion/facade-contract.ts +2 -0
- package/src/core/fusion/orchestrator.ts +3 -3
- package/src/core/fusion/prompts.ts +1 -1
- package/src/core/fusion/result-package.ts +259 -72
- package/src/core/fusion/source-policy.ts +43 -17
- package/src/core/lazy-module.ts +215 -0
- package/src/core/pi-launch.ts +390 -65
- package/src/core/registry.ts +2010 -381
- package/src/core/reload-shell-owner.ts +1662 -0
- package/src/core/shell-policy.ts +134 -0
- package/src/core/task-durable.ts +67 -0
- package/src/delegate-extension.ts +404 -144
- package/src/extension.ts +387 -114
- package/src/fusion-extension.ts +202 -96
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { readFile, rmdir } from 'node:fs/promises';
|
|
3
|
+
import { canonicalJson } from '../canonical-json.js';
|
|
4
|
+
import { replaceFileDurable } from '../durable-fs.js';
|
|
5
|
+
import { resolveAnthropicAttributionExtensionPath } from '../anthropic-attribution-path.js';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { DelegateArtifactStore, discardDelegateArtifactRoot } from './artifacts.js';
|
|
8
|
+
import { buildDelegateChildArgv, delegateChildEnv, ensureDelegateChildSessionDir, preflightDelegateLaunch, resolveDelegateChildExtensionPath, } from './launch.js';
|
|
9
|
+
import { DELEGATE_INLINE_ANSWER_BYTES } from './budget.js';
|
|
10
|
+
import { verifyDelegateResultPackage } from './result-package.js';
|
|
11
|
+
import { DelegateError, } from './types.js';
|
|
12
|
+
const PREPARATION_CLEANUP_ERROR_MAX_CHARS = 320;
|
|
13
|
+
function boundedPreparationError(error) {
|
|
14
|
+
const text = (error instanceof Error ? error.message : String(error))
|
|
15
|
+
.replace(/\s+/gu, ' ')
|
|
16
|
+
.trim();
|
|
17
|
+
if (text.length <= PREPARATION_CLEANUP_ERROR_MAX_CHARS)
|
|
18
|
+
return text;
|
|
19
|
+
return `${text.slice(0, PREPARATION_CLEANUP_ERROR_MAX_CHARS)}…`;
|
|
20
|
+
}
|
|
21
|
+
function filesystemErrorCode(error) {
|
|
22
|
+
if (typeof error !== 'object' || error === null)
|
|
23
|
+
return undefined;
|
|
24
|
+
const code = Reflect.get(error, 'code');
|
|
25
|
+
return typeof code === 'string' ? code : undefined;
|
|
26
|
+
}
|
|
27
|
+
async function removeEmptyDirectory(path) {
|
|
28
|
+
try {
|
|
29
|
+
await rmdir(path);
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
const code = filesystemErrorCode(error);
|
|
34
|
+
if (code === 'ENOENT')
|
|
35
|
+
return true;
|
|
36
|
+
if (code === 'ENOTEMPTY' || code === 'EEXIST')
|
|
37
|
+
return false;
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function discardUnownedDelegatePreparation(rootAbs) {
|
|
42
|
+
await discardDelegateArtifactRoot(rootAbs);
|
|
43
|
+
const runParent = dirname(rootAbs);
|
|
44
|
+
if (!(await removeEmptyDirectory(runParent)))
|
|
45
|
+
return;
|
|
46
|
+
await removeEmptyDirectory(dirname(runParent));
|
|
47
|
+
}
|
|
48
|
+
function throwIfPreparationAborted(signal) {
|
|
49
|
+
if (signal?.aborted !== true)
|
|
50
|
+
return;
|
|
51
|
+
const reason = signal.reason;
|
|
52
|
+
if (reason instanceof Error)
|
|
53
|
+
throw reason;
|
|
54
|
+
throw new Error('delegate launch preparation was cancelled before task registration');
|
|
55
|
+
}
|
|
56
|
+
function preparationCleanupFailure(original, cleanup) {
|
|
57
|
+
return new AggregateError([original, cleanup], `delegate launch preparation failed and rollback also failed: ${boundedPreparationError(cleanup)}`);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Prepare a delegate launch.
|
|
61
|
+
*
|
|
62
|
+
* Preflight runs first and completes entirely before the artifact directory is
|
|
63
|
+
* created, so every admission refusal leaves zero children AND zero artifacts.
|
|
64
|
+
* When a step after directory creation fails or activation cancellation is
|
|
65
|
+
* observed, the producer removes the unowned directory before rejecting.
|
|
66
|
+
*/
|
|
67
|
+
export async function prepareDelegateLaunch(input) {
|
|
68
|
+
throwIfPreparationAborted(input.signal);
|
|
69
|
+
// Resolve the guard extension before anything is created: a package missing
|
|
70
|
+
// its child guard must refuse rather than spawn an unguarded child.
|
|
71
|
+
const childExtensionPath = input.childExtensionPath ?? resolveDelegateChildExtensionPath();
|
|
72
|
+
let attributionExtensionPath;
|
|
73
|
+
if (input.route.provider === 'anthropic') {
|
|
74
|
+
try {
|
|
75
|
+
attributionExtensionPath =
|
|
76
|
+
input.attributionExtensionPath ?? resolveAnthropicAttributionExtensionPath();
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
throw new DelegateError(`Anthropic delegate attribution extension could not be resolved: ${error instanceof Error ? error.message : String(error)}`, {
|
|
80
|
+
code: 'delegate_isolation_unsupported',
|
|
81
|
+
childCreated: false,
|
|
82
|
+
remediation: ['Reinstall the package; Anthropic delegates require attribution.'],
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
throwIfPreparationAborted(input.signal);
|
|
87
|
+
const preflight = preflightDelegateLaunch(input);
|
|
88
|
+
throwIfPreparationAborted(input.signal);
|
|
89
|
+
let store;
|
|
90
|
+
try {
|
|
91
|
+
store = await DelegateArtifactStore.create({
|
|
92
|
+
cwd: input.cwd,
|
|
93
|
+
taskId: preflight.taskId,
|
|
94
|
+
launchNonce: preflight.launchNonce,
|
|
95
|
+
sessionId: input.sessionId,
|
|
96
|
+
childSessionId: preflight.childSessionId,
|
|
97
|
+
childSessionDir: '',
|
|
98
|
+
extensionMode: input.extensionMode,
|
|
99
|
+
route: input.route,
|
|
100
|
+
limits: preflight.limits,
|
|
101
|
+
seedSha256: preflight.seed.sha256,
|
|
102
|
+
...(input.now === undefined ? {} : { now: input.now }),
|
|
103
|
+
});
|
|
104
|
+
throwIfPreparationAborted(input.signal);
|
|
105
|
+
const seedRef = await store.writeSeed(preflight.seed.serialized);
|
|
106
|
+
throwIfPreparationAborted(input.signal);
|
|
107
|
+
// The persisted seed bytes are the bytes the child reads. Nothing
|
|
108
|
+
// re-serializes them between here and the child, and the child verifies the
|
|
109
|
+
// hash before its first model call.
|
|
110
|
+
if (seedRef.sha256 !== preflight.seed.sha256) {
|
|
111
|
+
throw new DelegateError('delegate seed hash changed between construction and persistence', {
|
|
112
|
+
code: 'seed_persist_failed',
|
|
113
|
+
childCreated: false,
|
|
114
|
+
taskId: preflight.taskId,
|
|
115
|
+
artifactDir: store.artifactDir,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
await store.writeLedger(preflight.seed.ledger);
|
|
119
|
+
throwIfPreparationAborted(input.signal);
|
|
120
|
+
await store.writeBudgetPlan(preflight.plan);
|
|
121
|
+
throwIfPreparationAborted(input.signal);
|
|
122
|
+
const childSessionDirAbs = await ensureDelegateChildSessionDir(store.artifactDirAbs);
|
|
123
|
+
throwIfPreparationAborted(input.signal);
|
|
124
|
+
const seedPathAbs = join(store.artifactDirAbs, 'seed.json');
|
|
125
|
+
const argv = buildDelegateChildArgv({
|
|
126
|
+
route: input.route,
|
|
127
|
+
capability: input.capability,
|
|
128
|
+
extensionMode: input.extensionMode,
|
|
129
|
+
childSessionId: preflight.childSessionId,
|
|
130
|
+
childSessionDir: childSessionDirAbs,
|
|
131
|
+
childExtensionPath,
|
|
132
|
+
attributionExtensionPath,
|
|
133
|
+
systemPrompt: preflight.childSystemPrompt,
|
|
134
|
+
});
|
|
135
|
+
const env = delegateChildEnv({
|
|
136
|
+
artifactDirAbs: store.artifactDirAbs,
|
|
137
|
+
seedPathAbs,
|
|
138
|
+
seedSha256: preflight.seed.sha256,
|
|
139
|
+
taskId: preflight.taskId,
|
|
140
|
+
launchNonce: preflight.launchNonce,
|
|
141
|
+
}, input.env ?? process.env);
|
|
142
|
+
const facts = {
|
|
143
|
+
taskId: preflight.taskId,
|
|
144
|
+
launchNonce: preflight.launchNonce,
|
|
145
|
+
artifactDir: store.artifactDir,
|
|
146
|
+
artifactDirAbs: store.artifactDirAbs,
|
|
147
|
+
seedSha256: preflight.seed.sha256,
|
|
148
|
+
childSessionId: preflight.childSessionId,
|
|
149
|
+
route: {
|
|
150
|
+
provider: input.route.provider,
|
|
151
|
+
model: input.route.model,
|
|
152
|
+
qualifiedId: input.route.qualified_id,
|
|
153
|
+
},
|
|
154
|
+
budget: {
|
|
155
|
+
family: preflight.plan.route.family,
|
|
156
|
+
rate_source: preflight.plan.route.rate_source,
|
|
157
|
+
conservative_rate_source: preflight.plan.conservative_estimate.rateSource,
|
|
158
|
+
},
|
|
159
|
+
extensionMode: input.extensionMode,
|
|
160
|
+
autoDeliver: input.autoDeliver,
|
|
161
|
+
};
|
|
162
|
+
const stdinBytes = Buffer.from(preflight.childPrompt, 'utf8');
|
|
163
|
+
// The persisted prompt bytes must equal the bytes sent to the child, so the
|
|
164
|
+
// artifact is evidence of what the child actually received.
|
|
165
|
+
await store.writeChildPrompt(stdinBytes);
|
|
166
|
+
throwIfPreparationAborted(input.signal);
|
|
167
|
+
const artifactDirAbs = store.artifactDirAbs;
|
|
168
|
+
let rollbackPromise;
|
|
169
|
+
const rollback = () => {
|
|
170
|
+
rollbackPromise ??= discardUnownedDelegatePreparation(artifactDirAbs);
|
|
171
|
+
return rollbackPromise;
|
|
172
|
+
};
|
|
173
|
+
return {
|
|
174
|
+
preflight,
|
|
175
|
+
store,
|
|
176
|
+
argv,
|
|
177
|
+
env,
|
|
178
|
+
facts,
|
|
179
|
+
childSessionDirAbs,
|
|
180
|
+
seedPathAbs,
|
|
181
|
+
stdinBytes,
|
|
182
|
+
rollback,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (store === undefined)
|
|
187
|
+
throw error;
|
|
188
|
+
try {
|
|
189
|
+
await discardUnownedDelegatePreparation(store.artifactDirAbs);
|
|
190
|
+
}
|
|
191
|
+
catch (cleanupError) {
|
|
192
|
+
throw preparationCleanupFailure(error, cleanupError);
|
|
193
|
+
}
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Evaluate a finished delegate child.
|
|
199
|
+
*
|
|
200
|
+
* The committed result package is the sole answer data plane. Its presence under
|
|
201
|
+
* its final name is the success signal; its absence means no answer was
|
|
202
|
+
* accepted, whatever the process exit code happened to be. A child that exits 0
|
|
203
|
+
* without committing is a typed `child_exited_without_commit`, never a silent
|
|
204
|
+
* empty success.
|
|
205
|
+
*/
|
|
206
|
+
export async function evaluateDelegateTerminal(input) {
|
|
207
|
+
const evaluation = await adjudicateDelegateTerminal(input);
|
|
208
|
+
// Record the parent's adjudicated view separately from the child-written
|
|
209
|
+
// result package, so neither writer can overwrite the other's claim.
|
|
210
|
+
try {
|
|
211
|
+
await replaceFileDurable(join(input.artifactDirAbs, 'outcome.json'), `${canonicalJson({
|
|
212
|
+
schema_version: 'pi-background-tasks.delegate-outcome.v1',
|
|
213
|
+
task_id: input.taskId,
|
|
214
|
+
launch_nonce: input.launchNonce,
|
|
215
|
+
observed_task_status: input.taskStatus,
|
|
216
|
+
outcome: evaluation.outcome,
|
|
217
|
+
error_code: evaluation.error?.code ?? null,
|
|
218
|
+
})}\n`);
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
// Failing to record the adjudication must not change the adjudication
|
|
222
|
+
// itself, which is returned to the caller either way.
|
|
223
|
+
}
|
|
224
|
+
return evaluation;
|
|
225
|
+
}
|
|
226
|
+
async function adjudicateDelegateTerminal(input) {
|
|
227
|
+
const resultPath = join(input.artifactDirAbs, 'result.json');
|
|
228
|
+
const terminalPath = join(input.artifactDirAbs, 'child-terminal.json');
|
|
229
|
+
if (!existsSync(resultPath)) {
|
|
230
|
+
const recorded = existsSync(terminalPath) ? await readChildTerminal(terminalPath) : undefined;
|
|
231
|
+
const cancelled = input.taskStatus === 'killed';
|
|
232
|
+
const code = recorded?.code ?? (cancelled ? 'child_cancelled' : 'child_exited_without_commit');
|
|
233
|
+
const detail = recorded?.message ??
|
|
234
|
+
input.taskError ??
|
|
235
|
+
'the delegate child exited without committing a result package';
|
|
236
|
+
const preserved = [
|
|
237
|
+
'seed.json',
|
|
238
|
+
'budget-plan.json',
|
|
239
|
+
'child-terminal.json',
|
|
240
|
+
'runtime-budget.json',
|
|
241
|
+
].filter((name) => existsSync(join(input.artifactDirAbs, name)));
|
|
242
|
+
if (input.taskOutputPath !== undefined &&
|
|
243
|
+
input.taskOutputAbsPath !== undefined &&
|
|
244
|
+
existsSync(input.taskOutputAbsPath)) {
|
|
245
|
+
preserved.push(input.taskOutputPath);
|
|
246
|
+
}
|
|
247
|
+
const diagnosticTargets = preserved.filter((name) => name === 'child-terminal.json' ||
|
|
248
|
+
name === 'runtime-budget.json' ||
|
|
249
|
+
name === input.taskOutputPath);
|
|
250
|
+
const diagnostic = diagnosticTargets.length === 0
|
|
251
|
+
? 'No child terminal record or merged task output exists; inspect the preserved launch artifacts listed above.'
|
|
252
|
+
: `Inspect the preserved diagnostic evidence: ${diagnosticTargets.join(', ')}.`;
|
|
253
|
+
const error = new DelegateError(`bg_delegate produced no committed answer: ${detail}`, {
|
|
254
|
+
code: isDelegateErrorCode(code) ? code : 'child_exited_without_commit',
|
|
255
|
+
childCreated: true,
|
|
256
|
+
taskId: input.taskId,
|
|
257
|
+
artifactDir: input.artifactDirAbs,
|
|
258
|
+
preserved,
|
|
259
|
+
remediation: [
|
|
260
|
+
diagnostic,
|
|
261
|
+
'No partial answer is returned; nothing was truncated to look like success.',
|
|
262
|
+
],
|
|
263
|
+
});
|
|
264
|
+
const outcome = {
|
|
265
|
+
status: cancelled ? 'cancelled' : 'failed',
|
|
266
|
+
errorCode: error.code,
|
|
267
|
+
};
|
|
268
|
+
return { outcome, error };
|
|
269
|
+
}
|
|
270
|
+
let raw;
|
|
271
|
+
try {
|
|
272
|
+
raw = await readFile(resultPath, 'utf8');
|
|
273
|
+
}
|
|
274
|
+
catch (error) {
|
|
275
|
+
const failure = new DelegateError(`bg_delegate could not read its committed result package: ${error instanceof Error ? error.message : String(error)}`, {
|
|
276
|
+
code: 'artifact_read_failed',
|
|
277
|
+
childCreated: true,
|
|
278
|
+
taskId: input.taskId,
|
|
279
|
+
artifactDir: input.artifactDirAbs,
|
|
280
|
+
});
|
|
281
|
+
return { outcome: { status: 'failed', errorCode: failure.code }, error: failure };
|
|
282
|
+
}
|
|
283
|
+
try {
|
|
284
|
+
const verified = verifyDelegateResultPackage(raw, {
|
|
285
|
+
taskId: input.taskId,
|
|
286
|
+
launchNonce: input.launchNonce,
|
|
287
|
+
seedSha256: input.seedSha256,
|
|
288
|
+
route: input.route,
|
|
289
|
+
});
|
|
290
|
+
return {
|
|
291
|
+
outcome: {
|
|
292
|
+
status: 'committed',
|
|
293
|
+
answerBytes: verified.package.answer.byte_length,
|
|
294
|
+
answerSha256: verified.package.answer.sha256,
|
|
295
|
+
turns: verified.package.turns,
|
|
296
|
+
toolCalls: verified.package.tool_calls,
|
|
297
|
+
},
|
|
298
|
+
result: verified,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
if (error instanceof DelegateError) {
|
|
303
|
+
return { outcome: { status: 'failed', errorCode: error.code }, error };
|
|
304
|
+
}
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
async function readChildTerminal(path) {
|
|
309
|
+
try {
|
|
310
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
311
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
312
|
+
return undefined;
|
|
313
|
+
const code = Reflect.get(parsed, 'code');
|
|
314
|
+
const message = Reflect.get(parsed, 'message');
|
|
315
|
+
if (typeof code !== 'string' || typeof message !== 'string')
|
|
316
|
+
return undefined;
|
|
317
|
+
return { code, message };
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
// A missing or malformed child-terminal record must not mask the primary
|
|
321
|
+
// "no committed answer" failure, which is reported by the caller either way.
|
|
322
|
+
return undefined;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
const DELEGATE_ERROR_CODE_SET = new Set([
|
|
326
|
+
'delegate_hook_contract_unsupported',
|
|
327
|
+
'delegate_isolation_unsupported',
|
|
328
|
+
'route_unresolved',
|
|
329
|
+
'route_capacity_unknown',
|
|
330
|
+
'seed_projection_failed',
|
|
331
|
+
'seed_budget_exceeded',
|
|
332
|
+
'seed_persist_failed',
|
|
333
|
+
'invalid_arguments',
|
|
334
|
+
'child_spawn_failed',
|
|
335
|
+
'child_startup_failed',
|
|
336
|
+
'child_timeout',
|
|
337
|
+
'child_cancelled',
|
|
338
|
+
'child_turn_limit',
|
|
339
|
+
'child_tool_call_limit',
|
|
340
|
+
'child_exited_without_commit',
|
|
341
|
+
'provider_context_budget_exhausted',
|
|
342
|
+
'aggregate_tool_output_cap',
|
|
343
|
+
'child_model_output_limit',
|
|
344
|
+
'child_capture_limit',
|
|
345
|
+
'child_result_invalid',
|
|
346
|
+
'child_result_encoding_invalid',
|
|
347
|
+
'route_attestation_missing',
|
|
348
|
+
'route_mismatch',
|
|
349
|
+
'seed_hash_mismatch',
|
|
350
|
+
'answer_hash_mismatch',
|
|
351
|
+
'artifact_spill_failed',
|
|
352
|
+
'artifact_read_failed',
|
|
353
|
+
'artifact_error',
|
|
354
|
+
'result_not_ready',
|
|
355
|
+
'result_unavailable',
|
|
356
|
+
'result_too_large_for_inline',
|
|
357
|
+
'task_unknown',
|
|
358
|
+
]);
|
|
359
|
+
function isDelegateErrorCode(value) {
|
|
360
|
+
return DELEGATE_ERROR_CODE_SET.has(value);
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Decide inline versus artifact delivery.
|
|
364
|
+
*
|
|
365
|
+
* The cap is applied to the exact serialized answer bytes. An answer over the
|
|
366
|
+
* cap degrades to an artifact reference explicitly and is never shortened to
|
|
367
|
+
* fit.
|
|
368
|
+
*/
|
|
369
|
+
export function decideDelegateDelivery(answerBytes, requested, cap = DELEGATE_INLINE_ANSWER_BYTES) {
|
|
370
|
+
if (requested === 'artifact') {
|
|
371
|
+
return { mode: 'artifact', reason: 'artifact delivery was requested explicitly' };
|
|
372
|
+
}
|
|
373
|
+
if (answerBytes <= cap) {
|
|
374
|
+
return {
|
|
375
|
+
mode: 'inline',
|
|
376
|
+
reason: `the answer is ${String(answerBytes)} bytes, within the ${String(cap)}-byte inline cap`,
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
return {
|
|
380
|
+
mode: 'artifact',
|
|
381
|
+
reason: `the answer is ${String(answerBytes)} bytes, over the ${String(cap)}-byte inline cap`,
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
/** Raised when inline delivery was explicitly requested for an oversized answer. */
|
|
385
|
+
export function inlineTooLarge(taskId, artifactDir, answerBytes, cap = DELEGATE_INLINE_ANSWER_BYTES) {
|
|
386
|
+
return new DelegateError(`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.`, {
|
|
387
|
+
code: 'result_too_large_for_inline',
|
|
388
|
+
childCreated: true,
|
|
389
|
+
taskId,
|
|
390
|
+
artifactDir,
|
|
391
|
+
preserved: [join(artifactDir, 'result.json')],
|
|
392
|
+
remediation: [
|
|
393
|
+
'Call bg_result with delivery:"artifact" to receive the verified metadata plus the artifact reference.',
|
|
394
|
+
'Read the answer from the artifact path directly if the full text is required.',
|
|
395
|
+
],
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
//# sourceMappingURL=runner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../../src/core/delegate/runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,wCAAwC,EAAE,MAAM,kCAAkC,CAAC;AAC5F,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,qBAAqB,EAAE,2BAA2B,EAAE,MAAM,gBAAgB,CAAC;AACpF,OAAO,EACL,sBAAsB,EACtB,gBAAgB,EAChB,6BAA6B,EAC7B,uBAAuB,EACvB,iCAAiC,GAGlC,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,4BAA4B,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAA+B,MAAM,qBAAqB,CAAC;AAC/F,OAAO,EACL,aAAa,GAId,MAAM,YAAY,CAAC;AAsCpB,MAA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kBAAkB;KAC9F,CAAC;AACJ,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,cAAc,CAC5B,MAAc,EACd,WAAmB,EACnB,WAAmB,EACnB,GAAG,GAAG,4BAA4B;IAElC,OAAO,IAAI,aAAa,CACtB,qDAAqD,MAAM,CAAC,WAAW,CAAC,oBAAoB,MAAM,CAAC,GAAG,CAAC,kEAAkE,IAAI,CAAC,WAAW,EAAE,aAAa,CAAC,+BAA+B,EACxO;QACE,IAAI,EAAE,6BAA6B;QACnC,YAAY,EAAE,IAAI;QAClB,MAAM;QACN,WAAW;QACX,SAAS,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;QAC7C,WAAW,EAAE;YACX,uGAAuG;YACvG,+EAA+E;SAChF;KACF,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { existsSync } from 'node:fs';\nimport { readFile, rmdir } from 'node:fs/promises';\nimport { canonicalJson } from '../canonical-json.js';\nimport { replaceFileDurable } from '../durable-fs.js';\nimport { resolveAnthropicAttributionExtensionPath } from '../anthropic-attribution-path.js';\nimport { dirname, join } from 'node:path';\nimport { DelegateArtifactStore, discardDelegateArtifactRoot } from './artifacts.js';\nimport {\n buildDelegateChildArgv,\n delegateChildEnv,\n ensureDelegateChildSessionDir,\n preflightDelegateLaunch,\n resolveDelegateChildExtensionPath,\n type DelegatePreflightInput,\n type DelegatePreflightResult,\n} from './launch.js';\nimport { DELEGATE_INLINE_ANSWER_BYTES } from './budget.js';\nimport { verifyDelegateResultPackage, type VerifiedDelegateResult } from './result-package.js';\nimport {\n DelegateError,\n type DelegateAutoDeliverMode,\n type DelegateExtensionMode,\n type DelegateResultPackageV1,\n} from './types.js';\nimport type { DelegateTaskFacts, DelegateTaskOutcome } from '../common.js';\n\n/**\n * Delegate launch preparation and terminal evaluation.\n *\n * Separated from the background-task registry so the ordering property that\n * matters most — preflight refusals create nothing — is testable without\n * spawning anything.\n */\n\nexport interface PreparedDelegateLaunch {\n preflight: DelegatePreflightResult;\n store: DelegateArtifactStore;\n argv: readonly string[];\n env: NodeJS.ProcessEnv;\n facts: DelegateTaskFacts;\n childSessionDirAbs: string;\n seedPathAbs: string;\n /** Exact prompt bytes delivered to the child over stdin. */\n stdinBytes: Buffer;\n /** Remove this complete preparation while it is still unowned by a task. */\n rollback: () => Promise<void>;\n}\n\nexport interface PrepareDelegateLaunchInput extends DelegatePreflightInput {\n cwd: string;\n sessionId: string | undefined;\n autoDeliver: DelegateAutoDeliverMode;\n extensionMode: DelegateExtensionMode;\n childExtensionPath?: string | undefined;\n attributionExtensionPath?: string | undefined;\n env?: NodeJS.ProcessEnv | undefined;\n now?: (() => Date) | undefined;\n /** Activation closure cancels preparation before task ownership transfers. */\n signal?: AbortSignal | undefined;\n}\n\nconst PREPARATION_CLEANUP_ERROR_MAX_CHARS = 320;\n\nfunction boundedPreparationError(error: unknown): string {\n const text = (error instanceof Error ? error.message : String(error))\n .replace(/\\s+/gu, ' ')\n .trim();\n if (text.length <= PREPARATION_CLEANUP_ERROR_MAX_CHARS) return text;\n return `${text.slice(0, PREPARATION_CLEANUP_ERROR_MAX_CHARS)}…`;\n}\n\nfunction filesystemErrorCode(error: unknown): string | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const code: unknown = Reflect.get(error, 'code');\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function removeEmptyDirectory(path: string): Promise<boolean> {\n try {\n await rmdir(path);\n return true;\n } catch (error) {\n const code = filesystemErrorCode(error);\n if (code === 'ENOENT') return true;\n if (code === 'ENOTEMPTY' || code === 'EEXIST') return false;\n throw error;\n }\n}\n\nasync function discardUnownedDelegatePreparation(rootAbs: string): Promise<void> {\n await discardDelegateArtifactRoot(rootAbs);\n const runParent = dirname(rootAbs);\n if (!(await removeEmptyDirectory(runParent))) return;\n await removeEmptyDirectory(dirname(runParent));\n}\n\nfunction throwIfPreparationAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted !== true) return;\n const reason: unknown = signal.reason;\n if (reason instanceof Error) throw reason;\n throw new Error('delegate launch preparation was cancelled before task registration');\n}\n\nfunction preparationCleanupFailure(original: unknown, cleanup: unknown): AggregateError {\n return new AggregateError(\n [original, cleanup],\n `delegate launch preparation failed and rollback also failed: ${boundedPreparationError(cleanup)}`,\n );\n}\n\n/**\n * Prepare a delegate launch.\n *\n * Preflight runs first and completes entirely before the artifact directory is\n * created, so every admission refusal leaves zero children AND zero artifacts.\n * When a step after directory creation fails or activation cancellation is\n * observed, the producer removes the unowned directory before rejecting.\n */\nexport async function prepareDelegateLaunch(\n input: PrepareDelegateLaunchInput,\n): Promise<PreparedDelegateLaunch> {\n throwIfPreparationAborted(input.signal);\n // Resolve the guard extension before anything is created: a package missing\n // its child guard must refuse rather than spawn an unguarded child.\n const childExtensionPath = input.childExtensionPath ?? resolveDelegateChildExtensionPath();\n let attributionExtensionPath: string | undefined;\n if (input.route.provider === 'anthropic') {\n try {\n attributionExtensionPath =\n input.attributionExtensionPath ?? resolveAnthropicAttributionExtensionPath();\n } catch (error) {\n throw new DelegateError(\n `Anthropic delegate attribution extension could not be resolved: ${error instanceof Error ? error.message : String(error)}`,\n {\n code: 'delegate_isolation_unsupported',\n childCreated: false,\n remediation: ['Reinstall the package; Anthropic delegates require attribution.'],\n },\n );\n }\n }\n\n throwIfPreparationAborted(input.signal);\n const preflight = preflightDelegateLaunch(input);\n throwIfPreparationAborted(input.signal);\n\n let store: DelegateArtifactStore | undefined;\n try {\n store = await DelegateArtifactStore.create({\n cwd: input.cwd,\n taskId: preflight.taskId,\n launchNonce: preflight.launchNonce,\n sessionId: input.sessionId,\n childSessionId: preflight.childSessionId,\n childSessionDir: '',\n extensionMode: input.extensionMode,\n route: input.route,\n limits: preflight.limits,\n seedSha256: preflight.seed.sha256,\n ...(input.now === undefined ? {} : { now: input.now }),\n });\n throwIfPreparationAborted(input.signal);\n\n const seedRef = await store.writeSeed(preflight.seed.serialized);\n throwIfPreparationAborted(input.signal);\n // The persisted seed bytes are the bytes the child reads. Nothing\n // re-serializes them between here and the child, and the child verifies the\n // hash before its first model call.\n if (seedRef.sha256 !== preflight.seed.sha256) {\n throw new DelegateError('delegate seed hash changed between construction and persistence', {\n code: 'seed_persist_failed',\n childCreated: false,\n taskId: preflight.taskId,\n artifactDir: store.artifactDir,\n });\n }\n await store.writeLedger(preflight.seed.ledger);\n throwIfPreparationAborted(input.signal);\n await store.writeBudgetPlan(preflight.plan);\n throwIfPreparationAborted(input.signal);\n const childSessionDirAbs = await ensureDelegateChildSessionDir(store.artifactDirAbs);\n throwIfPreparationAborted(input.signal);\n const seedPathAbs = join(store.artifactDirAbs, 'seed.json');\n const argv = buildDelegateChildArgv({\n route: input.route,\n capability: input.capability,\n extensionMode: input.extensionMode,\n childSessionId: preflight.childSessionId,\n childSessionDir: childSessionDirAbs,\n childExtensionPath,\n attributionExtensionPath,\n systemPrompt: preflight.childSystemPrompt,\n });\n const env = delegateChildEnv(\n {\n artifactDirAbs: store.artifactDirAbs,\n seedPathAbs,\n seedSha256: preflight.seed.sha256,\n taskId: preflight.taskId,\n launchNonce: preflight.launchNonce,\n },\n input.env ?? process.env,\n );\n const facts: DelegateTaskFacts = {\n taskId: preflight.taskId,\n launchNonce: preflight.launchNonce,\n artifactDir: store.artifactDir,\n artifactDirAbs: store.artifactDirAbs,\n seedSha256: preflight.seed.sha256,\n childSessionId: preflight.childSessionId,\n route: {\n provider: input.route.provider,\n model: input.route.model,\n qualifiedId: input.route.qualified_id,\n },\n budget: {\n family: preflight.plan.route.family,\n rate_source: preflight.plan.route.rate_source,\n conservative_rate_source: preflight.plan.conservative_estimate.rateSource,\n },\n extensionMode: input.extensionMode,\n autoDeliver: input.autoDeliver,\n };\n const stdinBytes = Buffer.from(preflight.childPrompt, 'utf8');\n // The persisted prompt bytes must equal the bytes sent to the child, so the\n // artifact is evidence of what the child actually received.\n await store.writeChildPrompt(stdinBytes);\n throwIfPreparationAborted(input.signal);\n const artifactDirAbs = store.artifactDirAbs;\n let rollbackPromise: Promise<void> | undefined;\n const rollback = (): Promise<void> => {\n rollbackPromise ??= discardUnownedDelegatePreparation(artifactDirAbs);\n return rollbackPromise;\n };\n return {\n preflight,\n store,\n argv,\n env,\n facts,\n childSessionDirAbs,\n seedPathAbs,\n stdinBytes,\n rollback,\n };\n } catch (error) {\n if (store === undefined) throw error;\n try {\n await discardUnownedDelegatePreparation(store.artifactDirAbs);\n } catch (cleanupError) {\n throw preparationCleanupFailure(error, cleanupError);\n }\n throw error;\n }\n}\n\nexport interface DelegateTerminalEvaluation {\n outcome: DelegateTaskOutcome;\n result?: VerifiedDelegateResult | undefined;\n error?: DelegateError | undefined;\n}\n\nexport interface EvaluateDelegateTerminalInput {\n artifactDirAbs: string;\n taskId: string;\n launchNonce: string;\n seedSha256: string;\n route: { provider: string; model: string };\n /** Terminal status observed by the background task registry. */\n taskStatus: 'completed' | 'failed' | 'killed';\n taskError: string | undefined;\n /** Real merged child output owned by the background-task registry. */\n taskOutputPath?: string | undefined;\n taskOutputAbsPath?: string | undefined;\n}\n\n/**\n * Evaluate a finished delegate child.\n *\n * The committed result package is the sole answer data plane. Its presence under\n * its final name is the success signal; its absence means no answer was\n * accepted, whatever the process exit code happened to be. A child that exits 0\n * without committing is a typed `child_exited_without_commit`, never a silent\n * empty success.\n */\nexport async function evaluateDelegateTerminal(\n input: EvaluateDelegateTerminalInput,\n): Promise<DelegateTerminalEvaluation> {\n const evaluation = await adjudicateDelegateTerminal(input);\n // Record the parent's adjudicated view separately from the child-written\n // result package, so neither writer can overwrite the other's claim.\n try {\n await replaceFileDurable(\n join(input.artifactDirAbs, 'outcome.json'),\n `${canonicalJson({\n schema_version: 'pi-background-tasks.delegate-outcome.v1',\n task_id: input.taskId,\n launch_nonce: input.launchNonce,\n observed_task_status: input.taskStatus,\n outcome: evaluation.outcome,\n error_code: evaluation.error?.code ?? null,\n })}\\n`,\n );\n } catch {\n // Failing to record the adjudication must not change the adjudication\n // itself, which is returned to the caller either way.\n }\n return evaluation;\n}\n\nasync function adjudicateDelegateTerminal(\n input: EvaluateDelegateTerminalInput,\n): Promise<DelegateTerminalEvaluation> {\n const resultPath = join(input.artifactDirAbs, 'result.json');\n const terminalPath = join(input.artifactDirAbs, 'child-terminal.json');\n if (!existsSync(resultPath)) {\n const recorded = existsSync(terminalPath) ? await readChildTerminal(terminalPath) : undefined;\n const cancelled = input.taskStatus === 'killed';\n const code = recorded?.code ?? (cancelled ? 'child_cancelled' : 'child_exited_without_commit');\n const detail =\n recorded?.message ??\n input.taskError ??\n 'the delegate child exited without committing a result package';\n const preserved = [\n 'seed.json',\n 'budget-plan.json',\n 'child-terminal.json',\n 'runtime-budget.json',\n ].filter((name) => existsSync(join(input.artifactDirAbs, name)));\n if (\n input.taskOutputPath !== undefined &&\n input.taskOutputAbsPath !== undefined &&\n existsSync(input.taskOutputAbsPath)\n ) {\n preserved.push(input.taskOutputPath);\n }\n const diagnosticTargets = preserved.filter(\n (name) =>\n name === 'child-terminal.json' ||\n name === 'runtime-budget.json' ||\n name === input.taskOutputPath,\n );\n const diagnostic =\n diagnosticTargets.length === 0\n ? 'No child terminal record or merged task output exists; inspect the preserved launch artifacts listed above.'\n : `Inspect the preserved diagnostic evidence: ${diagnosticTargets.join(', ')}.`;\n const error = new DelegateError(`bg_delegate produced no committed answer: ${detail}`, {\n code: isDelegateErrorCode(code) ? code : 'child_exited_without_commit',\n childCreated: true,\n taskId: input.taskId,\n artifactDir: input.artifactDirAbs,\n preserved,\n remediation: [\n diagnostic,\n 'No partial answer is returned; nothing was truncated to look like success.',\n ],\n });\n const outcome: DelegateTaskOutcome = {\n status: cancelled ? 'cancelled' : 'failed',\n errorCode: error.code,\n };\n return { outcome, error };\n }\n\n let raw: string;\n try {\n raw = await readFile(resultPath, 'utf8');\n } catch (error) {\n const failure = new DelegateError(\n `bg_delegate could not read its committed result package: ${error instanceof Error ? error.message : String(error)}`,\n {\n code: 'artifact_read_failed',\n childCreated: true,\n taskId: input.taskId,\n artifactDir: input.artifactDirAbs,\n },\n );\n return { outcome: { status: 'failed', errorCode: failure.code }, error: failure };\n }\n\n try {\n const verified = verifyDelegateResultPackage(raw, {\n taskId: input.taskId,\n launchNonce: input.launchNonce,\n seedSha256: input.seedSha256,\n route: input.route,\n });\n return {\n outcome: {\n status: 'committed',\n answerBytes: verified.package.answer.byte_length,\n answerSha256: verified.package.answer.sha256,\n turns: verified.package.turns,\n toolCalls: verified.package.tool_calls,\n },\n result: verified,\n };\n } catch (error) {\n if (error instanceof DelegateError) {\n return { outcome: { status: 'failed', errorCode: error.code }, error };\n }\n throw error;\n }\n}\n\ninterface ChildTerminalRecord {\n code: string;\n message: string;\n}\n\nasync function readChildTerminal(path: string): Promise<ChildTerminalRecord | undefined> {\n try {\n const parsed: unknown = JSON.parse(await readFile(path, 'utf8'));\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const code: unknown = Reflect.get(parsed, 'code');\n const message: unknown = Reflect.get(parsed, 'message');\n if (typeof code !== 'string' || typeof message !== 'string') return undefined;\n return { code, message };\n } catch {\n // A missing or malformed child-terminal record must not mask the primary\n // \"no committed answer\" failure, which is reported by the caller either way.\n return undefined;\n }\n}\n\nconst DELEGATE_ERROR_CODE_SET = new Set<string>([\n 'delegate_hook_contract_unsupported',\n 'delegate_isolation_unsupported',\n 'route_unresolved',\n 'route_capacity_unknown',\n 'seed_projection_failed',\n 'seed_budget_exceeded',\n 'seed_persist_failed',\n 'invalid_arguments',\n 'child_spawn_failed',\n 'child_startup_failed',\n 'child_timeout',\n 'child_cancelled',\n 'child_turn_limit',\n 'child_tool_call_limit',\n 'child_exited_without_commit',\n 'provider_context_budget_exhausted',\n 'aggregate_tool_output_cap',\n 'child_model_output_limit',\n 'child_capture_limit',\n 'child_result_invalid',\n 'child_result_encoding_invalid',\n 'route_attestation_missing',\n 'route_mismatch',\n 'seed_hash_mismatch',\n 'answer_hash_mismatch',\n 'artifact_spill_failed',\n 'artifact_read_failed',\n 'artifact_error',\n 'result_not_ready',\n 'result_unavailable',\n 'result_too_large_for_inline',\n 'task_unknown',\n]);\n\nfunction isDelegateErrorCode(value: string): value is DelegateError['code'] {\n return DELEGATE_ERROR_CODE_SET.has(value);\n}\n\nexport interface DelegateInlineDecision {\n mode: 'inline' | 'artifact';\n reason: string;\n}\n\n/**\n * Decide inline versus artifact delivery.\n *\n * The cap is applied to the exact serialized answer bytes. An answer over the\n * cap degrades to an artifact reference explicitly and is never shortened to\n * fit.\n */\nexport function decideDelegateDelivery(\n answerBytes: number,\n requested: 'inline' | 'artifact' | undefined,\n cap = DELEGATE_INLINE_ANSWER_BYTES,\n): DelegateInlineDecision {\n if (requested === 'artifact') {\n return { mode: 'artifact', reason: 'artifact delivery was requested explicitly' };\n }\n if (answerBytes <= cap) {\n return {\n mode: 'inline',\n reason: `the answer is ${String(answerBytes)} bytes, within the ${String(cap)}-byte inline cap`,\n };\n }\n return {\n mode: 'artifact',\n reason: `the answer is ${String(answerBytes)} bytes, over the ${String(cap)}-byte inline cap`,\n };\n}\n\n/** Raised when inline delivery was explicitly requested for an oversized answer. */\nexport function inlineTooLarge(\n taskId: string,\n artifactDir: string,\n answerBytes: number,\n cap = DELEGATE_INLINE_ANSWER_BYTES,\n): DelegateError {\n return new DelegateError(\n `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.`,\n {\n code: 'result_too_large_for_inline',\n childCreated: true,\n taskId,\n artifactDir,\n preserved: [join(artifactDir, 'result.json')],\n remediation: [\n 'Call bg_result with delivery:\"artifact\" to receive the verified metadata plus the artifact reference.',\n 'Read the answer from the artifact path directly if the full text is required.',\n ],\n },\n );\n}\n\nexport type { DelegateResultPackageV1 };\n"]}
|