@caupulican/pi-adaptative 0.81.5 → 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 +30 -0
- package/dist/core/agent-session.d.ts +8 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +125 -66
- package/dist/core/agent-session.js.map +1 -1
- 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 +10 -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/billing-failover-controller.d.ts +2 -2
- package/dist/core/billing-failover-controller.d.ts.map +1 -1
- package/dist/core/billing-failover-controller.js +2 -8
- package/dist/core/billing-failover-controller.js.map +1 -1
- package/dist/core/compaction-support.d.ts +3 -0
- package/dist/core/compaction-support.d.ts.map +1 -1
- package/dist/core/compaction-support.js +18 -4
- package/dist/core/compaction-support.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +1 -0
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +12 -0
- package/dist/core/context-pipeline.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/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +33 -9
- package/dist/core/extensions/loader.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/models/local-registration.d.ts +1 -0
- package/dist/core/models/local-registration.d.ts.map +1 -1
- package/dist/core/models/local-registration.js +3 -2
- package/dist/core/models/local-registration.js.map +1 -1
- package/dist/core/research/model-fitness.d.ts +16 -0
- package/dist/core/research/model-fitness.d.ts.map +1 -1
- package/dist/core/research/model-fitness.js +74 -1
- package/dist/core/research/model-fitness.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/session-tree-navigator.d.ts.map +1 -1
- package/dist/core/session-tree-navigator.js +1 -0
- package/dist/core/session-tree-navigator.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/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +6 -3
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/migrations.d.ts +1 -0
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +14 -2
- 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 +2 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +107 -91
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +10 -7
- package/dist/modes/interactive/session-flow-commands.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 +45 -44
- 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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-execution-controller.d.ts","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAwB,MAAM,2BAA2B,CAAC;AAC7E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,KAAK,UAAU,EAA6B,MAAM,oBAAoB,CAAC;AAChF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,KAAK,cAAc,EAA6B,MAAM,iBAAiB,CAAC;AAEjF,MAAM,WAAW,2BAA2B;IAC3C,QAAQ,IAAI,KAAK,CAAC;IAClB,iBAAiB,IAAI,cAAc,CAAC;IACpC,kBAAkB,IAAI,eAAe,CAAC;IACtC,yFAAuF;IACvF,WAAW,IAAI,OAAO,CAAC;CACvB;AAED,qBAAa,uBAAuB;IACnC,OAAO,CAAC,
|
|
1
|
+
{"version":3,"file":"bash-execution-controller.d.ts","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EA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* Standalone bash-command execution (the `/bash` path + extension-driven bash).\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the bash abort controller\n * and the pending-message queue that defers appending a bash result while the agent is streaming (so\n * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on\n * agent turn completion. Persists results through the session log via deps.\n */\n\nimport type { Agent, BashExecutionMessage } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { type BashResult, executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BashOperations, createLocalBashOperations } from \"./tools/bash.ts\";\n\nexport interface BashExecutionControllerDeps {\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\tgetSettingsManager(): SettingsManager;\n\t/** Whether the agent is currently streaming — defers appending a bash result if so. */\n\tisStreaming(): boolean;\n}\n\nexport class BashExecutionController {\n\tprivate _bashAbortControllers = new Set<AbortController>();\n\tprivate _pendingBashMessages: BashExecutionMessage[] = [];\n\n\tprivate readonly deps: BashExecutionControllerDeps;\n\n\tconstructor(deps: BashExecutionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: { excludeFromContext?: boolean; operations?: BashOperations },\n\t): Promise<BashResult> {\n\t\tconst abortController = new AbortController();\n\t\tthis._bashAbortControllers.add(abortController);\n\n\t\t// Apply command prefix if configured (e.g., \"shopt -s expand_aliases\" for alias support)\n\t\tconst prefix = this.deps.getSettingsManager().getShellCommandPrefix();\n\t\tconst shellPath = this.deps.getSettingsManager().getShellPath();\n\t\tconst resolvedCommand = prefix ? `${prefix}\\n${command}` : command;\n\t\tconst enableGitFilter = !options?.operations && !prefix && !shellPath;\n\n\t\ttry {\n\t\t\tconst result = await executeBashWithOperations(\n\t\t\t\tresolvedCommand,\n\t\t\t\tthis.deps.getSessionManager().getCwd(),\n\t\t\t\toptions?.operations ?? createLocalBashOperations({ shellPath }),\n\t\t\t\t{\n\t\t\t\t\tonChunk,\n\t\t\t\t\tsignal: abortController.signal,\n\t\t\t\t\tenableGitFilter,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tthis.recordBashResult(command, result, options);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tthis._bashAbortControllers.delete(abortController);\n\t\t}\n\t}\n\n\t/**\n\t * Record a bash execution result in session history.\n\t * Used by executeBash and by extensions that handle bash execution themselves.\n\t */\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {\n\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\trole: \"bashExecution\",\n\t\t\tcommand,\n\t\t\toutput: result.output,\n\t\t\texitCode: result.exitCode,\n\t\t\tcancelled: result.cancelled,\n\t\t\ttruncated: result.truncated,\n\t\t\tfullOutputPath: result.fullOutputPath,\n\t\t\ttimestamp: Date.now(),\n\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t};\n\n\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\tif (this.deps.isStreaming()) {\n\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t} else {\n\t\t\t// Add to agent state immediately\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\t}\n\n\t/**\n\t * Cancel running bash command.\n\t */\n\tabortBash(): void {\n\t\tfor (const controller of this._bashAbortControllers) {\n\t\t\tcontroller.abort();\n\t\t}\n\t}\n\n\t/** Whether a bash command is currently running */\n\tget isBashRunning(): boolean {\n\t\treturn this._bashAbortControllers.size > 0;\n\t}\n\n\t/** Whether there are pending bash messages waiting to be flushed */\n\tget hasPendingBashMessages(): boolean {\n\t\treturn this._pendingBashMessages.length > 0;\n\t}\n\n\t/**\n\t * Flush pending bash messages to agent state and session.\n\t * Called after agent turn completes to maintain proper message ordering.\n\t */\n\tflushPendingBashMessages(): void {\n\t\tif (this._pendingBashMessages.length === 0) return;\n\n\t\tfor (const bashMessage of this._pendingBashMessages) {\n\t\t\t// Add to agent state\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\n\t\tthis._pendingBashMessages = [];\n\t}\n}\n"]}
|
|
@@ -9,14 +9,15 @@
|
|
|
9
9
|
import { executeBashWithOperations } from "./bash-executor.js";
|
|
10
10
|
import { createLocalBashOperations } from "./tools/bash.js";
|
|
11
11
|
export class BashExecutionController {
|
|
12
|
-
|
|
12
|
+
_bashAbortControllers = new Set();
|
|
13
13
|
_pendingBashMessages = [];
|
|
14
14
|
deps;
|
|
15
15
|
constructor(deps) {
|
|
16
16
|
this.deps = deps;
|
|
17
17
|
}
|
|
18
18
|
async executeBash(command, onChunk, options) {
|
|
19
|
-
|
|
19
|
+
const abortController = new AbortController();
|
|
20
|
+
this._bashAbortControllers.add(abortController);
|
|
20
21
|
// Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
|
|
21
22
|
const prefix = this.deps.getSettingsManager().getShellCommandPrefix();
|
|
22
23
|
const shellPath = this.deps.getSettingsManager().getShellPath();
|
|
@@ -25,14 +26,14 @@ export class BashExecutionController {
|
|
|
25
26
|
try {
|
|
26
27
|
const result = await executeBashWithOperations(resolvedCommand, this.deps.getSessionManager().getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
|
|
27
28
|
onChunk,
|
|
28
|
-
signal:
|
|
29
|
+
signal: abortController.signal,
|
|
29
30
|
enableGitFilter,
|
|
30
31
|
});
|
|
31
32
|
this.recordBashResult(command, result, options);
|
|
32
33
|
return result;
|
|
33
34
|
}
|
|
34
35
|
finally {
|
|
35
|
-
this.
|
|
36
|
+
this._bashAbortControllers.delete(abortController);
|
|
36
37
|
}
|
|
37
38
|
}
|
|
38
39
|
/**
|
|
@@ -67,11 +68,13 @@ export class BashExecutionController {
|
|
|
67
68
|
* Cancel running bash command.
|
|
68
69
|
*/
|
|
69
70
|
abortBash() {
|
|
70
|
-
this.
|
|
71
|
+
for (const controller of this._bashAbortControllers) {
|
|
72
|
+
controller.abort();
|
|
73
|
+
}
|
|
71
74
|
}
|
|
72
75
|
/** Whether a bash command is currently running */
|
|
73
76
|
get isBashRunning() {
|
|
74
|
-
return this.
|
|
77
|
+
return this._bashAbortControllers.size > 0;
|
|
75
78
|
}
|
|
76
79
|
/** Whether there are pending bash messages waiting to be flushed */
|
|
77
80
|
get hasPendingBashMessages() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-execution-controller.js","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EAAmB,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAEhF,OAAO,EAAuB,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAUjF,MAAM,OAAO,uBAAuB;IAC3B,
|
|
1
|
+
{"version":3,"file":"bash-execution-controller.js","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EAAmB,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAEhF,OAAO,EAAuB,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAUjF,MAAM,OAAO,uBAAuB;IAC3B,qBAAqB,GAAG,IAAI,GAAG,EAAmB,CAAC;IACnD,oBAAoB,GAA2B,EAAE,CAAC;IAEzC,IAAI,CAA8B;IAEnD,YAAY,IAAiC,EAAE;QAC9C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,KAAK,CAAC,WAAW,CAChB,OAAe,EACf,OAAiC,EACjC,OAAuE,EACjD;QACtB,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;QAC9C,IAAI,CAAC,qBAAqB,CAAC,GAAG,CA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,aAAa,CAAC,WAAW,CAAC,CAAC;QAC1D,CAAC;QAED,IAAI,CAAC,oBAAoB,GAAG,EAAE,CAAC;IAAA,CAC/B;CACD","sourcesContent":["/**\n * Standalone bash-command execution (the `/bash` path + extension-driven bash).\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the bash abort controller\n * and the pending-message queue that defers appending a bash result while the agent is streaming (so\n * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on\n * agent turn completion. Persists results through the session log via deps.\n */\n\nimport type { Agent, BashExecutionMessage } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { type BashResult, executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BashOperations, createLocalBashOperations } from \"./tools/bash.ts\";\n\nexport interface BashExecutionControllerDeps {\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\tgetSettingsManager(): SettingsManager;\n\t/** Whether the agent is currently streaming — defers appending a bash result if so. */\n\tisStreaming(): boolean;\n}\n\nexport class BashExecutionController {\n\tprivate _bashAbortControllers = new Set<AbortController>();\n\tprivate _pendingBashMessages: BashExecutionMessage[] = [];\n\n\tprivate readonly deps: BashExecutionControllerDeps;\n\n\tconstructor(deps: BashExecutionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: { excludeFromContext?: boolean; operations?: BashOperations },\n\t): Promise<BashResult> {\n\t\tconst abortController = new AbortController();\n\t\tthis._bashAbortControllers.add(abortController);\n\n\t\t// Apply command prefix if configured (e.g., \"shopt -s expand_aliases\" for alias support)\n\t\tconst prefix = this.deps.getSettingsManager().getShellCommandPrefix();\n\t\tconst shellPath = this.deps.getSettingsManager().getShellPath();\n\t\tconst resolvedCommand = prefix ? `${prefix}\\n${command}` : command;\n\t\tconst enableGitFilter = !options?.operations && !prefix && !shellPath;\n\n\t\ttry {\n\t\t\tconst result = await executeBashWithOperations(\n\t\t\t\tresolvedCommand,\n\t\t\t\tthis.deps.getSessionManager().getCwd(),\n\t\t\t\toptions?.operations ?? createLocalBashOperations({ shellPath }),\n\t\t\t\t{\n\t\t\t\t\tonChunk,\n\t\t\t\t\tsignal: abortController.signal,\n\t\t\t\t\tenableGitFilter,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tthis.recordBashResult(command, result, options);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tthis._bashAbortControllers.delete(abortController);\n\t\t}\n\t}\n\n\t/**\n\t * Record a bash execution result in session history.\n\t * Used by executeBash and by extensions that handle bash execution themselves.\n\t */\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {\n\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\trole: \"bashExecution\",\n\t\t\tcommand,\n\t\t\toutput: result.output,\n\t\t\texitCode: result.exitCode,\n\t\t\tcancelled: result.cancelled,\n\t\t\ttruncated: result.truncated,\n\t\t\tfullOutputPath: result.fullOutputPath,\n\t\t\ttimestamp: Date.now(),\n\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t};\n\n\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\tif (this.deps.isStreaming()) {\n\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t} else {\n\t\t\t// Add to agent state immediately\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\t}\n\n\t/**\n\t * Cancel running bash command.\n\t */\n\tabortBash(): void {\n\t\tfor (const controller of this._bashAbortControllers) {\n\t\t\tcontroller.abort();\n\t\t}\n\t}\n\n\t/** Whether a bash command is currently running */\n\tget isBashRunning(): boolean {\n\t\treturn this._bashAbortControllers.size > 0;\n\t}\n\n\t/** Whether there are pending bash messages waiting to be flushed */\n\tget hasPendingBashMessages(): boolean {\n\t\treturn this._pendingBashMessages.length > 0;\n\t}\n\n\t/**\n\t * Flush pending bash messages to agent state and session.\n\t * Called after agent turn completes to maintain proper message ordering.\n\t */\n\tflushPendingBashMessages(): void {\n\t\tif (this._pendingBashMessages.length === 0) return;\n\n\t\tfor (const bashMessage of this._pendingBashMessages) {\n\t\t\t// Add to agent state\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\n\t\tthis._pendingBashMessages = [];\n\t}\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Agent } from "@caupulican/pi-agent-core";
|
|
2
|
-
import { classifyFailure } from "@caupulican/pi-agent-core";
|
|
2
|
+
import { type ClassifiedError, classifyFailure } from "@caupulican/pi-agent-core";
|
|
3
3
|
import type { AssistantMessage } from "@caupulican/pi-ai";
|
|
4
4
|
import type { ModelRegistry } from "./model-registry.ts";
|
|
5
5
|
import type { ModelRouterFailoverStatus } from "./model-router/status.ts";
|
|
@@ -33,6 +33,6 @@ export declare class BillingFailoverController {
|
|
|
33
33
|
snapshotExhausted(): string[];
|
|
34
34
|
getLastNotice(): string | undefined;
|
|
35
35
|
getStatus(): ModelRouterFailoverStatus;
|
|
36
|
-
handleAssistantError(message: AssistantMessage): Promise<boolean>;
|
|
36
|
+
handleAssistantError(message: AssistantMessage, classified?: ClassifiedError): Promise<boolean>;
|
|
37
37
|
}
|
|
38
38
|
//# sourceMappingURL=billing-failover-controller.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"billing-failover-controller.d.ts","sourceRoot":"","sources":["../../src/core/billing-failover-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"bill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E,6BAA6B,EAE9C;IAED,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAEhC;IAED,iBAAiB,IAAI,MAAM,EAAE,CAE5B;IAED,aAAa,IAAI,MAAM,GAAG,SAAS,CAElC;IAED,SAAS,IAAI,yBAAyB,CAErC;IAEK,oBAAoB,CAAC,OAAO,EAAE,gBAAgB,EAAE,UAAU,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,CAwBpG;CACD","sourcesContent":["import type { Agent } from \"@caupulican/pi-agent-core\";\nimport { type ClassifiedError, classifyFailure } from \"@caupulican/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@caupulican/pi-ai\";\nimport { decideBillingFailover } from \"./billing-failover.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ModelRouterFailoverStatus } from \"./model-router/status.ts\";\n\nconst DEFAULT_MODEL_PER_PROVIDER: Record<string, string> = {\n\t\"openai-codex\": \"gpt-5.5\",\n};\n\nexport class ExhaustedProviderRegistry {\n\tprivate readonly exhausted = new Map<string, number | undefined>();\n\n\tmarkExhausted(ref: string, until?: number): void {\n\t\tthis.exhausted.set(ref, until);\n\t}\n\n\tisExhausted(ref: string): boolean {\n\t\tconst until = this.exhausted.get(ref);\n\t\tif (until === undefined) return this.exhausted.has(ref);\n\t\tif (Date.now() < until) return true;\n\t\tthis.exhausted.delete(ref);\n\t\treturn false;\n\t}\n\n\tsnapshot(): string[] {\n\t\treturn [...this.exhausted.keys()].filter((ref) => this.isExhausted(ref));\n\t}\n}\n\nexport interface BillingFailoverControllerDeps {\n\tagent: Agent;\n\tmodelRegistry: ModelRegistry;\n\temit(event: { type: \"warning\"; message: string }): void;\n\texhausted: ExhaustedProviderRegistry;\n\tsubscriptionHop?: boolean;\n\trecordFailure?(args: {\n\t\tprovider?: string;\n\t\tmodelId?: string;\n\t\tmessage: string;\n\t\tclassified: ReturnType<typeof classifyFailure>;\n\t}): void;\n}\n\nexport class BillingFailoverController {\n\tprivate readonly deps: BillingFailoverControllerDeps;\n\tprivate lastNotice: string | undefined;\n\n\tconstructor(deps: BillingFailoverControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tisExhausted(ref: string): boolean {\n\t\treturn this.deps.exhausted.isExhausted(ref);\n\t}\n\n\tsnapshotExhausted(): string[] {\n\t\treturn this.deps.exhausted.snapshot();\n\t}\n\n\tgetLastNotice(): string | undefined {\n\t\treturn this.lastNotice;\n\t}\n\n\tgetStatus(): ModelRouterFailoverStatus {\n\t\treturn { exhausted: this.snapshotExhausted(), lastNotice: this.lastNotice };\n\t}\n\n\tasync handleAssistantError(message: AssistantMessage, classified?: ClassifiedError): Promise<boolean> {\n\t\tif (message.stopReason !== \"error\") return false;\n\t\tclassified ??= classifyFailure({ message: message.errorMessage ?? \"\", provider: message.provider });\n\t\tif (classified.reason !== \"billing_or_quota\") return false;\n\t\tconst failedModel = this.deps.modelRegistry.find(message.provider, message.model) ?? this.deps.agent.state.model;\n\t\tconst failedRef = `${failedModel.provider}/${failedModel.id}`;\n\t\tthis.deps.exhausted.markExhausted(failedRef, expiryFromRetryAfter(classified.retryAfterMs));\n\n\t\tconst defaultModelId = DEFAULT_MODEL_PER_PROVIDER[failedModel.provider];\n\t\tconst hop = defaultModelId ? this.deps.modelRegistry.find(failedModel.provider, defaultModelId) : undefined;\n\t\tconst action = decideBillingFailover({\n\t\t\tfailedModel: { provider: failedModel.provider, id: failedModel.id },\n\t\t\tbillingClass: this.deps.modelRegistry.isUsingOAuth(failedModel) ? \"subscription\" : \"metered\",\n\t\t\tproviderDefaultModelId: defaultModelId,\n\t\t\thopResolvesWithAuth: Boolean(hop && this.deps.modelRegistry.hasConfiguredAuth(hop)),\n\t\t\thopExhausted: hop ? this.deps.exhausted.isExhausted(`${hop.provider}/${hop.id}`) : false,\n\t\t\tsubscriptionHop: this.deps.subscriptionHop,\n\t\t});\n\t\tif (action.action === \"failover\") {\n\t\t\tthis.deps.agent.state.model = hop as Model<Api>;\n\t\t}\n\t\tthis.lastNotice = action.notice;\n\t\tthis.deps.emit({ type: \"warning\", message: action.notice });\n\t\treturn true;\n\t}\n}\n\nfunction expiryFromRetryAfter(retryAfterMs: number | undefined): number | undefined {\n\treturn retryAfterMs === undefined ? undefined : Date.now() + retryAfterMs;\n}\n"]}
|
|
@@ -39,16 +39,10 @@ export class BillingFailoverController {
|
|
|
39
39
|
getStatus() {
|
|
40
40
|
return { exhausted: this.snapshotExhausted(), lastNotice: this.lastNotice };
|
|
41
41
|
}
|
|
42
|
-
async handleAssistantError(message) {
|
|
42
|
+
async handleAssistantError(message, classified) {
|
|
43
43
|
if (message.stopReason !== "error")
|
|
44
44
|
return false;
|
|
45
|
-
|
|
46
|
-
this.deps.recordFailure?.({
|
|
47
|
-
provider: message.provider,
|
|
48
|
-
modelId: message.model,
|
|
49
|
-
message: message.errorMessage ?? "",
|
|
50
|
-
classified,
|
|
51
|
-
});
|
|
45
|
+
classified ??= classifyFailure({ message: message.errorMessage ?? "", provider: message.provider });
|
|
52
46
|
if (classified.reason !== "billing_or_quota")
|
|
53
47
|
return false;
|
|
54
48
|
const failedModel = this.deps.modelRegistry.find(message.provider, message.model) ?? this.deps.agent.state.model;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"billing-failover-controller.js","sourceRoot":"","sources":["../../src/core/billing-failover-controller.ts"],"names":[],"mappings":"AACA,OAAO,
|
|
1
|
+
{"version":3,"file":"billing-failover-controller.js","sourceRoot":"","sources":["../../src/core/billing-failover-controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAwB,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAElF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAI9D,MAAM,0BAA0B,GAA2B;IAC1D,cAAc,EAAE,SAAS;CACzB,CAAC;AAEF,MAAM,OAAO,yBAAyB;IACpB,SAAS,GAAG,IAAI,GAAG,EAA8B,CAAC;IAEnE,aAAa,CAAC,GAAW,EAAE,KAAc,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sB,EAAE,cAAc;YACtC,mBAAmB,EAAE,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC;YACnF,YAAY,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,GAAG,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK;YACxF,eAAe,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;SAC1C,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;YAClC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,GAAG,GAAiB,CAAC;QACjD,CAAC;QACD,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;QAChC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;QAC5D,OAAO,IAAI,CAAC;IAAA,CACZ;CACD;AAED,SAAS,oBAAoB,CAAC,YAAgC,EAAsB;IACnF,OAAO,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,YAAY,CAAC;AAAA,CAC1E","sourcesContent":["import type { Agent } from \"@caupulican/pi-agent-core\";\nimport { type ClassifiedError, classifyFailure } from \"@caupulican/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@caupulican/pi-ai\";\nimport { decideBillingFailover } from \"./billing-failover.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ModelRouterFailoverStatus } from \"./model-router/status.ts\";\n\nconst DEFAULT_MODEL_PER_PROVIDER: Record<string, string> = {\n\t\"openai-codex\": \"gpt-5.5\",\n};\n\nexport class ExhaustedProviderRegistry {\n\tprivate readonly exhausted = new Map<string, number | undefined>();\n\n\tmarkExhausted(ref: string, until?: number): void {\n\t\tthis.exhausted.set(ref, until);\n\t}\n\n\tisExhausted(ref: string): boolean {\n\t\tconst until = this.exhausted.get(ref);\n\t\tif (until === undefined) return this.exhausted.has(ref);\n\t\tif (Date.now() < until) return true;\n\t\tthis.exhausted.delete(ref);\n\t\treturn false;\n\t}\n\n\tsnapshot(): string[] {\n\t\treturn [...this.exhausted.keys()].filter((ref) => this.isExhausted(ref));\n\t}\n}\n\nexport interface BillingFailoverControllerDeps {\n\tagent: Agent;\n\tmodelRegistry: ModelRegistry;\n\temit(event: { type: \"warning\"; message: string }): void;\n\texhausted: ExhaustedProviderRegistry;\n\tsubscriptionHop?: boolean;\n\trecordFailure?(args: {\n\t\tprovider?: string;\n\t\tmodelId?: string;\n\t\tmessage: string;\n\t\tclassified: ReturnType<typeof classifyFailure>;\n\t}): void;\n}\n\nexport class BillingFailoverController {\n\tprivate readonly deps: BillingFailoverControllerDeps;\n\tprivate lastNotice: string | undefined;\n\n\tconstructor(deps: BillingFailoverControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tisExhausted(ref: string): boolean {\n\t\treturn this.deps.exhausted.isExhausted(ref);\n\t}\n\n\tsnapshotExhausted(): string[] {\n\t\treturn this.deps.exhausted.snapshot();\n\t}\n\n\tgetLastNotice(): string | undefined {\n\t\treturn this.lastNotice;\n\t}\n\n\tgetStatus(): ModelRouterFailoverStatus {\n\t\treturn { exhausted: this.snapshotExhausted(), lastNotice: this.lastNotice };\n\t}\n\n\tasync handleAssistantError(message: AssistantMessage, classified?: ClassifiedError): Promise<boolean> {\n\t\tif (message.stopReason !== \"error\") return false;\n\t\tclassified ??= classifyFailure({ message: message.errorMessage ?? \"\", provider: message.provider });\n\t\tif (classified.reason !== \"billing_or_quota\") return false;\n\t\tconst failedModel = this.deps.modelRegistry.find(message.provider, message.model) ?? this.deps.agent.state.model;\n\t\tconst failedRef = `${failedModel.provider}/${failedModel.id}`;\n\t\tthis.deps.exhausted.markExhausted(failedRef, expiryFromRetryAfter(classified.retryAfterMs));\n\n\t\tconst defaultModelId = DEFAULT_MODEL_PER_PROVIDER[failedModel.provider];\n\t\tconst hop = defaultModelId ? this.deps.modelRegistry.find(failedModel.provider, defaultModelId) : undefined;\n\t\tconst action = decideBillingFailover({\n\t\t\tfailedModel: { provider: failedModel.provider, id: failedModel.id },\n\t\t\tbillingClass: this.deps.modelRegistry.isUsingOAuth(failedModel) ? \"subscription\" : \"metered\",\n\t\t\tproviderDefaultModelId: defaultModelId,\n\t\t\thopResolvesWithAuth: Boolean(hop && this.deps.modelRegistry.hasConfiguredAuth(hop)),\n\t\t\thopExhausted: hop ? this.deps.exhausted.isExhausted(`${hop.provider}/${hop.id}`) : false,\n\t\t\tsubscriptionHop: this.deps.subscriptionHop,\n\t\t});\n\t\tif (action.action === \"failover\") {\n\t\t\tthis.deps.agent.state.model = hop as Model<Api>;\n\t\t}\n\t\tthis.lastNotice = action.notice;\n\t\tthis.deps.emit({ type: \"warning\", message: action.notice });\n\t\treturn true;\n\t}\n}\n\nfunction expiryFromRetryAfter(retryAfterMs: number | undefined): number | undefined {\n\treturn retryAfterMs === undefined ? undefined : Date.now() + retryAfterMs;\n}\n"]}
|
|
@@ -32,6 +32,7 @@ export declare class CompactionSupport {
|
|
|
32
32
|
private readonly deps;
|
|
33
33
|
private lastSelectionReason;
|
|
34
34
|
constructor(deps: CompactionSupportDeps);
|
|
35
|
+
getLastSelectionReason(): string | undefined;
|
|
35
36
|
getAdaptedSettings(): CompactionSettings;
|
|
36
37
|
getRequestAuth(model: Model<any>): Promise<{
|
|
37
38
|
apiKey?: string;
|
|
@@ -54,6 +55,8 @@ export declare class CompactionSupport {
|
|
|
54
55
|
private modelRef;
|
|
55
56
|
private resolveConfiguredModel;
|
|
56
57
|
private selectConfiguredModel;
|
|
58
|
+
private effectiveContextWindow;
|
|
59
|
+
private modelWithEffectiveWindow;
|
|
57
60
|
private resolveDefaultModel;
|
|
58
61
|
private modelsAreEqual;
|
|
59
62
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-support.d.ts","sourceRoot":"","sources":["../../src/core/compaction-support.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,KAAK,kBAAkB,EAAuB,MAAM,gCAAgC,CAAC;AAC9F,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D,MAAM,WAAW,qBAAqB;IACrC,QAAQ,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IACnC,kBAAkB,IAAI,eAAe,CAAC;IACtC,gBAAgB,IAAI,aAAa,CAAC;IAClC,wGAAsG;IACtG,WAAW,IAAI,OAAO,CAAC;IACvB,0FAA0F;IAC1F,sBAAsB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC,CAAC;IAC1G,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IACvC,sBAAsB,CAAC,GAAG,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAAC;IACpE,iGAAiG;IACjG,gCAAgC,IAAI,MAAM,CAAC;IAC3C,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACnC;AAED,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAwB;IAC7C,OAAO,CAAC,mBAAmB,CAAqB;IAEhD,YAAY,IAAI,EAAE,qBAAqB,EAEtC;IAED,kBAAkB,IAAI,kBAAkB,CAoBvC;IAEK,cAAc,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC;QAChD,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;KACjC,CAAC,CAOD;IAED;;;;;;OAMG;IACG,mBAAmB,CACxB,eAAe,EAAE,KAAK,CAAC,GAAG,CAAC,EAC3B,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,GACtB,OAAO,CAAC;QAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAwBrG;IAED,OAAO,CAAC,iCAAiC;IAKzC,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,sBAAsB;IAQ9B,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,mBAAmB;IAiC3B,OAAO,CAAC,cAAc;IAItB;;;;;OAKG;IACH,YAAY,CAAC,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAuBjD;IAED,0EAA0E;IAC1E,oBAAoB,CACnB,oBAAoB,EAAE,aAAa,GAAG,SAAS,EAC/C,eAAe,EAAE,KAAK,CAAC,GAAG,CAAC,EAC3B,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,GACtB,aAAa,GAAG,SAAS,CAY3B;CACD","sourcesContent":["/**\n * Compaction support: summarizer model selection (#30 cost guard), request-auth resolution\n * with session-model fallback, and window-adapted compaction settings.\n *\n * Extracted verbatim from AgentSession (agent-session.ts) as a narrow-deps collaborator; the\n * session keeps same-signature private delegations at every call-in point.\n */\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { type CompactionSettings, summarizerCanIngest } from \"@caupulican/pi-agent-core/node\";\nimport type { Model } from \"@caupulican/pi-ai\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { evaluateSurfaceFitness } from \"./model-router/fitness-gate.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport interface CompactionSupportDeps {\n\tgetModel(): Model<any> | undefined;\n\tgetSettingsManager(): SettingsManager;\n\tgetModelRegistry(): ModelRegistry;\n\t/** True when the agent's streamFn is (or wraps) the raw streamSimple — auth must be explicit then. */\n\tisRawStream(): boolean;\n\t/** Host auth resolution that THROWS with a user-actionable message when no key exists. */\n\tgetRequiredRequestAuth(model: Model<any>): Promise<{ apiKey?: string; headers?: Record<string, string> }>;\n\tisModelExhausted(ref: string): boolean;\n\tgetStoredFitnessReport(ref: string): ModelFitnessReport | undefined;\n\t/** Estimated tokens of the summarization input (live context; over-estimates, which is safe). */\n\testimateSummarizationInputTokens(): number;\n\temitWarning(message: string): void;\n}\n\nexport class CompactionSupport {\n\tprivate readonly deps: CompactionSupportDeps;\n\tprivate lastSelectionReason: string | undefined;\n\n\tconstructor(deps: CompactionSupportDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tgetAdaptedSettings(): CompactionSettings {\n\t\tconst settings = this.deps.getSettingsManager().getCompactionSettings();\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return settings;\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return settings;\n\n\t\t// Adapt reserveTokens: at most 25% of context window\n\t\tconst maxReserve = Math.floor(contextWindow * 0.25);\n\t\tconst reserveTokens = Math.min(settings.reserveTokens, maxReserve);\n\n\t\t// Adapt keepRecentTokens: at most 50% of context window\n\t\tconst maxKeepRecent = Math.floor(contextWindow * 0.5);\n\t\tconst keepRecentTokens = Math.min(settings.keepRecentTokens, maxKeepRecent);\n\n\t\treturn {\n\t\t\t...settings,\n\t\t\treserveTokens,\n\t\t\tkeepRecentTokens,\n\t\t};\n\t}\n\n\tasync getRequestAuth(model: Model<any>): Promise<{\n\t\tapiKey?: string;\n\t\theaders?: Record<string, string>;\n\t}> {\n\t\tif (this.deps.isRawStream()) {\n\t\t\treturn this.deps.getRequiredRequestAuth(model);\n\t\t}\n\n\t\tconst result = await this.deps.getModelRegistry().getApiKeyAndHeaders(model);\n\t\treturn result.ok ? { apiKey: result.apiKey, headers: result.headers } : {};\n\t}\n\n\t/**\n\t * Resolve the summarizer model AND its request auth for auto-compaction. The cheap auxiliary\n\t * model (#30) can be nominally available yet fail key resolution at request time (expired\n\t * OAuth, revoked key). Falling back to the session model keeps auto-compaction working in\n\t * exactly the situations where manual /compact works; only when neither resolves do we fail —\n\t * and then with a concrete message instead of a silent no-op.\n\t */\n\tasync resolveModelAndAuth(\n\t\tcompactionModel: Model<any>,\n\t\tsessionModel: Model<any>,\n\t): Promise<{ model: Model<any>; apiKey?: string; headers?: Record<string, string>; failure?: string }> {\n\t\tif (this.deps.isRawStream()) {\n\t\t\tconst registry = this.deps.getModelRegistry();\n\t\t\tlet auth = await registry.getApiKeyAndHeaders(compactionModel);\n\t\t\tif (auth.ok && auth.apiKey) {\n\t\t\t\treturn { model: compactionModel, apiKey: auth.apiKey, headers: auth.headers };\n\t\t\t}\n\t\t\tconst isSameModel =\n\t\t\t\tcompactionModel.provider === sessionModel.provider && compactionModel.id === sessionModel.id;\n\t\t\tif (!isSameModel) {\n\t\t\t\tauth = await registry.getApiKeyAndHeaders(sessionModel);\n\t\t\t\tif (auth.ok && auth.apiKey) {\n\t\t\t\t\treturn { model: sessionModel, apiKey: auth.apiKey, headers: auth.headers };\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tmodel: sessionModel,\n\t\t\t\tfailure: `no usable API key for the summarizer (tried ${compactionModel.id}${isSameModel ? \"\" : ` and ${sessionModel.id}`})`,\n\t\t\t};\n\t\t}\n\n\t\t// Custom streamFn owns auth injection (CLI path) — resolve best-effort, never fail here.\n\t\tconst { apiKey, headers } = await this.getRequestAuth(compactionModel);\n\t\treturn { model: compactionModel, apiKey, headers };\n\t}\n\n\tprivate getExplicitCompactionModelSetting(): string | undefined {\n\t\tconst setting = this.deps.getSettingsManager().getCompactionModel().trim();\n\t\treturn setting && setting !== \"auto\" ? setting : undefined;\n\t}\n\n\tprivate modelRef(model: Model<any>): string {\n\t\treturn `${model.provider}/${model.id}`;\n\t}\n\n\tprivate resolveConfiguredModel(pattern: string): { model?: Model<any>; cause?: \"unresolved\" | \"unauthed\" } {\n\t\tconst registry = this.deps.getModelRegistry();\n\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: registry });\n\t\tif (!resolved.model) return { cause: \"unresolved\" };\n\t\tif (!registry.hasConfiguredAuth(resolved.model)) return { cause: \"unauthed\" };\n\t\treturn { model: resolved.model };\n\t}\n\n\tprivate selectConfiguredModel(pattern: string): { model?: Model<any>; cause?: string } {\n\t\tconst resolved = this.resolveConfiguredModel(pattern);\n\t\tif (!resolved.model) return { cause: resolved.cause };\n\t\tif (this.deps.isModelExhausted(this.modelRef(resolved.model))) return { cause: \"exhausted\" };\n\t\treturn { model: resolved.model };\n\t}\n\n\tprivate resolveDefaultModel(sessionModel: Model<any>): Model<any> {\n\t\tconst router = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (!router.enabled || !router.cheapModel) {\n\t\t\tthis.lastSelectionReason = \"session_default\";\n\t\t\treturn sessionModel;\n\t\t}\n\t\tconst selected = this.selectConfiguredModel(router.cheapModel);\n\t\tif (!selected.model) {\n\t\t\tthis.lastSelectionReason = `fallback:${selected.cause}`;\n\t\t\treturn sessionModel;\n\t\t}\n\t\t// Capacity is a hard constraint, independent of the fitness doctrine: a summarizer whose\n\t\t// window cannot hold the actual span produces recall-empty checkpoints (local servers\n\t\t// silently truncate over-window prompts instead of erroring), and the verification gate\n\t\t// then fails deterministically.\n\t\tconst estimatedInputTokens = this.deps.estimateSummarizationInputTokens();\n\t\tif (!summarizerCanIngest(selected.model, estimatedInputTokens)) {\n\t\t\tthis.lastSelectionReason = `fallback:window_too_small(~${Math.ceil(estimatedInputTokens / 1000)}k input vs ${selected.model.contextWindow} window)`;\n\t\t\treturn sessionModel;\n\t\t}\n\t\tconst fitness = this.deps.getStoredFitnessReport(this.modelRef(selected.model));\n\t\tconst verdict = evaluateSurfaceFitness(\"compaction\", fitness);\n\t\tif (!verdict.fit) {\n\t\t\tthis.lastSelectionReason =\n\t\t\t\tverdict.reason === \"lane_failed\"\n\t\t\t\t\t? `fallback:digest_unfit(${verdict.succeeded}/${verdict.total})`\n\t\t\t\t\t: \"fallback:unprobed\";\n\t\t\treturn sessionModel;\n\t\t}\n\t\tthis.lastSelectionReason = \"router_cheap\";\n\t\treturn selected.model;\n\t}\n\n\tprivate modelsAreEqual(left: Model<any>, right: Model<any>): boolean {\n\t\treturn left.provider === right.provider && left.id === right.id;\n\t}\n\n\t/**\n\t * Resolve the model used to SUMMARIZE during compaction. Selection:\n\t * - an explicit `compaction.model` setting wins, but only if its provider is authed (else fall back);\n\t * - `\"auto\"`/unset follows the model router's configured cheap model when the router is enabled;\n\t * - otherwise the session model is used (safe default).\n\t */\n\tresolveModel(sessionModel: Model<any>): Model<any> {\n\t\tconst explicitSetting = this.getExplicitCompactionModelSetting();\n\t\tif (explicitSetting) {\n\t\t\tconst selected = this.selectConfiguredModel(explicitSetting);\n\t\t\tthis.lastSelectionReason = selected.model ? \"explicit\" : `fallback:${selected.cause}`;\n\t\t\tif (!selected.model) this.deps.emitWarning(`Compaction summarizer ${this.lastSelectionReason}`);\n\t\t\t// An explicit user choice is honored (Class C doctrine), but silently sending an\n\t\t\t// over-window prompt yields a recall-empty summary — warn with the numbers.\n\t\t\tif (selected.model) {\n\t\t\t\tconst estimatedInputTokens = this.deps.estimateSummarizationInputTokens();\n\t\t\t\tif (!summarizerCanIngest(selected.model, estimatedInputTokens)) {\n\t\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t\t`Compaction summarizer (explicit setting) likely cannot ingest the current context: ~${Math.ceil(estimatedInputTokens / 1000)}k input tokens vs a ${selected.model.contextWindow}-token window`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn selected.model ?? sessionModel;\n\t\t}\n\t\tconst model = this.resolveDefaultModel(sessionModel);\n\t\tif (this.lastSelectionReason?.startsWith(\"fallback:\")) {\n\t\t\tthis.deps.emitWarning(`Compaction summarizer ${this.lastSelectionReason}`);\n\t\t}\n\t\treturn model;\n\t}\n\n\t/** Default compaction should never inherit expensive session thinking. */\n\tresolveThinkingLevel(\n\t\tsessionThinkingLevel: ThinkingLevel | undefined,\n\t\tcompactionModel: Model<any>,\n\t\tsessionModel: Model<any>,\n\t): ThinkingLevel | undefined {\n\t\tif (this.getExplicitCompactionModelSetting()) return sessionThinkingLevel;\n\n\t\tconst router = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (router.enabled && router.cheapModel) {\n\t\t\tconst routerModel = this.resolveConfiguredModel(router.cheapModel).model;\n\t\t\tif (routerModel && this.modelsAreEqual(routerModel, compactionModel)) {\n\t\t\t\treturn router.cheapThinking ?? \"low\";\n\t\t\t}\n\t\t}\n\n\t\treturn this.modelsAreEqual(compactionModel, sessionModel) ? \"low\" : sessionThinkingLevel;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compaction-support.d.ts","sourceRoot":"","sources":["../../src/core/compaction-support.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,KAAK,kBAAkB,EAAuB,MAAM,gCAAgC,CAAC;AAC9F,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,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;OAMG;IACG,mBAAmB,CACxB,eAAe,EAAE,KAAK,CAAC,GAAG,CAAC,EAC3B,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,GACtB,OAAO,CAAC;QAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAwBrG;IAED,OAAO,CAAC,iCAAiC;IAKzC,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,sBAAsB;IAQ9B,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,sBAAsB;IAM9B,OAAO,CAAC,wBAAwB;IAKhC,OAAO,CAAC,mBAAmB;IAkC3B,OAAO,CAAC,cAAc;IAItB;;;;;OAKG;IACH,YAAY,CAAC,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAwBjD;IAED,0EAA0E;IAC1E,oBAAoB,CACnB,oBAAoB,EAAE,aAAa,GAAG,SAAS,EAC/C,eAAe,EAAE,KAAK,CAAC,GAAG,CAAC,EAC3B,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,GACtB,aAAa,GAAG,SAAS,CAY3B;CACD","sourcesContent":["/**\n * Compaction support: summarizer model selection (#30 cost guard), request-auth resolution\n * with session-model fallback, and window-adapted compaction settings.\n *\n * Extracted verbatim from AgentSession (agent-session.ts) as a narrow-deps collaborator; the\n * session keeps same-signature private delegations at every call-in point.\n */\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { type CompactionSettings, summarizerCanIngest } from \"@caupulican/pi-agent-core/node\";\nimport type { Model } from \"@caupulican/pi-ai\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { evaluateSurfaceFitness } from \"./model-router/fitness-gate.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport interface CompactionSupportDeps {\n\tgetModel(): Model<any> | undefined;\n\tgetSettingsManager(): SettingsManager;\n\tgetModelRegistry(): ModelRegistry;\n\t/** True when the agent's streamFn is (or wraps) the raw streamSimple — auth must be explicit then. */\n\tisRawStream(): boolean;\n\t/** Host auth resolution that THROWS with a user-actionable message when no key exists. */\n\tgetRequiredRequestAuth(model: Model<any>): Promise<{ apiKey?: string; headers?: Record<string, string> }>;\n\tisModelExhausted(ref: string): boolean;\n\tgetStoredFitnessReport(ref: string): ModelFitnessReport | undefined;\n\t/** Estimated tokens of the summarization input (live context; over-estimates, which is safe). */\n\testimateSummarizationInputTokens(): number;\n\temitWarning(message: string): void;\n}\n\nexport class CompactionSupport {\n\tprivate readonly deps: CompactionSupportDeps;\n\tprivate lastSelectionReason: string | undefined;\n\n\tconstructor(deps: CompactionSupportDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tgetLastSelectionReason(): string | undefined {\n\t\treturn this.lastSelectionReason;\n\t}\n\n\tgetAdaptedSettings(): CompactionSettings {\n\t\tconst settings = this.deps.getSettingsManager().getCompactionSettings();\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return settings;\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return settings;\n\n\t\t// Adapt reserveTokens: at most 25% of context window\n\t\tconst maxReserve = Math.floor(contextWindow * 0.25);\n\t\tconst reserveTokens = Math.min(settings.reserveTokens, maxReserve);\n\n\t\t// Adapt keepRecentTokens: at most 50% of context window\n\t\tconst maxKeepRecent = Math.floor(contextWindow * 0.5);\n\t\tconst keepRecentTokens = Math.min(settings.keepRecentTokens, maxKeepRecent);\n\n\t\treturn {\n\t\t\t...settings,\n\t\t\treserveTokens,\n\t\t\tkeepRecentTokens,\n\t\t};\n\t}\n\n\tasync getRequestAuth(model: Model<any>): Promise<{\n\t\tapiKey?: string;\n\t\theaders?: Record<string, string>;\n\t}> {\n\t\tif (this.deps.isRawStream()) {\n\t\t\treturn this.deps.getRequiredRequestAuth(model);\n\t\t}\n\n\t\tconst result = await this.deps.getModelRegistry().getApiKeyAndHeaders(model);\n\t\treturn result.ok ? { apiKey: result.apiKey, headers: result.headers } : {};\n\t}\n\n\t/**\n\t * Resolve the summarizer model AND its request auth for auto-compaction. The cheap auxiliary\n\t * model (#30) can be nominally available yet fail key resolution at request time (expired\n\t * OAuth, revoked key). Falling back to the session model keeps auto-compaction working in\n\t * exactly the situations where manual /compact works; only when neither resolves do we fail —\n\t * and then with a concrete message instead of a silent no-op.\n\t */\n\tasync resolveModelAndAuth(\n\t\tcompactionModel: Model<any>,\n\t\tsessionModel: Model<any>,\n\t): Promise<{ model: Model<any>; apiKey?: string; headers?: Record<string, string>; failure?: string }> {\n\t\tif (this.deps.isRawStream()) {\n\t\t\tconst registry = this.deps.getModelRegistry();\n\t\t\tlet auth = await registry.getApiKeyAndHeaders(compactionModel);\n\t\t\tif (auth.ok && auth.apiKey) {\n\t\t\t\treturn { model: compactionModel, apiKey: auth.apiKey, headers: auth.headers };\n\t\t\t}\n\t\t\tconst isSameModel =\n\t\t\t\tcompactionModel.provider === sessionModel.provider && compactionModel.id === sessionModel.id;\n\t\t\tif (!isSameModel) {\n\t\t\t\tauth = await registry.getApiKeyAndHeaders(sessionModel);\n\t\t\t\tif (auth.ok && auth.apiKey) {\n\t\t\t\t\treturn { model: sessionModel, apiKey: auth.apiKey, headers: auth.headers };\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tmodel: sessionModel,\n\t\t\t\tfailure: `no usable API key for the summarizer (tried ${compactionModel.id}${isSameModel ? \"\" : ` and ${sessionModel.id}`})`,\n\t\t\t};\n\t\t}\n\n\t\t// Custom streamFn owns auth injection (CLI path) — resolve best-effort, never fail here.\n\t\tconst { apiKey, headers } = await this.getRequestAuth(compactionModel);\n\t\treturn { model: compactionModel, apiKey, headers };\n\t}\n\n\tprivate getExplicitCompactionModelSetting(): string | undefined {\n\t\tconst setting = this.deps.getSettingsManager().getCompactionModel().trim();\n\t\treturn setting && setting !== \"auto\" ? setting : undefined;\n\t}\n\n\tprivate modelRef(model: Model<any>): string {\n\t\treturn `${model.provider}/${model.id}`;\n\t}\n\n\tprivate resolveConfiguredModel(pattern: string): { model?: Model<any>; cause?: \"unresolved\" | \"unauthed\" } {\n\t\tconst registry = this.deps.getModelRegistry();\n\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: registry });\n\t\tif (!resolved.model) return { cause: \"unresolved\" };\n\t\tif (!registry.hasConfiguredAuth(resolved.model)) return { cause: \"unauthed\" };\n\t\treturn { model: resolved.model };\n\t}\n\n\tprivate selectConfiguredModel(pattern: string): { model?: Model<any>; cause?: string } {\n\t\tconst resolved = this.resolveConfiguredModel(pattern);\n\t\tif (!resolved.model) return { cause: resolved.cause };\n\t\tif (this.deps.isModelExhausted(this.modelRef(resolved.model))) return { cause: \"exhausted\" };\n\t\treturn { model: resolved.model };\n\t}\n\n\tprivate effectiveContextWindow(model: Model<any>): number {\n\t\tconst registered = model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n\t\tconst served = this.deps.getStoredFitnessReport(this.modelRef(model))?.capacity?.servedContextWindow;\n\t\treturn served && served > 0 ? Math.min(registered, served) : registered;\n\t}\n\n\tprivate modelWithEffectiveWindow(model: Model<any>): Model<any> {\n\t\tconst contextWindow = this.effectiveContextWindow(model);\n\t\treturn contextWindow === model.contextWindow ? model : { ...model, contextWindow };\n\t}\n\n\tprivate resolveDefaultModel(sessionModel: Model<any>): Model<any> {\n\t\tconst router = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (!router.enabled || !router.cheapModel) {\n\t\t\tthis.lastSelectionReason = \"session_default\";\n\t\t\treturn sessionModel;\n\t\t}\n\t\tconst selected = this.selectConfiguredModel(router.cheapModel);\n\t\tif (!selected.model) {\n\t\t\tthis.lastSelectionReason = `fallback:${selected.cause}`;\n\t\t\treturn sessionModel;\n\t\t}\n\t\t// Capacity is a hard constraint, independent of the fitness doctrine: a summarizer whose\n\t\t// window cannot hold the actual span produces recall-empty checkpoints (local servers\n\t\t// silently truncate over-window prompts instead of erroring), and the verification gate\n\t\t// then fails deterministically.\n\t\tconst estimatedInputTokens = this.deps.estimateSummarizationInputTokens();\n\t\tconst effectiveWindow = this.effectiveContextWindow(selected.model);\n\t\tif (!summarizerCanIngest(this.modelWithEffectiveWindow(selected.model), estimatedInputTokens)) {\n\t\t\tthis.lastSelectionReason = `fallback:window_too_small(~${Math.ceil(estimatedInputTokens / 1000)}k input vs ${effectiveWindow} window)`;\n\t\t\treturn sessionModel;\n\t\t}\n\t\tconst fitness = this.deps.getStoredFitnessReport(this.modelRef(selected.model));\n\t\tconst verdict = evaluateSurfaceFitness(\"compaction\", fitness);\n\t\tif (!verdict.fit) {\n\t\t\tthis.lastSelectionReason =\n\t\t\t\tverdict.reason === \"lane_failed\"\n\t\t\t\t\t? `fallback:digest_unfit(${verdict.succeeded}/${verdict.total})`\n\t\t\t\t\t: \"fallback:unprobed\";\n\t\t\treturn sessionModel;\n\t\t}\n\t\tthis.lastSelectionReason = \"router_cheap\";\n\t\treturn selected.model;\n\t}\n\n\tprivate modelsAreEqual(left: Model<any>, right: Model<any>): boolean {\n\t\treturn left.provider === right.provider && left.id === right.id;\n\t}\n\n\t/**\n\t * Resolve the model used to SUMMARIZE during compaction. Selection:\n\t * - an explicit `compaction.model` setting wins, but only if its provider is authed (else fall back);\n\t * - `\"auto\"`/unset follows the model router's configured cheap model when the router is enabled;\n\t * - otherwise the session model is used (safe default).\n\t */\n\tresolveModel(sessionModel: Model<any>): Model<any> {\n\t\tconst explicitSetting = this.getExplicitCompactionModelSetting();\n\t\tif (explicitSetting) {\n\t\t\tconst selected = this.selectConfiguredModel(explicitSetting);\n\t\t\tthis.lastSelectionReason = selected.model ? \"explicit\" : `fallback:${selected.cause}`;\n\t\t\tif (!selected.model) this.deps.emitWarning(`Compaction summarizer ${this.lastSelectionReason}`);\n\t\t\t// An explicit user choice is honored (Class C doctrine), but silently sending an\n\t\t\t// over-window prompt yields a recall-empty summary — warn with the numbers.\n\t\t\tif (selected.model) {\n\t\t\t\tconst estimatedInputTokens = this.deps.estimateSummarizationInputTokens();\n\t\t\t\tconst effectiveWindow = this.effectiveContextWindow(selected.model);\n\t\t\t\tif (!summarizerCanIngest(this.modelWithEffectiveWindow(selected.model), estimatedInputTokens)) {\n\t\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t\t`Compaction summarizer (explicit setting) likely cannot ingest the current context: ~${Math.ceil(estimatedInputTokens / 1000)}k input tokens vs a ${effectiveWindow}-token window`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn selected.model ?? sessionModel;\n\t\t}\n\t\tconst model = this.resolveDefaultModel(sessionModel);\n\t\tif (this.lastSelectionReason?.startsWith(\"fallback:\")) {\n\t\t\tthis.deps.emitWarning(`Compaction summarizer ${this.lastSelectionReason}`);\n\t\t}\n\t\treturn model;\n\t}\n\n\t/** Default compaction should never inherit expensive session thinking. */\n\tresolveThinkingLevel(\n\t\tsessionThinkingLevel: ThinkingLevel | undefined,\n\t\tcompactionModel: Model<any>,\n\t\tsessionModel: Model<any>,\n\t): ThinkingLevel | undefined {\n\t\tif (this.getExplicitCompactionModelSetting()) return sessionThinkingLevel;\n\n\t\tconst router = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (router.enabled && router.cheapModel) {\n\t\t\tconst routerModel = this.resolveConfiguredModel(router.cheapModel).model;\n\t\t\tif (routerModel && this.modelsAreEqual(routerModel, compactionModel)) {\n\t\t\t\treturn router.cheapThinking ?? \"low\";\n\t\t\t}\n\t\t}\n\n\t\treturn this.modelsAreEqual(compactionModel, sessionModel) ? \"low\" : sessionThinkingLevel;\n\t}\n}\n"]}
|
|
@@ -7,6 +7,9 @@ export class CompactionSupport {
|
|
|
7
7
|
constructor(deps) {
|
|
8
8
|
this.deps = deps;
|
|
9
9
|
}
|
|
10
|
+
getLastSelectionReason() {
|
|
11
|
+
return this.lastSelectionReason;
|
|
12
|
+
}
|
|
10
13
|
getAdaptedSettings() {
|
|
11
14
|
const settings = this.deps.getSettingsManager().getCompactionSettings();
|
|
12
15
|
const model = this.deps.getModel();
|
|
@@ -88,6 +91,15 @@ export class CompactionSupport {
|
|
|
88
91
|
return { cause: "exhausted" };
|
|
89
92
|
return { model: resolved.model };
|
|
90
93
|
}
|
|
94
|
+
effectiveContextWindow(model) {
|
|
95
|
+
const registered = model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;
|
|
96
|
+
const served = this.deps.getStoredFitnessReport(this.modelRef(model))?.capacity?.servedContextWindow;
|
|
97
|
+
return served && served > 0 ? Math.min(registered, served) : registered;
|
|
98
|
+
}
|
|
99
|
+
modelWithEffectiveWindow(model) {
|
|
100
|
+
const contextWindow = this.effectiveContextWindow(model);
|
|
101
|
+
return contextWindow === model.contextWindow ? model : { ...model, contextWindow };
|
|
102
|
+
}
|
|
91
103
|
resolveDefaultModel(sessionModel) {
|
|
92
104
|
const router = this.deps.getSettingsManager().getModelRouterSettings();
|
|
93
105
|
if (!router.enabled || !router.cheapModel) {
|
|
@@ -104,8 +116,9 @@ export class CompactionSupport {
|
|
|
104
116
|
// silently truncate over-window prompts instead of erroring), and the verification gate
|
|
105
117
|
// then fails deterministically.
|
|
106
118
|
const estimatedInputTokens = this.deps.estimateSummarizationInputTokens();
|
|
107
|
-
|
|
108
|
-
|
|
119
|
+
const effectiveWindow = this.effectiveContextWindow(selected.model);
|
|
120
|
+
if (!summarizerCanIngest(this.modelWithEffectiveWindow(selected.model), estimatedInputTokens)) {
|
|
121
|
+
this.lastSelectionReason = `fallback:window_too_small(~${Math.ceil(estimatedInputTokens / 1000)}k input vs ${effectiveWindow} window)`;
|
|
109
122
|
return sessionModel;
|
|
110
123
|
}
|
|
111
124
|
const fitness = this.deps.getStoredFitnessReport(this.modelRef(selected.model));
|
|
@@ -140,8 +153,9 @@ export class CompactionSupport {
|
|
|
140
153
|
// over-window prompt yields a recall-empty summary — warn with the numbers.
|
|
141
154
|
if (selected.model) {
|
|
142
155
|
const estimatedInputTokens = this.deps.estimateSummarizationInputTokens();
|
|
143
|
-
|
|
144
|
-
|
|
156
|
+
const effectiveWindow = this.effectiveContextWindow(selected.model);
|
|
157
|
+
if (!summarizerCanIngest(this.modelWithEffectiveWindow(selected.model), estimatedInputTokens)) {
|
|
158
|
+
this.deps.emitWarning(`Compaction summarizer (explicit setting) likely cannot ingest the current context: ~${Math.ceil(estimatedInputTokens / 1000)}k input tokens vs a ${effectiveWindow}-token window`);
|
|
145
159
|
}
|
|
146
160
|
}
|
|
147
161
|
return selected.model ?? sessionModel;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-support.js","sourceRoot":"","sources":["../../src/core/compaction-support.ts"],"names":[],"mappings":"AAQA,OAAO,EAA2B,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAG9F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AAmBxE,MAAM,OAAO,iBAAiB;IACZ,IAAI,CAAwB;IACrC,mBAAmB,CAAqB;IAEhD,YAAY,IAA2B,EAAE;QACxC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,kBAAkB,GAAuB;QACxC,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC,qBAAqB,EAAE,CAAC;QACxE,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACnC,IAAI,CAAC,KAAK;YAAE,OAAO,QAAQ,CAAC;QAC5B,MAAM,aAAa,GAAG,KAAK,CAAC,aAAa,IAAI,CAAC,CAAC;QAC/C,IAAI,aAAa,IAAI,CAAC;YAAE,OAAO,QAAQ,C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rD,IAAI,IAAI,CAAC,mBAAmB,EAAE,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;YACvD,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,yBAAyB,IAAI,CAAC,mBAAmB,EAAE,CAAC,CAAC;QAC5E,CAAC;QACD,OAAO,KAAK,CAAC;IAAA,CACb;IAED,0EAA0E;IAC1E,oBAAoB,CACnB,oBAA+C,EAC/C,eAA2B,EAC3B,YAAwB,EACI;QAC5B,IAAI,IAAI,CAAC,iCAAiC,EAAE;YAAE,OAAO,oBAAoB,CAAC;QAE1E,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC,sBAAsB,EAAE,CAAC;QACvE,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;YACzC,MAAM,WAAW,GAAG,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC;YACzE,IAAI,WAAW,IAAI,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,eAAe,CAAC,EAAE,CAAC;gBACtE,OAAO,MAAM,CAAC,aAAa,IAAI,KAAK,CAAC;YACtC,CAAC;QACF,CAAC;QAED,OAAO,IAAI,CAAC,cAAc,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,oBAAoB,CAAC;IAAA,CACzF;CACD","sourcesContent":["/**\n * Compaction support: summarizer model selection (#30 cost guard), request-auth resolution\n * with session-model fallback, and window-adapted compaction settings.\n *\n * Extracted verbatim from AgentSession (agent-session.ts) as a narrow-deps collaborator; the\n * session keeps same-signature private delegations at every call-in point.\n */\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { type CompactionSettings, summarizerCanIngest } from \"@caupulican/pi-agent-core/node\";\nimport type { Model } from \"@caupulican/pi-ai\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { evaluateSurfaceFitness } from \"./model-router/fitness-gate.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport interface CompactionSupportDeps {\n\tgetModel(): Model<any> | undefined;\n\tgetSettingsManager(): SettingsManager;\n\tgetModelRegistry(): ModelRegistry;\n\t/** True when the agent's streamFn is (or wraps) the raw streamSimple — auth must be explicit then. */\n\tisRawStream(): boolean;\n\t/** Host auth resolution that THROWS with a user-actionable message when no key exists. */\n\tgetRequiredRequestAuth(model: Model<any>): Promise<{ apiKey?: string; headers?: Record<string, string> }>;\n\tisModelExhausted(ref: string): boolean;\n\tgetStoredFitnessReport(ref: string): ModelFitnessReport | undefined;\n\t/** Estimated tokens of the summarization input (live context; over-estimates, which is safe). */\n\testimateSummarizationInputTokens(): number;\n\temitWarning(message: string): void;\n}\n\nexport class CompactionSupport {\n\tprivate readonly deps: CompactionSupportDeps;\n\tprivate lastSelectionReason: string | undefined;\n\n\tconstructor(deps: CompactionSupportDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tgetAdaptedSettings(): CompactionSettings {\n\t\tconst settings = this.deps.getSettingsManager().getCompactionSettings();\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return settings;\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return settings;\n\n\t\t// Adapt reserveTokens: at most 25% of context window\n\t\tconst maxReserve = Math.floor(contextWindow * 0.25);\n\t\tconst reserveTokens = Math.min(settings.reserveTokens, maxReserve);\n\n\t\t// Adapt keepRecentTokens: at most 50% of context window\n\t\tconst maxKeepRecent = Math.floor(contextWindow * 0.5);\n\t\tconst keepRecentTokens = Math.min(settings.keepRecentTokens, maxKeepRecent);\n\n\t\treturn {\n\t\t\t...settings,\n\t\t\treserveTokens,\n\t\t\tkeepRecentTokens,\n\t\t};\n\t}\n\n\tasync getRequestAuth(model: Model<any>): Promise<{\n\t\tapiKey?: string;\n\t\theaders?: Record<string, string>;\n\t}> {\n\t\tif (this.deps.isRawStream()) {\n\t\t\treturn this.deps.getRequiredRequestAuth(model);\n\t\t}\n\n\t\tconst result = await this.deps.getModelRegistry().getApiKeyAndHeaders(model);\n\t\treturn result.ok ? { apiKey: result.apiKey, headers: result.headers } : {};\n\t}\n\n\t/**\n\t * Resolve the summarizer model AND its request auth for auto-compaction. The cheap auxiliary\n\t * model (#30) can be nominally available yet fail key resolution at request time (expired\n\t * OAuth, revoked key). Falling back to the session model keeps auto-compaction working in\n\t * exactly the situations where manual /compact works; only when neither resolves do we fail —\n\t * and then with a concrete message instead of a silent no-op.\n\t */\n\tasync resolveModelAndAuth(\n\t\tcompactionModel: Model<any>,\n\t\tsessionModel: Model<any>,\n\t): Promise<{ model: Model<any>; apiKey?: string; headers?: Record<string, string>; failure?: string }> {\n\t\tif (this.deps.isRawStream()) {\n\t\t\tconst registry = this.deps.getModelRegistry();\n\t\t\tlet auth = await registry.getApiKeyAndHeaders(compactionModel);\n\t\t\tif (auth.ok && auth.apiKey) {\n\t\t\t\treturn { model: compactionModel, apiKey: auth.apiKey, headers: auth.headers };\n\t\t\t}\n\t\t\tconst isSameModel =\n\t\t\t\tcompactionModel.provider === sessionModel.provider && compactionModel.id === sessionModel.id;\n\t\t\tif (!isSameModel) {\n\t\t\t\tauth = await registry.getApiKeyAndHeaders(sessionModel);\n\t\t\t\tif (auth.ok && auth.apiKey) {\n\t\t\t\t\treturn { model: sessionModel, apiKey: auth.apiKey, headers: auth.headers };\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tmodel: sessionModel,\n\t\t\t\tfailure: `no usable API key for the summarizer (tried ${compactionModel.id}${isSameModel ? \"\" : ` and ${sessionModel.id}`})`,\n\t\t\t};\n\t\t}\n\n\t\t// Custom streamFn owns auth injection (CLI path) — resolve best-effort, never fail here.\n\t\tconst { apiKey, headers } = await this.getRequestAuth(compactionModel);\n\t\treturn { model: compactionModel, apiKey, headers };\n\t}\n\n\tprivate getExplicitCompactionModelSetting(): string | undefined {\n\t\tconst setting = this.deps.getSettingsManager().getCompactionModel().trim();\n\t\treturn setting && setting !== \"auto\" ? setting : undefined;\n\t}\n\n\tprivate modelRef(model: Model<any>): string {\n\t\treturn `${model.provider}/${model.id}`;\n\t}\n\n\tprivate resolveConfiguredModel(pattern: string): { model?: Model<any>; cause?: \"unresolved\" | \"unauthed\" } {\n\t\tconst registry = this.deps.getModelRegistry();\n\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: registry });\n\t\tif (!resolved.model) return { cause: \"unresolved\" };\n\t\tif (!registry.hasConfiguredAuth(resolved.model)) return { cause: \"unauthed\" };\n\t\treturn { model: resolved.model };\n\t}\n\n\tprivate selectConfiguredModel(pattern: string): { model?: Model<any>; cause?: string } {\n\t\tconst resolved = this.resolveConfiguredModel(pattern);\n\t\tif (!resolved.model) return { cause: resolved.cause };\n\t\tif (this.deps.isModelExhausted(this.modelRef(resolved.model))) return { cause: \"exhausted\" };\n\t\treturn { model: resolved.model };\n\t}\n\n\tprivate resolveDefaultModel(sessionModel: Model<any>): Model<any> {\n\t\tconst router = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (!router.enabled || !router.cheapModel) {\n\t\t\tthis.lastSelectionReason = \"session_default\";\n\t\t\treturn sessionModel;\n\t\t}\n\t\tconst selected = this.selectConfiguredModel(router.cheapModel);\n\t\tif (!selected.model) {\n\t\t\tthis.lastSelectionReason = `fallback:${selected.cause}`;\n\t\t\treturn sessionModel;\n\t\t}\n\t\t// Capacity is a hard constraint, independent of the fitness doctrine: a summarizer whose\n\t\t// window cannot hold the actual span produces recall-empty checkpoints (local servers\n\t\t// silently truncate over-window prompts instead of erroring), and the verification gate\n\t\t// then fails deterministically.\n\t\tconst estimatedInputTokens = this.deps.estimateSummarizationInputTokens();\n\t\tif (!summarizerCanIngest(selected.model, estimatedInputTokens)) {\n\t\t\tthis.lastSelectionReason = `fallback:window_too_small(~${Math.ceil(estimatedInputTokens / 1000)}k input vs ${selected.model.contextWindow} window)`;\n\t\t\treturn sessionModel;\n\t\t}\n\t\tconst fitness = this.deps.getStoredFitnessReport(this.modelRef(selected.model));\n\t\tconst verdict = evaluateSurfaceFitness(\"compaction\", fitness);\n\t\tif (!verdict.fit) {\n\t\t\tthis.lastSelectionReason =\n\t\t\t\tverdict.reason === \"lane_failed\"\n\t\t\t\t\t? `fallback:digest_unfit(${verdict.succeeded}/${verdict.total})`\n\t\t\t\t\t: \"fallback:unprobed\";\n\t\t\treturn sessionModel;\n\t\t}\n\t\tthis.lastSelectionReason = \"router_cheap\";\n\t\treturn selected.model;\n\t}\n\n\tprivate modelsAreEqual(left: Model<any>, right: Model<any>): boolean {\n\t\treturn left.provider === right.provider && left.id === right.id;\n\t}\n\n\t/**\n\t * Resolve the model used to SUMMARIZE during compaction. Selection:\n\t * - an explicit `compaction.model` setting wins, but only if its provider is authed (else fall back);\n\t * - `\"auto\"`/unset follows the model router's configured cheap model when the router is enabled;\n\t * - otherwise the session model is used (safe default).\n\t */\n\tresolveModel(sessionModel: Model<any>): Model<any> {\n\t\tconst explicitSetting = this.getExplicitCompactionModelSetting();\n\t\tif (explicitSetting) {\n\t\t\tconst selected = this.selectConfiguredModel(explicitSetting);\n\t\t\tthis.lastSelectionReason = selected.model ? \"explicit\" : `fallback:${selected.cause}`;\n\t\t\tif (!selected.model) this.deps.emitWarning(`Compaction summarizer ${this.lastSelectionReason}`);\n\t\t\t// An explicit user choice is honored (Class C doctrine), but silently sending an\n\t\t\t// over-window prompt yields a recall-empty summary — warn with the numbers.\n\t\t\tif (selected.model) {\n\t\t\t\tconst estimatedInputTokens = this.deps.estimateSummarizationInputTokens();\n\t\t\t\tif (!summarizerCanIngest(selected.model, estimatedInputTokens)) {\n\t\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t\t`Compaction summarizer (explicit setting) likely cannot ingest the current context: ~${Math.ceil(estimatedInputTokens / 1000)}k input tokens vs a ${selected.model.contextWindow}-token window`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn selected.model ?? sessionModel;\n\t\t}\n\t\tconst model = this.resolveDefaultModel(sessionModel);\n\t\tif (this.lastSelectionReason?.startsWith(\"fallback:\")) {\n\t\t\tthis.deps.emitWarning(`Compaction summarizer ${this.lastSelectionReason}`);\n\t\t}\n\t\treturn model;\n\t}\n\n\t/** Default compaction should never inherit expensive session thinking. */\n\tresolveThinkingLevel(\n\t\tsessionThinkingLevel: ThinkingLevel | undefined,\n\t\tcompactionModel: Model<any>,\n\t\tsessionModel: Model<any>,\n\t): ThinkingLevel | undefined {\n\t\tif (this.getExplicitCompactionModelSetting()) return sessionThinkingLevel;\n\n\t\tconst router = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (router.enabled && router.cheapModel) {\n\t\t\tconst routerModel = this.resolveConfiguredModel(router.cheapModel).model;\n\t\t\tif (routerModel && this.modelsAreEqual(routerModel, compactionModel)) {\n\t\t\t\treturn router.cheapThinking ?? \"low\";\n\t\t\t}\n\t\t}\n\n\t\treturn this.modelsAreEqual(compactionModel, sessionModel) ? \"low\" : sessionThinkingLevel;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compaction-support.js","sourceRoot":"","sources":["../../src/core/compaction-support.ts"],"names":[],"mappings":"AAQA,OAAO,EAA2B,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAG9F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AAmBxE,MAAM,OAAO,iBAAiB;IACZ,IAAI,CAAwB;IACrC,mBAAmB,CAAqB;IAEhD,YAAY,IAA2B,EAAE;QACxC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,sBAAsB,GAAuB;QAC5C,OAAO,IAAI,CAAC,mBAAmB,CAAC;IAAA,CAChC;IAED,kBAAkB,GAAuB;QACxC,MAAM,QAAQ,GAAG,IAAI,C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E,CAAC;YACvD,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,yBAAyB,IAAI,CAAC,mBAAmB,EAAE,CAAC,CAAC;QAC5E,CAAC;QACD,OAAO,KAAK,CAAC;IAAA,CACb;IAED,0EAA0E;IAC1E,oBAAoB,CACnB,oBAA+C,EAC/C,eAA2B,EAC3B,YAAwB,EACI;QAC5B,IAAI,IAAI,CAAC,iCAAiC,EAAE;YAAE,OAAO,oBAAoB,CAAC;QAE1E,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC,sBAAsB,EAAE,CAAC;QACvE,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;YACzC,MAAM,WAAW,GAAG,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC;YACzE,IAAI,WAAW,IAAI,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,eAAe,CAAC,EAAE,CAAC;gBACtE,OAAO,MAAM,CAAC,aAAa,IAAI,KAAK,CAAC;YACtC,CAAC;QACF,CAAC;QAED,OAAO,IAAI,CAAC,cAAc,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,oBAAoB,CAAC;IAAA,CACzF;CACD","sourcesContent":["/**\n * Compaction support: summarizer model selection (#30 cost guard), request-auth resolution\n * with session-model fallback, and window-adapted compaction settings.\n *\n * Extracted verbatim from AgentSession (agent-session.ts) as a narrow-deps collaborator; the\n * session keeps same-signature private delegations at every call-in point.\n */\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { type CompactionSettings, summarizerCanIngest } from \"@caupulican/pi-agent-core/node\";\nimport type { Model } from \"@caupulican/pi-ai\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { evaluateSurfaceFitness } from \"./model-router/fitness-gate.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport interface CompactionSupportDeps {\n\tgetModel(): Model<any> | undefined;\n\tgetSettingsManager(): SettingsManager;\n\tgetModelRegistry(): ModelRegistry;\n\t/** True when the agent's streamFn is (or wraps) the raw streamSimple — auth must be explicit then. */\n\tisRawStream(): boolean;\n\t/** Host auth resolution that THROWS with a user-actionable message when no key exists. */\n\tgetRequiredRequestAuth(model: Model<any>): Promise<{ apiKey?: string; headers?: Record<string, string> }>;\n\tisModelExhausted(ref: string): boolean;\n\tgetStoredFitnessReport(ref: string): ModelFitnessReport | undefined;\n\t/** Estimated tokens of the summarization input (live context; over-estimates, which is safe). */\n\testimateSummarizationInputTokens(): number;\n\temitWarning(message: string): void;\n}\n\nexport class CompactionSupport {\n\tprivate readonly deps: CompactionSupportDeps;\n\tprivate lastSelectionReason: string | undefined;\n\n\tconstructor(deps: CompactionSupportDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tgetLastSelectionReason(): string | undefined {\n\t\treturn this.lastSelectionReason;\n\t}\n\n\tgetAdaptedSettings(): CompactionSettings {\n\t\tconst settings = this.deps.getSettingsManager().getCompactionSettings();\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return settings;\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return settings;\n\n\t\t// Adapt reserveTokens: at most 25% of context window\n\t\tconst maxReserve = Math.floor(contextWindow * 0.25);\n\t\tconst reserveTokens = Math.min(settings.reserveTokens, maxReserve);\n\n\t\t// Adapt keepRecentTokens: at most 50% of context window\n\t\tconst maxKeepRecent = Math.floor(contextWindow * 0.5);\n\t\tconst keepRecentTokens = Math.min(settings.keepRecentTokens, maxKeepRecent);\n\n\t\treturn {\n\t\t\t...settings,\n\t\t\treserveTokens,\n\t\t\tkeepRecentTokens,\n\t\t};\n\t}\n\n\tasync getRequestAuth(model: Model<any>): Promise<{\n\t\tapiKey?: string;\n\t\theaders?: Record<string, string>;\n\t}> {\n\t\tif (this.deps.isRawStream()) {\n\t\t\treturn this.deps.getRequiredRequestAuth(model);\n\t\t}\n\n\t\tconst result = await this.deps.getModelRegistry().getApiKeyAndHeaders(model);\n\t\treturn result.ok ? { apiKey: result.apiKey, headers: result.headers } : {};\n\t}\n\n\t/**\n\t * Resolve the summarizer model AND its request auth for auto-compaction. The cheap auxiliary\n\t * model (#30) can be nominally available yet fail key resolution at request time (expired\n\t * OAuth, revoked key). Falling back to the session model keeps auto-compaction working in\n\t * exactly the situations where manual /compact works; only when neither resolves do we fail —\n\t * and then with a concrete message instead of a silent no-op.\n\t */\n\tasync resolveModelAndAuth(\n\t\tcompactionModel: Model<any>,\n\t\tsessionModel: Model<any>,\n\t): Promise<{ model: Model<any>; apiKey?: string; headers?: Record<string, string>; failure?: string }> {\n\t\tif (this.deps.isRawStream()) {\n\t\t\tconst registry = this.deps.getModelRegistry();\n\t\t\tlet auth = await registry.getApiKeyAndHeaders(compactionModel);\n\t\t\tif (auth.ok && auth.apiKey) {\n\t\t\t\treturn { model: compactionModel, apiKey: auth.apiKey, headers: auth.headers };\n\t\t\t}\n\t\t\tconst isSameModel =\n\t\t\t\tcompactionModel.provider === sessionModel.provider && compactionModel.id === sessionModel.id;\n\t\t\tif (!isSameModel) {\n\t\t\t\tauth = await registry.getApiKeyAndHeaders(sessionModel);\n\t\t\t\tif (auth.ok && auth.apiKey) {\n\t\t\t\t\treturn { model: sessionModel, apiKey: auth.apiKey, headers: auth.headers };\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tmodel: sessionModel,\n\t\t\t\tfailure: `no usable API key for the summarizer (tried ${compactionModel.id}${isSameModel ? \"\" : ` and ${sessionModel.id}`})`,\n\t\t\t};\n\t\t}\n\n\t\t// Custom streamFn owns auth injection (CLI path) — resolve best-effort, never fail here.\n\t\tconst { apiKey, headers } = await this.getRequestAuth(compactionModel);\n\t\treturn { model: compactionModel, apiKey, headers };\n\t}\n\n\tprivate getExplicitCompactionModelSetting(): string | undefined {\n\t\tconst setting = this.deps.getSettingsManager().getCompactionModel().trim();\n\t\treturn setting && setting !== \"auto\" ? setting : undefined;\n\t}\n\n\tprivate modelRef(model: Model<any>): string {\n\t\treturn `${model.provider}/${model.id}`;\n\t}\n\n\tprivate resolveConfiguredModel(pattern: string): { model?: Model<any>; cause?: \"unresolved\" | \"unauthed\" } {\n\t\tconst registry = this.deps.getModelRegistry();\n\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: registry });\n\t\tif (!resolved.model) return { cause: \"unresolved\" };\n\t\tif (!registry.hasConfiguredAuth(resolved.model)) return { cause: \"unauthed\" };\n\t\treturn { model: resolved.model };\n\t}\n\n\tprivate selectConfiguredModel(pattern: string): { model?: Model<any>; cause?: string } {\n\t\tconst resolved = this.resolveConfiguredModel(pattern);\n\t\tif (!resolved.model) return { cause: resolved.cause };\n\t\tif (this.deps.isModelExhausted(this.modelRef(resolved.model))) return { cause: \"exhausted\" };\n\t\treturn { model: resolved.model };\n\t}\n\n\tprivate effectiveContextWindow(model: Model<any>): number {\n\t\tconst registered = model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n\t\tconst served = this.deps.getStoredFitnessReport(this.modelRef(model))?.capacity?.servedContextWindow;\n\t\treturn served && served > 0 ? Math.min(registered, served) : registered;\n\t}\n\n\tprivate modelWithEffectiveWindow(model: Model<any>): Model<any> {\n\t\tconst contextWindow = this.effectiveContextWindow(model);\n\t\treturn contextWindow === model.contextWindow ? model : { ...model, contextWindow };\n\t}\n\n\tprivate resolveDefaultModel(sessionModel: Model<any>): Model<any> {\n\t\tconst router = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (!router.enabled || !router.cheapModel) {\n\t\t\tthis.lastSelectionReason = \"session_default\";\n\t\t\treturn sessionModel;\n\t\t}\n\t\tconst selected = this.selectConfiguredModel(router.cheapModel);\n\t\tif (!selected.model) {\n\t\t\tthis.lastSelectionReason = `fallback:${selected.cause}`;\n\t\t\treturn sessionModel;\n\t\t}\n\t\t// Capacity is a hard constraint, independent of the fitness doctrine: a summarizer whose\n\t\t// window cannot hold the actual span produces recall-empty checkpoints (local servers\n\t\t// silently truncate over-window prompts instead of erroring), and the verification gate\n\t\t// then fails deterministically.\n\t\tconst estimatedInputTokens = this.deps.estimateSummarizationInputTokens();\n\t\tconst effectiveWindow = this.effectiveContextWindow(selected.model);\n\t\tif (!summarizerCanIngest(this.modelWithEffectiveWindow(selected.model), estimatedInputTokens)) {\n\t\t\tthis.lastSelectionReason = `fallback:window_too_small(~${Math.ceil(estimatedInputTokens / 1000)}k input vs ${effectiveWindow} window)`;\n\t\t\treturn sessionModel;\n\t\t}\n\t\tconst fitness = this.deps.getStoredFitnessReport(this.modelRef(selected.model));\n\t\tconst verdict = evaluateSurfaceFitness(\"compaction\", fitness);\n\t\tif (!verdict.fit) {\n\t\t\tthis.lastSelectionReason =\n\t\t\t\tverdict.reason === \"lane_failed\"\n\t\t\t\t\t? `fallback:digest_unfit(${verdict.succeeded}/${verdict.total})`\n\t\t\t\t\t: \"fallback:unprobed\";\n\t\t\treturn sessionModel;\n\t\t}\n\t\tthis.lastSelectionReason = \"router_cheap\";\n\t\treturn selected.model;\n\t}\n\n\tprivate modelsAreEqual(left: Model<any>, right: Model<any>): boolean {\n\t\treturn left.provider === right.provider && left.id === right.id;\n\t}\n\n\t/**\n\t * Resolve the model used to SUMMARIZE during compaction. Selection:\n\t * - an explicit `compaction.model` setting wins, but only if its provider is authed (else fall back);\n\t * - `\"auto\"`/unset follows the model router's configured cheap model when the router is enabled;\n\t * - otherwise the session model is used (safe default).\n\t */\n\tresolveModel(sessionModel: Model<any>): Model<any> {\n\t\tconst explicitSetting = this.getExplicitCompactionModelSetting();\n\t\tif (explicitSetting) {\n\t\t\tconst selected = this.selectConfiguredModel(explicitSetting);\n\t\t\tthis.lastSelectionReason = selected.model ? \"explicit\" : `fallback:${selected.cause}`;\n\t\t\tif (!selected.model) this.deps.emitWarning(`Compaction summarizer ${this.lastSelectionReason}`);\n\t\t\t// An explicit user choice is honored (Class C doctrine), but silently sending an\n\t\t\t// over-window prompt yields a recall-empty summary — warn with the numbers.\n\t\t\tif (selected.model) {\n\t\t\t\tconst estimatedInputTokens = this.deps.estimateSummarizationInputTokens();\n\t\t\t\tconst effectiveWindow = this.effectiveContextWindow(selected.model);\n\t\t\t\tif (!summarizerCanIngest(this.modelWithEffectiveWindow(selected.model), estimatedInputTokens)) {\n\t\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t\t`Compaction summarizer (explicit setting) likely cannot ingest the current context: ~${Math.ceil(estimatedInputTokens / 1000)}k input tokens vs a ${effectiveWindow}-token window`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn selected.model ?? sessionModel;\n\t\t}\n\t\tconst model = this.resolveDefaultModel(sessionModel);\n\t\tif (this.lastSelectionReason?.startsWith(\"fallback:\")) {\n\t\t\tthis.deps.emitWarning(`Compaction summarizer ${this.lastSelectionReason}`);\n\t\t}\n\t\treturn model;\n\t}\n\n\t/** Default compaction should never inherit expensive session thinking. */\n\tresolveThinkingLevel(\n\t\tsessionThinkingLevel: ThinkingLevel | undefined,\n\t\tcompactionModel: Model<any>,\n\t\tsessionModel: Model<any>,\n\t): ThinkingLevel | undefined {\n\t\tif (this.getExplicitCompactionModelSetting()) return sessionThinkingLevel;\n\n\t\tconst router = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (router.enabled && router.cheapModel) {\n\t\t\tconst routerModel = this.resolveConfiguredModel(router.cheapModel).model;\n\t\t\tif (routerModel && this.modelsAreEqual(routerModel, compactionModel)) {\n\t\t\t\treturn router.cheapThinking ?? \"low\";\n\t\t\t}\n\t\t}\n\n\t\treturn this.modelsAreEqual(compactionModel, sessionModel) ? \"low\" : sessionThinkingLevel;\n\t}\n}\n"]}
|
|
@@ -180,6 +180,7 @@ export declare class ContextPipeline {
|
|
|
180
180
|
* runModelFitness stores reports under it, while settings.model may be a bare id or pattern).
|
|
181
181
|
* Sets _lastCurationSkipReason on refusal; never throws.
|
|
182
182
|
*/
|
|
183
|
+
private _effectiveContextWindowFromFitness;
|
|
183
184
|
resolveCurationModelIfFit(): Model<Api> | undefined;
|
|
184
185
|
maybeDrainBrainCuration(): void;
|
|
185
186
|
/**
|