@draht/coding-agent 2026.11.5 → 2026.11.14
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 +66 -0
- package/dist/bundle/chunks/anthropic-messages-FKSSTO6N.js +6 -0
- package/dist/bundle/chunks/{azure-openai-responses-5YLWRJ4E.js → azure-openai-responses-AHIW4IRP.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
- package/dist/bundle/chunks/chunk-2CHTECAU.js +2 -0
- package/dist/bundle/chunks/{chunk-SPVE2GM7.js → chunk-46NQOOTO.js} +1 -1
- package/dist/bundle/chunks/{chunk-MKVW4KK2.js → chunk-4ALYWMDD.js} +1 -1
- package/dist/bundle/chunks/{chunk-EXZUXBS5.js → chunk-5K3TBDND.js} +12 -15
- package/dist/bundle/chunks/{chunk-PRT3JHOZ.js → chunk-DFFQ5ETM.js} +1 -1
- package/dist/bundle/chunks/chunk-EBTEI43G.js +20 -0
- package/dist/bundle/chunks/{chunk-LJ3SEGWI.js → chunk-G7DJ6PIU.js} +5 -1
- package/dist/bundle/chunks/{chunk-3LFBXSCO.js → chunk-GR3JEDCL.js} +1 -1
- package/dist/bundle/chunks/{chunk-JAT7HEFU.js → chunk-HIL6BIBX.js} +2 -2
- package/dist/bundle/chunks/{chunk-PZKD35UB.js → chunk-MXA4WY3C.js} +1 -1
- package/dist/bundle/chunks/chunk-NJDELBDB.js +82 -0
- package/dist/bundle/chunks/{chunk-CLNF6E5P.js → chunk-NLVN7RG3.js} +1 -1
- package/dist/bundle/chunks/chunk-NLYBRJ3F.js +9 -0
- package/dist/bundle/chunks/{chunk-UQSONZLL.js → chunk-OPLOTJXH.js} +3 -1
- package/dist/bundle/chunks/{chunk-YUBUKEPQ.js → chunk-PPJRJAR3.js} +169 -130
- package/dist/bundle/chunks/chunk-RIPTEKPX.js +44 -0
- package/dist/bundle/chunks/chunk-ROB5AWV5.js +30 -0
- package/dist/bundle/chunks/chunk-WNZ64GW3.js +2 -0
- package/dist/bundle/chunks/{chunk-ABW2JATG.js → chunk-XEVRP72T.js} +1 -1
- package/dist/bundle/chunks/{chunk-SKQFE2GA.js → chunk-XY64T2H6.js} +1 -1
- package/dist/bundle/chunks/chunk-ZZAOELWU.js +2 -0
- package/dist/bundle/chunks/{cli-7AMCJ2UG.js → cli-JDGPEN7N.js} +3 -3
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-QBCV2OWJ.js → cloudflare-workers-ai-system-one-ZPDQKK4H.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +2 -0
- package/dist/bundle/chunks/{execute-VOIPQMCI.js → execute-YOMYOVUT.js} +2 -2
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/google-generative-ai-EEDLVZAQ.js +2 -0
- package/dist/bundle/chunks/google-vertex-YQDP6U25.js +2 -0
- package/dist/bundle/chunks/{llama-cpp-classify-WGVYEPG2.js → llama-cpp-classify-SRUYBPZS.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-PV6RDK65.js → mistral-conversations-QKVAIF57.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-SEOL3EDF.js → openai-codex-responses-2FIT2Z3L.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-U32QPS37.js → openai-completions-42OND4EW.js} +3 -3
- package/dist/bundle/chunks/{openai-decisions-ULSYFV2A.js → openai-decisions-FAP6LRGH.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-5MYZJYPK.js → openai-responses-BGC7WCIQ.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-SGOP5SDW.js → openrouter-images-EAWW57ZG.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-QALFE2BD.js → pi-messages-JM6JDMH5.js} +1 -1
- package/dist/bundle/chunks/{runtime-GDH3ZURV.js → runtime-F63NCS5Y.js} +1 -1
- package/dist/bundle/chunks/{runtime-Z74VFUDD.js → runtime-S5WBSLTE.js} +1 -1
- package/dist/bundle/chunks/{settings-manager-T6UJFO2F.js → settings-manager-H3QEOPQ3.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-GTGS5MG6.js → typesafe-system-one-QOA2PTJR.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-2BURZRW7.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +5 -3
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-command.d.ts.map +1 -1
- package/dist/cli/auth-command.js +30 -6
- package/dist/cli/auth-command.js.map +1 -1
- package/dist/cli/auth-login.d.ts +15 -0
- package/dist/cli/auth-login.d.ts.map +1 -0
- package/dist/cli/auth-login.js +232 -0
- package/dist/cli/auth-login.js.map +1 -0
- package/dist/cli/auth-logout.d.ts +14 -0
- package/dist/cli/auth-logout.d.ts.map +1 -0
- package/dist/cli/auth-logout.js +57 -0
- package/dist/cli/auth-logout.js.map +1 -0
- package/dist/cli/auth-terminal.d.ts +17 -0
- package/dist/cli/auth-terminal.d.ts.map +1 -0
- package/dist/cli/auth-terminal.js +63 -0
- package/dist/cli/auth-terminal.js.map +1 -0
- package/dist/core/agent-session-runtime.d.ts +5 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +16 -2
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +20 -9
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +71 -29
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/ai-schemas.d.ts +1 -0
- package/dist/core/ai-schemas.d.ts.map +1 -1
- package/dist/core/builtins/budgets.d.ts.map +1 -1
- package/dist/core/builtins/budgets.js +6 -3
- package/dist/core/builtins/budgets.js.map +1 -1
- package/dist/core/cache-warmer.d.ts +4 -37
- package/dist/core/cache-warmer.d.ts.map +1 -1
- package/dist/core/cache-warmer.js +11 -91
- package/dist/core/cache-warmer.js.map +1 -1
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +2 -1
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/exec.d.ts +1 -0
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +4 -1
- package/dist/core/exec.js.map +1 -1
- package/dist/core/export-html/ansi-to-html.d.ts +5 -0
- package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
- package/dist/core/export-html/ansi-to-html.js +57 -20
- package/dist/core/export-html/ansi-to-html.js.map +1 -1
- package/dist/core/export-html/template.js +1 -1
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +2 -3
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/types.d.ts +3 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/model-config.d.ts +13 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-resolver.d.ts +0 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +17 -24
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +5 -0
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +7 -0
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/polyphase/render/format.d.ts +2 -0
- package/dist/core/polyphase/render/format.d.ts.map +1 -1
- package/dist/core/polyphase/render/format.js +6 -0
- package/dist/core/polyphase/render/format.js.map +1 -1
- package/dist/core/polyphase/render/run-block.d.ts +4 -0
- package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
- package/dist/core/polyphase/render/run-block.js +71 -12
- package/dist/core/polyphase/render/run-block.js.map +1 -1
- package/dist/core/polyphase/render/snapshot.d.ts +1 -1
- package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
- package/dist/core/polyphase/render/snapshot.js +22 -7
- package/dist/core/polyphase/render/snapshot.js.map +1 -1
- package/dist/core/polyphase/ui/dock.d.ts.map +1 -1
- package/dist/core/polyphase/ui/dock.js +34 -2
- package/dist/core/polyphase/ui/dock.js.map +1 -1
- package/dist/core/polyphase/ui/inspector.d.ts +18 -6
- package/dist/core/polyphase/ui/inspector.d.ts.map +1 -1
- package/dist/core/polyphase/ui/inspector.js +125 -44
- package/dist/core/polyphase/ui/inspector.js.map +1 -1
- package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -1
- package/dist/core/polyphase/ui/transcript-layout.js +5 -1
- package/dist/core/polyphase/ui/transcript-layout.js.map +1 -1
- package/dist/core/preferred-providers.d.ts +17 -0
- package/dist/core/preferred-providers.d.ts.map +1 -0
- package/dist/core/preferred-providers.js +24 -0
- package/dist/core/preferred-providers.js.map +1 -0
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +18 -2
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +2 -0
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/provider-matching.d.ts +6 -0
- package/dist/core/provider-matching.d.ts.map +1 -0
- package/dist/core/provider-matching.js +8 -0
- package/dist/core/provider-matching.js.map +1 -0
- package/dist/core/radius-mcp.d.ts +13 -0
- package/dist/core/radius-mcp.d.ts.map +1 -0
- package/dist/core/radius-mcp.js +29 -0
- package/dist/core/radius-mcp.js.map +1 -0
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +2 -0
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/runtime-credentials.d.ts +8 -0
- package/dist/core/runtime-credentials.d.ts.map +1 -1
- package/dist/core/runtime-credentials.js +15 -1
- package/dist/core/runtime-credentials.js.map +1 -1
- package/dist/core/session-cwd.d.ts +7 -0
- package/dist/core/session-cwd.d.ts.map +1 -1
- package/dist/core/session-cwd.js +9 -1
- package/dist/core/session-cwd.js.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +45 -36
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +1 -1
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +1 -1
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +35 -5
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +23 -14
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +182 -41
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +8 -7
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +57 -16
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +4 -0
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +20 -8
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +4 -1
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/powershell.d.ts.map +1 -1
- package/dist/core/tools/powershell.js +15 -2
- package/dist/core/tools/powershell.js.map +1 -1
- package/dist/core/tools/read.d.ts +13 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +146 -35
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/renderers/read.d.ts.map +1 -1
- package/dist/core/tools/renderers/read.js +6 -2
- package/dist/core/tools/renderers/read.js.map +1 -1
- package/dist/core/tools/truncate.d.ts +4 -0
- package/dist/core/tools/truncate.d.ts.map +1 -1
- package/dist/core/tools/truncate.js +24 -1
- package/dist/core/tools/truncate.js.map +1 -1
- package/dist/extensions/codemode/execute.js +4 -4
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +34 -12
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts +1 -1
- package/dist/extensions/llama/provider.js +1 -1
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +15 -3
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/extensions/mcp/cli.js +5 -8
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +2 -1
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +3 -2
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +18 -6
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +67 -15
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +2 -19
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +14 -6
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +10 -3
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +32 -5
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/provider-brand.d.ts +14 -0
- package/dist/modes/interactive/components/provider-brand.d.ts.map +1 -0
- package/dist/modes/interactive/components/provider-brand.js +66 -0
- package/dist/modes/interactive/components/provider-brand.js.map +1 -0
- package/dist/modes/interactive/components/radius-login-selector.d.ts +1 -2
- package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.js +6 -37
- package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +6 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +23 -5
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +3 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +11 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +133 -78
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/session-share.js +2 -0
- package/dist/modes/interactive/session-share.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +27 -4
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/prompts/commands/test-audit.md +84 -0
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/image-resize.js +3 -1
- package/dist/utils/image-resize.js.map +1 -1
- package/dist/utils/terminal-question.d.ts +8 -0
- package/dist/utils/terminal-question.d.ts.map +1 -0
- package/dist/utils/terminal-question.js +24 -0
- package/dist/utils/terminal-question.js.map +1 -0
- package/dist/utils/web-url.d.ts +12 -0
- package/dist/utils/web-url.d.ts.map +1 -0
- package/dist/utils/web-url.js +20 -0
- package/dist/utils/web-url.js.map +1 -0
- package/docs/cli.md +14 -1
- package/docs/extensions.md +6 -4
- package/docs/llama-cpp.md +5 -5
- package/docs/models-configuration.md +2 -1
- package/docs/nvidia-rtx-llama-cpp.md +5 -5
- package/docs/polyphase.md +13 -1
- package/docs/prompt-templates.md +1 -1
- package/docs/providers.md +4 -2
- package/docs/quickstart.md +1 -1
- package/docs/rpc-commands.md +1 -1
- package/docs/rpc.md +1 -1
- package/docs/sessions.md +7 -1
- package/docs/settings.md +1 -1
- package/docs/tui.md +1 -1
- package/examples/extensions/gondolin/index.ts +4 -7
- package/examples/extensions/subagent/index.ts +5 -1
- package/package.json +10 -10
- package/prompts/commands/test-audit.md +84 -0
- package/schemas/models.schema.json +5 -1
- package/schemas/settings.schema.json +1 -1
- package/dist/bundle/chunks/anthropic-messages-TXQXPH4S.js +0 -6
- package/dist/bundle/chunks/chunk-AOCWORXE.js +0 -2
- package/dist/bundle/chunks/chunk-DQ4G4IS4.js +0 -20
- package/dist/bundle/chunks/chunk-J7QTCDIN.js +0 -2
- package/dist/bundle/chunks/chunk-NNYZSIKR.js +0 -9
- package/dist/bundle/chunks/chunk-SUVMF4W5.js +0 -2
- package/dist/bundle/chunks/chunk-THDNEOXP.js +0 -44
- package/dist/bundle/chunks/chunk-TK3LS5QZ.js +0 -82
- package/dist/bundle/chunks/chunk-TYAEYYRA.js +0 -30
- package/dist/bundle/chunks/google-generative-ai-NC5KHHW3.js +0 -2
- package/dist/bundle/chunks/google-vertex-GAPUJEF7.js +0 -2
- package/dist/bundle/chunks/virtual-modules-ZUI2T3XR.js +0 -2
|
@@ -12,6 +12,7 @@ export declare const ProviderCompatSchema: Type.TUnsafe<{
|
|
|
12
12
|
requiresToolResultName?: boolean | undefined;
|
|
13
13
|
requiresAssistantAfterToolResult?: boolean | undefined;
|
|
14
14
|
requiresNonNullAssistantContent?: boolean | undefined;
|
|
15
|
+
requiresToolsWithToolHistory?: boolean | undefined;
|
|
15
16
|
requiresThinkingAsText?: boolean | undefined;
|
|
16
17
|
requiresReasoningContentOnAssistantMessages?: boolean | undefined;
|
|
17
18
|
thinkingFormat?: "ant-ling" | "baseten" | "chat-template" | "deepseek" | "openai" | "openrouter" | "qwen" | "qwen-chat-template" | "string-thinking" | "together" | "zai" | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-schemas.d.ts","sourceRoot":"","sources":["../../src/core/ai-schemas.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAoBH,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE/B,eAAO,MAAM,oBAAoB
|
|
1
|
+
{"version":3,"file":"ai-schemas.d.ts","sourceRoot":"","sources":["../../src/core/ai-schemas.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAoBH,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE/B,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAwD,CAAC;AAC1F,eAAO,MAAM,eAAe;;;;;;;;;;;;EAA8C,CAAC;AAC3E,eAAO,MAAM,sBAAsB;;;;;;;;;;;;EAA4D,CAAC;AAChG,eAAO,MAAM,wBAAwB,gCAAgE,CAAC;AACtG,eAAO,MAAM,sBAAsB;;;EAA4D,CAAC;AAChG,eAAO,MAAM,wBAAwB,+EAAgE,CAAC;AACtG,eAAO,MAAM,sBAAsB;;;;;;;;EAA4D,CAAC;AAEhG,sGAAsG;AACtG,eAAO,MAAM,sBAAsB;;;;;;;;;;;;GAAwE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"budgets.d.ts","sourceRoot":"","sources":["../../../src/core/builtins/budgets.ts"],"names":[],"mappings":"AAOA,OAAO,EAEN,KAAK,YAAY,EAGjB,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"budgets.d.ts","sourceRoot":"","sources":["../../../src/core/builtins/budgets.ts"],"names":[],"mappings":"AAOA,OAAO,EAEN,KAAK,YAAY,EAGjB,MAAM,wBAAwB,CAAC;AA4KhC,MAAM,CAAC,OAAO,UAAU,cAAc,CAAC,EAAE,EAAE,YAAY,QA2GtD"}
|
|
@@ -6,7 +6,7 @@ import { spawnProcess, waitForChildProcess } from "../../utils/child-process.js"
|
|
|
6
6
|
import { stripFrontmatter } from "../../utils/frontmatter.js";
|
|
7
7
|
import { splitBom } from "../../utils/text.js";
|
|
8
8
|
import { isToolCallEventType, } from "../extensions/types.js";
|
|
9
|
-
import { applyEditsToNormalizedContent,
|
|
9
|
+
import { applyEditsToNormalizedContent, applyReplacementsToOriginal, normalizeToLF } from "../tools/edit-diff.js";
|
|
10
10
|
import { resolveToCwd } from "../tools/path-utils.js";
|
|
11
11
|
import { BUDGET_GUIDANCE } from "./budget-guidance.js";
|
|
12
12
|
const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
|
|
@@ -133,8 +133,11 @@ function previewEdit(event, cwd) {
|
|
|
133
133
|
if (original === undefined)
|
|
134
134
|
return undefined;
|
|
135
135
|
const { bom, text } = splitBom(original);
|
|
136
|
-
const
|
|
137
|
-
|
|
136
|
+
const normalized = normalizeToLF(text);
|
|
137
|
+
const { newContent, replacements } = applyEditsToNormalizedContent(normalized, event.input.edits, event.input.path);
|
|
138
|
+
// Same splice as the edit tool, so untouched lines keep their line endings in the preview.
|
|
139
|
+
const content = text === normalized ? newContent : applyReplacementsToOriginal(text, replacements);
|
|
140
|
+
return [{ path, content: bom + content }];
|
|
138
141
|
}
|
|
139
142
|
catch {
|
|
140
143
|
return undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"budgets.js","sourceRoot":"","sources":["../../../src/core/builtins/budgets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,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AK,CAAC,CAAC;YACzB,CAAC;YACD,EAAE,CAAC,WAAW,CAAC,EAAE,UAAU,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;QAC1G,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { closeSync, constants, fstatSync, openSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\nimport { getPackageDir, isBunBinary } from \"../../config.ts\";\nimport { spawnProcess, waitForChildProcess } from \"../../utils/child-process.ts\";\nimport { stripFrontmatter } from \"../../utils/frontmatter.ts\";\nimport { splitBom } from \"../../utils/text.ts\";\nimport {\n\ttype BoundaryResult,\n\ttype ExtensionAPI,\n\tisToolCallEventType,\n\ttype ToolCallEvent,\n} from \"../extensions/types.ts\";\nimport type { SessionEntry } from \"../session-manager.ts\";\nimport {\n\tapplyEditsToNormalizedContent,\n\tdetectLineEnding,\n\tnormalizeToLF,\n\trestoreLineEndings,\n} from \"../tools/edit-diff.ts\";\nimport { resolveToCwd } from \"../tools/path-utils.ts\";\nimport { BUDGET_GUIDANCE } from \"./budget-guidance.ts\";\n\ninterface BudgetResult {\n\tstatus: \"passed\" | \"failed\" | \"disabled\" | \"error\";\n\tsummary: string;\n\ttaskId?: string;\n}\n\ntype ProposedFiles = Array<{ path: string; content: string | null }>;\n\nconst READ_ONLY_TOOLS = new Set([\"read\", \"grep\", \"find\", \"ls\"]);\nconst MAX_REPAIR_ATTEMPTS = 3;\nconst CONTEXT_TYPE = \"budget-context\";\nconst RUNTIME_TIMEOUT_MS = 60_000;\nconst MAX_OUTPUT_BYTES = 1024 * 1024;\n\nfunction runtimePath(): string {\n\treturn join(getPackageDir(), \"hooks\", \"checks\", \"budgets-runtime.cjs\");\n}\n\nfunction parseResult(value: unknown): BudgetResult {\n\tif (\n\t\ttypeof value !== \"object\" ||\n\t\tvalue === null ||\n\t\t!(\"status\" in value) ||\n\t\t!(\"summary\" in value) ||\n\t\t(value.status !== \"passed\" &&\n\t\t\tvalue.status !== \"failed\" &&\n\t\t\tvalue.status !== \"disabled\" &&\n\t\t\tvalue.status !== \"error\") ||\n\t\ttypeof value.summary !== \"string\"\n\t) {\n\t\tthrow new Error(\"Invalid budget policy result\");\n\t}\n\treturn {\n\t\tstatus: value.status,\n\t\tsummary: value.summary,\n\t\t...(\"taskId\" in value && typeof value.taskId === \"string\" ? { taskId: value.taskId } : {}),\n\t};\n}\n\nfunction failure(error: unknown): BudgetResult {\n\treturn {\n\t\tstatus: \"error\",\n\t\tsummary: `Budget check failed: ${error instanceof Error ? error.message : String(error)}`,\n\t};\n}\n\n/** Runs the packaged runtime in a child process, so snapshotting a large repository never blocks the session. */\nasync function callBudget(\n\tmethod: \"beginTask\" | \"checkBudget\" | \"auditBudget\",\n\trequest: { cwd: string; proposed?: ProposedFiles },\n\tsignal?: AbortSignal,\n): Promise<BudgetResult> {\n\tlet output = \"\";\n\tlet errors = \"\";\n\tlet termination: string | undefined;\n\ttry {\n\t\t// A compiled binary runs a script as plain Bun when BUN_BE_BUN is set, so budgets need no separate Node.\n\t\tconst child = spawnProcess(process.execPath, [runtimePath(), \"call\"], {\n\t\t\tcwd: request.cwd,\n\t\t\tenv: isBunBinary ? { ...process.env, BUN_BE_BUN: \"1\" } : process.env,\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tconst terminate = (reason: string) => {\n\t\t\ttermination ??= reason;\n\t\t\tchild.kill(\"SIGKILL\");\n\t\t};\n\t\tconst onAbort = () => terminate(\"Budget check was cancelled\");\n\t\tconst timeout = setTimeout(() => terminate(\"Budget check exceeded its 60-second limit\"), RUNTIME_TIMEOUT_MS);\n\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => {\n\t\t\toutput += chunk.toString();\n\t\t\tif (Buffer.byteLength(output) > MAX_OUTPUT_BYTES) terminate(\"Budget check output exceeded 1 MiB\");\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\terrors = `${errors}${chunk.toString()}`.slice(-4000);\n\t\t});\n\t\tif (signal?.aborted) onAbort();\n\t\telse signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tchild.stdin?.end(JSON.stringify({ method, request }));\n\t\ttry {\n\t\t\tconst code = await waitForChildProcess(child);\n\t\t\tif (termination) return failure(termination);\n\t\t\tif (code !== 0) return failure(`budget runtime exited ${code ?? \"without an exit status\"}. ${errors}`.trim());\n\t\t\treturn parseResult(JSON.parse(output));\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t} catch (error) {\n\t\treturn failure(error);\n\t}\n}\n\nfunction loadRuntime() {\n\tconst runtime: unknown = createRequire(import.meta.url)(runtimePath());\n\tif (\n\t\ttypeof runtime !== \"object\" ||\n\t\truntime === null ||\n\t\t!(\"beginTask\" in runtime) ||\n\t\t!(\"budgetConfigured\" in runtime)\n\t) {\n\t\tthrow new Error(\"Missing budget policy\");\n\t}\n\tconst { beginTask, budgetConfigured } = runtime;\n\tif (typeof beginTask !== \"function\" || typeof budgetConfigured !== \"function\")\n\t\tthrow new Error(\"Invalid budget policy\");\n\treturn {\n\t\t/** Starts a new task in this process: the runtime's command-line interface refuses to, so agents cannot. */\n\t\tstartNewTask: (cwd: string) => parseResult(beginTask({ cwd, newTask: true })),\n\t\t/** A file-system check that lets repositories without budgets skip the runtime process entirely. */\n\t\tconfigured: (cwd: string) => budgetConfigured(cwd) === true,\n\t};\n}\n\n/** Reads a regular file; the nonblocking open keeps a named pipe from stalling the session's thread. */\nfunction readRegularFile(path: string): string | undefined {\n\tconst descriptor = openSync(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n\ttry {\n\t\treturn fstatSync(descriptor).isFile() ? readFileSync(descriptor, \"utf8\") : undefined;\n\t} finally {\n\t\tcloseSync(descriptor);\n\t}\n}\n\n/**\n * Edits the tool itself would reject, of files that are not regular files, or that run on another filesystem are\n * left to the tool and the audit after it.\n */\nfunction previewEdit(event: ToolCallEvent, cwd: string): ProposedFiles | undefined {\n\tif (isToolCallEventType(\"write\", event)) {\n\t\treturn [{ path: resolveToCwd(event.input.path, cwd), content: event.input.content }];\n\t}\n\tif (!isToolCallEventType(\"edit\", event)) return undefined;\n\ttry {\n\t\tconst path = resolveToCwd(event.input.path, cwd);\n\t\tconst original = readRegularFile(path);\n\t\tif (original === undefined) return undefined;\n\t\tconst { bom, text } = splitBom(original);\n\t\tconst { newContent } = applyEditsToNormalizedContent(normalizeToLF(text), event.input.edits, event.input.path);\n\t\treturn [{ path, content: bom + restoreLineEndings(newContent, detectLineEnding(text)) }];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** True when budget guidance reached the context after the last compaction. */\nfunction hasBudgetContext(entries: readonly SessionEntry[]): boolean {\n\tconst compaction = entries.findLastIndex((entry) => entry.type === \"compaction\");\n\treturn entries\n\t\t.slice(compaction + 1)\n\t\t.some((entry) => entry.type === \"custom_message\" && entry.customType === CONTEXT_TYPE);\n}\n\nfunction configurationPrompt(request: string): string {\n\tconst packageDir = getPackageDir();\n\tconst body = stripFrontmatter(readFileSync(join(packageDir, \"hooks\", \"checks\", \"budget-command.md\"), \"utf8\"));\n\tconst runtime = runtimePath().replace(/[\"\\\\$`]/g, (character) => `\\\\${character}`);\n\treturn body.replaceAll(\"<BUDGET_RUNTIME>\", () => runtime).replaceAll(\"$ARGUMENTS\", () => request);\n}\n\nexport default function budgetsBuiltin(pi: ExtensionAPI) {\n\tlet runtime: ReturnType<typeof loadRuntime> | undefined;\n\tconst local = () => {\n\t\truntime ??= loadRuntime();\n\t\treturn runtime;\n\t};\n\t// Budgets are opt-in, so a run checks nothing until its start finds a configured repository.\n\tlet active = false;\n\tlet repairAttempts = 0;\n\tconst preflighted = new Set<string>();\n\n\tpi.on(\"before_agent_start\", async (_event, ctx) => {\n\t\trepairAttempts = 0;\n\t\ttry {\n\t\t\tactive = local().configured(ctx.cwd);\n\t\t} catch {\n\t\t\t// The runtime process reports why the packaged policy cannot load.\n\t\t\tactive = true;\n\t\t}\n\t\tif (!active) return;\n\t\tconst result = await callBudget(\"beginTask\", { cwd: ctx.cwd }, ctx.signal);\n\t\tactive = result.status !== \"disabled\";\n\t\tif (!active) return;\n\t\tconst informed = hasBudgetContext(ctx.sessionManager.getBranch());\n\t\tif (informed && result.status === \"passed\") return;\n\t\tconst guided = informed || result.status === \"error\" ? result.summary : `${result.summary}\\n${BUDGET_GUIDANCE}`;\n\t\treturn { message: { customType: CONTEXT_TYPE, content: guided, display: false, details: result } };\n\t});\n\n\tpi.on(\"tool_call\", async (event, ctx) => {\n\t\tif (!active) return;\n\t\tconst proposed = previewEdit(event, ctx.cwd);\n\t\tif (!proposed) return;\n\t\tconst result = await callBudget(\"checkBudget\", { cwd: ctx.cwd, proposed }, ctx.signal);\n\t\tif (result.status === \"failed\") return { block: true, reason: result.summary };\n\t\tif (result.status === \"passed\") preflighted.add(event.toolCallId);\n\t});\n\n\tpi.on(\"tool_result\", async (event, ctx) => {\n\t\tif (!active || READ_ONLY_TOOLS.has(event.toolName)) return;\n\t\t// A write or edit whose preflight passed wrote exactly the content that was checked.\n\t\tif (preflighted.delete(event.toolCallId)) return;\n\t\tconst result = await callBudget(\"auditBudget\", { cwd: ctx.cwd }, ctx.signal);\n\t\tif (result.status !== \"failed\") return;\n\t\treturn { content: [...event.content, { type: \"text\", text: result.summary }] };\n\t});\n\n\tpi.on(\"agent_before_settle\", async (event, ctx): Promise<BoundaryResult | undefined> => {\n\t\tif (!active || event.outcome !== \"completed\") return;\n\t\tconst result = await callBudget(\"auditBudget\", { cwd: ctx.cwd }, ctx.signal);\n\t\tif (result.status === \"passed\" || result.status === \"disabled\") return;\n\t\tconst continueRun = result.status === \"failed\" && repairAttempts < MAX_REPAIR_ATTEMPTS && !ctx.signal?.aborted;\n\t\tlet content: string;\n\t\tif (continueRun) {\n\t\t\trepairAttempts++;\n\t\t\tcontent = `Budget exceeded (repair ${repairAttempts}/${MAX_REPAIR_ATTEMPTS}). Reduce the reported excess while keeping code readable and documentation concise.\\n${result.summary}`;\n\t\t} else if (result.status === \"failed\") {\n\t\t\tcontent = `Budget verification failed. Automatic repair stopped; this work is not within budget.\\n${result.summary}`;\n\t\t} else {\n\t\t\tcontent = `Budget verification could not run, so this work is not checked against the budget. Fix .draht/budgets.json or start a new task with /budget new.\\n${result.summary}`;\n\t\t}\n\t\tif (!continueRun) {\n\t\t\tctx.ui.notify(content, \"error\");\n\t\t\tctx.abort();\n\t\t}\n\t\treturn {\n\t\t\tentries: [\n\t\t\t\t...event.entries,\n\t\t\t\t{ type: \"custom_message\", customType: \"budgets\", content, display: true, details: result },\n\t\t\t],\n\t\t\tcontinue: event.continue || continueRun,\n\t\t};\n\t});\n\n\tpi.registerCommand(\"budget\", {\n\t\tdescription: \"Configure file budgets, show status, or start a new shared task with /budget new\",\n\t\thandler: async (args, ctx) => {\n\t\t\tconst request = args.trim() || \"configure\";\n\t\t\tconst action = /^configure(?:\\s|$)/.test(request) ? \"configure\" : request;\n\t\t\tif (action !== \"configure\" && action !== \"status\" && action !== \"new\") {\n\t\t\t\tctx.ui.notify(\"Usage: /budget [configure|status|new]\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (action !== \"status\" && !ctx.isIdle()) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Wait for the active run to finish before configuring budgets or starting a new task.\",\n\t\t\t\t\t\"error\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (action === \"configure\") {\n\t\t\t\tpi.sendUserMessage(configurationPrompt(request), { expandPromptTemplates: false });\n\t\t\t\tawait ctx.waitForIdle();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet result: BudgetResult;\n\t\t\ttry {\n\t\t\t\tresult =\n\t\t\t\t\taction === \"new\"\n\t\t\t\t\t\t? local().startNewTask(ctx.cwd)\n\t\t\t\t\t\t: await callBudget(\"auditBudget\", { cwd: ctx.cwd }, ctx.signal);\n\t\t\t} catch (error) {\n\t\t\t\tresult = failure(error);\n\t\t\t}\n\t\t\tpi.sendMessage({ customType: \"budget-status\", content: result.summary, display: true, details: result });\n\t\t},\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"budgets.js","sourceRoot":"","sources":["../../../src/core/builtins/budgets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAGN,mBAAmB,GAEnB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,6BAA6B,EAAE,2BAA2B,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAClH,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAUvD,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;AAChE,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAC9B,MAAM,YAAY,GAAG,gBAAgB,CAAC;AACtC,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,gBAAgB,GAAG,IAAI,GAAG,IAAI,CAAC;AAErC,SAA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AAC;gBAC1C,GAAG,CAAC,EAAE,CAAC,MAAM,CACZ,sFAAsF,EACtF,OAAO,CACP,CAAC;gBACF,OAAO;YACR,CAAC;YACD,IAAI,MAAM,KAAK,WAAW,EAAE,CAAC;gBAC5B,EAAE,CAAC,eAAe,CAAC,mBAAmB,CAAC,OAAO,CAAC,EAAE,EAAE,qBAAqB,EAAE,KAAK,EAAE,CAAC,CAAC;gBACnF,MAAM,GAAG,CAAC,WAAW,EAAE,CAAC;gBACxB,OAAO;YACR,CAAC;YACD,IAAI,MAAoB,CAAC;YACzB,IAAI,CAAC;gBACJ,MAAM;oBACL,MAAM,KAAK,KAAK;wBACf,CAAC,CAAC,KAAK,EAAE,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC;wBAC/B,CAAC,CAAC,MAAM,UAAU,CAAC,aAAa,EAAE,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;YACnE,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;YACzB,CAAC;YACD,EAAE,CAAC,WAAW,CAAC,EAAE,UAAU,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;QAC1G,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { closeSync, constants, fstatSync, openSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\nimport { getPackageDir, isBunBinary } from \"../../config.ts\";\nimport { spawnProcess, waitForChildProcess } from \"../../utils/child-process.ts\";\nimport { stripFrontmatter } from \"../../utils/frontmatter.ts\";\nimport { splitBom } from \"../../utils/text.ts\";\nimport {\n\ttype BoundaryResult,\n\ttype ExtensionAPI,\n\tisToolCallEventType,\n\ttype ToolCallEvent,\n} from \"../extensions/types.ts\";\nimport type { SessionEntry } from \"../session-manager.ts\";\nimport { applyEditsToNormalizedContent, applyReplacementsToOriginal, normalizeToLF } from \"../tools/edit-diff.ts\";\nimport { resolveToCwd } from \"../tools/path-utils.ts\";\nimport { BUDGET_GUIDANCE } from \"./budget-guidance.ts\";\n\ninterface BudgetResult {\n\tstatus: \"passed\" | \"failed\" | \"disabled\" | \"error\";\n\tsummary: string;\n\ttaskId?: string;\n}\n\ntype ProposedFiles = Array<{ path: string; content: string | null }>;\n\nconst READ_ONLY_TOOLS = new Set([\"read\", \"grep\", \"find\", \"ls\"]);\nconst MAX_REPAIR_ATTEMPTS = 3;\nconst CONTEXT_TYPE = \"budget-context\";\nconst RUNTIME_TIMEOUT_MS = 60_000;\nconst MAX_OUTPUT_BYTES = 1024 * 1024;\n\nfunction runtimePath(): string {\n\treturn join(getPackageDir(), \"hooks\", \"checks\", \"budgets-runtime.cjs\");\n}\n\nfunction parseResult(value: unknown): BudgetResult {\n\tif (\n\t\ttypeof value !== \"object\" ||\n\t\tvalue === null ||\n\t\t!(\"status\" in value) ||\n\t\t!(\"summary\" in value) ||\n\t\t(value.status !== \"passed\" &&\n\t\t\tvalue.status !== \"failed\" &&\n\t\t\tvalue.status !== \"disabled\" &&\n\t\t\tvalue.status !== \"error\") ||\n\t\ttypeof value.summary !== \"string\"\n\t) {\n\t\tthrow new Error(\"Invalid budget policy result\");\n\t}\n\treturn {\n\t\tstatus: value.status,\n\t\tsummary: value.summary,\n\t\t...(\"taskId\" in value && typeof value.taskId === \"string\" ? { taskId: value.taskId } : {}),\n\t};\n}\n\nfunction failure(error: unknown): BudgetResult {\n\treturn {\n\t\tstatus: \"error\",\n\t\tsummary: `Budget check failed: ${error instanceof Error ? error.message : String(error)}`,\n\t};\n}\n\n/** Runs the packaged runtime in a child process, so snapshotting a large repository never blocks the session. */\nasync function callBudget(\n\tmethod: \"beginTask\" | \"checkBudget\" | \"auditBudget\",\n\trequest: { cwd: string; proposed?: ProposedFiles },\n\tsignal?: AbortSignal,\n): Promise<BudgetResult> {\n\tlet output = \"\";\n\tlet errors = \"\";\n\tlet termination: string | undefined;\n\ttry {\n\t\t// A compiled binary runs a script as plain Bun when BUN_BE_BUN is set, so budgets need no separate Node.\n\t\tconst child = spawnProcess(process.execPath, [runtimePath(), \"call\"], {\n\t\t\tcwd: request.cwd,\n\t\t\tenv: isBunBinary ? { ...process.env, BUN_BE_BUN: \"1\" } : process.env,\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tconst terminate = (reason: string) => {\n\t\t\ttermination ??= reason;\n\t\t\tchild.kill(\"SIGKILL\");\n\t\t};\n\t\tconst onAbort = () => terminate(\"Budget check was cancelled\");\n\t\tconst timeout = setTimeout(() => terminate(\"Budget check exceeded its 60-second limit\"), RUNTIME_TIMEOUT_MS);\n\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => {\n\t\t\toutput += chunk.toString();\n\t\t\tif (Buffer.byteLength(output) > MAX_OUTPUT_BYTES) terminate(\"Budget check output exceeded 1 MiB\");\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\terrors = `${errors}${chunk.toString()}`.slice(-4000);\n\t\t});\n\t\tif (signal?.aborted) onAbort();\n\t\telse signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tchild.stdin?.end(JSON.stringify({ method, request }));\n\t\ttry {\n\t\t\tconst code = await waitForChildProcess(child);\n\t\t\tif (termination) return failure(termination);\n\t\t\tif (code !== 0) return failure(`budget runtime exited ${code ?? \"without an exit status\"}. ${errors}`.trim());\n\t\t\treturn parseResult(JSON.parse(output));\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t} catch (error) {\n\t\treturn failure(error);\n\t}\n}\n\nfunction loadRuntime() {\n\tconst runtime: unknown = createRequire(import.meta.url)(runtimePath());\n\tif (\n\t\ttypeof runtime !== \"object\" ||\n\t\truntime === null ||\n\t\t!(\"beginTask\" in runtime) ||\n\t\t!(\"budgetConfigured\" in runtime)\n\t) {\n\t\tthrow new Error(\"Missing budget policy\");\n\t}\n\tconst { beginTask, budgetConfigured } = runtime;\n\tif (typeof beginTask !== \"function\" || typeof budgetConfigured !== \"function\")\n\t\tthrow new Error(\"Invalid budget policy\");\n\treturn {\n\t\t/** Starts a new task in this process: the runtime's command-line interface refuses to, so agents cannot. */\n\t\tstartNewTask: (cwd: string) => parseResult(beginTask({ cwd, newTask: true })),\n\t\t/** A file-system check that lets repositories without budgets skip the runtime process entirely. */\n\t\tconfigured: (cwd: string) => budgetConfigured(cwd) === true,\n\t};\n}\n\n/** Reads a regular file; the nonblocking open keeps a named pipe from stalling the session's thread. */\nfunction readRegularFile(path: string): string | undefined {\n\tconst descriptor = openSync(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n\ttry {\n\t\treturn fstatSync(descriptor).isFile() ? readFileSync(descriptor, \"utf8\") : undefined;\n\t} finally {\n\t\tcloseSync(descriptor);\n\t}\n}\n\n/**\n * Edits the tool itself would reject, of files that are not regular files, or that run on another filesystem are\n * left to the tool and the audit after it.\n */\nfunction previewEdit(event: ToolCallEvent, cwd: string): ProposedFiles | undefined {\n\tif (isToolCallEventType(\"write\", event)) {\n\t\treturn [{ path: resolveToCwd(event.input.path, cwd), content: event.input.content }];\n\t}\n\tif (!isToolCallEventType(\"edit\", event)) return undefined;\n\ttry {\n\t\tconst path = resolveToCwd(event.input.path, cwd);\n\t\tconst original = readRegularFile(path);\n\t\tif (original === undefined) return undefined;\n\t\tconst { bom, text } = splitBom(original);\n\t\tconst normalized = normalizeToLF(text);\n\t\tconst { newContent, replacements } = applyEditsToNormalizedContent(\n\t\t\tnormalized,\n\t\t\tevent.input.edits,\n\t\t\tevent.input.path,\n\t\t);\n\t\t// Same splice as the edit tool, so untouched lines keep their line endings in the preview.\n\t\tconst content = text === normalized ? newContent : applyReplacementsToOriginal(text, replacements);\n\t\treturn [{ path, content: bom + content }];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** True when budget guidance reached the context after the last compaction. */\nfunction hasBudgetContext(entries: readonly SessionEntry[]): boolean {\n\tconst compaction = entries.findLastIndex((entry) => entry.type === \"compaction\");\n\treturn entries\n\t\t.slice(compaction + 1)\n\t\t.some((entry) => entry.type === \"custom_message\" && entry.customType === CONTEXT_TYPE);\n}\n\nfunction configurationPrompt(request: string): string {\n\tconst packageDir = getPackageDir();\n\tconst body = stripFrontmatter(readFileSync(join(packageDir, \"hooks\", \"checks\", \"budget-command.md\"), \"utf8\"));\n\tconst runtime = runtimePath().replace(/[\"\\\\$`]/g, (character) => `\\\\${character}`);\n\treturn body.replaceAll(\"<BUDGET_RUNTIME>\", () => runtime).replaceAll(\"$ARGUMENTS\", () => request);\n}\n\nexport default function budgetsBuiltin(pi: ExtensionAPI) {\n\tlet runtime: ReturnType<typeof loadRuntime> | undefined;\n\tconst local = () => {\n\t\truntime ??= loadRuntime();\n\t\treturn runtime;\n\t};\n\t// Budgets are opt-in, so a run checks nothing until its start finds a configured repository.\n\tlet active = false;\n\tlet repairAttempts = 0;\n\tconst preflighted = new Set<string>();\n\n\tpi.on(\"before_agent_start\", async (_event, ctx) => {\n\t\trepairAttempts = 0;\n\t\ttry {\n\t\t\tactive = local().configured(ctx.cwd);\n\t\t} catch {\n\t\t\t// The runtime process reports why the packaged policy cannot load.\n\t\t\tactive = true;\n\t\t}\n\t\tif (!active) return;\n\t\tconst result = await callBudget(\"beginTask\", { cwd: ctx.cwd }, ctx.signal);\n\t\tactive = result.status !== \"disabled\";\n\t\tif (!active) return;\n\t\tconst informed = hasBudgetContext(ctx.sessionManager.getBranch());\n\t\tif (informed && result.status === \"passed\") return;\n\t\tconst guided = informed || result.status === \"error\" ? result.summary : `${result.summary}\\n${BUDGET_GUIDANCE}`;\n\t\treturn { message: { customType: CONTEXT_TYPE, content: guided, display: false, details: result } };\n\t});\n\n\tpi.on(\"tool_call\", async (event, ctx) => {\n\t\tif (!active) return;\n\t\tconst proposed = previewEdit(event, ctx.cwd);\n\t\tif (!proposed) return;\n\t\tconst result = await callBudget(\"checkBudget\", { cwd: ctx.cwd, proposed }, ctx.signal);\n\t\tif (result.status === \"failed\") return { block: true, reason: result.summary };\n\t\tif (result.status === \"passed\") preflighted.add(event.toolCallId);\n\t});\n\n\tpi.on(\"tool_result\", async (event, ctx) => {\n\t\tif (!active || READ_ONLY_TOOLS.has(event.toolName)) return;\n\t\t// A write or edit whose preflight passed wrote exactly the content that was checked.\n\t\tif (preflighted.delete(event.toolCallId)) return;\n\t\tconst result = await callBudget(\"auditBudget\", { cwd: ctx.cwd }, ctx.signal);\n\t\tif (result.status !== \"failed\") return;\n\t\treturn { content: [...event.content, { type: \"text\", text: result.summary }] };\n\t});\n\n\tpi.on(\"agent_before_settle\", async (event, ctx): Promise<BoundaryResult | undefined> => {\n\t\tif (!active || event.outcome !== \"completed\") return;\n\t\tconst result = await callBudget(\"auditBudget\", { cwd: ctx.cwd }, ctx.signal);\n\t\tif (result.status === \"passed\" || result.status === \"disabled\") return;\n\t\tconst continueRun = result.status === \"failed\" && repairAttempts < MAX_REPAIR_ATTEMPTS && !ctx.signal?.aborted;\n\t\tlet content: string;\n\t\tif (continueRun) {\n\t\t\trepairAttempts++;\n\t\t\tcontent = `Budget exceeded (repair ${repairAttempts}/${MAX_REPAIR_ATTEMPTS}). Reduce the reported excess while keeping code readable and documentation concise.\\n${result.summary}`;\n\t\t} else if (result.status === \"failed\") {\n\t\t\tcontent = `Budget verification failed. Automatic repair stopped; this work is not within budget.\\n${result.summary}`;\n\t\t} else {\n\t\t\tcontent = `Budget verification could not run, so this work is not checked against the budget. Fix .draht/budgets.json or start a new task with /budget new.\\n${result.summary}`;\n\t\t}\n\t\tif (!continueRun) {\n\t\t\tctx.ui.notify(content, \"error\");\n\t\t\tctx.abort();\n\t\t}\n\t\treturn {\n\t\t\tentries: [\n\t\t\t\t...event.entries,\n\t\t\t\t{ type: \"custom_message\", customType: \"budgets\", content, display: true, details: result },\n\t\t\t],\n\t\t\tcontinue: event.continue || continueRun,\n\t\t};\n\t});\n\n\tpi.registerCommand(\"budget\", {\n\t\tdescription: \"Configure file budgets, show status, or start a new shared task with /budget new\",\n\t\thandler: async (args, ctx) => {\n\t\t\tconst request = args.trim() || \"configure\";\n\t\t\tconst action = /^configure(?:\\s|$)/.test(request) ? \"configure\" : request;\n\t\t\tif (action !== \"configure\" && action !== \"status\" && action !== \"new\") {\n\t\t\t\tctx.ui.notify(\"Usage: /budget [configure|status|new]\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (action !== \"status\" && !ctx.isIdle()) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Wait for the active run to finish before configuring budgets or starting a new task.\",\n\t\t\t\t\t\"error\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (action === \"configure\") {\n\t\t\t\tpi.sendUserMessage(configurationPrompt(request), { expandPromptTemplates: false });\n\t\t\t\tawait ctx.waitForIdle();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet result: BudgetResult;\n\t\t\ttry {\n\t\t\t\tresult =\n\t\t\t\t\taction === \"new\"\n\t\t\t\t\t\t? local().startNewTask(ctx.cwd)\n\t\t\t\t\t\t: await callBudget(\"auditBudget\", { cwd: ctx.cwd }, ctx.signal);\n\t\t\t} catch (error) {\n\t\t\t\tresult = failure(error);\n\t\t\t}\n\t\t\tpi.sendMessage({ customType: \"budget-status\", content: result.summary, display: true, details: result });\n\t\t},\n\t});\n}\n"]}
|
|
@@ -1,41 +1,8 @@
|
|
|
1
|
-
import { type Api, type
|
|
1
|
+
import { type Api, type CacheWarmingAction, type CacheWarmingDecision, type Context, type Model, type ModelsSimpleStreamOptions } from "@draht/ai";
|
|
2
2
|
import type { ModelRuntime } from "./model-runtime.ts";
|
|
3
3
|
import type { SessionManager, UsageEntry } from "./session-manager.ts";
|
|
4
4
|
import type { CacheWarmingMode } from "./settings-manager.ts";
|
|
5
|
-
|
|
6
|
-
export declare function getCacheWarmingDelayMs(ttlMs: number): number | undefined;
|
|
7
|
-
/**
|
|
8
|
-
* Lifetime of the prompt cache entry a request writes, from the model's
|
|
9
|
-
* `promptCache` tier for the retention the request used. Undefined when the
|
|
10
|
-
* model has no lifetime for that tier or caching is off.
|
|
11
|
-
*/
|
|
12
|
-
export declare function getPromptCacheTtlMs(model: Model<Api>, options: SimpleStreamOptions | undefined): number | undefined;
|
|
13
|
-
/**
|
|
14
|
-
* Whether replaying the request with a one-token output cap leaves its cache
|
|
15
|
-
* entry untouched. Anthropic's budget-based thinking (Claude models without
|
|
16
|
-
* adaptive thinking) derives `budget_tokens` from `max_tokens`; the replay
|
|
17
|
-
* would get a different budget, which Anthropic keys the message cache on,
|
|
18
|
-
* and the model could still think for thousands of tokens.
|
|
19
|
-
*/
|
|
20
|
-
export declare function isReplayable(model: Model<Api>, options: SimpleStreamOptions | undefined): boolean;
|
|
21
|
-
export type CacheWarmingAction = "warm" | "stop";
|
|
22
|
-
/** Inputs and outcome of one warm-or-stop decision, as shown by `/session`. */
|
|
23
|
-
export interface CacheWarmingDecision {
|
|
24
|
-
/** "streaming" while the agent run that sent the request is still active. */
|
|
25
|
-
phase: "streaming" | "idle";
|
|
26
|
-
/** Price of this refresh: a cache read of the prompt plus one output token. */
|
|
27
|
-
warmCost: number;
|
|
28
|
-
/** Extra price of the next real request if the cache entry is lost. */
|
|
29
|
-
missCost: number;
|
|
30
|
-
/** Estimated chance that a real request arrives before the entry expires. */
|
|
31
|
-
continuationProbability: number;
|
|
32
|
-
/** `continuationProbability * missCost - warmCost`. */
|
|
33
|
-
expectedSavings: number;
|
|
34
|
-
/** False when the prompt size or the model's prices are unknown. */
|
|
35
|
-
economicsAvailable: boolean;
|
|
36
|
-
/** Pi's decision: "warm" when `expectedSavings` is at least $0.05. */
|
|
37
|
-
action: CacheWarmingAction;
|
|
38
|
-
}
|
|
5
|
+
export type { CacheWarmingAction, CacheWarmingDecision };
|
|
39
6
|
/**
|
|
40
7
|
* Fired before each refresh with draht's decision filled in. Everything else an
|
|
41
8
|
* extension might want (model, idle state, context size) is on the context.
|
|
@@ -98,6 +65,6 @@ export declare class CacheWarmer {
|
|
|
98
65
|
}
|
|
99
66
|
/** One-line status for `/session`. */
|
|
100
67
|
export declare function formatCacheWarmingStatus(status: CacheWarmingStatus, now?: number): string;
|
|
101
|
-
/** One-line transcript text for
|
|
102
|
-
export declare function formatCacheWarmingUsage(
|
|
68
|
+
/** One-line transcript text for the total cost of one or more consecutive cache warms. */
|
|
69
|
+
export declare function formatCacheWarmingUsage(totalCost: number, note?: string): string;
|
|
103
70
|
//# sourceMappingURL=cache-warmer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-warmer.d.ts","sourceRoot":"","sources":["../../src/core/cache-warmer.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,GAAG,
|
|
1
|
+
{"version":3,"file":"cache-warmer.d.ts","sourceRoot":"","sources":["../../src/core/cache-warmer.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,GAAG,EAIR,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EACzB,KAAK,OAAO,EAMZ,KAAK,KAAK,EACV,KAAK,yBAAyB,EAC9B,MAAM,WAAW,CAAC;AACnB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAgB,cAAc,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACrF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE9D,YAAY,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,CAAC;AAczD;;;GAGG;AACH,MAAM,WAAW,yBAChB,SAAQ,IAAI,CAAC,oBAAoB,EAAE,UAAU,GAAG,UAAU,GAAG,yBAAyB,GAAG,QAAQ,CAAC;IAClG,IAAI,EAAE,wBAAwB,CAAC;CAC/B;AAED,MAAM,W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,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,OAAO,GAAG,IAAI,CAsC/D;IAED,cAAc,IAAI,IAAI,CAYrB;IAED,wEAAwE;IACxE,aAAa,IAAI,IAAI,CAKpB;IAED,MAAM,IAAI,IAAI,CAEb;IAED,OAAO,CAAC,QAAQ;IAQhB,OAAO,CAAC,IAAI;IAKZ,OAAO,CAAC,QAAQ;YAiBF,OAAO;IAoDrB,OAAO,CAAC,qBAAqB;IAM7B,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,iBAAiB;IAOzB,OAAO,CAAC,QAAQ;CAGhB;AA+BD,sCAAsC;AACtC,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,kBAAkB,EAAE,GAAG,SAAa,GAAG,MAAM,CAa7F;AAED,0FAA0F;AAC1F,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAIhF"}
|
|
@@ -1,48 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { getProviderEnvValue } from "@draht/ai/utils/provider-env";
|
|
3
|
-
/** Streaming warming never continues past this long after the real request that started it. */
|
|
4
|
-
const MAX_WARMING_AGE_MS = 60 * 60_000;
|
|
5
|
-
/** Idle warming uses a shorter horizon because continuation estimates become less reliable with age. */
|
|
6
|
-
const MAX_IDLE_WARMING_AGE_MS = 30 * 60_000;
|
|
7
|
-
/** A refresh is sent only when it is expected to save at least this many dollars. */
|
|
8
|
-
const CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS = 0.05;
|
|
9
|
-
/**
|
|
10
|
-
* Chance that a real request arrives before the cache entry expires while the
|
|
11
|
-
* agent sits idle. Measured from our own usage; per-session estimates were not
|
|
12
|
-
* better than this constant.
|
|
13
|
-
*/
|
|
14
|
-
const IDLE_CONTINUATION_PROBABILITY = 0.15;
|
|
15
|
-
/** Refresh at 90% of the TTL while preserving at least ten seconds of margin. */
|
|
16
|
-
export function getCacheWarmingDelayMs(ttlMs) {
|
|
17
|
-
if (ttlMs <= 10_000)
|
|
18
|
-
return undefined;
|
|
19
|
-
return Math.max(1, Math.floor(Math.min(ttlMs * 0.9, ttlMs - 10_000)));
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* Lifetime of the prompt cache entry a request writes, from the model's
|
|
23
|
-
* `promptCache` tier for the retention the request used. Undefined when the
|
|
24
|
-
* model has no lifetime for that tier or caching is off.
|
|
25
|
-
*/
|
|
26
|
-
export function getPromptCacheTtlMs(model, options) {
|
|
27
|
-
const retention = options?.cacheRetention ??
|
|
28
|
-
(getProviderEnvValue("DRAHT_CACHE_RETENTION", options?.env) === "long" ? "long" : "short");
|
|
29
|
-
if (retention === "none")
|
|
30
|
-
return undefined;
|
|
31
|
-
const seconds = model.promptCache?.[retention];
|
|
32
|
-
return seconds === undefined ? undefined : seconds * 1000;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Whether replaying the request with a one-token output cap leaves its cache
|
|
36
|
-
* entry untouched. Anthropic's budget-based thinking (Claude models without
|
|
37
|
-
* adaptive thinking) derives `budget_tokens` from `max_tokens`; the replay
|
|
38
|
-
* would get a different budget, which Anthropic keys the message cache on,
|
|
39
|
-
* and the model could still think for thousands of tokens.
|
|
40
|
-
*/
|
|
41
|
-
export function isReplayable(model, options) {
|
|
42
|
-
if (!options?.reasoning || model.api !== "anthropic-messages")
|
|
43
|
-
return true;
|
|
44
|
-
return model.compat?.forceAdaptiveThinking === true;
|
|
45
|
-
}
|
|
1
|
+
import { CACHE_WARMING_MAX_AGE_MS, CACHE_WARMING_MAX_IDLE_AGE_MS, CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS, evaluateCacheWarming, getCacheWarmingDelayMs, getCacheWarmingRequestOptions, getPromptCacheTtlMs, isCacheWarmingReplayable, } from "@draht/ai";
|
|
46
2
|
/** Prompt size of the most recent real request on the branch, as reported by the provider. */
|
|
47
3
|
function lastPromptTokens(entries) {
|
|
48
4
|
for (let index = entries.length - 1; index >= 0; index--) {
|
|
@@ -54,18 +10,6 @@ function lastPromptTokens(entries) {
|
|
|
54
10
|
}
|
|
55
11
|
return 0;
|
|
56
12
|
}
|
|
57
|
-
function price(model, tokens) {
|
|
58
|
-
const usage = {
|
|
59
|
-
input: 0,
|
|
60
|
-
output: 0,
|
|
61
|
-
cacheRead: 0,
|
|
62
|
-
cacheWrite: 0,
|
|
63
|
-
totalTokens: 0,
|
|
64
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
65
|
-
...tokens,
|
|
66
|
-
};
|
|
67
|
-
return calculateCost(model, usage).total;
|
|
68
|
-
}
|
|
69
13
|
/**
|
|
70
14
|
* Keeps one prompt cache entry alive by re-sending its request with a
|
|
71
15
|
* one-token output cap before the entry expires. `start` replaces any
|
|
@@ -116,7 +60,7 @@ export class CacheWarmer {
|
|
|
116
60
|
this.stop("cache warming disabled");
|
|
117
61
|
return;
|
|
118
62
|
}
|
|
119
|
-
if (!
|
|
63
|
+
if (!isCacheWarmingReplayable(request.model, request.options)) {
|
|
120
64
|
this.stop("request cannot be replayed safely");
|
|
121
65
|
return;
|
|
122
66
|
}
|
|
@@ -155,7 +99,7 @@ export class CacheWarmer {
|
|
|
155
99
|
return;
|
|
156
100
|
}
|
|
157
101
|
run.phase = "idle";
|
|
158
|
-
const deadline = run.startedAt +
|
|
102
|
+
const deadline = run.startedAt + CACHE_WARMING_MAX_IDLE_AGE_MS;
|
|
159
103
|
if (run.nextWarmAt > deadline || Date.now() >= deadline) {
|
|
160
104
|
this.stop("30-minute idle safety limit reached");
|
|
161
105
|
}
|
|
@@ -192,7 +136,7 @@ export class CacheWarmer {
|
|
|
192
136
|
// the planned pre-expiry margin for that delay and request dispatch; a
|
|
193
137
|
// late refresh is likely a full-price cache write, not a cache warm.
|
|
194
138
|
run.refreshDeadlineAt = run.nextWarmAt + Math.floor((run.ttlMs - run.delayMs) / 2);
|
|
195
|
-
const deadline = run.startedAt + (run.phase === "idle" ?
|
|
139
|
+
const deadline = run.startedAt + (run.phase === "idle" ? CACHE_WARMING_MAX_IDLE_AGE_MS : CACHE_WARMING_MAX_AGE_MS);
|
|
196
140
|
if (run.nextWarmAt > deadline || Date.now() >= deadline) {
|
|
197
141
|
this.stop(run.phase === "idle" ? "30-minute idle safety limit reached" : "one-hour safety limit reached");
|
|
198
142
|
return;
|
|
@@ -236,14 +180,7 @@ export class CacheWarmer {
|
|
|
236
180
|
run.extensionOverride = extensionOverride;
|
|
237
181
|
try {
|
|
238
182
|
const message = await this.models
|
|
239
|
-
.streamSimple(run.model, run.context,
|
|
240
|
-
...run.options,
|
|
241
|
-
maxTokens: 1,
|
|
242
|
-
// The warm request repeats the last request; it must not replace the conversation's thread state.
|
|
243
|
-
disableContinuation: true,
|
|
244
|
-
maxRetries: 0,
|
|
245
|
-
signal: run.controller.signal,
|
|
246
|
-
})
|
|
183
|
+
.streamSimple(run.model, run.context, getCacheWarmingRequestOptions(run.options, run.controller.signal))
|
|
247
184
|
.result();
|
|
248
185
|
if (!this.validateRun(run))
|
|
249
186
|
return;
|
|
@@ -282,24 +219,7 @@ export class CacheWarmer {
|
|
|
282
219
|
return undefined;
|
|
283
220
|
}
|
|
284
221
|
evaluate(run) {
|
|
285
|
-
|
|
286
|
-
const promptTokens = lastPromptTokens(this.sessionManager.getBranch());
|
|
287
|
-
const cacheHitCost = price(model, { cacheRead: promptTokens });
|
|
288
|
-
const cacheMissCost = price(model, model.cost.cacheWrite > 0 ? { cacheWrite: promptTokens } : { input: promptTokens });
|
|
289
|
-
const warmCost = price(model, { cacheRead: promptTokens, output: 1 });
|
|
290
|
-
const missCost = Math.max(0, cacheMissCost - cacheHitCost);
|
|
291
|
-
const continuationProbability = run.phase === "idle" ? IDLE_CONTINUATION_PROBABILITY : 1;
|
|
292
|
-
const economicsAvailable = promptTokens > 0 && (cacheHitCost > 0 || cacheMissCost > 0);
|
|
293
|
-
const expectedSavings = continuationProbability * missCost - warmCost;
|
|
294
|
-
return {
|
|
295
|
-
phase: run.phase,
|
|
296
|
-
warmCost,
|
|
297
|
-
missCost,
|
|
298
|
-
continuationProbability,
|
|
299
|
-
expectedSavings,
|
|
300
|
-
economicsAvailable,
|
|
301
|
-
action: expectedSavings >= CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS ? "warm" : "stop",
|
|
302
|
-
};
|
|
222
|
+
return evaluateCacheWarming(run.model, lastPromptTokens(this.sessionManager.getBranch()), run.phase);
|
|
303
223
|
}
|
|
304
224
|
}
|
|
305
225
|
function formatDollars(value) {
|
|
@@ -349,10 +269,10 @@ export function formatCacheWarmingStatus(status, now = Date.now()) {
|
|
|
349
269
|
return `Warming cache (${details})`;
|
|
350
270
|
return `${formatCacheWarmingDecisionTime(status.nextWarmAt, now)} (${details})`;
|
|
351
271
|
}
|
|
352
|
-
/** One-line transcript text for
|
|
353
|
-
export function formatCacheWarmingUsage(
|
|
354
|
-
const
|
|
355
|
-
const cost =
|
|
356
|
-
return `Cache warmed${
|
|
272
|
+
/** One-line transcript text for the total cost of one or more consecutive cache warms. */
|
|
273
|
+
export function formatCacheWarmingUsage(totalCost, note) {
|
|
274
|
+
const noteText = note ? ` (${note})` : "";
|
|
275
|
+
const cost = totalCost.toFixed(6).replace(/(\.\d{3}\d*?)0+$/, "$1");
|
|
276
|
+
return `Cache warmed${noteText}: $${cost}`;
|
|
357
277
|
}
|
|
358
278
|
//# sourceMappingURL=cache-warmer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-warmer.js","sourceRoot":"","sources":["../../src/core/cache-warmer.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,aAAa,GAKb,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAKnE,+FAA+F;AAC/F,MAAM,kBAAkB,GAAG,EAAE,GAAG,MAAM,CAAC;AACvC,wGAAwG;AACxG,MAAM,uBAAuB,GAAG,EAAE,GAAG,MAAM,CAAC;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O,QAAQ,CAAC,MAAM,EAAE,CAAC;IACpE,IAAI,MAAM,CAAC,KAAK,KAAK,UAAU;QAAE,OAAO,YAAY,OAAO,GAAG,CAAC;IAC/D,IAAI,MAAM,CAAC,KAAK,KAAK,YAAY;QAAE,OAAO,kBAAkB,OAAO,GAAG,CAAC;IACvE,OAAO,GAAG,8BAA8B,CAAC,MAAM,CAAC,UAAU,EAAE,GAAG,CAAC,KAAK,OAAO,GAAG,CAAC;AACjF,CAAC;AAED,kEAAkE;AAClE,MAAM,UAAU,uBAAuB,CAAC,KAAiB;IACxD,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IAClD,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAkB,EAAE,IAAI,CAAC,CAAC;IACjF,OAAO,eAAe,IAAI,MAAM,IAAI,EAAE,CAAC;AACxC,CAAC","sourcesContent":["import {\n\ttype Api,\n\ttype Context,\n\tcalculateCost,\n\ttype Model,\n\ttype ModelsSimpleStreamOptions,\n\ttype SimpleStreamOptions,\n\ttype Usage,\n} from \"@draht/ai\";\nimport { getProviderEnvValue } from \"@draht/ai/utils/provider-env\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { SessionEntry, SessionManager, UsageEntry } from \"./session-manager.ts\";\nimport type { CacheWarmingMode } from \"./settings-manager.ts\";\n\n/** Streaming warming never continues past this long after the real request that started it. */\nconst MAX_WARMING_AGE_MS = 60 * 60_000;\n/** Idle warming uses a shorter horizon because continuation estimates become less reliable with age. */\nconst MAX_IDLE_WARMING_AGE_MS = 30 * 60_000;\n/** A refresh is sent only when it is expected to save at least this many dollars. */\nconst CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS = 0.05;\n/**\n * Chance that a real request arrives before the cache entry expires while the\n * agent sits idle. Measured from our own usage; per-session estimates were not\n * better than this constant.\n */\nconst IDLE_CONTINUATION_PROBABILITY = 0.15;\n\n/** Refresh at 90% of the TTL while preserving at least ten seconds of margin. */\nexport function getCacheWarmingDelayMs(ttlMs: number): number | undefined {\n\tif (ttlMs <= 10_000) return undefined;\n\treturn Math.max(1, Math.floor(Math.min(ttlMs * 0.9, ttlMs - 10_000)));\n}\n\n/**\n * Lifetime of the prompt cache entry a request writes, from the model's\n * `promptCache` tier for the retention the request used. Undefined when the\n * model has no lifetime for that tier or caching is off.\n */\nexport function getPromptCacheTtlMs(model: Model<Api>, options: SimpleStreamOptions | undefined): number | undefined {\n\tconst retention =\n\t\toptions?.cacheRetention ??\n\t\t(getProviderEnvValue(\"DRAHT_CACHE_RETENTION\", options?.env) === \"long\" ? \"long\" : \"short\");\n\tif (retention === \"none\") return undefined;\n\tconst seconds = model.promptCache?.[retention];\n\treturn seconds === undefined ? undefined : seconds * 1000;\n}\n\n/**\n * Whether replaying the request with a one-token output cap leaves its cache\n * entry untouched. Anthropic's budget-based thinking (Claude models without\n * adaptive thinking) derives `budget_tokens` from `max_tokens`; the replay\n * would get a different budget, which Anthropic keys the message cache on,\n * and the model could still think for thousands of tokens.\n */\nexport function isReplayable(model: Model<Api>, options: SimpleStreamOptions | undefined): boolean {\n\tif (!options?.reasoning || model.api !== \"anthropic-messages\") return true;\n\treturn (model as Model<\"anthropic-messages\">).compat?.forceAdaptiveThinking === true;\n}\n\n/** Prompt size of the most recent real request on the branch, as reported by the provider. */\nfunction lastPromptTokens(entries: SessionEntry[]): number {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tconst usage = entry.message.usage;\n\t\t\treturn usage.input + usage.cacheRead + usage.cacheWrite;\n\t\t}\n\t}\n\treturn 0;\n}\n\nfunction price(\n\tmodel: Model<Api>,\n\ttokens: Partial<Pick<Usage, \"input\" | \"output\" | \"cacheRead\" | \"cacheWrite\">>,\n): number {\n\tconst usage: Usage = {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t...tokens,\n\t};\n\treturn calculateCost(model, usage).total;\n}\n\nexport type CacheWarmingAction = \"warm\" | \"stop\";\n\n/** Inputs and outcome of one warm-or-stop decision, as shown by `/session`. */\nexport interface CacheWarmingDecision {\n\t/** \"streaming\" while the agent run that sent the request is still active. */\n\tphase: \"streaming\" | \"idle\";\n\t/** Price of this refresh: a cache read of the prompt plus one output token. */\n\twarmCost: number;\n\t/** Extra price of the next real request if the cache entry is lost. */\n\tmissCost: number;\n\t/** Estimated chance that a real request arrives before the entry expires. */\n\tcontinuationProbability: number;\n\t/** `continuationProbability * missCost - warmCost`. */\n\texpectedSavings: number;\n\t/** False when the prompt size or the model's prices are unknown. */\n\teconomicsAvailable: boolean;\n\t/** Pi's decision: \"warm\" when `expectedSavings` is at least $0.05. */\n\taction: CacheWarmingAction;\n}\n\n/**\n * Fired before each refresh with draht's decision filled in. Everything else an\n * extension might want (model, idle state, context size) is on the context.\n */\nexport interface CacheWarmingDecisionEvent\n\textends Pick<CacheWarmingDecision, \"warmCost\" | \"missCost\" | \"continuationProbability\" | \"action\"> {\n\ttype: \"cache_warming_decision\";\n}\n\nexport interface CacheWarmingDecisionEventResult {\n\t/** Override whether this refresh is sent. \"stop\" ends warming until the next real request. */\n\taction?: CacheWarmingAction;\n}\n\nexport interface CacheWarmingStatus {\n\t/** \"scheduled\": a refresh timer is armed; \"refreshing\": a warm request is in flight. */\n\tstate: \"inactive\" | \"scheduled\" | \"refreshing\";\n\t/** Why nothing is scheduled. */\n\treason?: string;\n\tnextWarmAt?: number;\n\t/** The pending decision, or the decision that stopped warming. */\n\tdecision?: CacheWarmingDecision;\n\t/** True when an extension changed `decision.action`. */\n\textensionOverride?: boolean;\n}\n\n/** The request whose prompt cache entry should be kept warm, exactly as it was sent. */\nexport interface CacheWarmRequest {\n\tmodel: Model<Api>;\n\tcontext: Context;\n\toptions: ModelsSimpleStreamOptions;\n}\n\ninterface ActiveRun extends CacheWarmRequest {\n\t/** False once the session's model or messages no longer match the request. */\n\tisCurrent: () => boolean;\n\tttlMs: number;\n\tdelayMs: number;\n\t/** Latest safe time to send this refresh, leaving half the original expiry margin. */\n\trefreshDeadlineAt: number;\n\tstartedAt: number;\n\tcontroller: AbortController;\n\tphase: \"streaming\" | \"idle\";\n\tnextWarmAt: number;\n\t/** Set while a refresh that an extension forced is in flight. */\n\textensionOverride: boolean;\n\ttimer?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Keeps one prompt cache entry alive by re-sending its request with a\n * one-token output cap before the entry expires. `start` replaces any\n * previous run; warm requests never extend the fixed safety windows.\n */\nexport class CacheWarmer {\n\tprivate run?: ActiveRun;\n\tprivate inactive: CacheWarmingStatus;\n\tprivate readonly models: Pick<ModelRuntime, \"streamSimple\">;\n\tprivate readonly sessionManager: Pick<SessionManager, \"appendUsage\" | \"getBranch\">;\n\tprivate readonly getMode: () => CacheWarmingMode;\n\t/** Lets extensions override `event.action`; failures fall back to draht's decision. */\n\tprivate readonly decide: (event: CacheWarmingDecisionEvent) => Promise<CacheWarmingAction>;\n\t/** Called with the persisted usage entry after each successful refresh. */\n\tonWarmed?: (entry: UsageEntry) => void;\n\n\tconstructor(\n\t\tmodels: Pick<ModelRuntime, \"streamSimple\">,\n\t\tsessionManager: Pick<SessionManager, \"appendUsage\" | \"getBranch\">,\n\t\tgetMode: () => CacheWarmingMode,\n\t\tdecide: (event: CacheWarmingDecisionEvent) => Promise<CacheWarmingAction> = async (event) => event.action,\n\t) {\n\t\tthis.models = models;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.getMode = getMode;\n\t\tthis.decide = decide;\n\t\tthis.inactive = { state: \"inactive\", reason: \"waiting for first request\" };\n\t}\n\n\tget status(): CacheWarmingStatus {\n\t\tif (this.getMode() === \"off\") return { state: \"inactive\", reason: \"cache warming disabled\" };\n\t\tconst run = this.run;\n\t\tif (!run) return this.inactive;\n\t\tif (!run.isCurrent()) return { state: \"inactive\", reason: \"conversation context changed\" };\n\t\tconst decision = this.evaluate(run);\n\t\tconst refreshing = run.timer === undefined;\n\t\tif (!decision.economicsAvailable && !refreshing) {\n\t\t\treturn { state: \"inactive\", reason: \"cache economics unavailable\" };\n\t\t}\n\t\treturn {\n\t\t\tstate: refreshing ? \"refreshing\" : \"scheduled\",\n\t\t\tnextWarmAt: run.nextWarmAt,\n\t\t\tdecision,\n\t\t\textensionOverride: run.extensionOverride,\n\t\t};\n\t}\n\n\t/** Keep the prompt cache entry written by `request` warm while `isCurrent` holds. */\n\tstart(request: CacheWarmRequest, isCurrent: () => boolean): void {\n\t\tthis.clearRun();\n\t\tconst mode = this.getMode();\n\t\tif (mode === \"off\") {\n\t\t\tthis.stop(\"cache warming disabled\");\n\t\t\treturn;\n\t\t}\n\t\tif (!isReplayable(request.model, request.options)) {\n\t\t\tthis.stop(\"request cannot be replayed safely\");\n\t\t\treturn;\n\t\t}\n\t\tconst ttlMs = getPromptCacheTtlMs(request.model, request.options);\n\t\tif (ttlMs === undefined) {\n\t\t\tthis.stop(\n\t\t\t\trequest.options.cacheRetention === \"none\"\n\t\t\t\t\t? \"request disabled prompt caching\"\n\t\t\t\t\t: \"cache lifetime unavailable\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst delayMs = getCacheWarmingDelayMs(ttlMs);\n\t\tif (delayMs === undefined) {\n\t\t\tthis.stop(\"cache lifetime unavailable\");\n\t\t\treturn;\n\t\t}\n\t\tthis.run = {\n\t\t\t...request,\n\t\t\tisCurrent,\n\t\t\tttlMs,\n\t\t\tdelayMs,\n\t\t\trefreshDeadlineAt: 0,\n\t\t\tstartedAt: Date.now(),\n\t\t\tcontroller: new AbortController(),\n\t\t\tphase: \"streaming\",\n\t\t\tnextWarmAt: 0,\n\t\t\textensionOverride: false,\n\t\t};\n\t\tthis.schedule(this.run);\n\t}\n\n\tonAgentSettled(): void {\n\t\tconst run = this.run;\n\t\tif (!run) return;\n\t\tif (this.getMode() === \"streaming\") {\n\t\t\tthis.stop(\"agent run settled\");\n\t\t\treturn;\n\t\t}\n\t\trun.phase = \"idle\";\n\t\tconst deadline = run.startedAt + MAX_IDLE_WARMING_AGE_MS;\n\t\tif (run.nextWarmAt > deadline || Date.now() >= deadline) {\n\t\t\tthis.stop(\"30-minute idle safety limit reached\");\n\t\t}\n\t}\n\n\t/** Reconcile an active run after the persisted warming mode changes. */\n\tonModeChanged(): void {\n\t\tconst run = this.run;\n\t\tif (!run) return;\n\t\tconst reason = this.getModeStopReason(run);\n\t\tif (reason) this.stop(reason);\n\t}\n\n\tcancel(): void {\n\t\tthis.stop(\"inactive\");\n\t}\n\n\tprivate clearRun(): void {\n\t\tconst run = this.run;\n\t\tif (!run) return;\n\t\tthis.run = undefined;\n\t\tif (run.timer) clearTimeout(run.timer);\n\t\trun.controller.abort();\n\t}\n\n\tprivate stop(reason: string, stopped?: Pick<CacheWarmingStatus, \"decision\" | \"extensionOverride\">): void {\n\t\tthis.clearRun();\n\t\tthis.inactive = { state: \"inactive\", reason, ...stopped };\n\t}\n\n\tprivate schedule(run: ActiveRun): void {\n\t\trun.extensionOverride = false;\n\t\trun.nextWarmAt = Date.now() + run.delayMs;\n\t\t// A timer can run late after sleep or event-loop blockage. Keep half of\n\t\t// the planned pre-expiry margin for that delay and request dispatch; a\n\t\t// late refresh is likely a full-price cache write, not a cache warm.\n\t\trun.refreshDeadlineAt = run.nextWarmAt + Math.floor((run.ttlMs - run.delayMs) / 2);\n\t\tconst deadline = run.startedAt + (run.phase === \"idle\" ? MAX_IDLE_WARMING_AGE_MS : MAX_WARMING_AGE_MS);\n\t\tif (run.nextWarmAt > deadline || Date.now() >= deadline) {\n\t\t\tthis.stop(run.phase === \"idle\" ? \"30-minute idle safety limit reached\" : \"one-hour safety limit reached\");\n\t\t\treturn;\n\t\t}\n\t\trun.timer = setTimeout(() => void this.refresh(run), Math.max(0, run.nextWarmAt - Date.now()));\n\t\trun.timer.unref?.();\n\t}\n\n\tprivate async refresh(run: ActiveRun): Promise<void> {\n\t\trun.timer = undefined;\n\t\tif (!this.validateRun(run)) return;\n\t\tif (this.refreshDeadlineMissed(run)) return;\n\t\tconst decision = this.evaluate(run);\n\t\tconst { warmCost, missCost, continuationProbability } = decision;\n\t\tlet action = decision.action;\n\t\ttry {\n\t\t\taction = await this.decide({\n\t\t\t\ttype: \"cache_warming_decision\",\n\t\t\t\twarmCost,\n\t\t\t\tmissCost,\n\t\t\t\tcontinuationProbability,\n\t\t\t\taction,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Extension failures fall back to draht's own decision.\n\t\t}\n\t\tif (!this.validateRun(run) || this.refreshDeadlineMissed(run)) return;\n\t\tconst extensionOverride = action !== decision.action;\n\t\tif (action === \"stop\") {\n\t\t\tconst reason = extensionOverride\n\t\t\t\t? \"stopped by extension\"\n\t\t\t\t: decision.economicsAvailable\n\t\t\t\t\t? \"expected savings below threshold\"\n\t\t\t\t\t: \"cache economics unavailable\";\n\t\t\tthis.stop(reason, { decision, extensionOverride });\n\t\t\treturn;\n\t\t}\n\n\t\trun.extensionOverride = extensionOverride;\n\t\ttry {\n\t\t\tconst message = await this.models\n\t\t\t\t.streamSimple(run.model, run.context, {\n\t\t\t\t\t...run.options,\n\t\t\t\t\tmaxTokens: 1,\n\t\t\t\t\t// The warm request repeats the last request; it must not replace the conversation's thread state.\n\t\t\t\t\tdisableContinuation: true,\n\t\t\t\t\tmaxRetries: 0,\n\t\t\t\t\tsignal: run.controller.signal,\n\t\t\t\t})\n\t\t\t\t.result();\n\t\t\tif (!this.validateRun(run)) return;\n\t\t\tif (message.stopReason !== \"error\" && message.stopReason !== \"aborted\") {\n\t\t\t\tconst entry = this.sessionManager.appendUsage(\n\t\t\t\t\t\"cache_warm\",\n\t\t\t\t\tmessage.provider,\n\t\t\t\t\tmessage.responseModel ?? message.model,\n\t\t\t\t\tmessage.usage,\n\t\t\t\t\textensionOverride ? \"extension override\" : undefined,\n\t\t\t\t);\n\t\t\t\tthis.onWarmed?.(entry);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Cache warming is best-effort and must not affect the active agent run.\n\t\t}\n\t\tif (this.run === run) this.schedule(run);\n\t}\n\n\tprivate refreshDeadlineMissed(run: ActiveRun): boolean {\n\t\tif (Date.now() <= run.refreshDeadlineAt) return false;\n\t\tthis.stop(\"cache refresh deadline missed\");\n\t\treturn true;\n\t}\n\n\tprivate validateRun(run: ActiveRun): boolean {\n\t\tif (this.run !== run) return false;\n\t\tconst reason = this.getModeStopReason(run) ?? (!run.isCurrent() ? \"conversation context changed\" : undefined);\n\t\tif (!reason) return true;\n\t\tthis.stop(reason);\n\t\treturn false;\n\t}\n\n\tprivate getModeStopReason(run: ActiveRun): string | undefined {\n\t\tconst mode = this.getMode();\n\t\tif (mode === \"off\") return \"cache warming disabled\";\n\t\tif (mode === \"streaming\" && run.phase === \"idle\") return \"agent run settled\";\n\t\treturn undefined;\n\t}\n\n\tprivate evaluate(run: ActiveRun): CacheWarmingDecision {\n\t\tconst model = run.model;\n\t\tconst promptTokens = lastPromptTokens(this.sessionManager.getBranch());\n\t\tconst cacheHitCost = price(model, { cacheRead: promptTokens });\n\t\tconst cacheMissCost = price(\n\t\t\tmodel,\n\t\t\tmodel.cost.cacheWrite > 0 ? { cacheWrite: promptTokens } : { input: promptTokens },\n\t\t);\n\t\tconst warmCost = price(model, { cacheRead: promptTokens, output: 1 });\n\t\tconst missCost = Math.max(0, cacheMissCost - cacheHitCost);\n\t\tconst continuationProbability = run.phase === \"idle\" ? IDLE_CONTINUATION_PROBABILITY : 1;\n\t\tconst economicsAvailable = promptTokens > 0 && (cacheHitCost > 0 || cacheMissCost > 0);\n\t\tconst expectedSavings = continuationProbability * missCost - warmCost;\n\t\treturn {\n\t\t\tphase: run.phase,\n\t\t\twarmCost,\n\t\t\tmissCost,\n\t\t\tcontinuationProbability,\n\t\t\texpectedSavings,\n\t\t\teconomicsAvailable,\n\t\t\taction: expectedSavings >= CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS ? \"warm\" : \"stop\",\n\t\t};\n\t}\n}\n\nfunction formatDollars(value: number): string {\n\treturn value < 0 ? `-$${Math.abs(value).toFixed(3)}` : `$${value.toFixed(3)}`;\n}\n\nfunction formatCacheWarmingEconomics(decision: CacheWarmingDecision): string {\n\tif (!decision.economicsAvailable) return \"cache economics unavailable\";\n\tconst probability = Math.round(decision.continuationProbability * 100);\n\tconst probabilityText =\n\t\tdecision.phase === \"streaming\"\n\t\t\t? `${probability}% continuation probability while agent is running`\n\t\t\t: `${probability}% continuation probability`;\n\tconst comparison = decision.action === \"warm\" ? \">=\" : \"<\";\n\treturn `${probabilityText}, expected savings ${formatDollars(decision.expectedSavings)} ${comparison} $${CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS.toFixed(3)}`;\n}\n\nfunction formatCacheWarmingDecisionTime(nextWarmAt: number | undefined, now: number): string {\n\tif (nextWarmAt === undefined || nextWarmAt <= now) return \"Decision now\";\n\tlet remainingSeconds = Math.ceil((nextWarmAt - now) / 1000);\n\tconst hours = Math.floor(remainingSeconds / 3600);\n\tremainingSeconds %= 3600;\n\tconst minutes = Math.floor(remainingSeconds / 60);\n\tconst seconds = remainingSeconds % 60;\n\tconst parts: string[] = [];\n\tif (hours > 0) parts.push(`${hours}h`);\n\tif (minutes > 0) parts.push(`${minutes}m`);\n\tif (seconds > 0 || parts.length === 0) parts.push(`${seconds}s`);\n\treturn `Decision in ${parts.join(\" \")}`;\n}\n\n/** One-line status for `/session`. */\nexport function formatCacheWarmingStatus(status: CacheWarmingStatus, now = Date.now()): string {\n\tconst decision = status.decision;\n\t// A decision is attached once pi (or an extension) acted on it; \"inactive\"\n\t// without one never got that far.\n\tif (!decision || (status.state === \"inactive\" && !decision.economicsAvailable && !status.extensionOverride)) {\n\t\treturn `Inactive (${status.reason ?? \"unknown reason\"})`;\n\t}\n\tconst details = status.extensionOverride\n\t\t? `extension override, ${formatCacheWarmingEconomics(decision)}`\n\t\t: `${formatCacheWarmingEconomics(decision)} -> ${decision.action}`;\n\tif (status.state === \"inactive\") return `Stopped (${details})`;\n\tif (status.state === \"refreshing\") return `Warming cache (${details})`;\n\treturn `${formatCacheWarmingDecisionTime(status.nextWarmAt, now)} (${details})`;\n}\n\n/** One-line transcript text for persisted cache-warming usage. */\nexport function formatCacheWarmingUsage(entry: UsageEntry): string {\n\tconst note = entry.note ? ` (${entry.note})` : \"\";\n\tconst cost = entry.usage.cost.total.toFixed(6).replace(/(\\.\\d{3}\\d*?)0+$/, \"$1\");\n\treturn `Cache warmed${note}: $${cost}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cache-warmer.js","sourceRoot":"","sources":["../../src/core/cache-warmer.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,wBAAwB,EACxB,6BAA6B,EAC7B,sCAAsC,EAItC,oBAAoB,EACpB,sBAAsB,EACtB,6BAA6B,EAC7B,mBAAmB,EACnB,wBAAwB,GAGxB,MAAM,WAAW,CAAC;AAOnB,8FAA8F;AAC9F,SAAS,gBAAgB,CAAC,OAAuB;IAChD,KAAK,IAAI,KAAK,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QAC1D,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;YACpE,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAClC,OAAO,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,UAAU,CAAC;QACzD,CAAC;IACF,CAAC;IACD,OAA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_WARMING_MAX_AGE_MS,\n\tCACHE_WARMING_MAX_IDLE_AGE_MS,\n\tCACHE_WARMING_MINIMUM_EXPECTED_SAVINGS,\n\ttype CacheWarmingAction,\n\ttype CacheWarmingDecision,\n\ttype Context,\n\tevaluateCacheWarming,\n\tgetCacheWarmingDelayMs,\n\tgetCacheWarmingRequestOptions,\n\tgetPromptCacheTtlMs,\n\tisCacheWarmingReplayable,\n\ttype Model,\n\ttype ModelsSimpleStreamOptions,\n} from \"@draht/ai\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { SessionEntry, SessionManager, UsageEntry } from \"./session-manager.ts\";\nimport type { CacheWarmingMode } from \"./settings-manager.ts\";\n\nexport type { CacheWarmingAction, CacheWarmingDecision };\n\n/** Prompt size of the most recent real request on the branch, as reported by the provider. */\nfunction lastPromptTokens(entries: SessionEntry[]): number {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tconst usage = entry.message.usage;\n\t\t\treturn usage.input + usage.cacheRead + usage.cacheWrite;\n\t\t}\n\t}\n\treturn 0;\n}\n\n/**\n * Fired before each refresh with draht's decision filled in. Everything else an\n * extension might want (model, idle state, context size) is on the context.\n */\nexport interface CacheWarmingDecisionEvent\n\textends Pick<CacheWarmingDecision, \"warmCost\" | \"missCost\" | \"continuationProbability\" | \"action\"> {\n\ttype: \"cache_warming_decision\";\n}\n\nexport interface CacheWarmingDecisionEventResult {\n\t/** Override whether this refresh is sent. \"stop\" ends warming until the next real request. */\n\taction?: CacheWarmingAction;\n}\n\nexport interface CacheWarmingStatus {\n\t/** \"scheduled\": a refresh timer is armed; \"refreshing\": a warm request is in flight. */\n\tstate: \"inactive\" | \"scheduled\" | \"refreshing\";\n\t/** Why nothing is scheduled. */\n\treason?: string;\n\tnextWarmAt?: number;\n\t/** The pending decision, or the decision that stopped warming. */\n\tdecision?: CacheWarmingDecision;\n\t/** True when an extension changed `decision.action`. */\n\textensionOverride?: boolean;\n}\n\n/** The request whose prompt cache entry should be kept warm, exactly as it was sent. */\nexport interface CacheWarmRequest {\n\tmodel: Model<Api>;\n\tcontext: Context;\n\toptions: ModelsSimpleStreamOptions;\n}\n\ninterface ActiveRun extends CacheWarmRequest {\n\t/** False once the session's model or messages no longer match the request. */\n\tisCurrent: () => boolean;\n\tttlMs: number;\n\tdelayMs: number;\n\t/** Latest safe time to send this refresh, leaving half the original expiry margin. */\n\trefreshDeadlineAt: number;\n\tstartedAt: number;\n\tcontroller: AbortController;\n\tphase: \"streaming\" | \"idle\";\n\tnextWarmAt: number;\n\t/** Set while a refresh that an extension forced is in flight. */\n\textensionOverride: boolean;\n\ttimer?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Keeps one prompt cache entry alive by re-sending its request with a\n * one-token output cap before the entry expires. `start` replaces any\n * previous run; warm requests never extend the fixed safety windows.\n */\nexport class CacheWarmer {\n\tprivate run?: ActiveRun;\n\tprivate inactive: CacheWarmingStatus;\n\tprivate readonly models: Pick<ModelRuntime, \"streamSimple\">;\n\tprivate readonly sessionManager: Pick<SessionManager, \"appendUsage\" | \"getBranch\">;\n\tprivate readonly getMode: () => CacheWarmingMode;\n\t/** Lets extensions override `event.action`; failures fall back to draht's decision. */\n\tprivate readonly decide: (event: CacheWarmingDecisionEvent) => Promise<CacheWarmingAction>;\n\t/** Called with the persisted usage entry after each successful refresh. */\n\tonWarmed?: (entry: UsageEntry) => void;\n\n\tconstructor(\n\t\tmodels: Pick<ModelRuntime, \"streamSimple\">,\n\t\tsessionManager: Pick<SessionManager, \"appendUsage\" | \"getBranch\">,\n\t\tgetMode: () => CacheWarmingMode,\n\t\tdecide: (event: CacheWarmingDecisionEvent) => Promise<CacheWarmingAction> = async (event) => event.action,\n\t) {\n\t\tthis.models = models;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.getMode = getMode;\n\t\tthis.decide = decide;\n\t\tthis.inactive = { state: \"inactive\", reason: \"waiting for first request\" };\n\t}\n\n\tget status(): CacheWarmingStatus {\n\t\tif (this.getMode() === \"off\") return { state: \"inactive\", reason: \"cache warming disabled\" };\n\t\tconst run = this.run;\n\t\tif (!run) return this.inactive;\n\t\tif (!run.isCurrent()) return { state: \"inactive\", reason: \"conversation context changed\" };\n\t\tconst decision = this.evaluate(run);\n\t\tconst refreshing = run.timer === undefined;\n\t\tif (!decision.economicsAvailable && !refreshing) {\n\t\t\treturn { state: \"inactive\", reason: \"cache economics unavailable\" };\n\t\t}\n\t\treturn {\n\t\t\tstate: refreshing ? \"refreshing\" : \"scheduled\",\n\t\t\tnextWarmAt: run.nextWarmAt,\n\t\t\tdecision,\n\t\t\textensionOverride: run.extensionOverride,\n\t\t};\n\t}\n\n\t/** Keep the prompt cache entry written by `request` warm while `isCurrent` holds. */\n\tstart(request: CacheWarmRequest, isCurrent: () => boolean): void {\n\t\tthis.clearRun();\n\t\tconst mode = this.getMode();\n\t\tif (mode === \"off\") {\n\t\t\tthis.stop(\"cache warming disabled\");\n\t\t\treturn;\n\t\t}\n\t\tif (!isCacheWarmingReplayable(request.model, request.options)) {\n\t\t\tthis.stop(\"request cannot be replayed safely\");\n\t\t\treturn;\n\t\t}\n\t\tconst ttlMs = getPromptCacheTtlMs(request.model, request.options);\n\t\tif (ttlMs === undefined) {\n\t\t\tthis.stop(\n\t\t\t\trequest.options.cacheRetention === \"none\"\n\t\t\t\t\t? \"request disabled prompt caching\"\n\t\t\t\t\t: \"cache lifetime unavailable\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst delayMs = getCacheWarmingDelayMs(ttlMs);\n\t\tif (delayMs === undefined) {\n\t\t\tthis.stop(\"cache lifetime unavailable\");\n\t\t\treturn;\n\t\t}\n\t\tthis.run = {\n\t\t\t...request,\n\t\t\tisCurrent,\n\t\t\tttlMs,\n\t\t\tdelayMs,\n\t\t\trefreshDeadlineAt: 0,\n\t\t\tstartedAt: Date.now(),\n\t\t\tcontroller: new AbortController(),\n\t\t\tphase: \"streaming\",\n\t\t\tnextWarmAt: 0,\n\t\t\textensionOverride: false,\n\t\t};\n\t\tthis.schedule(this.run);\n\t}\n\n\tonAgentSettled(): void {\n\t\tconst run = this.run;\n\t\tif (!run) return;\n\t\tif (this.getMode() === \"streaming\") {\n\t\t\tthis.stop(\"agent run settled\");\n\t\t\treturn;\n\t\t}\n\t\trun.phase = \"idle\";\n\t\tconst deadline = run.startedAt + CACHE_WARMING_MAX_IDLE_AGE_MS;\n\t\tif (run.nextWarmAt > deadline || Date.now() >= deadline) {\n\t\t\tthis.stop(\"30-minute idle safety limit reached\");\n\t\t}\n\t}\n\n\t/** Reconcile an active run after the persisted warming mode changes. */\n\tonModeChanged(): void {\n\t\tconst run = this.run;\n\t\tif (!run) return;\n\t\tconst reason = this.getModeStopReason(run);\n\t\tif (reason) this.stop(reason);\n\t}\n\n\tcancel(): void {\n\t\tthis.stop(\"inactive\");\n\t}\n\n\tprivate clearRun(): void {\n\t\tconst run = this.run;\n\t\tif (!run) return;\n\t\tthis.run = undefined;\n\t\tif (run.timer) clearTimeout(run.timer);\n\t\trun.controller.abort();\n\t}\n\n\tprivate stop(reason: string, stopped?: Pick<CacheWarmingStatus, \"decision\" | \"extensionOverride\">): void {\n\t\tthis.clearRun();\n\t\tthis.inactive = { state: \"inactive\", reason, ...stopped };\n\t}\n\n\tprivate schedule(run: ActiveRun): void {\n\t\trun.extensionOverride = false;\n\t\trun.nextWarmAt = Date.now() + run.delayMs;\n\t\t// A timer can run late after sleep or event-loop blockage. Keep half of\n\t\t// the planned pre-expiry margin for that delay and request dispatch; a\n\t\t// late refresh is likely a full-price cache write, not a cache warm.\n\t\trun.refreshDeadlineAt = run.nextWarmAt + Math.floor((run.ttlMs - run.delayMs) / 2);\n\t\tconst deadline =\n\t\t\trun.startedAt + (run.phase === \"idle\" ? CACHE_WARMING_MAX_IDLE_AGE_MS : CACHE_WARMING_MAX_AGE_MS);\n\t\tif (run.nextWarmAt > deadline || Date.now() >= deadline) {\n\t\t\tthis.stop(run.phase === \"idle\" ? \"30-minute idle safety limit reached\" : \"one-hour safety limit reached\");\n\t\t\treturn;\n\t\t}\n\t\trun.timer = setTimeout(() => void this.refresh(run), Math.max(0, run.nextWarmAt - Date.now()));\n\t\trun.timer.unref?.();\n\t}\n\n\tprivate async refresh(run: ActiveRun): Promise<void> {\n\t\trun.timer = undefined;\n\t\tif (!this.validateRun(run)) return;\n\t\tif (this.refreshDeadlineMissed(run)) return;\n\t\tconst decision = this.evaluate(run);\n\t\tconst { warmCost, missCost, continuationProbability } = decision;\n\t\tlet action = decision.action;\n\t\ttry {\n\t\t\taction = await this.decide({\n\t\t\t\ttype: \"cache_warming_decision\",\n\t\t\t\twarmCost,\n\t\t\t\tmissCost,\n\t\t\t\tcontinuationProbability,\n\t\t\t\taction,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Extension failures fall back to draht's own decision.\n\t\t}\n\t\tif (!this.validateRun(run) || this.refreshDeadlineMissed(run)) return;\n\t\tconst extensionOverride = action !== decision.action;\n\t\tif (action === \"stop\") {\n\t\t\tconst reason = extensionOverride\n\t\t\t\t? \"stopped by extension\"\n\t\t\t\t: decision.economicsAvailable\n\t\t\t\t\t? \"expected savings below threshold\"\n\t\t\t\t\t: \"cache economics unavailable\";\n\t\t\tthis.stop(reason, { decision, extensionOverride });\n\t\t\treturn;\n\t\t}\n\n\t\trun.extensionOverride = extensionOverride;\n\t\ttry {\n\t\t\tconst message = await this.models\n\t\t\t\t.streamSimple(run.model, run.context, getCacheWarmingRequestOptions(run.options, run.controller.signal))\n\t\t\t\t.result();\n\t\t\tif (!this.validateRun(run)) return;\n\t\t\tif (message.stopReason !== \"error\" && message.stopReason !== \"aborted\") {\n\t\t\t\tconst entry = this.sessionManager.appendUsage(\n\t\t\t\t\t\"cache_warm\",\n\t\t\t\t\tmessage.provider,\n\t\t\t\t\tmessage.responseModel ?? message.model,\n\t\t\t\t\tmessage.usage,\n\t\t\t\t\textensionOverride ? \"extension override\" : undefined,\n\t\t\t\t);\n\t\t\t\tthis.onWarmed?.(entry);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Cache warming is best-effort and must not affect the active agent run.\n\t\t}\n\t\tif (this.run === run) this.schedule(run);\n\t}\n\n\tprivate refreshDeadlineMissed(run: ActiveRun): boolean {\n\t\tif (Date.now() <= run.refreshDeadlineAt) return false;\n\t\tthis.stop(\"cache refresh deadline missed\");\n\t\treturn true;\n\t}\n\n\tprivate validateRun(run: ActiveRun): boolean {\n\t\tif (this.run !== run) return false;\n\t\tconst reason = this.getModeStopReason(run) ?? (!run.isCurrent() ? \"conversation context changed\" : undefined);\n\t\tif (!reason) return true;\n\t\tthis.stop(reason);\n\t\treturn false;\n\t}\n\n\tprivate getModeStopReason(run: ActiveRun): string | undefined {\n\t\tconst mode = this.getMode();\n\t\tif (mode === \"off\") return \"cache warming disabled\";\n\t\tif (mode === \"streaming\" && run.phase === \"idle\") return \"agent run settled\";\n\t\treturn undefined;\n\t}\n\n\tprivate evaluate(run: ActiveRun): CacheWarmingDecision {\n\t\treturn evaluateCacheWarming(run.model, lastPromptTokens(this.sessionManager.getBranch()), run.phase);\n\t}\n}\n\nfunction formatDollars(value: number): string {\n\treturn value < 0 ? `-$${Math.abs(value).toFixed(3)}` : `$${value.toFixed(3)}`;\n}\n\nfunction formatCacheWarmingEconomics(decision: CacheWarmingDecision): string {\n\tif (!decision.economicsAvailable) return \"cache economics unavailable\";\n\tconst probability = Math.round(decision.continuationProbability * 100);\n\tconst probabilityText =\n\t\tdecision.phase === \"streaming\"\n\t\t\t? `${probability}% continuation probability while agent is running`\n\t\t\t: `${probability}% continuation probability`;\n\tconst comparison = decision.action === \"warm\" ? \">=\" : \"<\";\n\treturn `${probabilityText}, expected savings ${formatDollars(decision.expectedSavings)} ${comparison} $${CACHE_WARMING_MINIMUM_EXPECTED_SAVINGS.toFixed(3)}`;\n}\n\nfunction formatCacheWarmingDecisionTime(nextWarmAt: number | undefined, now: number): string {\n\tif (nextWarmAt === undefined || nextWarmAt <= now) return \"Decision now\";\n\tlet remainingSeconds = Math.ceil((nextWarmAt - now) / 1000);\n\tconst hours = Math.floor(remainingSeconds / 3600);\n\tremainingSeconds %= 3600;\n\tconst minutes = Math.floor(remainingSeconds / 60);\n\tconst seconds = remainingSeconds % 60;\n\tconst parts: string[] = [];\n\tif (hours > 0) parts.push(`${hours}h`);\n\tif (minutes > 0) parts.push(`${minutes}m`);\n\tif (seconds > 0 || parts.length === 0) parts.push(`${seconds}s`);\n\treturn `Decision in ${parts.join(\" \")}`;\n}\n\n/** One-line status for `/session`. */\nexport function formatCacheWarmingStatus(status: CacheWarmingStatus, now = Date.now()): string {\n\tconst decision = status.decision;\n\t// A decision is attached once pi (or an extension) acted on it; \"inactive\"\n\t// without one never got that far.\n\tif (!decision || (status.state === \"inactive\" && !decision.economicsAvailable && !status.extensionOverride)) {\n\t\treturn `Inactive (${status.reason ?? \"unknown reason\"})`;\n\t}\n\tconst details = status.extensionOverride\n\t\t? `extension override, ${formatCacheWarmingEconomics(decision)}`\n\t\t: `${formatCacheWarmingEconomics(decision)} -> ${decision.action}`;\n\tif (status.state === \"inactive\") return `Stopped (${details})`;\n\tif (status.state === \"refreshing\") return `Warming cache (${details})`;\n\treturn `${formatCacheWarmingDecisionTime(status.nextWarmAt, now)} (${details})`;\n}\n\n/** One-line transcript text for the total cost of one or more consecutive cache warms. */\nexport function formatCacheWarmingUsage(totalCost: number, note?: string): string {\n\tconst noteText = note ? ` (${note})` : \"\";\n\tconst cost = totalCost.toFixed(6).replace(/(\\.\\d{3}\\d*?)0+$/, \"$1\");\n\treturn `Cache warmed${noteText}: $${cost}`;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAe,KAAK,OAAO,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAe,KAAK,OAAO,EAAE,MAAM,WAAW,CAAC;AAOtD,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAClB,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACpB;AAED,wBAAgB,aAAa,IAAI,cAAc,CAM9C;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,cAAc,GAAG,IAAI,CAe9F;AAkBD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG;IAAE,SAAS,EAAE,MAAM,EAAE,CAAC;IAAC,aAAa,EAAE,MAAM,EAAE,CAAA;CAAE,CAK1G;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,MAAM,CAUzF;AAmBD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAmCjE;AAMD,eAAO,MAAM,2BAA2B,6TAEmF,CAAC"}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Shared utilities for compaction and branch summarization.
|
|
3
3
|
*/
|
|
4
4
|
import { contentText } from "@draht/ai";
|
|
5
|
+
import { sliceHead } from "../tools/truncate.js";
|
|
5
6
|
export function createFileOps() {
|
|
6
7
|
return {
|
|
7
8
|
read: new Set(),
|
|
@@ -88,7 +89,7 @@ function truncateForSummary(text, maxChars) {
|
|
|
88
89
|
if (text.length <= maxChars)
|
|
89
90
|
return text;
|
|
90
91
|
const truncatedChars = text.length - maxChars;
|
|
91
|
-
return `${text
|
|
92
|
+
return `${sliceHead(text, maxChars)}\n\n[... ${truncatedChars} more characters truncated]`;
|
|
92
93
|
}
|
|
93
94
|
/**
|
|
94
95
|
* Serialize LLM messages to text for summarization.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,WAAW,EAAgB,MAAM,WAAW,CAAC;AAYtD,MAAM,UAAU,aAAa;IAC5B,OAAO;QACN,IAAI,EAAE,IAAI,GAAG,EAAE;QACf,OAAO,EAAE,IAAI,GAAG,EAAE;QAClB,MAAM,EAAE,IAAI,GAAG,EAAE;KACjB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAqB,EAAE,OAAuB;IACvF,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;QACnC,wEAAwE;QACxE,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,WAAW,EAAE,KAAK,IAAI,EAAE;YAAE,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACnG,OAAO;IACR,CAAC;IACD,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO;IACzC,IAAI,CAAC,CAAC,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO;IAEvE,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QACrC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;YAAE,SAAS;QAC1D,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,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ACtC,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;YAC7C,IAAI,OAAO,EAAE,CAAC;gBACb,KAAK,CAAC,IAAI,CAAC,kBAAkB,kBAAkB,CAAC,OAAO,EAAE,qBAAqB,CAAC,EAAE,CAAC,CAAC;YACpF,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC3B,CAAC;AAED,+EAA+E;AAC/E,8BAA8B;AAC9B,+EAA+E;AAE/E,MAAM,CAAC,MAAM,2BAA2B,GAAG;;2HAEgF,CAAC","sourcesContent":["/**\n * Shared utilities for compaction and branch summarization.\n */\n\nimport type { AgentMessage } from \"@draht/agent-core\";\nimport { contentText, type Message } from \"@draht/ai\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport function createFileOps(): FileOperations {\n\treturn {\n\t\tread: new Set(),\n\t\twritten: new Set(),\n\t\tedited: new Set(),\n\t};\n}\n\n/**\n * Extract file operations from tool calls in an assistant message, or from the nested calls\n * recorded on a tool result.\n */\nexport function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {\n\tif (message.role === \"toolResult\") {\n\t\t// Calls made from codemode scripts are recorded on the script's result.\n\t\tfor (const call of message.nestedCalls?.calls ?? []) addFileOp(call.name, call.arguments, fileOps);\n\t\treturn;\n\t}\n\tif (message.role !== \"assistant\") return;\n\tif (!(\"content\" in message) || !Array.isArray(message.content)) return;\n\n\tfor (const block of message.content) {\n\t\tif (typeof block !== \"object\" || block === null) continue;\n\t\tif (!(\"type\" in block) || block.type !== \"toolCall\") continue;\n\t\tif (!(\"arguments\" in block) || !(\"name\" in block)) continue;\n\t\taddFileOp(block.name, block.arguments as Record<string, unknown> | undefined, fileOps);\n\t}\n}\n\nfunction addFileOp(toolName: string, args: Record<string, unknown> | undefined, fileOps: FileOperations): void {\n\tconst path = typeof args?.path === \"string\" ? args.path : undefined;\n\tif (!path) return;\n\tswitch (toolName) {\n\t\tcase \"read\":\n\t\t\tfileOps.read.add(path);\n\t\t\tbreak;\n\t\tcase \"write\":\n\t\t\tfileOps.written.add(path);\n\t\t\tbreak;\n\t\tcase \"edit\":\n\t\t\tfileOps.edited.add(path);\n\t\t\tbreak;\n\t}\n}\n\n/**\n * Compute final file lists from file operations.\n * Returns readFiles (files only read, not modified) and modifiedFiles.\n */\nexport function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {\n\tconst modified = new Set([...fileOps.edited, ...fileOps.written]);\n\tconst readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();\n\tconst modifiedFiles = [...modified].sort();\n\treturn { readFiles: readOnly, modifiedFiles };\n}\n\n/**\n * Format file operations as XML tags for summary.\n */\nexport function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {\n\tconst sections: string[] = [];\n\tif (readFiles.length > 0) {\n\t\tsections.push(`<read-files>\\n${readFiles.join(\"\\n\")}\\n</read-files>`);\n\t}\n\tif (modifiedFiles.length > 0) {\n\t\tsections.push(`<modified-files>\\n${modifiedFiles.join(\"\\n\")}\\n</modified-files>`);\n\t}\n\tif (sections.length === 0) return \"\";\n\treturn `\\n\\n${sections.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Message Serialization\n// ============================================================================\n\n/** Maximum characters for a tool result in serialized summaries. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n\n/**\n * Truncate text to a maximum character length for summarization.\n * Keeps the beginning and appends a truncation marker.\n */\nfunction truncateForSummary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst truncatedChars = text.length - maxChars;\n\treturn `${text.slice(0, maxChars)}\\n\\n[... ${truncatedChars} more characters truncated]`;\n}\n\n/**\n * Serialize LLM messages to text for summarization.\n * This prevents the model from treating it as a conversation to continue.\n * Call convertToLlm() first to handle custom message types.\n *\n * Tool results are truncated to keep the summarization request within\n * reasonable token budgets. Full content is not needed for summarization.\n *\n * Thinking is omitted. Providers return summaries of the real reasoning, and\n * replayed thinking is often not part of the model's live context: for example,\n * a block that does not match its request is dropped. Including it can make the\n * summarization request larger than the context it summarizes. Visible text,\n * tool calls, and tool results record what happened.\n */\nexport function serializeConversation(messages: Message[]): string {\n\tconst parts: string[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content = contentText(msg.content, \"\");\n\t\t\tif (content) parts.push(`[User]: ${content}`);\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst toolCalls: string[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = block.arguments as Record<string, unknown>;\n\t\t\t\t\tconst argsStr = Object.entries(args)\n\t\t\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${argsStr})`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (msg.content.some((block) => block.type === \"text\")) {\n\t\t\t\tparts.push(`[Assistant]: ${contentText(msg.content)}`);\n\t\t\t}\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tparts.push(`[Assistant tool calls]: ${toolCalls.join(\"; \")}`);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst content = contentText(msg.content, \"\");\n\t\t\tif (content) {\n\t\t\t\tparts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ============================================================================\n// Summarization System Prompt\n// ============================================================================\n\nexport const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,WAAW,EAAgB,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAYjD,MAAM,UAAU,aAAa;IAC5B,OAAO;QACN,IAAI,EAAE,IAAI,GAAG,EAAE;QACf,OAAO,EAAE,IAAI,GAAG,EAAE;QAClB,MAAM,EAAE,IAAI,GAAG,EAAE;KACjB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAqB,EAAE,OAAuB;IACvF,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;QACnC,wEAAwE;QACxE,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,WAAW,EAAE,KAAK,IAAI,EAAE;YAAE,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACnG,OAAO;IACR,CAAC;IACD,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO;IACzC,IAAI,CAAC,CAAC,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO;IAEvE,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QACrC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;YAAE,SAAS;QAC1D,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;YAAE,SAAS;QAC9D,IAAI,CAAC,CAAC,WAAW,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC;YAAE,SAAS;QAC5D,SAAS,CA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CAAC,OAAO,EAAE,qBAAqB,CAAC,EAAE,CAAC,CAAC;YACpF,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC3B,CAAC;AAED,+EAA+E;AAC/E,8BAA8B;AAC9B,+EAA+E;AAE/E,MAAM,CAAC,MAAM,2BAA2B,GAAG;;2HAEgF,CAAC","sourcesContent":["/**\n * Shared utilities for compaction and branch summarization.\n */\n\nimport type { AgentMessage } from \"@draht/agent-core\";\nimport { contentText, type Message } from \"@draht/ai\";\nimport { sliceHead } from \"../tools/truncate.ts\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport function createFileOps(): FileOperations {\n\treturn {\n\t\tread: new Set(),\n\t\twritten: new Set(),\n\t\tedited: new Set(),\n\t};\n}\n\n/**\n * Extract file operations from tool calls in an assistant message, or from the nested calls\n * recorded on a tool result.\n */\nexport function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {\n\tif (message.role === \"toolResult\") {\n\t\t// Calls made from codemode scripts are recorded on the script's result.\n\t\tfor (const call of message.nestedCalls?.calls ?? []) addFileOp(call.name, call.arguments, fileOps);\n\t\treturn;\n\t}\n\tif (message.role !== \"assistant\") return;\n\tif (!(\"content\" in message) || !Array.isArray(message.content)) return;\n\n\tfor (const block of message.content) {\n\t\tif (typeof block !== \"object\" || block === null) continue;\n\t\tif (!(\"type\" in block) || block.type !== \"toolCall\") continue;\n\t\tif (!(\"arguments\" in block) || !(\"name\" in block)) continue;\n\t\taddFileOp(block.name, block.arguments as Record<string, unknown> | undefined, fileOps);\n\t}\n}\n\nfunction addFileOp(toolName: string, args: Record<string, unknown> | undefined, fileOps: FileOperations): void {\n\tconst path = typeof args?.path === \"string\" ? args.path : undefined;\n\tif (!path) return;\n\tswitch (toolName) {\n\t\tcase \"read\":\n\t\t\tfileOps.read.add(path);\n\t\t\tbreak;\n\t\tcase \"write\":\n\t\t\tfileOps.written.add(path);\n\t\t\tbreak;\n\t\tcase \"edit\":\n\t\t\tfileOps.edited.add(path);\n\t\t\tbreak;\n\t}\n}\n\n/**\n * Compute final file lists from file operations.\n * Returns readFiles (files only read, not modified) and modifiedFiles.\n */\nexport function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {\n\tconst modified = new Set([...fileOps.edited, ...fileOps.written]);\n\tconst readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();\n\tconst modifiedFiles = [...modified].sort();\n\treturn { readFiles: readOnly, modifiedFiles };\n}\n\n/**\n * Format file operations as XML tags for summary.\n */\nexport function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {\n\tconst sections: string[] = [];\n\tif (readFiles.length > 0) {\n\t\tsections.push(`<read-files>\\n${readFiles.join(\"\\n\")}\\n</read-files>`);\n\t}\n\tif (modifiedFiles.length > 0) {\n\t\tsections.push(`<modified-files>\\n${modifiedFiles.join(\"\\n\")}\\n</modified-files>`);\n\t}\n\tif (sections.length === 0) return \"\";\n\treturn `\\n\\n${sections.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Message Serialization\n// ============================================================================\n\n/** Maximum characters for a tool result in serialized summaries. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n\n/**\n * Truncate text to a maximum character length for summarization.\n * Keeps the beginning and appends a truncation marker.\n */\nfunction truncateForSummary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst truncatedChars = text.length - maxChars;\n\treturn `${sliceHead(text, maxChars)}\\n\\n[... ${truncatedChars} more characters truncated]`;\n}\n\n/**\n * Serialize LLM messages to text for summarization.\n * This prevents the model from treating it as a conversation to continue.\n * Call convertToLlm() first to handle custom message types.\n *\n * Tool results are truncated to keep the summarization request within\n * reasonable token budgets. Full content is not needed for summarization.\n *\n * Thinking is omitted. Providers return summaries of the real reasoning, and\n * replayed thinking is often not part of the model's live context: for example,\n * a block that does not match its request is dropped. Including it can make the\n * summarization request larger than the context it summarizes. Visible text,\n * tool calls, and tool results record what happened.\n */\nexport function serializeConversation(messages: Message[]): string {\n\tconst parts: string[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content = contentText(msg.content, \"\");\n\t\t\tif (content) parts.push(`[User]: ${content}`);\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst toolCalls: string[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = block.arguments as Record<string, unknown>;\n\t\t\t\t\tconst argsStr = Object.entries(args)\n\t\t\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${argsStr})`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (msg.content.some((block) => block.type === \"text\")) {\n\t\t\t\tparts.push(`[Assistant]: ${contentText(msg.content)}`);\n\t\t\t}\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tparts.push(`[Assistant tool calls]: ${toolCalls.join(\"; \")}`);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst content = contentText(msg.content, \"\");\n\t\t\tif (content) {\n\t\t\t\tparts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ============================================================================\n// Summarization System Prompt\n// ============================================================================\n\nexport const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n"]}
|
package/dist/core/exec.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ export interface ExecOptions {
|
|
|
23
23
|
export interface ExecResult {
|
|
24
24
|
stdout: string;
|
|
25
25
|
stderr: string;
|
|
26
|
+
/** Exit code, or 128 + signal number when a signal terminated the command (143 for SIGTERM). */
|
|
26
27
|
code: number;
|
|
27
28
|
/** The command was terminated by draht: timeout, abort, or output over `maxBuffer`. */
|
|
28
29
|
killed: boolean;
|