@caupulican/pi-adaptative 0.81.6 → 0.81.7
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 +17 -0
- package/dist/core/background-lane-controller.d.ts +1 -0
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +7 -3
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts +1 -1
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +9 -6
- package/dist/core/bash-execution-controller.js.map +1 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +7 -2
- package/dist/core/exec.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +19 -5
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/failure-corpus.d.ts.map +1 -1
- package/dist/core/failure-corpus.js +1 -1
- package/dist/core/failure-corpus.js.map +1 -1
- package/dist/core/learning/reflection-engine.d.ts.map +1 -1
- package/dist/core/learning/reflection-engine.js +3 -1
- package/dist/core/learning/reflection-engine.js.map +1 -1
- package/dist/core/scout-controller.d.ts +5 -0
- package/dist/core/scout-controller.d.ts.map +1 -1
- package/dist/core/scout-controller.js +4 -1
- package/dist/core/scout-controller.js.map +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/migrations.d.ts +1 -0
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +7 -1
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.js +14 -6
- package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +1 -0
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +11 -4
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +5 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +1 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +14 -1
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/bug-ledger.md +22 -22
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,20 @@
|
|
|
1
|
+
## [0.81.7] - 2026-07-06
|
|
2
|
+
|
|
3
|
+
### Fixed
|
|
4
|
+
- Fixed native reflection cost deduplication to derive report IDs from a stable turn digest instead of an absent message id.
|
|
5
|
+
- Fixed extension `tool_call` event dispatch so a throwing handler emits diagnostics without skipping later handlers.
|
|
6
|
+
- Fixed settings overlay merging to recurse through nested objects while still replacing arrays.
|
|
7
|
+
- Fixed root-session migration to extract filenames correctly from both POSIX and Windows-style paths.
|
|
8
|
+
- Fixed scout truncation accounting to count assistant output tokens against the output-token cap instead of total input plus output tokens.
|
|
9
|
+
- Fixed reflection-engine malformed-response handling to preserve provider usage after completed calls.
|
|
10
|
+
- Fixed research-lane spend limits to clamp configured lane budgets to the foreground capability envelope.
|
|
11
|
+
- Fixed failure-corpus secret redaction for separator-bearing `sk-proj-` and `sk-ant-` API key formats.
|
|
12
|
+
- Fixed shared exec output decoding to preserve multibyte UTF-8 characters split across stdout/stderr chunks.
|
|
13
|
+
- Fixed overlapping bash execution cancellation so aborting bash cancels every running command instead of only the latest one.
|
|
14
|
+
- Fixed concurrent first-run managed-tool downloads to share one in-flight download per tool.
|
|
15
|
+
- Fixed interactive-mode cleanup leaks by sequence-guarding current-scope session loads and disposing replaced custom editors.
|
|
16
|
+
- Fixed the mutation-barrier regression test to wait on explicit scheduling conditions instead of timing sleeps.
|
|
17
|
+
|
|
1
18
|
## [0.81.6] - 2026-07-06
|
|
2
19
|
|
|
3
20
|
### Fixed
|
|
@@ -28,6 +28,7 @@ import { type StoredFitnessReport } from "./models/fitness-store.ts";
|
|
|
28
28
|
import { type ModelFitnessReport } from "./research/model-fitness.ts";
|
|
29
29
|
import type { collectWorkspaceSources } from "./research/workspace-collector.ts";
|
|
30
30
|
import type { SettingsManager } from "./settings-manager.ts";
|
|
31
|
+
export declare function clampLaneMaxUsd(settingsMaxUsd: number, foregroundMaxEstimatedUsd?: number): number;
|
|
31
32
|
export interface BackgroundLaneControllerDeps {
|
|
32
33
|
/** A disposed session must never schedule/persist a lane or continuation. */
|
|
33
34
|
isDisposed(): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"background-lane-controller.d.ts","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,KAAK,EACX,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,EAC1B,yBAAyB,EACzB,wBAAwB,EACxB,aAAa,EACb,sBAAsB,EACtB,0BAA0B,EAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,kBAAkB,EAAE,cAAc,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAC/G,OAAO,EAAE,KAAK,UAAU,E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,sBAAsB,CAAC,CAgJlC;IAED;;;;;OAKG;IACG,uBAAuB,CAAC,OAAO,EAAE;QACtC,YAAY,EAAE,MAAM,CAAC;QACrB,+FAA+F;QAC/F,YAAY,CAAC,EAAE,MAAM,CAAC;KACtB,GAAG,OAAO,CAAC,0BAA0B,CAAC,CA4KtC;IAED;;;;;OAKG;IACG,eAAe,CAAC,IAAI,EAAE;QAC3B,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,CAAC,EAAE,MAAM,CAAC;KAChB,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,kBAAkB,CAAA;KAAE,GAAG;QAAE,OAAO,EAAE,KAAK,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC,CAqEjH;IAED,mGAAmG;IACnG,uBAAuB,IAAI,mBAAmB,EAAE,CAM/C;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 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: Math.min(\n\t\t\t\tmaxUsd,\n\t\t\t\tthis.deps.getCapabilityEnvelope()?.maxEstimatedUsd ?? Number.POSITIVE_INFINITY,\n\t\t\t),\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 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(settings.maxUsd, laneProfile),\n\t\t\t\tmaxUsd: settings.maxUsd,\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.d.ts","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,KAAK,EACX,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,EAC1B,yBAAyB,EACzB,wBAAwB,EACxB,aAAa,EACb,sBAAsB,EACtB,0BAA0B,EAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,kBAAkB,EAAE,cAAc,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAC/G,OAAO,EAAE,KAAK,UAAU,EAAe,MAAM,4BAA4B,CAAC;AAG1E,OAAO,EAAkC,KAAK,sBAAsB,EAAE,MAAM,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KAChB,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAiJlC;IAED;;;;;OAKG;IACG,uBAAuB,CAAC,OAAO,EAAE;QACtC,YAAY,EAAE,MAAM,CAAC;QACrB,+FAA+F;QAC/F,YAAY,CAAC,EAAE,MAAM,CAAC;KACtB,GAAG,OAAO,CAAC,0BAA0B,CAAC,CA4KtC;IAED;;;;;OAKG;IACG,eAAe,CAAC,IAAI,EAAE;QAC3B,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,CAAC,EAAE,MAAM,CAAC;KAChB,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,kBAAkB,CAAA;KAAE,GAAG;QAAE,OAAO,EAAE,KAAK,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC,CAqEjH;IAED,mGAAmG;IACnG,uBAAuB,IAAI,mBAAmB,EAAE,CAM/C;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"]}
|
|
@@ -25,6 +25,9 @@ import { resolveCliModel } from "./model-resolver.js";
|
|
|
25
25
|
import { FitnessStore } from "./models/fitness-store.js";
|
|
26
26
|
import { runModelFitnessProbe } from "./research/model-fitness.js";
|
|
27
27
|
import { runResearch } from "./research/research-runner.js";
|
|
28
|
+
export function clampLaneMaxUsd(settingsMaxUsd, foregroundMaxEstimatedUsd) {
|
|
29
|
+
return Math.min(settingsMaxUsd, foregroundMaxEstimatedUsd ?? Number.POSITIVE_INFINITY);
|
|
30
|
+
}
|
|
28
31
|
export class BackgroundLaneController {
|
|
29
32
|
/** Pending idle timer that starts bounded goal continuation after the session becomes idle. */
|
|
30
33
|
_goalAutoContinueTimer;
|
|
@@ -290,7 +293,7 @@ export class BackgroundLaneController {
|
|
|
290
293
|
profileId: laneProfile?.name,
|
|
291
294
|
capabilities: ["research", "read_files", "memory_read"],
|
|
292
295
|
...this._laneProfileToolGrants(laneProfile),
|
|
293
|
-
maxEstimatedUsd:
|
|
296
|
+
maxEstimatedUsd: clampLaneMaxUsd(maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd),
|
|
294
297
|
createdAt: new Date().toISOString(),
|
|
295
298
|
};
|
|
296
299
|
}
|
|
@@ -332,12 +335,13 @@ export class BackgroundLaneController {
|
|
|
332
335
|
cwd: this.deps.getCwd(),
|
|
333
336
|
maxSources: settings.maxSources,
|
|
334
337
|
});
|
|
338
|
+
const maxUsd = clampLaneMaxUsd(settings.maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd);
|
|
335
339
|
const result = await runResearch({
|
|
336
340
|
query: demand.query,
|
|
337
341
|
context: demand.context,
|
|
338
342
|
sources: workspaceSources,
|
|
339
|
-
envelope: this._buildResearchLaneEnvelope(
|
|
340
|
-
maxUsd
|
|
343
|
+
envelope: this._buildResearchLaneEnvelope(maxUsd, laneProfile),
|
|
344
|
+
maxUsd,
|
|
341
345
|
maxSources: settings.maxSources,
|
|
342
346
|
maxFindings: settings.maxFindings,
|
|
343
347
|
maxWallClockMs: settings.maxWallClockMs,
|
|
@@ -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,EAAE,kBAAkB,EAAE,MAAM,gCAAg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ACzC,+EAA+E;oBAC/E,mFAAiF;oBACjF,YAAY,EAAE,UAAU,CAAC,KAAK,CAAC,MAAM;oBACrC,MAAM,EAAE,MAAM;iBACd,CAAC;YAAA,CACF;SACD,CAAC,CAAC;QACH,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,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 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 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: Math.min(\n\t\t\t\tmaxUsd,\n\t\t\t\tthis.deps.getCapabilityEnvelope()?.maxEstimatedUsd ?? Number.POSITIVE_INFINITY,\n\t\t\t),\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 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(settings.maxUsd, laneProfile),\n\t\t\t\tmaxUsd: settings.maxUsd,\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","sourceR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I,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 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"]}
|
|
@@ -19,7 +19,7 @@ export interface BashExecutionControllerDeps {
|
|
|
19
19
|
isStreaming(): boolean;
|
|
20
20
|
}
|
|
21
21
|
export declare class BashExecutionController {
|
|
22
|
-
private
|
|
22
|
+
private _bashAbortControllers;
|
|
23
23
|
private _pendingBashMessages;
|
|
24
24
|
private readonly deps;
|
|
25
25
|
constructor(deps: BashExecutionControllerDeps);
|