open-multi-agent-kit 0.99.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -1
- package/README.md +3 -3
- package/dist/bun/cli.d.ts.map +1 -1
- package/dist/bun/cli.js +1 -0
- package/dist/bun/cli.js.map +1 -1
- package/dist/bun/register-bundled-coding-agent.d.ts +10 -0
- package/dist/bun/register-bundled-coding-agent.d.ts.map +1 -0
- package/dist/bun/register-bundled-coding-agent.js +12 -0
- package/dist/bun/register-bundled-coding-agent.js.map +1 -0
- package/dist/cli/args.d.ts +1 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +1 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/help.d.ts.map +1 -1
- package/dist/cli/help.js +2 -1
- package/dist/cli/help.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +14 -2
- package/dist/cli.js.map +1 -1
- package/dist/commands/neo-cli.d.ts +9 -0
- package/dist/commands/neo-cli.d.ts.map +1 -0
- package/dist/commands/neo-cli.js +61 -0
- package/dist/commands/neo-cli.js.map +1 -0
- package/dist/coordination/awareness.d.ts +32 -0
- package/dist/coordination/awareness.d.ts.map +1 -0
- package/dist/coordination/awareness.js +55 -0
- package/dist/coordination/awareness.js.map +1 -0
- package/dist/coordination/broker.d.ts +79 -0
- package/dist/coordination/broker.d.ts.map +1 -0
- package/dist/coordination/broker.js +195 -0
- package/dist/coordination/broker.js.map +1 -0
- package/dist/coordination/index.d.ts +16 -0
- package/dist/coordination/index.d.ts.map +1 -0
- package/dist/coordination/index.js +16 -0
- package/dist/coordination/index.js.map +1 -0
- package/dist/coordination/integration.d.ts +59 -0
- package/dist/coordination/integration.d.ts.map +1 -0
- package/dist/coordination/integration.js +126 -0
- package/dist/coordination/integration.js.map +1 -0
- package/dist/coordination/operation.d.ts +106 -0
- package/dist/coordination/operation.d.ts.map +1 -0
- package/dist/coordination/operation.js +179 -0
- package/dist/coordination/operation.js.map +1 -0
- package/dist/coordination/resource.d.ts +33 -0
- package/dist/coordination/resource.d.ts.map +1 -0
- package/dist/coordination/resource.js +89 -0
- package/dist/coordination/resource.js.map +1 -0
- package/dist/coordination/session.d.ts +74 -0
- package/dist/coordination/session.d.ts.map +1 -0
- package/dist/coordination/session.js +143 -0
- package/dist/coordination/session.js.map +1 -0
- package/dist/coordination/types.d.ts +68 -0
- package/dist/coordination/types.d.ts.map +1 -0
- package/dist/coordination/types.js +26 -0
- package/dist/coordination/types.js.map +1 -0
- package/dist/core/agent-session.d.ts +29 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +135 -37
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/bundled-skills.d.ts +4 -0
- package/dist/core/bundled-skills.d.ts.map +1 -0
- package/dist/core/bundled-skills.js +32 -0
- package/dist/core/bundled-skills.js.map +1 -0
- package/dist/core/cli-diagnostics.d.ts +6 -0
- package/dist/core/cli-diagnostics.d.ts.map +1 -0
- package/dist/core/cli-diagnostics.js +20 -0
- package/dist/core/cli-diagnostics.js.map +1 -0
- package/dist/core/compaction/control-state.d.ts +41 -0
- package/dist/core/compaction/control-state.d.ts.map +1 -0
- package/dist/core/compaction/control-state.js +85 -0
- package/dist/core/compaction/control-state.js.map +1 -0
- package/dist/core/compaction/fallback.d.ts +60 -0
- package/dist/core/compaction/fallback.d.ts.map +1 -0
- package/dist/core/compaction/fallback.js +117 -0
- package/dist/core/compaction/fallback.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/context-budget-headroom-candidates.d.ts +16 -1
- package/dist/core/context-budget-headroom-candidates.d.ts.map +1 -1
- package/dist/core/context-budget-headroom-candidates.js +31 -13
- package/dist/core/context-budget-headroom-candidates.js.map +1 -1
- package/dist/core/context-budget-headroom-types.d.ts +7 -1
- package/dist/core/context-budget-headroom-types.d.ts.map +1 -1
- package/dist/core/context-budget-headroom-types.js +0 -1
- package/dist/core/context-budget-headroom-types.js.map +1 -1
- package/dist/core/context-budget-headroom.d.ts +22 -0
- package/dist/core/context-budget-headroom.d.ts.map +1 -1
- package/dist/core/context-budget-headroom.js +46 -2
- package/dist/core/context-budget-headroom.js.map +1 -1
- package/dist/core/context-budget-v2-global-pass.d.ts +21 -0
- package/dist/core/context-budget-v2-global-pass.d.ts.map +1 -0
- package/dist/core/context-budget-v2-global-pass.js +203 -0
- package/dist/core/context-budget-v2-global-pass.js.map +1 -0
- package/dist/core/context-budget-v2-input-validation.d.ts +4 -0
- package/dist/core/context-budget-v2-input-validation.d.ts.map +1 -0
- package/dist/core/context-budget-v2-input-validation.js +79 -0
- package/dist/core/context-budget-v2-input-validation.js.map +1 -0
- package/dist/core/context-budget-v2-observability.d.ts +15 -0
- package/dist/core/context-budget-v2-observability.d.ts.map +1 -0
- package/dist/core/context-budget-v2-observability.js +35 -0
- package/dist/core/context-budget-v2-observability.js.map +1 -0
- package/dist/core/context-budget-v2-planned-items.d.ts +17 -0
- package/dist/core/context-budget-v2-planned-items.d.ts.map +1 -0
- package/dist/core/context-budget-v2-planned-items.js +59 -0
- package/dist/core/context-budget-v2-planned-items.js.map +1 -0
- package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
- package/dist/core/context-budget-v2-planner.js +69 -51
- package/dist/core/context-budget-v2-planner.js.map +1 -1
- package/dist/core/context-budget-v2-scoring.d.ts +7 -1
- package/dist/core/context-budget-v2-scoring.d.ts.map +1 -1
- package/dist/core/context-budget-v2-scoring.js.map +1 -1
- package/dist/core/context-budget-v2-selection.d.ts +22 -3
- package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
- package/dist/core/context-budget-v2-selection.js +41 -59
- package/dist/core/context-budget-v2-selection.js.map +1 -1
- package/dist/core/context-budget-v2-tiers.d.ts.map +1 -1
- package/dist/core/context-budget-v2-tiers.js +9 -42
- package/dist/core/context-budget-v2-tiers.js.map +1 -1
- package/dist/core/context-budget-v2-types.d.ts +14 -2
- package/dist/core/context-budget-v2-types.d.ts.map +1 -1
- package/dist/core/context-budget-v2-types.js +6 -1
- package/dist/core/context-budget-v2-types.js.map +1 -1
- package/dist/core/extensions/bundled-virtual-modules.d.ts +15 -0
- package/dist/core/extensions/bundled-virtual-modules.d.ts.map +1 -0
- package/dist/core/extensions/bundled-virtual-modules.js +63 -0
- package/dist/core/extensions/bundled-virtual-modules.js.map +1 -0
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +2 -42
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +1 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +6 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +10 -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 +2 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +2 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/loadout-runtime.d.ts +2 -8
- package/dist/core/loadout-runtime.d.ts.map +1 -1
- package/dist/core/loadout-runtime.js.map +1 -1
- package/dist/core/mcp/client.d.ts +27 -6
- package/dist/core/mcp/client.d.ts.map +1 -1
- package/dist/core/mcp/client.js +80 -20
- package/dist/core/mcp/client.js.map +1 -1
- package/dist/core/mcp/manager.d.ts +10 -1
- package/dist/core/mcp/manager.d.ts.map +1 -1
- package/dist/core/mcp/manager.js +68 -9
- package/dist/core/mcp/manager.js.map +1 -1
- package/dist/core/mcp/protocol.d.ts +9 -3
- package/dist/core/mcp/protocol.d.ts.map +1 -1
- package/dist/core/mcp/protocol.js +61 -15
- package/dist/core/mcp/protocol.js.map +1 -1
- package/dist/core/mcp/stdio-transport.d.ts +12 -1
- package/dist/core/mcp/stdio-transport.d.ts.map +1 -1
- package/dist/core/mcp/stdio-transport.js +30 -2
- package/dist/core/mcp/stdio-transport.js.map +1 -1
- package/dist/core/mcp-descriptor-injection.d.ts +26 -0
- package/dist/core/mcp-descriptor-injection.d.ts.map +1 -0
- package/dist/core/mcp-descriptor-injection.js +25 -0
- package/dist/core/mcp-descriptor-injection.js.map +1 -0
- package/dist/core/mcp-public-presets.d.ts +1 -3
- package/dist/core/mcp-public-presets.d.ts.map +1 -1
- package/dist/core/mcp-public-presets.js +3 -15
- package/dist/core/mcp-public-presets.js.map +1 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +24 -3
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/neo/catalog.d.ts +20 -0
- package/dist/core/neo/catalog.d.ts.map +1 -0
- package/dist/core/neo/catalog.js +50 -0
- package/dist/core/neo/catalog.js.map +1 -0
- package/dist/core/neo/setup.d.ts +3 -0
- package/dist/core/neo/setup.d.ts.map +1 -0
- package/dist/core/neo/setup.js +47 -0
- package/dist/core/neo/setup.js.map +1 -0
- package/dist/core/provider-default-models.d.ts +2 -0
- package/dist/core/provider-default-models.d.ts.map +1 -1
- package/dist/core/provider-default-models.js +2 -0
- package/dist/core/provider-default-models.js.map +1 -1
- package/dist/core/provider-display-names.d.ts.map +1 -1
- package/dist/core/provider-display-names.js +2 -0
- package/dist/core/provider-display-names.js.map +1 -1
- package/dist/core/provider-error-classification.d.ts +57 -0
- package/dist/core/provider-error-classification.d.ts.map +1 -0
- package/dist/core/provider-error-classification.js +103 -0
- package/dist/core/provider-error-classification.js.map +1 -0
- package/dist/core/provider-resilience.d.ts +10 -0
- package/dist/core/provider-resilience.d.ts.map +1 -1
- package/dist/core/provider-resilience.js +36 -3
- package/dist/core/provider-resilience.js.map +1 -1
- package/dist/core/provider-usage-commandcode.d.ts +9 -0
- package/dist/core/provider-usage-commandcode.d.ts.map +1 -0
- package/dist/core/provider-usage-commandcode.js +198 -0
- package/dist/core/provider-usage-commandcode.js.map +1 -0
- package/dist/core/provider-usage-devin.d.ts +5 -3
- package/dist/core/provider-usage-devin.d.ts.map +1 -1
- package/dist/core/provider-usage-devin.js +15 -5
- package/dist/core/provider-usage-devin.js.map +1 -1
- package/dist/core/provider-usage-types.d.ts +1 -1
- package/dist/core/provider-usage-types.d.ts.map +1 -1
- package/dist/core/provider-usage-types.js.map +1 -1
- package/dist/core/provider-usage.d.ts.map +1 -1
- package/dist/core/provider-usage.js +6 -0
- package/dist/core/provider-usage.js.map +1 -1
- package/dist/core/reasoning-router-resolver.d.ts +7 -0
- package/dist/core/reasoning-router-resolver.d.ts.map +1 -1
- package/dist/core/reasoning-router-resolver.js +21 -3
- package/dist/core/reasoning-router-resolver.js.map +1 -1
- package/dist/core/reasoning-router-v4.d.ts +8 -5
- package/dist/core/reasoning-router-v4.d.ts.map +1 -1
- package/dist/core/reasoning-router-v4.js +8 -5
- package/dist/core/reasoning-router-v4.js.map +1 -1
- package/dist/core/resource-admission.d.ts +36 -0
- package/dist/core/resource-admission.d.ts.map +1 -1
- package/dist/core/resource-admission.js +59 -0
- package/dist/core/resource-admission.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +2 -2
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/run-usage-ledger.d.ts +47 -0
- package/dist/core/run-usage-ledger.d.ts.map +1 -0
- package/dist/core/run-usage-ledger.js +162 -0
- package/dist/core/run-usage-ledger.js.map +1 -0
- package/dist/core/run-usage-operation.d.ts +8 -0
- package/dist/core/run-usage-operation.d.ts.map +1 -0
- package/dist/core/run-usage-operation.js +12 -0
- package/dist/core/run-usage-operation.js.map +1 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +5 -6
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-compaction-service.d.ts +15 -0
- package/dist/core/session-compaction-service.d.ts.map +1 -1
- package/dist/core/session-compaction-service.js +17 -4
- package/dist/core/session-compaction-service.js.map +1 -1
- package/dist/core/session-failure-cause.d.ts.map +1 -1
- package/dist/core/session-failure-cause.js +14 -5
- package/dist/core/session-failure-cause.js.map +1 -1
- package/dist/core/session-prompt-lifecycle.d.ts +6 -0
- package/dist/core/session-prompt-lifecycle.d.ts.map +1 -1
- package/dist/core/session-prompt-lifecycle.js +47 -2
- package/dist/core/session-prompt-lifecycle.js.map +1 -1
- package/dist/core/session-termination.d.ts.map +1 -1
- package/dist/core/session-termination.js +4 -2
- package/dist/core/session-termination.js.map +1 -1
- package/dist/core/subagent-lane-authority.d.ts +28 -0
- package/dist/core/subagent-lane-authority.d.ts.map +1 -0
- package/dist/core/subagent-lane-authority.js +119 -0
- package/dist/core/subagent-lane-authority.js.map +1 -0
- package/dist/core/subagent-lane-contract.d.ts +114 -0
- package/dist/core/subagent-lane-contract.d.ts.map +1 -0
- package/dist/core/subagent-lane-contract.js +18 -0
- package/dist/core/subagent-lane-contract.js.map +1 -0
- package/dist/core/subagent-lane-launcher.d.ts +3 -6
- package/dist/core/subagent-lane-launcher.d.ts.map +1 -1
- package/dist/core/subagent-lane-launcher.js +53 -12
- package/dist/core/subagent-lane-launcher.js.map +1 -1
- package/dist/core/subagent-orchestration.d.ts +4 -17
- package/dist/core/subagent-orchestration.d.ts.map +1 -1
- package/dist/core/subagent-orchestration.js.map +1 -1
- package/dist/core/todo-runtime-state.d.ts +12 -0
- package/dist/core/todo-runtime-state.d.ts.map +1 -1
- package/dist/core/todo-runtime-state.js +23 -0
- package/dist/core/todo-runtime-state.js.map +1 -1
- package/dist/core/verified-run/broker.d.ts.map +1 -1
- package/dist/core/verified-run/broker.js +4 -1
- package/dist/core/verified-run/broker.js.map +1 -1
- package/dist/core/workload-permit-pool.d.ts +1 -1
- package/dist/core/workload-permit-pool.d.ts.map +1 -1
- package/dist/core/workload-permit-pool.js +3 -0
- package/dist/core/workload-permit-pool.js.map +1 -1
- package/dist/guardrails/strict-evidence-approval-adapter.d.ts +34 -0
- package/dist/guardrails/strict-evidence-approval-adapter.d.ts.map +1 -0
- package/dist/guardrails/strict-evidence-approval-adapter.js +70 -0
- package/dist/guardrails/strict-evidence-approval-adapter.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +11 -18
- package/dist/main.js.map +1 -1
- package/dist/metacognition/calibration-selective.d.ts +78 -0
- package/dist/metacognition/calibration-selective.d.ts.map +1 -0
- package/dist/metacognition/calibration-selective.js +161 -0
- package/dist/metacognition/calibration-selective.js.map +1 -0
- package/dist/metacognition/calibration.d.ts +62 -0
- package/dist/metacognition/calibration.d.ts.map +1 -0
- package/dist/metacognition/calibration.js +122 -0
- package/dist/metacognition/calibration.js.map +1 -0
- package/dist/metacognition/checkpoint.d.ts +60 -0
- package/dist/metacognition/checkpoint.d.ts.map +1 -0
- package/dist/metacognition/checkpoint.js +57 -0
- package/dist/metacognition/checkpoint.js.map +1 -0
- package/dist/metacognition/context7.d.ts +48 -0
- package/dist/metacognition/context7.d.ts.map +1 -0
- package/dist/metacognition/context7.js +154 -0
- package/dist/metacognition/context7.js.map +1 -0
- package/dist/metacognition/decision.d.ts +44 -0
- package/dist/metacognition/decision.d.ts.map +1 -0
- package/dist/metacognition/decision.js +111 -0
- package/dist/metacognition/decision.js.map +1 -0
- package/dist/metacognition/evaluation.d.ts +73 -0
- package/dist/metacognition/evaluation.d.ts.map +1 -0
- package/dist/metacognition/evaluation.js +97 -0
- package/dist/metacognition/evaluation.js.map +1 -0
- package/dist/metacognition/index.d.ts +31 -0
- package/dist/metacognition/index.d.ts.map +1 -0
- package/dist/metacognition/index.js +31 -0
- package/dist/metacognition/index.js.map +1 -0
- package/dist/metacognition/knowledge-action.d.ts +43 -0
- package/dist/metacognition/knowledge-action.d.ts.map +1 -0
- package/dist/metacognition/knowledge-action.js +60 -0
- package/dist/metacognition/knowledge-action.js.map +1 -0
- package/dist/metacognition/knowledge.d.ts +84 -0
- package/dist/metacognition/knowledge.d.ts.map +1 -0
- package/dist/metacognition/knowledge.js +165 -0
- package/dist/metacognition/knowledge.js.map +1 -0
- package/dist/metacognition/obligations.d.ts +82 -0
- package/dist/metacognition/obligations.d.ts.map +1 -0
- package/dist/metacognition/obligations.js +139 -0
- package/dist/metacognition/obligations.js.map +1 -0
- package/dist/metacognition/observation-validity.d.ts +83 -0
- package/dist/metacognition/observation-validity.d.ts.map +1 -0
- package/dist/metacognition/observation-validity.js +118 -0
- package/dist/metacognition/observation-validity.js.map +1 -0
- package/dist/metacognition/observe.d.ts +45 -0
- package/dist/metacognition/observe.d.ts.map +1 -0
- package/dist/metacognition/observe.js +59 -0
- package/dist/metacognition/observe.js.map +1 -0
- package/dist/metacognition/policy.d.ts +53 -0
- package/dist/metacognition/policy.d.ts.map +1 -0
- package/dist/metacognition/policy.js +155 -0
- package/dist/metacognition/policy.js.map +1 -0
- package/dist/metacognition/predictions.d.ts +78 -0
- package/dist/metacognition/predictions.d.ts.map +1 -0
- package/dist/metacognition/predictions.js +181 -0
- package/dist/metacognition/predictions.js.map +1 -0
- package/dist/metacognition/retrieval.d.ts +53 -0
- package/dist/metacognition/retrieval.d.ts.map +1 -0
- package/dist/metacognition/retrieval.js +170 -0
- package/dist/metacognition/retrieval.js.map +1 -0
- package/dist/metacognition/risk.d.ts +48 -0
- package/dist/metacognition/risk.d.ts.map +1 -0
- package/dist/metacognition/risk.js +165 -0
- package/dist/metacognition/risk.js.map +1 -0
- package/dist/metacognition/route-economics.d.ts +95 -0
- package/dist/metacognition/route-economics.d.ts.map +1 -0
- package/dist/metacognition/route-economics.js +110 -0
- package/dist/metacognition/route-economics.js.map +1 -0
- package/dist/metacognition/runtime-bridge.d.ts +54 -0
- package/dist/metacognition/runtime-bridge.d.ts.map +1 -0
- package/dist/metacognition/runtime-bridge.js +140 -0
- package/dist/metacognition/runtime-bridge.js.map +1 -0
- package/dist/metacognition/skills.d.ts +42 -0
- package/dist/metacognition/skills.d.ts.map +1 -0
- package/dist/metacognition/skills.js +220 -0
- package/dist/metacognition/skills.js.map +1 -0
- package/dist/metacognition/state.d.ts +110 -0
- package/dist/metacognition/state.d.ts.map +1 -0
- package/dist/metacognition/state.js +52 -0
- package/dist/metacognition/state.js.map +1 -0
- package/dist/metacognition/validation.d.ts +19 -0
- package/dist/metacognition/validation.d.ts.map +1 -0
- package/dist/metacognition/validation.js +58 -0
- package/dist/metacognition/validation.js.map +1 -0
- package/dist/metacognition/verification.d.ts +93 -0
- package/dist/metacognition/verification.d.ts.map +1 -0
- package/dist/metacognition/verification.js +132 -0
- package/dist/metacognition/verification.js.map +1 -0
- package/dist/metacognition/verifier.d.ts +49 -0
- package/dist/metacognition/verifier.d.ts.map +1 -0
- package/dist/metacognition/verifier.js +88 -0
- package/dist/metacognition/verifier.js.map +1 -0
- package/dist/modes/acp/acp-agent.d.ts +24 -0
- package/dist/modes/acp/acp-agent.d.ts.map +1 -0
- package/dist/modes/acp/acp-agent.js +133 -0
- package/dist/modes/acp/acp-agent.js.map +1 -0
- package/dist/modes/acp/acp-mode.d.ts +4 -0
- package/dist/modes/acp/acp-mode.d.ts.map +1 -0
- package/dist/modes/acp/acp-mode.js +34 -0
- package/dist/modes/acp/acp-mode.js.map +1 -0
- package/dist/modes/acp/acp-session.d.ts +4 -0
- package/dist/modes/acp/acp-session.d.ts.map +1 -0
- package/dist/modes/acp/acp-session.js +76 -0
- package/dist/modes/acp/acp-session.js.map +1 -0
- package/dist/modes/acp/acp-transport.d.ts +5 -0
- package/dist/modes/acp/acp-transport.d.ts.map +1 -0
- package/dist/modes/acp/acp-transport.js +90 -0
- package/dist/modes/acp/acp-transport.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +1 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/observation/identity.d.ts +14 -0
- package/dist/observation/identity.d.ts.map +1 -0
- package/dist/observation/identity.js +29 -0
- package/dist/observation/identity.js.map +1 -0
- package/dist/observation/index.d.ts +13 -0
- package/dist/observation/index.d.ts.map +1 -0
- package/dist/observation/index.js +13 -0
- package/dist/observation/index.js.map +1 -0
- package/dist/observation/observe-mode.d.ts +46 -0
- package/dist/observation/observe-mode.d.ts.map +1 -0
- package/dist/observation/observe-mode.js +83 -0
- package/dist/observation/observe-mode.js.map +1 -0
- package/dist/observation/store.d.ts +53 -0
- package/dist/observation/store.d.ts.map +1 -0
- package/dist/observation/store.js +126 -0
- package/dist/observation/store.js.map +1 -0
- package/dist/observation/types.d.ts +72 -0
- package/dist/observation/types.d.ts.map +1 -0
- package/dist/observation/types.js +9 -0
- package/dist/observation/types.js.map +1 -0
- package/dist/observation/view.d.ts +39 -0
- package/dist/observation/view.d.ts.map +1 -0
- package/dist/observation/view.js +173 -0
- package/dist/observation/view.js.map +1 -0
- package/docs/audit-revalidation-2026-09-17.md +77 -0
- package/docs/devin-harness.md +33 -4
- package/docs/ecraf-normalization.md +83 -0
- package/docs/metacognition.md +51 -0
- package/docs/model-catalog-refresh.md +110 -1
- package/docs/models.md +1 -1
- package/docs/neo.md +134 -0
- package/docs/providers.md +125 -6
- package/docs/run-usage-ledger.md +56 -0
- package/docs/runtime-algorithms.md +151 -3
- package/docs/skills.md +1 -1
- package/docs/usage.md +2 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/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/subagent/adaptive-agent-runtime.ts +14 -1
- package/examples/extensions/subagent/graph-result.ts +48 -0
- package/examples/extensions/subagent/index.ts +246 -111
- package/examples/extensions/subagent/managed-process-tree.ts +42 -0
- package/examples/extensions/subagent/managed-process.test.ts +24 -0
- package/examples/extensions/subagent/managed-process.ts +93 -112
- package/examples/extensions/subagent/subagent-runtime-types.ts +17 -1
- package/examples/extensions/subagent/subagent-stream.ts +161 -0
- package/examples/extensions/terminal-browser/README.md +54 -0
- package/examples/extensions/terminal-browser/bridge-protocol.ts +29 -0
- package/examples/extensions/terminal-browser/bridge.ts +219 -0
- package/examples/extensions/terminal-browser/browser-surface.ts +288 -0
- package/examples/extensions/terminal-browser/index.ts +215 -0
- package/examples/extensions/terminal-browser/placeholders.ts +49 -0
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +18 -18
- package/package.json +8 -7
- package/resources/neo/skills/omk-browser/SKILL.md +32 -0
- package/resources/neo/skills/omk-code-review/SKILL.md +24 -0
- package/resources/neo/skills/omk-computeruse/SKILL.md +34 -0
- package/resources/neo/skills/omk-mcp-setup/SKILL.md +48 -0
- package/resources/neo/skills/omk-research/SKILL.md +24 -0
- package/resources/neo/skills/omk-site/SKILL.md +28 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-compaction-service.js","sourceRoot":"","sources":["../../src/core/session-compaction-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAE3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAMN,wBAAwB,EACxB,8BAA8B,EAC9B,2BAA2B,EAC3B,sBAAsB,EACtB,yBAAyB,EACzB,6BAA6B,EAC7B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAE3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB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BAC9B,QAAQ;wBACR,OAAO,EAAE,MAAM,CAAC,OAAO;wBACvB,aAAa,EAAE,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;qBAChF,CAAC,CAAC;oBACH,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,gBAAgB,CACxD,MAAM,CAAC,OAAO,EACd,MAAM,CAAC,gBAAgB,EACvB,MAAM,CAAC,YAAY,EACnB,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,EAClD,aAAa,CACb,CAAC;oBACF,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;oBACzD,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;wBAC3C,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;oBACzE,CAAC;oBACD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC;gBAC5B,CAAC;YACF,CAAC;QAAA,CACD,CAAC,CAAC;QACH,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;QACzB,OAAO,SAAS,CAAC;IAAA,CACjB;CACD","sourcesContent":["/**\n * Session compaction service: capture / barrier / repair / transaction / commit.\n *\n * Extracted from AgentSession so the session keeps lifecycle orchestration\n * (abort controllers, extension events, auth, model resolution) while this\n * owns the integrity-critical compaction state machine. Every method preserves\n * the exact semantics of the original session implementation — the\n * compaction-transaction / session-integrity suites pin them.\n */\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { repairTranscriptIntegrity } from \"omk-agent-core\";\nimport type { Api, Message, Model, ToolResultMessage } from \"omk-ai\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { CompactionResult } from \"./compaction/index.ts\";\nimport {\n\ttype CompactionBarrierResult,\n\ttype CompactionEnvelope,\n\ttype CompactionPreservedProvenanceInput,\n\ttype CompactionSourceIdentity,\n\ttype CompactionTransaction,\n\tcreateCompactionEnvelope,\n\tcreateCompactionSourceIdentity,\n\tcreateCompactionTransaction,\n\tdecideCompactionCommit,\n\tevaluateCompactionBarrier,\n\tredactCredentialShapedContent,\n\tvalidateCompactionEnvelope,\n} from \"./compaction/transaction.ts\";\nimport { redactSensitiveTextForced } from \"./redaction.ts\";\nimport type { SessionIntegrityReport } from \"./session-integrity.ts\";\nimport { inspectSessionIntegrity } from \"./session-integrity.ts\";\nimport type { CompactionEntry, SessionEntry, SessionManager } from \"./session-manager.ts\";\n\nexport interface CapturedCompactionState {\n\treadonly report: SessionIntegrityReport;\n\treadonly branchEntries: readonly SessionEntry[];\n\treadonly revision: CompactionTransaction[\"baseRevision\"];\n\treadonly source: CompactionSourceIdentity;\n}\n\nexport interface BegunCompaction {\n\treadonly capture: CapturedCompactionState;\n\treadonly transaction: CompactionTransaction;\n}\n\nexport interface CommittedCompaction {\n\treadonly entry: CompactionEntry;\n\treadonly envelope: CompactionEnvelope;\n}\n\nexport interface SessionCompactionServiceDeps {\n\treadonly sessionManager: SessionManager;\n\treadonly pendingToolCallIds: () => ReadonlySet<string>;\n\treadonly getUserMessageText: (message: Message) => string;\n\treadonly cwd: string;\n\treadonly invalidateContextBudget: () => void;\n\t/** Refresh agent messages from the session manager after tail repair/commit. */\n\treadonly refreshAgentMessages: () => void;\n\t/** Hysteresis bookkeeping after a successful commit. */\n\treadonly recordCommit: () => void;\n}\n\nexport class SessionCompactionService {\n\tprivate readonly deps: SessionCompactionServiceDeps;\n\n\tconstructor(deps: SessionCompactionServiceDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tcaptureState(): CapturedCompactionState {\n\t\treturn this.deps.sessionManager.withCompactionCommitLock(() => this.captureStateLocked());\n\t}\n\n\tprivate captureStateLocked(): CapturedCompactionState {\n\t\tconst { sessionManager } = this.deps;\n\t\tconst sessionFile = sessionManager.getSessionFile();\n\t\tconst bytes =\n\t\t\tsessionFile && existsSync(sessionFile)\n\t\t\t\t? new Uint8Array(readFileSync(sessionFile))\n\t\t\t\t: new TextEncoder().encode(\n\t\t\t\t\t\t`${[sessionManager.getHeader(), ...sessionManager.getEntries()]\n\t\t\t\t\t\t\t.filter((entry) => entry !== null)\n\t\t\t\t\t\t\t.map((entry) => JSON.stringify(entry))\n\t\t\t\t\t\t\t.join(\"\\n\")}\\n`,\n\t\t\t\t\t);\n\t\tconst report = inspectSessionIntegrity(bytes, { activeLeafId: sessionManager.getLeafId() });\n\t\tconst branchEntries = report.activeBranch;\n\t\tlet latestCompactionIndex = -1;\n\t\tfor (let index = branchEntries.length - 1; index >= 0; index -= 1) {\n\t\t\tif (branchEntries[index]?.type === \"compaction\") {\n\t\t\t\tlatestCompactionIndex = index;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tconst latestCompaction = branchEntries[latestCompactionIndex];\n\t\tconst firstKeptIndex =\n\t\t\tlatestCompaction?.type === \"compaction\"\n\t\t\t\t? branchEntries.findIndex((entry) => entry.id === latestCompaction.firstKeptEntryId)\n\t\t\t\t: -1;\n\t\tconst sourceEntries = branchEntries.slice(\n\t\t\tlatestCompactionIndex < 0 ? 0 : firstKeptIndex < 0 ? latestCompactionIndex : firstKeptIndex,\n\t\t);\n\t\tconst firstEntry = sourceEntries[0];\n\t\tconst lastEntry = sourceEntries[sourceEntries.length - 1];\n\t\tif (!firstEntry || !lastEntry || report.activeLeafId === null) {\n\t\t\tconst barrier = evaluateCompactionBarrier(report, [...this.deps.pendingToolCallIds()]);\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t\tthrow new Error(\"Nothing to compact: the active session branch is empty\");\n\t\t}\n\t\tconst revision = sessionManager.getDurableHeadToken();\n\t\tconst source = createCompactionSourceIdentity({\n\t\t\tsessionId: revision.sessionId,\n\t\t\tentryIds: sourceEntries.map((entry) => entry.id),\n\t\t\tfirstEntryId: firstEntry.id,\n\t\t\tlastEntryId: lastEntry.id,\n\t\t\tsourceSha256: createHash(\"sha256\")\n\t\t\t\t.update(sourceEntries.map((entry) => JSON.stringify(entry)).join(\"\\n\"), \"utf8\")\n\t\t\t\t.digest(\"hex\"),\n\t\t\tactiveLeafId: report.activeLeafId,\n\t\t\tmessageCount: report.activeMessages.length,\n\t\t});\n\t\treturn { report, branchEntries, revision, source };\n\t}\n\n\tbarrierError(barrier: CompactionBarrierResult): Error {\n\t\tif (barrier.status === \"defer\") {\n\t\t\treturn new Error(`Compaction deferred until the transcript closes (${barrier.reason})`);\n\t\t}\n\t\treturn new Error(\n\t\t\t`Compaction failed closed on transcript integrity (${barrier.reason}). Run the session doctor before retrying.`,\n\t\t);\n\t}\n\n\tevaluateBarrier(\n\t\tcapture: CapturedCompactionState,\n\t\tincludeMissingTailAsPending: boolean,\n\t\texcludedPendingIds: ReadonlySet<string> = new Set(),\n\t): CompactionBarrierResult {\n\t\tconst pending = new Set([...this.deps.pendingToolCallIds()].filter((id) => !excludedPendingIds.has(id)));\n\t\tif (includeMissingTailAsPending) {\n\t\t\tfor (const issue of capture.report.transcript?.issues ?? []) {\n\t\t\t\tif (issue.kind === \"missing_result\") pending.add(issue.toolCallId);\n\t\t\t}\n\t\t}\n\t\treturn evaluateCompactionBarrier(capture.report, [...pending]);\n\t}\n\n\trepairEmergencyTail(capture: CapturedCompactionState): {\n\t\treadonly capture: CapturedCompactionState;\n\t\treadonly repairedToolCallIds: ReadonlySet<string>;\n\t} {\n\t\tconst { sessionManager } = this.deps;\n\t\tconst barrier = this.evaluateBarrier(capture, true);\n\t\tif (barrier.status !== \"defer\" || barrier.reason !== \"missing_active_tail_results\") {\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t\treturn { capture, repairedToolCallIds: new Set() };\n\t\t}\n\t\tconst repairedMessages = repairTranscriptIntegrity(\n\t\t\t[...capture.report.activeMessages],\n\t\t\t\"Tool result missing; synthesized to close an emergency compaction barrier\",\n\t\t);\n\t\tconst inserted = repairedMessages.slice(capture.report.activeMessages.length);\n\t\tconst repairedToolCallIds = new Set<string>();\n\t\tfor (const message of inserted) {\n\t\t\tif (message.role !== \"toolResult\") {\n\t\t\t\tthrow new Error(\"Emergency compaction repair produced a non-tool result\");\n\t\t\t}\n\t\t\tconst toolResult: ToolResultMessage = message;\n\t\t\trepairedToolCallIds.add(toolResult.toolCallId);\n\t\t\tsessionManager.appendMessage(toolResult);\n\t\t}\n\t\tsessionManager.appendCustomEntry(\"compaction_transcript_repaired\", {\n\t\t\tinsertedToolCallIds: [...repairedToolCallIds],\n\t\t\treason: \"emergency_compaction\",\n\t\t});\n\t\tthis.deps.invalidateContextBudget();\n\t\tconst closedCapture = this.captureState();\n\t\tconst closedBarrier = this.evaluateBarrier(closedCapture, false, repairedToolCallIds);\n\t\tif (closedBarrier.status !== \"ready\") throw this.barrierError(closedBarrier);\n\t\tthis.deps.refreshAgentMessages();\n\t\treturn { capture: closedCapture, repairedToolCallIds };\n\t}\n\n\tpriorCommittedSourceDigests(): string[] {\n\t\tconst digests: string[] = [];\n\t\tfor (const entry of this.deps.sessionManager.getEntries()) {\n\t\t\tif (entry.type !== \"compaction\" || typeof entry.details !== \"object\" || entry.details === null) continue;\n\t\t\tif (Object.getOwnPropertyDescriptor(entry.details, \"compactionEnvelope\") === undefined) continue;\n\t\t\tconst envelope = validateCompactionEnvelope(Reflect.get(entry.details, \"compactionEnvelope\"));\n\t\t\tif (envelope.summary !== entry.summary) {\n\t\t\t\tthrow new Error(`Compaction entry ${entry.id} has invalid provenance. Run the session doctor.`);\n\t\t\t}\n\t\t\tdigests.push(envelope.source.sourceSha256);\n\t\t}\n\t\treturn digests;\n\t}\n\n\tbeginTransaction(compactionModel: Model<Api>, emergency: boolean): BegunCompaction {\n\t\tlet capture = this.captureState();\n\t\tif (emergency) {\n\t\t\tcapture = this.repairEmergencyTail(capture).capture;\n\t\t} else {\n\t\t\tconst barrier = this.evaluateBarrier(capture, false);\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t}\n\t\tconst transaction = createCompactionTransaction({\n\t\t\ttransactionId: randomUUID(),\n\t\t\tbaseRevision: capture.revision,\n\t\t\tsource: capture.source,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\tmodel: { provider: compactionModel.provider, id: compactionModel.id },\n\t\t\tpreserved: this.captureProvenance(capture),\n\t\t});\n\t\tif (this.priorCommittedSourceDigests().includes(transaction.source.sourceSha256)) {\n\t\t\tthrow new Error(\"This exact compaction source was already compacted\");\n\t\t}\n\t\treturn { capture, transaction };\n\t}\n\n\tcaptureProvenance(capture: CapturedCompactionState): CompactionPreservedProvenanceInput {\n\t\tlet latestIntent = \"Continue the current session\";\n\t\tfor (let index = capture.report.activeMessages.length - 1; index >= 0; index -= 1) {\n\t\t\tconst message = capture.report.activeMessages[index];\n\t\t\tif (message?.role !== \"user\") continue;\n\t\t\tconst candidate = redactCredentialShapedContent(\n\t\t\t\tsanitizeBinaryOutput(redactSensitiveTextForced(this.deps.getUserMessageText(message)).trim())\n\t\t\t\t\t.replace(/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/gu, \"\")\n\t\t\t\t\t.slice(0, 16_384),\n\t\t\t);\n\t\t\tif (candidate.length > 0) latestIntent = candidate;\n\t\t\tbreak;\n\t\t}\n\t\tconst modelHistory = capture.branchEntries\n\t\t\t.flatMap((entry) => {\n\t\t\t\tif (entry.type === \"model_change\") {\n\t\t\t\t\treturn [{ entryId: entry.id, provider: entry.provider, modelId: entry.modelId }];\n\t\t\t\t}\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\treturn [{ entryId: entry.id, provider: entry.message.provider, modelId: entry.message.model }];\n\t\t\t\t}\n\t\t\t\treturn [];\n\t\t\t})\n\t\t\t.slice(-256);\n\t\tconst customEntryIds = (customType: string): string[] =>\n\t\t\tcapture.branchEntries\n\t\t\t\t.filter((entry) => entry.type === \"custom\" && entry.customType === customType)\n\t\t\t\t.map((entry) => entry.id);\n\t\treturn {\n\t\t\tlatestIntent,\n\t\t\topenTasks: [],\n\t\t\tlaneIds: customEntryIds(\"lane\"),\n\t\t\tacceptancePredicateIds: customEntryIds(\"acceptance_predicate\"),\n\t\t\tevidenceReceiptIds: customEntryIds(\"evidence_receipt\"),\n\t\t\tblockerReasons: [],\n\t\t\trepairEventIds: [\n\t\t\t\t...customEntryIds(\"transcript_repaired\"),\n\t\t\t\t...customEntryIds(\"compaction_transcript_repaired\"),\n\t\t\t],\n\t\t\tbranch: null,\n\t\t\tworktree: this.deps.cwd,\n\t\t\tmodelHistory,\n\t\t\tnextAction: redactCredentialShapedContent(latestIntent.slice(0, 4096)) || \"Continue the current session\",\n\t\t};\n\t}\n\n\tdetailsWithEnvelope(details: unknown, envelope: CompactionEnvelope): unknown {\n\t\tif (typeof details === \"object\" && details !== null && !Array.isArray(details)) {\n\t\t\treturn { ...details, compactionEnvelope: envelope };\n\t\t}\n\t\treturn {\n\t\t\tcompactionEnvelope: envelope,\n\t\t\t...(details === undefined ? {} : { resultDetails: details }),\n\t\t};\n\t}\n\n\tcommit(begun: BegunCompaction, result: CompactionResult, fromExtension: boolean): CommittedCompaction {\n\t\tif (!begun.transaction.source.entryIds.includes(result.firstKeptEntryId)) {\n\t\t\tthrow new Error(\"Compaction first-kept entry is outside the captured source\");\n\t\t}\n\t\tconst committed = this.deps.sessionManager.withCompactionCommitLock(() => {\n\t\t\tconst current = this.captureState();\n\t\t\tconst barrier = this.evaluateBarrier(current, false);\n\t\t\tconst decision = decideCompactionCommit({\n\t\t\t\ttransaction: begun.transaction,\n\t\t\t\tcurrentRevision: current.revision,\n\t\t\t\tcurrentSource: current.source,\n\t\t\t\tbarrier,\n\t\t\t\tpriorCommittedSourceDigests: this.priorCommittedSourceDigests(),\n\t\t\t});\n\t\t\tswitch (decision.decision) {\n\t\t\t\tcase \"duplicate\":\n\t\t\t\t\tthrow new Error(\"This exact compaction source was already compacted\");\n\t\t\t\tcase \"stale\":\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Session changed during compaction (${decision.reason}); generated summary was discarded`,\n\t\t\t\t\t);\n\t\t\t\tcase \"defer\":\n\t\t\t\tcase \"fail_closed\":\n\t\t\t\t\tthrow this.barrierError(barrier);\n\t\t\t\tcase \"commit\": {\n\t\t\t\t\tconst envelope = createCompactionEnvelope({\n\t\t\t\t\t\ttransaction: begun.transaction,\n\t\t\t\t\t\tdecision,\n\t\t\t\t\t\tsummary: result.summary,\n\t\t\t\t\t\tsummarySha256: createHash(\"sha256\").update(result.summary, \"utf8\").digest(\"hex\"),\n\t\t\t\t\t});\n\t\t\t\t\tconst entryId = this.deps.sessionManager.appendCompaction(\n\t\t\t\t\t\tresult.summary,\n\t\t\t\t\t\tresult.firstKeptEntryId,\n\t\t\t\t\t\tresult.tokensBefore,\n\t\t\t\t\t\tthis.detailsWithEnvelope(result.details, envelope),\n\t\t\t\t\t\tfromExtension,\n\t\t\t\t\t);\n\t\t\t\t\tconst entry = this.deps.sessionManager.getEntry(entryId);\n\t\t\t\t\tif (!entry || entry.type !== \"compaction\") {\n\t\t\t\t\t\tthrow new Error(\"Compaction commit did not produce a compaction entry\");\n\t\t\t\t\t}\n\t\t\t\t\treturn { entry, envelope };\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tthis.deps.recordCommit();\n\t\treturn committed;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-compaction-service.js","sourceRoot":"","sources":["../../src/core/session-compaction-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAE3D,OAAO,EAAE,o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,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;oBACzD,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;wBAC3C,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;oBACzE,CAAC;oBACD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC;gBAC5B,CAAC;YACF,CAAC;QAAA,CACD,CAAC,CAAC;QACH,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;QACzB,OAAO,SAAS,CAAC;IAAA,CACjB;CACD","sourcesContent":["/**\n * Session compaction service: capture / barrier / repair / transaction / commit.\n *\n * Extracted from AgentSession so the session keeps lifecycle orchestration\n * (abort controllers, extension events, auth, model resolution) while this\n * owns the integrity-critical compaction state machine. Every method preserves\n * the exact semantics of the original session implementation — the\n * compaction-transaction / session-integrity suites pin them.\n */\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { repairTranscriptIntegrity } from \"omk-agent-core\";\nimport type { Api, Message, Model, ToolResultMessage } from \"omk-ai\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport {\n\ttype CompactionControlState,\n\tcontrolStateDigest,\n\tcontrolStateProvenance,\n\tvalidateControlState,\n} from \"./compaction/control-state.ts\";\nimport type { CompactionResult } from \"./compaction/index.ts\";\nimport {\n\ttype CompactionBarrierResult,\n\ttype CompactionEnvelope,\n\ttype CompactionPreservedProvenanceInput,\n\ttype CompactionSourceIdentity,\n\ttype CompactionTransaction,\n\tcreateCompactionEnvelope,\n\tcreateCompactionSourceIdentity,\n\tcreateCompactionTransaction,\n\tdecideCompactionCommit,\n\tevaluateCompactionBarrier,\n\tredactCredentialShapedContent,\n\tvalidateCompactionEnvelope,\n} from \"./compaction/transaction.ts\";\nimport { redactSensitiveTextForced } from \"./redaction.ts\";\nimport type { SessionIntegrityReport } from \"./session-integrity.ts\";\nimport { inspectSessionIntegrity } from \"./session-integrity.ts\";\nimport type { CompactionEntry, SessionEntry, SessionManager } from \"./session-manager.ts\";\n\nexport interface CapturedCompactionState {\n\treadonly report: SessionIntegrityReport;\n\treadonly branchEntries: readonly SessionEntry[];\n\treadonly revision: CompactionTransaction[\"baseRevision\"];\n\treadonly source: CompactionSourceIdentity;\n\t/**\n\t * Digest of the host control-state snapshot captured under the same commit\n\t * lock as `source`. `null` when no control authority is attached. A change\n\t * between capture and commit discards the summary like a source mismatch.\n\t */\n\treadonly controlStateDigest: string | null;\n\treadonly controlState: CompactionControlState | null;\n}\n\nexport interface BegunCompaction {\n\treadonly capture: CapturedCompactionState;\n\treadonly transaction: CompactionTransaction;\n}\n\nexport interface CommittedCompaction {\n\treadonly entry: CompactionEntry;\n\treadonly envelope: CompactionEnvelope;\n}\n\nexport interface SessionCompactionServiceDeps {\n\treadonly sessionManager: SessionManager;\n\treadonly pendingToolCallIds: () => ReadonlySet<string>;\n\treadonly getUserMessageText: (message: Message) => string;\n\treadonly cwd: string;\n\t/**\n\t * Optional host control authority. Called inside the compaction commit lock\n\t * so the snapshot is bound to the same captured source as the summary. Must\n\t * be deterministic for unchanged state — a changed snapshot discards the\n\t * in-flight summary at commit. Return `null` only when no authority exists.\n\t */\n\treadonly controlState?: () => CompactionControlState | null;\n\treadonly invalidateContextBudget: () => void;\n\t/** Refresh agent messages from the session manager after tail repair/commit. */\n\treadonly refreshAgentMessages: () => void;\n\t/** Hysteresis bookkeeping after a successful commit. */\n\treadonly recordCommit: () => void;\n}\n\nexport class SessionCompactionService {\n\tprivate readonly deps: SessionCompactionServiceDeps;\n\n\tconstructor(deps: SessionCompactionServiceDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tcaptureState(): CapturedCompactionState {\n\t\treturn this.deps.sessionManager.withCompactionCommitLock(() => this.captureStateLocked());\n\t}\n\n\tprivate captureStateLocked(): CapturedCompactionState {\n\t\tconst { sessionManager } = this.deps;\n\t\tconst sessionFile = sessionManager.getSessionFile();\n\t\tconst bytes =\n\t\t\tsessionFile && existsSync(sessionFile)\n\t\t\t\t? new Uint8Array(readFileSync(sessionFile))\n\t\t\t\t: new TextEncoder().encode(\n\t\t\t\t\t\t`${[sessionManager.getHeader(), ...sessionManager.getEntries()]\n\t\t\t\t\t\t\t.filter((entry) => entry !== null)\n\t\t\t\t\t\t\t.map((entry) => JSON.stringify(entry))\n\t\t\t\t\t\t\t.join(\"\\n\")}\\n`,\n\t\t\t\t\t);\n\t\tconst report = inspectSessionIntegrity(bytes, { activeLeafId: sessionManager.getLeafId() });\n\t\tconst branchEntries = report.activeBranch;\n\t\tlet latestCompactionIndex = -1;\n\t\tfor (let index = branchEntries.length - 1; index >= 0; index -= 1) {\n\t\t\tif (branchEntries[index]?.type === \"compaction\") {\n\t\t\t\tlatestCompactionIndex = index;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tconst latestCompaction = branchEntries[latestCompactionIndex];\n\t\tconst firstKeptIndex =\n\t\t\tlatestCompaction?.type === \"compaction\"\n\t\t\t\t? branchEntries.findIndex((entry) => entry.id === latestCompaction.firstKeptEntryId)\n\t\t\t\t: -1;\n\t\tconst sourceEntries = branchEntries.slice(\n\t\t\tlatestCompactionIndex < 0 ? 0 : firstKeptIndex < 0 ? latestCompactionIndex : firstKeptIndex,\n\t\t);\n\t\tconst firstEntry = sourceEntries[0];\n\t\tconst lastEntry = sourceEntries[sourceEntries.length - 1];\n\t\tif (!firstEntry || !lastEntry || report.activeLeafId === null) {\n\t\t\tconst barrier = evaluateCompactionBarrier(report, [...this.deps.pendingToolCallIds()]);\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t\tthrow new Error(\"Nothing to compact: the active session branch is empty\");\n\t\t}\n\t\tconst revision = sessionManager.getDurableHeadToken();\n\t\tconst source = createCompactionSourceIdentity({\n\t\t\tsessionId: revision.sessionId,\n\t\t\tentryIds: sourceEntries.map((entry) => entry.id),\n\t\t\tfirstEntryId: firstEntry.id,\n\t\t\tlastEntryId: lastEntry.id,\n\t\t\tsourceSha256: createHash(\"sha256\")\n\t\t\t\t.update(sourceEntries.map((entry) => JSON.stringify(entry)).join(\"\\n\"), \"utf8\")\n\t\t\t\t.digest(\"hex\"),\n\t\t\tactiveLeafId: report.activeLeafId,\n\t\t\tmessageCount: report.activeMessages.length,\n\t\t});\n\t\tconst controlState = validateControlState(this.deps.controlState?.() ?? null);\n\t\treturn {\n\t\t\treport,\n\t\t\tbranchEntries,\n\t\t\trevision,\n\t\t\tsource,\n\t\t\tcontrolStateDigest: controlStateDigest(controlState),\n\t\t\tcontrolState,\n\t\t};\n\t}\n\n\tbarrierError(barrier: CompactionBarrierResult): Error {\n\t\tif (barrier.status === \"defer\") {\n\t\t\treturn new Error(`Compaction deferred until the transcript closes (${barrier.reason})`);\n\t\t}\n\t\treturn new Error(\n\t\t\t`Compaction failed closed on transcript integrity (${barrier.reason}). Run the session doctor before retrying.`,\n\t\t);\n\t}\n\n\tevaluateBarrier(\n\t\tcapture: CapturedCompactionState,\n\t\tincludeMissingTailAsPending: boolean,\n\t\texcludedPendingIds: ReadonlySet<string> = new Set(),\n\t): CompactionBarrierResult {\n\t\tconst pending = new Set([...this.deps.pendingToolCallIds()].filter((id) => !excludedPendingIds.has(id)));\n\t\tif (includeMissingTailAsPending) {\n\t\t\tfor (const issue of capture.report.transcript?.issues ?? []) {\n\t\t\t\tif (issue.kind === \"missing_result\") pending.add(issue.toolCallId);\n\t\t\t}\n\t\t}\n\t\treturn evaluateCompactionBarrier(capture.report, [...pending]);\n\t}\n\n\trepairEmergencyTail(capture: CapturedCompactionState): {\n\t\treadonly capture: CapturedCompactionState;\n\t\treadonly repairedToolCallIds: ReadonlySet<string>;\n\t} {\n\t\tconst { sessionManager } = this.deps;\n\t\tconst barrier = this.evaluateBarrier(capture, true);\n\t\tif (barrier.status !== \"defer\" || barrier.reason !== \"missing_active_tail_results\") {\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t\treturn { capture, repairedToolCallIds: new Set() };\n\t\t}\n\t\tconst repairedMessages = repairTranscriptIntegrity(\n\t\t\t[...capture.report.activeMessages],\n\t\t\t\"Tool result missing; synthesized to close an emergency compaction barrier\",\n\t\t);\n\t\tconst inserted = repairedMessages.slice(capture.report.activeMessages.length);\n\t\tconst repairedToolCallIds = new Set<string>();\n\t\tfor (const message of inserted) {\n\t\t\tif (message.role !== \"toolResult\") {\n\t\t\t\tthrow new Error(\"Emergency compaction repair produced a non-tool result\");\n\t\t\t}\n\t\t\tconst toolResult: ToolResultMessage = message;\n\t\t\trepairedToolCallIds.add(toolResult.toolCallId);\n\t\t\tsessionManager.appendMessage(toolResult);\n\t\t}\n\t\tsessionManager.appendCustomEntry(\"compaction_transcript_repaired\", {\n\t\t\tinsertedToolCallIds: [...repairedToolCallIds],\n\t\t\treason: \"emergency_compaction\",\n\t\t});\n\t\tthis.deps.invalidateContextBudget();\n\t\tconst closedCapture = this.captureState();\n\t\tconst closedBarrier = this.evaluateBarrier(closedCapture, false, repairedToolCallIds);\n\t\tif (closedBarrier.status !== \"ready\") throw this.barrierError(closedBarrier);\n\t\tthis.deps.refreshAgentMessages();\n\t\treturn { capture: closedCapture, repairedToolCallIds };\n\t}\n\n\tpriorCommittedSourceDigests(): string[] {\n\t\tconst digests: string[] = [];\n\t\tfor (const entry of this.deps.sessionManager.getEntries()) {\n\t\t\tif (entry.type !== \"compaction\" || typeof entry.details !== \"object\" || entry.details === null) continue;\n\t\t\tif (Object.getOwnPropertyDescriptor(entry.details, \"compactionEnvelope\") === undefined) continue;\n\t\t\tconst envelope = validateCompactionEnvelope(Reflect.get(entry.details, \"compactionEnvelope\"));\n\t\t\tif (envelope.summary !== entry.summary) {\n\t\t\t\tthrow new Error(`Compaction entry ${entry.id} has invalid provenance. Run the session doctor.`);\n\t\t\t}\n\t\t\tdigests.push(envelope.source.sourceSha256);\n\t\t}\n\t\treturn digests;\n\t}\n\n\tbeginTransaction(compactionModel: Model<Api>, emergency: boolean): BegunCompaction {\n\t\tlet capture = this.captureState();\n\t\tif (emergency) {\n\t\t\tcapture = this.repairEmergencyTail(capture).capture;\n\t\t} else {\n\t\t\tconst barrier = this.evaluateBarrier(capture, false);\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t}\n\t\tconst transaction = createCompactionTransaction({\n\t\t\ttransactionId: randomUUID(),\n\t\t\tbaseRevision: capture.revision,\n\t\t\tsource: capture.source,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\tmodel: { provider: compactionModel.provider, id: compactionModel.id },\n\t\t\tpreserved: this.captureProvenance(capture),\n\t\t});\n\t\tif (this.priorCommittedSourceDigests().includes(transaction.source.sourceSha256)) {\n\t\t\tthrow new Error(\"This exact compaction source was already compacted\");\n\t\t}\n\t\treturn { capture, transaction };\n\t}\n\n\tcaptureProvenance(capture: CapturedCompactionState): CompactionPreservedProvenanceInput {\n\t\tlet latestIntent = \"Continue the current session\";\n\t\tfor (let index = capture.report.activeMessages.length - 1; index >= 0; index -= 1) {\n\t\t\tconst message = capture.report.activeMessages[index];\n\t\t\tif (message?.role !== \"user\") continue;\n\t\t\tconst candidate = redactCredentialShapedContent(\n\t\t\t\tsanitizeBinaryOutput(redactSensitiveTextForced(this.deps.getUserMessageText(message)).trim())\n\t\t\t\t\t.replace(/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/gu, \"\")\n\t\t\t\t\t.slice(0, 16_384),\n\t\t\t);\n\t\t\tif (candidate.length > 0) latestIntent = candidate;\n\t\t\tbreak;\n\t\t}\n\t\tconst modelHistory = capture.branchEntries\n\t\t\t.flatMap((entry) => {\n\t\t\t\tif (entry.type === \"model_change\") {\n\t\t\t\t\treturn [{ entryId: entry.id, provider: entry.provider, modelId: entry.modelId }];\n\t\t\t\t}\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\treturn [{ entryId: entry.id, provider: entry.message.provider, modelId: entry.message.model }];\n\t\t\t\t}\n\t\t\t\treturn [];\n\t\t\t})\n\t\t\t.slice(-256);\n\t\tconst customEntryIds = (customType: string): string[] =>\n\t\t\tcapture.branchEntries\n\t\t\t\t.filter((entry) => entry.type === \"custom\" && entry.customType === customType)\n\t\t\t\t.map((entry) => entry.id);\n\t\tconst control = controlStateProvenance(capture.controlState);\n\t\treturn {\n\t\t\tlatestIntent,\n\t\t\topenTasks: control.openTasks,\n\t\t\tlaneIds: customEntryIds(\"lane\"),\n\t\t\tacceptancePredicateIds: customEntryIds(\"acceptance_predicate\"),\n\t\t\tevidenceReceiptIds: customEntryIds(\"evidence_receipt\"),\n\t\t\tblockerReasons: control.blockerReasons,\n\t\t\trepairEventIds: [\n\t\t\t\t...customEntryIds(\"transcript_repaired\"),\n\t\t\t\t...customEntryIds(\"compaction_transcript_repaired\"),\n\t\t\t],\n\t\t\tbranch: control.branch,\n\t\t\tworktree: this.deps.cwd,\n\t\t\tmodelHistory,\n\t\t\tnextAction: redactCredentialShapedContent(latestIntent.slice(0, 4096)) || \"Continue the current session\",\n\t\t};\n\t}\n\n\tdetailsWithEnvelope(details: unknown, envelope: CompactionEnvelope): unknown {\n\t\tif (typeof details === \"object\" && details !== null && !Array.isArray(details)) {\n\t\t\treturn { ...details, compactionEnvelope: envelope };\n\t\t}\n\t\treturn {\n\t\t\tcompactionEnvelope: envelope,\n\t\t\t...(details === undefined ? {} : { resultDetails: details }),\n\t\t};\n\t}\n\n\tcommit(begun: BegunCompaction, result: CompactionResult, fromExtension: boolean): CommittedCompaction {\n\t\tif (!begun.transaction.source.entryIds.includes(result.firstKeptEntryId)) {\n\t\t\tthrow new Error(\"Compaction first-kept entry is outside the captured source\");\n\t\t}\n\t\tconst committed = this.deps.sessionManager.withCompactionCommitLock(() => {\n\t\t\tconst current = this.captureState();\n\t\t\tconst barrier = this.evaluateBarrier(current, false);\n\t\t\tconst decision = decideCompactionCommit({\n\t\t\t\ttransaction: begun.transaction,\n\t\t\t\tcurrentRevision: current.revision,\n\t\t\t\tcurrentSource: current.source,\n\t\t\t\tbarrier,\n\t\t\t\tpriorCommittedSourceDigests: this.priorCommittedSourceDigests(),\n\t\t\t});\n\t\t\tswitch (decision.decision) {\n\t\t\t\tcase \"duplicate\":\n\t\t\t\t\tthrow new Error(\"This exact compaction source was already compacted\");\n\t\t\t\tcase \"stale\":\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Session changed during compaction (${decision.reason}); generated summary was discarded`,\n\t\t\t\t\t);\n\t\t\t\tcase \"defer\":\n\t\t\t\tcase \"fail_closed\":\n\t\t\t\t\tthrow this.barrierError(barrier);\n\t\t\t\tcase \"commit\": {\n\t\t\t\t\tif (current.controlStateDigest !== begun.capture.controlStateDigest) {\n\t\t\t\t\t\tthrow new Error(\"Control state changed during compaction; generated summary was discarded\");\n\t\t\t\t\t}\n\t\t\t\t\tconst envelope = createCompactionEnvelope({\n\t\t\t\t\t\ttransaction: begun.transaction,\n\t\t\t\t\t\tdecision,\n\t\t\t\t\t\tsummary: result.summary,\n\t\t\t\t\t\tsummarySha256: createHash(\"sha256\").update(result.summary, \"utf8\").digest(\"hex\"),\n\t\t\t\t\t});\n\t\t\t\t\tconst entryId = this.deps.sessionManager.appendCompaction(\n\t\t\t\t\t\tresult.summary,\n\t\t\t\t\t\tresult.firstKeptEntryId,\n\t\t\t\t\t\tresult.tokensBefore,\n\t\t\t\t\t\tthis.detailsWithEnvelope(result.details, envelope),\n\t\t\t\t\t\tfromExtension,\n\t\t\t\t\t);\n\t\t\t\t\tconst entry = this.deps.sessionManager.getEntry(entryId);\n\t\t\t\t\tif (!entry || entry.type !== \"compaction\") {\n\t\t\t\t\t\tthrow new Error(\"Compaction commit did not produce a compaction entry\");\n\t\t\t\t\t}\n\t\t\t\t\treturn { entry, envelope };\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tthis.deps.recordCommit();\n\t\treturn committed;\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-failure-cause.d.ts","sourceRoot":"","sources":["../../src/core/session-failure-cause.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,KAAK,gBAAgB,EAAqB,MAAM,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"session-failure-cause.d.ts","sourceRoot":"","sources":["../../src/core/session-failure-cause.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,KAAK,gBAAgB,EAAqB,MAAM,QAAQ,CAAC;AAUlE,OAAO,EAA0C,KAAK,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAuBhH;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAKtF;AAED,8EAA8E;AAC9E,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,GAAG,uBAAuB,CA+D9G;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAG,uBAAuB,CA0BjG;AAED,iEAAiE;AACjE,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CAc3E","sourcesContent":["/**\n * Failure-text to `SessionTerminationCause` classification.\n *\n * This is the layer *below* `session-termination.ts`: that module turns a cause\n * into a kind/phase/next-action record, while this one decides which cause a\n * provider error, a preflight rejection, or a thrown runtime error represents.\n *\n * The functions are pure so the ordering can be pinned by direct tests. Ordering\n * is load-bearing in two places that are easy to regress:\n *\n * - quota/billing exhaustion is matched *before* the generic 401/403 auth\n * patterns, because `403 ... usage limit for this billing cycle` is\n * transient per cycle and must fail over instead of terminating as auth;\n * - upstream 5xx/dropped streams are matched *before* the protocol fallback,\n * so guidance points at retry/model-switch rather than transcript sanitize.\n */\n\nimport { type AssistantMessage, isContextOverflow } from \"omk-ai\";\nimport {\n\thasStatusCodeLike,\n\tisClaudeCodeVersionTooOldMessage,\n\tisCodexChatgptAccountUnsupportedModelMessage,\n\tisQuotaExhaustionMessage,\n\tisUpstreamUnavailableMessage,\n} from \"./provider-resilience.ts\";\nimport { redactSensitiveText } from \"./redaction.ts\";\nimport { RunBudgetExceededError, RunBudgetPolicyError } from \"./run-budget-policy.ts\";\nimport { MAX_SESSION_TERMINATION_MESSAGE_LENGTH, type SessionTerminationCause } from \"./session-termination.ts\";\n\nfunction isMissingEsmNamedExportMessage(text: string): boolean {\n\treturn /does not provide an export named/i.test(text);\n}\n\n/**\n * Errno codes that mean a write could not be durably completed. Anything else\n * (a missing path, for example) is not evidence of a persistence fault.\n */\nconst PERSISTENCE_ERRNO_CODES: ReadonlySet<string> = new Set([\n\t\"EACCES\",\n\t\"EDQUOT\",\n\t\"EFBIG\",\n\t\"EIO\",\n\t\"EISDIR\",\n\t\"EMFILE\",\n\t\"ENFILE\",\n\t\"ENOSPC\",\n\t\"EPERM\",\n\t\"EROFS\",\n]);\n\n/**\n * Normalize a free-text failure message for the termination record: redact\n * secret-shaped content, drop NUL bytes, and bound the length.\n */\nexport function terminationMessage(value: string | undefined, fallback: string): string {\n\tconst redacted = redactSensitiveText(value?.trim() || fallback)\n\t\t.replace(/\\0/g, \"\")\n\t\t.slice(0, MAX_SESSION_TERMINATION_MESSAGE_LENGTH);\n\treturn redacted || fallback;\n}\n\n/** Classify a failed provider turn from the assistant message it produced. */\nexport function providerFailureCause(message: AssistantMessage, contextWindow: number): SessionTerminationCause {\n\tconst text = message.errorMessage ?? \"\";\n\tif (isContextOverflow(message, contextWindow)) {\n\t\treturn { area: \"provider\", code: \"context_overflow\" };\n\t}\n\t// Fable/Claude often emit stop_reason=refusal on benign turns (false positive).\n\t// Match broadly so we never mislabel these as provider.protocol.\n\tif (\n\t\t/stop_reason\\s*=\\s*(refusal|sensitive)|content\\/safety stop|safety stop|provider\\.refusal|kind=provider_refusal/i.test(\n\t\t\ttext,\n\t\t)\n\t) {\n\t\treturn { area: \"provider\", code: \"refusal\" };\n\t}\n\t// A stale spoofed Claude Code version against a newer model's gate is a client\n\t// configuration fault, not a transcript-shape one: it must not inherit the\n\t// retryable protocol default at the bottom of this function.\n\tif (\n\t\tisClaudeCodeVersionTooOldMessage(text) ||\n\t\tisCodexChatgptAccountUnsupportedModelMessage(text) ||\n\t\tisMissingEsmNamedExportMessage(text)\n\t) {\n\t\treturn { area: \"configuration\", code: \"invalid\" };\n\t}\n\t// Quota/billing exhaustion is checked BEFORE the generic 401/403 auth\n\t// patterns: \"403 ... usage limit for this billing cycle\" is transient per\n\t// cycle and must fail over, not terminate the turn as an auth error.\n\t// Provider-capacity rejections are matched here too: they are transient waits,\n\t// not transcript faults, but their bodies carry no status or limit token, so\n\t// without these they reach the protocol fallback at the bottom and advertise\n\t// the orphan tool_call_id sanitize path. Observed 2026-09-03:\n\t// xai/grok-4.6 \"currently at capacity\" (HTTP 429) and\n\t// anthropic/claude-opus-5 `overloaded_error` / \"Overloaded\" (HTTP 529).\n\tif (\n\t\tisQuotaExhaustionMessage(text) ||\n\t\t/rate.?limit|too many requests|at capacity|high demand|overloaded/i.test(text) ||\n\t\thasStatusCodeLike(text, [429])\n\t) {\n\t\treturn { area: \"provider\", code: \"rate_limit\" };\n\t}\n\tif (\n\t\t/auth|unauthori[sz]ed|forbidden|invalid.?api.?key|no api key|\\/login/i.test(text) ||\n\t\thasStatusCodeLike(text, [401, 403])\n\t) {\n\t\treturn { area: \"provider\", code: \"auth\" };\n\t}\n\t// Gateway/upstream 5xx and dropped streams are transport failures, not\n\t// transcript-shape problems. Classify as network so the guidance points to\n\t// retry/model-switch instead of the protocol sanitize path.\n\tif (isUpstreamUnavailableMessage(text)) {\n\t\treturn { area: \"provider\", code: \"network\" };\n\t}\n\t// Kimi/K3 + OpenAI-compat: orphan tool results after dropped error assistants.\n\t// Sanitize-and-retry (transform-messages drops orphans), not a hard tool fatal.\n\tif (/tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|unknown\\s+tool_call_id/i.test(text)) {\n\t\treturn { area: \"provider\", code: \"protocol\" };\n\t}\n\tif (/tool.+timed? out|tool.+timeout/i.test(text)) return { area: \"tool\", code: \"timeout\" };\n\tif (/\\btool\\b/i.test(text) && !/tool_call_id/i.test(text)) return { area: \"tool\", code: \"fatal\" };\n\tif (/network|fetch failed|connection|socket|websocket|timed? out|timeout|dns|econn|^terminated$/i.test(text)) {\n\t\treturn { area: \"provider\", code: \"network\" };\n\t}\n\treturn { area: \"provider\", code: \"protocol\" };\n}\n\n/**\n * Classify a preflight rejection raised before the provider was called.\n * `hasModel` is false when no model is selected for the session.\n */\nexport function preflightFailureCause(message: string, hasModel: boolean): SessionTerminationCause {\n\tif (!hasModel || /no model|model selected|model is required/i.test(message)) {\n\t\treturn { area: \"configuration\", code: \"invalid\" };\n\t}\n\tif (isQuotaExhaustionMessage(message)) {\n\t\treturn { area: \"provider\", code: \"rate_limit\" };\n\t}\n\tif (/auth|api key|unauthori[sz]ed|forbidden|\\/login/i.test(message) || hasStatusCodeLike(message, [401, 403])) {\n\t\treturn { area: \"provider\", code: \"auth\" };\n\t}\n\tif (isUpstreamUnavailableMessage(message)) {\n\t\treturn { area: \"provider\", code: \"network\" };\n\t}\n\tif (/context.+overflow|context window|too many tokens/i.test(message)) {\n\t\treturn { area: \"provider\", code: \"context_overflow\" };\n\t}\n\tif (/duplicate.?result/i.test(message)) return { area: \"transcript\", code: \"duplicate_result\" };\n\tif (/orphan.?result/i.test(message)) return { area: \"transcript\", code: \"orphan_result\" };\n\tif (/duplicate.?call/i.test(message)) return { area: \"transcript\", code: \"duplicate_call_id\" };\n\tif (/transcript|missing.?result/i.test(message)) return { area: \"transcript\", code: \"missing_result\" };\n\tif (/compaction/i.test(message)) return { area: \"compaction\", code: \"failed\" };\n\tif (/fsync/i.test(message)) return { area: \"persistence\", code: \"fsync_failed\" };\n\tif (/lock/i.test(message)) return { area: \"persistence\", code: \"lock_failed\" };\n\tif (/append|persist|write/i.test(message)) return { area: \"persistence\", code: \"append_failed\" };\n\tif (/tool/i.test(message)) return { area: \"tool\", code: \"fatal\" };\n\treturn { area: \"internal\", code: \"unclassified\" };\n}\n\n/** Classify a value thrown out of the session runtime itself. */\nexport function runtimeFailureCause(error: unknown): SessionTerminationCause {\n\tif (error instanceof RunBudgetExceededError) return { area: \"budget\", code: error.code };\n\tif (error instanceof RunBudgetPolicyError) return { area: \"configuration\", code: \"invalid\" };\n\tconst code = typeof error === \"object\" && error !== null && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\tif (typeof code === \"string\" && PERSISTENCE_ERRNO_CODES.has(code)) {\n\t\treturn { area: \"persistence\", code: \"append_failed\" };\n\t}\n\tconst message = error instanceof Error ? error.message : String(error);\n\tif (isMissingEsmNamedExportMessage(message)) return { area: \"configuration\", code: \"invalid\" };\n\tif (/compaction.+stale|session changed during compaction/i.test(message)) {\n\t\treturn { area: \"compaction\", code: \"stale\" };\n\t}\n\tif (/compaction/i.test(message)) return { area: \"compaction\", code: \"failed\" };\n\treturn { area: \"internal\", code: \"unclassified\" };\n}\n"]}
|
|
@@ -15,10 +15,13 @@
|
|
|
15
15
|
* so guidance points at retry/model-switch rather than transcript sanitize.
|
|
16
16
|
*/
|
|
17
17
|
import { isContextOverflow } from "omk-ai";
|
|
18
|
-
import { isClaudeCodeVersionTooOldMessage, isCodexChatgptAccountUnsupportedModelMessage, isQuotaExhaustionMessage, isUpstreamUnavailableMessage, } from "./provider-resilience.js";
|
|
18
|
+
import { hasStatusCodeLike, isClaudeCodeVersionTooOldMessage, isCodexChatgptAccountUnsupportedModelMessage, isQuotaExhaustionMessage, isUpstreamUnavailableMessage, } from "./provider-resilience.js";
|
|
19
19
|
import { redactSensitiveText } from "./redaction.js";
|
|
20
20
|
import { RunBudgetExceededError, RunBudgetPolicyError } from "./run-budget-policy.js";
|
|
21
21
|
import { MAX_SESSION_TERMINATION_MESSAGE_LENGTH } from "./session-termination.js";
|
|
22
|
+
function isMissingEsmNamedExportMessage(text) {
|
|
23
|
+
return /does not provide an export named/i.test(text);
|
|
24
|
+
}
|
|
22
25
|
/**
|
|
23
26
|
* Errno codes that mean a write could not be durably completed. Anything else
|
|
24
27
|
* (a missing path, for example) is not evidence of a persistence fault.
|
|
@@ -59,7 +62,9 @@ export function providerFailureCause(message, contextWindow) {
|
|
|
59
62
|
// A stale spoofed Claude Code version against a newer model's gate is a client
|
|
60
63
|
// configuration fault, not a transcript-shape one: it must not inherit the
|
|
61
64
|
// retryable protocol default at the bottom of this function.
|
|
62
|
-
if (isClaudeCodeVersionTooOldMessage(text) ||
|
|
65
|
+
if (isClaudeCodeVersionTooOldMessage(text) ||
|
|
66
|
+
isCodexChatgptAccountUnsupportedModelMessage(text) ||
|
|
67
|
+
isMissingEsmNamedExportMessage(text)) {
|
|
63
68
|
return { area: "configuration", code: "invalid" };
|
|
64
69
|
}
|
|
65
70
|
// Quota/billing exhaustion is checked BEFORE the generic 401/403 auth
|
|
@@ -72,10 +77,12 @@ export function providerFailureCause(message, contextWindow) {
|
|
|
72
77
|
// xai/grok-4.6 "currently at capacity" (HTTP 429) and
|
|
73
78
|
// anthropic/claude-opus-5 `overloaded_error` / "Overloaded" (HTTP 529).
|
|
74
79
|
if (isQuotaExhaustionMessage(text) ||
|
|
75
|
-
/rate.?limit|too many requests|
|
|
80
|
+
/rate.?limit|too many requests|at capacity|high demand|overloaded/i.test(text) ||
|
|
81
|
+
hasStatusCodeLike(text, [429])) {
|
|
76
82
|
return { area: "provider", code: "rate_limit" };
|
|
77
83
|
}
|
|
78
|
-
if (/auth|unauthori[sz]ed|forbidden|invalid.?api.?key|no api key
|
|
84
|
+
if (/auth|unauthori[sz]ed|forbidden|invalid.?api.?key|no api key|\/login/i.test(text) ||
|
|
85
|
+
hasStatusCodeLike(text, [401, 403])) {
|
|
79
86
|
return { area: "provider", code: "auth" };
|
|
80
87
|
}
|
|
81
88
|
// Gateway/upstream 5xx and dropped streams are transport failures, not
|
|
@@ -109,7 +116,7 @@ export function preflightFailureCause(message, hasModel) {
|
|
|
109
116
|
if (isQuotaExhaustionMessage(message)) {
|
|
110
117
|
return { area: "provider", code: "rate_limit" };
|
|
111
118
|
}
|
|
112
|
-
if (/auth|api key|unauthori[sz]ed|forbidden
|
|
119
|
+
if (/auth|api key|unauthori[sz]ed|forbidden|\/login/i.test(message) || hasStatusCodeLike(message, [401, 403])) {
|
|
113
120
|
return { area: "provider", code: "auth" };
|
|
114
121
|
}
|
|
115
122
|
if (isUpstreamUnavailableMessage(message)) {
|
|
@@ -149,6 +156,8 @@ export function runtimeFailureCause(error) {
|
|
|
149
156
|
return { area: "persistence", code: "append_failed" };
|
|
150
157
|
}
|
|
151
158
|
const message = error instanceof Error ? error.message : String(error);
|
|
159
|
+
if (isMissingEsmNamedExportMessage(message))
|
|
160
|
+
return { area: "configuration", code: "invalid" };
|
|
152
161
|
if (/compaction.+stale|session changed during compaction/i.test(message)) {
|
|
153
162
|
return { area: "compaction", code: "stale" };
|
|
154
163
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-failure-cause.js","sourceRoot":"","sources":["../../src/core/session-failure-cause.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAyB,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AAClE,OAAO,EACN,gCAAgC,EAChC,4CAA4C,EAC5C,wBAAwB,EACxB,4BAA4B,GAC5B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACtF,OAAO,EAAE,sCAAsC,EAAgC,MAAM,0BAA0B,CAAC;AAEhH;;;GAGG;AACH,MAAM,uBAAuB,GAAwB,IAAI,GAAG,CAAC;IAC5D,QAAQ;IACR,QAAQ;IACR,OAAO;IACP,KAAK;IACL,QA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AG,CAAC,IAAI,CAAC,EAAE,CAAC;QACnE,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,IAAI,EAAE,eAAe,EAAE,CAAC;IACvD,CAAC;IACD,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,IAAI,sDAAsD,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAC1E,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC9C,CAAC;IACD,IAAI,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;IAC/E,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAAA,CAClD","sourcesContent":["/**\n * Failure-text to `SessionTerminationCause` classification.\n *\n * This is the layer *below* `session-termination.ts`: that module turns a cause\n * into a kind/phase/next-action record, while this one decides which cause a\n * provider error, a preflight rejection, or a thrown runtime error represents.\n *\n * The functions are pure so the ordering can be pinned by direct tests. Ordering\n * is load-bearing in two places that are easy to regress:\n *\n * - quota/billing exhaustion is matched *before* the generic 401/403 auth\n * patterns, because `403 ... usage limit for this billing cycle` is\n * transient per cycle and must fail over instead of terminating as auth;\n * - upstream 5xx/dropped streams are matched *before* the protocol fallback,\n * so guidance points at retry/model-switch rather than transcript sanitize.\n */\n\nimport { type AssistantMessage, isContextOverflow } from \"omk-ai\";\nimport {\n\tisClaudeCodeVersionTooOldMessage,\n\tisCodexChatgptAccountUnsupportedModelMessage,\n\tisQuotaExhaustionMessage,\n\tisUpstreamUnavailableMessage,\n} from \"./provider-resilience.ts\";\nimport { redactSensitiveText } from \"./redaction.ts\";\nimport { RunBudgetExceededError, RunBudgetPolicyError } from \"./run-budget-policy.ts\";\nimport { MAX_SESSION_TERMINATION_MESSAGE_LENGTH, type SessionTerminationCause } from \"./session-termination.ts\";\n\n/**\n * Errno codes that mean a write could not be durably completed. Anything else\n * (a missing path, for example) is not evidence of a persistence fault.\n */\nconst PERSISTENCE_ERRNO_CODES: ReadonlySet<string> = new Set([\n\t\"EACCES\",\n\t\"EDQUOT\",\n\t\"EFBIG\",\n\t\"EIO\",\n\t\"EISDIR\",\n\t\"EMFILE\",\n\t\"ENFILE\",\n\t\"ENOSPC\",\n\t\"EPERM\",\n\t\"EROFS\",\n]);\n\n/**\n * Normalize a free-text failure message for the termination record: redact\n * secret-shaped content, drop NUL bytes, and bound the length.\n */\nexport function terminationMessage(value: string | undefined, fallback: string): string {\n\tconst redacted = redactSensitiveText(value?.trim() || fallback)\n\t\t.replace(/\\0/g, \"\")\n\t\t.slice(0, MAX_SESSION_TERMINATION_MESSAGE_LENGTH);\n\treturn redacted || fallback;\n}\n\n/** Classify a failed provider turn from the assistant message it produced. */\nexport function providerFailureCause(message: AssistantMessage, contextWindow: number): SessionTerminationCause {\n\tconst text = message.errorMessage ?? \"\";\n\tif (isContextOverflow(message, contextWindow)) {\n\t\treturn { area: \"provider\", code: \"context_overflow\" };\n\t}\n\t// Fable/Claude often emit stop_reason=refusal on benign turns (false positive).\n\t// Match broadly so we never mislabel these as provider.protocol.\n\tif (\n\t\t/stop_reason\\s*=\\s*(refusal|sensitive)|content\\/safety stop|safety stop|provider\\.refusal|kind=provider_refusal/i.test(\n\t\t\ttext,\n\t\t)\n\t) {\n\t\treturn { area: \"provider\", code: \"refusal\" };\n\t}\n\t// A stale spoofed Claude Code version against a newer model's gate is a client\n\t// configuration fault, not a transcript-shape one: it must not inherit the\n\t// retryable protocol default at the bottom of this function.\n\tif (isClaudeCodeVersionTooOldMessage(text) || isCodexChatgptAccountUnsupportedModelMessage(text)) {\n\t\treturn { area: \"configuration\", code: \"invalid\" };\n\t}\n\t// Quota/billing exhaustion is checked BEFORE the generic 401/403 auth\n\t// patterns: \"403 ... usage limit for this billing cycle\" is transient per\n\t// cycle and must fail over, not terminate the turn as an auth error.\n\t// Provider-capacity rejections are matched here too: they are transient waits,\n\t// not transcript faults, but their bodies carry no status or limit token, so\n\t// without these they reach the protocol fallback at the bottom and advertise\n\t// the orphan tool_call_id sanitize path. Observed 2026-09-03:\n\t// xai/grok-4.6 \"currently at capacity\" (HTTP 429) and\n\t// anthropic/claude-opus-5 `overloaded_error` / \"Overloaded\" (HTTP 529).\n\tif (\n\t\tisQuotaExhaustionMessage(text) ||\n\t\t/rate.?limit|too many requests|429|at capacity|high demand|overloaded/i.test(text)\n\t) {\n\t\treturn { area: \"provider\", code: \"rate_limit\" };\n\t}\n\tif (/auth|unauthori[sz]ed|forbidden|invalid.?api.?key|no api key|401|403|\\/login/i.test(text)) {\n\t\treturn { area: \"provider\", code: \"auth\" };\n\t}\n\t// Gateway/upstream 5xx and dropped streams are transport failures, not\n\t// transcript-shape problems. Classify as network so the guidance points to\n\t// retry/model-switch instead of the protocol sanitize path.\n\tif (isUpstreamUnavailableMessage(text)) {\n\t\treturn { area: \"provider\", code: \"network\" };\n\t}\n\t// Kimi/K3 + OpenAI-compat: orphan tool results after dropped error assistants.\n\t// Sanitize-and-retry (transform-messages drops orphans), not a hard tool fatal.\n\tif (/tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|unknown\\s+tool_call_id/i.test(text)) {\n\t\treturn { area: \"provider\", code: \"protocol\" };\n\t}\n\tif (/tool.+timed? out|tool.+timeout/i.test(text)) return { area: \"tool\", code: \"timeout\" };\n\tif (/\\btool\\b/i.test(text) && !/tool_call_id/i.test(text)) return { area: \"tool\", code: \"fatal\" };\n\tif (/network|fetch failed|connection|socket|websocket|timed? out|timeout|dns|econn|^terminated$/i.test(text)) {\n\t\treturn { area: \"provider\", code: \"network\" };\n\t}\n\treturn { area: \"provider\", code: \"protocol\" };\n}\n\n/**\n * Classify a preflight rejection raised before the provider was called.\n * `hasModel` is false when no model is selected for the session.\n */\nexport function preflightFailureCause(message: string, hasModel: boolean): SessionTerminationCause {\n\tif (!hasModel || /no model|model selected|model is required/i.test(message)) {\n\t\treturn { area: \"configuration\", code: \"invalid\" };\n\t}\n\tif (isQuotaExhaustionMessage(message)) {\n\t\treturn { area: \"provider\", code: \"rate_limit\" };\n\t}\n\tif (/auth|api key|unauthori[sz]ed|forbidden|401|403|\\/login/i.test(message)) {\n\t\treturn { area: \"provider\", code: \"auth\" };\n\t}\n\tif (isUpstreamUnavailableMessage(message)) {\n\t\treturn { area: \"provider\", code: \"network\" };\n\t}\n\tif (/context.+overflow|context window|too many tokens/i.test(message)) {\n\t\treturn { area: \"provider\", code: \"context_overflow\" };\n\t}\n\tif (/duplicate.?result/i.test(message)) return { area: \"transcript\", code: \"duplicate_result\" };\n\tif (/orphan.?result/i.test(message)) return { area: \"transcript\", code: \"orphan_result\" };\n\tif (/duplicate.?call/i.test(message)) return { area: \"transcript\", code: \"duplicate_call_id\" };\n\tif (/transcript|missing.?result/i.test(message)) return { area: \"transcript\", code: \"missing_result\" };\n\tif (/compaction/i.test(message)) return { area: \"compaction\", code: \"failed\" };\n\tif (/fsync/i.test(message)) return { area: \"persistence\", code: \"fsync_failed\" };\n\tif (/lock/i.test(message)) return { area: \"persistence\", code: \"lock_failed\" };\n\tif (/append|persist|write/i.test(message)) return { area: \"persistence\", code: \"append_failed\" };\n\tif (/tool/i.test(message)) return { area: \"tool\", code: \"fatal\" };\n\treturn { area: \"internal\", code: \"unclassified\" };\n}\n\n/** Classify a value thrown out of the session runtime itself. */\nexport function runtimeFailureCause(error: unknown): SessionTerminationCause {\n\tif (error instanceof RunBudgetExceededError) return { area: \"budget\", code: error.code };\n\tif (error instanceof RunBudgetPolicyError) return { area: \"configuration\", code: \"invalid\" };\n\tconst code = typeof error === \"object\" && error !== null && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\tif (typeof code === \"string\" && PERSISTENCE_ERRNO_CODES.has(code)) {\n\t\treturn { area: \"persistence\", code: \"append_failed\" };\n\t}\n\tconst message = error instanceof Error ? error.message : String(error);\n\tif (/compaction.+stale|session changed during compaction/i.test(message)) {\n\t\treturn { area: \"compaction\", code: \"stale\" };\n\t}\n\tif (/compaction/i.test(message)) return { area: \"compaction\", code: \"failed\" };\n\treturn { area: \"internal\", code: \"unclassified\" };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-failure-cause.js","sourceRoot":"","sources":["../../src/core/session-failure-cause.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAyB,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AAClE,OAAO,EACN,iBAAiB,EACjB,gCAAgC,EAChC,4CAA4C,EAC5C,wBAAwB,EACxB,4BAA4B,GAC5B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACtF,OAAO,EAAE,sCAAsC,EAAgC,MAAM,0BAA0B,CAAC;AAEhH,SAAS,8BAA8B,CAAC,IAAY,EAAW;IAC9D,OAAO,mCAAmC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACtD;AAED;;;GAGG;AACH,MAAM,uBAAuB,GAAwB,IAAI,GAAG,CAAC;IAC5D,QAAQ;IACR,QAAQ;IACR,OAAO;IACP,KAAK;IACL,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,OAAO;IACP,OAAO;CACP,CAAC,CAAC;AAEH;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAyB,EAAE,QAAgB,EAAU;IACvF,MAAM,QAAQ,GAAG,mBAAmB,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,QAAQ,CAAC;SAC7D,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;SAClB,KAAK,CAAC,CAAC,EAAE,sCAAsC,CAAC,CAAC;IACnD,OAAO,QA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D,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,IAAI,8BAA8B,CAAC,OAAO,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,eAAe,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;IAC/F,IAAI,sDAAsD,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAC1E,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC9C,CAAC;IACD,IAAI,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;IAC/E,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAAA,CAClD","sourcesContent":["/**\n * Failure-text to `SessionTerminationCause` classification.\n *\n * This is the layer *below* `session-termination.ts`: that module turns a cause\n * into a kind/phase/next-action record, while this one decides which cause a\n * provider error, a preflight rejection, or a thrown runtime error represents.\n *\n * The functions are pure so the ordering can be pinned by direct tests. Ordering\n * is load-bearing in two places that are easy to regress:\n *\n * - quota/billing exhaustion is matched *before* the generic 401/403 auth\n * patterns, because `403 ... usage limit for this billing cycle` is\n * transient per cycle and must fail over instead of terminating as auth;\n * - upstream 5xx/dropped streams are matched *before* the protocol fallback,\n * so guidance points at retry/model-switch rather than transcript sanitize.\n */\n\nimport { type AssistantMessage, isContextOverflow } from \"omk-ai\";\nimport {\n\thasStatusCodeLike,\n\tisClaudeCodeVersionTooOldMessage,\n\tisCodexChatgptAccountUnsupportedModelMessage,\n\tisQuotaExhaustionMessage,\n\tisUpstreamUnavailableMessage,\n} from \"./provider-resilience.ts\";\nimport { redactSensitiveText } from \"./redaction.ts\";\nimport { RunBudgetExceededError, RunBudgetPolicyError } from \"./run-budget-policy.ts\";\nimport { MAX_SESSION_TERMINATION_MESSAGE_LENGTH, type SessionTerminationCause } from \"./session-termination.ts\";\n\nfunction isMissingEsmNamedExportMessage(text: string): boolean {\n\treturn /does not provide an export named/i.test(text);\n}\n\n/**\n * Errno codes that mean a write could not be durably completed. Anything else\n * (a missing path, for example) is not evidence of a persistence fault.\n */\nconst PERSISTENCE_ERRNO_CODES: ReadonlySet<string> = new Set([\n\t\"EACCES\",\n\t\"EDQUOT\",\n\t\"EFBIG\",\n\t\"EIO\",\n\t\"EISDIR\",\n\t\"EMFILE\",\n\t\"ENFILE\",\n\t\"ENOSPC\",\n\t\"EPERM\",\n\t\"EROFS\",\n]);\n\n/**\n * Normalize a free-text failure message for the termination record: redact\n * secret-shaped content, drop NUL bytes, and bound the length.\n */\nexport function terminationMessage(value: string | undefined, fallback: string): string {\n\tconst redacted = redactSensitiveText(value?.trim() || fallback)\n\t\t.replace(/\\0/g, \"\")\n\t\t.slice(0, MAX_SESSION_TERMINATION_MESSAGE_LENGTH);\n\treturn redacted || fallback;\n}\n\n/** Classify a failed provider turn from the assistant message it produced. */\nexport function providerFailureCause(message: AssistantMessage, contextWindow: number): SessionTerminationCause {\n\tconst text = message.errorMessage ?? \"\";\n\tif (isContextOverflow(message, contextWindow)) {\n\t\treturn { area: \"provider\", code: \"context_overflow\" };\n\t}\n\t// Fable/Claude often emit stop_reason=refusal on benign turns (false positive).\n\t// Match broadly so we never mislabel these as provider.protocol.\n\tif (\n\t\t/stop_reason\\s*=\\s*(refusal|sensitive)|content\\/safety stop|safety stop|provider\\.refusal|kind=provider_refusal/i.test(\n\t\t\ttext,\n\t\t)\n\t) {\n\t\treturn { area: \"provider\", code: \"refusal\" };\n\t}\n\t// A stale spoofed Claude Code version against a newer model's gate is a client\n\t// configuration fault, not a transcript-shape one: it must not inherit the\n\t// retryable protocol default at the bottom of this function.\n\tif (\n\t\tisClaudeCodeVersionTooOldMessage(text) ||\n\t\tisCodexChatgptAccountUnsupportedModelMessage(text) ||\n\t\tisMissingEsmNamedExportMessage(text)\n\t) {\n\t\treturn { area: \"configuration\", code: \"invalid\" };\n\t}\n\t// Quota/billing exhaustion is checked BEFORE the generic 401/403 auth\n\t// patterns: \"403 ... usage limit for this billing cycle\" is transient per\n\t// cycle and must fail over, not terminate the turn as an auth error.\n\t// Provider-capacity rejections are matched here too: they are transient waits,\n\t// not transcript faults, but their bodies carry no status or limit token, so\n\t// without these they reach the protocol fallback at the bottom and advertise\n\t// the orphan tool_call_id sanitize path. Observed 2026-09-03:\n\t// xai/grok-4.6 \"currently at capacity\" (HTTP 429) and\n\t// anthropic/claude-opus-5 `overloaded_error` / \"Overloaded\" (HTTP 529).\n\tif (\n\t\tisQuotaExhaustionMessage(text) ||\n\t\t/rate.?limit|too many requests|at capacity|high demand|overloaded/i.test(text) ||\n\t\thasStatusCodeLike(text, [429])\n\t) {\n\t\treturn { area: \"provider\", code: \"rate_limit\" };\n\t}\n\tif (\n\t\t/auth|unauthori[sz]ed|forbidden|invalid.?api.?key|no api key|\\/login/i.test(text) ||\n\t\thasStatusCodeLike(text, [401, 403])\n\t) {\n\t\treturn { area: \"provider\", code: \"auth\" };\n\t}\n\t// Gateway/upstream 5xx and dropped streams are transport failures, not\n\t// transcript-shape problems. Classify as network so the guidance points to\n\t// retry/model-switch instead of the protocol sanitize path.\n\tif (isUpstreamUnavailableMessage(text)) {\n\t\treturn { area: \"provider\", code: \"network\" };\n\t}\n\t// Kimi/K3 + OpenAI-compat: orphan tool results after dropped error assistants.\n\t// Sanitize-and-retry (transform-messages drops orphans), not a hard tool fatal.\n\tif (/tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|unknown\\s+tool_call_id/i.test(text)) {\n\t\treturn { area: \"provider\", code: \"protocol\" };\n\t}\n\tif (/tool.+timed? out|tool.+timeout/i.test(text)) return { area: \"tool\", code: \"timeout\" };\n\tif (/\\btool\\b/i.test(text) && !/tool_call_id/i.test(text)) return { area: \"tool\", code: \"fatal\" };\n\tif (/network|fetch failed|connection|socket|websocket|timed? out|timeout|dns|econn|^terminated$/i.test(text)) {\n\t\treturn { area: \"provider\", code: \"network\" };\n\t}\n\treturn { area: \"provider\", code: \"protocol\" };\n}\n\n/**\n * Classify a preflight rejection raised before the provider was called.\n * `hasModel` is false when no model is selected for the session.\n */\nexport function preflightFailureCause(message: string, hasModel: boolean): SessionTerminationCause {\n\tif (!hasModel || /no model|model selected|model is required/i.test(message)) {\n\t\treturn { area: \"configuration\", code: \"invalid\" };\n\t}\n\tif (isQuotaExhaustionMessage(message)) {\n\t\treturn { area: \"provider\", code: \"rate_limit\" };\n\t}\n\tif (/auth|api key|unauthori[sz]ed|forbidden|\\/login/i.test(message) || hasStatusCodeLike(message, [401, 403])) {\n\t\treturn { area: \"provider\", code: \"auth\" };\n\t}\n\tif (isUpstreamUnavailableMessage(message)) {\n\t\treturn { area: \"provider\", code: \"network\" };\n\t}\n\tif (/context.+overflow|context window|too many tokens/i.test(message)) {\n\t\treturn { area: \"provider\", code: \"context_overflow\" };\n\t}\n\tif (/duplicate.?result/i.test(message)) return { area: \"transcript\", code: \"duplicate_result\" };\n\tif (/orphan.?result/i.test(message)) return { area: \"transcript\", code: \"orphan_result\" };\n\tif (/duplicate.?call/i.test(message)) return { area: \"transcript\", code: \"duplicate_call_id\" };\n\tif (/transcript|missing.?result/i.test(message)) return { area: \"transcript\", code: \"missing_result\" };\n\tif (/compaction/i.test(message)) return { area: \"compaction\", code: \"failed\" };\n\tif (/fsync/i.test(message)) return { area: \"persistence\", code: \"fsync_failed\" };\n\tif (/lock/i.test(message)) return { area: \"persistence\", code: \"lock_failed\" };\n\tif (/append|persist|write/i.test(message)) return { area: \"persistence\", code: \"append_failed\" };\n\tif (/tool/i.test(message)) return { area: \"tool\", code: \"fatal\" };\n\treturn { area: \"internal\", code: \"unclassified\" };\n}\n\n/** Classify a value thrown out of the session runtime itself. */\nexport function runtimeFailureCause(error: unknown): SessionTerminationCause {\n\tif (error instanceof RunBudgetExceededError) return { area: \"budget\", code: error.code };\n\tif (error instanceof RunBudgetPolicyError) return { area: \"configuration\", code: \"invalid\" };\n\tconst code = typeof error === \"object\" && error !== null && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\tif (typeof code === \"string\" && PERSISTENCE_ERRNO_CODES.has(code)) {\n\t\treturn { area: \"persistence\", code: \"append_failed\" };\n\t}\n\tconst message = error instanceof Error ? error.message : String(error);\n\tif (isMissingEsmNamedExportMessage(message)) return { area: \"configuration\", code: \"invalid\" };\n\tif (/compaction.+stale|session changed during compaction/i.test(message)) {\n\t\treturn { area: \"compaction\", code: \"stale\" };\n\t}\n\tif (/compaction/i.test(message)) return { area: \"compaction\", code: \"failed\" };\n\treturn { area: \"internal\", code: \"unclassified\" };\n}\n"]}
|
|
@@ -14,12 +14,18 @@ export declare class SessionPromptLifecycle {
|
|
|
14
14
|
auditsLateSettlement?: () => boolean;
|
|
15
15
|
});
|
|
16
16
|
assertIdle(): void;
|
|
17
|
+
/** §16.2 — currently open prompt run id, if any. */
|
|
18
|
+
get activePromptRunId(): string | undefined;
|
|
17
19
|
begin(promptRunId: string): {
|
|
18
20
|
finish: (outcome: PromptSettlementOutcome, notify: (event: PromptSettledEvent) => void) => void;
|
|
19
21
|
};
|
|
20
22
|
wrapTool(tool: AgentTool): AgentTool;
|
|
21
23
|
/** Called after the root producer drains, or after late-settlement event delivery. */
|
|
22
24
|
flush(): void;
|
|
25
|
+
/** Spec 020 Req3.1 — child가 승인된 spawn 직전 +1. 반환된 release()를 정확히 한 번 호출. */
|
|
26
|
+
noteDetachedChild(): () => void;
|
|
27
|
+
/** Spec 020 Req3.1 — shard가 승인된 spawn 직전 +1. */
|
|
28
|
+
noteDetachedShard(): () => void;
|
|
23
29
|
dispose(): void;
|
|
24
30
|
}
|
|
25
31
|
//# sourceMappingURL=session-prompt-lifecycle.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-prompt-lifecycle.d.ts","sourceRoot":"","sources":["../../src/core/session-prompt-lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,EAG5B,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"session-prompt-lifecycle.d.ts","sourceRoot":"","sources":["../../src/core/session-prompt-lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,EAG5B,MAAM,wBAAwB,CAAC;AAYhC,qBAAa,wBAAyB,SAAQ,KAAK;IAClD,cAGC;CACD;AAED,oFAAoF;AACpF,qBAAa,sBAAsB;IAClC,OAAO,CAAC,KAAK,CAA0B;IACvC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAgB;IAC1C,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAgB;IAErD,YAAY,OAAO,GAAE;QAAE,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;QAAC,oBAAoB,CAAC,EAAE,MAAM,OAAO,CAAA;KAAO,EAG5F;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,uDAAoD;IACpD,IAAI,iBAAiB,IAAI,MAAM,GAAG,SAAS,CAE1C;IAED,KAAK,CAAC,WAAW,EAAE,MAAM,GAAG;QAC3B,MAAM,EAAE,CAAC,OAAO,EAAE,uBAAuB,EAAE,MAAM,EAAE,CAAC,KAAK,EAAE,kBAAkB,KAAK,IAAI,KAAK,IAAI,CAAC;KAChG,CAiBA;IAED,QAAQ,CAAC,IAAI,EAAE,SAAS,GAAG,SAAS,CA6BnC;IAED,sFAAsF;IACtF,KAAK,IAAI,IAAI,CAkBZ;IAED,+GAA2E;IAC3E,iBAAiB,IAAI,MAAM,IAAI,CAW9B;IAED,8DAAgD;IAChD,iBAAiB,IAAI,MAAM,IAAI,CAW9B;IAED,OAAO,IAAI,IAAI,CAGd;CACD","sourcesContent":["import type { AgentTool } from \"omk-agent-core\";\nimport {\n\tcreatePromptSettlementState,\n\ttype PromptSettledEvent,\n\ttype PromptSettlementOutcome,\n\treducePromptSettlement,\n\tsettlePromptIfReady,\n} from \"./prompt-settlement.ts\";\n\ninterface PromptOwner {\n\treadonly promptRunId: string;\n\treadonly startedAt: number;\n\treadonly executions: Set<symbol>;\n\t/** Spec 020 Req3 — detach된 자식/샤드의 live 카운터 (심볼 executions와 별도). */\n\tdetachedChildren: number;\n\tdetachedShards: number;\n\tterminal?: { readonly outcome: PromptSettlementOutcome; readonly notify: (event: PromptSettledEvent) => void };\n}\n\nexport class PromptExecutionBusyError extends Error {\n\tconstructor() {\n\t\tsuper(\"Agent is already processing or has unsettled tool execution. Wait for actual termination.\");\n\t\tthis.name = \"PromptExecutionBusyError\";\n\t}\n}\n\n/** Session-local ownership, not a durable journal or a detached-process sandbox. */\nexport class SessionPromptLifecycle {\n\tprivate owner: PromptOwner | undefined;\n\tprivate disposed = false;\n\tprivate readonly canSettle: () => boolean;\n\tprivate readonly auditsLateSettlement: () => boolean;\n\n\tconstructor(options: { canSettle?: () => boolean; auditsLateSettlement?: () => boolean } = {}) {\n\t\tthis.canSettle = options.canSettle ?? (() => true);\n\t\tthis.auditsLateSettlement = options.auditsLateSettlement ?? (() => true);\n\t}\n\n\tassertIdle(): void {\n\t\tif (this.owner !== undefined || this.disposed) throw new PromptExecutionBusyError();\n\t}\n\n\t/** §16.2 — currently open prompt run id, if any. */\n\tget activePromptRunId(): string | undefined {\n\t\treturn this.owner?.promptRunId;\n\t}\n\n\tbegin(promptRunId: string): {\n\t\tfinish: (outcome: PromptSettlementOutcome, notify: (event: PromptSettledEvent) => void) => void;\n\t} {\n\t\tthis.assertIdle();\n\t\tconst owner: PromptOwner = {\n\t\t\tpromptRunId,\n\t\t\tstartedAt: performance.now(),\n\t\t\texecutions: new Set(),\n\t\t\tdetachedChildren: 0,\n\t\t\tdetachedShards: 0,\n\t\t};\n\t\tthis.owner = owner;\n\t\treturn {\n\t\t\tfinish: (outcome, notify) => {\n\t\t\t\tif (owner.terminal !== undefined) return;\n\t\t\t\towner.terminal = { outcome, notify };\n\t\t\t\tthis.flush();\n\t\t\t},\n\t\t};\n\t}\n\n\twrapTool(tool: AgentTool): AgentTool {\n\t\treturn {\n\t\t\tname: tool.name,\n\t\t\tlabel: tool.label,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters,\n\t\t\tprepareArguments: tool.prepareArguments,\n\t\t\texecutionMode: tool.executionMode,\n\t\t\tresourceClaims: tool.resourceClaims,\n\t\t\t// A spread would evaluate and freeze the context-sensitive timeout too early.\n\t\t\tget timeoutMs() {\n\t\t\t\treturn tool.timeoutMs;\n\t\t\t},\n\t\t\texecute: async (...args) => {\n\t\t\t\tconst owner = this.owner;\n\t\t\t\tif (this.disposed || owner?.terminal !== undefined) throw new PromptExecutionBusyError();\n\t\t\t\t// Runtime-owned identities cannot collide with reused model toolCallIds.\n\t\t\t\tconst execution = Symbol();\n\t\t\t\tconst requiresAudit = this.auditsLateSettlement();\n\t\t\t\towner?.executions.add(execution);\n\t\t\t\ttry {\n\t\t\t\t\treturn await tool.execute(...args);\n\t\t\t\t} finally {\n\t\t\t\t\towner?.executions.delete(execution);\n\t\t\t\t\t// Audit mode flushes only after the late event has been delivered.\n\t\t\t\t\tif (!requiresAudit) this.flush();\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\n\t/** Called after the root producer drains, or after late-settlement event delivery. */\n\tflush(): void {\n\t\tconst owner = this.owner;\n\t\tif (\n\t\t\t!owner?.terminal ||\n\t\t\towner.executions.size > 0 ||\n\t\t\towner.detachedChildren > 0 ||\n\t\t\towner.detachedShards > 0 ||\n\t\t\tthis.disposed ||\n\t\t\t!this.canSettle()\n\t\t)\n\t\t\treturn;\n\t\tconst state = reducePromptSettlement(createPromptSettlementState(owner.promptRunId, owner.startedAt), {\n\t\t\tkind: \"terminal\",\n\t\t\toutcome: owner.terminal.outcome,\n\t\t});\n\t\tconst { event } = settlePromptIfReady(state, performance.now());\n\t\tthis.owner = undefined;\n\t\tif (event !== null) owner.terminal.notify(event);\n\t}\n\n\t/** Spec 020 Req3.1 — child가 승인된 spawn 직전 +1. 반환된 release()를 정확히 한 번 호출. */\n\tnoteDetachedChild(): () => void {\n\t\tconst owner = this.owner;\n\t\tif (!owner) return () => {};\n\t\towner.detachedChildren += 1;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\towner.detachedChildren = Math.max(0, owner.detachedChildren - 1);\n\t\t\tthis.flush();\n\t\t};\n\t}\n\n\t/** Spec 020 Req3.1 — shard가 승인된 spawn 직전 +1. */\n\tnoteDetachedShard(): () => void {\n\t\tconst owner = this.owner;\n\t\tif (!owner) return () => {};\n\t\towner.detachedShards += 1;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\towner.detachedShards = Math.max(0, owner.detachedShards - 1);\n\t\t\tthis.flush();\n\t\t};\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.owner = undefined;\n\t}\n}\n"]}
|
|
@@ -19,9 +19,19 @@ export class SessionPromptLifecycle {
|
|
|
19
19
|
if (this.owner !== undefined || this.disposed)
|
|
20
20
|
throw new PromptExecutionBusyError();
|
|
21
21
|
}
|
|
22
|
+
/** §16.2 — currently open prompt run id, if any. */
|
|
23
|
+
get activePromptRunId() {
|
|
24
|
+
return this.owner?.promptRunId;
|
|
25
|
+
}
|
|
22
26
|
begin(promptRunId) {
|
|
23
27
|
this.assertIdle();
|
|
24
|
-
const owner = {
|
|
28
|
+
const owner = {
|
|
29
|
+
promptRunId,
|
|
30
|
+
startedAt: performance.now(),
|
|
31
|
+
executions: new Set(),
|
|
32
|
+
detachedChildren: 0,
|
|
33
|
+
detachedShards: 0,
|
|
34
|
+
};
|
|
25
35
|
this.owner = owner;
|
|
26
36
|
return {
|
|
27
37
|
finish: (outcome, notify) => {
|
|
@@ -68,7 +78,12 @@ export class SessionPromptLifecycle {
|
|
|
68
78
|
/** Called after the root producer drains, or after late-settlement event delivery. */
|
|
69
79
|
flush() {
|
|
70
80
|
const owner = this.owner;
|
|
71
|
-
if (!owner?.terminal ||
|
|
81
|
+
if (!owner?.terminal ||
|
|
82
|
+
owner.executions.size > 0 ||
|
|
83
|
+
owner.detachedChildren > 0 ||
|
|
84
|
+
owner.detachedShards > 0 ||
|
|
85
|
+
this.disposed ||
|
|
86
|
+
!this.canSettle())
|
|
72
87
|
return;
|
|
73
88
|
const state = reducePromptSettlement(createPromptSettlementState(owner.promptRunId, owner.startedAt), {
|
|
74
89
|
kind: "terminal",
|
|
@@ -79,6 +94,36 @@ export class SessionPromptLifecycle {
|
|
|
79
94
|
if (event !== null)
|
|
80
95
|
owner.terminal.notify(event);
|
|
81
96
|
}
|
|
97
|
+
/** Spec 020 Req3.1 — child가 승인된 spawn 직전 +1. 반환된 release()를 정확히 한 번 호출. */
|
|
98
|
+
noteDetachedChild() {
|
|
99
|
+
const owner = this.owner;
|
|
100
|
+
if (!owner)
|
|
101
|
+
return () => { };
|
|
102
|
+
owner.detachedChildren += 1;
|
|
103
|
+
let released = false;
|
|
104
|
+
return () => {
|
|
105
|
+
if (released)
|
|
106
|
+
return;
|
|
107
|
+
released = true;
|
|
108
|
+
owner.detachedChildren = Math.max(0, owner.detachedChildren - 1);
|
|
109
|
+
this.flush();
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** Spec 020 Req3.1 — shard가 승인된 spawn 직전 +1. */
|
|
113
|
+
noteDetachedShard() {
|
|
114
|
+
const owner = this.owner;
|
|
115
|
+
if (!owner)
|
|
116
|
+
return () => { };
|
|
117
|
+
owner.detachedShards += 1;
|
|
118
|
+
let released = false;
|
|
119
|
+
return () => {
|
|
120
|
+
if (released)
|
|
121
|
+
return;
|
|
122
|
+
released = true;
|
|
123
|
+
owner.detachedShards = Math.max(0, owner.detachedShards - 1);
|
|
124
|
+
this.flush();
|
|
125
|
+
};
|
|
126
|
+
}
|
|
82
127
|
dispose() {
|
|
83
128
|
this.disposed = true;
|
|
84
129
|
this.owner = undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-prompt-lifecycle.js","sourceRoot":"","sources":["../../src/core/session-prompt-lifecycle.ts"],"names":[],"mappings":"AACA,OAAO,EACN,2BAA2B,EAG3B,sBAAsB,EACtB,mBAAmB,GACnB,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"session-prompt-lifecycle.js","sourceRoot":"","sources":["../../src/core/session-prompt-lifecycle.ts"],"names":[],"mappings":"AACA,OAAO,EACN,2BAA2B,EAG3B,sBAAsB,EACtB,mBAAmB,GACnB,MAAM,wBAAwB,CAAC;AAYhC,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAClD,cAAc;QACb,KAAK,CAAC,2FAA2F,CAAC,CAAC;QACnG,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;IAAA,CACvC;CACD;AAED,oFAAoF;AACpF,MAAM,OAAO,sBAAsB;IAC1B,KAAK,CAA0B;IAC/B,QAAQ,GAAG,KAAK,CAAC;IACR,SAAS,CAAgB;IACzB,oBAAoB,CAAgB;IAErD,YAAY,OAAO,GAAwE,EAAE,EAAE;QAC9F,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;QACnD,IAAI,CAAC,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;IAAA,CACzE;IAED,UAAU,GAAS;QAClB,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,wBAAwB,EAAE,CAAC;IAAA,CACpF;IAED,uDAAoD;IACp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ype PromptSettlementOutcome,\n\treducePromptSettlement,\n\tsettlePromptIfReady,\n} from \"./prompt-settlement.ts\";\n\ninterface PromptOwner {\n\treadonly promptRunId: string;\n\treadonly startedAt: number;\n\treadonly executions: Set<symbol>;\n\t/** Spec 020 Req3 — detach된 자식/샤드의 live 카운터 (심볼 executions와 별도). */\n\tdetachedChildren: number;\n\tdetachedShards: number;\n\tterminal?: { readonly outcome: PromptSettlementOutcome; readonly notify: (event: PromptSettledEvent) => void };\n}\n\nexport class PromptExecutionBusyError extends Error {\n\tconstructor() {\n\t\tsuper(\"Agent is already processing or has unsettled tool execution. Wait for actual termination.\");\n\t\tthis.name = \"PromptExecutionBusyError\";\n\t}\n}\n\n/** Session-local ownership, not a durable journal or a detached-process sandbox. */\nexport class SessionPromptLifecycle {\n\tprivate owner: PromptOwner | undefined;\n\tprivate disposed = false;\n\tprivate readonly canSettle: () => boolean;\n\tprivate readonly auditsLateSettlement: () => boolean;\n\n\tconstructor(options: { canSettle?: () => boolean; auditsLateSettlement?: () => boolean } = {}) {\n\t\tthis.canSettle = options.canSettle ?? (() => true);\n\t\tthis.auditsLateSettlement = options.auditsLateSettlement ?? (() => true);\n\t}\n\n\tassertIdle(): void {\n\t\tif (this.owner !== undefined || this.disposed) throw new PromptExecutionBusyError();\n\t}\n\n\t/** §16.2 — currently open prompt run id, if any. */\n\tget activePromptRunId(): string | undefined {\n\t\treturn this.owner?.promptRunId;\n\t}\n\n\tbegin(promptRunId: string): {\n\t\tfinish: (outcome: PromptSettlementOutcome, notify: (event: PromptSettledEvent) => void) => void;\n\t} {\n\t\tthis.assertIdle();\n\t\tconst owner: PromptOwner = {\n\t\t\tpromptRunId,\n\t\t\tstartedAt: performance.now(),\n\t\t\texecutions: new Set(),\n\t\t\tdetachedChildren: 0,\n\t\t\tdetachedShards: 0,\n\t\t};\n\t\tthis.owner = owner;\n\t\treturn {\n\t\t\tfinish: (outcome, notify) => {\n\t\t\t\tif (owner.terminal !== undefined) return;\n\t\t\t\towner.terminal = { outcome, notify };\n\t\t\t\tthis.flush();\n\t\t\t},\n\t\t};\n\t}\n\n\twrapTool(tool: AgentTool): AgentTool {\n\t\treturn {\n\t\t\tname: tool.name,\n\t\t\tlabel: tool.label,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters,\n\t\t\tprepareArguments: tool.prepareArguments,\n\t\t\texecutionMode: tool.executionMode,\n\t\t\tresourceClaims: tool.resourceClaims,\n\t\t\t// A spread would evaluate and freeze the context-sensitive timeout too early.\n\t\t\tget timeoutMs() {\n\t\t\t\treturn tool.timeoutMs;\n\t\t\t},\n\t\t\texecute: async (...args) => {\n\t\t\t\tconst owner = this.owner;\n\t\t\t\tif (this.disposed || owner?.terminal !== undefined) throw new PromptExecutionBusyError();\n\t\t\t\t// Runtime-owned identities cannot collide with reused model toolCallIds.\n\t\t\t\tconst execution = Symbol();\n\t\t\t\tconst requiresAudit = this.auditsLateSettlement();\n\t\t\t\towner?.executions.add(execution);\n\t\t\t\ttry {\n\t\t\t\t\treturn await tool.execute(...args);\n\t\t\t\t} finally {\n\t\t\t\t\towner?.executions.delete(execution);\n\t\t\t\t\t// Audit mode flushes only after the late event has been delivered.\n\t\t\t\t\tif (!requiresAudit) this.flush();\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\n\t/** Called after the root producer drains, or after late-settlement event delivery. */\n\tflush(): void {\n\t\tconst owner = this.owner;\n\t\tif (\n\t\t\t!owner?.terminal ||\n\t\t\towner.executions.size > 0 ||\n\t\t\towner.detachedChildren > 0 ||\n\t\t\towner.detachedShards > 0 ||\n\t\t\tthis.disposed ||\n\t\t\t!this.canSettle()\n\t\t)\n\t\t\treturn;\n\t\tconst state = reducePromptSettlement(createPromptSettlementState(owner.promptRunId, owner.startedAt), {\n\t\t\tkind: \"terminal\",\n\t\t\toutcome: owner.terminal.outcome,\n\t\t});\n\t\tconst { event } = settlePromptIfReady(state, performance.now());\n\t\tthis.owner = undefined;\n\t\tif (event !== null) owner.terminal.notify(event);\n\t}\n\n\t/** Spec 020 Req3.1 — child가 승인된 spawn 직전 +1. 반환된 release()를 정확히 한 번 호출. */\n\tnoteDetachedChild(): () => void {\n\t\tconst owner = this.owner;\n\t\tif (!owner) return () => {};\n\t\towner.detachedChildren += 1;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\towner.detachedChildren = Math.max(0, owner.detachedChildren - 1);\n\t\t\tthis.flush();\n\t\t};\n\t}\n\n\t/** Spec 020 Req3.1 — shard가 승인된 spawn 직전 +1. */\n\tnoteDetachedShard(): () => void {\n\t\tconst owner = this.owner;\n\t\tif (!owner) return () => {};\n\t\towner.detachedShards += 1;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\towner.detachedShards = Math.max(0, owner.detachedShards - 1);\n\t\t\tthis.flush();\n\t\t};\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.owner = undefined;\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-termination.d.ts","sourceRoot":"","sources":["../../src/core/session-termination.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,+BAA+B,EAOpC,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,EAO5B,MAAM,gCAAgC,CAAC;AAExC,cAAc,gCAAgC,CAAC;AAE/C,qBAAa,uBAAwB,SAAQ,KAAK;IACjD,QAAQ,CAAC,WAAW,EAAE,kBAAkB,CAAC;IAEzC,YAAY,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,kBAAkB,EAI3D;CACD;AA4JD,wBAAgB,gCAAgC,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,oBAAoB,GAAG,uBAAuB,CAWrH;AA8BD,oFAAoF;AACpF,wBAAgB,mCAAmC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAYzE;AAmOD,wEAAwE;AACxE,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,kBAAkB,GAAG,MAAM,CAchF;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,+BAA+B,GAAG,kBAAkB,CA2CrG","sourcesContent":["import { RUN_BUDGET_STOP_CODES } from \"./run-budget-policy.ts\";\nimport {\n\ttype ClassifySessionTerminationInput,\n\ttype CompactionTerminationCauseCode,\n\tMAX_SESSION_TERMINATION_MESSAGE_LENGTH,\n\ttype PersistenceTerminationCauseCode,\n\ttype ProviderTerminationCauseCode,\n\ttype ResourceTerminationCauseCode,\n\tSESSION_TERMINATION_SCHEMA_VERSION,\n\ttype SessionProcessSignal,\n\ttype SessionTermination,\n\ttype SessionTerminationCause,\n\ttype SessionTerminationCauseCode,\n\ttype SessionTerminationKind,\n\ttype SessionTerminationPhase,\n\ttype SessionTerminationSource,\n\ttype ToolTerminationCauseCode,\n\ttype TranscriptTerminationCauseCode,\n} from \"./session-termination-types.ts\";\n\nexport * from \"./session-termination-types.ts\";\n\nexport class SessionTerminationError extends Error {\n\treadonly termination: SessionTermination;\n\n\tconstructor(message: string, termination: SessionTermination) {\n\t\tsuper(message);\n\t\tthis.name = \"SessionTerminationError\";\n\t\tthis.termination = termination;\n\t}\n}\n\ninterface Classification {\n\treadonly kind: SessionTerminationKind;\n\treadonly phase: SessionTerminationPhase;\n\treadonly causeCode: SessionTerminationCauseCode;\n\treadonly retryable: boolean;\n\treadonly processSignal?: SessionProcessSignal;\n\treadonly transcriptIssue?: TranscriptTerminationCauseCode;\n}\n\nconst CREDENTIAL_SHAPES = [\n\t/-----BEGIN [A-Z ]*PRIVATE KEY-----/i,\n\t/\\b(?:sk-[A-Za-z0-9_-]{16,}|github_pat_[A-Za-z0-9_]{16,}|gh[pousr]_[A-Za-z0-9]{16,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[A-Z0-9]{16})\\b/,\n\t/\\bBearer\\s+[A-Za-z0-9._~+/-]{8,}={0,2}\\b/i,\n\t/\\beyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\b/,\n\t/(?:^|[^A-Za-z0-9])(?:[A-Za-z0-9]+[_-])*(?:authorization|api[-_ ]?key|access[-_ ]?token|token|password|secret(?:[-_ ]?key)?|private[-_ ]?key|cookie)[\"']?\\s*[:=]/i,\n] as const;\n\nconst TOP_LEVEL_KEYS = new Set([\n\t\"sessionId\",\n\t\"runId\",\n\t\"timestamp\",\n\t\"source\",\n\t\"message\",\n\t\"cause\",\n\t\"sideEffects\",\n\t\"retryAfterMs\",\n\t\"provider\",\n\t\"model\",\n\t\"toolCallId\",\n\t\"toolName\",\n]);\nconst PROVIDER_CAUSE_CODES = new Set<ProviderTerminationCauseCode>([\n\t\"abort\",\n\t\"auth\",\n\t\"rate_limit\",\n\t\"network\",\n\t\"protocol\",\n\t\"refusal\",\n\t\"context_overflow\",\n]);\nconst TOOL_CAUSE_CODES = new Set<ToolTerminationCauseCode>([\"timeout\", \"fatal\"]);\nconst RESOURCE_CAUSE_CODES = new Set<ResourceTerminationCauseCode>([\n\t\"memory\",\n\t\"disk\",\n\t\"cpu\",\n\t\"heap\",\n\t\"probe_unavailable\",\n\t\"queue_overflow\",\n]);\nconst COMPACTION_CAUSE_CODES = new Set<CompactionTerminationCauseCode>([\n\t\"aborted\",\n\t\"failed\",\n\t\"stale\",\n\t\"quota_exhausted\",\n]);\nconst PERSISTENCE_CAUSE_CODES = new Set<PersistenceTerminationCauseCode>([\n\t\"read_failed\",\n\t\"append_failed\",\n\t\"replace_failed\",\n\t\"fsync_failed\",\n\t\"lock_failed\",\n]);\nconst TRANSCRIPT_CAUSE_CODES = new Set<TranscriptTerminationCauseCode>([\n\t\"missing_result\",\n\t\"duplicate_result\",\n\t\"orphan_result\",\n\t\"duplicate_call_id\",\n\t\"interleaved_non_result\",\n\t\"invalid_jsonl\",\n\t\"invalid_tree\",\n\t\"unsupported_version\",\n\t\"trailing_fragment\",\n]);\nconst PROCESS_SIGNALS = new Set<SessionProcessSignal>([\"SIGINT\", \"SIGTERM\", \"SIGHUP\", \"SIGQUIT\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasOnlyKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n\tconst allowed = new Set(keys);\n\treturn Object.keys(value).every((key) => allowed.has(key));\n}\n\nfunction assertCause(cause: unknown): asserts cause is SessionTerminationCause {\n\tif (!isRecord(cause) || typeof cause.area !== \"string\") {\n\t\tthrow new TypeError(\"cause must be a bounded structured termination cause\");\n\t}\n\tconst code = cause.code;\n\tlet valid = false;\n\tswitch (cause.area) {\n\t\tcase \"completed\":\n\t\t\tvalid = hasOnlyKeys(cause, [\"area\"]);\n\t\t\tbreak;\n\t\tcase \"user\":\n\t\t\tvalid = code === \"abort\" && hasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"provider\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tPROVIDER_CAUSE_CODES.has(code as ProviderTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"tool\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tTOOL_CAUSE_CODES.has(code as ToolTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"compaction\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tCOMPACTION_CAUSE_CODES.has(code as CompactionTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"persistence\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tPERSISTENCE_CAUSE_CODES.has(code as PersistenceTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"process\":\n\t\t\tvalid =\n\t\t\t\t(code === \"crash\" && hasOnlyKeys(cause, [\"area\", \"code\"])) ||\n\t\t\t\t(code === \"signal\" &&\n\t\t\t\t\ttypeof cause.signal === \"string\" &&\n\t\t\t\t\tPROCESS_SIGNALS.has(cause.signal as SessionProcessSignal) &&\n\t\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\", \"signal\"]));\n\t\t\tbreak;\n\t\tcase \"transcript\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tTRANSCRIPT_CAUSE_CODES.has(code as TranscriptTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"configuration\":\n\t\t\tvalid = code === \"invalid\" && hasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"internal\":\n\t\t\tvalid = code === \"unclassified\" && hasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"budget\":\n\t\t\tvalid = RUN_BUDGET_STOP_CODES.some((allowed) => allowed === code) && hasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"resource\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tRESOURCE_CAUSE_CODES.has(code as ResourceTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t}\n\tif (!valid) throw new TypeError(\"cause must be a bounded structured termination cause\");\n}\n\nexport function parseSessionTerminationCauseCode(code: string, signal?: SessionProcessSignal): SessionTerminationCause {\n\tif (code === \"session.completed\") return { area: \"completed\" };\n\tif (code === \"session.user_abort\") return { area: \"user\", code: \"abort\" };\n\tconst dot = code.indexOf(\".\");\n\tconst cause = {\n\t\tarea: code.slice(0, dot),\n\t\tcode: code.slice(dot + 1),\n\t\t...(code === \"process.signal\" ? { signal } : {}),\n\t};\n\tassertCause(cause);\n\treturn cause;\n}\n\nfunction assertClassifierInput(input: unknown): asserts input is ClassifySessionTerminationInput {\n\tif (!isRecord(input) || Object.keys(input).some((key) => !TOP_LEVEL_KEYS.has(key))) {\n\t\tthrow new TypeError(\"input must contain only bounded structured termination fields\");\n\t}\n\tif (\n\t\ttypeof input.sessionId !== \"string\" ||\n\t\ttypeof input.runId !== \"string\" ||\n\t\ttypeof input.timestamp !== \"string\" ||\n\t\ttypeof input.message !== \"string\" ||\n\t\t(input.source !== \"observed\" && input.source !== \"inferred_on_resume\") ||\n\t\t(input.sideEffects !== \"none\" && input.sideEffects !== \"possible\" && input.sideEffects !== \"confirmed\") ||\n\t\t(input.retryAfterMs !== undefined && typeof input.retryAfterMs !== \"number\") ||\n\t\t(input.provider !== undefined && typeof input.provider !== \"string\") ||\n\t\t(input.model !== undefined && typeof input.model !== \"string\") ||\n\t\t(input.toolCallId !== undefined && typeof input.toolCallId !== \"string\") ||\n\t\t(input.toolName !== undefined && typeof input.toolName !== \"string\")\n\t) {\n\t\tthrow new TypeError(\"input must contain only bounded structured termination fields\");\n\t}\n\tassertCause(input.cause);\n}\n\nfunction assertIdentifier(value: string, name: string, maxLength: number): void {\n\tif (value.length === 0 || value.length > maxLength || /[\\u0000-\\u001f\\u007f]/.test(value)) {\n\t\tthrow new TypeError(`${name} must be non-empty bounded text without C0 or DEL control characters`);\n\t}\n}\n\n/** Validate text at the termination trust boundary without attempting redaction. */\nexport function assertPreRedactedTerminationMessage(message: string): void {\n\tif (message.length === 0 || message.length > MAX_SESSION_TERMINATION_MESSAGE_LENGTH) {\n\t\tthrow new TypeError(\n\t\t\t`message must contain 1-${MAX_SESSION_TERMINATION_MESSAGE_LENGTH} characters of pre-redacted text`,\n\t\t);\n\t}\n\tif (message.includes(\"\\0\")) {\n\t\tthrow new TypeError(\"message must not contain NUL\");\n\t}\n\tif (CREDENTIAL_SHAPES.some((pattern) => pattern.test(message))) {\n\t\tthrow new TypeError(\"message contains a credential-shaped literal; redact it before classification\");\n\t}\n}\n\nfunction assertTimestamp(timestamp: string): void {\n\tconst parsed = new Date(timestamp);\n\tif (!Number.isFinite(parsed.getTime()) || parsed.toISOString() !== timestamp) {\n\t\tthrow new TypeError(\"timestamp must be a canonical ISO-8601 UTC instant\");\n\t}\n}\n\nfunction classifyProvider(code: ProviderTerminationCauseCode): Classification {\n\tswitch (code) {\n\t\tcase \"abort\":\n\t\t\treturn {\n\t\t\t\tkind: \"provider_abort\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.abort\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"auth\":\n\t\t\treturn {\n\t\t\t\tkind: \"provider_auth\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.auth\",\n\t\t\t\tretryable: false,\n\t\t\t};\n\t\tcase \"rate_limit\":\n\t\t\treturn {\n\t\t\t\tkind: \"provider_rate_limit\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.rate_limit\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"network\":\n\t\t\treturn {\n\t\t\t\tkind: \"provider_network\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.network\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"protocol\":\n\t\t\t// Many \"protocol\" stops are sticky transcript shape bugs (orphan tool_call_id)\n\t\t\t// that succeed after transform-messages sanitizes and the turn is retried.\n\t\t\t// Mark retryable so auto-retry can heal; safeToAutoRetry stays false (needs sanitize path).\n\t\t\treturn {\n\t\t\t\tkind: \"provider_protocol\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.protocol\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"context_overflow\":\n\t\t\treturn {\n\t\t\t\tkind: \"context_overflow\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.context_overflow\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"refusal\":\n\t\t\treturn {\n\t\t\t\tkind: \"provider_refusal\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.refusal\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t}\n}\n\nfunction classifyCause(cause: SessionTerminationCause, source: SessionTerminationSource): Classification {\n\tswitch (cause.area) {\n\t\tcase \"completed\":\n\t\t\treturn {\n\t\t\t\tkind: \"completed\",\n\t\t\t\tphase: \"completed\",\n\t\t\t\tcauseCode: \"session.completed\",\n\t\t\t\tretryable: false,\n\t\t\t};\n\t\tcase \"user\":\n\t\t\treturn {\n\t\t\t\tkind: \"user_abort\",\n\t\t\t\tphase: \"control\",\n\t\t\t\tcauseCode: \"session.user_abort\",\n\t\t\t\tretryable: false,\n\t\t\t};\n\t\tcase \"provider\":\n\t\t\treturn classifyProvider(cause.code);\n\t\tcase \"tool\":\n\t\t\treturn cause.code === \"timeout\"\n\t\t\t\t? { kind: \"tool_timeout\", phase: \"tool\", causeCode: \"tool.timeout\", retryable: true }\n\t\t\t\t: { kind: \"tool_fatal\", phase: \"tool\", causeCode: \"tool.fatal\", retryable: false };\n\t\tcase \"compaction\":\n\t\t\treturn {\n\t\t\t\tkind: \"compaction\",\n\t\t\t\tphase: \"compaction\",\n\t\t\t\tcauseCode: `compaction.${cause.code}`,\n\t\t\t\t// Quota exhaustion does not heal by retrying: same-model retries\n\t\t\t\t// keep failing until the provider cycle resets or the model changes.\n\t\t\t\tretryable: cause.code !== \"quota_exhausted\",\n\t\t\t};\n\t\tcase \"persistence\":\n\t\t\treturn {\n\t\t\t\tkind: \"persistence\",\n\t\t\t\tphase: \"persistence\",\n\t\t\t\tcauseCode: `persistence.${cause.code}`,\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"process\":\n\t\t\tif (cause.code === \"signal\") {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"process_signal\",\n\t\t\t\t\tphase: \"process\",\n\t\t\t\t\tcauseCode: \"process.signal\",\n\t\t\t\t\tretryable: false,\n\t\t\t\t\tprocessSignal: cause.signal,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"process_crash\",\n\t\t\t\tphase: \"resume\",\n\t\t\t\tcauseCode: \"process.crash\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"transcript\":\n\t\t\treturn {\n\t\t\t\tkind: \"transcript_invalid\",\n\t\t\t\tphase: source === \"inferred_on_resume\" ? \"resume\" : \"preflight\",\n\t\t\t\tcauseCode: `transcript.${cause.code}`,\n\t\t\t\tretryable: false,\n\t\t\t\ttranscriptIssue: cause.code,\n\t\t\t};\n\t\tcase \"configuration\":\n\t\t\treturn {\n\t\t\t\tkind: \"configuration\",\n\t\t\t\tphase: \"preflight\",\n\t\t\t\tcauseCode: \"configuration.invalid\",\n\t\t\t\tretryable: false,\n\t\t\t};\n\t\tcase \"internal\":\n\t\t\treturn {\n\t\t\t\tkind: \"internal_error\",\n\t\t\t\tphase: \"preflight\",\n\t\t\t\tcauseCode: \"internal.unclassified\",\n\t\t\t\tretryable: false,\n\t\t\t};\n\t\tcase \"budget\":\n\t\t\treturn { kind: \"budget_exhausted\", phase: \"control\", causeCode: `budget.${cause.code}`, retryable: false };\n\t\tcase \"resource\":\n\t\t\t// §15.4: every resource cause is retryable; queue overflow surfaces at\n\t\t\t// the tool boundary, everything else at preflight admission.\n\t\t\treturn {\n\t\t\t\tkind: \"resource_pressure\",\n\t\t\t\tphase: cause.code === \"queue_overflow\" ? \"tool\" : \"preflight\",\n\t\t\t\tcauseCode: `resource.${cause.code}`,\n\t\t\t\tretryable: true,\n\t\t\t};\n\t}\n}\n\nfunction isSafeToAutoRetry(classification: Classification, input: ClassifySessionTerminationInput): boolean {\n\t// provider_refusal: Fable/Claude often false-positive on benign turns. Safe to auto-retry once\n\t// when no tool side effects occurred (same class of recovery as rate_limit/network).\n\treturn (\n\t\tclassification.retryable &&\n\t\tinput.source === \"observed\" &&\n\t\tinput.sideEffects === \"none\" &&\n\t\t(classification.kind === \"provider_rate_limit\" ||\n\t\t\tclassification.kind === \"provider_network\" ||\n\t\t\tclassification.kind === \"provider_refusal\" ||\n\t\t\t// §15.4 mapping: only cpu pressure is safe to auto-retry (with delay).\n\t\t\tclassification.causeCode === \"resource.cpu\")\n\t);\n}\n\nfunction nextActionFor(classification: Classification, input: ClassifySessionTerminationInput): string {\n\tswitch (classification.kind) {\n\t\tcase \"completed\":\n\t\t\treturn \"No recovery action is required; continue with the next prompt.\";\n\t\tcase \"user_abort\":\n\t\t\treturn \"Review possible partial side effects, then retry only if intended.\";\n\t\tcase \"budget_exhausted\":\n\t\t\treturn \"Review partial work and remaining requests; start a new run only with an explicitly approved budget.\";\n\t\tcase \"resource_pressure\":\n\t\t\treturn \"Host resources are constrained; reduce load or wait for recovery, then retry.\";\n\t\tcase \"provider_abort\":\n\t\t\treturn \"Confirm provider availability, then retry the request.\";\n\t\tcase \"provider_auth\":\n\t\t\t// A credential-less install resolves a placeholder model whose provider is\n\t\t\t// literally \"unknown\"; never echo that back as a login target.\n\t\t\treturn `Run /login${input.provider && input.provider !== \"unknown\" ? ` ${input.provider}` : \"\"} in an interactive session, or set the provider's API key environment variable, then retry.`;\n\t\tcase \"provider_rate_limit\":\n\t\t\treturn \"Wait for the provider retry window or choose another model, then retry.\";\n\t\tcase \"provider_network\":\n\t\t\treturn \"Check network and provider connectivity, then retry.\";\n\t\tcase \"provider_protocol\":\n\t\t\treturn \"Often an orphan tool_call_id / sticky transcript after a dropped error turn — auto-retry after sanitize, or /new session if it persists.\";\n\t\tcase \"provider_refusal\":\n\t\t\treturn \"Model declined this turn (content/safety stop). Usually a false positive on Fable/Claude — auto-retry once, or switch model (k3/qwen3.8-max/grok-4.5/deepseek) / rephrase as a pure coding task.\";\n\t\tcase \"context_overflow\":\n\t\t\treturn \"Compact or reduce context, or switch to a larger-context model.\";\n\t\tcase \"tool_timeout\":\n\t\t\treturn \"Inspect possible tool side effects and increase the tool timeout only if safe.\";\n\t\tcase \"tool_fatal\":\n\t\t\treturn \"Inspect the failed tool result and repair its configuration before retrying.\";\n\t\tcase \"compaction\":\n\t\t\tswitch (classification.causeCode) {\n\t\t\t\tcase \"compaction.aborted\":\n\t\t\t\t\treturn \"Retry /compact if cancellation was unintended; avoid Escape while compaction is running.\";\n\t\t\t\tcase \"compaction.stale\":\n\t\t\t\t\treturn \"Retry /compact after pending session changes settle.\";\n\t\t\t\tcase \"compaction.quota_exhausted\":\n\t\t\t\t\treturn \"The summarization model's quota is exhausted — retrying cannot help yet. Switch model (/model), set compaction.model in settings, or wait for the quota reset, then retry /compact. OMK already tried the failover chain automatically.\";\n\t\t\t\tdefault:\n\t\t\t\t\treturn \"Resolve the reported compaction error, then retry /compact.\";\n\t\t\t}\n\t\tcase \"persistence\":\n\t\t\treturn `Run omk session doctor --session ${input.sessionId} before resuming.`;\n\t\tcase \"process_signal\":\n\t\t\treturn \"Review possible partial side effects before resuming the session.\";\n\t\tcase \"process_crash\":\n\t\t\treturn `Run omk session doctor --session ${input.sessionId} and review partial side effects.`;\n\t\tcase \"transcript_invalid\":\n\t\t\treturn `Run omk session doctor --session ${input.sessionId}; do not resume until integrity passes.`;\n\t\tcase \"configuration\":\n\t\t\treturn \"This model or client is not valid for the current login. Switch with /model or fix provider/client settings; /new session will not grant access.\";\n\t\tcase \"internal_error\":\n\t\t\treturn `Inspect run ${input.runId} diagnostics and the run journal before retrying.`;\n\t}\n}\n\n/** Concise actionable rendering shared by non-JSON and TUI surfaces. */\nexport function formatSessionTermination(termination: SessionTermination): string {\n\tconst route =\n\t\ttermination.provider || termination.model\n\t\t\t? `${termination.provider ?? \"unknown\"}/${termination.model ?? \"unknown\"}`\n\t\t\t: \"n/a\";\n\treturn [\n\t\t`kind=${termination.kind}`,\n\t\t`provider/model=${route}`,\n\t\t`retryable=${termination.retryable}`,\n\t\t`cause=${termination.causeCode}`,\n\t\t`message=${termination.message}`,\n\t\t`run=${termination.runId}`,\n\t\t`next=${termination.nextAction}`,\n\t].join(\" \");\n}\n\n/**\n * Classify a bounded, structured termination cause. This intentionally accepts\n * no raw Error value, stack, provider body, or arbitrary cause code.\n */\nexport function classifySessionTermination(input: ClassifySessionTerminationInput): SessionTermination {\n\tassertClassifierInput(input);\n\tassertIdentifier(input.sessionId, \"sessionId\", 128);\n\tassertIdentifier(input.runId, \"runId\", 128);\n\tassertTimestamp(input.timestamp);\n\tassertPreRedactedTerminationMessage(input.message);\n\tif (input.provider !== undefined) assertIdentifier(input.provider, \"provider\", 128);\n\tif (input.model !== undefined) assertIdentifier(input.model, \"model\", 256);\n\tif (input.toolCallId !== undefined) assertIdentifier(input.toolCallId, \"toolCallId\", 512);\n\tif (input.toolName !== undefined) assertIdentifier(input.toolName, \"toolName\", 128);\n\tif (input.retryAfterMs !== undefined && (!Number.isSafeInteger(input.retryAfterMs) || input.retryAfterMs < 0)) {\n\t\tthrow new TypeError(\"retryAfterMs must be a non-negative safe integer\");\n\t}\n\tif (input.cause.area === \"process\" && input.cause.code === \"crash\" && input.source !== \"inferred_on_resume\") {\n\t\tthrow new TypeError(\"process crashes may only be classified as inferred_on_resume\");\n\t}\n\tif (input.cause.area === \"process\" && input.cause.code === \"signal\" && input.source !== \"observed\") {\n\t\tthrow new TypeError(\"process signals must be observed\");\n\t}\n\n\tconst classification = classifyCause(input.cause, input.source);\n\treturn Object.freeze({\n\t\tschemaVersion: SESSION_TERMINATION_SCHEMA_VERSION,\n\t\tsessionId: input.sessionId,\n\t\trunId: input.runId,\n\t\tkind: classification.kind,\n\t\tphase: classification.phase,\n\t\tsource: input.source,\n\t\tmessage: input.message,\n\t\tcauseCode: classification.causeCode,\n\t\tnextAction: nextActionFor(classification, input),\n\t\tretryable: classification.retryable,\n\t\tsafeToAutoRetry: isSafeToAutoRetry(classification, input),\n\t\tsideEffects: input.sideEffects,\n\t\ttimestamp: input.timestamp,\n\t\t...(input.retryAfterMs === undefined ? {} : { retryAfterMs: input.retryAfterMs }),\n\t\t...(input.provider === undefined ? {} : { provider: input.provider }),\n\t\t...(input.model === undefined ? {} : { model: input.model }),\n\t\t...(input.toolCallId === undefined ? {} : { toolCallId: input.toolCallId }),\n\t\t...(input.toolName === undefined ? {} : { toolName: input.toolName }),\n\t\t...(classification.processSignal === undefined ? {} : { processSignal: classification.processSignal }),\n\t\t...(classification.transcriptIssue === undefined ? {} : { transcriptIssue: classification.transcriptIssue }),\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-termination.d.ts","sourceRoot":"","sources":["../../src/core/session-termination.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,+BAA+B,EAOpC,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,EAO5B,MAAM,gCAAgC,CAAC;AAExC,cAAc,gCAAgC,CAAC;AAE/C,qBAAa,uBAAwB,SAAQ,KAAK;IACjD,QAAQ,CAAC,WAAW,EAAE,kBAAkB,CAAC;IAEzC,YAAY,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,kBAAkB,EAI3D;CACD;AA4JD,wBAAgB,gCAAgC,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,oBAAoB,GAAG,uBAAuB,CAWrH;AA8BD,oFAAoF;AACpF,wBAAgB,mCAAmC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAYzE;AAqOD,wEAAwE;AACxE,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,kBAAkB,GAAG,MAAM,CAchF;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,+BAA+B,GAAG,kBAAkB,CA2CrG","sourcesContent":["import { RUN_BUDGET_STOP_CODES } from \"./run-budget-policy.ts\";\nimport {\n\ttype ClassifySessionTerminationInput,\n\ttype CompactionTerminationCauseCode,\n\tMAX_SESSION_TERMINATION_MESSAGE_LENGTH,\n\ttype PersistenceTerminationCauseCode,\n\ttype ProviderTerminationCauseCode,\n\ttype ResourceTerminationCauseCode,\n\tSESSION_TERMINATION_SCHEMA_VERSION,\n\ttype SessionProcessSignal,\n\ttype SessionTermination,\n\ttype SessionTerminationCause,\n\ttype SessionTerminationCauseCode,\n\ttype SessionTerminationKind,\n\ttype SessionTerminationPhase,\n\ttype SessionTerminationSource,\n\ttype ToolTerminationCauseCode,\n\ttype TranscriptTerminationCauseCode,\n} from \"./session-termination-types.ts\";\n\nexport * from \"./session-termination-types.ts\";\n\nexport class SessionTerminationError extends Error {\n\treadonly termination: SessionTermination;\n\n\tconstructor(message: string, termination: SessionTermination) {\n\t\tsuper(message);\n\t\tthis.name = \"SessionTerminationError\";\n\t\tthis.termination = termination;\n\t}\n}\n\ninterface Classification {\n\treadonly kind: SessionTerminationKind;\n\treadonly phase: SessionTerminationPhase;\n\treadonly causeCode: SessionTerminationCauseCode;\n\treadonly retryable: boolean;\n\treadonly processSignal?: SessionProcessSignal;\n\treadonly transcriptIssue?: TranscriptTerminationCauseCode;\n}\n\nconst CREDENTIAL_SHAPES = [\n\t/-----BEGIN [A-Z ]*PRIVATE KEY-----/i,\n\t/\\b(?:sk-[A-Za-z0-9_-]{16,}|github_pat_[A-Za-z0-9_]{16,}|gh[pousr]_[A-Za-z0-9]{16,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[A-Z0-9]{16})\\b/,\n\t/\\bBearer\\s+[A-Za-z0-9._~+/-]{8,}={0,2}\\b/i,\n\t/\\beyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\b/,\n\t/(?:^|[^A-Za-z0-9])(?:[A-Za-z0-9]+[_-])*(?:authorization|api[-_ ]?key|access[-_ ]?token|token|password|secret(?:[-_ ]?key)?|private[-_ ]?key|cookie)[\"']?\\s*[:=]/i,\n] as const;\n\nconst TOP_LEVEL_KEYS = new Set([\n\t\"sessionId\",\n\t\"runId\",\n\t\"timestamp\",\n\t\"source\",\n\t\"message\",\n\t\"cause\",\n\t\"sideEffects\",\n\t\"retryAfterMs\",\n\t\"provider\",\n\t\"model\",\n\t\"toolCallId\",\n\t\"toolName\",\n]);\nconst PROVIDER_CAUSE_CODES = new Set<ProviderTerminationCauseCode>([\n\t\"abort\",\n\t\"auth\",\n\t\"rate_limit\",\n\t\"network\",\n\t\"protocol\",\n\t\"refusal\",\n\t\"context_overflow\",\n]);\nconst TOOL_CAUSE_CODES = new Set<ToolTerminationCauseCode>([\"timeout\", \"fatal\"]);\nconst RESOURCE_CAUSE_CODES = new Set<ResourceTerminationCauseCode>([\n\t\"memory\",\n\t\"disk\",\n\t\"cpu\",\n\t\"heap\",\n\t\"probe_unavailable\",\n\t\"queue_overflow\",\n]);\nconst COMPACTION_CAUSE_CODES = new Set<CompactionTerminationCauseCode>([\n\t\"aborted\",\n\t\"failed\",\n\t\"stale\",\n\t\"quota_exhausted\",\n]);\nconst PERSISTENCE_CAUSE_CODES = new Set<PersistenceTerminationCauseCode>([\n\t\"read_failed\",\n\t\"append_failed\",\n\t\"replace_failed\",\n\t\"fsync_failed\",\n\t\"lock_failed\",\n]);\nconst TRANSCRIPT_CAUSE_CODES = new Set<TranscriptTerminationCauseCode>([\n\t\"missing_result\",\n\t\"duplicate_result\",\n\t\"orphan_result\",\n\t\"duplicate_call_id\",\n\t\"interleaved_non_result\",\n\t\"invalid_jsonl\",\n\t\"invalid_tree\",\n\t\"unsupported_version\",\n\t\"trailing_fragment\",\n]);\nconst PROCESS_SIGNALS = new Set<SessionProcessSignal>([\"SIGINT\", \"SIGTERM\", \"SIGHUP\", \"SIGQUIT\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasOnlyKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n\tconst allowed = new Set(keys);\n\treturn Object.keys(value).every((key) => allowed.has(key));\n}\n\nfunction assertCause(cause: unknown): asserts cause is SessionTerminationCause {\n\tif (!isRecord(cause) || typeof cause.area !== \"string\") {\n\t\tthrow new TypeError(\"cause must be a bounded structured termination cause\");\n\t}\n\tconst code = cause.code;\n\tlet valid = false;\n\tswitch (cause.area) {\n\t\tcase \"completed\":\n\t\t\tvalid = hasOnlyKeys(cause, [\"area\"]);\n\t\t\tbreak;\n\t\tcase \"user\":\n\t\t\tvalid = code === \"abort\" && hasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"provider\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tPROVIDER_CAUSE_CODES.has(code as ProviderTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"tool\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tTOOL_CAUSE_CODES.has(code as ToolTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"compaction\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tCOMPACTION_CAUSE_CODES.has(code as CompactionTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"persistence\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tPERSISTENCE_CAUSE_CODES.has(code as PersistenceTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"process\":\n\t\t\tvalid =\n\t\t\t\t(code === \"crash\" && hasOnlyKeys(cause, [\"area\", \"code\"])) ||\n\t\t\t\t(code === \"signal\" &&\n\t\t\t\t\ttypeof cause.signal === \"string\" &&\n\t\t\t\t\tPROCESS_SIGNALS.has(cause.signal as SessionProcessSignal) &&\n\t\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\", \"signal\"]));\n\t\t\tbreak;\n\t\tcase \"transcript\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tTRANSCRIPT_CAUSE_CODES.has(code as TranscriptTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"configuration\":\n\t\t\tvalid = code === \"invalid\" && hasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"internal\":\n\t\t\tvalid = code === \"unclassified\" && hasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"budget\":\n\t\t\tvalid = RUN_BUDGET_STOP_CODES.some((allowed) => allowed === code) && hasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t\tcase \"resource\":\n\t\t\tvalid =\n\t\t\t\ttypeof code === \"string\" &&\n\t\t\t\tRESOURCE_CAUSE_CODES.has(code as ResourceTerminationCauseCode) &&\n\t\t\t\thasOnlyKeys(cause, [\"area\", \"code\"]);\n\t\t\tbreak;\n\t}\n\tif (!valid) throw new TypeError(\"cause must be a bounded structured termination cause\");\n}\n\nexport function parseSessionTerminationCauseCode(code: string, signal?: SessionProcessSignal): SessionTerminationCause {\n\tif (code === \"session.completed\") return { area: \"completed\" };\n\tif (code === \"session.user_abort\") return { area: \"user\", code: \"abort\" };\n\tconst dot = code.indexOf(\".\");\n\tconst cause = {\n\t\tarea: code.slice(0, dot),\n\t\tcode: code.slice(dot + 1),\n\t\t...(code === \"process.signal\" ? { signal } : {}),\n\t};\n\tassertCause(cause);\n\treturn cause;\n}\n\nfunction assertClassifierInput(input: unknown): asserts input is ClassifySessionTerminationInput {\n\tif (!isRecord(input) || Object.keys(input).some((key) => !TOP_LEVEL_KEYS.has(key))) {\n\t\tthrow new TypeError(\"input must contain only bounded structured termination fields\");\n\t}\n\tif (\n\t\ttypeof input.sessionId !== \"string\" ||\n\t\ttypeof input.runId !== \"string\" ||\n\t\ttypeof input.timestamp !== \"string\" ||\n\t\ttypeof input.message !== \"string\" ||\n\t\t(input.source !== \"observed\" && input.source !== \"inferred_on_resume\") ||\n\t\t(input.sideEffects !== \"none\" && input.sideEffects !== \"possible\" && input.sideEffects !== \"confirmed\") ||\n\t\t(input.retryAfterMs !== undefined && typeof input.retryAfterMs !== \"number\") ||\n\t\t(input.provider !== undefined && typeof input.provider !== \"string\") ||\n\t\t(input.model !== undefined && typeof input.model !== \"string\") ||\n\t\t(input.toolCallId !== undefined && typeof input.toolCallId !== \"string\") ||\n\t\t(input.toolName !== undefined && typeof input.toolName !== \"string\")\n\t) {\n\t\tthrow new TypeError(\"input must contain only bounded structured termination fields\");\n\t}\n\tassertCause(input.cause);\n}\n\nfunction assertIdentifier(value: string, name: string, maxLength: number): void {\n\tif (value.length === 0 || value.length > maxLength || /[\\u0000-\\u001f\\u007f]/.test(value)) {\n\t\tthrow new TypeError(`${name} must be non-empty bounded text without C0 or DEL control characters`);\n\t}\n}\n\n/** Validate text at the termination trust boundary without attempting redaction. */\nexport function assertPreRedactedTerminationMessage(message: string): void {\n\tif (message.length === 0 || message.length > MAX_SESSION_TERMINATION_MESSAGE_LENGTH) {\n\t\tthrow new TypeError(\n\t\t\t`message must contain 1-${MAX_SESSION_TERMINATION_MESSAGE_LENGTH} characters of pre-redacted text`,\n\t\t);\n\t}\n\tif (message.includes(\"\\0\")) {\n\t\tthrow new TypeError(\"message must not contain NUL\");\n\t}\n\tif (CREDENTIAL_SHAPES.some((pattern) => pattern.test(message))) {\n\t\tthrow new TypeError(\"message contains a credential-shaped literal; redact it before classification\");\n\t}\n}\n\nfunction assertTimestamp(timestamp: string): void {\n\tconst parsed = new Date(timestamp);\n\tif (!Number.isFinite(parsed.getTime()) || parsed.toISOString() !== timestamp) {\n\t\tthrow new TypeError(\"timestamp must be a canonical ISO-8601 UTC instant\");\n\t}\n}\n\nfunction classifyProvider(code: ProviderTerminationCauseCode): Classification {\n\tswitch (code) {\n\t\tcase \"abort\":\n\t\t\treturn {\n\t\t\t\tkind: \"provider_abort\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.abort\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"auth\":\n\t\t\treturn {\n\t\t\t\tkind: \"provider_auth\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.auth\",\n\t\t\t\tretryable: false,\n\t\t\t};\n\t\tcase \"rate_limit\":\n\t\t\treturn {\n\t\t\t\tkind: \"provider_rate_limit\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.rate_limit\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"network\":\n\t\t\treturn {\n\t\t\t\tkind: \"provider_network\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.network\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"protocol\":\n\t\t\t// Many \"protocol\" stops are sticky transcript shape bugs (orphan tool_call_id)\n\t\t\t// that succeed after transform-messages sanitizes and the turn is retried.\n\t\t\t// Mark retryable so auto-retry can heal; safeToAutoRetry stays false (needs sanitize path).\n\t\t\treturn {\n\t\t\t\tkind: \"provider_protocol\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.protocol\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"context_overflow\":\n\t\t\treturn {\n\t\t\t\tkind: \"context_overflow\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.context_overflow\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"refusal\":\n\t\t\treturn {\n\t\t\t\tkind: \"provider_refusal\",\n\t\t\t\tphase: \"provider\",\n\t\t\t\tcauseCode: \"provider.refusal\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t}\n}\n\nfunction classifyCause(cause: SessionTerminationCause, source: SessionTerminationSource): Classification {\n\tswitch (cause.area) {\n\t\tcase \"completed\":\n\t\t\treturn {\n\t\t\t\tkind: \"completed\",\n\t\t\t\tphase: \"completed\",\n\t\t\t\tcauseCode: \"session.completed\",\n\t\t\t\tretryable: false,\n\t\t\t};\n\t\tcase \"user\":\n\t\t\treturn {\n\t\t\t\tkind: \"user_abort\",\n\t\t\t\tphase: \"control\",\n\t\t\t\tcauseCode: \"session.user_abort\",\n\t\t\t\tretryable: false,\n\t\t\t};\n\t\tcase \"provider\":\n\t\t\treturn classifyProvider(cause.code);\n\t\tcase \"tool\":\n\t\t\treturn cause.code === \"timeout\"\n\t\t\t\t? { kind: \"tool_timeout\", phase: \"tool\", causeCode: \"tool.timeout\", retryable: true }\n\t\t\t\t: { kind: \"tool_fatal\", phase: \"tool\", causeCode: \"tool.fatal\", retryable: false };\n\t\tcase \"compaction\":\n\t\t\treturn {\n\t\t\t\tkind: \"compaction\",\n\t\t\t\tphase: \"compaction\",\n\t\t\t\tcauseCode: `compaction.${cause.code}`,\n\t\t\t\t// Quota exhaustion does not heal by retrying: same-model retries\n\t\t\t\t// keep failing until the provider cycle resets or the model changes.\n\t\t\t\tretryable: cause.code !== \"quota_exhausted\",\n\t\t\t};\n\t\tcase \"persistence\":\n\t\t\treturn {\n\t\t\t\tkind: \"persistence\",\n\t\t\t\tphase: \"persistence\",\n\t\t\t\tcauseCode: `persistence.${cause.code}`,\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"process\":\n\t\t\tif (cause.code === \"signal\") {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"process_signal\",\n\t\t\t\t\tphase: \"process\",\n\t\t\t\t\tcauseCode: \"process.signal\",\n\t\t\t\t\tretryable: false,\n\t\t\t\t\tprocessSignal: cause.signal,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"process_crash\",\n\t\t\t\tphase: \"resume\",\n\t\t\t\tcauseCode: \"process.crash\",\n\t\t\t\tretryable: true,\n\t\t\t};\n\t\tcase \"transcript\":\n\t\t\treturn {\n\t\t\t\tkind: \"transcript_invalid\",\n\t\t\t\tphase: source === \"inferred_on_resume\" ? \"resume\" : \"preflight\",\n\t\t\t\tcauseCode: `transcript.${cause.code}`,\n\t\t\t\tretryable: false,\n\t\t\t\ttranscriptIssue: cause.code,\n\t\t\t};\n\t\tcase \"configuration\":\n\t\t\treturn {\n\t\t\t\tkind: \"configuration\",\n\t\t\t\tphase: \"preflight\",\n\t\t\t\tcauseCode: \"configuration.invalid\",\n\t\t\t\tretryable: false,\n\t\t\t};\n\t\tcase \"internal\":\n\t\t\treturn {\n\t\t\t\tkind: \"internal_error\",\n\t\t\t\tphase: \"preflight\",\n\t\t\t\tcauseCode: \"internal.unclassified\",\n\t\t\t\tretryable: false,\n\t\t\t};\n\t\tcase \"budget\":\n\t\t\treturn { kind: \"budget_exhausted\", phase: \"control\", causeCode: `budget.${cause.code}`, retryable: false };\n\t\tcase \"resource\":\n\t\t\t// §15.4: every resource cause is retryable; queue overflow surfaces at\n\t\t\t// the tool boundary, everything else at preflight admission.\n\t\t\treturn {\n\t\t\t\tkind: \"resource_pressure\",\n\t\t\t\tphase: cause.code === \"queue_overflow\" ? \"tool\" : \"preflight\",\n\t\t\t\tcauseCode: `resource.${cause.code}`,\n\t\t\t\tretryable: true,\n\t\t\t};\n\t}\n}\n\nfunction isSafeToAutoRetry(classification: Classification, input: ClassifySessionTerminationInput): boolean {\n\t// provider_refusal: Fable/Claude often false-positive on benign turns. Safe to auto-retry once\n\t// when no tool side effects occurred (same class of recovery as rate_limit/network).\n\treturn (\n\t\tclassification.retryable &&\n\t\tinput.source === \"observed\" &&\n\t\tinput.sideEffects === \"none\" &&\n\t\t(classification.kind === \"provider_rate_limit\" ||\n\t\t\tclassification.kind === \"provider_network\" ||\n\t\t\tclassification.kind === \"provider_refusal\" ||\n\t\t\t// §15.4 mapping: only cpu pressure is safe to auto-retry (with delay).\n\t\t\tclassification.causeCode === \"resource.cpu\")\n\t);\n}\n\nfunction nextActionFor(classification: Classification, input: ClassifySessionTerminationInput): string {\n\tswitch (classification.kind) {\n\t\tcase \"completed\":\n\t\t\treturn \"No recovery action is required; continue with the next prompt.\";\n\t\tcase \"user_abort\":\n\t\t\treturn \"Review possible partial side effects, then retry only if intended.\";\n\t\tcase \"budget_exhausted\":\n\t\t\treturn \"Review partial work and remaining requests; start a new run only with an explicitly approved budget.\";\n\t\tcase \"resource_pressure\":\n\t\t\treturn \"Host resources are constrained; reduce load or wait for recovery, then retry.\";\n\t\tcase \"provider_abort\":\n\t\t\treturn \"Confirm provider availability, then retry the request.\";\n\t\tcase \"provider_auth\":\n\t\t\t// A credential-less install resolves a placeholder model whose provider is\n\t\t\t// literally \"unknown\"; never echo that back as a login target.\n\t\t\treturn `Run /login${input.provider && input.provider !== \"unknown\" ? ` ${input.provider}` : \"\"} in an interactive session, or set the provider's API key environment variable, then retry.`;\n\t\tcase \"provider_rate_limit\":\n\t\t\treturn \"Wait for the provider retry window or choose another model, then retry.\";\n\t\tcase \"provider_network\":\n\t\t\treturn \"Check network and provider connectivity, then retry.\";\n\t\tcase \"provider_protocol\":\n\t\t\treturn \"Check request parameters and tool/message consistency in /debug before retrying. A new session does not reload provider code; restart OMK after an adapter update.\";\n\t\tcase \"provider_refusal\":\n\t\t\treturn \"Model declined this turn (content/safety stop). Usually a false positive on Fable/Claude — auto-retry once, or switch model (k3/qwen3.8-max/grok-4.5/deepseek) / rephrase as a pure coding task.\";\n\t\tcase \"context_overflow\":\n\t\t\treturn \"Compact or reduce context, or switch to a larger-context model.\";\n\t\tcase \"tool_timeout\":\n\t\t\treturn \"Inspect possible tool side effects and increase the tool timeout only if safe.\";\n\t\tcase \"tool_fatal\":\n\t\t\treturn \"Inspect the failed tool result and repair its configuration before retrying.\";\n\t\tcase \"compaction\":\n\t\t\tswitch (classification.causeCode) {\n\t\t\t\tcase \"compaction.aborted\":\n\t\t\t\t\treturn \"Retry /compact if cancellation was unintended; avoid Escape while compaction is running.\";\n\t\t\t\tcase \"compaction.stale\":\n\t\t\t\t\treturn \"Retry /compact after pending session changes settle.\";\n\t\t\t\tcase \"compaction.quota_exhausted\":\n\t\t\t\t\treturn \"The summarization model's quota is exhausted — retrying cannot help yet. Switch model (/model), set compaction.model in settings, or wait for the quota reset, then retry /compact. OMK already tried the failover chain automatically.\";\n\t\t\t\tdefault:\n\t\t\t\t\treturn \"Resolve the reported compaction error, then retry /compact.\";\n\t\t\t}\n\t\tcase \"persistence\":\n\t\t\treturn `Run omk session doctor --session ${input.sessionId} before resuming.`;\n\t\tcase \"process_signal\":\n\t\t\treturn \"Review possible partial side effects before resuming the session.\";\n\t\tcase \"process_crash\":\n\t\t\treturn `Run omk session doctor --session ${input.sessionId} and review partial side effects.`;\n\t\tcase \"transcript_invalid\":\n\t\t\treturn `Run omk session doctor --session ${input.sessionId}; do not resume until integrity passes.`;\n\t\tcase \"configuration\":\n\t\t\treturn /does not provide an export named/i.test(input.message)\n\t\t\t\t? \"Provider code failed to load. Quit and restart OMK so the rebuilt adapter is imported; /new session does not reload modules.\"\n\t\t\t\t: \"This model or client is not valid for the current login. Switch with /model or fix provider/client settings; /new session will not grant access.\";\n\t\tcase \"internal_error\":\n\t\t\treturn `Inspect run ${input.runId} diagnostics and the run journal before retrying.`;\n\t}\n}\n\n/** Concise actionable rendering shared by non-JSON and TUI surfaces. */\nexport function formatSessionTermination(termination: SessionTermination): string {\n\tconst route =\n\t\ttermination.provider || termination.model\n\t\t\t? `${termination.provider ?? \"unknown\"}/${termination.model ?? \"unknown\"}`\n\t\t\t: \"n/a\";\n\treturn [\n\t\t`kind=${termination.kind}`,\n\t\t`provider/model=${route}`,\n\t\t`retryable=${termination.retryable}`,\n\t\t`cause=${termination.causeCode}`,\n\t\t`message=${termination.message}`,\n\t\t`run=${termination.runId}`,\n\t\t`next=${termination.nextAction}`,\n\t].join(\" \");\n}\n\n/**\n * Classify a bounded, structured termination cause. This intentionally accepts\n * no raw Error value, stack, provider body, or arbitrary cause code.\n */\nexport function classifySessionTermination(input: ClassifySessionTerminationInput): SessionTermination {\n\tassertClassifierInput(input);\n\tassertIdentifier(input.sessionId, \"sessionId\", 128);\n\tassertIdentifier(input.runId, \"runId\", 128);\n\tassertTimestamp(input.timestamp);\n\tassertPreRedactedTerminationMessage(input.message);\n\tif (input.provider !== undefined) assertIdentifier(input.provider, \"provider\", 128);\n\tif (input.model !== undefined) assertIdentifier(input.model, \"model\", 256);\n\tif (input.toolCallId !== undefined) assertIdentifier(input.toolCallId, \"toolCallId\", 512);\n\tif (input.toolName !== undefined) assertIdentifier(input.toolName, \"toolName\", 128);\n\tif (input.retryAfterMs !== undefined && (!Number.isSafeInteger(input.retryAfterMs) || input.retryAfterMs < 0)) {\n\t\tthrow new TypeError(\"retryAfterMs must be a non-negative safe integer\");\n\t}\n\tif (input.cause.area === \"process\" && input.cause.code === \"crash\" && input.source !== \"inferred_on_resume\") {\n\t\tthrow new TypeError(\"process crashes may only be classified as inferred_on_resume\");\n\t}\n\tif (input.cause.area === \"process\" && input.cause.code === \"signal\" && input.source !== \"observed\") {\n\t\tthrow new TypeError(\"process signals must be observed\");\n\t}\n\n\tconst classification = classifyCause(input.cause, input.source);\n\treturn Object.freeze({\n\t\tschemaVersion: SESSION_TERMINATION_SCHEMA_VERSION,\n\t\tsessionId: input.sessionId,\n\t\trunId: input.runId,\n\t\tkind: classification.kind,\n\t\tphase: classification.phase,\n\t\tsource: input.source,\n\t\tmessage: input.message,\n\t\tcauseCode: classification.causeCode,\n\t\tnextAction: nextActionFor(classification, input),\n\t\tretryable: classification.retryable,\n\t\tsafeToAutoRetry: isSafeToAutoRetry(classification, input),\n\t\tsideEffects: input.sideEffects,\n\t\ttimestamp: input.timestamp,\n\t\t...(input.retryAfterMs === undefined ? {} : { retryAfterMs: input.retryAfterMs }),\n\t\t...(input.provider === undefined ? {} : { provider: input.provider }),\n\t\t...(input.model === undefined ? {} : { model: input.model }),\n\t\t...(input.toolCallId === undefined ? {} : { toolCallId: input.toolCallId }),\n\t\t...(input.toolName === undefined ? {} : { toolName: input.toolName }),\n\t\t...(classification.processSignal === undefined ? {} : { processSignal: classification.processSignal }),\n\t\t...(classification.transcriptIssue === undefined ? {} : { transcriptIssue: classification.transcriptIssue }),\n\t});\n}\n"]}
|