open-multi-agent-kit 0.90.7 → 0.90.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +17 -10
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +5 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/commands/doctor-provider-cli.d.ts +33 -0
- package/dist/commands/doctor-provider-cli.d.ts.map +1 -0
- package/dist/commands/doctor-provider-cli.js +215 -0
- package/dist/commands/doctor-provider-cli.js.map +1 -0
- package/dist/commands/doctor-provider-transport.d.ts +35 -0
- package/dist/commands/doctor-provider-transport.d.ts.map +1 -0
- package/dist/commands/doctor-provider-transport.js +185 -0
- package/dist/commands/doctor-provider-transport.js.map +1 -0
- package/dist/commands/doctor-provider.d.ts +121 -7
- package/dist/commands/doctor-provider.d.ts.map +1 -1
- package/dist/commands/doctor-provider.js +1295 -102
- package/dist/commands/doctor-provider.js.map +1 -1
- package/dist/commands/session-doctor-cli.d.ts +43 -0
- package/dist/commands/session-doctor-cli.d.ts.map +1 -0
- package/dist/commands/session-doctor-cli.js +494 -0
- package/dist/commands/session-doctor-cli.js.map +1 -0
- package/dist/commands/verify-ci.d.ts +21 -0
- package/dist/commands/verify-ci.d.ts.map +1 -0
- package/dist/commands/verify-ci.js +66 -0
- package/dist/commands/verify-ci.js.map +1 -0
- package/dist/core/agent-session-services.d.ts +3 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +3 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +116 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1015 -71
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/agent-tool-settings.d.ts +35 -0
- package/dist/core/agent-tool-settings.d.ts.map +1 -0
- package/dist/core/agent-tool-settings.js +155 -0
- package/dist/core/agent-tool-settings.js.map +1 -0
- package/dist/core/atomic-session-file.d.ts +14 -0
- package/dist/core/atomic-session-file.d.ts.map +1 -0
- package/dist/core/atomic-session-file.js +104 -0
- package/dist/core/atomic-session-file.js.map +1 -0
- package/dist/core/compaction/compaction.d.ts +6 -0
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +12 -1
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/hysteresis.d.ts +27 -0
- package/dist/core/compaction/hysteresis.d.ts.map +1 -0
- package/dist/core/compaction/hysteresis.js +84 -0
- package/dist/core/compaction/hysteresis.js.map +1 -0
- package/dist/core/compaction/index.d.ts +2 -0
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js +2 -0
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/transaction.d.ts +172 -0
- package/dist/core/compaction/transaction.d.ts.map +1 -0
- package/dist/core/compaction/transaction.js +824 -0
- package/dist/core/compaction/transaction.js.map +1 -0
- package/dist/core/context-budget-governor-v2.d.ts +2 -1
- package/dist/core/context-budget-governor-v2.d.ts.map +1 -1
- package/dist/core/context-budget-governor-v2.js +2 -1
- package/dist/core/context-budget-governor-v2.js.map +1 -1
- package/dist/core/context-budget-headroom.d.ts.map +1 -1
- package/dist/core/context-budget-headroom.js +5 -1
- package/dist/core/context-budget-headroom.js.map +1 -1
- package/dist/core/context-budget-reserved-tokens.d.ts +110 -0
- package/dist/core/context-budget-reserved-tokens.d.ts.map +1 -0
- package/dist/core/context-budget-reserved-tokens.js +188 -0
- package/dist/core/context-budget-reserved-tokens.js.map +1 -0
- package/dist/core/context-budget-v2-cache-invalidation.d.ts +133 -0
- package/dist/core/context-budget-v2-cache-invalidation.d.ts.map +1 -0
- package/dist/core/context-budget-v2-cache-invalidation.js +452 -0
- package/dist/core/context-budget-v2-cache-invalidation.js.map +1 -0
- package/dist/core/context-budget-v2-cache-keys.d.ts +3 -0
- package/dist/core/context-budget-v2-cache-keys.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-keys.js +6 -0
- package/dist/core/context-budget-v2-cache-keys.js.map +1 -1
- package/dist/core/context-budget-v2-cache-provider.d.ts +8 -2
- package/dist/core/context-budget-v2-cache-provider.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-provider.js +28 -5
- package/dist/core/context-budget-v2-cache-provider.js.map +1 -1
- package/dist/core/context-budget-v2-plan-cache-keys.d.ts.map +1 -1
- package/dist/core/context-budget-v2-plan-cache-keys.js +1 -0
- package/dist/core/context-budget-v2-plan-cache-keys.js.map +1 -1
- package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
- package/dist/core/context-budget-v2-planner.js +1 -0
- package/dist/core/context-budget-v2-planner.js.map +1 -1
- package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
- package/dist/core/context-budget-v2-selection.js +9 -0
- package/dist/core/context-budget-v2-selection.js.map +1 -1
- package/dist/core/context-budget-v2-types.d.ts +4 -0
- package/dist/core/context-budget-v2-types.d.ts.map +1 -1
- package/dist/core/context-budget-v2-types.js.map +1 -1
- package/dist/core/durable-file-directory.d.ts +4 -0
- package/dist/core/durable-file-directory.d.ts.map +1 -0
- package/dist/core/durable-file-directory.js +76 -0
- package/dist/core/durable-file-directory.js.map +1 -0
- package/dist/core/durable-file-identity.d.ts +26 -0
- package/dist/core/durable-file-identity.d.ts.map +1 -0
- package/dist/core/durable-file-identity.js +118 -0
- package/dist/core/durable-file-identity.js.map +1 -0
- package/dist/core/durable-file-io.d.ts +29 -0
- package/dist/core/durable-file-io.d.ts.map +1 -0
- package/dist/core/durable-file-io.js +179 -0
- package/dist/core/durable-file-io.js.map +1 -0
- package/dist/core/durable-file-lock-cleanup.d.ts +12 -0
- package/dist/core/durable-file-lock-cleanup.d.ts.map +1 -0
- package/dist/core/durable-file-lock-cleanup.js +39 -0
- package/dist/core/durable-file-lock-cleanup.js.map +1 -0
- package/dist/core/durable-file-lock-owner.d.ts +18 -0
- package/dist/core/durable-file-lock-owner.d.ts.map +1 -0
- package/dist/core/durable-file-lock-owner.js +78 -0
- package/dist/core/durable-file-lock-owner.js.map +1 -0
- package/dist/core/durable-file-lock-storage.d.ts +35 -0
- package/dist/core/durable-file-lock-storage.d.ts.map +1 -0
- package/dist/core/durable-file-lock-storage.js +263 -0
- package/dist/core/durable-file-lock-storage.js.map +1 -0
- package/dist/core/durable-file-mode.d.ts +8 -0
- package/dist/core/durable-file-mode.d.ts.map +1 -0
- package/dist/core/durable-file-mode.js +41 -0
- package/dist/core/durable-file-mode.js.map +1 -0
- package/dist/core/extensions/loader.d.ts +12 -0
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +50 -37
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/index.d.ts +6 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +5 -0
- package/dist/core/index.js.map +1 -1
- package/dist/core/loop-gates.d.ts.map +1 -1
- package/dist/core/loop-gates.js +25 -1
- package/dist/core/loop-gates.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/pi-package-intake.d.ts +1 -0
- package/dist/core/pi-package-intake.d.ts.map +1 -1
- package/dist/core/pi-package-intake.js +7 -0
- package/dist/core/pi-package-intake.js.map +1 -1
- package/dist/core/redaction.d.ts +8 -0
- package/dist/core/redaction.d.ts.map +1 -0
- package/dist/core/redaction.js +31 -0
- package/dist/core/redaction.js.map +1 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +36 -0
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/run-journal-store.d.ts +53 -0
- package/dist/core/run-journal-store.d.ts.map +1 -0
- package/dist/core/run-journal-store.js +278 -0
- package/dist/core/run-journal-store.js.map +1 -0
- package/dist/core/run-journal.d.ts +172 -0
- package/dist/core/run-journal.d.ts.map +1 -0
- package/dist/core/run-journal.js +1053 -0
- package/dist/core/run-journal.js.map +1 -0
- package/dist/core/sdk.d.ts +7 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +94 -3
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-doctor-plan.d.ts +128 -0
- package/dist/core/session-doctor-plan.d.ts.map +1 -0
- package/dist/core/session-doctor-plan.js +833 -0
- package/dist/core/session-doctor-plan.js.map +1 -0
- package/dist/core/session-file-compaction.d.ts +6 -0
- package/dist/core/session-file-compaction.d.ts.map +1 -0
- package/dist/core/session-file-compaction.js +169 -0
- package/dist/core/session-file-compaction.js.map +1 -0
- package/dist/core/session-file-head.d.ts +10 -0
- package/dist/core/session-file-head.d.ts.map +1 -0
- package/dist/core/session-file-head.js +78 -0
- package/dist/core/session-file-head.js.map +1 -0
- package/dist/core/session-file-persistence.d.ts +30 -0
- package/dist/core/session-file-persistence.d.ts.map +1 -0
- package/dist/core/session-file-persistence.js +106 -0
- package/dist/core/session-file-persistence.js.map +1 -0
- package/dist/core/session-integrity.d.ts +43 -0
- package/dist/core/session-integrity.d.ts.map +1 -0
- package/dist/core/session-integrity.js +420 -0
- package/dist/core/session-integrity.js.map +1 -0
- package/dist/core/session-manager.d.ts +24 -4
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +242 -125
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-owner-lease.d.ts +22 -0
- package/dist/core/session-owner-lease.d.ts.map +1 -0
- package/dist/core/session-owner-lease.js +176 -0
- package/dist/core/session-owner-lease.js.map +1 -0
- package/dist/core/session-path-policy.d.ts +132 -0
- package/dist/core/session-path-policy.d.ts.map +1 -0
- package/dist/core/session-path-policy.js +780 -0
- package/dist/core/session-path-policy.js.map +1 -0
- package/dist/core/session-repair-plan.d.ts +49 -0
- package/dist/core/session-repair-plan.d.ts.map +1 -0
- package/dist/core/session-repair-plan.js +202 -0
- package/dist/core/session-repair-plan.js.map +1 -0
- package/dist/core/session-termination.d.ts +100 -0
- package/dist/core/session-termination.d.ts.map +1 -0
- package/dist/core/session-termination.js +403 -0
- package/dist/core/session-termination.js.map +1 -0
- package/dist/core/settings-manager.d.ts +32 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +52 -5
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/verified-bash-adapter.d.ts +36 -0
- package/dist/core/verified-bash-adapter.d.ts.map +1 -0
- package/dist/core/verified-bash-adapter.js +90 -0
- package/dist/core/verified-bash-adapter.js.map +1 -0
- package/dist/guardrails/command-redaction.d.ts +32 -0
- package/dist/guardrails/command-redaction.d.ts.map +1 -0
- package/dist/guardrails/command-redaction.js +776 -0
- package/dist/guardrails/command-redaction.js.map +1 -0
- package/dist/guardrails/evidence-attestation.d.ts +31 -0
- package/dist/guardrails/evidence-attestation.d.ts.map +1 -0
- package/dist/guardrails/evidence-attestation.js +178 -0
- package/dist/guardrails/evidence-attestation.js.map +1 -0
- package/dist/guardrails/evidence-receipt-store.d.ts +33 -0
- package/dist/guardrails/evidence-receipt-store.d.ts.map +1 -0
- package/dist/guardrails/evidence-receipt-store.js +446 -0
- package/dist/guardrails/evidence-receipt-store.js.map +1 -0
- package/dist/guardrails/evidence-receipt.d.ts +58 -0
- package/dist/guardrails/evidence-receipt.d.ts.map +1 -0
- package/dist/guardrails/evidence-receipt.js +389 -0
- package/dist/guardrails/evidence-receipt.js.map +1 -0
- package/dist/guardrails/evidence-system.d.ts +40 -9
- package/dist/guardrails/evidence-system.d.ts.map +1 -1
- package/dist/guardrails/evidence-system.js +379 -83
- package/dist/guardrails/evidence-system.js.map +1 -1
- package/dist/guardrails/replay-ledger-io.d.ts +6 -0
- package/dist/guardrails/replay-ledger-io.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-io.js +42 -0
- package/dist/guardrails/replay-ledger-io.js.map +1 -0
- package/dist/guardrails/replay-ledger-lock-owner.d.ts +32 -0
- package/dist/guardrails/replay-ledger-lock-owner.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-lock-owner.js +138 -0
- package/dist/guardrails/replay-ledger-lock-owner.js.map +1 -0
- package/dist/guardrails/replay-ledger-lock.d.ts +24 -0
- package/dist/guardrails/replay-ledger-lock.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-lock.js +135 -0
- package/dist/guardrails/replay-ledger-lock.js.map +1 -0
- package/dist/guardrails/replay-ledger-mutation-gate.d.ts +24 -0
- package/dist/guardrails/replay-ledger-mutation-gate.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-mutation-gate.js +205 -0
- package/dist/guardrails/replay-ledger-mutation-gate.js.map +1 -0
- package/dist/guardrails/replay-ledger-quarantine.d.ts +2 -0
- package/dist/guardrails/replay-ledger-quarantine.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-quarantine.js +19 -0
- package/dist/guardrails/replay-ledger-quarantine.js.map +1 -0
- package/dist/guardrails/replay-ledger-store.d.ts +32 -0
- package/dist/guardrails/replay-ledger-store.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-store.js +211 -0
- package/dist/guardrails/replay-ledger-store.js.map +1 -0
- package/dist/guardrails/shell-command-name-glob.d.ts +3 -0
- package/dist/guardrails/shell-command-name-glob.d.ts.map +1 -0
- package/dist/guardrails/shell-command-name-glob.js +233 -0
- package/dist/guardrails/shell-command-name-glob.js.map +1 -0
- package/dist/guardrails/shell-command-option.d.ts +7 -0
- package/dist/guardrails/shell-command-option.d.ts.map +1 -0
- package/dist/guardrails/shell-command-option.js +24 -0
- package/dist/guardrails/shell-command-option.js.map +1 -0
- package/dist/guardrails/shell-command-tokenizer.d.ts +29 -0
- package/dist/guardrails/shell-command-tokenizer.d.ts.map +1 -0
- package/dist/guardrails/shell-command-tokenizer.js +145 -0
- package/dist/guardrails/shell-command-tokenizer.js.map +1 -0
- package/dist/guardrails/shell-command-wrapper.d.ts +18 -0
- package/dist/guardrails/shell-command-wrapper.d.ts.map +1 -0
- package/dist/guardrails/shell-command-wrapper.js +42 -0
- package/dist/guardrails/shell-command-wrapper.js.map +1 -0
- package/dist/guardrails/verified-executor.d.ts +65 -0
- package/dist/guardrails/verified-executor.d.ts.map +1 -0
- package/dist/guardrails/verified-executor.js +171 -0
- package/dist/guardrails/verified-executor.js.map +1 -0
- package/dist/guardrails/workspace-fingerprint.d.ts +23 -0
- package/dist/guardrails/workspace-fingerprint.d.ts.map +1 -0
- package/dist/guardrails/workspace-fingerprint.js +634 -0
- package/dist/guardrails/workspace-fingerprint.js.map +1 -0
- package/dist/index.d.ts +15 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +12 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/control-panel-layout.d.ts.map +1 -1
- package/dist/modes/interactive/components/control-panel-layout.js +1 -1
- package/dist/modes/interactive/components/control-panel-layout.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +1 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +59 -9
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +43 -2
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +23 -5
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +3 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/types/evidence.d.ts +215 -1
- package/dist/types/evidence.d.ts.map +1 -1
- package/dist/types/evidence.js.map +1 -1
- package/dist/verify-ci.d.ts +3 -0
- package/dist/verify-ci.d.ts.map +1 -0
- package/dist/verify-ci.js +30 -0
- package/dist/verify-ci.js.map +1 -0
- package/docs/compaction.md +44 -4
- package/docs/extensions.md +2 -0
- package/docs/providers.md +6 -0
- package/docs/sdk.md +238 -1
- package/docs/settings.md +67 -4
- package/docs/usage.md +38 -0
- package/examples/extensions/correctness-wall/README.md +6 -6
- package/examples/extensions/correctness-wall/index.ts +37 -11
- package/examples/extensions/custom-provider-anthropic/package-lock.json +5 -5
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +4 -4
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure, deterministic reserved-token budget arithmetic.
|
|
3
|
+
*
|
|
4
|
+
* This module is host-API-free: it relies only on plain ECMAScript value
|
|
5
|
+
* semantics. Invalid input and unsafe arithmetic that would lose integer
|
|
6
|
+
* precision both fail closed by throwing {@link ReservedTokenBudgetError}.
|
|
7
|
+
*
|
|
8
|
+
* The budget is one exact subtraction:
|
|
9
|
+
*
|
|
10
|
+
* effectiveBudget = modelContextWindow
|
|
11
|
+
* - systemPromptTokens
|
|
12
|
+
* - reservedOutputTokens
|
|
13
|
+
* - reservedToolResultTokens
|
|
14
|
+
* - safetyMarginTokens
|
|
15
|
+
* - imageReserveTokens
|
|
16
|
+
*
|
|
17
|
+
* The four reserve terms (output, tool result, safety margin, image reserve)
|
|
18
|
+
* are summed into `totalReserved` first; the final budget is the single
|
|
19
|
+
* subtraction `modelContextWindow - (systemPromptTokens + totalReserved)`.
|
|
20
|
+
*/
|
|
21
|
+
/**
|
|
22
|
+
* The complete, frozen set of supported tool-result classes. The literal union
|
|
23
|
+
* {@link ToolResultClass} is derived from this tuple. Frozen at runtime so the
|
|
24
|
+
* supported set cannot be mutated after import; the `as const` tuple type is
|
|
25
|
+
* preserved (freeze returns `Readonly` of the same tuple).
|
|
26
|
+
*/
|
|
27
|
+
export const TOOL_RESULT_CLASSES = Object.freeze(["text", "image", "large-output"]);
|
|
28
|
+
/**
|
|
29
|
+
* Fixed upper bound on the number of per-class requests accepted by
|
|
30
|
+
* {@link estimateToolResultReserve}. Request arrays longer than this cap are
|
|
31
|
+
* rejected before any iteration or arithmetic, keeping the estimator's loop
|
|
32
|
+
* bounded and predictable. A deliberately conservative constant.
|
|
33
|
+
*/
|
|
34
|
+
export const MAX_TOOL_RESULT_RESERVE_REQUESTS = 64;
|
|
35
|
+
const TOOL_RESULT_CLASS_SET = new Set(TOOL_RESULT_CLASSES);
|
|
36
|
+
const REQUEST_KEYS = ["class", "count", "tokensPerResult"];
|
|
37
|
+
const BUDGET_INPUT_KEYS = [
|
|
38
|
+
"modelContextWindow",
|
|
39
|
+
"systemPromptTokens",
|
|
40
|
+
"reservedOutputTokens",
|
|
41
|
+
"reservedToolResultTokens",
|
|
42
|
+
"safetyMarginTokens",
|
|
43
|
+
"imageReserveTokens",
|
|
44
|
+
];
|
|
45
|
+
export class ReservedTokenBudgetError extends Error {
|
|
46
|
+
constructor(message) {
|
|
47
|
+
super(message);
|
|
48
|
+
this.name = "ReservedTokenBudgetError";
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Validate that `value` is a plain data record with exactly the expected keys.
|
|
53
|
+
*
|
|
54
|
+
* A plain data record is a non-null, non-array object whose prototype is
|
|
55
|
+
* `Object.prototype` or `null` (null-prototype data objects are accepted) and
|
|
56
|
+
* whose own properties are all data properties (no getters/setters). This
|
|
57
|
+
* rejects arrays, class instances / other non-standard prototypes, accessor
|
|
58
|
+
* properties, and records with missing or unexpected keys — all via
|
|
59
|
+
* {@link ReservedTokenBudgetError} so callers fail closed consistently.
|
|
60
|
+
*/
|
|
61
|
+
function assertPlainDataRecord(value, label, expected) {
|
|
62
|
+
if (typeof value !== "object" || value === null) {
|
|
63
|
+
throw new ReservedTokenBudgetError(`${label} must be a non-null object`);
|
|
64
|
+
}
|
|
65
|
+
if (Array.isArray(value)) {
|
|
66
|
+
throw new ReservedTokenBudgetError(`${label} must be a plain object, not an array`);
|
|
67
|
+
}
|
|
68
|
+
const proto = Object.getPrototypeOf(value);
|
|
69
|
+
if (proto !== null && proto !== Object.prototype) {
|
|
70
|
+
throw new ReservedTokenBudgetError(`${label} must be a plain data record (unexpected prototype)`);
|
|
71
|
+
}
|
|
72
|
+
for (const key of Object.getOwnPropertyNames(value)) {
|
|
73
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
74
|
+
if (descriptor !== undefined && (typeof descriptor.get === "function" || typeof descriptor.set === "function")) {
|
|
75
|
+
throw new ReservedTokenBudgetError(`${label} must not have accessor property "${key}"`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const expectedSet = new Set(expected);
|
|
79
|
+
const actual = Object.keys(value);
|
|
80
|
+
for (const key of actual) {
|
|
81
|
+
if (!expectedSet.has(key)) {
|
|
82
|
+
throw new ReservedTokenBudgetError(`${label} has unexpected key "${key}"`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (actual.length !== expected.length) {
|
|
86
|
+
const missing = expected.filter((key) => !(key in value));
|
|
87
|
+
throw new ReservedTokenBudgetError(`${label} is missing required key(s): ${missing.join(", ")}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function assertNonNegativeSafeInteger(value, label) {
|
|
91
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
92
|
+
throw new ReservedTokenBudgetError(`${label} must be a finite number (got ${String(value)})`);
|
|
93
|
+
}
|
|
94
|
+
if (!Number.isSafeInteger(value)) {
|
|
95
|
+
throw new ReservedTokenBudgetError(`${label} must be a safe integer (got ${value})`);
|
|
96
|
+
}
|
|
97
|
+
if (value < 0) {
|
|
98
|
+
throw new ReservedTokenBudgetError(`${label} must be nonnegative (got ${value})`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** Add two nonnegative safe integers, failing closed before precision loss. */
|
|
102
|
+
function safeAdd(a, b, label) {
|
|
103
|
+
if (b > Number.MAX_SAFE_INTEGER - a) {
|
|
104
|
+
throw new ReservedTokenBudgetError(`arithmetic overflow while ${label}: ${a} + ${b}`);
|
|
105
|
+
}
|
|
106
|
+
return a + b;
|
|
107
|
+
}
|
|
108
|
+
/** Multiply two nonnegative safe integers, failing closed if the product is unsafe. */
|
|
109
|
+
function safeMultiply(a, b, label) {
|
|
110
|
+
if (a === 0 || b === 0) {
|
|
111
|
+
return 0;
|
|
112
|
+
}
|
|
113
|
+
const product = a * b;
|
|
114
|
+
if (!Number.isSafeInteger(product) || product / a !== b || product / b !== a) {
|
|
115
|
+
throw new ReservedTokenBudgetError(`arithmetic overflow while ${label}: ${a} * ${b}`);
|
|
116
|
+
}
|
|
117
|
+
return product;
|
|
118
|
+
}
|
|
119
|
+
function deepFreeze(value) {
|
|
120
|
+
if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
|
|
121
|
+
return value;
|
|
122
|
+
}
|
|
123
|
+
for (const child of Object.values(value)) {
|
|
124
|
+
deepFreeze(child);
|
|
125
|
+
}
|
|
126
|
+
return Object.freeze(value);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Estimate reserved tool-result tokens from bounded per-class requests using
|
|
130
|
+
* safe-integer arithmetic. Returns the exact total. Empty input yields 0.
|
|
131
|
+
* Throws {@link ReservedTokenBudgetError} on any invalid/overflowing input.
|
|
132
|
+
*/
|
|
133
|
+
export function estimateToolResultReserve(requests) {
|
|
134
|
+
if (!Array.isArray(requests)) {
|
|
135
|
+
throw new ReservedTokenBudgetError("requests must be an array");
|
|
136
|
+
}
|
|
137
|
+
if (requests.length > MAX_TOOL_RESULT_RESERVE_REQUESTS) {
|
|
138
|
+
throw new ReservedTokenBudgetError(`requests length ${requests.length} exceeds maximum ${MAX_TOOL_RESULT_RESERVE_REQUESTS}`);
|
|
139
|
+
}
|
|
140
|
+
let total = 0;
|
|
141
|
+
for (let i = 0; i < requests.length; i += 1) {
|
|
142
|
+
const request = requests[i];
|
|
143
|
+
const itemLabel = `requests[${i}]`;
|
|
144
|
+
assertPlainDataRecord(request, itemLabel, REQUEST_KEYS);
|
|
145
|
+
if (!TOOL_RESULT_CLASS_SET.has(request.class)) {
|
|
146
|
+
throw new ReservedTokenBudgetError(`${itemLabel}.class must be one of ${TOOL_RESULT_CLASSES.join(", ")} (got ${String(request.class)})`);
|
|
147
|
+
}
|
|
148
|
+
assertNonNegativeSafeInteger(request.count, `${itemLabel}.count`);
|
|
149
|
+
assertNonNegativeSafeInteger(request.tokensPerResult, `${itemLabel}.tokensPerResult`);
|
|
150
|
+
const perClassTotal = safeMultiply(request.count, request.tokensPerResult, `${itemLabel} count*tokensPerResult`);
|
|
151
|
+
total = safeAdd(total, perClassTotal, `summing tool result reserves at ${itemLabel}`);
|
|
152
|
+
}
|
|
153
|
+
return total;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Compute the effective reserved-token budget via a single exact subtraction.
|
|
157
|
+
* All inputs must be nonnegative safe integers. The returned object (and its
|
|
158
|
+
* nested `terms`) is deeply frozen and independent of the caller's input.
|
|
159
|
+
*/
|
|
160
|
+
export function computeReservedTokenBudget(input) {
|
|
161
|
+
assertPlainDataRecord(input, "input", BUDGET_INPUT_KEYS);
|
|
162
|
+
assertNonNegativeSafeInteger(input.modelContextWindow, "modelContextWindow");
|
|
163
|
+
assertNonNegativeSafeInteger(input.systemPromptTokens, "systemPromptTokens");
|
|
164
|
+
assertNonNegativeSafeInteger(input.reservedOutputTokens, "reservedOutputTokens");
|
|
165
|
+
assertNonNegativeSafeInteger(input.reservedToolResultTokens, "reservedToolResultTokens");
|
|
166
|
+
assertNonNegativeSafeInteger(input.safetyMarginTokens, "safetyMarginTokens");
|
|
167
|
+
assertNonNegativeSafeInteger(input.imageReserveTokens, "imageReserveTokens");
|
|
168
|
+
const totalReserved = safeAdd(safeAdd(safeAdd(input.reservedOutputTokens, input.reservedToolResultTokens, "output+toolResult"), input.safetyMarginTokens, "+safetyMargin"), input.imageReserveTokens, "+imageReserve");
|
|
169
|
+
const consumed = safeAdd(input.systemPromptTokens, totalReserved, "systemPrompt+totalReserved");
|
|
170
|
+
const rawEffective = input.modelContextWindow - consumed;
|
|
171
|
+
const overflow = rawEffective < 0;
|
|
172
|
+
const effectiveBudget = overflow ? 0 : rawEffective;
|
|
173
|
+
const terms = {
|
|
174
|
+
modelContextWindow: input.modelContextWindow,
|
|
175
|
+
systemPromptTokens: input.systemPromptTokens,
|
|
176
|
+
reservedOutputTokens: input.reservedOutputTokens,
|
|
177
|
+
reservedToolResultTokens: input.reservedToolResultTokens,
|
|
178
|
+
safetyMarginTokens: input.safetyMarginTokens,
|
|
179
|
+
imageReserveTokens: input.imageReserveTokens,
|
|
180
|
+
};
|
|
181
|
+
return deepFreeze({
|
|
182
|
+
terms,
|
|
183
|
+
totalReserved,
|
|
184
|
+
effectiveBudget,
|
|
185
|
+
overflow,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
//# sourceMappingURL=context-budget-reserved-tokens.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-budget-reserved-tokens.js","sourceRoot":"","sources":["../../src/core/context-budget-reserved-tokens.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;;;;GAKG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC,C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ACzD,MAAM,QAAQ,GAAG,YAAY,GAAG,CAAC,CAAC;IAClC,MAAM,eAAe,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC;IAEpD,MAAM,KAAK,GAA6B;QACvC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;KAC5C,CAAC;IACF,OAAO,UAAU,CAAC;QACjB,KAAK;QACL,aAAa;QACb,eAAe;QACf,QAAQ;KACR,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Pure, deterministic reserved-token budget arithmetic.\n *\n * This module is host-API-free: it relies only on plain ECMAScript value\n * semantics. Invalid input and unsafe arithmetic that would lose integer\n * precision both fail closed by throwing {@link ReservedTokenBudgetError}.\n *\n * The budget is one exact subtraction:\n *\n * effectiveBudget = modelContextWindow\n * - systemPromptTokens\n * - reservedOutputTokens\n * - reservedToolResultTokens\n * - safetyMarginTokens\n * - imageReserveTokens\n *\n * The four reserve terms (output, tool result, safety margin, image reserve)\n * are summed into `totalReserved` first; the final budget is the single\n * subtraction `modelContextWindow - (systemPromptTokens + totalReserved)`.\n */\n\n/**\n * The complete, frozen set of supported tool-result classes. The literal union\n * {@link ToolResultClass} is derived from this tuple. Frozen at runtime so the\n * supported set cannot be mutated after import; the `as const` tuple type is\n * preserved (freeze returns `Readonly` of the same tuple).\n */\nexport const TOOL_RESULT_CLASSES = Object.freeze([\"text\", \"image\", \"large-output\"] as const);\nexport type ToolResultClass = (typeof TOOL_RESULT_CLASSES)[number];\n\n/**\n * Fixed upper bound on the number of per-class requests accepted by\n * {@link estimateToolResultReserve}. Request arrays longer than this cap are\n * rejected before any iteration or arithmetic, keeping the estimator's loop\n * bounded and predictable. A deliberately conservative constant.\n */\nexport const MAX_TOOL_RESULT_RESERVE_REQUESTS = 64;\n\nconst TOOL_RESULT_CLASS_SET: ReadonlySet<string> = new Set(TOOL_RESULT_CLASSES);\n\nconst REQUEST_KEYS = [\"class\", \"count\", \"tokensPerResult\"] as const;\n\nconst BUDGET_INPUT_KEYS = [\n\t\"modelContextWindow\",\n\t\"systemPromptTokens\",\n\t\"reservedOutputTokens\",\n\t\"reservedToolResultTokens\",\n\t\"safetyMarginTokens\",\n\t\"imageReserveTokens\",\n] as const;\n\n/**\n * A bounded per-class reserve request for tool results.\n *\n * `count` results of `class`, each reserving `tokensPerResult` tokens.\n */\nexport interface ToolResultReserveRequest {\n\treadonly class: ToolResultClass;\n\treadonly count: number;\n\treadonly tokensPerResult: number;\n}\n\n/** Exact inputs to {@link computeReservedTokenBudget}. All terms are nonnegative safe integers. */\nexport interface ReservedTokenBudgetInput {\n\treadonly modelContextWindow: number;\n\treadonly systemPromptTokens: number;\n\t/** A single output-reserve term. No implicit ratio or default is applied. */\n\treadonly reservedOutputTokens: number;\n\t/**\n\t * Single term for reserved tool-result tokens. Pass\n\t * {@link estimateToolResultReserve} here. Empty/zero is allowed.\n\t */\n\treadonly reservedToolResultTokens: number;\n\treadonly safetyMarginTokens: number;\n\t/**\n\t * Reserve for image content. Distinct from the tool-result `image` class:\n\t * account image tokens in exactly one of these two places to avoid\n\t * double-accounting.\n\t */\n\treadonly imageReserveTokens: number;\n}\n\n/** A deeply frozen copy of the terms used in the budget computation. */\nexport interface ReservedTokenBudgetTerms {\n\treadonly modelContextWindow: number;\n\treadonly systemPromptTokens: number;\n\treadonly reservedOutputTokens: number;\n\treadonly reservedToolResultTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly imageReserveTokens: number;\n}\n\nexport interface ReservedTokenBudgetResult {\n\treadonly terms: ReservedTokenBudgetTerms;\n\t/** reservedOutput + reservedToolResult + safetyMargin + imageReserve (excludes systemPrompt and the window). */\n\treadonly totalReserved: number;\n\t/**\n\t * `modelContextWindow - systemPromptTokens - totalReserved`, clamped at 0.\n\t *\n\t * Exact-zero semantics: when the raw subtraction is exactly 0 the budget is\n\t * 0 and {@link overflow} is `false` — the window is exactly filled, not\n\t * exceeded. {@link overflow} is `true` only when the raw subtraction is\n\t * strictly negative (see {@link overflow}).\n\t */\n\treadonly effectiveBudget: number;\n\t/**\n\t * `true` only when the raw subtraction\n\t * `modelContextWindow - systemPromptTokens - totalReserved` is strictly\n\t * negative (reserves exceed the window). A raw result of exactly 0 is NOT\n\t * overflow: {@link effectiveBudget} is 0 but this flag stays `false`.\n\t */\n\treadonly overflow: boolean;\n}\n\nexport class ReservedTokenBudgetError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ReservedTokenBudgetError\";\n\t}\n}\n\n/**\n * Validate that `value` is a plain data record with exactly the expected keys.\n *\n * A plain data record is a non-null, non-array object whose prototype is\n * `Object.prototype` or `null` (null-prototype data objects are accepted) and\n * whose own properties are all data properties (no getters/setters). This\n * rejects arrays, class instances / other non-standard prototypes, accessor\n * properties, and records with missing or unexpected keys — all via\n * {@link ReservedTokenBudgetError} so callers fail closed consistently.\n */\nfunction assertPlainDataRecord(value: unknown, label: string, expected: readonly string[]): void {\n\tif (typeof value !== \"object\" || value === null) {\n\t\tthrow new ReservedTokenBudgetError(`${label} must be a non-null object`);\n\t}\n\tif (Array.isArray(value)) {\n\t\tthrow new ReservedTokenBudgetError(`${label} must be a plain object, not an array`);\n\t}\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== null && proto !== Object.prototype) {\n\t\tthrow new ReservedTokenBudgetError(`${label} must be a plain data record (unexpected prototype)`);\n\t}\n\tfor (const key of Object.getOwnPropertyNames(value)) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (descriptor !== undefined && (typeof descriptor.get === \"function\" || typeof descriptor.set === \"function\")) {\n\t\t\tthrow new ReservedTokenBudgetError(`${label} must not have accessor property \"${key}\"`);\n\t\t}\n\t}\n\tconst expectedSet = new Set(expected);\n\tconst actual = Object.keys(value);\n\tfor (const key of actual) {\n\t\tif (!expectedSet.has(key)) {\n\t\t\tthrow new ReservedTokenBudgetError(`${label} has unexpected key \"${key}\"`);\n\t\t}\n\t}\n\tif (actual.length !== expected.length) {\n\t\tconst missing = expected.filter((key) => !(key in value));\n\t\tthrow new ReservedTokenBudgetError(`${label} is missing required key(s): ${missing.join(\", \")}`);\n\t}\n}\n\nfunction assertNonNegativeSafeInteger(value: unknown, label: string): void {\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) {\n\t\tthrow new ReservedTokenBudgetError(`${label} must be a finite number (got ${String(value)})`);\n\t}\n\tif (!Number.isSafeInteger(value)) {\n\t\tthrow new ReservedTokenBudgetError(`${label} must be a safe integer (got ${value})`);\n\t}\n\tif (value < 0) {\n\t\tthrow new ReservedTokenBudgetError(`${label} must be nonnegative (got ${value})`);\n\t}\n}\n\n/** Add two nonnegative safe integers, failing closed before precision loss. */\nfunction safeAdd(a: number, b: number, label: string): number {\n\tif (b > Number.MAX_SAFE_INTEGER - a) {\n\t\tthrow new ReservedTokenBudgetError(`arithmetic overflow while ${label}: ${a} + ${b}`);\n\t}\n\treturn a + b;\n}\n\n/** Multiply two nonnegative safe integers, failing closed if the product is unsafe. */\nfunction safeMultiply(a: number, b: number, label: string): number {\n\tif (a === 0 || b === 0) {\n\t\treturn 0;\n\t}\n\tconst product = a * b;\n\tif (!Number.isSafeInteger(product) || product / a !== b || product / b !== a) {\n\t\tthrow new ReservedTokenBudgetError(`arithmetic overflow while ${label}: ${a} * ${b}`);\n\t}\n\treturn product;\n}\n\nfunction deepFreeze<T>(value: T): T {\n\tif (typeof value !== \"object\" || value === null || Object.isFrozen(value)) {\n\t\treturn value;\n\t}\n\tfor (const child of Object.values(value)) {\n\t\tdeepFreeze(child);\n\t}\n\treturn Object.freeze(value);\n}\n\n/**\n * Estimate reserved tool-result tokens from bounded per-class requests using\n * safe-integer arithmetic. Returns the exact total. Empty input yields 0.\n * Throws {@link ReservedTokenBudgetError} on any invalid/overflowing input.\n */\nexport function estimateToolResultReserve(requests: readonly ToolResultReserveRequest[]): number {\n\tif (!Array.isArray(requests)) {\n\t\tthrow new ReservedTokenBudgetError(\"requests must be an array\");\n\t}\n\tif (requests.length > MAX_TOOL_RESULT_RESERVE_REQUESTS) {\n\t\tthrow new ReservedTokenBudgetError(\n\t\t\t`requests length ${requests.length} exceeds maximum ${MAX_TOOL_RESULT_RESERVE_REQUESTS}`,\n\t\t);\n\t}\n\tlet total = 0;\n\tfor (let i = 0; i < requests.length; i += 1) {\n\t\tconst request = requests[i];\n\t\tconst itemLabel = `requests[${i}]`;\n\t\tassertPlainDataRecord(request, itemLabel, REQUEST_KEYS);\n\t\tif (!TOOL_RESULT_CLASS_SET.has(request.class)) {\n\t\t\tthrow new ReservedTokenBudgetError(\n\t\t\t\t`${itemLabel}.class must be one of ${TOOL_RESULT_CLASSES.join(\", \")} (got ${String(request.class)})`,\n\t\t\t);\n\t\t}\n\t\tassertNonNegativeSafeInteger(request.count, `${itemLabel}.count`);\n\t\tassertNonNegativeSafeInteger(request.tokensPerResult, `${itemLabel}.tokensPerResult`);\n\t\tconst perClassTotal = safeMultiply(request.count, request.tokensPerResult, `${itemLabel} count*tokensPerResult`);\n\t\ttotal = safeAdd(total, perClassTotal, `summing tool result reserves at ${itemLabel}`);\n\t}\n\treturn total;\n}\n\n/**\n * Compute the effective reserved-token budget via a single exact subtraction.\n * All inputs must be nonnegative safe integers. The returned object (and its\n * nested `terms`) is deeply frozen and independent of the caller's input.\n */\nexport function computeReservedTokenBudget(input: ReservedTokenBudgetInput): ReservedTokenBudgetResult {\n\tassertPlainDataRecord(input, \"input\", BUDGET_INPUT_KEYS);\n\tassertNonNegativeSafeInteger(input.modelContextWindow, \"modelContextWindow\");\n\tassertNonNegativeSafeInteger(input.systemPromptTokens, \"systemPromptTokens\");\n\tassertNonNegativeSafeInteger(input.reservedOutputTokens, \"reservedOutputTokens\");\n\tassertNonNegativeSafeInteger(input.reservedToolResultTokens, \"reservedToolResultTokens\");\n\tassertNonNegativeSafeInteger(input.safetyMarginTokens, \"safetyMarginTokens\");\n\tassertNonNegativeSafeInteger(input.imageReserveTokens, \"imageReserveTokens\");\n\n\tconst totalReserved = safeAdd(\n\t\tsafeAdd(\n\t\t\tsafeAdd(input.reservedOutputTokens, input.reservedToolResultTokens, \"output+toolResult\"),\n\t\t\tinput.safetyMarginTokens,\n\t\t\t\"+safetyMargin\",\n\t\t),\n\t\tinput.imageReserveTokens,\n\t\t\"+imageReserve\",\n\t);\n\tconst consumed = safeAdd(input.systemPromptTokens, totalReserved, \"systemPrompt+totalReserved\");\n\tconst rawEffective = input.modelContextWindow - consumed;\n\tconst overflow = rawEffective < 0;\n\tconst effectiveBudget = overflow ? 0 : rawEffective;\n\n\tconst terms: ReservedTokenBudgetTerms = {\n\t\tmodelContextWindow: input.modelContextWindow,\n\t\tsystemPromptTokens: input.systemPromptTokens,\n\t\treservedOutputTokens: input.reservedOutputTokens,\n\t\treservedToolResultTokens: input.reservedToolResultTokens,\n\t\tsafetyMarginTokens: input.safetyMarginTokens,\n\t\timageReserveTokens: input.imageReserveTokens,\n\t};\n\treturn deepFreeze({\n\t\tterms,\n\t\ttotalReserved,\n\t\teffectiveBudget,\n\t\toverflow,\n\t});\n}\n"]}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-safe, pure context-cache invalidation snapshot helper.
|
|
3
|
+
*
|
|
4
|
+
* Every public function is side-effect free and depends only on
|
|
5
|
+
* platform-agnostic primitives. Returned snapshots are always
|
|
6
|
+
* independently deep-frozen copies of the caller-supplied data, so
|
|
7
|
+
* callers cannot mutate cached state through retained references.
|
|
8
|
+
*
|
|
9
|
+
* Snapshots are cache-key material for invalidation tracking, not an
|
|
10
|
+
* authorization or authentication primitive.
|
|
11
|
+
*
|
|
12
|
+
* Schema: context-cache-invalidation-v1.
|
|
13
|
+
*/
|
|
14
|
+
export declare const CONTEXT_CACHE_INVALIDATION_SCHEMA_VERSION: "context-cache-invalidation-v1";
|
|
15
|
+
export declare const CONTEXT_CACHE_INVALIDATION_SAFE_ID_MAX_LENGTH = 256;
|
|
16
|
+
/** Event counters tracked by an invalidation snapshot. */
|
|
17
|
+
export interface ContextCacheInvalidationCounters {
|
|
18
|
+
readonly transcriptRepair: number;
|
|
19
|
+
readonly toolResultDisposition: number;
|
|
20
|
+
readonly evidenceReceipt: number;
|
|
21
|
+
readonly userSteering: number;
|
|
22
|
+
readonly settings: number;
|
|
23
|
+
}
|
|
24
|
+
/** Immutable schema-v1 invalidation snapshot. */
|
|
25
|
+
export interface ContextCacheInvalidationSnapshot {
|
|
26
|
+
readonly schemaVersion: typeof CONTEXT_CACHE_INVALIDATION_SCHEMA_VERSION;
|
|
27
|
+
readonly forkId: string;
|
|
28
|
+
readonly globalEpoch: number;
|
|
29
|
+
readonly counters: ContextCacheInvalidationCounters;
|
|
30
|
+
readonly worktreeFingerprint: string;
|
|
31
|
+
readonly activeModelId: string;
|
|
32
|
+
readonly compactionModelId: string;
|
|
33
|
+
}
|
|
34
|
+
/** Constructor input for a fresh snapshot. Counters and epoch default to 0. */
|
|
35
|
+
export interface ContextCacheInvalidationSnapshotInit {
|
|
36
|
+
readonly forkId: string;
|
|
37
|
+
readonly worktreeFingerprint: string;
|
|
38
|
+
readonly activeModelId: string;
|
|
39
|
+
readonly compactionModelId: string;
|
|
40
|
+
readonly globalEpoch?: number;
|
|
41
|
+
readonly transcriptRepair?: number;
|
|
42
|
+
readonly toolResultDisposition?: number;
|
|
43
|
+
readonly evidenceReceipt?: number;
|
|
44
|
+
readonly userSteering?: number;
|
|
45
|
+
readonly settings?: number;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Strict union covering all eight invalidation events. The five counter
|
|
49
|
+
* events increment their counter; the three identity events set a value.
|
|
50
|
+
*/
|
|
51
|
+
export type ContextCacheInvalidationEvent = {
|
|
52
|
+
readonly type: "transcriptRepair";
|
|
53
|
+
} | {
|
|
54
|
+
readonly type: "toolResultDisposition";
|
|
55
|
+
} | {
|
|
56
|
+
readonly type: "evidenceReceipt";
|
|
57
|
+
} | {
|
|
58
|
+
readonly type: "userSteering";
|
|
59
|
+
} | {
|
|
60
|
+
readonly type: "settings";
|
|
61
|
+
} | {
|
|
62
|
+
readonly type: "worktreeFingerprint";
|
|
63
|
+
readonly value: string;
|
|
64
|
+
} | {
|
|
65
|
+
readonly type: "activeModelId";
|
|
66
|
+
readonly value: string;
|
|
67
|
+
} | {
|
|
68
|
+
readonly type: "compactionModelId";
|
|
69
|
+
readonly value: string;
|
|
70
|
+
};
|
|
71
|
+
export type ContextCacheInvalidationStatus = "applied" | "unchanged" | "overflow";
|
|
72
|
+
export interface ContextCacheInvalidationResult {
|
|
73
|
+
readonly status: ContextCacheInvalidationStatus;
|
|
74
|
+
readonly snapshot: ContextCacheInvalidationSnapshot;
|
|
75
|
+
}
|
|
76
|
+
export type ContextCacheMergeStatus = "equal" | "dominant" | "divergent";
|
|
77
|
+
export type ContextCacheMergeResult = {
|
|
78
|
+
readonly status: "equal";
|
|
79
|
+
readonly snapshot: ContextCacheInvalidationSnapshot;
|
|
80
|
+
} | {
|
|
81
|
+
readonly status: "dominant";
|
|
82
|
+
readonly snapshot: ContextCacheInvalidationSnapshot;
|
|
83
|
+
} | {
|
|
84
|
+
readonly status: "divergent";
|
|
85
|
+
readonly left: ContextCacheInvalidationSnapshot;
|
|
86
|
+
readonly right: ContextCacheInvalidationSnapshot;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Strictly validate that {@link input} is a structurally correct snapshot.
|
|
90
|
+
* Rejects extra keys, missing keys, malformed counters, unsafe integers,
|
|
91
|
+
* and control/credential-unsafe identifier strings. Does not require the
|
|
92
|
+
* object to be frozen.
|
|
93
|
+
*/
|
|
94
|
+
export declare function validateContextCacheInvalidationSnapshot(input: unknown): asserts input is ContextCacheInvalidationSnapshot;
|
|
95
|
+
/** Non-throwing variant of {@link validateContextCacheInvalidationSnapshot}. */
|
|
96
|
+
export declare function isContextCacheInvalidationSnapshot(input: unknown): input is ContextCacheInvalidationSnapshot;
|
|
97
|
+
/** Build a validated, deep-frozen initial snapshot. */
|
|
98
|
+
export declare function createContextCacheInvalidationSnapshot(init: ContextCacheInvalidationSnapshotInit): ContextCacheInvalidationSnapshot;
|
|
99
|
+
/**
|
|
100
|
+
* Apply a single invalidation event. Increments the global epoch and the
|
|
101
|
+
* relevant counter, or sets an identity. A same-value identity set is a
|
|
102
|
+
* no-op and returns {@link ContextCacheInvalidationStatus.unchanged} without
|
|
103
|
+
* an epoch bump. Any counter or epoch overflow returns
|
|
104
|
+
* {@link ContextCacheInvalidationStatus.overflow} with the snapshot unchanged
|
|
105
|
+
* and never wraps.
|
|
106
|
+
*/
|
|
107
|
+
export declare function applyContextCacheInvalidation(current: ContextCacheInvalidationSnapshot, event: ContextCacheInvalidationEvent): ContextCacheInvalidationResult;
|
|
108
|
+
/**
|
|
109
|
+
* Fork a snapshot: keep all event counters and identity values, change the
|
|
110
|
+
* fork id, and reset the global epoch to 0. The caller supplies the new fork
|
|
111
|
+
* id. Rejects an id equal to the current fork id.
|
|
112
|
+
*/
|
|
113
|
+
export declare function forkContextCacheSnapshot(current: ContextCacheInvalidationSnapshot, nextForkId: string): ContextCacheInvalidationSnapshot;
|
|
114
|
+
/**
|
|
115
|
+
* Fail-closed merge of two snapshots.
|
|
116
|
+
*
|
|
117
|
+
* - Different fork ids, or two snapshots that are not on a shared linear
|
|
118
|
+
* history, yield {@link ContextCacheMergeStatus.divergent}. Disjoint
|
|
119
|
+
* changes are never max-merged.
|
|
120
|
+
* - Structurally equal snapshots yield {@link ContextCacheMergeStatus.equal}.
|
|
121
|
+
* - When one snapshot componentwise-dominates the other (epoch and every
|
|
122
|
+
* counter greater-or-equal, and all identity values equal), the dominant
|
|
123
|
+
* snapshot is chosen via {@link ContextCacheMergeStatus.dominant}.
|
|
124
|
+
*/
|
|
125
|
+
export declare function mergeContextCacheSnapshots(a: ContextCacheInvalidationSnapshot, b: ContextCacheInvalidationSnapshot): ContextCacheMergeResult;
|
|
126
|
+
/**
|
|
127
|
+
* Canonical, fixed-order JSON serialization of a snapshot, suitable as
|
|
128
|
+
* future cache-key material. The field order is fixed and every distinct
|
|
129
|
+
* field participates, so any distinct field change alters the result.
|
|
130
|
+
* Returns a deterministic string with no hash claim.
|
|
131
|
+
*/
|
|
132
|
+
export declare function serializeContextCacheSnapshot(snapshot: ContextCacheInvalidationSnapshot): string;
|
|
133
|
+
//# sourceMappingURL=context-budget-v2-cache-invalidation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-budget-v2-cache-invalidation.d.ts","sourceRoot":"","sources":["../../src/core/context-budget-v2-cache-invalidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,eAAO,MAAM,yCAAyC,iCAA2C,CAAC;AAClG,eAAO,MAAM,6CAA6C,MAAM,CAAC;AAEjE,0DAA0D;AAC1D,MAAM,WAAW,gCAAgC;IAChD,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC;IACvC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC1B;AAED,iDAAiD;AACjD,MAAM,WAAW,gCAAgC;IAChD,QAAQ,CAAC,aAAa,EAAE,OAAO,yCAAyC,CAAC;IACzE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,gCAAgC,CAAC;IACpD,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,QAAQ,CAAC,a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EAAE,gCAAgC,EACnC,CAAC,EAAE,gCAAgC,GACjC,uBAAuB,CAkBzB;AAED;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,QAAQ,EAAE,gCAAgC,GAAG,MAAM,CAiBhG","sourcesContent":["/**\n * Browser-safe, pure context-cache invalidation snapshot helper.\n *\n * Every public function is side-effect free and depends only on\n * platform-agnostic primitives. Returned snapshots are always\n * independently deep-frozen copies of the caller-supplied data, so\n * callers cannot mutate cached state through retained references.\n *\n * Snapshots are cache-key material for invalidation tracking, not an\n * authorization or authentication primitive.\n *\n * Schema: context-cache-invalidation-v1.\n */\n\nexport const CONTEXT_CACHE_INVALIDATION_SCHEMA_VERSION = \"context-cache-invalidation-v1\" as const;\nexport const CONTEXT_CACHE_INVALIDATION_SAFE_ID_MAX_LENGTH = 256;\n\n/** Event counters tracked by an invalidation snapshot. */\nexport interface ContextCacheInvalidationCounters {\n\treadonly transcriptRepair: number;\n\treadonly toolResultDisposition: number;\n\treadonly evidenceReceipt: number;\n\treadonly userSteering: number;\n\treadonly settings: number;\n}\n\n/** Immutable schema-v1 invalidation snapshot. */\nexport interface ContextCacheInvalidationSnapshot {\n\treadonly schemaVersion: typeof CONTEXT_CACHE_INVALIDATION_SCHEMA_VERSION;\n\treadonly forkId: string;\n\treadonly globalEpoch: number;\n\treadonly counters: ContextCacheInvalidationCounters;\n\treadonly worktreeFingerprint: string;\n\treadonly activeModelId: string;\n\treadonly compactionModelId: string;\n}\n\n/** Constructor input for a fresh snapshot. Counters and epoch default to 0. */\nexport interface ContextCacheInvalidationSnapshotInit {\n\treadonly forkId: string;\n\treadonly worktreeFingerprint: string;\n\treadonly activeModelId: string;\n\treadonly compactionModelId: string;\n\treadonly globalEpoch?: number;\n\treadonly transcriptRepair?: number;\n\treadonly toolResultDisposition?: number;\n\treadonly evidenceReceipt?: number;\n\treadonly userSteering?: number;\n\treadonly settings?: number;\n}\n\n/**\n * Strict union covering all eight invalidation events. The five counter\n * events increment their counter; the three identity events set a value.\n */\nexport type ContextCacheInvalidationEvent =\n\t| { readonly type: \"transcriptRepair\" }\n\t| { readonly type: \"toolResultDisposition\" }\n\t| { readonly type: \"evidenceReceipt\" }\n\t| { readonly type: \"userSteering\" }\n\t| { readonly type: \"settings\" }\n\t| { readonly type: \"worktreeFingerprint\"; readonly value: string }\n\t| { readonly type: \"activeModelId\"; readonly value: string }\n\t| { readonly type: \"compactionModelId\"; readonly value: string };\n\nexport type ContextCacheInvalidationStatus = \"applied\" | \"unchanged\" | \"overflow\";\n\nexport interface ContextCacheInvalidationResult {\n\treadonly status: ContextCacheInvalidationStatus;\n\treadonly snapshot: ContextCacheInvalidationSnapshot;\n}\n\nexport type ContextCacheMergeStatus = \"equal\" | \"dominant\" | \"divergent\";\n\nexport type ContextCacheMergeResult =\n\t| { readonly status: \"equal\"; readonly snapshot: ContextCacheInvalidationSnapshot }\n\t| { readonly status: \"dominant\"; readonly snapshot: ContextCacheInvalidationSnapshot }\n\t| {\n\t\t\treadonly status: \"divergent\";\n\t\t\treadonly left: ContextCacheInvalidationSnapshot;\n\t\t\treadonly right: ContextCacheInvalidationSnapshot;\n\t };\n\ntype CounterKey = \"transcriptRepair\" | \"toolResultDisposition\" | \"evidenceReceipt\" | \"userSteering\" | \"settings\";\n\ntype IdentityKey = \"worktreeFingerprint\" | \"activeModelId\" | \"compactionModelId\";\n\nconst MAX_REPRESENTABLE = Number.MAX_SAFE_INTEGER;\nconst SAFE_ID_PATTERN = /^[\\w.\\-:+]+$/u;\n\n/**\n * High-confidence credential markers, checked in addition to the\n * safe-character gate. A value already consists only of safe characters\n * before it is tested here. Each pattern is anchored to the whole string\n * to keep the false-positive rate low; identifiers and fingerprints in\n * this domain never legitimately take these shapes.\n */\nconst CREDENTIAL_MARKERS: ReadonlyArray<RegExp> = [\n\t/^sk-[A-Za-z0-9_-]{8,}$/i, // OpenAI / generic \"sk-\" secret keys\n\t/^gh[pousr]_[A-Za-z0-9]{16,}$/i, // GitHub classic tokens (ghp_ gho_ ghu_ ghs_ ghr_)\n\t/^github_pat_[A-Za-z0-9_]{20,}$/i, // GitHub fine-grained PATs\n\t/^xox[pabrse]-[A-Za-z0-9-]{10,}$/i, // Slack tokens (xoxp xoxb xoxa xoxs xoxr xoxe)\n\t/^AKIA[0-9A-Z]{16}$/, // AWS access key id (20 chars, uppercase)\n\t/^eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}$/, // JWT (three base64url segments)\n\t/^bearer$/i, // literal Bearer token marker\n];\n\nfunction looksLikeCredential(value: string): boolean {\n\tfor (const marker of CREDENTIAL_MARKERS) {\n\t\tif (marker.test(value)) return true;\n\t}\n\treturn false;\n}\n\nconst TOP_LEVEL_KEYS: ReadonlySet<string> = new Set([\n\t\"schemaVersion\",\n\t\"forkId\",\n\t\"globalEpoch\",\n\t\"counters\",\n\t\"worktreeFingerprint\",\n\t\"activeModelId\",\n\t\"compactionModelId\",\n]);\n\nconst COUNTER_KEYS: ReadonlySet<string> = new Set([\n\t\"transcriptRepair\",\n\t\"toolResultDisposition\",\n\t\"evidenceReceipt\",\n\t\"userSteering\",\n\t\"settings\",\n]);\n\nfunction fail(reason: string): never {\n\tthrow new Error(`context-cache-invalidation: ${reason}`);\n}\n\nfunction assertSafeId(value: unknown, field: string): asserts value is string {\n\tif (typeof value !== \"string\") fail(`${field} must be a string`);\n\tif (value.length === 0) fail(`${field} must not be empty`);\n\tif (value.length > CONTEXT_CACHE_INVALIDATION_SAFE_ID_MAX_LENGTH) {\n\t\tfail(`${field} exceeds ${CONTEXT_CACHE_INVALIDATION_SAFE_ID_MAX_LENGTH} characters`);\n\t}\n\tif (!SAFE_ID_PATTERN.test(value)) fail(`${field} contains unsafe characters`);\n\tif (looksLikeCredential(value)) fail(`${field} looks like a credential and was rejected`);\n}\n\nfunction assertNonNegativeSafeInt(value: unknown, field: string): asserts value is number {\n\tif (typeof value !== \"number\") fail(`${field} must be a number`);\n\tif (!Number.isFinite(value)) fail(`${field} must be finite`);\n\tif (!Number.isInteger(value)) fail(`${field} must be an integer`);\n\tif (value < 0) fail(`${field} must be nonnegative`);\n\tif (!Number.isSafeInteger(value)) fail(`${field} must be a safe integer`);\n}\n\nfunction assertExactKeys(record: Record<string, unknown>, allowed: ReadonlySet<string>, scope: string): void {\n\tconst keys = Object.keys(record);\n\tif (keys.length !== allowed.size) fail(`${scope} has unexpected keys`);\n\tfor (const key of keys) {\n\t\tif (!allowed.has(key)) fail(`${scope} has unknown key \"${key}\"`);\n\t}\n}\n\n/** Reject non-plain inputs: null, arrays, primitives, and class instances. */\nfunction assertPlainObject(value: unknown, scope: string): asserts value is Record<string, unknown> {\n\tif (value === null || typeof value !== \"object\") fail(`${scope} must be a plain object`);\n\tif (Array.isArray(value)) fail(`${scope} must be a plain object`);\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== null && proto !== Object.prototype) fail(`${scope} must be a plain object`);\n}\n\n/** Reject getter/setter accessors, whose reads are not stable. */\nfunction assertNoAccessors(record: object, scope: string): void {\n\tfor (const key of Object.getOwnPropertyNames(record)) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(record, key);\n\t\tif (desc !== undefined && (typeof desc.get === \"function\" || typeof desc.set === \"function\")) {\n\t\t\tfail(`${scope} must not define accessors`);\n\t\t}\n\t}\n}\n\nconst INIT_REQUIRED_KEYS: ReadonlySet<string> = new Set([\n\t\"forkId\",\n\t\"worktreeFingerprint\",\n\t\"activeModelId\",\n\t\"compactionModelId\",\n]);\n\nconst INIT_OPTIONAL_KEYS: ReadonlySet<string> = new Set([\n\t\"globalEpoch\",\n\t\"transcriptRepair\",\n\t\"toolResultDisposition\",\n\t\"evidenceReceipt\",\n\t\"userSteering\",\n\t\"settings\",\n]);\n\nconst INIT_ALLOWED_KEYS: ReadonlySet<string> = new Set([...INIT_REQUIRED_KEYS, ...INIT_OPTIONAL_KEYS]);\n\n/**\n * Strictly validate a snapshot constructor input: a plain data object with\n * exactly the required identity/fork keys plus optional counters/epoch, and\n * no accessor properties. Rejects null, arrays, class instances, unknown\n * keys, and getters/setters with a stable error.\n */\nfunction assertInitShape(input: unknown): asserts input is ContextCacheInvalidationSnapshotInit {\n\tassertPlainObject(input, \"init\");\n\tassertNoAccessors(input, \"init\");\n\tfor (const key of Object.keys(input)) {\n\t\tif (!INIT_ALLOWED_KEYS.has(key)) fail(`init has unknown key \"${key}\"`);\n\t}\n\tfor (const required of INIT_REQUIRED_KEYS) {\n\t\tif (!Object.hasOwn(input, required)) {\n\t\t\tfail(`init is missing required key \"${required}\"`);\n\t\t}\n\t}\n}\n\nconst COUNTER_EVENT_TYPES: ReadonlySet<string> = new Set([\n\t\"transcriptRepair\",\n\t\"toolResultDisposition\",\n\t\"evidenceReceipt\",\n\t\"userSteering\",\n\t\"settings\",\n]);\n\nconst IDENTITY_EVENT_TYPES: ReadonlySet<string> = new Set([\n\t\"worktreeFingerprint\",\n\t\"activeModelId\",\n\t\"compactionModelId\",\n]);\n\nconst COUNTER_EVENT_KEYS: ReadonlySet<string> = new Set([\"type\"]);\nconst IDENTITY_EVENT_KEYS: ReadonlySet<string> = new Set([\"type\", \"value\"]);\n\n/**\n * Strictly validate a runtime invalidation event before dispatch. The event\n * must be a plain data object carrying exactly the keys its discriminant\n * allows (counter events: `{ type }`; identity events: `{ type, value }`),\n * a known `type` string, and (for identity events) a safe value. Forged or\n * malformed events always throw here and can never fall through to an\n * undefined result.\n */\nfunction validateEvent(input: unknown): asserts input is ContextCacheInvalidationEvent {\n\tassertPlainObject(input, \"event\");\n\tassertNoAccessors(input, \"event\");\n\tconst type = input.type;\n\tif (type === undefined) fail(\"event is missing type\");\n\tif (typeof type !== \"string\") fail(\"event type must be a string\");\n\tif (COUNTER_EVENT_TYPES.has(type)) {\n\t\tassertExactKeys(input, COUNTER_EVENT_KEYS, \"event\");\n\t\treturn;\n\t}\n\tif (IDENTITY_EVENT_TYPES.has(type)) {\n\t\tassertExactKeys(input, IDENTITY_EVENT_KEYS, \"event\");\n\t\tassertSafeId(input.value, type);\n\t\treturn;\n\t}\n\tfail(`event type \"${type}\" is unknown`);\n}\n\n/**\n * Strictly validate that {@link input} is a structurally correct snapshot.\n * Rejects extra keys, missing keys, malformed counters, unsafe integers,\n * and control/credential-unsafe identifier strings. Does not require the\n * object to be frozen.\n */\nexport function validateContextCacheInvalidationSnapshot(\n\tinput: unknown,\n): asserts input is ContextCacheInvalidationSnapshot {\n\tif (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n\t\tfail(\"snapshot must be a plain object\");\n\t}\n\tconst obj = input as Record<string, unknown>;\n\tassertExactKeys(obj, TOP_LEVEL_KEYS, \"snapshot\");\n\tif (obj.schemaVersion !== CONTEXT_CACHE_INVALIDATION_SCHEMA_VERSION) {\n\t\tfail(`schemaVersion must be ${CONTEXT_CACHE_INVALIDATION_SCHEMA_VERSION}`);\n\t}\n\tassertSafeId(obj.forkId, \"forkId\");\n\tassertNonNegativeSafeInt(obj.globalEpoch, \"globalEpoch\");\n\tif (obj.counters === null || typeof obj.counters !== \"object\" || Array.isArray(obj.counters)) {\n\t\tfail(\"counters must be a plain object\");\n\t}\n\tconst counters = obj.counters as Record<string, unknown>;\n\tassertExactKeys(counters, COUNTER_KEYS, \"counters\");\n\tassertNonNegativeSafeInt(counters.transcriptRepair, \"counters.transcriptRepair\");\n\tassertNonNegativeSafeInt(counters.toolResultDisposition, \"counters.toolResultDisposition\");\n\tassertNonNegativeSafeInt(counters.evidenceReceipt, \"counters.evidenceReceipt\");\n\tassertNonNegativeSafeInt(counters.userSteering, \"counters.userSteering\");\n\tassertNonNegativeSafeInt(counters.settings, \"counters.settings\");\n\tassertSafeId(obj.worktreeFingerprint, \"worktreeFingerprint\");\n\tassertSafeId(obj.activeModelId, \"activeModelId\");\n\tassertSafeId(obj.compactionModelId, \"compactionModelId\");\n}\n\n/** Non-throwing variant of {@link validateContextCacheInvalidationSnapshot}. */\nexport function isContextCacheInvalidationSnapshot(input: unknown): input is ContextCacheInvalidationSnapshot {\n\ttry {\n\t\tvalidateContextCacheInvalidationSnapshot(input);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\ninterface SnapshotBuilder {\n\tschemaVersion: typeof CONTEXT_CACHE_INVALIDATION_SCHEMA_VERSION;\n\tforkId: string;\n\tglobalEpoch: number;\n\tcounters: ContextCacheInvalidationCounters;\n\tworktreeFingerprint: string;\n\tactiveModelId: string;\n\tcompactionModelId: string;\n}\n\nfunction freezeSnapshot(builder: SnapshotBuilder): ContextCacheInvalidationSnapshot {\n\tObject.freeze(builder.counters);\n\treturn Object.freeze(builder) as ContextCacheInvalidationSnapshot;\n}\n\nfunction copyCounters(counters: ContextCacheInvalidationCounters): Record<CounterKey, number> {\n\treturn {\n\t\ttranscriptRepair: counters.transcriptRepair,\n\t\ttoolResultDisposition: counters.toolResultDisposition,\n\t\tevidenceReceipt: counters.evidenceReceipt,\n\t\tuserSteering: counters.userSteering,\n\t\tsettings: counters.settings,\n\t};\n}\n\nfunction cloneAndFreeze(snapshot: ContextCacheInvalidationSnapshot): ContextCacheInvalidationSnapshot {\n\treturn freezeSnapshot({\n\t\tschemaVersion: snapshot.schemaVersion,\n\t\tforkId: snapshot.forkId,\n\t\tglobalEpoch: snapshot.globalEpoch,\n\t\tcounters: copyCounters(snapshot.counters),\n\t\tworktreeFingerprint: snapshot.worktreeFingerprint,\n\t\tactiveModelId: snapshot.activeModelId,\n\t\tcompactionModelId: snapshot.compactionModelId,\n\t});\n}\n\nfunction resolveOptionalCounter(value: number | undefined, field: string): number {\n\tif (value === undefined) return 0;\n\tassertNonNegativeSafeInt(value, field);\n\treturn value;\n}\n\n/** Build a validated, deep-frozen initial snapshot. */\nexport function createContextCacheInvalidationSnapshot(\n\tinit: ContextCacheInvalidationSnapshotInit,\n): ContextCacheInvalidationSnapshot {\n\tassertInitShape(init);\n\tassertSafeId(init.forkId, \"forkId\");\n\tassertSafeId(init.worktreeFingerprint, \"worktreeFingerprint\");\n\tassertSafeId(init.activeModelId, \"activeModelId\");\n\tassertSafeId(init.compactionModelId, \"compactionModelId\");\n\tconst globalEpoch = init.globalEpoch ?? 0;\n\tassertNonNegativeSafeInt(globalEpoch, \"globalEpoch\");\n\treturn freezeSnapshot({\n\t\tschemaVersion: CONTEXT_CACHE_INVALIDATION_SCHEMA_VERSION,\n\t\tforkId: init.forkId,\n\t\tglobalEpoch,\n\t\tcounters: {\n\t\t\ttranscriptRepair: resolveOptionalCounter(init.transcriptRepair, \"transcriptRepair\"),\n\t\t\ttoolResultDisposition: resolveOptionalCounter(init.toolResultDisposition, \"toolResultDisposition\"),\n\t\t\tevidenceReceipt: resolveOptionalCounter(init.evidenceReceipt, \"evidenceReceipt\"),\n\t\t\tuserSteering: resolveOptionalCounter(init.userSteering, \"userSteering\"),\n\t\t\tsettings: resolveOptionalCounter(init.settings, \"settings\"),\n\t\t},\n\t\tworktreeFingerprint: init.worktreeFingerprint,\n\t\tactiveModelId: init.activeModelId,\n\t\tcompactionModelId: init.compactionModelId,\n\t});\n}\n\nfunction applyCounterEvent(current: ContextCacheInvalidationSnapshot, key: CounterKey): ContextCacheInvalidationResult {\n\tconst value = current.counters[key];\n\tif (value >= MAX_REPRESENTABLE || current.globalEpoch >= MAX_REPRESENTABLE) {\n\t\treturn Object.freeze({ status: \"overflow\", snapshot: cloneAndFreeze(current) } as const);\n\t}\n\tconst nextCounters = copyCounters(current.counters);\n\tnextCounters[key] = value + 1;\n\treturn Object.freeze({\n\t\tstatus: \"applied\",\n\t\tsnapshot: freezeSnapshot({\n\t\t\tschemaVersion: current.schemaVersion,\n\t\t\tforkId: current.forkId,\n\t\t\tglobalEpoch: current.globalEpoch + 1,\n\t\t\tcounters: nextCounters,\n\t\t\tworktreeFingerprint: current.worktreeFingerprint,\n\t\t\tactiveModelId: current.activeModelId,\n\t\t\tcompactionModelId: current.compactionModelId,\n\t\t}),\n\t} as const);\n}\n\nfunction applyIdentityEvent(\n\tcurrent: ContextCacheInvalidationSnapshot,\n\tkey: IdentityKey,\n\tvalue: string,\n): ContextCacheInvalidationResult {\n\tassertSafeId(value, key);\n\tif (current[key] === value) {\n\t\treturn Object.freeze({ status: \"unchanged\", snapshot: cloneAndFreeze(current) } as const);\n\t}\n\tif (current.globalEpoch >= MAX_REPRESENTABLE) {\n\t\treturn Object.freeze({ status: \"overflow\", snapshot: cloneAndFreeze(current) } as const);\n\t}\n\treturn Object.freeze({\n\t\tstatus: \"applied\",\n\t\tsnapshot: freezeSnapshot({\n\t\t\tschemaVersion: current.schemaVersion,\n\t\t\tforkId: current.forkId,\n\t\t\tglobalEpoch: current.globalEpoch + 1,\n\t\t\tcounters: copyCounters(current.counters),\n\t\t\tworktreeFingerprint: key === \"worktreeFingerprint\" ? value : current.worktreeFingerprint,\n\t\t\tactiveModelId: key === \"activeModelId\" ? value : current.activeModelId,\n\t\t\tcompactionModelId: key === \"compactionModelId\" ? value : current.compactionModelId,\n\t\t}),\n\t} as const);\n}\n\n/**\n * Apply a single invalidation event. Increments the global epoch and the\n * relevant counter, or sets an identity. A same-value identity set is a\n * no-op and returns {@link ContextCacheInvalidationStatus.unchanged} without\n * an epoch bump. Any counter or epoch overflow returns\n * {@link ContextCacheInvalidationStatus.overflow} with the snapshot unchanged\n * and never wraps.\n */\nexport function applyContextCacheInvalidation(\n\tcurrent: ContextCacheInvalidationSnapshot,\n\tevent: ContextCacheInvalidationEvent,\n): ContextCacheInvalidationResult {\n\tvalidateContextCacheInvalidationSnapshot(current);\n\tvalidateEvent(event);\n\tswitch (event.type) {\n\t\tcase \"transcriptRepair\":\n\t\tcase \"toolResultDisposition\":\n\t\tcase \"evidenceReceipt\":\n\t\tcase \"userSteering\":\n\t\tcase \"settings\":\n\t\t\treturn applyCounterEvent(current, event.type);\n\t\tcase \"worktreeFingerprint\":\n\t\tcase \"activeModelId\":\n\t\tcase \"compactionModelId\":\n\t\t\treturn applyIdentityEvent(current, event.type, event.value);\n\t\tdefault: {\n\t\t\t// Exhaustiveness guard: a new event variant without a matching\n\t\t\t// case becomes a compile error on the assignment below.\n\t\t\tconst _exhaustive: never = event;\n\t\t\tfail(`unhandled event type ${_exhaustive}`);\n\t\t}\n\t}\n}\n\n/**\n * Fork a snapshot: keep all event counters and identity values, change the\n * fork id, and reset the global epoch to 0. The caller supplies the new fork\n * id. Rejects an id equal to the current fork id.\n */\nexport function forkContextCacheSnapshot(\n\tcurrent: ContextCacheInvalidationSnapshot,\n\tnextForkId: string,\n): ContextCacheInvalidationSnapshot {\n\tvalidateContextCacheInvalidationSnapshot(current);\n\tassertSafeId(nextForkId, \"forkId\");\n\tif (nextForkId === current.forkId) {\n\t\tfail(\"forkId must differ from current fork\");\n\t}\n\treturn freezeSnapshot({\n\t\tschemaVersion: current.schemaVersion,\n\t\tforkId: nextForkId,\n\t\tglobalEpoch: 0,\n\t\tcounters: copyCounters(current.counters),\n\t\tworktreeFingerprint: current.worktreeFingerprint,\n\t\tactiveModelId: current.activeModelId,\n\t\tcompactionModelId: current.compactionModelId,\n\t});\n}\n\nfunction snapshotsEqual(a: ContextCacheInvalidationSnapshot, b: ContextCacheInvalidationSnapshot): boolean {\n\treturn (\n\t\ta.globalEpoch === b.globalEpoch &&\n\t\ta.counters.transcriptRepair === b.counters.transcriptRepair &&\n\t\ta.counters.toolResultDisposition === b.counters.toolResultDisposition &&\n\t\ta.counters.evidenceReceipt === b.counters.evidenceReceipt &&\n\t\ta.counters.userSteering === b.counters.userSteering &&\n\t\ta.counters.settings === b.counters.settings &&\n\t\ta.worktreeFingerprint === b.worktreeFingerprint &&\n\t\ta.activeModelId === b.activeModelId &&\n\t\ta.compactionModelId === b.compactionModelId\n\t);\n}\n\nfunction dominates(x: ContextCacheInvalidationSnapshot, y: ContextCacheInvalidationSnapshot): boolean {\n\treturn (\n\t\tx.globalEpoch >= y.globalEpoch &&\n\t\tx.counters.transcriptRepair >= y.counters.transcriptRepair &&\n\t\tx.counters.toolResultDisposition >= y.counters.toolResultDisposition &&\n\t\tx.counters.evidenceReceipt >= y.counters.evidenceReceipt &&\n\t\tx.counters.userSteering >= y.counters.userSteering &&\n\t\tx.counters.settings >= y.counters.settings &&\n\t\tx.worktreeFingerprint === y.worktreeFingerprint &&\n\t\tx.activeModelId === y.activeModelId &&\n\t\tx.compactionModelId === y.compactionModelId\n\t);\n}\n\n/**\n * Fail-closed merge of two snapshots.\n *\n * - Different fork ids, or two snapshots that are not on a shared linear\n * history, yield {@link ContextCacheMergeStatus.divergent}. Disjoint\n * changes are never max-merged.\n * - Structurally equal snapshots yield {@link ContextCacheMergeStatus.equal}.\n * - When one snapshot componentwise-dominates the other (epoch and every\n * counter greater-or-equal, and all identity values equal), the dominant\n * snapshot is chosen via {@link ContextCacheMergeStatus.dominant}.\n */\nexport function mergeContextCacheSnapshots(\n\ta: ContextCacheInvalidationSnapshot,\n\tb: ContextCacheInvalidationSnapshot,\n): ContextCacheMergeResult {\n\tvalidateContextCacheInvalidationSnapshot(a);\n\tvalidateContextCacheInvalidationSnapshot(b);\n\tif (a.forkId !== b.forkId) {\n\t\treturn Object.freeze({ status: \"divergent\", left: cloneAndFreeze(a), right: cloneAndFreeze(b) } as const);\n\t}\n\tif (snapshotsEqual(a, b)) {\n\t\treturn Object.freeze({ status: \"equal\", snapshot: cloneAndFreeze(a) } as const);\n\t}\n\tconst aDominates = dominates(a, b);\n\tconst bDominates = dominates(b, a);\n\tif (aDominates && !bDominates) {\n\t\treturn Object.freeze({ status: \"dominant\", snapshot: cloneAndFreeze(a) } as const);\n\t}\n\tif (bDominates && !aDominates) {\n\t\treturn Object.freeze({ status: \"dominant\", snapshot: cloneAndFreeze(b) } as const);\n\t}\n\treturn Object.freeze({ status: \"divergent\", left: cloneAndFreeze(a), right: cloneAndFreeze(b) } as const);\n}\n\n/**\n * Canonical, fixed-order JSON serialization of a snapshot, suitable as\n * future cache-key material. The field order is fixed and every distinct\n * field participates, so any distinct field change alters the result.\n * Returns a deterministic string with no hash claim.\n */\nexport function serializeContextCacheSnapshot(snapshot: ContextCacheInvalidationSnapshot): string {\n\tvalidateContextCacheInvalidationSnapshot(snapshot);\n\treturn JSON.stringify({\n\t\tschemaVersion: snapshot.schemaVersion,\n\t\tforkId: snapshot.forkId,\n\t\tglobalEpoch: snapshot.globalEpoch,\n\t\tcounters: {\n\t\t\ttranscriptRepair: snapshot.counters.transcriptRepair,\n\t\t\ttoolResultDisposition: snapshot.counters.toolResultDisposition,\n\t\t\tevidenceReceipt: snapshot.counters.evidenceReceipt,\n\t\t\tuserSteering: snapshot.counters.userSteering,\n\t\t\tsettings: snapshot.counters.settings,\n\t\t},\n\t\tworktreeFingerprint: snapshot.worktreeFingerprint,\n\t\tactiveModelId: snapshot.activeModelId,\n\t\tcompactionModelId: snapshot.compactionModelId,\n\t});\n}\n"]}
|