@caupulican/pi-adaptative 0.85.8 → 0.86.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/dist/core/agent-paths.d.ts +6 -3
- package/dist/core/agent-paths.d.ts.map +1 -1
- package/dist/core/agent-paths.js +10 -3
- package/dist/core/agent-paths.js.map +1 -1
- package/dist/core/agent-session.d.ts +5 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +7 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
- package/dist/core/autonomy/bounded-completion.js +19 -8
- package/dist/core/autonomy/bounded-completion.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +11 -5
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +34 -8
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/autonomy/subagent-prompt.d.ts +3 -3
- package/dist/core/autonomy/subagent-prompt.js +9 -9
- package/dist/core/autonomy/subagent-prompt.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +10 -8
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +23 -13
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts +4 -0
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +11 -4
- package/dist/core/bash-execution-controller.js.map +1 -1
- package/dist/core/bash-executor.d.ts +2 -0
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +2 -1
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/capability-contract.d.ts +1 -1
- package/dist/core/capability-contract.d.ts.map +1 -1
- package/dist/core/capability-contract.js +0 -1
- package/dist/core/capability-contract.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts +1 -0
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +3 -2
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts +27 -8
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +191 -33
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-agent-control.d.ts +45 -6
- package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control.js +110 -13
- package/dist/core/delegation/worker-agent-control.js.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.js +177 -158
- package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
- package/dist/core/delegation/worker-authority-resolver.d.ts +23 -0
- package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -0
- package/dist/core/delegation/worker-authority-resolver.js +128 -0
- package/dist/core/delegation/worker-authority-resolver.js.map +1 -0
- package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
- package/dist/core/delegation/worker-conversation-store.js +1 -1
- package/dist/core/delegation/worker-conversation-store.js.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts +7 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.js +260 -87
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
- package/dist/core/delegation/worker-delegation-request.d.ts +25 -4
- package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-request.js +90 -1
- package/dist/core/delegation/worker-delegation-request.js.map +1 -1
- package/dist/core/delegation/worker-execution-policy.d.ts +2 -0
- package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
- package/dist/core/delegation/worker-execution-policy.js +22 -12
- package/dist/core/delegation/worker-execution-policy.js.map +1 -1
- package/dist/core/delegation/worker-lifecycle.d.ts +1 -0
- package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
- package/dist/core/delegation/worker-lifecycle.js +4 -2
- package/dist/core/delegation/worker-lifecycle.js.map +1 -1
- package/dist/core/delegation/worker-profile-resolver.d.ts +0 -2
- package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
- package/dist/core/delegation/worker-profile-resolver.js +8 -35
- package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
- package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-recovery-coordinator.js +1 -0
- package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-runner.d.ts +6 -1
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +20 -6
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +47 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.js +210 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -0
- package/dist/core/memory/providers/file-store.d.ts +2 -0
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +22 -20
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/models/runtime-process.d.ts.map +1 -1
- package/dist/core/models/runtime-process.js +5 -18
- package/dist/core/models/runtime-process.js.map +1 -1
- package/dist/core/orchestration/bounded-string-array.d.ts +11 -0
- package/dist/core/orchestration/bounded-string-array.d.ts.map +1 -0
- package/dist/core/orchestration/bounded-string-array.js +17 -0
- package/dist/core/orchestration/bounded-string-array.js.map +1 -0
- package/dist/core/orchestration/capability-gateway.d.ts +16 -0
- package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
- package/dist/core/orchestration/capability-gateway.js +38 -0
- package/dist/core/orchestration/capability-gateway.js.map +1 -1
- package/dist/core/orchestration/contracts.d.ts +11 -3
- package/dist/core/orchestration/contracts.d.ts.map +1 -1
- package/dist/core/orchestration/contracts.js +0 -1
- package/dist/core/orchestration/contracts.js.map +1 -1
- package/dist/core/orchestration/delegation-ledger.d.ts +1 -0
- package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
- package/dist/core/orchestration/delegation-ledger.js +3 -0
- package/dist/core/orchestration/delegation-ledger.js.map +1 -1
- package/dist/core/orchestration/event-store.d.ts +12 -10
- package/dist/core/orchestration/event-store.d.ts.map +1 -1
- package/dist/core/orchestration/event-store.js +94 -104
- package/dist/core/orchestration/event-store.js.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.d.ts +2 -2
- package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.js +4 -1
- package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
- package/dist/core/orchestration/policy-compiler.d.ts.map +1 -1
- package/dist/core/orchestration/policy-compiler.js +8 -9
- package/dist/core/orchestration/policy-compiler.js.map +1 -1
- package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
- package/dist/core/orchestration/profile-registry.js +4 -10
- package/dist/core/orchestration/profile-registry.js.map +1 -1
- package/dist/core/orchestration/task-runtime.d.ts +1 -0
- package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
- package/dist/core/orchestration/task-runtime.js +58 -3
- package/dist/core/orchestration/task-runtime.js.map +1 -1
- package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
- package/dist/core/orchestration/worker-execution-contract.js +10 -17
- package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
- package/dist/core/risk-classifier.js +3 -3
- package/dist/core/risk-classifier.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +4 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +34 -15
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/secrets/bitwarden-credential-storage.d.ts +51 -0
- package/dist/core/secrets/bitwarden-credential-storage.d.ts.map +1 -0
- package/dist/core/secrets/bitwarden-credential-storage.js +345 -0
- package/dist/core/secrets/bitwarden-credential-storage.js.map +1 -0
- package/dist/core/secrets/credential-exposure-guard.d.ts +8 -4
- package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -1
- package/dist/core/secrets/credential-exposure-guard.js +30 -31
- package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
- package/dist/core/secrets/credential-manager.d.ts +109 -0
- package/dist/core/secrets/credential-manager.d.ts.map +1 -0
- package/dist/core/secrets/credential-manager.js +384 -0
- package/dist/core/secrets/credential-manager.js.map +1 -0
- package/dist/core/secrets/credential-project.d.ts +4 -0
- package/dist/core/secrets/credential-project.d.ts.map +1 -0
- package/dist/core/secrets/credential-project.js +145 -0
- package/dist/core/secrets/credential-project.js.map +1 -0
- package/dist/core/secrets/secret-dotenv.d.ts +1 -1
- package/dist/core/secrets/secret-dotenv.js +1 -1
- package/dist/core/secrets/secret-dotenv.js.map +1 -1
- package/dist/core/settings-manager.d.ts +4 -2
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +9 -5
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tool-capability-policy.js +2 -2
- package/dist/core/tool-capability-policy.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +29 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +179 -28
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/git-filter.d.ts +1 -0
- package/dist/core/tools/git-filter.d.ts.map +1 -1
- package/dist/core/tools/git-filter.js +1 -1
- package/dist/core/tools/git-filter.js.map +1 -1
- package/dist/core/tools/profile-writer.js +3 -3
- package/dist/core/tools/profile-writer.js.map +1 -1
- package/dist/core/tools/python.d.ts +2 -0
- package/dist/core/tools/python.d.ts.map +1 -1
- package/dist/core/tools/python.js +17 -12
- package/dist/core/tools/python.js.map +1 -1
- package/dist/core/tools/run-process.d.ts +2 -0
- package/dist/core/tools/run-process.d.ts.map +1 -1
- package/dist/core/tools/run-process.js +7 -3
- package/dist/core/tools/run-process.js.map +1 -1
- package/dist/core/tools/secret-store.d.ts +8 -18
- package/dist/core/tools/secret-store.d.ts.map +1 -1
- package/dist/core/tools/secret-store.js +83 -348
- package/dist/core/tools/secret-store.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +38 -1
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +35 -14
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +26 -3
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/secret-menu-controller.d.ts +21 -0
- package/dist/modes/interactive/secret-menu-controller.d.ts.map +1 -0
- package/dist/modes/interactive/secret-menu-controller.js +276 -0
- package/dist/modes/interactive/secret-menu-controller.js.map +1 -0
- package/dist/utils/tools-manager.d.ts +2 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +43 -48
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/zip-extractor.d.ts +8 -0
- package/dist/utils/zip-extractor.d.ts.map +1 -0
- package/dist/utils/zip-extractor.js +275 -0
- package/dist/utils/zip-extractor.js.map +1 -0
- package/docs/harness-architecture.md +34 -22
- package/docs/index.md +1 -1
- package/docs/resources.md +1 -1
- package/docs/settings.md +39 -103
- package/docs/usage.md +7 -5
- package/docs/worker-profiles.md +9 -7
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
- package/dist/core/secrets/secret-vault-format.d.ts +0 -112
- package/dist/core/secrets/secret-vault-format.d.ts.map +0 -1
- package/dist/core/secrets/secret-vault-format.js +0 -396
- package/dist/core/secrets/secret-vault-format.js.map +0 -1
- package/dist/core/secrets/secret-vault.d.ts +0 -72
- package/dist/core/secrets/secret-vault.d.ts.map +0 -1
- package/dist/core/secrets/secret-vault.js +0 -663
- package/dist/core/secrets/secret-vault.js.map +0 -1
|
@@ -4,7 +4,7 @@ import { sanitizeToolFailureContext } from "@caupulican/pi-agent-core/tool-failu
|
|
|
4
4
|
import { addUsage, createEmptyUsage } from "@caupulican/pi-agent-core/usage";
|
|
5
5
|
import { safeRealpathSync } from "../autonomy/path-scope.js";
|
|
6
6
|
import { composeSubagentSystemPrompt } from "../autonomy/subagent-prompt.js";
|
|
7
|
-
import { attemptUsageFromGatewayUsage, EMPTY_ATTEMPT_USAGE
|
|
7
|
+
import { attemptUsageFromGatewayUsage, EMPTY_ATTEMPT_USAGE } from "../orchestration/attempt-usage.js";
|
|
8
8
|
import { WorkerActionJournal } from "./worker-action-journal.js";
|
|
9
9
|
import { runWorker } from "./worker-runner.js";
|
|
10
10
|
function recordAssistantUsage(surface, message) {
|
|
@@ -60,6 +60,15 @@ export function createWorkerAttemptExecutor(options) {
|
|
|
60
60
|
options.lifecycle.checkpoint(options.laneId, { summary, usage });
|
|
61
61
|
return usage;
|
|
62
62
|
};
|
|
63
|
+
const remainingAttemptTokens = () => options.toolSurface.gateway?.remainingAttemptTokenBudget();
|
|
64
|
+
const reserveProviderBudget = async (requestedMaxTokens, subject, signal) => {
|
|
65
|
+
if (options.toolSurface.gateway) {
|
|
66
|
+
return options.toolSurface.gateway.reserveProviderBudget(requestedMaxTokens, subject, signal);
|
|
67
|
+
}
|
|
68
|
+
if (signal?.aborted)
|
|
69
|
+
throw signal.reason;
|
|
70
|
+
return { maxTokens: requestedMaxTokens, release: () => undefined };
|
|
71
|
+
};
|
|
63
72
|
let failedCompactionUsage;
|
|
64
73
|
const retentionPolicy = options.retentionPolicy && {
|
|
65
74
|
...options.retentionPolicy,
|
|
@@ -72,8 +81,8 @@ export function createWorkerAttemptExecutor(options) {
|
|
|
72
81
|
throw new Error("Worker compaction attempted to select a model outside the lane binding.");
|
|
73
82
|
}
|
|
74
83
|
options.toolSurface.gateway?.assertBudgetAvailable("worker_compaction_provider_completion");
|
|
75
|
-
const
|
|
76
|
-
if (
|
|
84
|
+
const availableTokens = remainingAttemptTokens();
|
|
85
|
+
if (availableTokens !== undefined && availableTokens <= 0) {
|
|
77
86
|
throw new Error("Worker token budget exhausted before compaction provider completion.");
|
|
78
87
|
}
|
|
79
88
|
const requestedMaxTokens = requestOptions.maxTokens;
|
|
@@ -82,47 +91,48 @@ export function createWorkerAttemptExecutor(options) {
|
|
|
82
91
|
requestedMaxTokens > 0
|
|
83
92
|
? requestedMaxTokens
|
|
84
93
|
: options.laneCapability.laneMaxOutputTokens;
|
|
85
|
-
const maxTokens = Math.min(configuredMaxTokens,
|
|
94
|
+
const maxTokens = Math.min(configuredMaxTokens, availableTokens ?? configuredMaxTokens);
|
|
86
95
|
if (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) {
|
|
87
96
|
throw new Error("Worker compaction provider completion has no valid remaining token budget.");
|
|
88
97
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
98
|
+
let reservation;
|
|
99
|
+
try {
|
|
100
|
+
const completion = await options.runIsolatedCompletion({
|
|
101
|
+
systemPrompt: context.systemPrompt ?? "",
|
|
102
|
+
messages: context.messages,
|
|
103
|
+
model: options.model,
|
|
104
|
+
thinkingLevel: options.thinkingLevel,
|
|
105
|
+
maxTokens,
|
|
106
|
+
requestPreflight: async () => {
|
|
107
|
+
reservation?.release();
|
|
108
|
+
reservation = await reserveProviderBudget(maxTokens, "worker_compaction_provider_completion", requestOptions.signal ?? options.signal);
|
|
109
|
+
return { maxTokens: reservation.maxTokens };
|
|
110
|
+
},
|
|
111
|
+
signal: requestOptions.signal ?? options.signal,
|
|
112
|
+
cacheRetention: "none",
|
|
113
|
+
laneKind: "worker-compaction",
|
|
114
|
+
});
|
|
115
|
+
addUsage(compactionUsage, completion.usage);
|
|
116
|
+
const response = {
|
|
117
|
+
role: "assistant",
|
|
118
|
+
content: completion.text ? [{ type: "text", text: completion.text }] : [],
|
|
119
|
+
api: options.model.api,
|
|
120
|
+
provider: options.model.provider,
|
|
121
|
+
model: options.model.id,
|
|
122
|
+
usage: completion.usage,
|
|
123
|
+
stopReason: completion.stopReason,
|
|
124
|
+
timestamp: Date.now(),
|
|
125
|
+
...(completion.stopReason === "error"
|
|
126
|
+
? { errorMessage: completion.text || "Worker compaction provider request failed." }
|
|
127
|
+
: {}),
|
|
128
|
+
};
|
|
129
|
+
recordAssistantUsage(options.toolSurface, response);
|
|
130
|
+
checkpointUsage("Persisted worker compaction provider usage before verification.");
|
|
131
|
+
return response;
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
reservation?.release();
|
|
135
|
+
}
|
|
126
136
|
},
|
|
127
137
|
});
|
|
128
138
|
},
|
|
@@ -151,6 +161,7 @@ export function createWorkerAttemptExecutor(options) {
|
|
|
151
161
|
signal: options.signal,
|
|
152
162
|
cwd: options.cwd,
|
|
153
163
|
processCapable: options.processCapable,
|
|
164
|
+
delegationCapable: options.toolSurface.allowedTools.includes("delegate"),
|
|
154
165
|
...(options.verificationSubjectTaskId
|
|
155
166
|
? { verificationSubjectTaskId: options.verificationSubjectTaskId }
|
|
156
167
|
: {}),
|
|
@@ -175,6 +186,11 @@ export function createWorkerAttemptExecutor(options) {
|
|
|
175
186
|
}
|
|
176
187
|
const persistedToolAssistantIds = new Set();
|
|
177
188
|
const pendingToolAssistants = new Map();
|
|
189
|
+
let providerReservation;
|
|
190
|
+
const releaseProviderReservation = () => {
|
|
191
|
+
providerReservation?.release();
|
|
192
|
+
providerReservation = undefined;
|
|
193
|
+
};
|
|
178
194
|
const persistToolRequest = (message) => {
|
|
179
195
|
const toolCallIds = message.content.flatMap((content) => content.type === "toolCall" ? [content.id] : []);
|
|
180
196
|
if (toolCallIds.length === 0 || toolCallIds.every((id) => persistedToolAssistantIds.has(id)))
|
|
@@ -186,10 +202,11 @@ export function createWorkerAttemptExecutor(options) {
|
|
|
186
202
|
pendingToolAssistants.delete(id);
|
|
187
203
|
}
|
|
188
204
|
checkpointUsage("Persisted worker assistant tool request and its cumulative provider usage.");
|
|
205
|
+
releaseProviderReservation();
|
|
189
206
|
};
|
|
190
207
|
options.toolSurface.gateway?.assertBudgetAvailable("worker_provider_completion");
|
|
191
|
-
const
|
|
192
|
-
if (
|
|
208
|
+
const availableTokens = remainingAttemptTokens();
|
|
209
|
+
if (availableTokens !== undefined && availableTokens <= 0) {
|
|
193
210
|
throw new Error("Worker token budget exhausted before provider completion.");
|
|
194
211
|
}
|
|
195
212
|
let history = options.conversation.getProviderMessages();
|
|
@@ -201,128 +218,130 @@ export function createWorkerAttemptExecutor(options) {
|
|
|
201
218
|
});
|
|
202
219
|
history = options.conversation.getProviderMessages();
|
|
203
220
|
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
options.toolSurface.
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
221
|
+
let completion;
|
|
222
|
+
try {
|
|
223
|
+
completion = await options.runIsolatedCompletion({
|
|
224
|
+
systemPrompt: composeSubagentSystemPrompt({
|
|
225
|
+
soul: options.soul,
|
|
226
|
+
rolePrompt: [systemPrompt, options.workerResourceSystemPrompt].filter(Boolean).join("\n\n"),
|
|
227
|
+
}),
|
|
228
|
+
history,
|
|
229
|
+
messages: [],
|
|
230
|
+
model: options.model,
|
|
231
|
+
thinkingLevel: options.thinkingLevel,
|
|
232
|
+
maxTokens: Math.min(options.laneCapability.laneMaxOutputTokens, availableTokens ?? Number.POSITIVE_INFINITY),
|
|
233
|
+
tools: options.toolSurface.tools,
|
|
234
|
+
requestPreflight: async () => {
|
|
235
|
+
releaseProviderReservation();
|
|
236
|
+
providerReservation = await reserveProviderBudget(options.laneCapability.laneMaxOutputTokens, "worker_provider_completion", signal);
|
|
237
|
+
return { maxTokens: providerReservation.maxTokens };
|
|
238
|
+
},
|
|
239
|
+
beforeToolCall: async (context, toolSignal) => {
|
|
240
|
+
persistToolRequest(context.assistantMessage);
|
|
241
|
+
const decision = await options.toolSurface.beforeToolCall(context, toolSignal);
|
|
242
|
+
if (decision?.block) {
|
|
243
|
+
toolIssues.add(`${context.toolCall.name} blocked: ${decision.reason ?? "capability denied"}`);
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
checkpointUsage(`Authorized worker tool '${context.toolCall.name}' under its durable grant.`);
|
|
247
|
+
}
|
|
248
|
+
return decision;
|
|
249
|
+
},
|
|
250
|
+
afterToolCall: async ({ toolCall, args, isError }) => {
|
|
251
|
+
if ((toolCall.name === "write" || toolCall.name === "edit") &&
|
|
252
|
+
args &&
|
|
253
|
+
typeof args === "object" &&
|
|
254
|
+
!Array.isArray(args)) {
|
|
255
|
+
const rawPath = args.path;
|
|
256
|
+
if (typeof rawPath === "string" && rawPath.length > 0) {
|
|
257
|
+
const absolutePath = path.isAbsolute(rawPath)
|
|
258
|
+
? path.resolve(rawPath)
|
|
259
|
+
: path.resolve(options.cwd, rawPath);
|
|
260
|
+
let canonicalPath = absolutePath;
|
|
261
|
+
try {
|
|
262
|
+
canonicalPath = safeRealpathSync(absolutePath);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
// The operation entered execution; retain its lexical target if canonicalization failed.
|
|
266
|
+
}
|
|
267
|
+
recordChangedFile(path.relative(options.cwd, canonicalPath).split(path.sep).join("/"));
|
|
249
268
|
}
|
|
250
|
-
|
|
251
|
-
|
|
269
|
+
}
|
|
270
|
+
if (isError)
|
|
271
|
+
toolIssues.add(`${toolCall.name} failed during isolated execution`);
|
|
272
|
+
return undefined;
|
|
273
|
+
},
|
|
274
|
+
onMessage: (message) => {
|
|
275
|
+
if (message.role === "assistant" && isToolRequest(message)) {
|
|
276
|
+
// Known calls are normalized before beforeToolCall and persist from that hook.
|
|
277
|
+
// Retain the request only so immediate unknown/malformed results can close the
|
|
278
|
+
// transcript without freezing pre-repair arguments into durable history.
|
|
279
|
+
for (const content of message.content) {
|
|
280
|
+
if (content.type === "toolCall")
|
|
281
|
+
pendingToolAssistants.set(content.id, message);
|
|
252
282
|
}
|
|
253
|
-
|
|
283
|
+
return;
|
|
254
284
|
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
},
|
|
260
|
-
onMessage: (message) => {
|
|
261
|
-
if (message.role === "assistant" && isToolRequest(message)) {
|
|
262
|
-
// Known calls are normalized before beforeToolCall and persist from that hook.
|
|
263
|
-
// Retain the request only so immediate unknown/malformed results can close the
|
|
264
|
-
// transcript without freezing pre-repair arguments into durable history.
|
|
265
|
-
for (const content of message.content) {
|
|
266
|
-
if (content.type === "toolCall")
|
|
267
|
-
pendingToolAssistants.set(content.id, message);
|
|
285
|
+
if (message.role === "toolResult" && !persistedToolAssistantIds.has(message.toolCallId)) {
|
|
286
|
+
const pending = pendingToolAssistants.get(message.toolCallId);
|
|
287
|
+
if (pending)
|
|
288
|
+
persistToolRequest(pending);
|
|
268
289
|
}
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
if (
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
290
|
+
if (message.role === "assistant")
|
|
291
|
+
recordAssistantUsage(options.toolSurface, message);
|
|
292
|
+
options.conversation.appendMessage(message);
|
|
293
|
+
options.agentControl.acknowledgeMailboxMessage(options.agentId, message);
|
|
294
|
+
if (message.role === "assistant") {
|
|
295
|
+
checkpointUsage("Persisted worker assistant response and its cumulative provider usage.");
|
|
296
|
+
releaseProviderReservation();
|
|
297
|
+
}
|
|
298
|
+
if (message.role === "toolResult")
|
|
299
|
+
checkpointUsage(`Persisted worker tool result '${message.toolCallId}'.`);
|
|
300
|
+
},
|
|
301
|
+
getSteeringMessages: async () => {
|
|
302
|
+
const includeFollowUp = firstMailboxPoll;
|
|
303
|
+
firstMailboxPoll = false;
|
|
304
|
+
return options.agentControl.mailboxMessagesForConversation(options.agentId, options.conversation, includeFollowUp);
|
|
305
|
+
},
|
|
306
|
+
getFollowUpMessages: async () => options.agentControl.mailboxMessagesForConversation(options.agentId, options.conversation, true),
|
|
307
|
+
...(retentionPolicy
|
|
308
|
+
? {
|
|
309
|
+
transformContext: async (messages) => {
|
|
310
|
+
try {
|
|
311
|
+
const retained = await options.conversation.compactProviderContext(retentionPolicy, options.signal);
|
|
312
|
+
if (retained.status === "compacted_verified" ||
|
|
313
|
+
retained.status === "compacted_deterministic") {
|
|
314
|
+
providerContextCompacted = true;
|
|
315
|
+
}
|
|
316
|
+
if (retained.contextUsage.tokens > retentionPolicy.maxContextTokens &&
|
|
317
|
+
!retentionWarningEmitted) {
|
|
318
|
+
retentionWarningEmitted = true;
|
|
319
|
+
options.warn(`Worker ${options.laneId} has one retained turn larger than its context policy; provider overflow recovery may be required.`);
|
|
320
|
+
}
|
|
321
|
+
if (retained.status !== "compacted_verified" &&
|
|
322
|
+
retained.status !== "compacted_deterministic") {
|
|
323
|
+
return messages;
|
|
324
|
+
}
|
|
325
|
+
return sanitizeToolFailureContext(retained.context.messages, "").messages;
|
|
305
326
|
}
|
|
306
|
-
|
|
307
|
-
|
|
327
|
+
catch (error) {
|
|
328
|
+
if (!retentionWarningEmitted) {
|
|
329
|
+
retentionWarningEmitted = true;
|
|
330
|
+
options.warn(`Worker context retention failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
331
|
+
}
|
|
308
332
|
return messages;
|
|
309
333
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
: {}),
|
|
322
|
-
signal,
|
|
323
|
-
cacheRetention: "short",
|
|
324
|
-
laneKind: "worker",
|
|
325
|
-
});
|
|
334
|
+
},
|
|
335
|
+
}
|
|
336
|
+
: {}),
|
|
337
|
+
signal,
|
|
338
|
+
cacheRetention: "short",
|
|
339
|
+
laneKind: "worker",
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
finally {
|
|
343
|
+
releaseProviderReservation();
|
|
344
|
+
}
|
|
326
345
|
if (!providerContextCompacted) {
|
|
327
346
|
options.conversation.commitTranscript(completion.messages ?? options.conversation.getProviderMessages());
|
|
328
347
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-attempt-executor.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-attempt-executor.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,MAAM,iDAAiD,CAAC;AAC1E,OAAO,EAAE,0BAA0B,EAAE,MAAM,+CAA+C,CAAC;AAE3F,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAK7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAE7E,OAAO,EACN,4BAA4B,EAC5B,mBAAmB,EACnB,oBAAoB,GACpB,MAAM,mCAAmC,CAAC;AAG3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAMjE,OAAO,EAAE,SAAS,EAAyB,MAAM,oBAAoB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AAO;wBACN,IAAI,EAAE,UAAU,CAAC,IAAI;wBACrB,OAAO,EAAE,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK;wBACpC,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC;wBACzC,YAAY,EAAE,CAAC,GAAG,YAAY,CAAC;wBAC/B,QAAQ,EAAE,CAAC,GAAG,UAAU,CAAC;qBACzB,CAAC;gBACH,CAAC;aACD,CAAC,CAAC;YACH,MAAM,KAAK,GAAG,eAAe,CAAC,iEAAiE,CAAC,CAAC;YACjG,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC,GAAG,YAAY,CAAC,EAAE,CAAC;QAC/D,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import path from \"node:path\";\nimport { compact } from \"@caupulican/pi-agent-core/compaction/compaction\";\nimport { sanitizeToolFailureContext } from \"@caupulican/pi-agent-core/tool-failure-memory\";\nimport type { AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core/types\";\nimport { addUsage, createEmptyUsage } from \"@caupulican/pi-agent-core/usage\";\nimport type { Api, AssistantMessage, Message, Model, Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"../agent-session-contracts.ts\";\nimport type { WorkerRequest } from \"../autonomy/contracts.ts\";\nimport type { LaneToolSurface } from \"../autonomy/lane-tool-surface.ts\";\nimport { safeRealpathSync } from \"../autonomy/path-scope.ts\";\nimport { composeSubagentSystemPrompt } from \"../autonomy/subagent-prompt.ts\";\nimport type { ModelCapabilityProfile } from \"../model-capability.ts\";\nimport {\n\tattemptUsageFromGatewayUsage,\n\tEMPTY_ATTEMPT_USAGE,\n\tremainingTokenBudget,\n} from \"../orchestration/attempt-usage.ts\";\nimport type { AttemptUsageSnapshot, ExecutionGrant } from \"../orchestration/contracts.ts\";\nimport type { StartedDelegationAttempt } from \"../orchestration/delegation-ledger.ts\";\nimport { WorkerActionJournal } from \"./worker-action-journal.ts\";\nimport type { AppliedActionsReport, WorkerAction } from \"./worker-actions.ts\";\nimport type { WorkerAgentControlCoordinator } from \"./worker-agent-control-coordinator.ts\";\nimport type { WorkerConversation, WorkerConversationRetentionPolicy } from \"./worker-conversation-store.ts\";\nimport type { WorkerExecutionPlan } from \"./worker-execution-policy.ts\";\nimport type { WorkerLifecycle } from \"./worker-lifecycle.ts\";\nimport { runWorker, type WorkerRunOutcome } from \"./worker-runner.ts\";\n\nexport interface RecoveredWorkerTerminalCompletion {\n\ttext: string;\n\tusage: Usage;\n\tstopReason: string;\n}\n\n/** The live mutable state that must be visible to session disposal before provider work yields. */\nexport interface WorkerAttemptExecutionLedger {\n\tchangedFiles: Set<string>;\n\tgetUsage(): AttemptUsageSnapshot;\n}\n\nexport interface WorkerAttemptExecutionResult {\n\trawOutcome: WorkerRunOutcome;\n\tusage: AttemptUsageSnapshot;\n\tchangedFiles: readonly string[];\n}\n\n/**\n * The provider/tool-loop portion of a prepared worker attempt.\n *\n * Admission, durable leasing, grant compilation, terminalization, notification, verification, and\n * scheduling remain outside this boundary. This unit owns only the ordered child conversation:\n * persist assistant tool requests before execution, append messages before mailbox acknowledgements,\n * checkpoint cumulative usage before later boundaries, and compact only the provider projection.\n */\nexport interface WorkerAttemptExecutorOptions {\n\trequest: WorkerRequest;\n\tgrant: ExecutionGrant;\n\texecutionPlan: WorkerExecutionPlan;\n\ttoolSurface: LaneToolSurface;\n\tconversation: WorkerConversation;\n\tlifecycle: Pick<WorkerLifecycle, \"checkpoint\">;\n\tlaneId: string;\n\tagentId: string;\n\tdurableHandle: StartedDelegationAttempt;\n\tparentSessionId: string;\n\tagentDir: string;\n\tcwd: string;\n\tmodel: Model<Api>;\n\tthinkingLevel?: ThinkingLevel;\n\tlaneCapability: Pick<ModelCapabilityProfile, \"laneMaxOutputTokens\">;\n\tsoul?: string;\n\tworkerResourceSystemPrompt: string;\n\tinitialUsage: AttemptUsageSnapshot;\n\thasPersistedUsageCheckpoint: boolean;\n\tusageReportId: string;\n\tprocessCapable: boolean;\n\tverificationSubjectTaskId?: string;\n\trecoveredTerminal?: RecoveredWorkerTerminalCompletion;\n\tretentionPolicy?: WorkerConversationRetentionPolicy;\n\tsignal?: AbortSignal;\n\trunIsolatedCompletion(options: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\tagentControl: Pick<WorkerAgentControlCoordinator, \"acknowledgeMailboxMessage\" | \"mailboxMessagesForConversation\">;\n\tapplyActions?(actions: readonly WorkerAction[], actionJournal?: WorkerActionJournal): AppliedActionsReport;\n\twarn(message: string): void;\n}\n\nfunction recordAssistantUsage(surface: LaneToolSurface, message: Extract<Message, { role: \"assistant\" }>): void {\n\tsurface.gateway?.recordUsage({\n\t\tinputTokens: message.usage.input,\n\t\toutputTokens: message.usage.output,\n\t\tcacheReadTokens: message.usage.cacheRead,\n\t\tcacheWriteTokens: message.usage.cacheWrite,\n\t\ttotalTokens: message.usage.totalTokens,\n\t\tcostUsd: message.usage.cost.total,\n\t});\n}\n\nfunction isToolRequest(message: Message): boolean {\n\treturn message.role === \"assistant\" && message.content.some((content) => content.type === \"toolCall\");\n}\n\n/**\n * Constructs one execution exactly once. The caller registers {@link ledger} before calling\n * {@link run}, allowing synchronous disposal to observe mutations and cumulative usage while the\n * provider/tool loop is suspended.\n */\nexport function createWorkerAttemptExecutor(options: WorkerAttemptExecutorOptions): {\n\tledger: WorkerAttemptExecutionLedger;\n\tcheckpointUsage(summary: string): AttemptUsageSnapshot;\n\trun(): Promise<WorkerAttemptExecutionResult>;\n} {\n\tconst changedFiles = new Set(options.conversation.getChangedFiles(options.durableHandle.attemptId));\n\tconst toolIssues = new Set<string>();\n\tconst recordChangedFile = (filePath: string): void => {\n\t\tchangedFiles.add(filePath);\n\t\ttry {\n\t\t\toptions.conversation.recordChangedFile(options.durableHandle.attemptId, filePath);\n\t\t} catch (error) {\n\t\t\ttoolIssues.add(\"worker changed-file progress could not be persisted; parent review is required\");\n\t\t\toptions.warn(\n\t\t\t\t`Worker changed-file progress persistence failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t};\n\tconst actionJournal = options.request.envelope.capabilities.includes(\"filesystem.write\")\n\t\t? new WorkerActionJournal({\n\t\t\t\tagentDir: options.agentDir,\n\t\t\t\tparentSessionId: options.parentSessionId,\n\t\t\t\ttaskId: options.durableHandle.taskId,\n\t\t\t\tattemptId: options.durableHandle.attemptId,\n\t\t\t\tfencingToken: options.durableHandle.fencingToken,\n\t\t\t})\n\t\t: undefined;\n\tlet providerContextCompacted = options.conversation.hasProviderCompaction();\n\tlet retentionWarningEmitted = false;\n\tlet firstMailboxPoll = true;\n\tlet ran = false;\n\n\tconst currentUsage = (): AttemptUsageSnapshot =>\n\t\tattemptUsageFromGatewayUsage(\n\t\t\toptions.toolSurface.gateway?.getUsage() ?? {\n\t\t\t\t...EMPTY_ATTEMPT_USAGE,\n\t\t\t\twallClockMs: options.initialUsage.activeWallClockMs,\n\t\t\t},\n\t\t);\n\tconst checkpointUsage = (summary: string): AttemptUsageSnapshot => {\n\t\tconst usage = currentUsage();\n\t\toptions.lifecycle.checkpoint(options.laneId, { summary, usage });\n\t\treturn usage;\n\t};\n\tlet failedCompactionUsage: Usage | undefined;\n\tconst retentionPolicy = options.retentionPolicy && {\n\t\t...options.retentionPolicy,\n\t\tgenerateVerifiedCompaction: async (preparation: Parameters<typeof compact>[0]) => {\n\t\t\tconst compactionUsage = createEmptyUsage();\n\t\t\tfailedCompactionUsage = compactionUsage;\n\t\t\treturn compact(\n\t\t\t\tpreparation,\n\t\t\t\toptions.model,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\toptions.signal,\n\t\t\t\toptions.thinkingLevel,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t{\n\t\t\t\t\tcompletion: async (model, context, requestOptions): Promise<AssistantMessage> => {\n\t\t\t\t\t\tif (model.provider !== options.model.provider || model.id !== options.model.id) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker compaction attempted to select a model outside the lane binding.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_compaction_provider_completion\");\n\t\t\t\t\t\tconst remainingTokens = remainingTokenBudget(options.grant.budget.maxTokens, currentUsage());\n\t\t\t\t\t\tif (remainingTokens !== undefined && remainingTokens <= 0) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before compaction provider completion.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst requestedMaxTokens = requestOptions.maxTokens;\n\t\t\t\t\t\tconst configuredMaxTokens =\n\t\t\t\t\t\t\ttypeof requestedMaxTokens === \"number\" &&\n\t\t\t\t\t\t\tNumber.isSafeInteger(requestedMaxTokens) &&\n\t\t\t\t\t\t\trequestedMaxTokens > 0\n\t\t\t\t\t\t\t\t? requestedMaxTokens\n\t\t\t\t\t\t\t\t: options.laneCapability.laneMaxOutputTokens;\n\t\t\t\t\t\tconst maxTokens = Math.min(configuredMaxTokens, remainingTokens ?? configuredMaxTokens);\n\t\t\t\t\t\tif (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker compaction provider completion has no valid remaining token budget.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst completion = await options.runIsolatedCompletion({\n\t\t\t\t\t\t\tsystemPrompt: context.systemPrompt ?? \"\",\n\t\t\t\t\t\t\tmessages: context.messages,\n\t\t\t\t\t\t\tmodel: options.model,\n\t\t\t\t\t\t\tthinkingLevel: options.thinkingLevel,\n\t\t\t\t\t\t\tmaxTokens,\n\t\t\t\t\t\t\trequestPreflight: async () => {\n\t\t\t\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_compaction_provider_completion\");\n\t\t\t\t\t\t\t\tconst requestRemainingTokens = remainingTokenBudget(\n\t\t\t\t\t\t\t\t\toptions.grant.budget.maxTokens,\n\t\t\t\t\t\t\t\t\tcurrentUsage(),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (requestRemainingTokens !== undefined && requestRemainingTokens <= 0) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before compaction provider completion.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tmaxTokens: Math.min(maxTokens, requestRemainingTokens ?? maxTokens),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tsignal: requestOptions.signal ?? options.signal,\n\t\t\t\t\t\t\tcacheRetention: \"none\",\n\t\t\t\t\t\t\tlaneKind: \"worker-compaction\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\taddUsage(compactionUsage, completion.usage);\n\t\t\t\t\t\tconst response: AssistantMessage = {\n\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t\tcontent: completion.text ? [{ type: \"text\", text: completion.text }] : [],\n\t\t\t\t\t\t\tapi: options.model.api,\n\t\t\t\t\t\t\tprovider: options.model.provider,\n\t\t\t\t\t\t\tmodel: options.model.id,\n\t\t\t\t\t\t\tusage: completion.usage,\n\t\t\t\t\t\t\tstopReason: completion.stopReason,\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\t...(completion.stopReason === \"error\"\n\t\t\t\t\t\t\t\t? { errorMessage: completion.text || \"Worker compaction provider request failed.\" }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t\trecordAssistantUsage(options.toolSurface, response);\n\t\t\t\t\t\tcheckpointUsage(\"Persisted worker compaction provider usage before verification.\");\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tgetFailedCompactionUsage: () => failedCompactionUsage,\n\t};\n\tconst ledger: WorkerAttemptExecutionLedger = {\n\t\tchangedFiles,\n\t\tgetUsage: currentUsage,\n\t};\n\n\treturn {\n\t\tledger,\n\t\tcheckpointUsage,\n\t\tasync run(): Promise<WorkerAttemptExecutionResult> {\n\t\t\tif (ran) throw new Error(\"A worker attempt executor may run only once.\");\n\t\t\tran = true;\n\t\t\tif (!options.hasPersistedUsageCheckpoint) {\n\t\t\t\tcheckpointUsage(\"Persisted deterministic cumulative usage baseline for the durable worker transcript.\");\n\t\t\t}\n\t\t\tconst rawOutcome = await runWorker({\n\t\t\t\trequest: options.request,\n\t\t\t\tmaxUsd: options.grant.budget.maxCostUsd,\n\t\t\t\tmaxWallClockMs: options.grant.budget.maxWallClockMs ?? 0,\n\t\t\t\tusageReportId: options.usageReportId,\n\t\t\t\tgetChangedFiles: () => [...changedFiles],\n\t\t\t\tsignal: options.signal,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tprocessCapable: options.processCapable,\n\t\t\t\t...(options.verificationSubjectTaskId\n\t\t\t\t\t? { verificationSubjectTaskId: options.verificationSubjectTaskId }\n\t\t\t\t\t: {}),\n\t\t\t\t...(options.applyActions\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tapplyActions: (actions: readonly WorkerAction[]) => {\n\t\t\t\t\t\t\t\tconst report = options.applyActions!(actions, actionJournal);\n\t\t\t\t\t\t\t\tfor (const filePath of report.changedFiles) recordChangedFile(filePath);\n\t\t\t\t\t\t\t\treturn report;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tif (options.recoveredTerminal) {\n\t\t\t\t\t\tcheckpointUsage(\"Reused the persisted terminal worker assistant response after recovery.\");\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: options.recoveredTerminal.text,\n\t\t\t\t\t\t\tcostUsd: options.initialUsage.costUsd,\n\t\t\t\t\t\t\tstopReason: options.recoveredTerminal.stopReason,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst persistedToolAssistantIds = new Set<string>();\n\t\t\t\t\tconst pendingToolAssistants = new Map<string, AssistantMessage>();\n\t\t\t\t\tconst persistToolRequest = (message: AssistantMessage): void => {\n\t\t\t\t\t\tconst toolCallIds = message.content.flatMap((content) =>\n\t\t\t\t\t\t\tcontent.type === \"toolCall\" ? [content.id] : [],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (toolCallIds.length === 0 || toolCallIds.every((id) => persistedToolAssistantIds.has(id))) return;\n\t\t\t\t\t\trecordAssistantUsage(options.toolSurface, message);\n\t\t\t\t\t\toptions.conversation.appendMessage(message);\n\t\t\t\t\t\tfor (const id of toolCallIds) {\n\t\t\t\t\t\t\tpersistedToolAssistantIds.add(id);\n\t\t\t\t\t\t\tpendingToolAssistants.delete(id);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckpointUsage(\"Persisted worker assistant tool request and its cumulative provider usage.\");\n\t\t\t\t\t};\n\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_provider_completion\");\n\t\t\t\t\tconst remainingTokens = remainingTokenBudget(options.grant.budget.maxTokens, currentUsage());\n\t\t\t\t\tif (remainingTokens !== undefined && remainingTokens <= 0) {\n\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before provider completion.\");\n\t\t\t\t\t}\n\t\t\t\t\tlet history = options.conversation.getProviderMessages();\n\t\t\t\t\tif (history.length === 0) {\n\t\t\t\t\t\toptions.conversation.appendMessage({\n\t\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: userPrompt }],\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\thistory = options.conversation.getProviderMessages();\n\t\t\t\t\t}\n\t\t\t\t\tconst completion = await options.runIsolatedCompletion({\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: options.soul,\n\t\t\t\t\t\t\trolePrompt: [systemPrompt, options.workerResourceSystemPrompt].filter(Boolean).join(\"\\n\\n\"),\n\t\t\t\t\t\t}),\n\t\t\t\t\t\thistory,\n\t\t\t\t\t\tmessages: [],\n\t\t\t\t\t\tmodel: options.model,\n\t\t\t\t\t\tthinkingLevel: options.thinkingLevel,\n\t\t\t\t\t\tmaxTokens: Math.min(\n\t\t\t\t\t\t\toptions.laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\t\tremainingTokens ?? Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t),\n\t\t\t\t\t\ttools: options.toolSurface.tools,\n\t\t\t\t\t\trequestPreflight: async () => {\n\t\t\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_provider_completion\");\n\t\t\t\t\t\t\tconst requestRemainingTokens = remainingTokenBudget(\n\t\t\t\t\t\t\t\toptions.grant.budget.maxTokens,\n\t\t\t\t\t\t\t\tcurrentUsage(),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (requestRemainingTokens !== undefined && requestRemainingTokens <= 0) {\n\t\t\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before provider completion.\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tmaxTokens: Math.min(\n\t\t\t\t\t\t\t\t\toptions.laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\t\t\t\trequestRemainingTokens ?? Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbeforeToolCall: async (context, toolSignal) => {\n\t\t\t\t\t\t\tpersistToolRequest(context.assistantMessage);\n\t\t\t\t\t\t\tconst decision = await options.toolSurface.beforeToolCall(context, toolSignal);\n\t\t\t\t\t\t\tif (decision?.block) {\n\t\t\t\t\t\t\t\ttoolIssues.add(`${context.toolCall.name} blocked: ${decision.reason ?? \"capability denied\"}`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcheckpointUsage(`Authorized worker tool '${context.toolCall.name}' under its durable grant.`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn decision;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tafterToolCall: async ({ toolCall, args, isError }) => {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t(toolCall.name === \"write\" || toolCall.name === \"edit\") &&\n\t\t\t\t\t\t\t\targs &&\n\t\t\t\t\t\t\t\ttypeof args === \"object\" &&\n\t\t\t\t\t\t\t\t!Array.isArray(args)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tconst rawPath = (args as Record<string, unknown>).path;\n\t\t\t\t\t\t\t\tif (typeof rawPath === \"string\" && rawPath.length > 0) {\n\t\t\t\t\t\t\t\t\tconst absolutePath = path.isAbsolute(rawPath)\n\t\t\t\t\t\t\t\t\t\t? path.resolve(rawPath)\n\t\t\t\t\t\t\t\t\t\t: path.resolve(options.cwd, rawPath);\n\t\t\t\t\t\t\t\t\tlet canonicalPath = absolutePath;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tcanonicalPath = safeRealpathSync(absolutePath);\n\t\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\t\t// The operation entered execution; retain its lexical target if canonicalization failed.\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\trecordChangedFile(path.relative(options.cwd, canonicalPath).split(path.sep).join(\"/\"));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (isError) toolIssues.add(`${toolCall.name} failed during isolated execution`);\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tonMessage: (message) => {\n\t\t\t\t\t\t\tif (message.role === \"assistant\" && isToolRequest(message)) {\n\t\t\t\t\t\t\t\t// Known calls are normalized before beforeToolCall and persist from that hook.\n\t\t\t\t\t\t\t\t// Retain the request only so immediate unknown/malformed results can close the\n\t\t\t\t\t\t\t\t// transcript without freezing pre-repair arguments into durable history.\n\t\t\t\t\t\t\t\tfor (const content of message.content) {\n\t\t\t\t\t\t\t\t\tif (content.type === \"toolCall\") pendingToolAssistants.set(content.id, message);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (message.role === \"toolResult\" && !persistedToolAssistantIds.has(message.toolCallId)) {\n\t\t\t\t\t\t\t\tconst pending = pendingToolAssistants.get(message.toolCallId);\n\t\t\t\t\t\t\t\tif (pending) persistToolRequest(pending);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (message.role === \"assistant\") recordAssistantUsage(options.toolSurface, message);\n\t\t\t\t\t\t\toptions.conversation.appendMessage(message);\n\t\t\t\t\t\t\toptions.agentControl.acknowledgeMailboxMessage(options.agentId, message);\n\t\t\t\t\t\t\tif (message.role === \"assistant\") {\n\t\t\t\t\t\t\t\tcheckpointUsage(\"Persisted worker assistant response and its cumulative provider usage.\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (message.role === \"toolResult\")\n\t\t\t\t\t\t\t\tcheckpointUsage(`Persisted worker tool result '${message.toolCallId}'.`);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgetSteeringMessages: async (): Promise<AgentMessage[]> => {\n\t\t\t\t\t\t\tconst includeFollowUp = firstMailboxPoll;\n\t\t\t\t\t\t\tfirstMailboxPoll = false;\n\t\t\t\t\t\t\treturn options.agentControl.mailboxMessagesForConversation(\n\t\t\t\t\t\t\t\toptions.agentId,\n\t\t\t\t\t\t\t\toptions.conversation,\n\t\t\t\t\t\t\t\tincludeFollowUp,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgetFollowUpMessages: async (): Promise<AgentMessage[]> =>\n\t\t\t\t\t\t\toptions.agentControl.mailboxMessagesForConversation(options.agentId, options.conversation, true),\n\t\t\t\t\t\t...(retentionPolicy\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\ttransformContext: async (messages: AgentMessage[]) => {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tconst retained = await options.conversation.compactProviderContext(\n\t\t\t\t\t\t\t\t\t\t\t\tretentionPolicy,\n\t\t\t\t\t\t\t\t\t\t\t\toptions.signal,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status === \"compacted_verified\" ||\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status === \"compacted_deterministic\"\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\tproviderContextCompacted = true;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tretained.contextUsage.tokens > retentionPolicy.maxContextTokens &&\n\t\t\t\t\t\t\t\t\t\t\t\t!retentionWarningEmitted\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\tretentionWarningEmitted = true;\n\t\t\t\t\t\t\t\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t\t\t\t\t\t\t\t`Worker ${options.laneId} has one retained turn larger than its context policy; provider overflow recovery may be required.`,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status !== \"compacted_verified\" &&\n\t\t\t\t\t\t\t\t\t\t\t\tretained.status !== \"compacted_deterministic\"\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn messages;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn sanitizeToolFailureContext(retained.context.messages, \"\").messages;\n\t\t\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\t\t\tif (!retentionWarningEmitted) {\n\t\t\t\t\t\t\t\t\t\t\t\tretentionWarningEmitted = true;\n\t\t\t\t\t\t\t\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t\t\t\t\t\t\t\t`Worker context retention failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn messages;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t\tlaneKind: \"worker\",\n\t\t\t\t\t});\n\t\t\t\t\tif (!providerContextCompacted) {\n\t\t\t\t\t\toptions.conversation.commitTranscript(\n\t\t\t\t\t\t\tcompletion.messages ?? options.conversation.getProviderMessages(),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcheckpointUsage(\n\t\t\t\t\t\t`Persisted worker conversation through ${options.conversation.getProviderContext().messages.length} messages.`,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t\tchangedFiles: [...changedFiles],\n\t\t\t\t\t\tblockers: [...toolIssues],\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst usage = checkpointUsage(\"Persisted final cumulative worker usage before terminal result.\");\n\t\t\treturn { rawOutcome, usage, changedFiles: [...changedFiles] };\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"worker-attempt-executor.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-attempt-executor.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,MA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,EAAE,YAAY,EAAE,CAAC,GAAG,YAAY,CAAC,EAAE,CAAC;QAC/D,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import path from \"node:path\";\nimport { compact } from \"@caupulican/pi-agent-core/compaction/compaction\";\nimport { sanitizeToolFailureContext } from \"@caupulican/pi-agent-core/tool-failure-memory\";\nimport type { AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core/types\";\nimport { addUsage, createEmptyUsage } from \"@caupulican/pi-agent-core/usage\";\nimport type { Api, AssistantMessage, Message, Model, Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"../agent-session-contracts.ts\";\nimport type { WorkerRequest } from \"../autonomy/contracts.ts\";\nimport type { LaneToolSurface } from \"../autonomy/lane-tool-surface.ts\";\nimport { safeRealpathSync } from \"../autonomy/path-scope.ts\";\nimport { composeSubagentSystemPrompt } from \"../autonomy/subagent-prompt.ts\";\nimport type { ModelCapabilityProfile } from \"../model-capability.ts\";\nimport { attemptUsageFromGatewayUsage, EMPTY_ATTEMPT_USAGE } from \"../orchestration/attempt-usage.ts\";\nimport type { ProviderBudgetReservation } from \"../orchestration/capability-gateway.ts\";\nimport type { AttemptUsageSnapshot, ExecutionGrant } from \"../orchestration/contracts.ts\";\nimport type { StartedDelegationAttempt } from \"../orchestration/delegation-ledger.ts\";\nimport { WorkerActionJournal } from \"./worker-action-journal.ts\";\nimport type { AppliedActionsReport, WorkerAction } from \"./worker-actions.ts\";\nimport type { WorkerAgentControlCoordinator } from \"./worker-agent-control-coordinator.ts\";\nimport type { WorkerConversation, WorkerConversationRetentionPolicy } from \"./worker-conversation-store.ts\";\nimport type { WorkerExecutionPlan } from \"./worker-execution-policy.ts\";\nimport type { WorkerLifecycle } from \"./worker-lifecycle.ts\";\nimport { runWorker, type WorkerRunOutcome } from \"./worker-runner.ts\";\n\nexport interface RecoveredWorkerTerminalCompletion {\n\ttext: string;\n\tusage: Usage;\n\tstopReason: string;\n}\n\n/** The live mutable state that must be visible to session disposal before provider work yields. */\nexport interface WorkerAttemptExecutionLedger {\n\tchangedFiles: Set<string>;\n\tgetUsage(): AttemptUsageSnapshot;\n}\n\nexport interface WorkerAttemptExecutionResult {\n\trawOutcome: WorkerRunOutcome;\n\tusage: AttemptUsageSnapshot;\n\tchangedFiles: readonly string[];\n}\n\n/**\n * The provider/tool-loop portion of a prepared worker attempt.\n *\n * Admission, durable leasing, grant compilation, terminalization, notification, verification, and\n * scheduling remain outside this boundary. This unit owns only the ordered child conversation:\n * persist assistant tool requests before execution, append messages before mailbox acknowledgements,\n * checkpoint cumulative usage before later boundaries, and compact only the provider projection.\n */\nexport interface WorkerAttemptExecutorOptions {\n\trequest: WorkerRequest;\n\tgrant: ExecutionGrant;\n\texecutionPlan: WorkerExecutionPlan;\n\ttoolSurface: LaneToolSurface;\n\tconversation: WorkerConversation;\n\tlifecycle: Pick<WorkerLifecycle, \"checkpoint\">;\n\tlaneId: string;\n\tagentId: string;\n\tdurableHandle: StartedDelegationAttempt;\n\tparentSessionId: string;\n\tagentDir: string;\n\tcwd: string;\n\tmodel: Model<Api>;\n\tthinkingLevel?: ThinkingLevel;\n\tlaneCapability: Pick<ModelCapabilityProfile, \"laneMaxOutputTokens\">;\n\tsoul?: string;\n\tworkerResourceSystemPrompt: string;\n\tinitialUsage: AttemptUsageSnapshot;\n\thasPersistedUsageCheckpoint: boolean;\n\tusageReportId: string;\n\tprocessCapable: boolean;\n\tverificationSubjectTaskId?: string;\n\trecoveredTerminal?: RecoveredWorkerTerminalCompletion;\n\tretentionPolicy?: WorkerConversationRetentionPolicy;\n\tsignal?: AbortSignal;\n\trunIsolatedCompletion(options: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\tagentControl: Pick<WorkerAgentControlCoordinator, \"acknowledgeMailboxMessage\" | \"mailboxMessagesForConversation\">;\n\tapplyActions?(actions: readonly WorkerAction[], actionJournal?: WorkerActionJournal): AppliedActionsReport;\n\twarn(message: string): void;\n}\n\nfunction recordAssistantUsage(surface: LaneToolSurface, message: Extract<Message, { role: \"assistant\" }>): void {\n\tsurface.gateway?.recordUsage({\n\t\tinputTokens: message.usage.input,\n\t\toutputTokens: message.usage.output,\n\t\tcacheReadTokens: message.usage.cacheRead,\n\t\tcacheWriteTokens: message.usage.cacheWrite,\n\t\ttotalTokens: message.usage.totalTokens,\n\t\tcostUsd: message.usage.cost.total,\n\t});\n}\n\nfunction isToolRequest(message: Message): boolean {\n\treturn message.role === \"assistant\" && message.content.some((content) => content.type === \"toolCall\");\n}\n\n/**\n * Constructs one execution exactly once. The caller registers {@link ledger} before calling\n * {@link run}, allowing synchronous disposal to observe mutations and cumulative usage while the\n * provider/tool loop is suspended.\n */\nexport function createWorkerAttemptExecutor(options: WorkerAttemptExecutorOptions): {\n\tledger: WorkerAttemptExecutionLedger;\n\tcheckpointUsage(summary: string): AttemptUsageSnapshot;\n\trun(): Promise<WorkerAttemptExecutionResult>;\n} {\n\tconst changedFiles = new Set(options.conversation.getChangedFiles(options.durableHandle.attemptId));\n\tconst toolIssues = new Set<string>();\n\tconst recordChangedFile = (filePath: string): void => {\n\t\tchangedFiles.add(filePath);\n\t\ttry {\n\t\t\toptions.conversation.recordChangedFile(options.durableHandle.attemptId, filePath);\n\t\t} catch (error) {\n\t\t\ttoolIssues.add(\"worker changed-file progress could not be persisted; parent review is required\");\n\t\t\toptions.warn(\n\t\t\t\t`Worker changed-file progress persistence failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t};\n\tconst actionJournal = options.request.envelope.capabilities.includes(\"filesystem.write\")\n\t\t? new WorkerActionJournal({\n\t\t\t\tagentDir: options.agentDir,\n\t\t\t\tparentSessionId: options.parentSessionId,\n\t\t\t\ttaskId: options.durableHandle.taskId,\n\t\t\t\tattemptId: options.durableHandle.attemptId,\n\t\t\t\tfencingToken: options.durableHandle.fencingToken,\n\t\t\t})\n\t\t: undefined;\n\tlet providerContextCompacted = options.conversation.hasProviderCompaction();\n\tlet retentionWarningEmitted = false;\n\tlet firstMailboxPoll = true;\n\tlet ran = false;\n\n\tconst currentUsage = (): AttemptUsageSnapshot =>\n\t\tattemptUsageFromGatewayUsage(\n\t\t\toptions.toolSurface.gateway?.getUsage() ?? {\n\t\t\t\t...EMPTY_ATTEMPT_USAGE,\n\t\t\t\twallClockMs: options.initialUsage.activeWallClockMs,\n\t\t\t},\n\t\t);\n\tconst checkpointUsage = (summary: string): AttemptUsageSnapshot => {\n\t\tconst usage = currentUsage();\n\t\toptions.lifecycle.checkpoint(options.laneId, { summary, usage });\n\t\treturn usage;\n\t};\n\tconst remainingAttemptTokens = (): number | undefined => options.toolSurface.gateway?.remainingAttemptTokenBudget();\n\tconst reserveProviderBudget = async (\n\t\trequestedMaxTokens: number,\n\t\tsubject: string,\n\t\tsignal?: AbortSignal,\n\t): Promise<ProviderBudgetReservation> => {\n\t\tif (options.toolSurface.gateway) {\n\t\t\treturn options.toolSurface.gateway.reserveProviderBudget(requestedMaxTokens, subject, signal);\n\t\t}\n\t\tif (signal?.aborted) throw signal.reason;\n\t\treturn { maxTokens: requestedMaxTokens, release: () => undefined };\n\t};\n\tlet failedCompactionUsage: Usage | undefined;\n\tconst retentionPolicy = options.retentionPolicy && {\n\t\t...options.retentionPolicy,\n\t\tgenerateVerifiedCompaction: async (preparation: Parameters<typeof compact>[0]) => {\n\t\t\tconst compactionUsage = createEmptyUsage();\n\t\t\tfailedCompactionUsage = compactionUsage;\n\t\t\treturn compact(\n\t\t\t\tpreparation,\n\t\t\t\toptions.model,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\toptions.signal,\n\t\t\t\toptions.thinkingLevel,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t{\n\t\t\t\t\tcompletion: async (model, context, requestOptions): Promise<AssistantMessage> => {\n\t\t\t\t\t\tif (model.provider !== options.model.provider || model.id !== options.model.id) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker compaction attempted to select a model outside the lane binding.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_compaction_provider_completion\");\n\t\t\t\t\t\tconst availableTokens = remainingAttemptTokens();\n\t\t\t\t\t\tif (availableTokens !== undefined && availableTokens <= 0) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before compaction provider completion.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst requestedMaxTokens = requestOptions.maxTokens;\n\t\t\t\t\t\tconst configuredMaxTokens =\n\t\t\t\t\t\t\ttypeof requestedMaxTokens === \"number\" &&\n\t\t\t\t\t\t\tNumber.isSafeInteger(requestedMaxTokens) &&\n\t\t\t\t\t\t\trequestedMaxTokens > 0\n\t\t\t\t\t\t\t\t? requestedMaxTokens\n\t\t\t\t\t\t\t\t: options.laneCapability.laneMaxOutputTokens;\n\t\t\t\t\t\tconst maxTokens = Math.min(configuredMaxTokens, availableTokens ?? configuredMaxTokens);\n\t\t\t\t\t\tif (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) {\n\t\t\t\t\t\t\tthrow new Error(\"Worker compaction provider completion has no valid remaining token budget.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet reservation: ProviderBudgetReservation | undefined;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst completion = await options.runIsolatedCompletion({\n\t\t\t\t\t\t\t\tsystemPrompt: context.systemPrompt ?? \"\",\n\t\t\t\t\t\t\t\tmessages: context.messages,\n\t\t\t\t\t\t\t\tmodel: options.model,\n\t\t\t\t\t\t\t\tthinkingLevel: options.thinkingLevel,\n\t\t\t\t\t\t\t\tmaxTokens,\n\t\t\t\t\t\t\t\trequestPreflight: async () => {\n\t\t\t\t\t\t\t\t\treservation?.release();\n\t\t\t\t\t\t\t\t\treservation = await reserveProviderBudget(\n\t\t\t\t\t\t\t\t\t\tmaxTokens,\n\t\t\t\t\t\t\t\t\t\t\"worker_compaction_provider_completion\",\n\t\t\t\t\t\t\t\t\t\trequestOptions.signal ?? options.signal,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\treturn { maxTokens: reservation.maxTokens };\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tsignal: requestOptions.signal ?? options.signal,\n\t\t\t\t\t\t\t\tcacheRetention: \"none\",\n\t\t\t\t\t\t\t\tlaneKind: \"worker-compaction\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\taddUsage(compactionUsage, completion.usage);\n\t\t\t\t\t\t\tconst response: AssistantMessage = {\n\t\t\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\t\t\tcontent: completion.text ? [{ type: \"text\", text: completion.text }] : [],\n\t\t\t\t\t\t\t\tapi: options.model.api,\n\t\t\t\t\t\t\t\tprovider: options.model.provider,\n\t\t\t\t\t\t\t\tmodel: options.model.id,\n\t\t\t\t\t\t\t\tusage: completion.usage,\n\t\t\t\t\t\t\t\tstopReason: completion.stopReason,\n\t\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\t\t...(completion.stopReason === \"error\"\n\t\t\t\t\t\t\t\t\t? { errorMessage: completion.text || \"Worker compaction provider request failed.\" }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\trecordAssistantUsage(options.toolSurface, response);\n\t\t\t\t\t\t\tcheckpointUsage(\"Persisted worker compaction provider usage before verification.\");\n\t\t\t\t\t\t\treturn response;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\treservation?.release();\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tgetFailedCompactionUsage: () => failedCompactionUsage,\n\t};\n\tconst ledger: WorkerAttemptExecutionLedger = {\n\t\tchangedFiles,\n\t\tgetUsage: currentUsage,\n\t};\n\n\treturn {\n\t\tledger,\n\t\tcheckpointUsage,\n\t\tasync run(): Promise<WorkerAttemptExecutionResult> {\n\t\t\tif (ran) throw new Error(\"A worker attempt executor may run only once.\");\n\t\t\tran = true;\n\t\t\tif (!options.hasPersistedUsageCheckpoint) {\n\t\t\t\tcheckpointUsage(\"Persisted deterministic cumulative usage baseline for the durable worker transcript.\");\n\t\t\t}\n\t\t\tconst rawOutcome = await runWorker({\n\t\t\t\trequest: options.request,\n\t\t\t\tmaxUsd: options.grant.budget.maxCostUsd,\n\t\t\t\tmaxWallClockMs: options.grant.budget.maxWallClockMs ?? 0,\n\t\t\t\tusageReportId: options.usageReportId,\n\t\t\t\tgetChangedFiles: () => [...changedFiles],\n\t\t\t\tsignal: options.signal,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tprocessCapable: options.processCapable,\n\t\t\t\tdelegationCapable: options.toolSurface.allowedTools.includes(\"delegate\"),\n\t\t\t\t...(options.verificationSubjectTaskId\n\t\t\t\t\t? { verificationSubjectTaskId: options.verificationSubjectTaskId }\n\t\t\t\t\t: {}),\n\t\t\t\t...(options.applyActions\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tapplyActions: (actions: readonly WorkerAction[]) => {\n\t\t\t\t\t\t\t\tconst report = options.applyActions!(actions, actionJournal);\n\t\t\t\t\t\t\t\tfor (const filePath of report.changedFiles) recordChangedFile(filePath);\n\t\t\t\t\t\t\t\treturn report;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tif (options.recoveredTerminal) {\n\t\t\t\t\t\tcheckpointUsage(\"Reused the persisted terminal worker assistant response after recovery.\");\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: options.recoveredTerminal.text,\n\t\t\t\t\t\t\tcostUsd: options.initialUsage.costUsd,\n\t\t\t\t\t\t\tstopReason: options.recoveredTerminal.stopReason,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst persistedToolAssistantIds = new Set<string>();\n\t\t\t\t\tconst pendingToolAssistants = new Map<string, AssistantMessage>();\n\t\t\t\t\tlet providerReservation: ProviderBudgetReservation | undefined;\n\t\t\t\t\tconst releaseProviderReservation = (): void => {\n\t\t\t\t\t\tproviderReservation?.release();\n\t\t\t\t\t\tproviderReservation = undefined;\n\t\t\t\t\t};\n\t\t\t\t\tconst persistToolRequest = (message: AssistantMessage): void => {\n\t\t\t\t\t\tconst toolCallIds = message.content.flatMap((content) =>\n\t\t\t\t\t\t\tcontent.type === \"toolCall\" ? [content.id] : [],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (toolCallIds.length === 0 || toolCallIds.every((id) => persistedToolAssistantIds.has(id))) return;\n\t\t\t\t\t\trecordAssistantUsage(options.toolSurface, message);\n\t\t\t\t\t\toptions.conversation.appendMessage(message);\n\t\t\t\t\t\tfor (const id of toolCallIds) {\n\t\t\t\t\t\t\tpersistedToolAssistantIds.add(id);\n\t\t\t\t\t\t\tpendingToolAssistants.delete(id);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckpointUsage(\"Persisted worker assistant tool request and its cumulative provider usage.\");\n\t\t\t\t\t\treleaseProviderReservation();\n\t\t\t\t\t};\n\t\t\t\t\toptions.toolSurface.gateway?.assertBudgetAvailable(\"worker_provider_completion\");\n\t\t\t\t\tconst availableTokens = remainingAttemptTokens();\n\t\t\t\t\tif (availableTokens !== undefined && availableTokens <= 0) {\n\t\t\t\t\t\tthrow new Error(\"Worker token budget exhausted before provider completion.\");\n\t\t\t\t\t}\n\t\t\t\t\tlet history = options.conversation.getProviderMessages();\n\t\t\t\t\tif (history.length === 0) {\n\t\t\t\t\t\toptions.conversation.appendMessage({\n\t\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: userPrompt }],\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\thistory = options.conversation.getProviderMessages();\n\t\t\t\t\t}\n\t\t\t\t\tlet completion: IsolatedCompletionResult;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcompletion = await options.runIsolatedCompletion({\n\t\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\t\tsoul: options.soul,\n\t\t\t\t\t\t\t\trolePrompt: [systemPrompt, options.workerResourceSystemPrompt].filter(Boolean).join(\"\\n\\n\"),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\thistory,\n\t\t\t\t\t\t\tmessages: [],\n\t\t\t\t\t\t\tmodel: options.model,\n\t\t\t\t\t\t\tthinkingLevel: options.thinkingLevel,\n\t\t\t\t\t\t\tmaxTokens: Math.min(\n\t\t\t\t\t\t\t\toptions.laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\t\t\tavailableTokens ?? Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\ttools: options.toolSurface.tools,\n\t\t\t\t\t\t\trequestPreflight: async () => {\n\t\t\t\t\t\t\t\treleaseProviderReservation();\n\t\t\t\t\t\t\t\tproviderReservation = await reserveProviderBudget(\n\t\t\t\t\t\t\t\t\toptions.laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\t\t\t\t\"worker_provider_completion\",\n\t\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn { maxTokens: providerReservation.maxTokens };\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tbeforeToolCall: async (context, toolSignal) => {\n\t\t\t\t\t\t\t\tpersistToolRequest(context.assistantMessage);\n\t\t\t\t\t\t\t\tconst decision = await options.toolSurface.beforeToolCall(context, toolSignal);\n\t\t\t\t\t\t\t\tif (decision?.block) {\n\t\t\t\t\t\t\t\t\ttoolIssues.add(\n\t\t\t\t\t\t\t\t\t\t`${context.toolCall.name} blocked: ${decision.reason ?? \"capability denied\"}`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcheckpointUsage(\n\t\t\t\t\t\t\t\t\t\t`Authorized worker tool '${context.toolCall.name}' under its durable grant.`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn decision;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tafterToolCall: async ({ toolCall, args, isError }) => {\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t(toolCall.name === \"write\" || toolCall.name === \"edit\") &&\n\t\t\t\t\t\t\t\t\targs &&\n\t\t\t\t\t\t\t\t\ttypeof args === \"object\" &&\n\t\t\t\t\t\t\t\t\t!Array.isArray(args)\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tconst rawPath = (args as Record<string, unknown>).path;\n\t\t\t\t\t\t\t\t\tif (typeof rawPath === \"string\" && rawPath.length > 0) {\n\t\t\t\t\t\t\t\t\t\tconst absolutePath = path.isAbsolute(rawPath)\n\t\t\t\t\t\t\t\t\t\t\t? path.resolve(rawPath)\n\t\t\t\t\t\t\t\t\t\t\t: path.resolve(options.cwd, rawPath);\n\t\t\t\t\t\t\t\t\t\tlet canonicalPath = absolutePath;\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tcanonicalPath = safeRealpathSync(absolutePath);\n\t\t\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\t\t\t// The operation entered execution; retain its lexical target if canonicalization failed.\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\trecordChangedFile(path.relative(options.cwd, canonicalPath).split(path.sep).join(\"/\"));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (isError) toolIssues.add(`${toolCall.name} failed during isolated execution`);\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tonMessage: (message) => {\n\t\t\t\t\t\t\t\tif (message.role === \"assistant\" && isToolRequest(message)) {\n\t\t\t\t\t\t\t\t\t// Known calls are normalized before beforeToolCall and persist from that hook.\n\t\t\t\t\t\t\t\t\t// Retain the request only so immediate unknown/malformed results can close the\n\t\t\t\t\t\t\t\t\t// transcript without freezing pre-repair arguments into durable history.\n\t\t\t\t\t\t\t\t\tfor (const content of message.content) {\n\t\t\t\t\t\t\t\t\t\tif (content.type === \"toolCall\") pendingToolAssistants.set(content.id, message);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (message.role === \"toolResult\" && !persistedToolAssistantIds.has(message.toolCallId)) {\n\t\t\t\t\t\t\t\t\tconst pending = pendingToolAssistants.get(message.toolCallId);\n\t\t\t\t\t\t\t\t\tif (pending) persistToolRequest(pending);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (message.role === \"assistant\") recordAssistantUsage(options.toolSurface, message);\n\t\t\t\t\t\t\t\toptions.conversation.appendMessage(message);\n\t\t\t\t\t\t\t\toptions.agentControl.acknowledgeMailboxMessage(options.agentId, message);\n\t\t\t\t\t\t\t\tif (message.role === \"assistant\") {\n\t\t\t\t\t\t\t\t\tcheckpointUsage(\"Persisted worker assistant response and its cumulative provider usage.\");\n\t\t\t\t\t\t\t\t\treleaseProviderReservation();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (message.role === \"toolResult\")\n\t\t\t\t\t\t\t\t\tcheckpointUsage(`Persisted worker tool result '${message.toolCallId}'.`);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tgetSteeringMessages: async (): Promise<AgentMessage[]> => {\n\t\t\t\t\t\t\t\tconst includeFollowUp = firstMailboxPoll;\n\t\t\t\t\t\t\t\tfirstMailboxPoll = false;\n\t\t\t\t\t\t\t\treturn options.agentControl.mailboxMessagesForConversation(\n\t\t\t\t\t\t\t\t\toptions.agentId,\n\t\t\t\t\t\t\t\t\toptions.conversation,\n\t\t\t\t\t\t\t\t\tincludeFollowUp,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tgetFollowUpMessages: async (): Promise<AgentMessage[]> =>\n\t\t\t\t\t\t\t\toptions.agentControl.mailboxMessagesForConversation(\n\t\t\t\t\t\t\t\t\toptions.agentId,\n\t\t\t\t\t\t\t\t\toptions.conversation,\n\t\t\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t...(retentionPolicy\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\ttransformContext: async (messages: AgentMessage[]) => {\n\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\tconst retained = await options.conversation.compactProviderContext(\n\t\t\t\t\t\t\t\t\t\t\t\t\tretentionPolicy,\n\t\t\t\t\t\t\t\t\t\t\t\t\toptions.signal,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\t\tretained.status === \"compacted_verified\" ||\n\t\t\t\t\t\t\t\t\t\t\t\t\tretained.status === \"compacted_deterministic\"\n\t\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tproviderContextCompacted = true;\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\t\tretained.contextUsage.tokens > retentionPolicy.maxContextTokens &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t!retentionWarningEmitted\n\t\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tretentionWarningEmitted = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t`Worker ${options.laneId} has one retained turn larger than its context policy; provider overflow recovery may be required.`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\t\tretained.status !== \"compacted_verified\" &&\n\t\t\t\t\t\t\t\t\t\t\t\t\tretained.status !== \"compacted_deterministic\"\n\t\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\t\treturn messages;\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\treturn sanitizeToolFailureContext(retained.context.messages, \"\").messages;\n\t\t\t\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (!retentionWarningEmitted) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tretentionWarningEmitted = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\toptions.warn(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t`Worker context retention failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\treturn messages;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t\t\tlaneKind: \"worker\",\n\t\t\t\t\t\t});\n\t\t\t\t\t} finally {\n\t\t\t\t\t\treleaseProviderReservation();\n\t\t\t\t\t}\n\t\t\t\t\tif (!providerContextCompacted) {\n\t\t\t\t\t\toptions.conversation.commitTranscript(\n\t\t\t\t\t\t\tcompletion.messages ?? options.conversation.getProviderMessages(),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcheckpointUsage(\n\t\t\t\t\t\t`Persisted worker conversation through ${options.conversation.getProviderContext().messages.length} messages.`,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t\tchangedFiles: [...changedFiles],\n\t\t\t\t\t\tblockers: [...toolIssues],\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst usage = checkpointUsage(\"Persisted final cumulative worker usage before terminal result.\");\n\t\t\treturn { rawOutcome, usage, changedFiles: [...changedFiles] };\n\t\t},\n\t};\n}\n"]}
|