open-multi-agent-kit 0.90.7 → 0.90.9
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 +52 -0
- package/README.md +17 -10
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +5 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/commands/doctor-provider-cli.d.ts +33 -0
- package/dist/commands/doctor-provider-cli.d.ts.map +1 -0
- package/dist/commands/doctor-provider-cli.js +215 -0
- package/dist/commands/doctor-provider-cli.js.map +1 -0
- package/dist/commands/doctor-provider-transport.d.ts +35 -0
- package/dist/commands/doctor-provider-transport.d.ts.map +1 -0
- package/dist/commands/doctor-provider-transport.js +185 -0
- package/dist/commands/doctor-provider-transport.js.map +1 -0
- package/dist/commands/doctor-provider.d.ts +121 -7
- package/dist/commands/doctor-provider.d.ts.map +1 -1
- package/dist/commands/doctor-provider.js +1295 -102
- package/dist/commands/doctor-provider.js.map +1 -1
- package/dist/commands/session-doctor-cli.d.ts +43 -0
- package/dist/commands/session-doctor-cli.d.ts.map +1 -0
- package/dist/commands/session-doctor-cli.js +494 -0
- package/dist/commands/session-doctor-cli.js.map +1 -0
- package/dist/commands/verify-ci.d.ts +21 -0
- package/dist/commands/verify-ci.d.ts.map +1 -0
- package/dist/commands/verify-ci.js +66 -0
- package/dist/commands/verify-ci.js.map +1 -0
- package/dist/core/agent-session-services.d.ts +3 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +3 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +116 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1015 -71
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/agent-tool-settings.d.ts +35 -0
- package/dist/core/agent-tool-settings.d.ts.map +1 -0
- package/dist/core/agent-tool-settings.js +155 -0
- package/dist/core/agent-tool-settings.js.map +1 -0
- package/dist/core/atomic-session-file.d.ts +14 -0
- package/dist/core/atomic-session-file.d.ts.map +1 -0
- package/dist/core/atomic-session-file.js +104 -0
- package/dist/core/atomic-session-file.js.map +1 -0
- package/dist/core/compaction/compaction.d.ts +6 -0
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +12 -1
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/hysteresis.d.ts +27 -0
- package/dist/core/compaction/hysteresis.d.ts.map +1 -0
- package/dist/core/compaction/hysteresis.js +84 -0
- package/dist/core/compaction/hysteresis.js.map +1 -0
- package/dist/core/compaction/index.d.ts +2 -0
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js +2 -0
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/transaction.d.ts +172 -0
- package/dist/core/compaction/transaction.d.ts.map +1 -0
- package/dist/core/compaction/transaction.js +824 -0
- package/dist/core/compaction/transaction.js.map +1 -0
- package/dist/core/context-budget-governor-v2.d.ts +2 -1
- package/dist/core/context-budget-governor-v2.d.ts.map +1 -1
- package/dist/core/context-budget-governor-v2.js +2 -1
- package/dist/core/context-budget-governor-v2.js.map +1 -1
- package/dist/core/context-budget-headroom.d.ts.map +1 -1
- package/dist/core/context-budget-headroom.js +5 -1
- package/dist/core/context-budget-headroom.js.map +1 -1
- package/dist/core/context-budget-reserved-tokens.d.ts +110 -0
- package/dist/core/context-budget-reserved-tokens.d.ts.map +1 -0
- package/dist/core/context-budget-reserved-tokens.js +188 -0
- package/dist/core/context-budget-reserved-tokens.js.map +1 -0
- package/dist/core/context-budget-v2-cache-invalidation.d.ts +133 -0
- package/dist/core/context-budget-v2-cache-invalidation.d.ts.map +1 -0
- package/dist/core/context-budget-v2-cache-invalidation.js +452 -0
- package/dist/core/context-budget-v2-cache-invalidation.js.map +1 -0
- package/dist/core/context-budget-v2-cache-keys.d.ts +3 -0
- package/dist/core/context-budget-v2-cache-keys.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-keys.js +6 -0
- package/dist/core/context-budget-v2-cache-keys.js.map +1 -1
- package/dist/core/context-budget-v2-cache-provider.d.ts +8 -2
- package/dist/core/context-budget-v2-cache-provider.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-provider.js +28 -5
- package/dist/core/context-budget-v2-cache-provider.js.map +1 -1
- package/dist/core/context-budget-v2-plan-cache-keys.d.ts.map +1 -1
- package/dist/core/context-budget-v2-plan-cache-keys.js +1 -0
- package/dist/core/context-budget-v2-plan-cache-keys.js.map +1 -1
- package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
- package/dist/core/context-budget-v2-planner.js +1 -0
- package/dist/core/context-budget-v2-planner.js.map +1 -1
- package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
- package/dist/core/context-budget-v2-selection.js +9 -0
- package/dist/core/context-budget-v2-selection.js.map +1 -1
- package/dist/core/context-budget-v2-types.d.ts +4 -0
- package/dist/core/context-budget-v2-types.d.ts.map +1 -1
- package/dist/core/context-budget-v2-types.js.map +1 -1
- package/dist/core/durable-file-directory.d.ts +4 -0
- package/dist/core/durable-file-directory.d.ts.map +1 -0
- package/dist/core/durable-file-directory.js +76 -0
- package/dist/core/durable-file-directory.js.map +1 -0
- package/dist/core/durable-file-identity.d.ts +26 -0
- package/dist/core/durable-file-identity.d.ts.map +1 -0
- package/dist/core/durable-file-identity.js +118 -0
- package/dist/core/durable-file-identity.js.map +1 -0
- package/dist/core/durable-file-io.d.ts +29 -0
- package/dist/core/durable-file-io.d.ts.map +1 -0
- package/dist/core/durable-file-io.js +179 -0
- package/dist/core/durable-file-io.js.map +1 -0
- package/dist/core/durable-file-lock-cleanup.d.ts +12 -0
- package/dist/core/durable-file-lock-cleanup.d.ts.map +1 -0
- package/dist/core/durable-file-lock-cleanup.js +39 -0
- package/dist/core/durable-file-lock-cleanup.js.map +1 -0
- package/dist/core/durable-file-lock-owner.d.ts +18 -0
- package/dist/core/durable-file-lock-owner.d.ts.map +1 -0
- package/dist/core/durable-file-lock-owner.js +78 -0
- package/dist/core/durable-file-lock-owner.js.map +1 -0
- package/dist/core/durable-file-lock-storage.d.ts +35 -0
- package/dist/core/durable-file-lock-storage.d.ts.map +1 -0
- package/dist/core/durable-file-lock-storage.js +263 -0
- package/dist/core/durable-file-lock-storage.js.map +1 -0
- package/dist/core/durable-file-mode.d.ts +8 -0
- package/dist/core/durable-file-mode.d.ts.map +1 -0
- package/dist/core/durable-file-mode.js +41 -0
- package/dist/core/durable-file-mode.js.map +1 -0
- package/dist/core/extensions/loader.d.ts +12 -0
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +50 -37
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/index.d.ts +6 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +5 -0
- package/dist/core/index.js.map +1 -1
- package/dist/core/loop-gates.d.ts.map +1 -1
- package/dist/core/loop-gates.js +25 -1
- package/dist/core/loop-gates.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/pi-package-intake.d.ts +1 -0
- package/dist/core/pi-package-intake.d.ts.map +1 -1
- package/dist/core/pi-package-intake.js +7 -0
- package/dist/core/pi-package-intake.js.map +1 -1
- package/dist/core/redaction.d.ts +8 -0
- package/dist/core/redaction.d.ts.map +1 -0
- package/dist/core/redaction.js +31 -0
- package/dist/core/redaction.js.map +1 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +36 -0
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/run-journal-store.d.ts +53 -0
- package/dist/core/run-journal-store.d.ts.map +1 -0
- package/dist/core/run-journal-store.js +278 -0
- package/dist/core/run-journal-store.js.map +1 -0
- package/dist/core/run-journal.d.ts +172 -0
- package/dist/core/run-journal.d.ts.map +1 -0
- package/dist/core/run-journal.js +1053 -0
- package/dist/core/run-journal.js.map +1 -0
- package/dist/core/sdk.d.ts +7 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +94 -3
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-doctor-plan.d.ts +128 -0
- package/dist/core/session-doctor-plan.d.ts.map +1 -0
- package/dist/core/session-doctor-plan.js +833 -0
- package/dist/core/session-doctor-plan.js.map +1 -0
- package/dist/core/session-file-compaction.d.ts +6 -0
- package/dist/core/session-file-compaction.d.ts.map +1 -0
- package/dist/core/session-file-compaction.js +169 -0
- package/dist/core/session-file-compaction.js.map +1 -0
- package/dist/core/session-file-head.d.ts +10 -0
- package/dist/core/session-file-head.d.ts.map +1 -0
- package/dist/core/session-file-head.js +78 -0
- package/dist/core/session-file-head.js.map +1 -0
- package/dist/core/session-file-persistence.d.ts +30 -0
- package/dist/core/session-file-persistence.d.ts.map +1 -0
- package/dist/core/session-file-persistence.js +106 -0
- package/dist/core/session-file-persistence.js.map +1 -0
- package/dist/core/session-integrity.d.ts +43 -0
- package/dist/core/session-integrity.d.ts.map +1 -0
- package/dist/core/session-integrity.js +420 -0
- package/dist/core/session-integrity.js.map +1 -0
- package/dist/core/session-manager.d.ts +24 -4
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +242 -125
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-owner-lease.d.ts +22 -0
- package/dist/core/session-owner-lease.d.ts.map +1 -0
- package/dist/core/session-owner-lease.js +176 -0
- package/dist/core/session-owner-lease.js.map +1 -0
- package/dist/core/session-path-policy.d.ts +132 -0
- package/dist/core/session-path-policy.d.ts.map +1 -0
- package/dist/core/session-path-policy.js +780 -0
- package/dist/core/session-path-policy.js.map +1 -0
- package/dist/core/session-repair-plan.d.ts +49 -0
- package/dist/core/session-repair-plan.d.ts.map +1 -0
- package/dist/core/session-repair-plan.js +202 -0
- package/dist/core/session-repair-plan.js.map +1 -0
- package/dist/core/session-termination.d.ts +100 -0
- package/dist/core/session-termination.d.ts.map +1 -0
- package/dist/core/session-termination.js +403 -0
- package/dist/core/session-termination.js.map +1 -0
- package/dist/core/settings-manager.d.ts +32 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +52 -5
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/verified-bash-adapter.d.ts +36 -0
- package/dist/core/verified-bash-adapter.d.ts.map +1 -0
- package/dist/core/verified-bash-adapter.js +90 -0
- package/dist/core/verified-bash-adapter.js.map +1 -0
- package/dist/guardrails/command-redaction.d.ts +32 -0
- package/dist/guardrails/command-redaction.d.ts.map +1 -0
- package/dist/guardrails/command-redaction.js +776 -0
- package/dist/guardrails/command-redaction.js.map +1 -0
- package/dist/guardrails/evidence-attestation.d.ts +31 -0
- package/dist/guardrails/evidence-attestation.d.ts.map +1 -0
- package/dist/guardrails/evidence-attestation.js +178 -0
- package/dist/guardrails/evidence-attestation.js.map +1 -0
- package/dist/guardrails/evidence-receipt-store.d.ts +33 -0
- package/dist/guardrails/evidence-receipt-store.d.ts.map +1 -0
- package/dist/guardrails/evidence-receipt-store.js +446 -0
- package/dist/guardrails/evidence-receipt-store.js.map +1 -0
- package/dist/guardrails/evidence-receipt.d.ts +58 -0
- package/dist/guardrails/evidence-receipt.d.ts.map +1 -0
- package/dist/guardrails/evidence-receipt.js +389 -0
- package/dist/guardrails/evidence-receipt.js.map +1 -0
- package/dist/guardrails/evidence-system.d.ts +40 -9
- package/dist/guardrails/evidence-system.d.ts.map +1 -1
- package/dist/guardrails/evidence-system.js +379 -83
- package/dist/guardrails/evidence-system.js.map +1 -1
- package/dist/guardrails/replay-ledger-io.d.ts +6 -0
- package/dist/guardrails/replay-ledger-io.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-io.js +42 -0
- package/dist/guardrails/replay-ledger-io.js.map +1 -0
- package/dist/guardrails/replay-ledger-lock-owner.d.ts +32 -0
- package/dist/guardrails/replay-ledger-lock-owner.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-lock-owner.js +138 -0
- package/dist/guardrails/replay-ledger-lock-owner.js.map +1 -0
- package/dist/guardrails/replay-ledger-lock.d.ts +24 -0
- package/dist/guardrails/replay-ledger-lock.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-lock.js +135 -0
- package/dist/guardrails/replay-ledger-lock.js.map +1 -0
- package/dist/guardrails/replay-ledger-mutation-gate.d.ts +24 -0
- package/dist/guardrails/replay-ledger-mutation-gate.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-mutation-gate.js +205 -0
- package/dist/guardrails/replay-ledger-mutation-gate.js.map +1 -0
- package/dist/guardrails/replay-ledger-quarantine.d.ts +2 -0
- package/dist/guardrails/replay-ledger-quarantine.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-quarantine.js +19 -0
- package/dist/guardrails/replay-ledger-quarantine.js.map +1 -0
- package/dist/guardrails/replay-ledger-store.d.ts +32 -0
- package/dist/guardrails/replay-ledger-store.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-store.js +211 -0
- package/dist/guardrails/replay-ledger-store.js.map +1 -0
- package/dist/guardrails/shell-command-name-glob.d.ts +3 -0
- package/dist/guardrails/shell-command-name-glob.d.ts.map +1 -0
- package/dist/guardrails/shell-command-name-glob.js +233 -0
- package/dist/guardrails/shell-command-name-glob.js.map +1 -0
- package/dist/guardrails/shell-command-option.d.ts +7 -0
- package/dist/guardrails/shell-command-option.d.ts.map +1 -0
- package/dist/guardrails/shell-command-option.js +24 -0
- package/dist/guardrails/shell-command-option.js.map +1 -0
- package/dist/guardrails/shell-command-tokenizer.d.ts +29 -0
- package/dist/guardrails/shell-command-tokenizer.d.ts.map +1 -0
- package/dist/guardrails/shell-command-tokenizer.js +145 -0
- package/dist/guardrails/shell-command-tokenizer.js.map +1 -0
- package/dist/guardrails/shell-command-wrapper.d.ts +18 -0
- package/dist/guardrails/shell-command-wrapper.d.ts.map +1 -0
- package/dist/guardrails/shell-command-wrapper.js +42 -0
- package/dist/guardrails/shell-command-wrapper.js.map +1 -0
- package/dist/guardrails/verified-executor.d.ts +65 -0
- package/dist/guardrails/verified-executor.d.ts.map +1 -0
- package/dist/guardrails/verified-executor.js +171 -0
- package/dist/guardrails/verified-executor.js.map +1 -0
- package/dist/guardrails/workspace-fingerprint.d.ts +23 -0
- package/dist/guardrails/workspace-fingerprint.d.ts.map +1 -0
- package/dist/guardrails/workspace-fingerprint.js +634 -0
- package/dist/guardrails/workspace-fingerprint.js.map +1 -0
- package/dist/index.d.ts +15 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +12 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/control-panel-layout.d.ts.map +1 -1
- package/dist/modes/interactive/components/control-panel-layout.js +1 -1
- package/dist/modes/interactive/components/control-panel-layout.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +1 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +59 -9
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +43 -2
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +23 -5
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +3 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/types/evidence.d.ts +215 -1
- package/dist/types/evidence.d.ts.map +1 -1
- package/dist/types/evidence.js.map +1 -1
- package/dist/verify-ci.d.ts +3 -0
- package/dist/verify-ci.d.ts.map +1 -0
- package/dist/verify-ci.js +30 -0
- package/dist/verify-ci.js.map +1 -0
- package/docs/compaction.md +44 -4
- package/docs/extensions.md +2 -0
- package/docs/providers.md +6 -0
- package/docs/sdk.md +238 -1
- package/docs/settings.md +67 -4
- package/docs/usage.md +38 -0
- package/examples/extensions/correctness-wall/README.md +6 -6
- package/examples/extensions/correctness-wall/index.ts +37 -11
- package/examples/extensions/custom-provider-anthropic/package-lock.json +5 -5
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/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 +4 -4
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { AgentOptions } from "omk-agent-core";
|
|
2
|
+
import type { SettingsManager } from "./settings-manager.ts";
|
|
3
|
+
/** §6.3 timeout categories. `undefined` category falls through to the global setting. */
|
|
4
|
+
export type ToolTimeoutCategory = "read" | "write" | "mcp" | "process" | "browser";
|
|
5
|
+
/** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */
|
|
6
|
+
export declare const TOOL_CATEGORY_TIMEOUTS: Readonly<Record<ToolTimeoutCategory, number>>;
|
|
7
|
+
/**
|
|
8
|
+
* Classify a tool name into its §6.3 timeout category. Conservative on
|
|
9
|
+
* purpose: unknown names return `undefined` and keep the global timeout.
|
|
10
|
+
* A browser/computer-use match wins over the generic MCP category because
|
|
11
|
+
* browser automation is the slower bound.
|
|
12
|
+
*/
|
|
13
|
+
export declare function resolveToolTimeoutCategory(toolName: string): ToolTimeoutCategory | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* Fill §6.3 category default timeouts for every active tool name that has no
|
|
16
|
+
* explicit per-name entry. Explicit entries (user settings and built-in
|
|
17
|
+
* defaults) always win and are all preserved; names without a category are
|
|
18
|
+
* omitted so they fall through to the global `toolTimeoutMs` at runtime.
|
|
19
|
+
*/
|
|
20
|
+
export declare function applyCategoryTimeoutDefaults(toolNames: Iterable<string>, explicit: Readonly<Record<string, number>>): Record<string, number>;
|
|
21
|
+
type ToolScheduler = NonNullable<AgentOptions["toolScheduler"]>;
|
|
22
|
+
export interface ResolvedAgentToolSettings {
|
|
23
|
+
readonly toolScheduler: ToolScheduler;
|
|
24
|
+
readonly maxToolConcurrency: number | undefined;
|
|
25
|
+
readonly strictExtensionClaims: boolean;
|
|
26
|
+
readonly toolTimeoutMs: number;
|
|
27
|
+
readonly toolTimeouts: Record<string, number>;
|
|
28
|
+
}
|
|
29
|
+
export declare class AgentToolSettingsError extends Error {
|
|
30
|
+
readonly settingName: string;
|
|
31
|
+
constructor(settingName: string);
|
|
32
|
+
}
|
|
33
|
+
export declare function resolveAgentToolSettings(settingsManager: SettingsManager, env?: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>>): ResolvedAgentToolSettings;
|
|
34
|
+
export {};
|
|
35
|
+
//# sourceMappingURL=agent-tool-settings.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-tool-settings.d.ts","sourceRoot":"","sources":["../../src/core/agent-tool-settings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,KAAK,EAAwB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAiBnF,0FAAyF;AACzF,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,OAAO,GA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CHEDULER = \"dag-v2\";\nconst DEFAULT_MAX_TOOL_CONCURRENCY = 4;\nconst DEFAULT_TOOL_TIMEOUT_MS = 0;\nconst MAX_TOOL_TIMEOUT_MS = 2_147_483_647;\n\nconst DEFAULT_BUILTIN_TOOL_TIMEOUTS: Readonly<Record<string, number>> = {\n\tbash: 300_000,\n\tedit: 60_000,\n\tfind: 30_000,\n\tgrep: 30_000,\n\tls: 30_000,\n\tread: 30_000,\n\twrite: 60_000,\n};\n\n/** §6.3 timeout categories. `undefined` category falls through to the global setting. */\nexport type ToolTimeoutCategory = \"read\" | \"write\" | \"mcp\" | \"process\" | \"browser\";\n\n/** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */\nexport const TOOL_CATEGORY_TIMEOUTS: Readonly<Record<ToolTimeoutCategory, number>> = Object.freeze({\n\tread: 30_000,\n\twrite: 60_000,\n\tmcp: 120_000,\n\tprocess: 300_000,\n\tbrowser: 180_000,\n});\n\nconst READ_CATEGORY_TOOLS = new Set([\"read\", \"ls\", \"find\", \"grep\", \"glob\", \"list\", \"search\"]);\nconst WRITE_CATEGORY_TOOLS = new Set([\"write\", \"edit\"]);\nconst PROCESS_CATEGORY_TOOLS = new Set([\"bash\"]);\n// Matches direct browser/computer-use tools and browser tools bridged through\n// MCP servers (e.g. `mcp__playwright__browser_click`).\nconst BROWSER_TOOL_PATTERN = /(^|__)(browser_|computer[-_]?use$|computer_)/;\n\n/**\n * Classify a tool name into its §6.3 timeout category. Conservative on\n * purpose: unknown names return `undefined` and keep the global timeout.\n * A browser/computer-use match wins over the generic MCP category because\n * browser automation is the slower bound.\n */\nexport function resolveToolTimeoutCategory(toolName: string): ToolTimeoutCategory | undefined {\n\tif (READ_CATEGORY_TOOLS.has(toolName)) return \"read\";\n\tif (WRITE_CATEGORY_TOOLS.has(toolName)) return \"write\";\n\tif (PROCESS_CATEGORY_TOOLS.has(toolName)) return \"process\";\n\tif (BROWSER_TOOL_PATTERN.test(toolName)) return \"browser\";\n\tif (toolName.startsWith(\"mcp__\")) return \"mcp\";\n\treturn undefined;\n}\n\n/**\n * Fill §6.3 category default timeouts for every active tool name that has no\n * explicit per-name entry. Explicit entries (user settings and built-in\n * defaults) always win and are all preserved; names without a category are\n * omitted so they fall through to the global `toolTimeoutMs` at runtime.\n */\nexport function applyCategoryTimeoutDefaults(\n\ttoolNames: Iterable<string>,\n\texplicit: Readonly<Record<string, number>>,\n): Record<string, number> {\n\tconst merged: Record<string, number> = Object.create(null);\n\tfor (const toolName of toolNames) {\n\t\tif (Object.hasOwn(explicit, toolName)) continue;\n\t\tconst category = resolveToolTimeoutCategory(toolName);\n\t\tif (category !== undefined) {\n\t\t\tmerged[toolName] = TOOL_CATEGORY_TIMEOUTS[category];\n\t\t}\n\t}\n\tfor (const [toolName, timeoutMs] of Object.entries(explicit)) {\n\t\tmerged[toolName] = timeoutMs;\n\t}\n\treturn merged;\n}\n\ntype ToolScheduler = NonNullable<AgentOptions[\"toolScheduler\"]>;\n\nexport interface ResolvedAgentToolSettings {\n\treadonly toolScheduler: ToolScheduler;\n\treadonly maxToolConcurrency: number | undefined;\n\treadonly strictExtensionClaims: boolean;\n\treadonly toolTimeoutMs: number;\n\treadonly toolTimeouts: Record<string, number>;\n}\n\nexport class AgentToolSettingsError extends Error {\n\treadonly settingName: string;\n\n\tconstructor(settingName: string) {\n\t\tsuper(`Invalid ${settingName} setting`);\n\t\tthis.name = \"AgentToolSettingsError\";\n\t\tthis.settingName = settingName;\n\t}\n}\n\nfunction parseScheduler(value: unknown, settingName: string): ToolScheduler | undefined {\n\tif (value === undefined) {\n\t\treturn undefined;\n\t}\n\tif (value === \"waves-v1\" || value === \"dag-v2\") {\n\t\treturn value;\n\t}\n\tthrow new AgentToolSettingsError(settingName);\n}\n\nfunction parseTimeout(value: unknown, settingName: string, defaultValue: number): number {\n\tif (value === undefined) {\n\t\treturn defaultValue;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0 || value > MAX_TOOL_TIMEOUT_MS) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseConcurrency(value: unknown): number | undefined {\n\tif (value === undefined) {\n\t\treturn DEFAULT_MAX_TOOL_CONCURRENCY;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n\t\tthrow new AgentToolSettingsError(\"agent.maxToolConcurrency\");\n\t}\n\treturn value === 0 ? undefined : value;\n}\n\nfunction parseAgentSettings(value: AgentRuntimeSettings | undefined, settingName: string): AgentRuntimeSettings {\n\tif (value === undefined) {\n\t\treturn {};\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseToolTimeoutEntries(\n\tvalue: AgentRuntimeSettings[\"toolTimeouts\"],\n\tsettingName: string,\n): readonly (readonly [string, number])[] {\n\tif (value === undefined) {\n\t\treturn [];\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\n\treturn Object.entries(value).map(([toolName, timeoutMs]) => {\n\t\tif (toolName.length === 0) {\n\t\t\tthrow new AgentToolSettingsError(settingName);\n\t\t}\n\t\treturn [toolName, parseTimeout(timeoutMs, `${settingName}.${toolName}`, DEFAULT_TOOL_TIMEOUT_MS)] as const;\n\t});\n}\n\nfunction resolveToolTimeouts(\n\tglobalSettings: AgentRuntimeSettings,\n\tprojectSettings: AgentRuntimeSettings,\n\teffectiveSettings: AgentRuntimeSettings,\n): Record<string, number> {\n\tconst timeouts: Record<string, number> = Object.create(null);\n\tconst entryGroups = [\n\t\tObject.entries(DEFAULT_BUILTIN_TOOL_TIMEOUTS),\n\t\tparseToolTimeoutEntries(globalSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(projectSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(effectiveSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t];\n\tfor (const entries of entryGroups) {\n\t\tfor (const [toolName, timeoutMs] of entries) {\n\t\t\ttimeouts[toolName] = timeoutMs;\n\t\t}\n\t}\n\treturn timeouts;\n}\n\nexport function resolveAgentToolSettings(\n\tsettingsManager: SettingsManager,\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): ResolvedAgentToolSettings {\n\tconst globalSettings = parseAgentSettings(settingsManager.getGlobalSettings().agent, \"agent\");\n\tconst projectSettings = parseAgentSettings(settingsManager.getProjectSettings().agent, \"agent\");\n\tconst settings = parseAgentSettings(settingsManager.getAgentRuntimeSettings(), \"agent\");\n\tconst envScheduler = parseScheduler(env.OMK_TOOL_SCHEDULER, \"OMK_TOOL_SCHEDULER\");\n\tconst settingsScheduler = parseScheduler(settings.toolScheduler, \"agent.toolScheduler\");\n\n\treturn {\n\t\ttoolScheduler: envScheduler ?? settingsScheduler ?? DEFAULT_TOOL_SCHEDULER,\n\t\tmaxToolConcurrency: parseConcurrency(settings.maxToolConcurrency),\n\t\tstrictExtensionClaims: true,\n\t\ttoolTimeoutMs: parseTimeout(settings.toolTimeoutMs, \"agent.toolTimeoutMs\", DEFAULT_TOOL_TIMEOUT_MS),\n\t\ttoolTimeouts: resolveToolTimeouts(globalSettings, projectSettings, settings),\n\t};\n}\n"]}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
const DEFAULT_TOOL_SCHEDULER = "dag-v2";
|
|
2
|
+
const DEFAULT_MAX_TOOL_CONCURRENCY = 4;
|
|
3
|
+
const DEFAULT_TOOL_TIMEOUT_MS = 0;
|
|
4
|
+
const MAX_TOOL_TIMEOUT_MS = 2_147_483_647;
|
|
5
|
+
const DEFAULT_BUILTIN_TOOL_TIMEOUTS = {
|
|
6
|
+
bash: 300_000,
|
|
7
|
+
edit: 60_000,
|
|
8
|
+
find: 30_000,
|
|
9
|
+
grep: 30_000,
|
|
10
|
+
ls: 30_000,
|
|
11
|
+
read: 30_000,
|
|
12
|
+
write: 60_000,
|
|
13
|
+
};
|
|
14
|
+
/** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */
|
|
15
|
+
export const TOOL_CATEGORY_TIMEOUTS = Object.freeze({
|
|
16
|
+
read: 30_000,
|
|
17
|
+
write: 60_000,
|
|
18
|
+
mcp: 120_000,
|
|
19
|
+
process: 300_000,
|
|
20
|
+
browser: 180_000,
|
|
21
|
+
});
|
|
22
|
+
const READ_CATEGORY_TOOLS = new Set(["read", "ls", "find", "grep", "glob", "list", "search"]);
|
|
23
|
+
const WRITE_CATEGORY_TOOLS = new Set(["write", "edit"]);
|
|
24
|
+
const PROCESS_CATEGORY_TOOLS = new Set(["bash"]);
|
|
25
|
+
// Matches direct browser/computer-use tools and browser tools bridged through
|
|
26
|
+
// MCP servers (e.g. `mcp__playwright__browser_click`).
|
|
27
|
+
const BROWSER_TOOL_PATTERN = /(^|__)(browser_|computer[-_]?use$|computer_)/;
|
|
28
|
+
/**
|
|
29
|
+
* Classify a tool name into its §6.3 timeout category. Conservative on
|
|
30
|
+
* purpose: unknown names return `undefined` and keep the global timeout.
|
|
31
|
+
* A browser/computer-use match wins over the generic MCP category because
|
|
32
|
+
* browser automation is the slower bound.
|
|
33
|
+
*/
|
|
34
|
+
export function resolveToolTimeoutCategory(toolName) {
|
|
35
|
+
if (READ_CATEGORY_TOOLS.has(toolName))
|
|
36
|
+
return "read";
|
|
37
|
+
if (WRITE_CATEGORY_TOOLS.has(toolName))
|
|
38
|
+
return "write";
|
|
39
|
+
if (PROCESS_CATEGORY_TOOLS.has(toolName))
|
|
40
|
+
return "process";
|
|
41
|
+
if (BROWSER_TOOL_PATTERN.test(toolName))
|
|
42
|
+
return "browser";
|
|
43
|
+
if (toolName.startsWith("mcp__"))
|
|
44
|
+
return "mcp";
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Fill §6.3 category default timeouts for every active tool name that has no
|
|
49
|
+
* explicit per-name entry. Explicit entries (user settings and built-in
|
|
50
|
+
* defaults) always win and are all preserved; names without a category are
|
|
51
|
+
* omitted so they fall through to the global `toolTimeoutMs` at runtime.
|
|
52
|
+
*/
|
|
53
|
+
export function applyCategoryTimeoutDefaults(toolNames, explicit) {
|
|
54
|
+
const merged = Object.create(null);
|
|
55
|
+
for (const toolName of toolNames) {
|
|
56
|
+
if (Object.hasOwn(explicit, toolName))
|
|
57
|
+
continue;
|
|
58
|
+
const category = resolveToolTimeoutCategory(toolName);
|
|
59
|
+
if (category !== undefined) {
|
|
60
|
+
merged[toolName] = TOOL_CATEGORY_TIMEOUTS[category];
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
for (const [toolName, timeoutMs] of Object.entries(explicit)) {
|
|
64
|
+
merged[toolName] = timeoutMs;
|
|
65
|
+
}
|
|
66
|
+
return merged;
|
|
67
|
+
}
|
|
68
|
+
export class AgentToolSettingsError extends Error {
|
|
69
|
+
settingName;
|
|
70
|
+
constructor(settingName) {
|
|
71
|
+
super(`Invalid ${settingName} setting`);
|
|
72
|
+
this.name = "AgentToolSettingsError";
|
|
73
|
+
this.settingName = settingName;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function parseScheduler(value, settingName) {
|
|
77
|
+
if (value === undefined) {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
if (value === "waves-v1" || value === "dag-v2") {
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
throw new AgentToolSettingsError(settingName);
|
|
84
|
+
}
|
|
85
|
+
function parseTimeout(value, settingName, defaultValue) {
|
|
86
|
+
if (value === undefined) {
|
|
87
|
+
return defaultValue;
|
|
88
|
+
}
|
|
89
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > MAX_TOOL_TIMEOUT_MS) {
|
|
90
|
+
throw new AgentToolSettingsError(settingName);
|
|
91
|
+
}
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
function parseConcurrency(value) {
|
|
95
|
+
if (value === undefined) {
|
|
96
|
+
return DEFAULT_MAX_TOOL_CONCURRENCY;
|
|
97
|
+
}
|
|
98
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
|
|
99
|
+
throw new AgentToolSettingsError("agent.maxToolConcurrency");
|
|
100
|
+
}
|
|
101
|
+
return value === 0 ? undefined : value;
|
|
102
|
+
}
|
|
103
|
+
function parseAgentSettings(value, settingName) {
|
|
104
|
+
if (value === undefined) {
|
|
105
|
+
return {};
|
|
106
|
+
}
|
|
107
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
108
|
+
throw new AgentToolSettingsError(settingName);
|
|
109
|
+
}
|
|
110
|
+
return value;
|
|
111
|
+
}
|
|
112
|
+
function parseToolTimeoutEntries(value, settingName) {
|
|
113
|
+
if (value === undefined) {
|
|
114
|
+
return [];
|
|
115
|
+
}
|
|
116
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
117
|
+
throw new AgentToolSettingsError(settingName);
|
|
118
|
+
}
|
|
119
|
+
return Object.entries(value).map(([toolName, timeoutMs]) => {
|
|
120
|
+
if (toolName.length === 0) {
|
|
121
|
+
throw new AgentToolSettingsError(settingName);
|
|
122
|
+
}
|
|
123
|
+
return [toolName, parseTimeout(timeoutMs, `${settingName}.${toolName}`, DEFAULT_TOOL_TIMEOUT_MS)];
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
function resolveToolTimeouts(globalSettings, projectSettings, effectiveSettings) {
|
|
127
|
+
const timeouts = Object.create(null);
|
|
128
|
+
const entryGroups = [
|
|
129
|
+
Object.entries(DEFAULT_BUILTIN_TOOL_TIMEOUTS),
|
|
130
|
+
parseToolTimeoutEntries(globalSettings.toolTimeouts, "agent.toolTimeouts"),
|
|
131
|
+
parseToolTimeoutEntries(projectSettings.toolTimeouts, "agent.toolTimeouts"),
|
|
132
|
+
parseToolTimeoutEntries(effectiveSettings.toolTimeouts, "agent.toolTimeouts"),
|
|
133
|
+
];
|
|
134
|
+
for (const entries of entryGroups) {
|
|
135
|
+
for (const [toolName, timeoutMs] of entries) {
|
|
136
|
+
timeouts[toolName] = timeoutMs;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return timeouts;
|
|
140
|
+
}
|
|
141
|
+
export function resolveAgentToolSettings(settingsManager, env = process.env) {
|
|
142
|
+
const globalSettings = parseAgentSettings(settingsManager.getGlobalSettings().agent, "agent");
|
|
143
|
+
const projectSettings = parseAgentSettings(settingsManager.getProjectSettings().agent, "agent");
|
|
144
|
+
const settings = parseAgentSettings(settingsManager.getAgentRuntimeSettings(), "agent");
|
|
145
|
+
const envScheduler = parseScheduler(env.OMK_TOOL_SCHEDULER, "OMK_TOOL_SCHEDULER");
|
|
146
|
+
const settingsScheduler = parseScheduler(settings.toolScheduler, "agent.toolScheduler");
|
|
147
|
+
return {
|
|
148
|
+
toolScheduler: envScheduler ?? settingsScheduler ?? DEFAULT_TOOL_SCHEDULER,
|
|
149
|
+
maxToolConcurrency: parseConcurrency(settings.maxToolConcurrency),
|
|
150
|
+
strictExtensionClaims: true,
|
|
151
|
+
toolTimeoutMs: parseTimeout(settings.toolTimeoutMs, "agent.toolTimeoutMs", DEFAULT_TOOL_TIMEOUT_MS),
|
|
152
|
+
toolTimeouts: resolveToolTimeouts(globalSettings, projectSettings, settings),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
//# sourceMappingURL=agent-tool-settings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-tool-settings.js","sourceRoot":"","sources":["../../src/core/agent-tool-settings.ts"],"names":[],"mappings":"AAGA,MAAM,sBAAsB,GAAG,QAAQ,CAAC;AACxC,MAAM,4BAA4B,GAAG,CAAC,CAAC;AACvC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAClC,MAAM,mBAAmB,GAAG,aAAa,CAAC;A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C;AAAA,CAChB;AAED,MAAM,UAAU,wBAAwB,CACvC,eAAgC,EAChC,GAAG,GAAqE,OAAO,CAAC,GAAG,EACvD;IAC5B,MAAM,cAAc,GAAG,kBAAkB,CAAC,eAAe,CAAC,iBAAiB,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC9F,MAAM,eAAe,GAAG,kBAAkB,CAAC,eAAe,CAAC,kBAAkB,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAChG,MAAM,QAAQ,GAAG,kBAAkB,CAAC,eAAe,CAAC,uBAAuB,EAAE,EAAE,OAAO,CAAC,CAAC;IACxF,MAAM,YAAY,GAAG,cAAc,CAAC,GAAG,CAAC,kBAAkB,EAAE,oBAAoB,CAAC,CAAC;IAClF,MAAM,iBAAiB,GAAG,cAAc,CAAC,QAAQ,CAAC,aAAa,EAAE,qBAAqB,CAAC,CAAC;IAExF,OAAO;QACN,aAAa,EAAE,YAAY,IAAI,iBAAiB,IAAI,sBAAsB;QAC1E,kBAAkB,EAAE,gBAAgB,CAAC,QAAQ,CAAC,kBAAkB,CAAC;QACjE,qBAAqB,EAAE,IAAI;QAC3B,aAAa,EAAE,YAAY,CAAC,QAAQ,CAAC,aAAa,EAAE,qBAAqB,EAAE,uBAAuB,CAAC;QACnG,YAAY,EAAE,mBAAmB,CAAC,cAAc,EAAE,eAAe,EAAE,QAAQ,CAAC;KAC5E,CAAC;AAAA,CACF","sourcesContent":["import type { AgentOptions } from \"omk-agent-core\";\nimport type { AgentRuntimeSettings, SettingsManager } from \"./settings-manager.ts\";\n\nconst DEFAULT_TOOL_SCHEDULER = \"dag-v2\";\nconst DEFAULT_MAX_TOOL_CONCURRENCY = 4;\nconst DEFAULT_TOOL_TIMEOUT_MS = 0;\nconst MAX_TOOL_TIMEOUT_MS = 2_147_483_647;\n\nconst DEFAULT_BUILTIN_TOOL_TIMEOUTS: Readonly<Record<string, number>> = {\n\tbash: 300_000,\n\tedit: 60_000,\n\tfind: 30_000,\n\tgrep: 30_000,\n\tls: 30_000,\n\tread: 30_000,\n\twrite: 60_000,\n};\n\n/** §6.3 timeout categories. `undefined` category falls through to the global setting. */\nexport type ToolTimeoutCategory = \"read\" | \"write\" | \"mcp\" | \"process\" | \"browser\";\n\n/** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */\nexport const TOOL_CATEGORY_TIMEOUTS: Readonly<Record<ToolTimeoutCategory, number>> = Object.freeze({\n\tread: 30_000,\n\twrite: 60_000,\n\tmcp: 120_000,\n\tprocess: 300_000,\n\tbrowser: 180_000,\n});\n\nconst READ_CATEGORY_TOOLS = new Set([\"read\", \"ls\", \"find\", \"grep\", \"glob\", \"list\", \"search\"]);\nconst WRITE_CATEGORY_TOOLS = new Set([\"write\", \"edit\"]);\nconst PROCESS_CATEGORY_TOOLS = new Set([\"bash\"]);\n// Matches direct browser/computer-use tools and browser tools bridged through\n// MCP servers (e.g. `mcp__playwright__browser_click`).\nconst BROWSER_TOOL_PATTERN = /(^|__)(browser_|computer[-_]?use$|computer_)/;\n\n/**\n * Classify a tool name into its §6.3 timeout category. Conservative on\n * purpose: unknown names return `undefined` and keep the global timeout.\n * A browser/computer-use match wins over the generic MCP category because\n * browser automation is the slower bound.\n */\nexport function resolveToolTimeoutCategory(toolName: string): ToolTimeoutCategory | undefined {\n\tif (READ_CATEGORY_TOOLS.has(toolName)) return \"read\";\n\tif (WRITE_CATEGORY_TOOLS.has(toolName)) return \"write\";\n\tif (PROCESS_CATEGORY_TOOLS.has(toolName)) return \"process\";\n\tif (BROWSER_TOOL_PATTERN.test(toolName)) return \"browser\";\n\tif (toolName.startsWith(\"mcp__\")) return \"mcp\";\n\treturn undefined;\n}\n\n/**\n * Fill §6.3 category default timeouts for every active tool name that has no\n * explicit per-name entry. Explicit entries (user settings and built-in\n * defaults) always win and are all preserved; names without a category are\n * omitted so they fall through to the global `toolTimeoutMs` at runtime.\n */\nexport function applyCategoryTimeoutDefaults(\n\ttoolNames: Iterable<string>,\n\texplicit: Readonly<Record<string, number>>,\n): Record<string, number> {\n\tconst merged: Record<string, number> = Object.create(null);\n\tfor (const toolName of toolNames) {\n\t\tif (Object.hasOwn(explicit, toolName)) continue;\n\t\tconst category = resolveToolTimeoutCategory(toolName);\n\t\tif (category !== undefined) {\n\t\t\tmerged[toolName] = TOOL_CATEGORY_TIMEOUTS[category];\n\t\t}\n\t}\n\tfor (const [toolName, timeoutMs] of Object.entries(explicit)) {\n\t\tmerged[toolName] = timeoutMs;\n\t}\n\treturn merged;\n}\n\ntype ToolScheduler = NonNullable<AgentOptions[\"toolScheduler\"]>;\n\nexport interface ResolvedAgentToolSettings {\n\treadonly toolScheduler: ToolScheduler;\n\treadonly maxToolConcurrency: number | undefined;\n\treadonly strictExtensionClaims: boolean;\n\treadonly toolTimeoutMs: number;\n\treadonly toolTimeouts: Record<string, number>;\n}\n\nexport class AgentToolSettingsError extends Error {\n\treadonly settingName: string;\n\n\tconstructor(settingName: string) {\n\t\tsuper(`Invalid ${settingName} setting`);\n\t\tthis.name = \"AgentToolSettingsError\";\n\t\tthis.settingName = settingName;\n\t}\n}\n\nfunction parseScheduler(value: unknown, settingName: string): ToolScheduler | undefined {\n\tif (value === undefined) {\n\t\treturn undefined;\n\t}\n\tif (value === \"waves-v1\" || value === \"dag-v2\") {\n\t\treturn value;\n\t}\n\tthrow new AgentToolSettingsError(settingName);\n}\n\nfunction parseTimeout(value: unknown, settingName: string, defaultValue: number): number {\n\tif (value === undefined) {\n\t\treturn defaultValue;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0 || value > MAX_TOOL_TIMEOUT_MS) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseConcurrency(value: unknown): number | undefined {\n\tif (value === undefined) {\n\t\treturn DEFAULT_MAX_TOOL_CONCURRENCY;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n\t\tthrow new AgentToolSettingsError(\"agent.maxToolConcurrency\");\n\t}\n\treturn value === 0 ? undefined : value;\n}\n\nfunction parseAgentSettings(value: AgentRuntimeSettings | undefined, settingName: string): AgentRuntimeSettings {\n\tif (value === undefined) {\n\t\treturn {};\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseToolTimeoutEntries(\n\tvalue: AgentRuntimeSettings[\"toolTimeouts\"],\n\tsettingName: string,\n): readonly (readonly [string, number])[] {\n\tif (value === undefined) {\n\t\treturn [];\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\n\treturn Object.entries(value).map(([toolName, timeoutMs]) => {\n\t\tif (toolName.length === 0) {\n\t\t\tthrow new AgentToolSettingsError(settingName);\n\t\t}\n\t\treturn [toolName, parseTimeout(timeoutMs, `${settingName}.${toolName}`, DEFAULT_TOOL_TIMEOUT_MS)] as const;\n\t});\n}\n\nfunction resolveToolTimeouts(\n\tglobalSettings: AgentRuntimeSettings,\n\tprojectSettings: AgentRuntimeSettings,\n\teffectiveSettings: AgentRuntimeSettings,\n): Record<string, number> {\n\tconst timeouts: Record<string, number> = Object.create(null);\n\tconst entryGroups = [\n\t\tObject.entries(DEFAULT_BUILTIN_TOOL_TIMEOUTS),\n\t\tparseToolTimeoutEntries(globalSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(projectSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(effectiveSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t];\n\tfor (const entries of entryGroups) {\n\t\tfor (const [toolName, timeoutMs] of entries) {\n\t\t\ttimeouts[toolName] = timeoutMs;\n\t\t}\n\t}\n\treturn timeouts;\n}\n\nexport function resolveAgentToolSettings(\n\tsettingsManager: SettingsManager,\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): ResolvedAgentToolSettings {\n\tconst globalSettings = parseAgentSettings(settingsManager.getGlobalSettings().agent, \"agent\");\n\tconst projectSettings = parseAgentSettings(settingsManager.getProjectSettings().agent, \"agent\");\n\tconst settings = parseAgentSettings(settingsManager.getAgentRuntimeSettings(), \"agent\");\n\tconst envScheduler = parseScheduler(env.OMK_TOOL_SCHEDULER, \"OMK_TOOL_SCHEDULER\");\n\tconst settingsScheduler = parseScheduler(settings.toolScheduler, \"agent.toolScheduler\");\n\n\treturn {\n\t\ttoolScheduler: envScheduler ?? settingsScheduler ?? DEFAULT_TOOL_SCHEDULER,\n\t\tmaxToolConcurrency: parseConcurrency(settings.maxToolConcurrency),\n\t\tstrictExtensionClaims: true,\n\t\ttoolTimeoutMs: parseTimeout(settings.toolTimeoutMs, \"agent.toolTimeoutMs\", DEFAULT_TOOL_TIMEOUT_MS),\n\t\ttoolTimeouts: resolveToolTimeouts(globalSettings, projectSettings, settings),\n\t};\n}\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Atomically and durably replace the contents of `targetPath`.
|
|
3
|
+
*
|
|
4
|
+
* Writes a uniquely named temp file in the same directory, preserves the
|
|
5
|
+
* exact private mode 0600, fsyncs and closes the temp file, then renames it
|
|
6
|
+
* over the target so readers only ever observe the complete old or
|
|
7
|
+
* complete new content, never a truncated file. The parent directory is
|
|
8
|
+
* fsynced where supported. Windows and explicit unsupported-filesystem codes
|
|
9
|
+
* skip that final operation; real durability failures propagate. On any failure
|
|
10
|
+
* before the rename completes, the temp file is
|
|
11
|
+
* removed (best-effort) and the original target is left untouched.
|
|
12
|
+
*/
|
|
13
|
+
export declare function atomicRewriteFileSync(targetPath: string, data: string | Uint8Array): void;
|
|
14
|
+
//# sourceMappingURL=atomic-session-file.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"atomic-session-file.d.ts","sourceRoot":"","sources":["../../src/core/atomic-session-file.ts"],"names":[],"mappings":"AAuBA;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,CAkEzF","sourcesContent":["import { randomBytes } from \"crypto\";\nimport {\n\tcloseSync,\n\tfsyncSync,\n\tlstatSync,\n\topenSync,\n\trealpathSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteSync,\n} from \"fs\";\nimport { basename, dirname, join } from \"path\";\nimport { enforcePrivateFileDescriptorModeSync } from \"./durable-file-mode.ts\";\n\nfunction assertRewriteTargetSafe(path: string): void {\n\ttry {\n\t\tif (statSync(path).nlink > 1) throw new Error(\"Atomic rewrite refused for a target with more than one hard link\");\n\t} catch (error) {\n\t\tif (!(error instanceof Error) || !(\"code\" in error) || Reflect.get(error, \"code\") !== \"ENOENT\") throw error;\n\t}\n}\n\n/**\n * Atomically and durably replace the contents of `targetPath`.\n *\n * Writes a uniquely named temp file in the same directory, preserves the\n * exact private mode 0600, fsyncs and closes the temp file, then renames it\n * over the target so readers only ever observe the complete old or\n * complete new content, never a truncated file. The parent directory is\n * fsynced where supported. Windows and explicit unsupported-filesystem codes\n * skip that final operation; real durability failures propagate. On any failure\n * before the rename completes, the temp file is\n * removed (best-effort) and the original target is left untouched.\n */\nexport function atomicRewriteFileSync(targetPath: string, data: string | Uint8Array): void {\n\tlet rewritePath: string;\n\ttry {\n\t\trewritePath = realpathSync.native(targetPath);\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\t\tif (code !== \"ENOENT\") throw error;\n\t\tlet danglingLink = false;\n\t\ttry {\n\t\t\tdanglingLink = lstatSync(targetPath).isSymbolicLink();\n\t\t} catch (lstatError) {\n\t\t\tconst lstatCode =\n\t\t\t\tlstatError instanceof Error && \"code\" in lstatError ? Reflect.get(lstatError, \"code\") : undefined;\n\t\t\tif (lstatCode !== \"ENOENT\") throw lstatError;\n\t\t}\n\t\tif (danglingLink) throw error;\n\t\trewritePath = targetPath;\n\t}\n\tconst dir = dirname(rewritePath);\n\n\tassertRewriteTargetSafe(rewritePath);\n\tconst tempPath = join(dir, `.${basename(rewritePath)}.${process.pid}.${randomBytes(6).toString(\"hex\")}.tmp`);\n\tlet fd: number | undefined;\n\ttry {\n\t\tfd = openSync(tempPath, \"wx\", 0o600);\n\t\tenforcePrivateFileDescriptorModeSync(fd, rewritePath);\n\t\tconst buffer = typeof data === \"string\" ? Buffer.from(data, \"utf8\") : Buffer.from(data);\n\t\tlet offset = 0;\n\t\twhile (offset < buffer.length) {\n\t\t\toffset += writeSync(fd, buffer, offset);\n\t\t}\n\t\tfsyncSync(fd);\n\t\tcloseSync(fd);\n\t\tfd = undefined;\n\t\tassertRewriteTargetSafe(rewritePath);\n\t\trenameSync(tempPath, rewritePath);\n\t} catch (error) {\n\t\tif (fd !== undefined) {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} catch (cleanupError) {\n\t\t\t\tif (!(cleanupError instanceof Error)) throw cleanupError;\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tunlinkSync(tempPath);\n\t\t} catch (cleanupError) {\n\t\t\tif (!(cleanupError instanceof Error)) throw cleanupError;\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (process.platform === \"win32\") return;\n\ttry {\n\t\tconst dirFd = openSync(dir, \"r\");\n\t\ttry {\n\t\t\tfsyncSync(dirFd);\n\t\t} finally {\n\t\t\tcloseSync(dirFd);\n\t\t}\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\t\tif (typeof code !== \"string\" || !new Set([\"EINVAL\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\"]).has(code)) {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n"]}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { randomBytes } from "crypto";
|
|
2
|
+
import { closeSync, fsyncSync, lstatSync, openSync, realpathSync, renameSync, statSync, unlinkSync, writeSync, } from "fs";
|
|
3
|
+
import { basename, dirname, join } from "path";
|
|
4
|
+
import { enforcePrivateFileDescriptorModeSync } from "./durable-file-mode.js";
|
|
5
|
+
function assertRewriteTargetSafe(path) {
|
|
6
|
+
try {
|
|
7
|
+
if (statSync(path).nlink > 1)
|
|
8
|
+
throw new Error("Atomic rewrite refused for a target with more than one hard link");
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
if (!(error instanceof Error) || !("code" in error) || Reflect.get(error, "code") !== "ENOENT")
|
|
12
|
+
throw error;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Atomically and durably replace the contents of `targetPath`.
|
|
17
|
+
*
|
|
18
|
+
* Writes a uniquely named temp file in the same directory, preserves the
|
|
19
|
+
* exact private mode 0600, fsyncs and closes the temp file, then renames it
|
|
20
|
+
* over the target so readers only ever observe the complete old or
|
|
21
|
+
* complete new content, never a truncated file. The parent directory is
|
|
22
|
+
* fsynced where supported. Windows and explicit unsupported-filesystem codes
|
|
23
|
+
* skip that final operation; real durability failures propagate. On any failure
|
|
24
|
+
* before the rename completes, the temp file is
|
|
25
|
+
* removed (best-effort) and the original target is left untouched.
|
|
26
|
+
*/
|
|
27
|
+
export function atomicRewriteFileSync(targetPath, data) {
|
|
28
|
+
let rewritePath;
|
|
29
|
+
try {
|
|
30
|
+
rewritePath = realpathSync.native(targetPath);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
const code = error instanceof Error && "code" in error ? Reflect.get(error, "code") : undefined;
|
|
34
|
+
if (code !== "ENOENT")
|
|
35
|
+
throw error;
|
|
36
|
+
let danglingLink = false;
|
|
37
|
+
try {
|
|
38
|
+
danglingLink = lstatSync(targetPath).isSymbolicLink();
|
|
39
|
+
}
|
|
40
|
+
catch (lstatError) {
|
|
41
|
+
const lstatCode = lstatError instanceof Error && "code" in lstatError ? Reflect.get(lstatError, "code") : undefined;
|
|
42
|
+
if (lstatCode !== "ENOENT")
|
|
43
|
+
throw lstatError;
|
|
44
|
+
}
|
|
45
|
+
if (danglingLink)
|
|
46
|
+
throw error;
|
|
47
|
+
rewritePath = targetPath;
|
|
48
|
+
}
|
|
49
|
+
const dir = dirname(rewritePath);
|
|
50
|
+
assertRewriteTargetSafe(rewritePath);
|
|
51
|
+
const tempPath = join(dir, `.${basename(rewritePath)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
|
52
|
+
let fd;
|
|
53
|
+
try {
|
|
54
|
+
fd = openSync(tempPath, "wx", 0o600);
|
|
55
|
+
enforcePrivateFileDescriptorModeSync(fd, rewritePath);
|
|
56
|
+
const buffer = typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data);
|
|
57
|
+
let offset = 0;
|
|
58
|
+
while (offset < buffer.length) {
|
|
59
|
+
offset += writeSync(fd, buffer, offset);
|
|
60
|
+
}
|
|
61
|
+
fsyncSync(fd);
|
|
62
|
+
closeSync(fd);
|
|
63
|
+
fd = undefined;
|
|
64
|
+
assertRewriteTargetSafe(rewritePath);
|
|
65
|
+
renameSync(tempPath, rewritePath);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (fd !== undefined) {
|
|
69
|
+
try {
|
|
70
|
+
closeSync(fd);
|
|
71
|
+
}
|
|
72
|
+
catch (cleanupError) {
|
|
73
|
+
if (!(cleanupError instanceof Error))
|
|
74
|
+
throw cleanupError;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
unlinkSync(tempPath);
|
|
79
|
+
}
|
|
80
|
+
catch (cleanupError) {
|
|
81
|
+
if (!(cleanupError instanceof Error))
|
|
82
|
+
throw cleanupError;
|
|
83
|
+
}
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
if (process.platform === "win32")
|
|
87
|
+
return;
|
|
88
|
+
try {
|
|
89
|
+
const dirFd = openSync(dir, "r");
|
|
90
|
+
try {
|
|
91
|
+
fsyncSync(dirFd);
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
closeSync(dirFd);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
const code = error instanceof Error && "code" in error ? Reflect.get(error, "code") : undefined;
|
|
99
|
+
if (typeof code !== "string" || !new Set(["EINVAL", "ENOTSUP", "EOPNOTSUPP", "ENOSYS"]).has(code)) {
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=atomic-session-file.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"atomic-session-file.js","sourceRoot":"","sources":["../../src/core/atomic-session-file.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,EACN,SAAS,EACT,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,SAAS,GACT,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC/C,OAAO,EAAE,oCAAoC,EAAE,MAAM,wBAAwB,CAAC;AAE9E,SAAS,uBAAuB,CAAC,IAAY,EAAQ;IACpD,IAAI,CAAC;QACJ,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;IACnH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,QAAQ;YAAE,MAAM,KAAK,CAAC;IAC7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O;QAAE,OAAO;IACzC,IAAI,CAAC;QACJ,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QACjC,IAAI,CAAC;YACJ,SAAS,CAAC,KAAK,CAAC,CAAC;QAClB,CAAC;gBAAS,CAAC;YACV,SAAS,CAAC,KAAK,CAAC,CAAC;QAClB,CAAC;IACF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,GAAG,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAChG,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,SAAS,EAAE,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YACnG,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { randomBytes } from \"crypto\";\nimport {\n\tcloseSync,\n\tfsyncSync,\n\tlstatSync,\n\topenSync,\n\trealpathSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteSync,\n} from \"fs\";\nimport { basename, dirname, join } from \"path\";\nimport { enforcePrivateFileDescriptorModeSync } from \"./durable-file-mode.ts\";\n\nfunction assertRewriteTargetSafe(path: string): void {\n\ttry {\n\t\tif (statSync(path).nlink > 1) throw new Error(\"Atomic rewrite refused for a target with more than one hard link\");\n\t} catch (error) {\n\t\tif (!(error instanceof Error) || !(\"code\" in error) || Reflect.get(error, \"code\") !== \"ENOENT\") throw error;\n\t}\n}\n\n/**\n * Atomically and durably replace the contents of `targetPath`.\n *\n * Writes a uniquely named temp file in the same directory, preserves the\n * exact private mode 0600, fsyncs and closes the temp file, then renames it\n * over the target so readers only ever observe the complete old or\n * complete new content, never a truncated file. The parent directory is\n * fsynced where supported. Windows and explicit unsupported-filesystem codes\n * skip that final operation; real durability failures propagate. On any failure\n * before the rename completes, the temp file is\n * removed (best-effort) and the original target is left untouched.\n */\nexport function atomicRewriteFileSync(targetPath: string, data: string | Uint8Array): void {\n\tlet rewritePath: string;\n\ttry {\n\t\trewritePath = realpathSync.native(targetPath);\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\t\tif (code !== \"ENOENT\") throw error;\n\t\tlet danglingLink = false;\n\t\ttry {\n\t\t\tdanglingLink = lstatSync(targetPath).isSymbolicLink();\n\t\t} catch (lstatError) {\n\t\t\tconst lstatCode =\n\t\t\t\tlstatError instanceof Error && \"code\" in lstatError ? Reflect.get(lstatError, \"code\") : undefined;\n\t\t\tif (lstatCode !== \"ENOENT\") throw lstatError;\n\t\t}\n\t\tif (danglingLink) throw error;\n\t\trewritePath = targetPath;\n\t}\n\tconst dir = dirname(rewritePath);\n\n\tassertRewriteTargetSafe(rewritePath);\n\tconst tempPath = join(dir, `.${basename(rewritePath)}.${process.pid}.${randomBytes(6).toString(\"hex\")}.tmp`);\n\tlet fd: number | undefined;\n\ttry {\n\t\tfd = openSync(tempPath, \"wx\", 0o600);\n\t\tenforcePrivateFileDescriptorModeSync(fd, rewritePath);\n\t\tconst buffer = typeof data === \"string\" ? Buffer.from(data, \"utf8\") : Buffer.from(data);\n\t\tlet offset = 0;\n\t\twhile (offset < buffer.length) {\n\t\t\toffset += writeSync(fd, buffer, offset);\n\t\t}\n\t\tfsyncSync(fd);\n\t\tcloseSync(fd);\n\t\tfd = undefined;\n\t\tassertRewriteTargetSafe(rewritePath);\n\t\trenameSync(tempPath, rewritePath);\n\t} catch (error) {\n\t\tif (fd !== undefined) {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} catch (cleanupError) {\n\t\t\t\tif (!(cleanupError instanceof Error)) throw cleanupError;\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tunlinkSync(tempPath);\n\t\t} catch (cleanupError) {\n\t\t\tif (!(cleanupError instanceof Error)) throw cleanupError;\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (process.platform === \"win32\") return;\n\ttry {\n\t\tconst dirFd = openSync(dir, \"r\");\n\t\ttry {\n\t\t\tfsyncSync(dirFd);\n\t\t} finally {\n\t\t\tcloseSync(dirFd);\n\t\t}\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\t\tif (typeof code !== \"string\" || !new Set([\"EINVAL\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\"]).has(code)) {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n"]}
|
|
@@ -24,9 +24,15 @@ export interface CompactionResult<T = unknown> {
|
|
|
24
24
|
export interface CompactionSettings {
|
|
25
25
|
enabled: boolean;
|
|
26
26
|
reserveTokens: number;
|
|
27
|
+
reservedOutputTokens?: number;
|
|
28
|
+
reservedToolResultTokens?: number;
|
|
29
|
+
safetyMarginTokens?: number;
|
|
30
|
+
imageReserveTokens?: number;
|
|
27
31
|
keepRecentTokens: number;
|
|
28
32
|
/** Maximum fraction of the context window to use before compaction. Default: 0.9. */
|
|
29
33
|
maxUsageRatio?: number;
|
|
34
|
+
rearmRatio?: number;
|
|
35
|
+
emergencyRatio?: number;
|
|
30
36
|
}
|
|
31
37
|
export declare const DEFAULT_COMPACTION_MAX_USAGE_RATIO = 0.9;
|
|
32
38
|
export declare const DEFAULT_COMPACTION_SETTINGS: CompactionSettings;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC5E,OAAO,KAAK,EAA6B,KAAK,EAAuB,KAAK,EAAE,MAAM,QAAQ,CA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ure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"omk-agent-core\";\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions, Usage } from \"omk-ai\";\nimport { completeSimple } from \"omk-ai\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"../messages.ts\";\nimport { buildSessionContext, type CompactionEntry, type SessionEntry } from \"../session-manager.ts\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\n/**\n * Extract file operations from messages and previous compaction entries.\n */\nfunction extractFileOperations(\n\tmessages: AgentMessage[],\n\tentries: SessionEntry[],\n\tprevCompactionIndex: number,\n): FileOperations {\n\tconst fileOps = createFileOps();\n\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = entries[prevCompactionIndex] as CompactionEntry;\n\t\tif (!prevCompaction.fromHook && prevCompaction.details) {\n\t\t\t// fromHook field kept for session file compatibility\n\t\t\tconst details = prevCompaction.details as CompactionDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\tfor (const f of details.modifiedFiles) fileOps.edited.add(f);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Extract from tool calls in messages\n\tfor (const msg of messages) {\n\t\textractFileOpsFromMessage(msg, fileOps);\n\t}\n\n\treturn fileOps;\n}\n\n// ============================================================================\n// Message Extraction\n// ============================================================================\n\n/**\n * Extract AgentMessage from an entry if it produces one.\n * Returns undefined for entries that don't contribute to LLM context.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction getMessageFromEntryForCompaction(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\treturn getMessageFromEntry(entry);\n}\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\tkeepRecentTokens: number;\n\t/** Maximum fraction of the context window to use before compaction. Default: 0.9. */\n\tmaxUsageRatio?: number;\n}\n\nexport const DEFAULT_COMPACTION_MAX_USAGE_RATIO = 0.9;\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tkeepRecentTokens: 20000,\n\tmaxUsageRatio: DEFAULT_COMPACTION_MAX_USAGE_RATIO,\n};\n\n// ============================================================================\n// Token calculation\n// ============================================================================\n\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/** Estimate context tokens after adding messages that have not been sent yet. */\nexport function estimateProjectedContextTokens(\n\tmessages: AgentMessage[],\n\tpendingMessages: AgentMessage[],\n): ContextUsageEstimate {\n\treturn estimateContextTokens([...messages, ...pendingMessages]);\n}\n\nexport type CompactionHeadroomLimit = \"max_usage_ratio\" | \"reserve_tokens\";\n\nexport interface CompactionHeadroomThreshold {\n\ttriggerTokens: number;\n\theadroomTokens: number;\n\tmaxUsageRatioTokens: number;\n\treserveBoundaryTokens: number;\n\tlimitedBy: CompactionHeadroomLimit;\n}\n\n/** Return the earliest compaction threshold from ratio-based headroom and absolute reserve. */\nexport function getCompactionHeadroomThreshold(\n\tcontextWindow: number,\n\tsettings: CompactionSettings,\n): CompactionHeadroomThreshold | undefined {\n\tif (!settings.enabled || !Number.isFinite(contextWindow) || contextWindow <= 0) {\n\t\treturn undefined;\n\t}\n\n\tconst windowTokens = Math.floor(contextWindow);\n\tconst reserveTokens = Number.isFinite(settings.reserveTokens) ? Math.max(0, Math.floor(settings.reserveTokens)) : 0;\n\tconst configuredMaxUsageRatio = settings.maxUsageRatio ?? DEFAULT_COMPACTION_MAX_USAGE_RATIO;\n\tconst maxUsageRatio =\n\t\tNumber.isFinite(configuredMaxUsageRatio) && configuredMaxUsageRatio > 0 && configuredMaxUsageRatio < 1\n\t\t\t? configuredMaxUsageRatio\n\t\t\t: DEFAULT_COMPACTION_MAX_USAGE_RATIO;\n\tconst maxUsageRatioTokens = Math.max(1, Math.floor(windowTokens * maxUsageRatio));\n\tconst reserveBoundaryTokens =\n\t\treserveTokens >= windowTokens ? maxUsageRatioTokens : Math.max(1, windowTokens - reserveTokens);\n\tconst triggerTokens = Math.min(maxUsageRatioTokens, reserveBoundaryTokens);\n\n\treturn {\n\t\ttriggerTokens,\n\t\theadroomTokens: windowTokens - triggerTokens,\n\t\tmaxUsageRatioTokens,\n\t\treserveBoundaryTokens,\n\t\tlimitedBy: reserveBoundaryTokens <= maxUsageRatioTokens ? \"reserve_tokens\" : \"max_usage_ratio\",\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean {\n\tconst threshold = getCompactionHeadroomThreshold(contextWindow, settings);\n\treturn threshold !== undefined && Number.isFinite(contextTokens) && contextTokens >= threshold.triggerTokens;\n}\n\n// ============================================================================\n// Cut point detection\n// ============================================================================\n\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nfunction estimateTextAndImageContentChars(content: string | Array<{ type: string; text?: string }>): number {\n\tif (typeof content === \"string\") {\n\t\treturn content.length;\n\t}\n\n\tlet chars = 0;\n\tfor (const block of content) {\n\t\tif (block.type === \"text\" && block.text) {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"image\") {\n\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t}\n\t}\n\treturn chars;\n}\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tchars = estimateTextAndImageContentChars(\n\t\t\t\t(message as { content: string | Array<{ type: string; text?: string }> }).content,\n\t\t\t);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tchars = estimateTextAndImageContentChars(message.content);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/**\n * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n * BashExecutionMessage is treated like a user message (user-initiated context).\n */\nfunction findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst role = entry.message.role;\n\t\t\t\tswitch (role) {\n\t\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tcase \"custom\":\n\t\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\tcase \"user\":\n\t\t\t\t\tcase \"assistant\":\n\t\t\t\t\t\tcutPoints.push(i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"toolResult\":\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"thinking_level_change\":\n\t\t\tcase \"model_change\":\n\t\t\tcase \"compaction\":\n\t\t\tcase \"branch_summary\":\n\t\t\tcase \"custom\":\n\t\t\tcase \"custom_message\":\n\t\t\tcase \"label\":\n\t\t\tcase \"session_info\":\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// branch_summary and custom_message are user-role messages, valid cut points\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the user message (or bashExecution) that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n * BashExecutionMessage is treated like a user message for turn boundaries.\n */\nexport function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\t// branch_summary and custom_message are user-role messages, can start a turn\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\treturn i;\n\t\t}\n\t\tif (entry.type === \"message\") {\n\t\t\tconst role = entry.message.role;\n\t\t\tif (role === \"user\" || role === \"bashExecution\") {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\n\t// Walk backwards from newest, accumulating estimated message sizes\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"message\") continue;\n\n\t\t// Estimate this message's size\n\t\tconst messageTokens = estimateTokens(entry.message);\n\t\taccumulatedTokens += messageTokens;\n\n\t\t// Check if we've exceeded the budget\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\t// Find the closest valid cut point at or after this entry\n\t\t\tfor (let c = 0; c < cutPoints.length; c++) {\n\t\t\t\tif (cutPoints[c] >= i) {\n\t\t\t\t\tcutIndex = cutPoints[c];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\t// Stop at session header or compaction boundaries\n\t\tif (prevEntry.type === \"compaction\") {\n\t\t\tbreak;\n\t\t}\n\t\tif (prevEntry.type === \"message\") {\n\t\t\t// Stop if we hit any message\n\t\t\tbreak;\n\t\t}\n\t\t// Include this non-message entry (bash, settings change, etc.)\n\t\tcutIndex--;\n\t}\n\n\t// Determine if this is a split turn\n\tconst cutEntry = entries[cutIndex];\n\tconst isUserMessage = cutEntry.type === \"message\" && cutEntry.message.role === \"user\";\n\tconst turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !isUserMessage && turnStartIndex !== -1,\n\t};\n}\n\n// ============================================================================\n// Summarization\n// ============================================================================\n\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nUpdate the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nfunction createSummarizationOptions(\n\tmodel: Model<any>,\n\tmaxTokens: number,\n\tapiKey: string | undefined,\n\theaders: Record<string, string> | undefined,\n\tsignal: AbortSignal | undefined,\n\tthinkingLevel: ThinkingLevel | undefined,\n): SimpleStreamOptions {\n\tconst options: SimpleStreamOptions = { maxTokens, signal, apiKey, headers };\n\tif (model.reasoning && thinkingLevel && thinkingLevel !== \"off\") {\n\t\toptions.reasoning = thinkingLevel;\n\t}\n\treturn options;\n}\n\nasync function completeSummarization(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\tif (!streamFn) {\n\t\treturn completeSimple(model, context, options);\n\t}\n\tconst stream = await streamFn(model, context, options);\n\treturn stream.result();\n}\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.8 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t);\n\n\t// Use update prompt if we have a previous summary, otherwise initial prompt\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt = `${basePrompt}\\n\\nAdditional focus: ${customInstructions}`;\n\t}\n\n\t// Serialize conversation to text so model doesn't try to continue it\n\t// Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build the prompt with conversation wrapped in tags\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completionOptions = createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel);\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcompletionOptions,\n\t\tstreamFn,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\tconst textContent = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\treturn textContent;\n}\n\n// ============================================================================\n// Compaction Preparation (for extensions)\n// ============================================================================\n\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;\n\n\tconst cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);\n\n\t// Get UUID of first kept entry\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\n\t// Messages to summarize (will be discarded after summary)\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\n\t// Messages for turn prefix summary (if splitting a turn)\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\t// Extract file operations from messages and previous compaction\n\tconst fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\n\t// Also extract file ops from turn prefix if splitting\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\n// ============================================================================\n// Main compaction function\n// ============================================================================\n\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n */\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n): Promise<CompactionResult> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\n\t// Generate summaries (can be parallel if both needed) and merge into one\n\tlet summary: string;\n\n\tif (isSplitTurn && turnPrefixMessages.length > 0) {\n\t\t// Generate both summaries in parallel\n\t\tconst [historyResult, turnPrefixResult] = await Promise.all([\n\t\t\tmessagesToSummarize.length > 0\n\t\t\t\t? generateSummary(\n\t\t\t\t\t\tmessagesToSummarize,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\tpreviousSummary,\n\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t\tstreamFn,\n\t\t\t\t\t)\n\t\t\t\t: Promise.resolve(\"No prior history.\"),\n\t\t\tgenerateTurnPrefixSummary(\n\t\t\t\tturnPrefixMessages,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tstreamFn,\n\t\t\t),\n\t\t]);\n\t\t// Merge into single summary\n\t\tsummary = `${historyResult}\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n${turnPrefixResult}`;\n\t} else {\n\t\t// Just generate history summary\n\t\tsummary = await generateSummary(\n\t\t\tmessagesToSummarize,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t);\n\t}\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\tif (!firstKeptEntryId) {\n\t\tthrow new Error(\"First kept entry has no UUID - session may need migration\");\n\t}\n\n\treturn {\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails: { readFiles, modifiedFiles } as CompactionDetails,\n\t};\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.5 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcreateSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel),\n\t\tstreamFn,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Turn prefix summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\treturn response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC5E,OAAO,KAAK,EAA6B,KAAK,EAAuB,KAAK,EAAE,MAAM,QAAQ,CAAC;AAS3F,OAAO,EAA6C,KAAK,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAIN,KAAK,cAAc,EAInB,MAAM,YAAY,CAAC;AAMpB,kEAAkE;AAClE,MAAM,WAAW,iBAAiB;IACjC,SAAS,EAAE,MAAM,EAAE,C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sourcesContent":["/**\n * Context compaction for long sessions.\n *\n * Pure functions for compaction logic. The session manager handles I/O,\n * and after compaction the session is reloaded.\n */\n\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"omk-agent-core\";\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions, Usage } from \"omk-ai\";\nimport { completeSimple } from \"omk-ai\";\nimport { computeReservedTokenBudget } from \"../context-budget-reserved-tokens.ts\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"../messages.ts\";\nimport { buildSessionContext, type CompactionEntry, type SessionEntry } from \"../session-manager.ts\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\n/** Details stored in CompactionEntry.details for file tracking */\nexport interface CompactionDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\n/**\n * Extract file operations from messages and previous compaction entries.\n */\nfunction extractFileOperations(\n\tmessages: AgentMessage[],\n\tentries: SessionEntry[],\n\tprevCompactionIndex: number,\n): FileOperations {\n\tconst fileOps = createFileOps();\n\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = entries[prevCompactionIndex] as CompactionEntry;\n\t\tif (!prevCompaction.fromHook && prevCompaction.details) {\n\t\t\t// fromHook field kept for session file compatibility\n\t\t\tconst details = prevCompaction.details as CompactionDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\tfor (const f of details.modifiedFiles) fileOps.edited.add(f);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Extract from tool calls in messages\n\tfor (const msg of messages) {\n\t\textractFileOpsFromMessage(msg, fileOps);\n\t}\n\n\treturn fileOps;\n}\n\n// ============================================================================\n// Message Extraction\n// ============================================================================\n\n/**\n * Extract AgentMessage from an entry if it produces one.\n * Returns undefined for entries that don't contribute to LLM context.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction getMessageFromEntryForCompaction(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\treturn getMessageFromEntry(entry);\n}\n\n/** Result from compact() - SessionManager adds uuid/parentUuid when saving */\nexport interface CompactionResult<T = unknown> {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\treservedOutputTokens?: number;\n\treservedToolResultTokens?: number;\n\tsafetyMarginTokens?: number;\n\timageReserveTokens?: number;\n\tkeepRecentTokens: number;\n\t/** Maximum fraction of the context window to use before compaction. Default: 0.9. */\n\tmaxUsageRatio?: number;\n\trearmRatio?: number;\n\temergencyRatio?: number;\n}\n\nexport const DEFAULT_COMPACTION_MAX_USAGE_RATIO = 0.9;\n\nexport const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {\n\tenabled: true,\n\treserveTokens: 16384,\n\tkeepRecentTokens: 20000,\n\tmaxUsageRatio: DEFAULT_COMPACTION_MAX_USAGE_RATIO,\n};\n\n// ============================================================================\n// Token calculation\n// ============================================================================\n\n/**\n * Calculate total context tokens from usage.\n * Uses the native totalTokens field when available, falls back to computing from components.\n */\nexport function calculateContextTokens(usage: Usage): number {\n\treturn usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n}\n\n/**\n * Get usage from an assistant message if available.\n * Skips aborted and error messages as they don't have valid usage data.\n */\nfunction getAssistantUsage(msg: AgentMessage): Usage | undefined {\n\tif (msg.role === \"assistant\" && \"usage\" in msg) {\n\t\tconst assistantMsg = msg as AssistantMessage;\n\t\tif (assistantMsg.stopReason !== \"aborted\" && assistantMsg.stopReason !== \"error\" && assistantMsg.usage) {\n\t\t\treturn assistantMsg.usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Find the last non-aborted assistant message usage from session entries.\n */\nexport function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type === \"message\") {\n\t\t\tconst usage = getAssistantUsage(entry.message);\n\t\t\tif (usage) return usage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport interface ContextUsageEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\nfunction getLastAssistantUsageInfo(messages: AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst usage = getAssistantUsage(messages[i]);\n\t\tif (usage) return { usage, index: i };\n\t}\n\treturn undefined;\n}\n\n/**\n * Estimate context tokens from messages, using the last assistant usage when available.\n * If there are messages after the last usage, estimate their tokens with estimateTokens.\n */\nexport function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate {\n\tconst usageInfo = getLastAssistantUsageInfo(messages);\n\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += estimateTokens(message);\n\t\t}\n\t\treturn {\n\t\t\ttokens: estimated,\n\t\t\tusageTokens: 0,\n\t\t\ttrailingTokens: estimated,\n\t\t\tlastUsageIndex: null,\n\t\t};\n\t}\n\n\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\tlet trailingTokens = 0;\n\tfor (let i = usageInfo.index + 1; i < messages.length; i++) {\n\t\ttrailingTokens += estimateTokens(messages[i]);\n\t}\n\n\treturn {\n\t\ttokens: usageTokens + trailingTokens,\n\t\tusageTokens,\n\t\ttrailingTokens,\n\t\tlastUsageIndex: usageInfo.index,\n\t};\n}\n\n/** Estimate context tokens after adding messages that have not been sent yet. */\nexport function estimateProjectedContextTokens(\n\tmessages: AgentMessage[],\n\tpendingMessages: AgentMessage[],\n): ContextUsageEstimate {\n\treturn estimateContextTokens([...messages, ...pendingMessages]);\n}\n\nexport type CompactionHeadroomLimit = \"max_usage_ratio\" | \"reserve_tokens\";\n\nexport interface CompactionHeadroomThreshold {\n\ttriggerTokens: number;\n\theadroomTokens: number;\n\tmaxUsageRatioTokens: number;\n\treserveBoundaryTokens: number;\n\tlimitedBy: CompactionHeadroomLimit;\n}\n\n/** Return the earliest compaction threshold from ratio-based headroom and absolute reserve. */\nexport function getCompactionHeadroomThreshold(\n\tcontextWindow: number,\n\tsettings: CompactionSettings,\n): CompactionHeadroomThreshold | undefined {\n\tif (!settings.enabled || !Number.isFinite(contextWindow) || contextWindow <= 0) {\n\t\treturn undefined;\n\t}\n\n\tconst windowTokens = Math.floor(contextWindow);\n\tconst reserveTokens = Number.isFinite(settings.reserveTokens) ? Math.max(0, Math.floor(settings.reserveTokens)) : 0;\n\tconst configuredMaxUsageRatio = settings.maxUsageRatio ?? DEFAULT_COMPACTION_MAX_USAGE_RATIO;\n\tconst maxUsageRatio =\n\t\tNumber.isFinite(configuredMaxUsageRatio) && configuredMaxUsageRatio > 0 && configuredMaxUsageRatio < 1\n\t\t\t? configuredMaxUsageRatio\n\t\t\t: DEFAULT_COMPACTION_MAX_USAGE_RATIO;\n\tconst maxUsageRatioTokens = Math.max(1, Math.floor(windowTokens * maxUsageRatio));\n\tconst reservedBudget = computeReservedTokenBudget({\n\t\tmodelContextWindow: windowTokens,\n\t\tsystemPromptTokens: 0,\n\t\treservedOutputTokens: settings.reservedOutputTokens ?? reserveTokens,\n\t\treservedToolResultTokens: settings.reservedToolResultTokens ?? 0,\n\t\tsafetyMarginTokens: settings.safetyMarginTokens ?? 0,\n\t\timageReserveTokens: settings.imageReserveTokens ?? 0,\n\t});\n\tconst reserveBoundaryTokens =\n\t\treservedBudget.overflow || reservedBudget.effectiveBudget === 0\n\t\t\t? maxUsageRatioTokens\n\t\t\t: Math.max(1, reservedBudget.effectiveBudget);\n\tconst triggerTokens = Math.min(maxUsageRatioTokens, reserveBoundaryTokens);\n\n\treturn {\n\t\ttriggerTokens,\n\t\theadroomTokens: windowTokens - triggerTokens,\n\t\tmaxUsageRatioTokens,\n\t\treserveBoundaryTokens,\n\t\tlimitedBy: reserveBoundaryTokens <= maxUsageRatioTokens ? \"reserve_tokens\" : \"max_usage_ratio\",\n\t};\n}\n\n/**\n * Check if compaction should trigger based on context usage.\n */\nexport function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean {\n\tconst threshold = getCompactionHeadroomThreshold(contextWindow, settings);\n\treturn threshold !== undefined && Number.isFinite(contextTokens) && contextTokens >= threshold.triggerTokens;\n}\n\n// ============================================================================\n// Cut point detection\n// ============================================================================\n\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nfunction estimateTextAndImageContentChars(content: string | Array<{ type: string; text?: string }>): number {\n\tif (typeof content === \"string\") {\n\t\treturn content.length;\n\t}\n\n\tlet chars = 0;\n\tfor (const block of content) {\n\t\tif (block.type === \"text\" && block.text) {\n\t\t\tchars += block.text.length;\n\t\t} else if (block.type === \"image\") {\n\t\t\tchars += ESTIMATED_IMAGE_CHARS;\n\t\t}\n\t}\n\treturn chars;\n}\n\n/**\n * Estimate token count for a message using chars/4 heuristic.\n * This is conservative (overestimates tokens).\n */\nexport function estimateTokens(message: AgentMessage): number {\n\tlet chars = 0;\n\n\tswitch (message.role) {\n\t\tcase \"user\": {\n\t\t\tchars = estimateTextAndImageContentChars(\n\t\t\t\t(message as { content: string | Array<{ type: string; text?: string }> }).content,\n\t\t\t);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"assistant\": {\n\t\t\tconst assistant = message as AssistantMessage;\n\t\t\tfor (const block of assistant.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tchars += block.text.length;\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tchars += block.thinking.length;\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tchars += block.name.length + JSON.stringify(block.arguments).length;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"custom\":\n\t\tcase \"toolResult\": {\n\t\t\tchars = estimateTextAndImageContentChars(message.content);\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"bashExecution\": {\n\t\t\tchars = message.command.length + message.output.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t\tcase \"branchSummary\":\n\t\tcase \"compactionSummary\": {\n\t\t\tchars = message.summary.length;\n\t\t\treturn Math.ceil(chars / 4);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/**\n * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.\n * Never cut at tool results (they must follow their tool call).\n * When we cut at an assistant message with tool calls, its tool results follow it\n * and will be kept.\n * BashExecutionMessage is treated like a user message (user-initiated context).\n */\nfunction findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {\n\tconst cutPoints: number[] = [];\n\tfor (let i = startIndex; i < endIndex; i++) {\n\t\tconst entry = entries[i];\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst role = entry.message.role;\n\t\t\t\tswitch (role) {\n\t\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tcase \"custom\":\n\t\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\tcase \"user\":\n\t\t\t\t\tcase \"assistant\":\n\t\t\t\t\t\tcutPoints.push(i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"toolResult\":\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"thinking_level_change\":\n\t\t\tcase \"model_change\":\n\t\t\tcase \"compaction\":\n\t\t\tcase \"branch_summary\":\n\t\t\tcase \"custom\":\n\t\t\tcase \"custom_message\":\n\t\t\tcase \"label\":\n\t\t\tcase \"session_info\":\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// branch_summary and custom_message are user-role messages, valid cut points\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\tcutPoints.push(i);\n\t\t}\n\t}\n\treturn cutPoints;\n}\n\n/**\n * Find the user message (or bashExecution) that starts the turn containing the given entry index.\n * Returns -1 if no turn start found before the index.\n * BashExecutionMessage is treated like a user message for turn boundaries.\n */\nexport function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {\n\tfor (let i = entryIndex; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\t// branch_summary and custom_message are user-role messages, can start a turn\n\t\tif (entry.type === \"branch_summary\" || entry.type === \"custom_message\") {\n\t\t\treturn i;\n\t\t}\n\t\tif (entry.type === \"message\") {\n\t\t\tconst role = entry.message.role;\n\t\t\tif (role === \"user\" || role === \"bashExecution\") {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}\n\nexport interface CutPointResult {\n\t/** Index of first entry to keep */\n\tfirstKeptEntryIndex: number;\n\t/** Index of user message that starts the turn being split, or -1 if not splitting */\n\tturnStartIndex: number;\n\t/** Whether this cut splits a turn (cut point is not a user message) */\n\tisSplitTurn: boolean;\n}\n\n/**\n * Find the cut point in session entries that keeps approximately `keepRecentTokens`.\n *\n * Algorithm: Walk backwards from newest, accumulating estimated message sizes.\n * Stop when we've accumulated >= keepRecentTokens. Cut at that point.\n *\n * Can cut at user OR assistant messages (never tool results). When cutting at an\n * assistant message with tool calls, its tool results come after and will be kept.\n *\n * Returns CutPointResult with:\n * - firstKeptEntryIndex: the entry index to start keeping from\n * - turnStartIndex: if cutting mid-turn, the user message that started that turn\n * - isSplitTurn: whether we're cutting in the middle of a turn\n *\n * Only considers entries between `startIndex` and `endIndex` (exclusive).\n */\nexport function findCutPoint(\n\tentries: SessionEntry[],\n\tstartIndex: number,\n\tendIndex: number,\n\tkeepRecentTokens: number,\n): CutPointResult {\n\tconst cutPoints = findValidCutPoints(entries, startIndex, endIndex);\n\n\tif (cutPoints.length === 0) {\n\t\treturn { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };\n\t}\n\n\t// Walk backwards from newest, accumulating estimated message sizes\n\tlet accumulatedTokens = 0;\n\tlet cutIndex = cutPoints[0]; // Default: keep from first message (not header)\n\n\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"message\") continue;\n\n\t\t// Estimate this message's size\n\t\tconst messageTokens = estimateTokens(entry.message);\n\t\taccumulatedTokens += messageTokens;\n\n\t\t// Check if we've exceeded the budget\n\t\tif (accumulatedTokens >= keepRecentTokens) {\n\t\t\t// Find the closest valid cut point at or after this entry\n\t\t\tfor (let c = 0; c < cutPoints.length; c++) {\n\t\t\t\tif (cutPoints[c] >= i) {\n\t\t\t\t\tcutIndex = cutPoints[c];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)\n\twhile (cutIndex > startIndex) {\n\t\tconst prevEntry = entries[cutIndex - 1];\n\t\t// Stop at session header or compaction boundaries\n\t\tif (prevEntry.type === \"compaction\") {\n\t\t\tbreak;\n\t\t}\n\t\tif (prevEntry.type === \"message\") {\n\t\t\t// Stop if we hit any message\n\t\t\tbreak;\n\t\t}\n\t\t// Include this non-message entry (bash, settings change, etc.)\n\t\tcutIndex--;\n\t}\n\n\t// Determine if this is a split turn\n\tconst cutEntry = entries[cutIndex];\n\tconst isUserMessage = cutEntry.type === \"message\" && cutEntry.message.role === \"user\";\n\tconst turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);\n\n\treturn {\n\t\tfirstKeptEntryIndex: cutIndex,\n\t\tturnStartIndex,\n\t\tisSplitTurn: !isUserMessage && turnStartIndex !== -1,\n\t};\n}\n\n// ============================================================================\n// Summarization\n// ============================================================================\n\nconst SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nconst UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nUpdate the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\nfunction createSummarizationOptions(\n\tmodel: Model<any>,\n\tmaxTokens: number,\n\tapiKey: string | undefined,\n\theaders: Record<string, string> | undefined,\n\tsignal: AbortSignal | undefined,\n\tthinkingLevel: ThinkingLevel | undefined,\n): SimpleStreamOptions {\n\tconst options: SimpleStreamOptions = { maxTokens, signal, apiKey, headers };\n\tif (model.reasoning && thinkingLevel && thinkingLevel !== \"off\") {\n\t\toptions.reasoning = thinkingLevel;\n\t}\n\treturn options;\n}\n\nasync function completeSummarization(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\tif (!streamFn) {\n\t\treturn completeSimple(model, context, options);\n\t}\n\tconst stream = await streamFn(model, context, options);\n\treturn stream.result();\n}\n\n/**\n * Generate a summary of the conversation using the LLM.\n * If previousSummary is provided, uses the update prompt to merge.\n */\nexport async function generateSummary(\n\tcurrentMessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tcustomInstructions?: string,\n\tpreviousSummary?: string,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.8 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t);\n\n\t// Use update prompt if we have a previous summary, otherwise initial prompt\n\tlet basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;\n\tif (customInstructions) {\n\t\tbasePrompt = `${basePrompt}\\n\\nAdditional focus: ${customInstructions}`;\n\t}\n\n\t// Serialize conversation to text so model doesn't try to continue it\n\t// Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)\n\tconst llmMessages = convertToLlm(currentMessages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build the prompt with conversation wrapped in tags\n\tlet promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n`;\n\tif (previousSummary) {\n\t\tpromptText += `<previous-summary>\\n${previousSummary}\\n</previous-summary>\\n\\n`;\n\t}\n\tpromptText += basePrompt;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst completionOptions = createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel);\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcompletionOptions,\n\t\tstreamFn,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\tconst textContent = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\treturn textContent;\n}\n\n// ============================================================================\n// Compaction Preparation (for extensions)\n// ============================================================================\n\nexport interface CompactionPreparation {\n\t/** UUID of first entry to keep */\n\tfirstKeptEntryId: string;\n\t/** Messages that will be summarized and discarded */\n\tmessagesToSummarize: AgentMessage[];\n\t/** Messages that will be turned into turn prefix summary (if splitting) */\n\tturnPrefixMessages: AgentMessage[];\n\t/** Whether this is a split turn (cut point in middle of turn) */\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\t/** Summary from previous compaction, for iterative update */\n\tpreviousSummary?: string;\n\t/** File operations extracted from messagesToSummarize */\n\tfileOps: FileOperations;\n\t/** Compaction settions from settings.jsonl\t*/\n\tsettings: CompactionSettings;\n}\n\nexport function prepareCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n): CompactionPreparation | undefined {\n\tif (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === \"compaction\") {\n\t\treturn undefined;\n\t}\n\n\tlet prevCompactionIndex = -1;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tif (pathEntries[i].type === \"compaction\") {\n\t\t\tprevCompactionIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet previousSummary: string | undefined;\n\tlet boundaryStart = 0;\n\tif (prevCompactionIndex >= 0) {\n\t\tconst prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;\n\t\tpreviousSummary = prevCompaction.summary;\n\t\tconst firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);\n\t\tboundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;\n\t}\n\tconst boundaryEnd = pathEntries.length;\n\n\tconst tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;\n\n\tconst cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);\n\n\t// Get UUID of first kept entry\n\tconst firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];\n\tif (!firstKeptEntry?.id) {\n\t\treturn undefined; // Session needs migration\n\t}\n\tconst firstKeptEntryId = firstKeptEntry.id;\n\n\tconst historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;\n\n\t// Messages to summarize (will be discarded after summary)\n\tconst messagesToSummarize: AgentMessage[] = [];\n\tfor (let i = boundaryStart; i < historyEnd; i++) {\n\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\tif (msg) messagesToSummarize.push(msg);\n\t}\n\n\t// Messages for turn prefix summary (if splitting a turn)\n\tconst turnPrefixMessages: AgentMessage[] = [];\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {\n\t\t\tconst msg = getMessageFromEntryForCompaction(pathEntries[i]);\n\t\t\tif (msg) turnPrefixMessages.push(msg);\n\t\t}\n\t}\n\n\t// Extract file operations from messages and previous compaction\n\tconst fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);\n\n\t// Also extract file ops from turn prefix if splitting\n\tif (cutPoint.isSplitTurn) {\n\t\tfor (const msg of turnPrefixMessages) {\n\t\t\textractFileOpsFromMessage(msg, fileOps);\n\t\t}\n\t}\n\n\treturn {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn: cutPoint.isSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t};\n}\n\n// ============================================================================\n// Main compaction function\n// ============================================================================\n\nconst TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.`;\n\n/**\n * Generate summaries for compaction using prepared data.\n * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.\n *\n * @param preparation - Pre-calculated preparation from prepareCompaction()\n * @param customInstructions - Optional custom focus for the summary\n */\nexport async function compact(\n\tpreparation: CompactionPreparation,\n\tmodel: Model<any>,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tcustomInstructions?: string,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n): Promise<CompactionResult> {\n\tconst {\n\t\tfirstKeptEntryId,\n\t\tmessagesToSummarize,\n\t\tturnPrefixMessages,\n\t\tisSplitTurn,\n\t\ttokensBefore,\n\t\tpreviousSummary,\n\t\tfileOps,\n\t\tsettings,\n\t} = preparation;\n\n\t// Generate summaries (can be parallel if both needed) and merge into one\n\tlet summary: string;\n\n\tif (isSplitTurn && turnPrefixMessages.length > 0) {\n\t\t// Generate both summaries in parallel\n\t\tconst [historyResult, turnPrefixResult] = await Promise.all([\n\t\t\tmessagesToSummarize.length > 0\n\t\t\t\t? generateSummary(\n\t\t\t\t\t\tmessagesToSummarize,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettings.reserveTokens,\n\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\tpreviousSummary,\n\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t\tstreamFn,\n\t\t\t\t\t)\n\t\t\t\t: Promise.resolve(\"No prior history.\"),\n\t\t\tgenerateTurnPrefixSummary(\n\t\t\t\tturnPrefixMessages,\n\t\t\t\tmodel,\n\t\t\t\tsettings.reserveTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tstreamFn,\n\t\t\t),\n\t\t]);\n\t\t// Merge into single summary\n\t\tsummary = `${historyResult}\\n\\n---\\n\\n**Turn Context (split turn):**\\n\\n${turnPrefixResult}`;\n\t} else {\n\t\t// Just generate history summary\n\t\tsummary = await generateSummary(\n\t\t\tmessagesToSummarize,\n\t\t\tmodel,\n\t\t\tsettings.reserveTokens,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tcustomInstructions,\n\t\t\tpreviousSummary,\n\t\t\tthinkingLevel,\n\t\t\tstreamFn,\n\t\t);\n\t}\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\tif (!firstKeptEntryId) {\n\t\tthrow new Error(\"First kept entry has no UUID - session may need migration\");\n\t}\n\n\treturn {\n\t\tsummary,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails: { readFiles, modifiedFiles } as CompactionDetails,\n\t};\n}\n\n/**\n * Generate a summary for a turn prefix (when splitting a turn).\n */\nasync function generateTurnPrefixSummary(\n\tmessages: AgentMessage[],\n\tmodel: Model<any>,\n\treserveTokens: number,\n\tapiKey: string | undefined,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel?: ThinkingLevel,\n\tstreamFn?: StreamFn,\n): Promise<string> {\n\tconst maxTokens = Math.min(\n\t\tMath.floor(0.5 * reserveTokens),\n\t\tmodel.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,\n\t); // Smaller budget for turn prefix\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\tconst response = await completeSummarization(\n\t\tmodel,\n\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\tcreateSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel),\n\t\tstreamFn,\n\t);\n\n\tif (response.stopReason === \"error\") {\n\t\tthrow new Error(`Turn prefix summarization failed: ${response.errorMessage || \"Unknown error\"}`);\n\t}\n\n\treturn response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n}\n"]}
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* and after compaction the session is reloaded.
|
|
6
6
|
*/
|
|
7
7
|
import { completeSimple } from "omk-ai";
|
|
8
|
+
import { computeReservedTokenBudget } from "../context-budget-reserved-tokens.js";
|
|
8
9
|
import { convertToLlm, createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage, } from "../messages.js";
|
|
9
10
|
import { buildSessionContext } from "../session-manager.js";
|
|
10
11
|
import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";
|
|
@@ -160,7 +161,17 @@ export function getCompactionHeadroomThreshold(contextWindow, settings) {
|
|
|
160
161
|
? configuredMaxUsageRatio
|
|
161
162
|
: DEFAULT_COMPACTION_MAX_USAGE_RATIO;
|
|
162
163
|
const maxUsageRatioTokens = Math.max(1, Math.floor(windowTokens * maxUsageRatio));
|
|
163
|
-
const
|
|
164
|
+
const reservedBudget = computeReservedTokenBudget({
|
|
165
|
+
modelContextWindow: windowTokens,
|
|
166
|
+
systemPromptTokens: 0,
|
|
167
|
+
reservedOutputTokens: settings.reservedOutputTokens ?? reserveTokens,
|
|
168
|
+
reservedToolResultTokens: settings.reservedToolResultTokens ?? 0,
|
|
169
|
+
safetyMarginTokens: settings.safetyMarginTokens ?? 0,
|
|
170
|
+
imageReserveTokens: settings.imageReserveTokens ?? 0,
|
|
171
|
+
});
|
|
172
|
+
const reserveBoundaryTokens = reservedBudget.overflow || reservedBudget.effectiveBudget === 0
|
|
173
|
+
? maxUsageRatioTokens
|
|
174
|
+
: Math.max(1, reservedBudget.effectiveBudget);
|
|
164
175
|
const triggerTokens = Math.min(maxUsageRatioTokens, reserveBoundaryTokens);
|
|
165
176
|
return {
|
|
166
177
|
triggerTokens,
|