@caupulican/pi-adaptative 0.81.26 → 0.81.27
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 +31 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +3 -2
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +4 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +19 -2
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +21 -10
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +71 -33
- 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 +59 -19
- package/dist/core/autonomy/bounded-completion.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +31 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -0
- package/dist/core/autonomy/lane-tool-surface.js +96 -0
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -0
- package/dist/core/background-lane-controller.d.ts +6 -3
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +134 -25
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/billing-failover-controller.d.ts.map +1 -1
- package/dist/core/billing-failover-controller.js +1 -1
- package/dist/core/billing-failover-controller.js.map +1 -1
- package/dist/core/context/current-work-memory.d.ts +9 -0
- package/dist/core/context/current-work-memory.d.ts.map +1 -0
- package/dist/core/context/current-work-memory.js +61 -0
- package/dist/core/context/current-work-memory.js.map +1 -0
- package/dist/core/context/file-store-memory-provider.d.ts +9 -0
- package/dist/core/context/file-store-memory-provider.d.ts.map +1 -0
- package/dist/core/context/file-store-memory-provider.js +106 -0
- package/dist/core/context/file-store-memory-provider.js.map +1 -0
- package/dist/core/context/long-term-memory-trigger.d.ts +15 -0
- package/dist/core/context/long-term-memory-trigger.d.ts.map +1 -0
- package/dist/core/context/long-term-memory-trigger.js +39 -0
- package/dist/core/context/long-term-memory-trigger.js.map +1 -0
- package/dist/core/context/memory-prompt-block.d.ts +3 -1
- package/dist/core/context/memory-prompt-block.d.ts.map +1 -1
- package/dist/core/context/memory-prompt-block.js +20 -3
- package/dist/core/context/memory-prompt-block.js.map +1 -1
- package/dist/core/context/memory-prompt-budget.d.ts +17 -0
- package/dist/core/context/memory-prompt-budget.d.ts.map +1 -0
- package/dist/core/context/memory-prompt-budget.js +64 -0
- package/dist/core/context/memory-prompt-budget.js.map +1 -0
- package/dist/core/context/memory-provider-contract.d.ts.map +1 -1
- package/dist/core/context/memory-provider-contract.js +2 -5
- package/dist/core/context/memory-provider-contract.js.map +1 -1
- package/dist/core/context/memory-tier-composer.d.ts +27 -0
- package/dist/core/context/memory-tier-composer.d.ts.map +1 -0
- package/dist/core/context/memory-tier-composer.js +79 -0
- package/dist/core/context/memory-tier-composer.js.map +1 -0
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +1 -0
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/cost/cost-summary.d.ts +3 -1
- package/dist/core/cost/cost-summary.d.ts.map +1 -1
- package/dist/core/cost/cost-summary.js +3 -3
- package/dist/core/cost/cost-summary.js.map +1 -1
- package/dist/core/cost-guard.d.ts +17 -7
- package/dist/core/cost-guard.d.ts.map +1 -1
- package/dist/core/cost-guard.js +33 -10
- package/dist/core/cost-guard.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts +9 -0
- package/dist/core/default-tool-surface.d.ts.map +1 -0
- package/dist/core/default-tool-surface.js +18 -0
- package/dist/core/default-tool-surface.js.map +1 -0
- package/dist/core/delegation/worker-runner.d.ts +11 -5
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +24 -12
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +15 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +2 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +7 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/failure-corpus.d.ts.map +1 -1
- package/dist/core/failure-corpus.js +2 -4
- package/dist/core/failure-corpus.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +9 -1
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.js +4 -3
- package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +12 -0
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +42 -4
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/memory/memory-manager.d.ts +8 -3
- package/dist/core/memory/memory-manager.d.ts.map +1 -1
- package/dist/core/memory/memory-manager.js +27 -11
- package/dist/core/memory/memory-manager.js.map +1 -1
- package/dist/core/memory/memory-provider.d.ts +5 -1
- package/dist/core/memory/memory-provider.d.ts.map +1 -1
- package/dist/core/memory/memory-provider.js.map +1 -1
- package/dist/core/memory/providers/file-store.d.ts +3 -1
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +7 -2
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/memory/providers/transcript-recall.d.ts +1 -0
- package/dist/core/memory/providers/transcript-recall.d.ts.map +1 -1
- package/dist/core/memory/providers/transcript-recall.js +4 -7
- package/dist/core/memory/providers/transcript-recall.js.map +1 -1
- package/dist/core/memory-controller.d.ts +36 -10
- package/dist/core/memory-controller.d.ts.map +1 -1
- package/dist/core/memory-controller.js +137 -21
- package/dist/core/memory-controller.js.map +1 -1
- package/dist/core/model-registry.d.ts +23 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +87 -8
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +30 -11
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-router-controller.d.ts.map +1 -1
- package/dist/core/model-router-controller.js +33 -29
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/model-selection-controller.d.ts +3 -0
- package/dist/core/model-selection-controller.d.ts.map +1 -1
- package/dist/core/model-selection-controller.js +8 -1
- package/dist/core/model-selection-controller.js.map +1 -1
- package/dist/core/models/perf-profile.d.ts.map +1 -1
- package/dist/core/models/perf-profile.js +95 -33
- package/dist/core/models/perf-profile.js.map +1 -1
- package/dist/core/profile-filter-controller.d.ts +11 -0
- package/dist/core/profile-filter-controller.d.ts.map +1 -1
- package/dist/core/profile-filter-controller.js +56 -11
- package/dist/core/profile-filter-controller.js.map +1 -1
- package/dist/core/profile-registry.d.ts +2 -2
- package/dist/core/profile-registry.d.ts.map +1 -1
- package/dist/core/profile-registry.js +58 -7
- package/dist/core/profile-registry.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +7 -7
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +78 -12
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/research/research-runner.d.ts +2 -2
- package/dist/core/research/research-runner.d.ts.map +1 -1
- package/dist/core/research/research-runner.js +8 -6
- package/dist/core/research/research-runner.js.map +1 -1
- package/dist/core/resource-loader.d.ts +4 -2
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +11 -1
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +13 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +127 -35
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/sdk.d.ts +8 -7
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +35 -5
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/security/secret-text.d.ts +3 -0
- package/dist/core/security/secret-text.d.ts.map +1 -0
- package/dist/core/security/secret-text.js +26 -0
- package/dist/core/security/secret-text.js.map +1 -0
- package/dist/core/settings-manager.d.ts +59 -17
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +300 -51
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +1 -1
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +7 -0
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +23 -1
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +15 -11
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +2 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +8 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +69 -29
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +2 -0
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/config-backup.d.ts +7 -1
- package/dist/modes/interactive/config-backup.d.ts.map +1 -1
- package/dist/modes/interactive/config-backup.js +196 -32
- package/dist/modes/interactive/config-backup.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +10 -28
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
- package/dist/modes/interactive/local-model-commands.js +2 -0
- package/dist/modes/interactive/local-model-commands.js.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.d.ts +6 -4
- package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.js +248 -65
- package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
- package/dist/modes/interactive/report-commands.d.ts.map +1 -1
- package/dist/modes/interactive/report-commands.js +8 -2
- package/dist/modes/interactive/report-commands.js.map +1 -1
- package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -1
- package/dist/modes/interactive/settings-selector-flow.js +8 -0
- package/dist/modes/interactive/settings-selector-flow.js.map +1 -1
- package/dist/modes/interactive/theme/theme-schema.json +1 -1
- package/dist/modes/interactive/theme/theme.d.ts +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +3 -1
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/docs/extensions.md +32 -0
- package/docs/resources.md +15 -7
- package/docs/settings.md +54 -5
- 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/preset.ts +2 -2
- 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 +44 -35
- package/package.json +4 -4
|
@@ -14,7 +14,10 @@
|
|
|
14
14
|
* delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this
|
|
15
15
|
* controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.
|
|
16
16
|
*/
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
import { createLaneToolSurface } from "./autonomy/lane-tool-surface.js";
|
|
17
19
|
import { LaneTracker } from "./autonomy/lane-tracker.js";
|
|
20
|
+
import { safeRealpathSync } from "./autonomy/path-scope.js";
|
|
18
21
|
import { appendLaneRecordSnapshot, getLaneRecordSnapshots } from "./autonomy/session-lane-record.js";
|
|
19
22
|
import { composeSubagentSystemPrompt } from "./autonomy/subagent-prompt.js";
|
|
20
23
|
import { AUTONOMY_TELEMETRY_EVENT_TYPES } from "./autonomy/telemetry-events.js";
|
|
@@ -45,6 +48,8 @@ export class BackgroundLaneController {
|
|
|
45
48
|
_researchLaneAbort = new AbortController();
|
|
46
49
|
/** Session-lifetime abort for in-flight delegated workers. */
|
|
47
50
|
_workerDelegationAbort = new AbortController();
|
|
51
|
+
/** Session-local de-duplication for fail-closed profile grants that cannot bind to lane tools. */
|
|
52
|
+
_warnedUnboundLaneToolGrants = new Set();
|
|
48
53
|
deps;
|
|
49
54
|
constructor(deps) {
|
|
50
55
|
this.deps = deps;
|
|
@@ -174,10 +179,6 @@ export class BackgroundLaneController {
|
|
|
174
179
|
scheduleResearchLaneFromIdle() {
|
|
175
180
|
if (this._isResearchLaneRunning || this.deps.isDisposed() || this.deps.isChildSession())
|
|
176
181
|
return;
|
|
177
|
-
if (!this.deps.getModelCapabilityProfile().backgroundLanesEnabled) {
|
|
178
|
-
this._lastResearchLaneSkipReason = "model_context_too_small";
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
182
|
const research = this.deps.getSettingsManager().getResearchLaneSettings();
|
|
182
183
|
if (!research.enabled) {
|
|
183
184
|
this._lastResearchLaneSkipReason = "research_lane_disabled";
|
|
@@ -195,6 +196,15 @@ export class BackgroundLaneController {
|
|
|
195
196
|
}
|
|
196
197
|
if (!this._buildResearchLaneDemand())
|
|
197
198
|
return;
|
|
199
|
+
const shipment = this._resolveLaneShipment(research, "no_research_model");
|
|
200
|
+
if (!shipment.ok) {
|
|
201
|
+
this._lastResearchLaneSkipReason = shipment.skipReason;
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (!this._laneCapabilityProfile(shipment.model).backgroundLanesEnabled) {
|
|
205
|
+
this._lastResearchLaneSkipReason = "model_research_unsupported";
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
198
208
|
this.clearResearchLaneTimer();
|
|
199
209
|
this._researchLaneTimer = setTimeout(() => {
|
|
200
210
|
this._researchLaneTimer = undefined;
|
|
@@ -252,7 +262,12 @@ export class BackgroundLaneController {
|
|
|
252
262
|
_resolveLaneShipment(laneSettings, missingModelReason) {
|
|
253
263
|
let laneProfile;
|
|
254
264
|
if (laneSettings.profile) {
|
|
255
|
-
|
|
265
|
+
const profileRef = laneSettings.profile.trim();
|
|
266
|
+
const registry = this.deps.getSettingsManager().getProfileRegistry();
|
|
267
|
+
laneProfile =
|
|
268
|
+
profileRef.startsWith("./") || profileRef.startsWith("../")
|
|
269
|
+
? registry.resolveProfileRef(profileRef, this.deps.getCwd())
|
|
270
|
+
: registry.getProfile(profileRef);
|
|
256
271
|
if (!laneProfile) {
|
|
257
272
|
return { ok: false, skipReason: "lane_profile_not_found" };
|
|
258
273
|
}
|
|
@@ -278,21 +293,27 @@ export class BackgroundLaneController {
|
|
|
278
293
|
}
|
|
279
294
|
return { ok: true, model, laneProfile };
|
|
280
295
|
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
296
|
+
_warnUnboundLaneToolGrants(laneProfile, surface) {
|
|
297
|
+
if (!laneProfile || surface.unboundAllowPatterns.length === 0)
|
|
298
|
+
return;
|
|
299
|
+
const warningKey = `${laneProfile.name}\0${[...surface.unboundAllowPatterns].sort().join("\0")}`;
|
|
300
|
+
if (this._warnedUnboundLaneToolGrants.has(warningKey))
|
|
301
|
+
return;
|
|
302
|
+
this._warnedUnboundLaneToolGrants.add(warningKey);
|
|
303
|
+
this.deps.emit({
|
|
304
|
+
type: "warning",
|
|
305
|
+
message: `Lane profile '${laneProfile.name}' grants unavailable isolated-lane tools: ${surface.unboundAllowPatterns.join(", ")}. Only classified lane tools can execute.`,
|
|
306
|
+
});
|
|
288
307
|
}
|
|
289
308
|
/** Stripped research envelope — never the foreground/architect envelope. */
|
|
290
|
-
_buildResearchLaneEnvelope(maxUsd, laneProfile) {
|
|
309
|
+
_buildResearchLaneEnvelope(maxUsd, laneProfile, surface) {
|
|
291
310
|
return {
|
|
292
311
|
id: `research-${this.deps.getSessionId()}-${Date.now()}`,
|
|
293
312
|
profileId: laneProfile?.name,
|
|
294
313
|
capabilities: ["research", "read_files", "memory_read"],
|
|
295
|
-
...
|
|
314
|
+
allowedTools: [...surface.allowedTools],
|
|
315
|
+
deniedTools: [...surface.deniedTools],
|
|
316
|
+
allowedPaths: [this.deps.getCwd()],
|
|
296
317
|
maxEstimatedUsd: clampLaneMaxUsd(maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd),
|
|
297
318
|
createdAt: new Date().toISOString(),
|
|
298
319
|
};
|
|
@@ -323,6 +344,11 @@ export class BackgroundLaneController {
|
|
|
323
344
|
return { started: false, skipReason: shipment.skipReason };
|
|
324
345
|
}
|
|
325
346
|
const { model, laneProfile } = shipment;
|
|
347
|
+
const laneCapability = this._laneCapabilityProfile(model);
|
|
348
|
+
if (!laneCapability.backgroundLanesEnabled) {
|
|
349
|
+
this._lastResearchLaneSkipReason = "model_research_unsupported";
|
|
350
|
+
return { started: false, skipReason: "model_research_unsupported" };
|
|
351
|
+
}
|
|
326
352
|
this._isResearchLaneRunning = true;
|
|
327
353
|
this._laneTracker.ensureCounterAtLeast(getLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1);
|
|
328
354
|
const startedRecord = this._laneTracker.start({ type: "research", goalId: demand.goalId });
|
|
@@ -336,11 +362,13 @@ export class BackgroundLaneController {
|
|
|
336
362
|
maxSources: settings.maxSources,
|
|
337
363
|
});
|
|
338
364
|
const maxUsd = clampLaneMaxUsd(settings.maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd);
|
|
365
|
+
const toolSurface = createLaneToolSurface({ cwd: this.deps.getCwd(), profile: laneProfile });
|
|
366
|
+
this._warnUnboundLaneToolGrants(laneProfile, toolSurface);
|
|
339
367
|
const result = await runResearch({
|
|
340
368
|
query: demand.query,
|
|
341
369
|
context: demand.context,
|
|
342
370
|
sources: workspaceSources,
|
|
343
|
-
envelope: this._buildResearchLaneEnvelope(maxUsd, laneProfile),
|
|
371
|
+
envelope: this._buildResearchLaneEnvelope(maxUsd, laneProfile, toolSurface),
|
|
344
372
|
maxUsd,
|
|
345
373
|
maxSources: settings.maxSources,
|
|
346
374
|
maxFindings: settings.maxFindings,
|
|
@@ -358,7 +386,10 @@ export class BackgroundLaneController {
|
|
|
358
386
|
messages: [{ role: "user", content: [{ type: "text", text: userPrompt }], timestamp: Date.now() }],
|
|
359
387
|
model,
|
|
360
388
|
thinkingLevel: laneProfile?.thinking ?? "off",
|
|
361
|
-
maxTokens:
|
|
389
|
+
maxTokens: laneCapability.laneMaxOutputTokens,
|
|
390
|
+
tools: toolSurface.tools,
|
|
391
|
+
maxTurns: 6,
|
|
392
|
+
beforeToolCall: toolSurface.beforeToolCall,
|
|
362
393
|
signal,
|
|
363
394
|
// Core/soul/role are all static per configuration — the provider can cache the prefix.
|
|
364
395
|
cacheRetention: "short",
|
|
@@ -462,6 +493,9 @@ export class BackgroundLaneController {
|
|
|
462
493
|
return { started: false, skipReason: "missing_instructions" };
|
|
463
494
|
}
|
|
464
495
|
const settings = delegationSettings;
|
|
496
|
+
if (!this.deps.isDelegateToolActive()) {
|
|
497
|
+
return { started: false, skipReason: "delegate_tool_inactive" };
|
|
498
|
+
}
|
|
465
499
|
if (!settings.enabled) {
|
|
466
500
|
return { started: false, skipReason: "worker_delegation_disabled" };
|
|
467
501
|
}
|
|
@@ -470,29 +504,42 @@ export class BackgroundLaneController {
|
|
|
470
504
|
return { started: false, skipReason: shipment.skipReason };
|
|
471
505
|
}
|
|
472
506
|
const { model, laneProfile } = shipment;
|
|
507
|
+
const laneCapability = this._laneCapabilityProfile(model);
|
|
508
|
+
if (!laneCapability.backgroundLanesEnabled) {
|
|
509
|
+
return { started: false, skipReason: "model_delegation_unsupported" };
|
|
510
|
+
}
|
|
473
511
|
this._laneTracker.ensureCounterAtLeast(getLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1);
|
|
474
512
|
const startedRecord = this._laneTracker.start({ type: "worker" });
|
|
475
513
|
const maxUsd = Math.min(settings.maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd ?? Number.POSITIVE_INFINITY);
|
|
514
|
+
const writeEnabled = settings.writeEnabled && settings.writePaths.length > 0;
|
|
515
|
+
const toolSurface = createLaneToolSurface({
|
|
516
|
+
cwd: this.deps.getCwd(),
|
|
517
|
+
profile: laneProfile,
|
|
518
|
+
writeEnabled,
|
|
519
|
+
writePaths: settings.writePaths,
|
|
520
|
+
});
|
|
521
|
+
this._warnUnboundLaneToolGrants(laneProfile, toolSurface);
|
|
522
|
+
const allowedActionOps = new Set(toolSurface.allowedTools.filter((name) => name === "write" || name === "edit"));
|
|
523
|
+
const writeGranted = writeEnabled && allowedActionOps.size > 0;
|
|
476
524
|
const workerRequest = {
|
|
477
525
|
id: startedRecord.laneId,
|
|
478
526
|
instructions,
|
|
479
527
|
route: {
|
|
480
528
|
tier: "cheap",
|
|
481
|
-
risk: "read-only",
|
|
529
|
+
risk: writeGranted ? "scoped-write" : "read-only",
|
|
482
530
|
confidence: 1,
|
|
483
531
|
reasonCode: "scout_worker",
|
|
484
|
-
reasons: ["Read-only scout delegation"],
|
|
532
|
+
reasons: [writeGranted ? "Path-scoped worker delegation" : "Read-only scout delegation"],
|
|
485
533
|
},
|
|
486
534
|
envelope: {
|
|
487
535
|
id: `worker-${this.deps.getSessionId()}-${startedRecord.laneId}`,
|
|
488
536
|
profileId: laneProfile?.name,
|
|
489
537
|
// write_files requires BOTH the opt-in AND an explicit non-empty path scope —
|
|
490
538
|
// an unscoped write grant is refused here, not discovered at validation time.
|
|
491
|
-
capabilities:
|
|
492
|
-
...(
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
...this._laneProfileToolGrants(laneProfile),
|
|
539
|
+
capabilities: writeGranted ? ["read_files", "write_files"] : ["read_files"],
|
|
540
|
+
...(writeGranted ? { allowedPaths: [...settings.writePaths] } : {}),
|
|
541
|
+
allowedTools: [...toolSurface.allowedTools],
|
|
542
|
+
deniedTools: [...toolSurface.deniedTools],
|
|
496
543
|
maxEstimatedUsd: maxUsd,
|
|
497
544
|
createdAt: new Date().toISOString(),
|
|
498
545
|
},
|
|
@@ -513,17 +560,39 @@ export class BackgroundLaneController {
|
|
|
513
560
|
const usageReportId = `worker:${this.deps.getSessionId()}:${startedRecord.laneId}`;
|
|
514
561
|
try {
|
|
515
562
|
let spentUsage;
|
|
563
|
+
const toolChangedFiles = new Set();
|
|
564
|
+
const toolIssues = new Set();
|
|
516
565
|
const outcome = await runWorker({
|
|
517
566
|
request: workerRequest,
|
|
518
567
|
maxUsd,
|
|
519
568
|
maxWallClockMs: settings.maxWallClockMs,
|
|
520
569
|
usageReportId,
|
|
570
|
+
getChangedFiles: () => [...toolChangedFiles],
|
|
521
571
|
signal: this._workerDelegationAbort.signal,
|
|
522
572
|
// Parent validation must use the same relative-path baseline the runner reports in.
|
|
523
573
|
cwd: this.deps.getCwd(),
|
|
524
574
|
// Write lane (G2): runner-side action application through the envelope path scope.
|
|
525
575
|
applyActions: workerRequest.envelope.capabilities.includes("write_files")
|
|
526
|
-
? (actions) =>
|
|
576
|
+
? (actions) => {
|
|
577
|
+
const permitted = actions.filter((action) => allowedActionOps.has(action.op));
|
|
578
|
+
const applied = applyWorkerActions({
|
|
579
|
+
actions: permitted,
|
|
580
|
+
envelope: workerRequest.envelope,
|
|
581
|
+
cwd: this.deps.getCwd(),
|
|
582
|
+
});
|
|
583
|
+
return {
|
|
584
|
+
...applied,
|
|
585
|
+
refused: [
|
|
586
|
+
...actions
|
|
587
|
+
.filter((action) => !allowedActionOps.has(action.op))
|
|
588
|
+
.map((action) => ({
|
|
589
|
+
path: action.path,
|
|
590
|
+
reason: `${action.op} is not granted by the lane profile`,
|
|
591
|
+
})),
|
|
592
|
+
...applied.refused,
|
|
593
|
+
],
|
|
594
|
+
};
|
|
595
|
+
}
|
|
527
596
|
: undefined,
|
|
528
597
|
complete: async ({ systemPrompt, userPrompt, signal }) => {
|
|
529
598
|
const completion = await this.deps.runIsolatedCompletion({
|
|
@@ -537,7 +606,45 @@ export class BackgroundLaneController {
|
|
|
537
606
|
messages: [{ role: "user", content: [{ type: "text", text: userPrompt }], timestamp: Date.now() }],
|
|
538
607
|
model,
|
|
539
608
|
thinkingLevel: laneProfile?.thinking ?? "off",
|
|
540
|
-
maxTokens:
|
|
609
|
+
maxTokens: laneCapability.laneMaxOutputTokens,
|
|
610
|
+
tools: toolSurface.tools,
|
|
611
|
+
maxTurns: 6,
|
|
612
|
+
beforeToolCall: async (context, toolSignal) => {
|
|
613
|
+
const decision = await toolSurface.beforeToolCall(context, toolSignal);
|
|
614
|
+
if (decision?.block) {
|
|
615
|
+
toolIssues.add(`${context.toolCall.name} blocked: ${decision.reason ?? "capability denied"}`);
|
|
616
|
+
}
|
|
617
|
+
return decision;
|
|
618
|
+
},
|
|
619
|
+
afterToolCall: async ({ toolCall, args, isError }) => {
|
|
620
|
+
// This hook runs only for a validated, gate-approved tool that actually entered
|
|
621
|
+
// execution. Record a direct mutation target before inspecting `isError`: write/edit
|
|
622
|
+
// may have changed disk and then observed cancellation, timeout, or a late I/O error.
|
|
623
|
+
// Pre-gate/profile/path refusals never reach afterToolCall, so they remain unreported.
|
|
624
|
+
if (toolCall.name === "write" || toolCall.name === "edit") {
|
|
625
|
+
if (args && typeof args === "object" && !Array.isArray(args)) {
|
|
626
|
+
const rawPath = args.path;
|
|
627
|
+
if (typeof rawPath === "string" && rawPath.length > 0) {
|
|
628
|
+
const absolutePath = path.isAbsolute(rawPath)
|
|
629
|
+
? path.resolve(rawPath)
|
|
630
|
+
: path.resolve(this.deps.getCwd(), rawPath);
|
|
631
|
+
let canonicalPath = absolutePath;
|
|
632
|
+
try {
|
|
633
|
+
canonicalPath = safeRealpathSync(absolutePath);
|
|
634
|
+
}
|
|
635
|
+
catch {
|
|
636
|
+
// Execution was attempted; preserve conservative accounting with the lexical path.
|
|
637
|
+
}
|
|
638
|
+
toolChangedFiles.add(path.relative(this.deps.getCwd(), canonicalPath));
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
if (isError) {
|
|
643
|
+
toolIssues.add(`${toolCall.name} failed during isolated execution`);
|
|
644
|
+
return undefined;
|
|
645
|
+
}
|
|
646
|
+
return undefined;
|
|
647
|
+
},
|
|
541
648
|
signal,
|
|
542
649
|
// Core/soul/role are all static per configuration — the provider can cache the prefix.
|
|
543
650
|
cacheRetention: "short",
|
|
@@ -547,6 +654,8 @@ export class BackgroundLaneController {
|
|
|
547
654
|
text: completion.text,
|
|
548
655
|
costUsd: completion.usage.cost.total,
|
|
549
656
|
stopReason: String(completion.stopReason),
|
|
657
|
+
changedFiles: [...toolChangedFiles],
|
|
658
|
+
blockers: [...toolIssues],
|
|
550
659
|
};
|
|
551
660
|
},
|
|
552
661
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"background-lane-controller.js","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAeH,OAAO,EAAmB,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AACrG,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,8BAA8B,EAA+B,MAAM,gCAAgC,CAAC;AAC7G,OAAO,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,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,UAAU,EAAE,CAAC;QACvE,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,EAAE,CAAC;QACX,CAAC;IAAA,CACD;CACD","sourcesContent":["/**\n * Background-lane controller: goal auto-continue, the research lane, scout-worker delegation, and\n * the model-fitness probe.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the lane timers, the\n * single-flight guards, the last research-lane skip reason, the live {@link LaneTracker}, and the\n * session-lifetime abort controllers for in-flight research/worker passes. Everything else it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, Model, Usage } from \"@caupulican/pi-ai\";\nimport type {\n\tAgentSessionEvent,\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tIsolatedCompletionOptions,\n\tIsolatedCompletionResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session.ts\";\nimport type { CapabilityEnvelope, EvidenceBundle, WorkerRequest, WorkerResult } from \"./autonomy/contracts.ts\";\nimport { type LaneRecord, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { appendLaneRecordSnapshot, getLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { composeSubagentSystemPrompt } from \"./autonomy/subagent-prompt.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport { applyWorkerActions } from \"./delegation/worker-actions.ts\";\nimport { runWorker } from \"./delegation/worker-runner.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport {\n\tderiveModelCapabilityProfile,\n\ttype ModelCapabilityProfile,\n\tscaleContinuationBudgetsForCapability,\n} from \"./model-capability.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { FitnessStore, type StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { NormalizedProfile } from \"./profile-registry.ts\";\nimport { type ModelFitnessReport, runModelFitnessProbe } from \"./research/model-fitness.ts\";\nimport { runResearch } from \"./research/research-runner.ts\";\nimport type { collectWorkspaceSources } from \"./research/workspace-collector.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport function clampLaneMaxUsd(settingsMaxUsd: number, foregroundMaxEstimatedUsd?: number): number {\n\treturn Math.min(settingsMaxUsd, foregroundMaxEstimatedUsd ?? Number.POSITIVE_INFINITY);\n}\n\nexport interface BackgroundLaneControllerDeps {\n\t/** A disposed session must never schedule/persist a lane or continuation. */\n\tisDisposed(): boolean;\n\t/** Child sessions never run the idle research lane (only the top-level session drives autonomy). */\n\tisChildSession(): boolean;\n\t/** This session's id, for lane envelope ids and spawned-usage report ids. */\n\tgetSessionId(): string;\n\t/** The workspace root a lane runs relative to (worker path scope + research source collection). */\n\tgetCwd(): string;\n\t/** Root dir the host-keyed {@link FitnessStore} persists under. */\n\tgetAgentDir(): string;\n\t/** Session log: lane records read/append here and feed lane-history dedupe. */\n\tgetSessionManager(): SessionManager;\n\t/** Autonomy / research-lane / worker-delegation / model-capability settings + the profile registry. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolves a configured lane model pattern against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Session-scoped provider/model quota exhaustion guard. */\n\tisModelExhausted(model: Model<Api>): boolean;\n\t/** The session's current model — lanes inherit it unless a lane model is explicitly configured. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Foreground cost ceiling — a lane budget is clamped to it, never exceeds it. */\n\tgetCapabilityEnvelope(): CapabilityEnvelope | undefined;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Emits a session event (only `warning` from this controller). */\n\temit(event: AgentSessionEvent): void;\n\t/** G3/G8 telemetry sink (codes/ids only — never lane product text). */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Durable goal state, if a goal is active (the research lane's demand source). */\n\tgetGoalStateSnapshot(): GoalState | undefined;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Latest persisted evidence bundle, for research-lane dedupe. */\n\tgetEvidenceBundleSnapshot(): EvidenceBundle | undefined;\n\t/** Persist a research lane's evidence bundle to the session log. */\n\tsaveEvidenceBundleSnapshot(bundle: EvidenceBundle): string;\n\t/** Persist a worker delegation's result snapshot to the session log. */\n\tsaveWorkerResultSnapshot(result: WorkerResult, request?: WorkerRequest): string;\n\t/** Roll a lane's spawned usage into session accounting (idempotent per reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** One-shot LLM call fully isolated from the main session — the lane execution primitive. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\t/** Best-effort workspace evidence collection (silent-on-failure; [] preserves prior behavior). */\n\tcollectWorkspaceSources: typeof collectWorkspaceSources;\n}\n\nexport class BackgroundLaneController {\n\t/** Pending idle timer that starts bounded goal continuation after the session becomes idle. */\n\tprivate _goalAutoContinueTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Guards bounded idle autosteer so continuation prompts do not recursively trigger themselves. */\n\tprivate _isGoalAutoContinuing = false;\n\t/** Pending idle timer that starts an autonomous research pass after the session becomes idle. */\n\tprivate _researchLaneTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Single-flight guard: at most one research pass runs at a time per session. */\n\tprivate _isResearchLaneRunning = false;\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tprivate _lastResearchLaneSkipReason: string | undefined;\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\t/** Session-lifetime abort for in-flight research passes (same pattern as _reflectionAbort). */\n\tprivate readonly _researchLaneAbort = new AbortController();\n\t/** Session-lifetime abort for in-flight delegated workers. */\n\tprivate readonly _workerDelegationAbort = new AbortController();\n\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\treturn this._laneTracker.getRecords();\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this._laneTracker.getActiveCount();\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._lastResearchLaneSkipReason;\n\t}\n\n\t/** Abort any in-flight research pass or delegated worker (called on session dispose). */\n\tabortInFlightLanes(): void {\n\t\tthis._researchLaneAbort.abort();\n\t\tthis._workerDelegationAbort.abort();\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tif (this._goalAutoContinueTimer !== undefined) {\n\t\t\tclearTimeout(this._goalAutoContinueTimer);\n\t\t\tthis._goalAutoContinueTimer = undefined;\n\t\t}\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tif (options?.autoContinueGoal === false || this._isGoalAutoContinuing || this.deps.isDisposed()) return;\n\n\t\t// Small-window models cannot afford multi-thousand-token continuation prompts per idle turn.\n\t\tif (!this.deps.getModelCapabilityProfile().backgroundLanesEnabled) return;\n\n\t\tconst { maxStallTurns, goalAutoContinue, goalAutoContinueDelayMs } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\n\t\tthis.clearGoalAutoContinueTimer();\n\t\tthis._goalAutoContinueTimer = setTimeout(() => {\n\t\t\tthis._goalAutoContinueTimer = undefined;\n\t\t\tvoid this._runScheduledGoalAutoContinue();\n\t\t}, goalAutoContinueDelayMs);\n\n\t\tconst timer = this._goalAutoContinueTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tprivate async _runScheduledGoalAutoContinue(): Promise<void> {\n\t\tif (this._isGoalAutoContinuing || this.deps.isDisposed()) return;\n\n\t\tconst { maxStallTurns, goalContinueTurns, goalContinueMaxWallClockMinutes, goalAutoContinue } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\n\t\t// Lean-window models (16-32k) keep autosteer but at a reduced budget; full passes through.\n\t\tconst scaled = scaleContinuationBudgetsForCapability(this.deps.getModelCapabilityProfile(), {\n\t\t\tmaxTurns: goalContinueTurns,\n\t\t\tmaxWallClockMinutes: goalContinueMaxWallClockMinutes,\n\t\t});\n\n\t\tthis._isGoalAutoContinuing = true;\n\t\ttry {\n\t\t\tawait this.deps.continueGoalLoop({\n\t\t\t\tmaxTurns: scaled.maxTurns,\n\t\t\t\tmaxStallTurns,\n\t\t\t\tmaxWallClockMinutes: scaled.maxWallClockMinutes,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Goal auto-continuation failed: ${message}` });\n\t\t} finally {\n\t\t\tthis._isGoalAutoContinuing = false;\n\t\t}\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tif (this._researchLaneTimer !== undefined) {\n\t\t\tclearTimeout(this._researchLaneTimer);\n\t\t\tthis._researchLaneTimer = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Derive the research demand from durable goal state: an active goal with open requirements,\n\t * deduplicated against the latest persisted bundle so the same requirement set is never\n\t * researched twice (the query is deterministic, so dedupe survives session reload).\n\t */\n\tprivate _buildResearchLaneDemand(): { query: string; context: string; goalId: string } | undefined {\n\t\tconst goal = this.deps.getGoalStateSnapshot();\n\t\tif (!goal || goal.status !== \"active\") {\n\t\t\tthis._lastResearchLaneSkipReason = \"no_active_goal\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst open = goal.requirements.filter((requirement) => requirement.status === \"open\");\n\t\tif (open.length === 0) {\n\t\t\tthis._lastResearchLaneSkipReason = \"no_open_requirements\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst query = `goal:${goal.goalId} requirements:${open\n\t\t\t.map((requirement) => requirement.id)\n\t\t\t.sort()\n\t\t\t.join(\",\")}`;\n\t\tif (this.deps.getEvidenceBundleSnapshot()?.query === query) {\n\t\t\tthis._lastResearchLaneSkipReason = \"recent_evidence_sufficient\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst context = [\n\t\t\t`Goal: ${goal.userGoal}`,\n\t\t\t\"Open requirements:\",\n\t\t\t...open.slice(0, 20).map((requirement) => `- ${requirement.text}`),\n\t\t].join(\"\\n\");\n\t\treturn { query, context, goalId: goal.goalId };\n\t}\n\n\t/**\n\t * Idle trigger for the autonomous research lane (mirrors {@link scheduleGoalAutoContinueFromIdle}).\n\t * All skips are recorded in `_lastResearchLaneSkipReason` and surfaced via diagnostics — the lane\n\t * informs, it never prompts or blocks the foreground.\n\t */\n\tscheduleResearchLaneFromIdle(): void {\n\t\tif (this._isResearchLaneRunning || this.deps.isDisposed() || this.deps.isChildSession()) return;\n\n\t\tif (!this.deps.getModelCapabilityProfile().backgroundLanesEnabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"model_context_too_small\";\n\t\t\treturn;\n\t\t}\n\n\t\tconst research = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tif (!research.enabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"research_lane_disabled\";\n\t\t\treturn;\n\t\t}\n\t\tconst { mode } = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (mode === \"off\") {\n\t\t\tthis._lastResearchLaneSkipReason = \"autonomy_mode_off\";\n\t\t\treturn;\n\t\t}\n\t\tconst priorRuns = getLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).filter(\n\t\t\t(record) => record.type === \"research\",\n\t\t).length;\n\t\tif (priorRuns >= research.maxRunsPerSession) {\n\t\t\tthis._lastResearchLaneSkipReason = \"max_runs_reached\";\n\t\t\treturn;\n\t\t}\n\t\tif (!this._buildResearchLaneDemand()) return;\n\n\t\tthis.clearResearchLaneTimer();\n\t\tthis._researchLaneTimer = setTimeout(() => {\n\t\t\tthis._researchLaneTimer = undefined;\n\t\t\tvoid this._runScheduledResearchLane();\n\t\t}, research.idleDelayMs);\n\n\t\tconst timer = this._researchLaneTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tprivate async _runScheduledResearchLane(): Promise<void> {\n\t\tif (this._isResearchLaneRunning || this.deps.isDisposed()) return;\n\n\t\tconst research = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tconst { mode } = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!research.enabled || mode === \"off\") return;\n\n\t\ttry {\n\t\t\tawait this.runResearchLaneOnce();\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Research lane failed: ${message}` });\n\t\t}\n\t}\n\n\t/** Capability profile for a specific lane model (lane budgets scale to the lane model's window). */\n\tprivate _laneCapabilityProfile(model: Model<Api>): ModelCapabilityProfile {\n\t\treturn deriveModelCapabilityProfile({\n\t\t\tcontextWindow: model.contextWindow,\n\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t});\n\t}\n\n\t/**\n\t * Resolve the model for a background lane. Lanes are shipped BY this session, so they inherit\n\t * the session's own model unless a lane-specific model is explicitly configured — a single-model\n\t * setup (e.g. one local open model) runs its lanes on that same model. An explicitly configured\n\t * pattern that cannot resolve/authenticate is a visible skip, not a silent fallback.\n\t */\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\tif (configuredPattern) {\n\t\t\tconst resolved = resolveCliModel({ cliModel: configuredPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (resolved.model && this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\t\treturn resolved.model;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.deps.getModel() ?? undefined;\n\t}\n\n\t/**\n\t * Resolve what a lane ships with. Precedence: explicit lane model setting, then the lane\n\t * profile's model (a shipped profile with a model MUST be obeyed — unresolvable is a visible\n\t * skip, never a fallback), then generic inheritance of the session model.\n\t */\n\tprivate _resolveLaneShipment(\n\t\tlaneSettings: { model?: string; profile?: string },\n\t\tmissingModelReason: string,\n\t): { ok: true; model: Model<Api>; laneProfile?: NormalizedProfile } | { ok: false; skipReason: string } {\n\t\tlet laneProfile: NormalizedProfile | undefined;\n\t\tif (laneSettings.profile) {\n\t\t\tlaneProfile = this.deps.getSettingsManager().getProfileRegistry().getProfile(laneSettings.profile);\n\t\t\tif (!laneProfile) {\n\t\t\t\treturn { ok: false, skipReason: \"lane_profile_not_found\" };\n\t\t\t}\n\t\t}\n\n\t\tlet model: Model<Api> | undefined;\n\t\tif (laneSettings.model) {\n\t\t\tmodel = this.resolveLaneModel(laneSettings.model);\n\t\t\tif (!model) return { ok: false, skipReason: missingModelReason };\n\t\t} else if (laneProfile?.model) {\n\t\t\tmodel = this.resolveLaneModel(laneProfile.model);\n\t\t\tif (!model) return { ok: false, skipReason: \"no_lane_profile_model\" };\n\t\t} else {\n\t\t\tmodel = this.deps.getModel() ?? undefined;\n\t\t\tif (!model) return { ok: false, skipReason: missingModelReason };\n\t\t}\n\t\tif (this.deps.isModelExhausted(model)) {\n\t\t\treturn { ok: false, skipReason: `${model.provider}/${model.id} model exhausted: quota` };\n\t\t}\n\t\treturn { ok: true, model, laneProfile };\n\t}\n\n\t/** UAC tool grants from a shipped lane profile, recorded on the lane envelope. */\n\tprivate _laneProfileToolGrants(\n\t\tlaneProfile?: NormalizedProfile,\n\t): Pick<CapabilityEnvelope, \"allowedTools\" | \"deniedTools\"> {\n\t\tconst toolsFilter = laneProfile?.resources.tools;\n\t\treturn {\n\t\t\t...(toolsFilter?.allow && toolsFilter.allow.length > 0 ? { allowedTools: [...toolsFilter.allow] } : {}),\n\t\t\t...(toolsFilter?.block && toolsFilter.block.length > 0 ? { deniedTools: [...toolsFilter.block] } : {}),\n\t\t};\n\t}\n\n\t/** Stripped research envelope — never the foreground/architect envelope. */\n\tprivate _buildResearchLaneEnvelope(maxUsd: number, laneProfile?: NormalizedProfile): CapabilityEnvelope {\n\t\treturn {\n\t\t\tid: `research-${this.deps.getSessionId()}-${Date.now()}`,\n\t\t\tprofileId: laneProfile?.name,\n\t\t\tcapabilities: [\"research\", \"read_files\", \"memory_read\"],\n\t\t\t...this._laneProfileToolGrants(laneProfile),\n\t\t\tmaxEstimatedUsd: clampLaneMaxUsd(maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd),\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\tif (this._isResearchLaneRunning) {\n\t\t\treturn { started: false, skipReason: \"research_lane_already_running\" };\n\t\t}\n\t\tif (this.deps.isDisposed()) {\n\t\t\treturn { started: false, skipReason: \"session_disposed\" };\n\t\t}\n\n\t\tconst settings = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tconst demand = request?.query\n\t\t\t? { query: request.query, context: request.context ?? \"\", goalId: request.goalId }\n\t\t\t: this._buildResearchLaneDemand();\n\t\tif (!demand) {\n\t\t\treturn { started: false, skipReason: this._lastResearchLaneSkipReason ?? \"no_research_demand\" };\n\t\t}\n\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_research_model\");\n\t\tif (!shipment.ok) {\n\t\t\tthis._lastResearchLaneSkipReason = shipment.skipReason;\n\t\t\treturn { started: false, skipReason: shipment.skipReason };\n\t\t}\n\t\tconst { model, laneProfile } = shipment;\n\n\t\tthis._isResearchLaneRunning = true;\n\t\tthis._laneTracker.ensureCounterAtLeast(\n\t\t\tgetLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1,\n\t\t);\n\t\tconst startedRecord = this._laneTracker.start({ type: \"research\", goalId: demand.goalId });\n\t\ttry {\n\t\t\tlet spentUsage: Usage | undefined;\n\t\t\t// Best-effort, pointer-first workspace evidence. Derives search terms from the goal/requirement\n\t\t\t// text (not the identity-key query) and is bounded + silent-on-failure: [] == today's behavior.\n\t\t\tconst workspaceSources = await this.deps.collectWorkspaceSources({\n\t\t\t\tquery: `${demand.context}\\n${demand.query}`,\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tmaxSources: settings.maxSources,\n\t\t\t});\n\t\t\tconst maxUsd = clampLaneMaxUsd(settings.maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd);\n\t\t\tconst result = await runResearch({\n\t\t\t\tquery: demand.query,\n\t\t\t\tcontext: demand.context,\n\t\t\t\tsources: workspaceSources,\n\t\t\t\tenvelope: this._buildResearchLaneEnvelope(maxUsd, laneProfile),\n\t\t\t\tmaxUsd,\n\t\t\t\tmaxSources: settings.maxSources,\n\t\t\t\tmaxFindings: settings.maxFindings,\n\t\t\t\tmaxWallClockMs: settings.maxWallClockMs,\n\t\t\t\tsignal: this._researchLaneAbort.signal,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t// Level-0 core always survives; profile soul and role prompt are the replaceable\n\t\t\t\t\t\t// layers; a settings-provided prompt replaces everything above the core.\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: laneProfile?.soul,\n\t\t\t\t\t\t\trolePrompt: systemPrompt,\n\t\t\t\t\t\t\toverride: settings.systemPrompt,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: laneProfile?.thinking ?? \"off\",\n\t\t\t\t\t\tmaxTokens: this._laneCapabilityProfile(model).laneMaxOutputTokens,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Core/soul/role are all static per configuration — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tspentUsage = completion.usage;\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};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Bug #21 pattern: if the session was disposed while the completion was in flight, do NOT\n\t\t\t// persist evidence/records/usage against the dead session.\n\t\t\tif (this.deps.isDisposed()) {\n\t\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t\t});\n\t\t\t\treturn { started: true, record, result };\n\t\t\t}\n\n\t\t\tlet evidenceEntryId: string | undefined;\n\t\t\tif (result.bundle) {\n\t\t\t\tevidenceEntryId = this.deps.saveEvidenceBundleSnapshot(result.bundle);\n\t\t\t}\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, {\n\t\t\t\t\tlabel: \"research-lane\",\n\t\t\t\t\treportId: `research:${this.deps.getSessionId()}:${startedRecord.laneId}`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: result.status,\n\t\t\t\treasonCode: result.reasonCode,\n\t\t\t\tcostUsd: result.costUsd,\n\t\t\t\tevidenceEntryId,\n\t\t\t});\n\t\t\tif (record) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\t// G3: a research lane's product is an evidence bundle, so its terminal record maps to\n\t\t\t\t// the evidence_bundle event. Lane outcome only (status/reasonCode/cost) — no findings text.\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.evidenceBundle,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t\thasEvidence: record.evidenceEntryId !== undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { started: true, record, result };\n\t\t} catch (error) {\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treasonCode: \"research_lane_error\",\n\t\t\t});\n\t\t\tif (record && !this.deps.isDisposed()) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.evidenceBundle,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t\thasEvidence: record.evidenceEntryId !== undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Research lane failed: ${message}` });\n\t\t\treturn { started: true, record };\n\t\t} finally {\n\t\t\tthis._isResearchLaneRunning = false;\n\t\t}\n\t}\n\n\t/**\n\t * Run one bounded scout-worker delegation: build a WorkerRequest with a stripped read-only\n\t * envelope, execute it as an isolated completion on a cheap lane, validate the result via\n\t * {@link validateWorkerResult} before acceptance, and persist result + lane record + spawned\n\t * usage (idempotent per-lane reportId). Consumed by the `delegate` tool.\n\t */\n\tasync runWorkerDelegationOnce(request: {\n\t\tinstructions: string;\n\t\t/** Model-provided replacement for the worker role prompt (the level-0 core always remains). */\n\t\tsystemPrompt?: string;\n\t}): Promise<WorkerDelegationRunOutcome> {\n\t\tconst delegationSettings = this.deps.getSettingsManager().getWorkerDelegationSettings();\n\t\tif (this._laneTracker.getActiveCount(\"worker\") >= delegationSettings.maxConcurrent) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_already_running\" };\n\t\t}\n\t\tif (this.deps.isDisposed()) {\n\t\t\treturn { started: false, skipReason: \"session_disposed\" };\n\t\t}\n\t\tconst instructions = request.instructions.trim();\n\t\tif (instructions.length === 0) {\n\t\t\treturn { started: false, skipReason: \"missing_instructions\" };\n\t\t}\n\n\t\tconst settings = delegationSettings;\n\t\tif (!settings.enabled) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_disabled\" };\n\t\t}\n\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_worker_model\");\n\t\tif (!shipment.ok) {\n\t\t\treturn { started: false, skipReason: shipment.skipReason };\n\t\t}\n\t\tconst { model, laneProfile } = shipment;\n\n\t\tthis._laneTracker.ensureCounterAtLeast(\n\t\t\tgetLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1,\n\t\t);\n\t\tconst startedRecord = this._laneTracker.start({ type: \"worker\" });\n\t\tconst maxUsd = Math.min(\n\t\t\tsettings.maxUsd,\n\t\t\tthis.deps.getCapabilityEnvelope()?.maxEstimatedUsd ?? Number.POSITIVE_INFINITY,\n\t\t);\n\t\tconst workerRequest: WorkerRequest = {\n\t\t\tid: startedRecord.laneId,\n\t\t\tinstructions,\n\t\t\troute: {\n\t\t\t\ttier: \"cheap\",\n\t\t\t\trisk: \"read-only\",\n\t\t\t\tconfidence: 1,\n\t\t\t\treasonCode: \"scout_worker\",\n\t\t\t\treasons: [\"Read-only scout delegation\"],\n\t\t\t},\n\t\t\tenvelope: {\n\t\t\t\tid: `worker-${this.deps.getSessionId()}-${startedRecord.laneId}`,\n\t\t\t\tprofileId: laneProfile?.name,\n\t\t\t\t// write_files requires BOTH the opt-in AND an explicit non-empty path scope —\n\t\t\t\t// an unscoped write grant is refused here, not discovered at validation time.\n\t\t\t\tcapabilities:\n\t\t\t\t\tsettings.writeEnabled && settings.writePaths.length > 0 ? [\"read_files\", \"write_files\"] : [\"read_files\"],\n\t\t\t\t...(settings.writeEnabled && settings.writePaths.length > 0\n\t\t\t\t\t? { allowedPaths: [...settings.writePaths] }\n\t\t\t\t\t: {}),\n\t\t\t\t...this._laneProfileToolGrants(laneProfile),\n\t\t\t\tmaxEstimatedUsd: maxUsd,\n\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t},\n\t\t\tmaxEstimatedUsd: maxUsd,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t\t// G8: worker delegation START. Routing/scope codes + budget only — never the instructions text.\n\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerRequest,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tpayload: {\n\t\t\t\tid: workerRequest.id,\n\t\t\t\ttier: workerRequest.route.tier,\n\t\t\t\tcapabilities: [...workerRequest.envelope.capabilities],\n\t\t\t\tmaxEstimatedUsd: workerRequest.maxEstimatedUsd ?? null,\n\t\t\t},\n\t\t});\n\t\tconst usageReportId = `worker:${this.deps.getSessionId()}:${startedRecord.laneId}`;\n\n\t\ttry {\n\t\t\tlet spentUsage: Usage | undefined;\n\t\t\tconst outcome = await runWorker({\n\t\t\t\trequest: workerRequest,\n\t\t\t\tmaxUsd,\n\t\t\t\tmaxWallClockMs: settings.maxWallClockMs,\n\t\t\t\tusageReportId,\n\t\t\t\tsignal: this._workerDelegationAbort.signal,\n\t\t\t\t// Parent validation must use the same relative-path baseline the runner reports in.\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t// Write lane (G2): runner-side action application through the envelope path scope.\n\t\t\t\tapplyActions: workerRequest.envelope.capabilities.includes(\"write_files\")\n\t\t\t\t\t? (actions) => applyWorkerActions({ actions, envelope: workerRequest.envelope, cwd: this.deps.getCwd() })\n\t\t\t\t\t: undefined,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t// Level-0 core always survives. A model-provided prompt (delegate tool) is the most\n\t\t\t\t\t\t// specific override, then the settings-level prompt, then profile soul + role prompt.\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: laneProfile?.soul,\n\t\t\t\t\t\t\trolePrompt: systemPrompt,\n\t\t\t\t\t\t\toverride: request.systemPrompt ?? settings.systemPrompt,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: laneProfile?.thinking ?? \"off\",\n\t\t\t\t\t\tmaxTokens: this._laneCapabilityProfile(model).laneMaxOutputTokens,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Core/soul/role are all static per configuration — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tspentUsage = completion.usage;\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};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Bug #21 pattern: never persist against a disposed session.\n\t\t\tif (this.deps.isDisposed()) {\n\t\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t\t});\n\t\t\t\treturn { started: true, record, outcome };\n\t\t\t}\n\n\t\t\tthis.deps.saveWorkerResultSnapshot(outcome.result, workerRequest);\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"worker-delegation\", reportId: usageReportId });\n\t\t\t}\n\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: outcome.laneStatus,\n\t\t\t\treasonCode: outcome.reasonCode,\n\t\t\t\tcostUsd: outcome.costUsd,\n\t\t\t});\n\t\t\tif (record) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\t// G3: worker lane terminal record -> worker_result event. Lane outcome only\n\t\t\t\t// (status/reasonCode/cost) — never the worker's summary/changed-file text.\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerResult,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { started: true, record, outcome };\n\t\t} catch (error) {\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treasonCode: \"worker_delegation_error\",\n\t\t\t});\n\t\t\tif (record && !this.deps.isDisposed()) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerResult,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Worker delegation failed: ${message}` });\n\t\t\treturn { started: true, record };\n\t\t} finally {\n\t\t}\n\t}\n\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\tif (this.deps.isDisposed()) return { started: false, skipReason: \"session_disposed\" };\n\t\tconst resolved = this.resolveLaneModel(args.model.trim() || undefined);\n\t\tif (!resolved) return { started: false, skipReason: \"model_unresolved_or_unauthenticated\" };\n\t\tconst capability = this._laneCapabilityProfile(resolved);\n\n\t\tconst spent: Usage = {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t};\n\t\tconst report = await runModelFitnessProbe({\n\t\t\ttrials: args.trials,\n\t\t\tsignal: this._researchLaneAbort.signal,\n\t\t\tcapacityProbe:\n\t\t\t\tresolved.provider === \"ollama\" && resolved.contextWindow > 0\n\t\t\t\t\t? { registeredContextWindow: resolved.contextWindow }\n\t\t\t\t\t: undefined,\n\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\tconst callStarted = Date.now();\n\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\tmodel: resolved,\n\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\tmaxTokens: capability.laneMaxOutputTokens,\n\t\t\t\t\tsignal,\n\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t});\n\t\t\t\tconst callMs = Date.now() - callStarted;\n\t\t\t\tspent.input += completion.usage.input;\n\t\t\t\tspent.output += completion.usage.output;\n\t\t\t\tspent.cacheRead += completion.usage.cacheRead;\n\t\t\t\tspent.cacheWrite += completion.usage.cacheWrite;\n\t\t\t\tspent.totalTokens += completion.usage.totalTokens;\n\t\t\t\tspent.cost.input += completion.usage.cost.input;\n\t\t\t\tspent.cost.output += completion.usage.cost.output;\n\t\t\t\tspent.cost.cacheRead += completion.usage.cost.cacheRead;\n\t\t\t\tspent.cost.cacheWrite += completion.usage.cost.cacheWrite;\n\t\t\t\tspent.cost.total += completion.usage.cost.total;\n\t\t\t\treturn {\n\t\t\t\t\ttext: completion.text,\n\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t// Wall-clock fallback for tok/s: providers don't expose pure eval time, so the\n\t\t\t\t\t// measured call time stands in — slightly conservative (includes network/queue).\n\t\t\t\t\toutputTokens: completion.usage.output,\n\t\t\t\t\tevalMs: callMs,\n\t\t\t\t};\n\t\t\t},\n\t\t});\n\t\tif (!this.deps.isDisposed() && (spent.cost.total > 0 || spent.totalTokens > 0)) {\n\t\t\tthis.deps.addSpawnedUsage(spent, { label: \"model-fitness\" });\n\t\t}\n\t\tconst modelRef = `${resolved.provider}/${resolved.id}`;\n\t\t// Fitness is a property of a model ON a host — persist the report host-keyed so role\n\t\t// assignments stay per-machine (a model can await better hardware without being forgotten).\n\t\t// Best-effort: a disk problem must not fail the probe itself.\n\t\ttry {\n\t\t\tif (!this.deps.isDisposed()) {\n\t\t\t\tFitnessStore.forAgentDir(this.deps.getAgentDir()).save(modelRef, report);\n\t\t\t}\n\t\t} catch {\n\t\t\t// best-effort persistence\n\t\t}\n\t\treturn { started: true, model: modelRef, report };\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\ttry {\n\t\t\treturn FitnessStore.forAgentDir(this.deps.getAgentDir()).getForHost();\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"background-lane-controller.js","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,IAAI,MAAM,WAAW,CAAC;AAc7B,OAAO,EAAE,qBAAqB,EAAwB,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EAAmB,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AACrG,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,8BAA8B,EAA+B,MAAM,gCAAgC,CAAC;AAC7G,OAAO,EAAE,kBAAkB,EAAqB,MAAM,gCAAgC,CAAC;AACvF,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAG1D,OAAO,EACN,4BAA4B,EAE5B,qCAAqC,GACrC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,YAAY,EAA4B,MAAM,2BAA2B,CAAC;AAEnF,OAAO,EAA2B,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAC5F,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AA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,CAAC,KAAK,GAAG,CAAC,IAAI,KAAK,CAAC,WAAW,GAAG,CAAC,CAAC,EAAE,CAAC;YAChF,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC,CAAC;QAC9D,CAAC;QACD,MAAM,QAAQ,GAAG,GAAG,QAAQ,CAAC,QAAQ,IAAI,QAAQ,CAAC,EAAE,EAAE,CAAC;QACvD,uFAAqF;QACrF,4FAA4F;QAC5F,8DAA8D;QAC9D,IAAI,CAAC;YACJ,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,CAAC;gBAC7B,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;YAC1E,CAAC;QACF,CAAC;QAAC,MAAM,CAAC;YACR,0BAA0B;QAC3B,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;IAAA,CAClD;IAED,mGAAmG;IACnG,uBAAuB,GAA0B;QAChD,IAAI,CAAC;YACJ,OAAO,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,UAAU,EAAE,CAAC;QACvE,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,EAAE,CAAC;QACX,CAAC;IAAA,CACD;CACD","sourcesContent":["/**\n * Background-lane controller: goal auto-continue, the research lane, scout-worker delegation, and\n * the model-fitness probe.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the lane timers, the\n * single-flight guards, the last research-lane skip reason, the live {@link LaneTracker}, and the\n * session-lifetime abort controllers for in-flight research/worker passes. Everything else it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport path from \"node:path\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, Model, Usage } from \"@caupulican/pi-ai\";\nimport type {\n\tAgentSessionEvent,\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tIsolatedCompletionOptions,\n\tIsolatedCompletionResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session.ts\";\nimport type { CapabilityEnvelope, EvidenceBundle, WorkerRequest, WorkerResult } from \"./autonomy/contracts.ts\";\nimport { createLaneToolSurface, type LaneToolSurface } from \"./autonomy/lane-tool-surface.ts\";\nimport { type LaneRecord, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { safeRealpathSync } from \"./autonomy/path-scope.ts\";\nimport { appendLaneRecordSnapshot, getLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { composeSubagentSystemPrompt } from \"./autonomy/subagent-prompt.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport { applyWorkerActions, type WorkerAction } from \"./delegation/worker-actions.ts\";\nimport { runWorker } from \"./delegation/worker-runner.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport {\n\tderiveModelCapabilityProfile,\n\ttype ModelCapabilityProfile,\n\tscaleContinuationBudgetsForCapability,\n} from \"./model-capability.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { FitnessStore, type StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { NormalizedProfile } from \"./profile-registry.ts\";\nimport { type ModelFitnessReport, runModelFitnessProbe } from \"./research/model-fitness.ts\";\nimport { runResearch } from \"./research/research-runner.ts\";\nimport type { collectWorkspaceSources } from \"./research/workspace-collector.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport function clampLaneMaxUsd(settingsMaxUsd: number, foregroundMaxEstimatedUsd?: number): number {\n\treturn Math.min(settingsMaxUsd, foregroundMaxEstimatedUsd ?? Number.POSITIVE_INFINITY);\n}\n\nexport interface BackgroundLaneControllerDeps {\n\t/** A disposed session must never schedule/persist a lane or continuation. */\n\tisDisposed(): boolean;\n\t/** Child sessions never run the idle research lane (only the top-level session drives autonomy). */\n\tisChildSession(): boolean;\n\t/** This session's id, for lane envelope ids and spawned-usage report ids. */\n\tgetSessionId(): string;\n\t/** The workspace root a lane runs relative to (worker path scope + research source collection). */\n\tgetCwd(): string;\n\t/** Root dir the host-keyed {@link FitnessStore} persists under. */\n\tgetAgentDir(): string;\n\t/** Session log: lane records read/append here and feed lane-history dedupe. */\n\tgetSessionManager(): SessionManager;\n\t/** Autonomy / research-lane / worker-delegation / model-capability settings + the profile registry. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolves a configured lane model pattern against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Session-scoped provider/model quota exhaustion guard. */\n\tisModelExhausted(model: Model<Api>): boolean;\n\t/** The session's current model — lanes inherit it unless a lane model is explicitly configured. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Tool/profile gate: delegation is unavailable when the active surface removes `delegate`. */\n\tisDelegateToolActive(): boolean;\n\t/** Foreground cost ceiling — a lane budget is clamped to it, never exceeds it. */\n\tgetCapabilityEnvelope(): CapabilityEnvelope | undefined;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Emits a session event (only `warning` from this controller). */\n\temit(event: AgentSessionEvent): void;\n\t/** G3/G8 telemetry sink (codes/ids only — never lane product text). */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Durable goal state, if a goal is active (the research lane's demand source). */\n\tgetGoalStateSnapshot(): GoalState | undefined;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Latest persisted evidence bundle, for research-lane dedupe. */\n\tgetEvidenceBundleSnapshot(): EvidenceBundle | undefined;\n\t/** Persist a research lane's evidence bundle to the session log. */\n\tsaveEvidenceBundleSnapshot(bundle: EvidenceBundle): string;\n\t/** Persist a worker delegation's result snapshot to the session log. */\n\tsaveWorkerResultSnapshot(result: WorkerResult, request?: WorkerRequest): string;\n\t/** Roll a lane's spawned usage into session accounting (idempotent per reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** Bounded LLM call fully isolated from the main session; lanes may supply a child tool loop. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\t/** Best-effort workspace evidence collection (silent-on-failure; [] preserves prior behavior). */\n\tcollectWorkspaceSources: typeof collectWorkspaceSources;\n}\n\nexport class BackgroundLaneController {\n\t/** Pending idle timer that starts bounded goal continuation after the session becomes idle. */\n\tprivate _goalAutoContinueTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Guards bounded idle autosteer so continuation prompts do not recursively trigger themselves. */\n\tprivate _isGoalAutoContinuing = false;\n\t/** Pending idle timer that starts an autonomous research pass after the session becomes idle. */\n\tprivate _researchLaneTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Single-flight guard: at most one research pass runs at a time per session. */\n\tprivate _isResearchLaneRunning = false;\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tprivate _lastResearchLaneSkipReason: string | undefined;\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\t/** Session-lifetime abort for in-flight research passes (same pattern as _reflectionAbort). */\n\tprivate readonly _researchLaneAbort = new AbortController();\n\t/** Session-lifetime abort for in-flight delegated workers. */\n\tprivate readonly _workerDelegationAbort = new AbortController();\n\t/** Session-local de-duplication for fail-closed profile grants that cannot bind to lane tools. */\n\tprivate readonly _warnedUnboundLaneToolGrants = new Set<string>();\n\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\treturn this._laneTracker.getRecords();\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this._laneTracker.getActiveCount();\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._lastResearchLaneSkipReason;\n\t}\n\n\t/** Abort any in-flight research pass or delegated worker (called on session dispose). */\n\tabortInFlightLanes(): void {\n\t\tthis._researchLaneAbort.abort();\n\t\tthis._workerDelegationAbort.abort();\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tif (this._goalAutoContinueTimer !== undefined) {\n\t\t\tclearTimeout(this._goalAutoContinueTimer);\n\t\t\tthis._goalAutoContinueTimer = undefined;\n\t\t}\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tif (options?.autoContinueGoal === false || this._isGoalAutoContinuing || this.deps.isDisposed()) return;\n\n\t\t// Small-window models cannot afford multi-thousand-token continuation prompts per idle turn.\n\t\tif (!this.deps.getModelCapabilityProfile().backgroundLanesEnabled) return;\n\n\t\tconst { maxStallTurns, goalAutoContinue, goalAutoContinueDelayMs } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\n\t\tthis.clearGoalAutoContinueTimer();\n\t\tthis._goalAutoContinueTimer = setTimeout(() => {\n\t\t\tthis._goalAutoContinueTimer = undefined;\n\t\t\tvoid this._runScheduledGoalAutoContinue();\n\t\t}, goalAutoContinueDelayMs);\n\n\t\tconst timer = this._goalAutoContinueTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tprivate async _runScheduledGoalAutoContinue(): Promise<void> {\n\t\tif (this._isGoalAutoContinuing || this.deps.isDisposed()) return;\n\n\t\tconst { maxStallTurns, goalContinueTurns, goalContinueMaxWallClockMinutes, goalAutoContinue } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\n\t\t// Lean-window models (16-32k) keep autosteer but at a reduced budget; full passes through.\n\t\tconst scaled = scaleContinuationBudgetsForCapability(this.deps.getModelCapabilityProfile(), {\n\t\t\tmaxTurns: goalContinueTurns,\n\t\t\tmaxWallClockMinutes: goalContinueMaxWallClockMinutes,\n\t\t});\n\n\t\tthis._isGoalAutoContinuing = true;\n\t\ttry {\n\t\t\tawait this.deps.continueGoalLoop({\n\t\t\t\tmaxTurns: scaled.maxTurns,\n\t\t\t\tmaxStallTurns,\n\t\t\t\tmaxWallClockMinutes: scaled.maxWallClockMinutes,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Goal auto-continuation failed: ${message}` });\n\t\t} finally {\n\t\t\tthis._isGoalAutoContinuing = false;\n\t\t}\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tif (this._researchLaneTimer !== undefined) {\n\t\t\tclearTimeout(this._researchLaneTimer);\n\t\t\tthis._researchLaneTimer = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Derive the research demand from durable goal state: an active goal with open requirements,\n\t * deduplicated against the latest persisted bundle so the same requirement set is never\n\t * researched twice (the query is deterministic, so dedupe survives session reload).\n\t */\n\tprivate _buildResearchLaneDemand(): { query: string; context: string; goalId: string } | undefined {\n\t\tconst goal = this.deps.getGoalStateSnapshot();\n\t\tif (!goal || goal.status !== \"active\") {\n\t\t\tthis._lastResearchLaneSkipReason = \"no_active_goal\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst open = goal.requirements.filter((requirement) => requirement.status === \"open\");\n\t\tif (open.length === 0) {\n\t\t\tthis._lastResearchLaneSkipReason = \"no_open_requirements\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst query = `goal:${goal.goalId} requirements:${open\n\t\t\t.map((requirement) => requirement.id)\n\t\t\t.sort()\n\t\t\t.join(\",\")}`;\n\t\tif (this.deps.getEvidenceBundleSnapshot()?.query === query) {\n\t\t\tthis._lastResearchLaneSkipReason = \"recent_evidence_sufficient\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst context = [\n\t\t\t`Goal: ${goal.userGoal}`,\n\t\t\t\"Open requirements:\",\n\t\t\t...open.slice(0, 20).map((requirement) => `- ${requirement.text}`),\n\t\t].join(\"\\n\");\n\t\treturn { query, context, goalId: goal.goalId };\n\t}\n\n\t/**\n\t * Idle trigger for the autonomous research lane (mirrors {@link scheduleGoalAutoContinueFromIdle}).\n\t * All skips are recorded in `_lastResearchLaneSkipReason` and surfaced via diagnostics — the lane\n\t * informs, it never prompts or blocks the foreground.\n\t */\n\tscheduleResearchLaneFromIdle(): void {\n\t\tif (this._isResearchLaneRunning || this.deps.isDisposed() || this.deps.isChildSession()) return;\n\n\t\tconst research = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tif (!research.enabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"research_lane_disabled\";\n\t\t\treturn;\n\t\t}\n\t\tconst { mode } = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (mode === \"off\") {\n\t\t\tthis._lastResearchLaneSkipReason = \"autonomy_mode_off\";\n\t\t\treturn;\n\t\t}\n\t\tconst priorRuns = getLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).filter(\n\t\t\t(record) => record.type === \"research\",\n\t\t).length;\n\t\tif (priorRuns >= research.maxRunsPerSession) {\n\t\t\tthis._lastResearchLaneSkipReason = \"max_runs_reached\";\n\t\t\treturn;\n\t\t}\n\t\tif (!this._buildResearchLaneDemand()) return;\n\t\tconst shipment = this._resolveLaneShipment(research, \"no_research_model\");\n\t\tif (!shipment.ok) {\n\t\t\tthis._lastResearchLaneSkipReason = shipment.skipReason;\n\t\t\treturn;\n\t\t}\n\t\tif (!this._laneCapabilityProfile(shipment.model).backgroundLanesEnabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"model_research_unsupported\";\n\t\t\treturn;\n\t\t}\n\n\t\tthis.clearResearchLaneTimer();\n\t\tthis._researchLaneTimer = setTimeout(() => {\n\t\t\tthis._researchLaneTimer = undefined;\n\t\t\tvoid this._runScheduledResearchLane();\n\t\t}, research.idleDelayMs);\n\n\t\tconst timer = this._researchLaneTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tprivate async _runScheduledResearchLane(): Promise<void> {\n\t\tif (this._isResearchLaneRunning || this.deps.isDisposed()) return;\n\n\t\tconst research = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tconst { mode } = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!research.enabled || mode === \"off\") return;\n\n\t\ttry {\n\t\t\tawait this.runResearchLaneOnce();\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Research lane failed: ${message}` });\n\t\t}\n\t}\n\n\t/** Capability profile for a specific lane model (lane budgets scale to the lane model's window). */\n\tprivate _laneCapabilityProfile(model: Model<Api>): ModelCapabilityProfile {\n\t\treturn deriveModelCapabilityProfile({\n\t\t\tcontextWindow: model.contextWindow,\n\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t});\n\t}\n\n\t/**\n\t * Resolve the model for a background lane. Lanes are shipped BY this session, so they inherit\n\t * the session's own model unless a lane-specific model is explicitly configured — a single-model\n\t * setup (e.g. one local open model) runs its lanes on that same model. An explicitly configured\n\t * pattern that cannot resolve/authenticate is a visible skip, not a silent fallback.\n\t */\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\tif (configuredPattern) {\n\t\t\tconst resolved = resolveCliModel({ cliModel: configuredPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (resolved.model && this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\t\treturn resolved.model;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.deps.getModel() ?? undefined;\n\t}\n\n\t/**\n\t * Resolve what a lane ships with. Precedence: explicit lane model setting, then the lane\n\t * profile's model (a shipped profile with a model MUST be obeyed — unresolvable is a visible\n\t * skip, never a fallback), then generic inheritance of the session model.\n\t */\n\tprivate _resolveLaneShipment(\n\t\tlaneSettings: { model?: string; profile?: string },\n\t\tmissingModelReason: string,\n\t): { ok: true; model: Model<Api>; laneProfile?: NormalizedProfile } | { ok: false; skipReason: string } {\n\t\tlet laneProfile: NormalizedProfile | undefined;\n\t\tif (laneSettings.profile) {\n\t\t\tconst profileRef = laneSettings.profile.trim();\n\t\t\tconst registry = this.deps.getSettingsManager().getProfileRegistry();\n\t\t\tlaneProfile =\n\t\t\t\tprofileRef.startsWith(\"./\") || profileRef.startsWith(\"../\")\n\t\t\t\t\t? registry.resolveProfileRef(profileRef, this.deps.getCwd())\n\t\t\t\t\t: registry.getProfile(profileRef);\n\t\t\tif (!laneProfile) {\n\t\t\t\treturn { ok: false, skipReason: \"lane_profile_not_found\" };\n\t\t\t}\n\t\t}\n\n\t\tlet model: Model<Api> | undefined;\n\t\tif (laneSettings.model) {\n\t\t\tmodel = this.resolveLaneModel(laneSettings.model);\n\t\t\tif (!model) return { ok: false, skipReason: missingModelReason };\n\t\t} else if (laneProfile?.model) {\n\t\t\tmodel = this.resolveLaneModel(laneProfile.model);\n\t\t\tif (!model) return { ok: false, skipReason: \"no_lane_profile_model\" };\n\t\t} else {\n\t\t\tmodel = this.deps.getModel() ?? undefined;\n\t\t\tif (!model) return { ok: false, skipReason: missingModelReason };\n\t\t}\n\t\tif (this.deps.isModelExhausted(model)) {\n\t\t\treturn { ok: false, skipReason: `${model.provider}/${model.id} model exhausted: quota` };\n\t\t}\n\t\treturn { ok: true, model, laneProfile };\n\t}\n\n\tprivate _warnUnboundLaneToolGrants(laneProfile: NormalizedProfile | undefined, surface: LaneToolSurface): void {\n\t\tif (!laneProfile || surface.unboundAllowPatterns.length === 0) return;\n\t\tconst warningKey = `${laneProfile.name}\\0${[...surface.unboundAllowPatterns].sort().join(\"\\0\")}`;\n\t\tif (this._warnedUnboundLaneToolGrants.has(warningKey)) return;\n\t\tthis._warnedUnboundLaneToolGrants.add(warningKey);\n\t\tthis.deps.emit({\n\t\t\ttype: \"warning\",\n\t\t\tmessage: `Lane profile '${laneProfile.name}' grants unavailable isolated-lane tools: ${surface.unboundAllowPatterns.join(\", \")}. Only classified lane tools can execute.`,\n\t\t});\n\t}\n\n\t/** Stripped research envelope — never the foreground/architect envelope. */\n\tprivate _buildResearchLaneEnvelope(\n\t\tmaxUsd: number,\n\t\tlaneProfile: NormalizedProfile | undefined,\n\t\tsurface: LaneToolSurface,\n\t): CapabilityEnvelope {\n\t\treturn {\n\t\t\tid: `research-${this.deps.getSessionId()}-${Date.now()}`,\n\t\t\tprofileId: laneProfile?.name,\n\t\t\tcapabilities: [\"research\", \"read_files\", \"memory_read\"],\n\t\t\tallowedTools: [...surface.allowedTools],\n\t\t\tdeniedTools: [...surface.deniedTools],\n\t\t\tallowedPaths: [this.deps.getCwd()],\n\t\t\tmaxEstimatedUsd: clampLaneMaxUsd(maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd),\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\tif (this._isResearchLaneRunning) {\n\t\t\treturn { started: false, skipReason: \"research_lane_already_running\" };\n\t\t}\n\t\tif (this.deps.isDisposed()) {\n\t\t\treturn { started: false, skipReason: \"session_disposed\" };\n\t\t}\n\n\t\tconst settings = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tconst demand = request?.query\n\t\t\t? { query: request.query, context: request.context ?? \"\", goalId: request.goalId }\n\t\t\t: this._buildResearchLaneDemand();\n\t\tif (!demand) {\n\t\t\treturn { started: false, skipReason: this._lastResearchLaneSkipReason ?? \"no_research_demand\" };\n\t\t}\n\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_research_model\");\n\t\tif (!shipment.ok) {\n\t\t\tthis._lastResearchLaneSkipReason = shipment.skipReason;\n\t\t\treturn { started: false, skipReason: shipment.skipReason };\n\t\t}\n\t\tconst { model, laneProfile } = shipment;\n\t\tconst laneCapability = this._laneCapabilityProfile(model);\n\t\tif (!laneCapability.backgroundLanesEnabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"model_research_unsupported\";\n\t\t\treturn { started: false, skipReason: \"model_research_unsupported\" };\n\t\t}\n\n\t\tthis._isResearchLaneRunning = true;\n\t\tthis._laneTracker.ensureCounterAtLeast(\n\t\t\tgetLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1,\n\t\t);\n\t\tconst startedRecord = this._laneTracker.start({ type: \"research\", goalId: demand.goalId });\n\t\ttry {\n\t\t\tlet spentUsage: Usage | undefined;\n\t\t\t// Best-effort, pointer-first workspace evidence. Derives search terms from the goal/requirement\n\t\t\t// text (not the identity-key query) and is bounded + silent-on-failure: [] == today's behavior.\n\t\t\tconst workspaceSources = await this.deps.collectWorkspaceSources({\n\t\t\t\tquery: `${demand.context}\\n${demand.query}`,\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tmaxSources: settings.maxSources,\n\t\t\t});\n\t\t\tconst maxUsd = clampLaneMaxUsd(settings.maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd);\n\t\t\tconst toolSurface = createLaneToolSurface({ cwd: this.deps.getCwd(), profile: laneProfile });\n\t\t\tthis._warnUnboundLaneToolGrants(laneProfile, toolSurface);\n\t\t\tconst result = await runResearch({\n\t\t\t\tquery: demand.query,\n\t\t\t\tcontext: demand.context,\n\t\t\t\tsources: workspaceSources,\n\t\t\t\tenvelope: this._buildResearchLaneEnvelope(maxUsd, laneProfile, toolSurface),\n\t\t\t\tmaxUsd,\n\t\t\t\tmaxSources: settings.maxSources,\n\t\t\t\tmaxFindings: settings.maxFindings,\n\t\t\t\tmaxWallClockMs: settings.maxWallClockMs,\n\t\t\t\tsignal: this._researchLaneAbort.signal,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t// Level-0 core always survives; profile soul and role prompt are the replaceable\n\t\t\t\t\t\t// layers; a settings-provided prompt replaces everything above the core.\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: laneProfile?.soul,\n\t\t\t\t\t\t\trolePrompt: systemPrompt,\n\t\t\t\t\t\t\toverride: settings.systemPrompt,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: laneProfile?.thinking ?? \"off\",\n\t\t\t\t\t\tmaxTokens: laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\ttools: toolSurface.tools,\n\t\t\t\t\t\tmaxTurns: 6,\n\t\t\t\t\t\tbeforeToolCall: toolSurface.beforeToolCall,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Core/soul/role are all static per configuration — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tspentUsage = completion.usage;\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};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Bug #21 pattern: if the session was disposed while the completion was in flight, do NOT\n\t\t\t// persist evidence/records/usage against the dead session.\n\t\t\tif (this.deps.isDisposed()) {\n\t\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t\t});\n\t\t\t\treturn { started: true, record, result };\n\t\t\t}\n\n\t\t\tlet evidenceEntryId: string | undefined;\n\t\t\tif (result.bundle) {\n\t\t\t\tevidenceEntryId = this.deps.saveEvidenceBundleSnapshot(result.bundle);\n\t\t\t}\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, {\n\t\t\t\t\tlabel: \"research-lane\",\n\t\t\t\t\treportId: `research:${this.deps.getSessionId()}:${startedRecord.laneId}`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: result.status,\n\t\t\t\treasonCode: result.reasonCode,\n\t\t\t\tcostUsd: result.costUsd,\n\t\t\t\tevidenceEntryId,\n\t\t\t});\n\t\t\tif (record) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\t// G3: a research lane's product is an evidence bundle, so its terminal record maps to\n\t\t\t\t// the evidence_bundle event. Lane outcome only (status/reasonCode/cost) — no findings text.\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.evidenceBundle,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t\thasEvidence: record.evidenceEntryId !== undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { started: true, record, result };\n\t\t} catch (error) {\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treasonCode: \"research_lane_error\",\n\t\t\t});\n\t\t\tif (record && !this.deps.isDisposed()) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.evidenceBundle,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t\thasEvidence: record.evidenceEntryId !== undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Research lane failed: ${message}` });\n\t\t\treturn { started: true, record };\n\t\t} finally {\n\t\t\tthis._isResearchLaneRunning = false;\n\t\t}\n\t}\n\n\t/**\n\t * Run one bounded scout-worker delegation: build a WorkerRequest with a stripped read-only\n\t * envelope, execute it as an isolated completion on a cheap lane, validate the result via\n\t * {@link validateWorkerResult} before acceptance, and persist result + lane record + spawned\n\t * usage (idempotent per-lane reportId). Consumed by the `delegate` tool.\n\t */\n\tasync runWorkerDelegationOnce(request: {\n\t\tinstructions: string;\n\t\t/** Model-provided replacement for the worker role prompt (the level-0 core always remains). */\n\t\tsystemPrompt?: string;\n\t}): Promise<WorkerDelegationRunOutcome> {\n\t\tconst delegationSettings = this.deps.getSettingsManager().getWorkerDelegationSettings();\n\t\tif (this._laneTracker.getActiveCount(\"worker\") >= delegationSettings.maxConcurrent) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_already_running\" };\n\t\t}\n\t\tif (this.deps.isDisposed()) {\n\t\t\treturn { started: false, skipReason: \"session_disposed\" };\n\t\t}\n\t\tconst instructions = request.instructions.trim();\n\t\tif (instructions.length === 0) {\n\t\t\treturn { started: false, skipReason: \"missing_instructions\" };\n\t\t}\n\n\t\tconst settings = delegationSettings;\n\t\tif (!this.deps.isDelegateToolActive()) {\n\t\t\treturn { started: false, skipReason: \"delegate_tool_inactive\" };\n\t\t}\n\t\tif (!settings.enabled) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_disabled\" };\n\t\t}\n\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_worker_model\");\n\t\tif (!shipment.ok) {\n\t\t\treturn { started: false, skipReason: shipment.skipReason };\n\t\t}\n\t\tconst { model, laneProfile } = shipment;\n\t\tconst laneCapability = this._laneCapabilityProfile(model);\n\t\tif (!laneCapability.backgroundLanesEnabled) {\n\t\t\treturn { started: false, skipReason: \"model_delegation_unsupported\" };\n\t\t}\n\n\t\tthis._laneTracker.ensureCounterAtLeast(\n\t\t\tgetLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1,\n\t\t);\n\t\tconst startedRecord = this._laneTracker.start({ type: \"worker\" });\n\t\tconst maxUsd = Math.min(\n\t\t\tsettings.maxUsd,\n\t\t\tthis.deps.getCapabilityEnvelope()?.maxEstimatedUsd ?? Number.POSITIVE_INFINITY,\n\t\t);\n\t\tconst writeEnabled = settings.writeEnabled && settings.writePaths.length > 0;\n\t\tconst toolSurface = createLaneToolSurface({\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tprofile: laneProfile,\n\t\t\twriteEnabled,\n\t\t\twritePaths: settings.writePaths,\n\t\t});\n\t\tthis._warnUnboundLaneToolGrants(laneProfile, toolSurface);\n\t\tconst allowedActionOps = new Set<WorkerAction[\"op\"]>(\n\t\t\ttoolSurface.allowedTools.filter((name): name is WorkerAction[\"op\"] => name === \"write\" || name === \"edit\"),\n\t\t);\n\t\tconst writeGranted = writeEnabled && allowedActionOps.size > 0;\n\t\tconst workerRequest: WorkerRequest = {\n\t\t\tid: startedRecord.laneId,\n\t\t\tinstructions,\n\t\t\troute: {\n\t\t\t\ttier: \"cheap\",\n\t\t\t\trisk: writeGranted ? \"scoped-write\" : \"read-only\",\n\t\t\t\tconfidence: 1,\n\t\t\t\treasonCode: \"scout_worker\",\n\t\t\t\treasons: [writeGranted ? \"Path-scoped worker delegation\" : \"Read-only scout delegation\"],\n\t\t\t},\n\t\t\tenvelope: {\n\t\t\t\tid: `worker-${this.deps.getSessionId()}-${startedRecord.laneId}`,\n\t\t\t\tprofileId: laneProfile?.name,\n\t\t\t\t// write_files requires BOTH the opt-in AND an explicit non-empty path scope —\n\t\t\t\t// an unscoped write grant is refused here, not discovered at validation time.\n\t\t\t\tcapabilities: writeGranted ? [\"read_files\", \"write_files\"] : [\"read_files\"],\n\t\t\t\t...(writeGranted ? { allowedPaths: [...settings.writePaths] } : {}),\n\t\t\t\tallowedTools: [...toolSurface.allowedTools],\n\t\t\t\tdeniedTools: [...toolSurface.deniedTools],\n\t\t\t\tmaxEstimatedUsd: maxUsd,\n\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t},\n\t\t\tmaxEstimatedUsd: maxUsd,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t\t// G8: worker delegation START. Routing/scope codes + budget only — never the instructions text.\n\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerRequest,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tpayload: {\n\t\t\t\tid: workerRequest.id,\n\t\t\t\ttier: workerRequest.route.tier,\n\t\t\t\tcapabilities: [...workerRequest.envelope.capabilities],\n\t\t\t\tmaxEstimatedUsd: workerRequest.maxEstimatedUsd ?? null,\n\t\t\t},\n\t\t});\n\t\tconst usageReportId = `worker:${this.deps.getSessionId()}:${startedRecord.laneId}`;\n\n\t\ttry {\n\t\t\tlet spentUsage: Usage | undefined;\n\t\t\tconst toolChangedFiles = new Set<string>();\n\t\t\tconst toolIssues = new Set<string>();\n\t\t\tconst outcome = await runWorker({\n\t\t\t\trequest: workerRequest,\n\t\t\t\tmaxUsd,\n\t\t\t\tmaxWallClockMs: settings.maxWallClockMs,\n\t\t\t\tusageReportId,\n\t\t\t\tgetChangedFiles: () => [...toolChangedFiles],\n\t\t\t\tsignal: this._workerDelegationAbort.signal,\n\t\t\t\t// Parent validation must use the same relative-path baseline the runner reports in.\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t// Write lane (G2): runner-side action application through the envelope path scope.\n\t\t\t\tapplyActions: workerRequest.envelope.capabilities.includes(\"write_files\")\n\t\t\t\t\t? (actions) => {\n\t\t\t\t\t\t\tconst permitted = actions.filter((action) => allowedActionOps.has(action.op));\n\t\t\t\t\t\t\tconst applied = applyWorkerActions({\n\t\t\t\t\t\t\t\tactions: permitted,\n\t\t\t\t\t\t\t\tenvelope: workerRequest.envelope,\n\t\t\t\t\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t...applied,\n\t\t\t\t\t\t\t\trefused: [\n\t\t\t\t\t\t\t\t\t...actions\n\t\t\t\t\t\t\t\t\t\t.filter((action) => !allowedActionOps.has(action.op))\n\t\t\t\t\t\t\t\t\t\t.map((action) => ({\n\t\t\t\t\t\t\t\t\t\t\tpath: action.path,\n\t\t\t\t\t\t\t\t\t\t\treason: `${action.op} is not granted by the lane profile`,\n\t\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t\t...applied.refused,\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: undefined,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t// Level-0 core always survives. A model-provided prompt (delegate tool) is the most\n\t\t\t\t\t\t// specific override, then the settings-level prompt, then profile soul + role prompt.\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: laneProfile?.soul,\n\t\t\t\t\t\t\trolePrompt: systemPrompt,\n\t\t\t\t\t\t\toverride: request.systemPrompt ?? settings.systemPrompt,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: laneProfile?.thinking ?? \"off\",\n\t\t\t\t\t\tmaxTokens: laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\ttools: toolSurface.tools,\n\t\t\t\t\t\tmaxTurns: 6,\n\t\t\t\t\t\tbeforeToolCall: async (context, toolSignal) => {\n\t\t\t\t\t\t\tconst decision = await 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}\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\t// This hook runs only for a validated, gate-approved tool that actually entered\n\t\t\t\t\t\t\t// execution. Record a direct mutation target before inspecting `isError`: write/edit\n\t\t\t\t\t\t\t// may have changed disk and then observed cancellation, timeout, or a late I/O error.\n\t\t\t\t\t\t\t// Pre-gate/profile/path refusals never reach afterToolCall, so they remain unreported.\n\t\t\t\t\t\t\tif (toolCall.name === \"write\" || toolCall.name === \"edit\") {\n\t\t\t\t\t\t\t\tif (args && typeof args === \"object\" && !Array.isArray(args)) {\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(this.deps.getCwd(), 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// Execution was attempted; preserve conservative accounting with the lexical path.\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\ttoolChangedFiles.add(path.relative(this.deps.getCwd(), canonicalPath));\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\t\tif (isError) {\n\t\t\t\t\t\t\t\ttoolIssues.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\treturn undefined;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Core/soul/role are all static per configuration — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tspentUsage = completion.usage;\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: [...toolChangedFiles],\n\t\t\t\t\t\tblockers: [...toolIssues],\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Bug #21 pattern: never persist against a disposed session.\n\t\t\tif (this.deps.isDisposed()) {\n\t\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t\t});\n\t\t\t\treturn { started: true, record, outcome };\n\t\t\t}\n\n\t\t\tthis.deps.saveWorkerResultSnapshot(outcome.result, workerRequest);\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"worker-delegation\", reportId: usageReportId });\n\t\t\t}\n\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: outcome.laneStatus,\n\t\t\t\treasonCode: outcome.reasonCode,\n\t\t\t\tcostUsd: outcome.costUsd,\n\t\t\t});\n\t\t\tif (record) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\t// G3: worker lane terminal record -> worker_result event. Lane outcome only\n\t\t\t\t// (status/reasonCode/cost) — never the worker's summary/changed-file text.\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerResult,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { started: true, record, outcome };\n\t\t} catch (error) {\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treasonCode: \"worker_delegation_error\",\n\t\t\t});\n\t\t\tif (record && !this.deps.isDisposed()) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerResult,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Worker delegation failed: ${message}` });\n\t\t\treturn { started: true, record };\n\t\t} finally {\n\t\t}\n\t}\n\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\tif (this.deps.isDisposed()) return { started: false, skipReason: \"session_disposed\" };\n\t\tconst resolved = this.resolveLaneModel(args.model.trim() || undefined);\n\t\tif (!resolved) return { started: false, skipReason: \"model_unresolved_or_unauthenticated\" };\n\t\tconst capability = this._laneCapabilityProfile(resolved);\n\n\t\tconst spent: Usage = {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t};\n\t\tconst report = await runModelFitnessProbe({\n\t\t\ttrials: args.trials,\n\t\t\tsignal: this._researchLaneAbort.signal,\n\t\t\tcapacityProbe:\n\t\t\t\tresolved.provider === \"ollama\" && resolved.contextWindow > 0\n\t\t\t\t\t? { registeredContextWindow: resolved.contextWindow }\n\t\t\t\t\t: undefined,\n\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\tconst callStarted = Date.now();\n\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\tmodel: resolved,\n\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\tmaxTokens: capability.laneMaxOutputTokens,\n\t\t\t\t\tsignal,\n\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t});\n\t\t\t\tconst callMs = Date.now() - callStarted;\n\t\t\t\tspent.input += completion.usage.input;\n\t\t\t\tspent.output += completion.usage.output;\n\t\t\t\tspent.cacheRead += completion.usage.cacheRead;\n\t\t\t\tspent.cacheWrite += completion.usage.cacheWrite;\n\t\t\t\tspent.totalTokens += completion.usage.totalTokens;\n\t\t\t\tspent.cost.input += completion.usage.cost.input;\n\t\t\t\tspent.cost.output += completion.usage.cost.output;\n\t\t\t\tspent.cost.cacheRead += completion.usage.cost.cacheRead;\n\t\t\t\tspent.cost.cacheWrite += completion.usage.cost.cacheWrite;\n\t\t\t\tspent.cost.total += completion.usage.cost.total;\n\t\t\t\treturn {\n\t\t\t\t\ttext: completion.text,\n\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t// Wall-clock fallback for tok/s: providers don't expose pure eval time, so the\n\t\t\t\t\t// measured call time stands in — slightly conservative (includes network/queue).\n\t\t\t\t\toutputTokens: completion.usage.output,\n\t\t\t\t\tevalMs: callMs,\n\t\t\t\t};\n\t\t\t},\n\t\t});\n\t\tif (!this.deps.isDisposed() && (spent.cost.total > 0 || spent.totalTokens > 0)) {\n\t\t\tthis.deps.addSpawnedUsage(spent, { label: \"model-fitness\" });\n\t\t}\n\t\tconst modelRef = `${resolved.provider}/${resolved.id}`;\n\t\t// Fitness is a property of a model ON a host — persist the report host-keyed so role\n\t\t// assignments stay per-machine (a model can await better hardware without being forgotten).\n\t\t// Best-effort: a disk problem must not fail the probe itself.\n\t\ttry {\n\t\t\tif (!this.deps.isDisposed()) {\n\t\t\t\tFitnessStore.forAgentDir(this.deps.getAgentDir()).save(modelRef, report);\n\t\t\t}\n\t\t} catch {\n\t\t\t// best-effort persistence\n\t\t}\n\t\treturn { started: true, model: modelRef, report };\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\ttry {\n\t\t\treturn FitnessStore.forAgentDir(this.deps.getAgentDir()).getForHost();\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n"]}
|