dsh-harness-reflex 0.1.0 → 0.3.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.
Files changed (124) hide show
  1. package/README.md +20 -6
  2. package/client.js +3511 -185
  3. package/dist/attribution.d.ts +266 -0
  4. package/dist/attribution.js +238 -0
  5. package/dist/attribution.js.map +1 -0
  6. package/dist/bridge.d.ts +311 -13
  7. package/dist/bridge.js +714 -42
  8. package/dist/bridge.js.map +1 -1
  9. package/dist/client-bundle.js +4 -1
  10. package/dist/client-bundle.js.map +1 -1
  11. package/dist/command.js +10 -0
  12. package/dist/command.js.map +1 -1
  13. package/dist/config.d.ts +530 -22
  14. package/dist/config.js +808 -27
  15. package/dist/config.js.map +1 -1
  16. package/dist/delegation-dispatch.d.ts +132 -0
  17. package/dist/delegation-dispatch.js +186 -0
  18. package/dist/delegation-dispatch.js.map +1 -0
  19. package/dist/delegation-health.d.ts +131 -0
  20. package/dist/delegation-health.js +97 -0
  21. package/dist/delegation-health.js.map +1 -0
  22. package/dist/delegation.d.ts +148 -0
  23. package/dist/delegation.js +186 -0
  24. package/dist/delegation.js.map +1 -0
  25. package/dist/effort-delegation.d.ts +144 -0
  26. package/dist/effort-delegation.js +280 -0
  27. package/dist/effort-delegation.js.map +1 -0
  28. package/dist/effort.d.ts +141 -0
  29. package/dist/effort.js +251 -9
  30. package/dist/effort.js.map +1 -1
  31. package/dist/host-patch.d.ts +156 -0
  32. package/dist/host-patch.js +534 -0
  33. package/dist/host-patch.js.map +1 -0
  34. package/dist/index.d.ts +12 -3
  35. package/dist/index.js +99 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/interventions.d.ts +98 -373
  38. package/dist/interventions.js +442 -1702
  39. package/dist/interventions.js.map +1 -1
  40. package/dist/panel-api.d.ts +328 -4
  41. package/dist/panel-api.js +322 -15
  42. package/dist/panel-api.js.map +1 -1
  43. package/dist/panel-mount.d.ts +81 -22
  44. package/dist/panel-mount.js +228 -7
  45. package/dist/panel-mount.js.map +1 -1
  46. package/dist/routing.d.ts +23 -18
  47. package/dist/routing.js +471 -153
  48. package/dist/routing.js.map +1 -1
  49. package/dist/session-audit.d.ts +70 -0
  50. package/dist/session-audit.js +73 -0
  51. package/dist/session-audit.js.map +1 -1
  52. package/dist/systemone-probe.d.ts +114 -0
  53. package/dist/systemone-probe.js +383 -0
  54. package/dist/systemone-probe.js.map +1 -0
  55. package/dist/testing.d.ts +212 -7
  56. package/dist/testing.js +333 -27
  57. package/dist/testing.js.map +1 -1
  58. package/dist/tools.d.ts +109 -3
  59. package/dist/tools.js +103 -4
  60. package/dist/tools.js.map +1 -1
  61. package/dist/unconfigured-backend.d.ts +72 -0
  62. package/dist/unconfigured-backend.js +94 -0
  63. package/dist/unconfigured-backend.js.map +1 -0
  64. package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
  65. package/dist/vendor/harness-reflex/backend/factory.js +18 -3
  66. package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
  67. package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
  68. package/dist/vendor/harness-reflex/backend/jev.js +11 -4
  69. package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
  70. package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
  71. package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
  72. package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
  73. package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
  74. package/dist/vendor/harness-reflex/core/closing.js +111 -0
  75. package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
  76. package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
  77. package/dist/vendor/harness-reflex/core/evidence.js +209 -0
  78. package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
  79. package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
  80. package/dist/vendor/harness-reflex/core/judge.js +251 -0
  81. package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
  82. package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
  83. package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
  84. package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
  85. package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
  86. package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
  87. package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
  88. package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
  89. package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
  90. package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
  91. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
  92. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
  93. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
  94. package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
  95. package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
  96. package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
  97. package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
  98. package/dist/vendor/harness-reflex/core/policy.js +102 -0
  99. package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
  100. package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
  101. package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
  102. package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
  103. package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
  104. package/dist/vendor/harness-reflex/core/text.js +66 -0
  105. package/dist/vendor/harness-reflex/core/text.js.map +1 -0
  106. package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
  107. package/dist/vendor/harness-reflex/ports/audit.js +11 -0
  108. package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
  109. package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
  110. package/dist/vendor/harness-reflex/ports/clock.js +11 -0
  111. package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
  112. package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
  113. package/dist/vendor/harness-reflex/ports/decision.js +2 -0
  114. package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
  115. package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
  116. package/dist/vendor/harness-reflex/ports/index.js +2 -0
  117. package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
  118. package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
  119. package/dist/vendor/harness-reflex/ports/log.js +12 -0
  120. package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
  121. package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
  122. package/dist/vendor/harness-reflex/ports/state.js +13 -0
  123. package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
  124. package/package.json +25 -13
@@ -1 +1 @@
1
- {"version":3,"file":"interventions.js","sourceRoot":"","sources":["../src/interventions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAKtE,OAAO,EACL,yBAAyB,EAI1B,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,wBAAwB,EAAE,YAAY,EAAgC,MAAM,oBAAoB,CAAC;AAI1G;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,mBAAmB,CAAC;AAS5D,iFAAiF;AACjF,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,iFAAiF;AACjF,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,8EAA8E;AAC9E,MAAM,UAAU,GAAG,GAAG,CAAC;AACvB,qDAAqD;AACrD,MAAM,SAAS,GAAG,E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IACD,OAAO,UAAU,CAAC,MAAM,GAAG,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;AACxG,CAAC;AAED,8EAA8E;AAC9E,yBAAyB;AACzB,OAAO,EAAE,wBAAwB,EAAE,CAAC","sourcesContent":["/**\n * Automatic interventions on the Host's native tool and agent lifecycle hooks.\n *\n * The plugin's eight MCP tools are pull-based: they act only when the *model*\n * decides to call one. This module is the push half — the same System 1\n * judgments, spent automatically at the four points where the Host already asks\n * its listeners a question:\n *\n * | Hook | Capability | What it may do |\n * | --- | --- | --- |\n * | `tools/pre-execute` | `stagnation` | deny a call the run is repeating |\n * | `tools/post-execute` | `prune` | replace an oversized result with its reduction |\n * | `tools/post-execute` | `gate` | turn a repeated failure into corrective feedback |\n * | `agent/pre-step` | `stagnation` | attach the correction to the next step |\n * | `agent/turn-stopping` | `closing` | object to a turn closing on contradicted evidence |\n *\n * ## The three-state discipline\n *\n * Every capability runs in one of three modes. The distinction is *not* \"on/off\n * with logging\": `observe` runs the same detection, the same judgment, and the\n * same plan as `active`, and withholds only the application. That is what makes\n * the mode worth having — what observe measures is exactly what active would\n * have done, on the same payloads, at the same cost.\n *\n * | Mode | Detection | Judgment | Application | Model-visible change |\n * | --- | --- | --- | --- | --- |\n * | `off` | none | none | none | none |\n * | `observe` | full | full | none | **none at all** |\n * | `active` | full | full | full | the planned text |\n *\n * `observe` is therefore *not* the reference plugin's shadow mode: that one\n * injects a model-visible notice saying it changed nothing. Here an observation\n * has no model-visible surface whatsoever — no message, no rewritten content, no\n * denial, no steering. The one thing it produces is an audit record in the\n * session log, which the model cannot read.\n *\n * ## Cost discipline\n *\n * A deterministic, local pre-trigger decides whether a *judgment* may be spent\n * at all, and judgments are budgeted per turn and per session: at most\n * {@link ResolvedInterventionsConfig.maxJudgmentsPerTurn} per turn and\n * {@link ResolvedInterventionsConfig.maxJudgmentsPerSession} per agent, with one\n * verdict reused by every hook of the same turn. A turn presenting twenty\n * similar results therefore costs one judgment, not twenty. Applied\n * interventions carry their own ceiling, so an intervention can never become the\n * loop it was meant to break.\n *\n * ## Fail-open and isolation\n *\n * Every hook delegates first (`await next()`), and every planning step is\n * wrapped: an exception, an aborted signal, or an unusable verdict leaves the\n * call, the result, the messages, and the turn exactly as the rest of the\n * waterfall left them. Detection state is keyed by agent id, so two agents in one\n * process can never see each other's history, verdicts, or budgets. Nothing here\n * grants a permission the Host would not have granted, and nothing here overrides\n * one either: a call the rest of the waterfall denied, cancelled, or routed to an\n * approval flow is returned untouched, so the only decision this module can add\n * is a strictly narrower one on top of a plain `allow`.\n *\n * ## Retained originals\n *\n * A reduction is installed only after the bytes it replaces have been retained\n * in the agent's own Session log, in the plugin-record channel the audit trail\n * already uses. The replacement publishes a locator derived from the payload's\n * digest, a reader resolves it back to the verbatim original, and a payload that\n * cannot be retained — too large, no session, a log that did not commit — is\n * never replaced: `saved` is reported only for a replacement that really\n * happened and can really be checked.\n *\n * @module dsh-reflex/interventions\n */\nimport { createHash } from 'node:crypto';\nimport type { Context } from '@deepseek-ai/cordis';\nimport { MessageId, boundContextSummary } from '@deepseek-ai/dsh-llm';\nimport type { ContentBlock, ContextFormed, UserMessage } from '@deepseek-ai/dsh-llm';\nimport type { PreStepDecision } from '@deepseek-ai/dsh-agent';\nimport type { PostToolDecision, PreToolDecision, ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools';\n\nimport {\n INTERVENTION_CAPABILITIES,\n type InterventionCapability,\n type InterventionMode,\n type ResolvedInterventionsConfig\n} from './config.js';\nimport { appendInterventionRecord, pruneLocator, type InterventionAuditRecord } from './session-audit.js';\nimport type { ReflexGateService, StagnationDetector, ToolResultPruner } from './vendor/harness-reflex/index.js';\nimport type { ActionStep, PruneResponse, StagnationCheckResponse } from './vendor/harness-reflex/index.js';\n\n/**\n * Producer-owned source kind of every message this plugin appends.\n *\n * Session format v4 has no catch-all `plugin` kind and refuses that literal\n * outright, so the producer names itself — the same identity this plugin already\n * uses for its audit records.\n */\nexport const INTERVENTION_SOURCE_KIND = 'plugin:dsh-reflex';\n\ndeclare module '@deepseek-ai/dsh-llm' {\n interface MessageSourceMap {\n /** One corrective context this plugin attached to a step. */\n 'plugin:dsh-reflex': { kind: 'plugin:dsh-reflex' } & ContextFormed;\n }\n}\n\n/** Default share of a floored reduction's context budget taken from the head. */\nconst FLOOR_HEAD_CHARS = 400;\n/** Default share of a floored reduction's context budget taken from the tail. */\nconst FLOOR_TAIL_CHARS = 400;\n/** Characters of one observed step's input or output retained for judging. */\nconst STEP_CHARS = 600;\n/** Steps one agent's detection window may retain. */\nconst MAX_STEPS = 12;\n/** Characters of assistant text retained per turn for the closing check. */\nconst CLAIM_CHARS = 4000;\n/**\n * Evidence entries retained per turn for the closing check.\n *\n * Entries are candidates, not conclusions: every observed result contributes its\n * tail summary, and a failure-marker line is kept as a safety floor. The\n * character budget (not this count) decides what the judgment reads.\n */\nconst MAX_EVIDENCE = 16;\n/** Characters of one evidence line. */\nconst EVIDENCE_CHARS = 400;\n/** Characters of one result's tail summary. */\nconst EVIDENCE_TAIL_CHARS = 240;\n/** Characters of the \"other\" (non-diagnostic, non-tail) fallback per result. */\nconst EVIDENCE_OTHER_CHARS = 120;\n/** Completion claim candidates submitted to one closing judgment. */\nconst MAX_CLAIMS = 3;\n/** Minimum sentence length worth classifying as a claim candidate. */\nconst MIN_CLAIM_CHARS = 8;\n/** Agent states retained before the least recently used is dropped. */\nconst MAX_AGENTS = 64;\n/** Reductions memoized per activation, bounded by least recent use. */\nconst MAX_MEMO = 128;\n/** Audit records retained for the panel, per activation. */\nconst MAX_RECENT = 20;\n/** Longest corrective text this module hands to the model, in characters. */\nconst FEEDBACK_CHARS = 600;\n/**\n * Line breaks a payload needs before it is treated as line-oriented output.\n *\n * A prune rewrites a *result* — command output, a test log, a build trace — and\n * the judgment is asked to extract the diagnostics from exactly that shape. A\n * payload with no line structure (one long JSON document, a single runaway\n * line) is not that shape: its value is semantic rather than diagnostic, and\n * cutting it in half would destroy it rather than compress it. Those payloads\n * are left alone, in both modes, and the skip is reported as\n * `unsupported-payload`.\n */\nconst PRUNE_MIN_LINES = 4;\n/**\n * Largest payload this module is willing to copy into the session log.\n *\n * Retention is what makes a reduction safe, so the cap is a *precondition* of\n * pruning rather than a fallback: above it the engine reports\n * `retention-too-large` and leaves the result untouched, so an oversized\n * payload can never be reported as saved on the strength of a copy that was\n * never kept. A hundred kilobyte log line stays readable and bounded.\n */\nconst MAX_RETAINED_CHARS = 100_000;\n\n/**\n * Matches the failure markers that make a result a *candidate* for the closing\n * evidence. A hit is a safety floor: the line is kept whatever the budget says.\n * A miss is never a \"failure-free\" conclusion — the tail summary goes to System\n * One, which decides what the result means.\n */\nexport const FAILURE_MARKER = /(\\berror\\b|\\berrors\\b|\\bfailed\\b|\\bfailure\\b|\\bfailures\\b|\\bfail\\b|exit code [1-9]|\\bnot ok\\b|\\bFAIL\\b|\\bexception\\b|\\btraceback\\b)/i;\n\n/**\n * Prefilter for a failure *suspicion* — the deterministic trigger that makes a\n * closing judgment worth buying. It is broader than {@link FAILURE_MARKER}\n * because `{ok:false}`, a timeout, and a Chinese error must reach System One\n * too; none of these decides anything by itself.\n */\nconst FAILURE_CUE = new RegExp(\n `${FAILURE_MARKER.source}|\\\\bok\\\\b\\\\s*[:=]\\\\s*false|\"ok\"\\\\s*:\\\\s*false|\\\\btimed?\\\\s*out\\\\b|\\\\btimeout\\\\b|`\n + '失败|错误|异常|超时|无法|未通过|仍有失败|还有失败|报错',\n 'i'\n);\n\n/** The action names one plan may carry. */\nexport type InterventionAction =\n | 'deny-call'\n | 'prune-result'\n | 'corrective-feedback'\n | 'corrective-context'\n | 'steer-closing';\n\n/**\n * One planned intervention, before the mode decides whether it is applied.\n *\n * The plan is the *same* object in observe and active mode; only the audit\n * record's `applied` differs. That is what lets a reader compare what a mode\n * measured with what it did.\n */\nexport interface InterventionPlan {\n capability: InterventionCapability;\n action: InterventionAction;\n reason: string;\n /** Text the active path hands to the model; never empty. */\n feedback: string;\n detail: {\n pattern?: string;\n confidence?: number;\n repeats?: number;\n digest?: string;\n floorApplied?: boolean;\n /** Whether the reduction was installed short of the floor's promised share. */\n floorMissed?: boolean;\n /** Whether a floor miss had to omit its locator marker to stay smaller. */\n markerOmitted?: boolean;\n turn?: number;\n step?: number;\n /** Which judging path produced the prune candidate. */\n judgePath?: 'segmented' | 'local' | 'fallback';\n /** Segments handed to System One by the prune judgment. */\n judgedSegments?: number;\n /** Segments beyond the per-request limit, kept deterministically instead. */\n unjudgedSegments?: number;\n /** Segments the composed candidate kept whole. */\n keptSegments?: number;\n /** Characters of the aggressive-budget candidate the judgment built. */\n aggressiveChars?: number;\n /** Characters of the balanced-budget candidate the judgment built. */\n balancedChars?: number;\n /** Characters of the conservative-budget candidate the judgment built. */\n conservativeChars?: number;\n /** Segments System One really scored, out of the judged ones. */\n scoredSegments?: number;\n /** Segments kept whole without a score (the unjudged safety margin). */\n autoKeptSegments?: number;\n /** Answers returned for a judged segment that carried no usable score. */\n unparsedScoreAnswers?: number;\n /** Characters of the payload the plan was about. */\n originalChars?: number;\n /** Characters of the candidate the plan would install. */\n candidateChars?: number;\n /** Why the segmented judge fell back to the local candidates, when it did. */\n fallbackReason?: string;\n };\n}\n\n/**\n * Prune-path facts an abandoned plan carries into its audit record.\n *\n * The engine computes these on the way to a decision — the payload's identity\n * and size up front, the judged path and segment counts once the service has\n * answered — so a skip can say *which* decision path was abandoned instead of\n * only that one was. Nothing here is recomputed for the audit; the values are\n * the ones the decision itself used.\n */\nexport interface InterventionSkipDetail {\n /** Payload identity, when a payload was the subject of the decision. */\n digest?: string;\n /** Characters of that payload. */\n originalChars?: number;\n /** Characters of the candidate the decision would have installed. */\n candidateChars?: number;\n /** Tokens of that payload, when already known. */\n originalTokens?: number;\n /** Tokens of that candidate, when already known. */\n candidateTokens?: number;\n /** Whether the installed text carried the floor form (`floored` in the audit). */\n floored?: boolean;\n /** Whether the installed reduction fell short of the floor's promised share. */\n floorMissed?: boolean;\n /** Whether a floor miss had to omit its locator marker to stay smaller. */\n markerOmitted?: boolean;\n /** Which judging path produced the candidate. */\n judgePath?: 'segmented' | 'local' | 'fallback';\n /** Segments handed to System One by the judgment. */\n judgedSegments?: number;\n /** Segments beyond the per-request limit, kept deterministically instead. */\n unjudgedSegments?: number;\n /** Segments the candidate kept whole. */\n keptSegments?: number;\n /** Characters of the aggressive-budget candidate the judgment built. */\n aggressiveChars?: number;\n /** Characters of the balanced-budget candidate the judgment built. */\n balancedChars?: number;\n /** Characters of the conservative-budget candidate the judgment built. */\n conservativeChars?: number;\n /** Segments System One really scored, out of the judged ones. */\n scoredSegments?: number;\n /** Segments kept whole without a score (the unjudged safety margin). */\n autoKeptSegments?: number;\n /** Answers returned for a judged segment that carried no usable score. */\n unparsedScoreAnswers?: number;\n /** Why the segmented judge fell back to the local candidates. */\n fallbackReason?: string;\n}\n\n/** What one abandoned plan tells the audit sink about itself. */\ninterface SkipContext {\n /** Capability whose plan was abandoned. */\n capability: InterventionCapability;\n /** The deciding agent's bookkeeping, when the hook had it. */\n state?: AgentState;\n /** The agent (or payload carrying one) whose session receives the record. */\n agent?: unknown;\n /** Prune-path facts, when a payload was involved. */\n detail?: InterventionSkipDetail;\n /** The judgment this decision rode on, so a paid skip is not booked as free. */\n judgment?: JudgmentCharge;\n}\n\n/**\n * The identity of one tool call, stable across its pre- and post-execute hooks.\n * @param exec - the execution.\n * @returns the call's own identity, falling back to its name.\n */\nfunction callKeyOf(exec: ToolExecution): string {\n const token = (exec as { token?: unknown }).token;\n if (typeof token === 'string' && token.length > 0) return token;\n const callId = (exec as { callId?: unknown }).callId;\n return typeof callId === 'string' && callId.length > 0 ? callId : exec.name;\n}\n\n/**\n * The Host's background-job *query* tools, and the call shape each one needs\n * before it counts as a legitimate wait.\n *\n * This is the documented default of the stagnation exemption, and it is\n * deliberately identity-based rather than wording-based: the keys are the names\n * the DSH Host itself registers for background jobs — `@deepseek-ai/dsh-tool-jobs`\n * registers `job_output`, `job_list`, and `job_kill`, and the background modes\n * of the shell tools hand their jobs to the same `job_output` verb. The\n * tool's *description* is never parsed, and no result text is ever read, so an\n * output that happens to contain `wait`, `sleep`, or `poll` earns nothing.\n *\n * The shape is the structured job handle the call is about, in the Host's own\n * declared parameter name (`job_id`). `job_list` declares no parameters at all —\n * it lists the caller's own jobs — so its shape is the empty argument object.\n * `job_kill` is deliberately absent: it is a terminating action, not a query a\n * waiting run repeats, and a run that repeats it is not waiting for anything.\n */\nexport const WAIT_QUERY_TOOLS: Readonly<Record<string, { handles: readonly string[]; argumentless?: boolean }>> = {\n job_output: { handles: ['job_id'] },\n job_list: { handles: [], argumentless: true }\n};\n\n/**\n * One call's arguments as a plain object, or `undefined` when they are not one.\n * @param exec - the execution.\n * @returns the argument object, never an array or a primitive.\n */\nfunction structuredArguments(exec: ToolExecution): Record<string, unknown> | undefined {\n const raw: unknown = exec.arguments;\n let value: unknown = raw;\n if (typeof raw === 'string') {\n try {\n value = JSON.parse(raw);\n } catch {\n return undefined;\n }\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/**\n * Whether one call is a legitimate wait rather than a candidate repetition.\n *\n * Two structured facts decide it, and nothing else: the tool's identity in\n * {@link WAIT_QUERY_TOOLS}, and the argument shape that identity requires — a\n * non-empty job handle in a string field the Host itself declares. A call that\n * repeats the same handle is exactly the sanctioned poll of a background job, so\n * its repetition carries no information about progress, while any other tool\n * (however its output reads) is judged as before.\n *\n * @param exec - the call about to run.\n * @returns whether the call is a wait query.\n */\nexport function isWaitQuery(exec: ToolExecution): boolean {\n const shape = WAIT_QUERY_TOOLS[exec.name];\n if (!shape) return false;\n const args = structuredArguments(exec);\n if (!args) return false;\n if (shape.argumentless === true) return Object.keys(args).length === 0;\n return shape.handles.some((field) => typeof args[field] === 'string' && (args[field] as string).length > 0);\n}\n\n/** Field names that name a background handle a status query is about. */\nconst POLL_HANDLE_FIELD = /(?:^|_)(?:job|task|run|process|pid|handle|call|query|poll|id)$/i;\n\n/**\n * The argument shape that makes a *non-listed* repetition a wait suspect.\n *\n * The tool-name list is deliberately narrow (the Host's own job tools), but a\n * run can wait through another backend's poll verb. A non-empty handle-shaped\n * field is the cue that the repetition may be a status query; it only makes the\n * call worth asking about — System One still decides whether it is a wait.\n * @param exec - the call about to run.\n * @returns a shape label, or `undefined` when the arguments carry no handle.\n */\nexport function pollShapeOf(exec: ToolExecution): string | undefined {\n const args = structuredArguments(exec);\n if (!args) return undefined;\n for (const [key, value] of Object.entries(args)) {\n if (!POLL_HANDLE_FIELD.test(key)) continue;\n if (typeof value === 'string' && value.length > 0) return 'poll-handle';\n if (typeof value === 'number' && Number.isFinite(value)) return 'poll-handle';\n }\n return undefined;\n}\n\n/** A compact, bounded rendering of one call's arguments. */\nfunction argumentShapeOf(exec: ToolExecution): string {\n const args = structuredArguments(exec);\n if (!args) return 'non-object';\n const entries = Object.entries(args).map(([key, value]) => {\n const rendered = value === null || typeof value !== 'object' ? clip(String(value), 60) : '…';\n return `${key}=${rendered}`;\n });\n return entries.length > 0 ? entries.join(', ') : 'empty';\n}\n\n/**\n * The context one wait question carries into the stagnation judgment.\n *\n * It is *context*, not a verdict: the tool name, the argument shape, and the\n * repeat count let System One tell a sanctioned wait from a no-progress loop,\n * and nothing here allows or refuses the call by itself.\n */\nexport function waitGoalOf(exec: ToolExecution, shape: string, repeats: number): string {\n return [\n `suspect: ${shape}`,\n `tool: ${exec.name}`,\n `argument-shape: ${argumentShapeOf(exec)}`,\n `repeats: ${repeats}`,\n 'A repeated status/job query can be a legitimate wait for background work rather than a no-progress loop; decide from the action history and the polled outputs.'\n ].join('; ');\n}\n\n/**\n * Label each poll of one series with its place in it.\n *\n * The backend reasons about the run, not about string identity: two polls of the\n * same job are successive observations, and telling them apart keeps a\n * sanctioned wait from being read as the same action retried forever. Every\n * other step is passed through untouched.\n * @param steps - the window the question is about.\n * @param signature - identity of the poll being proposed.\n * @returns a copy with `[poll #n]` appended to each poll's input.\n */\nexport function annotateWaitHistory(steps: readonly ObservedStep[], signature: string): ObservedStep[] {\n let poll = 0;\n return steps.map((step) => {\n if (step.signature !== signature) return step;\n poll += 1;\n return { ...step, input: clip(`${step.input} [poll #${poll}]`, STEP_CHARS) };\n });\n}\n\n/** One step of one agent's detection window. */\ninterface ObservedStep {\n /** `tool:argumentsDigest` — the identity a repetition is measured on. */\n signature: string;\n tool: string;\n input: string;\n output: string;\n error: string;\n failed: boolean;\n turn: number;\n at: number;\n /** Whether the step was a legitimate wait query (see {@link isWaitQuery}). */\n wait?: boolean;\n}\n\n/**\n * The window a stagnation trigger and its judgment are measured on.\n *\n * A wait query is not progress the run can be repeating: an identically repeated\n * status/result query of the same background job is the sanctioned way to wait,\n * so those steps are dropped before the repetition, failure, and oscillation\n * triggers read the window. Genuine calls on either side of a wait stay adjacent\n * instead of being separated by it, which is what keeps a real loop visible\n * while a run is waiting.\n * @param steps - observed steps, oldest first.\n * @returns the steps that count as progress.\n */\nfunction progressSteps(steps: readonly ObservedStep[]): readonly ObservedStep[] {\n return steps.some((step) => step.wait === true) ? steps.filter((step) => step.wait !== true) : steps;\n}\n\n/** One agent's detection state, budgets, and counters. */\ninterface AgentState {\n /** Session this agent's state belongs to; memoized reductions never cross it. */\n sessionKey: string;\n turn: number;\n step: number;\n steps: ObservedStep[];\n /** Assistant text of the current turn, for the closing check. */\n claims: string;\n /** Evidence candidates the current turn produced (see {@link EvidenceEntry}). */\n evidence: EvidenceEntry[];\n /** Whether any evidence candidate is a failure suspicion worth judging. */\n evidenceSuspect: boolean;\n /** Interventions applied in the current turn. */\n interventions: number;\n judgmentsTurn: number;\n judgmentsCount: number;\n judgmentsSession: number;\n verdictTurn: number;\n /** Identity of the window the cached verdict was about. */\n verdictKey: string;\n verdict?: StagnationCheckResponse;\n /** Wait-suspect call identities already classified this turn. */\n waited: Set<string>;\n /** Identities this turn already intervened on, so no action repeats itself. */\n applied: Set<string>;\n /** Call signatures already refused this turn. */\n denied: Set<string>;\n /** Calls this engine refused, keyed by the call identity. */\n refused: Set<string>;\n}\n\n/** One token and latency account of a mode or a capability. */\nexport interface InterventionCostBucket {\n /** Decisions planned. */\n plans: number;\n /** Decisions whose plan was executed. */\n applied: number;\n /** System 1 judgments paid for. */\n judgments: number;\n /** Judgments served from the per-turn verdict memo instead of a new call. */\n memoHits: number;\n /** Milliseconds spent in local, deterministic work. */\n localLatencyMs: number;\n /** Milliseconds spent waiting for System 1. */\n remoteLatencyMs: number;\n /** Tokens the judgments reasoned about. */\n judgeTokens: number;\n /** Tokens of the payloads decisions were made about. */\n originalTokens: number;\n /** Tokens the candidates would carry. */\n candidateTokens: number;\n /** Tokens the candidates would have saved. */\n potentialSavedTokens: number;\n /** Tokens actually removed from the model-visible surface. */\n actualSavedTokens: number;\n /** Tokens actually added to the model-visible surface. */\n injectedTokens: number;\n}\n\n/** The baseline side of the accounting: what the hooks were shown, untouched. */\nexport interface InterventionBaseline {\n /** Results the post-execute hook was shown. */\n results: number;\n /** Tokens those results carried. */\n originalTokens: number;\n /** Failing results the post-execute hook was shown. */\n failures: number;\n}\n\n/** One activation's intervention accounting, as the panel and tests read it. */\nexport interface InterventionReport {\n mode: InterventionMode;\n capabilities: Record<InterventionCapability, InterventionMode>;\n baseline: InterventionBaseline;\n observe: InterventionCostBucket;\n active: InterventionCostBucket;\n byCapability: Record<InterventionCapability, InterventionCostBucket>;\n /** Hook-level refusals, by reason, sorted. */\n skips: Record<string, number>;\n /** The most recent decisions, oldest first, bounded. */\n recent: InterventionAuditRecord[];\n /**\n * Originals this activation retained before replacing them.\n *\n * `copies` counts every verified retention; `locators` keeps the most recent\n * ones, so a reader can resolve a live replacement back to its bytes without\n * scanning the whole log.\n */\n retained: { copies: number; locators: string[] };\n /**\n * Closing-evidence bytes kept vs. dropped by the character budget.\n *\n * Truncation is by priority (diagnostic lines, then tail summaries, then the\n * rest); a diagnostic floor line is never dropped, so a nonzero `truncatedChars`\n * describes tail/other material only.\n */\n evidence: { retainedChars: number; truncatedChars: number };\n}\n\n/** Dependencies of one intervention engine. */\nexport interface InterventionEngineOptions {\n /** Resolved `interventions` block. */\n config: ResolvedInterventionsConfig;\n /** Character threshold above which a result is a pruning candidate. */\n pruneThreshold: number;\n stagnation: Pick<StagnationDetector, 'check'>;\n prune: Pick<ToolResultPruner, 'prune'>;\n /** Verification plus the closing-claim classification that precedes it. */\n gate: Pick<ReflexGateService, 'verify' | 'classifyClaims'>;\n /** Names of this plugin's own tools: their output is already optimized. */\n ownTools?: readonly string[];\n /** Clock seam. */\n now?: () => number;\n /**\n * Controlled retention of a payload a reduction is about to replace.\n *\n * Mandatory for pruning: the engine asks the sink to keep the original, and\n * only a *verifiable* copy — the locator the replacement will publish — makes\n * the reduction installable. A sink that returns `undefined`, throws, or is not\n * configured at all leaves the result untouched and the saving at zero, so a\n * deployment without controlled retention still runs, it just does not prune.\n */\n retain?: (session: unknown, request: PruneRetentionRequest) => PruneRetention | undefined;\n /** Audit sink; the plugin attaches the session log here. */\n audit?: (record: InterventionAuditRecord, session: unknown) => void;\n}\n\n/** A fresh, zeroed cost bucket. */\nfunction emptyBucket(): InterventionCostBucket {\n return {\n plans: 0,\n applied: 0,\n judgments: 0,\n memoHits: 0,\n localLatencyMs: 0,\n remoteLatencyMs: 0,\n judgeTokens: 0,\n originalTokens: 0,\n candidateTokens: 0,\n potentialSavedTokens: 0,\n actualSavedTokens: 0,\n injectedTokens: 0\n };\n}\n\n/**\n * The payload half of a prune decision's audit fields.\n *\n * Taken before the service is asked, so a branch that refuses the payload early\n * still names the payload it refused. An empty payload has no identity worth\n * recording.\n * @param text - the effective text the decision is about.\n * @returns the digest and size of that text, or nothing for an empty payload.\n */\nfunction prunePayloadDetail(text: string): InterventionSkipDetail {\n return text.length === 0 ? {} : { digest: digestOf(text), originalChars: text.length };\n}\n\n/**\n * The judgment-path half of a prune decision's audit fields.\n *\n * Pure pass-through of what the prune service computed: which path produced the\n * candidate, how many segments it judged, and why it fell back when it did.\n * @param response - the service's answer.\n * @returns the diagnostics it reported.\n */\nfunction pruneDiagnosticsOf(response: PruneResponse): InterventionSkipDetail {\n return {\n ...(response.judgePath === undefined ? {} : { judgePath: response.judgePath }),\n ...(response.judgedSegments === undefined ? {} : { judgedSegments: response.judgedSegments }),\n ...(response.unjudgedSegments === undefined ? {} : { unjudgedSegments: response.unjudgedSegments }),\n ...(response.keptSegments === undefined ? {} : { keptSegments: response.keptSegments }),\n ...(response.aggressiveChars === undefined ? {} : { aggressiveChars: response.aggressiveChars }),\n ...(response.balancedChars === undefined ? {} : { balancedChars: response.balancedChars }),\n ...(response.conservativeChars === undefined ? {} : { conservativeChars: response.conservativeChars }),\n ...(response.scoredSegments === undefined ? {} : { scoredSegments: response.scoredSegments }),\n ...(response.autoKeptSegments === undefined ? {} : { autoKeptSegments: response.autoKeptSegments }),\n ...(response.unparsedScoreAnswers === undefined ? {} : { unparsedScoreAnswers: response.unparsedScoreAnswers }),\n ...(response.fallbackReason === undefined ? {} : { fallbackReason: response.fallbackReason })\n };\n}\n\n/**\n * Tokens one text costs, at the ledger's shared four-characters-per-token rate.\n * @param text - any text.\n * @returns the estimated token count.\n */\nexport function estimateTokens(text: string): number {\n return text.length === 0 ? 0 : Math.ceil(text.length / 4);\n}\n\n/**\n * Stable short digest of one value, used as a tool-call identity.\n * @param value - the text to digest.\n * @returns sixteen hexadecimal characters.\n */\nexport function digestOf(value: string): string {\n return createHash('sha256').update(value).digest('hex').slice(0, 16);\n}\n\n/**\n * Concatenate the text blocks of one content list.\n * @param content - message or result content.\n * @returns the text, in block order.\n */\nexport function textOfContent(content: readonly ContentBlock[] | undefined): string {\n if (!content) return '';\n const parts: string[] = [];\n for (const block of content) {\n if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') {\n parts.push((block as { text?: string }).text ?? '');\n }\n }\n return parts.join('\\n');\n}\n\n/**\n * Whether one content list carries at least one text block.\n * @param content - message or result content.\n * @returns whether there is text to rewrite.\n */\nexport function hasTextBlock(content: readonly ContentBlock[] | undefined): boolean {\n if (!content) return false;\n for (const block of content) {\n if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') return true;\n }\n return false;\n}\n\n/**\n * Bound one text to a character budget, marking the cut.\n * @param text - any text.\n * @param max - maximum characters to keep.\n * @returns the bounded text.\n */\nfunction clip(text: string, max: number): string {\n return text.length <= max ? text : `${text.slice(0, max)}…`;\n}\n\n// ── what counts as a failed result ──────────────────────────────────────────\n\n/**\n * The exit status one tool result carries in its own canonical value.\n *\n * A shell result is *reported*, not errored: a command that exits 1 returns a\n * successful `ToolExecutionResult` whose `value.exitCode` is the whole truth. The\n * distinction matters twice over — a correction that never fires because the\n * failure looked like a success, and a closing check that reads a green claim\n * over a red build — so the status is taken from the tool's own structured field\n * whenever the payload exposes one.\n *\n * @param value - the result's canonical value, when it has one.\n * @returns the exit status, or `undefined` when the value is not a shell result.\n */\nexport function structuredExitStatus(value: unknown): { exitCode: number; signal?: string } | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const candidate = value as { exitCode?: unknown; signal?: unknown };\n if (typeof candidate.exitCode !== 'number' || !Number.isFinite(candidate.exitCode)) return undefined;\n const status: { exitCode: number; signal?: string } = { exitCode: candidate.exitCode };\n if (typeof candidate.signal === 'string') status.signal = candidate.signal;\n return status;\n}\n\n/**\n * Whether the text ends in the Host's own exit marker for a failed command.\n *\n * The marker is the last line of the model-facing content, so anchoring it to the\n * end of the text keeps an *ordinary* result that merely mentions \"exit code 1\"\n * in its body from being misread as a failure. This is the fallback for a result\n * that carries no structured value — a Virtual tool, a replay from an older\n * record — not a replacement for {@link structuredExitStatus}.\n * @param text - the model-facing text.\n * @returns whether the last marker line reports a non-zero exit or a signal.\n */\nexport function exitMarkerFailure(text: string): boolean {\n const match = /(?:^|\\n)\\[exit code: ([0-9]+)\\]\\s*$/.exec(text);\n if (match) return Number(match[1]) !== 0;\n return /(?:^|\\n)\\[killed by signal: [^\\]\\n]+\\]\\s*$/.test(text);\n}\n\n/**\n * Whether one result is a failure the interventions may act on.\n *\n * Three sources, in order of authority: the Host's own `isError` flag, the exit\n * status inside the tool's structured value, and the exit marker the Host appends\n * to the text. A text heuristic over words like \"failed\" is deliberately absent:\n * a test log that prints the word is not a failing command, and treating it as\n * one would both spend a judgment on it and block a legitimate retry.\n *\n * @param result - the execution-local result.\n * @param text - the effective model-facing text of that result.\n * @returns whether the result proves a failure.\n */\nexport function failureOf(result: Readonly<ToolExecutionResult> | undefined, text: string): boolean {\n if (!result) return false;\n if (result.isError === true) return true;\n const status = structuredExitStatus((result as { value?: unknown }).value);\n if (status) return status.exitCode !== 0 || status.signal !== undefined;\n return exitMarkerFailure(text);\n}\n\n/**\n * Priority of one closing-evidence candidate when the budget truncates.\n *\n * `diagnostic` lines are the safety floor: a FAILURE_MARKER hit is kept even\n * past the budget. `tail` summaries carry the structured/status facts of every\n * observed result (so `{ok:false}`, a timeout, or a Chinese error reaches System\n * One). `other` is the head fallback, dropped first.\n */\nexport type EvidencePriority = 'diagnostic' | 'tail' | 'other';\n\n/** One candidate the closing judgment may read. */\nexport interface EvidenceEntry {\n /** Tool that produced the result. */\n tool: string;\n /** Bounded line or summary. */\n text: string;\n /** Truncation priority (lower is safer). */\n priority: EvidencePriority;\n /** Whether the result behind this entry is a failure suspicion. */\n suspect: boolean;\n}\n\n/** The primitive structured facts one result exposes, for the tail summary. */\nfunction structuredFacts(\n result: Readonly<ToolExecutionResult> | undefined\n): Record<string, string | number | boolean> {\n const facts: Record<string, string | number | boolean> = {};\n if (!result) return facts;\n if (result.isError !== undefined) facts.isError = result.isError === true;\n const status = structuredExitStatus((result as { value?: unknown }).value);\n if (status) {\n facts.exitCode = status.exitCode;\n if (status.signal !== undefined) facts.signal = status.signal;\n }\n let value: unknown = (result as { value?: unknown }).value;\n if (typeof value === 'string' && /^\\s*[{[]/.test(value)) {\n try {\n value = JSON.parse(value);\n } catch {\n value = undefined;\n }\n }\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n const record = value as Record<string, unknown>;\n for (const key of ['ok', 'status', 'timedOut', 'timeout', 'isError', 'exitCode', 'signal']) {\n const field = record[key];\n if (typeof field === 'string' || typeof field === 'number' || typeof field === 'boolean') facts[key] = field;\n }\n }\n return facts;\n}\n\n/** Whether structured facts alone prove (or at least suspect) a failure. */\nfunction factsSuspectFailure(facts: Readonly<Record<string, string | number | boolean>>): boolean {\n if (facts.isError === true) return true;\n if (typeof facts.exitCode === 'number' && facts.exitCode !== 0) return true;\n if (typeof facts.signal === 'string' && facts.signal.length > 0) return true;\n if (facts.ok === false || facts.timedOut === true || facts.timeout === true) return true;\n if (typeof facts.status === 'string' && /fail|error|timeout|timed_?out/i.test(facts.status)) return true;\n return false;\n}\n\n/**\n * Turn one observed result into closing-evidence candidates.\n *\n * The regex is a prefilter and a floor, never a conclusion: matching lines are\n * kept whatever else happens, and a non-matching result still contributes its\n * tail summary (with the structured facts) to System One. A result is a failure\n * *suspicion* when a structured fact, a marker line, or a broader cue says so;\n * what the result really means is decided by `gate.verify`.\n *\n * @param tool - tool name that produced the result.\n * @param result - the execution-local result.\n * @param text - the effective model-facing text.\n * @returns bounded candidates, diagnostics first.\n */\nexport function evidenceOf(\n tool: string,\n result: Readonly<ToolExecutionResult> | undefined,\n text: string\n): EvidenceEntry[] {\n const entries: EvidenceEntry[] = [];\n const lines = text.split(/\\r?\\n/);\n const diagnostics = lines.filter((line) => FAILURE_MARKER.test(line));\n for (const line of diagnostics) {\n const clipped = clip(line.trim(), EVIDENCE_CHARS);\n if (clipped.length > 0) entries.push({ tool, text: clipped, priority: 'diagnostic', suspect: true });\n }\n const facts = structuredFacts(result);\n const factText = Object.keys(facts).length > 0 ? `{${JSON.stringify(facts)}} ` : '';\n const collapsed = text.replace(/\\s+/g, ' ').trim();\n const tail = clip(`${factText}${collapsed}`, EVIDENCE_TAIL_CHARS);\n if (tail.length > 0) {\n entries.push({\n tool,\n text: `${tool} tail: ${tail}`,\n priority: 'tail',\n suspect:\n failureOf(result, text)\n || diagnostics.length > 0\n || factsSuspectFailure(facts)\n || FAILURE_CUE.test(text)\n });\n }\n if (diagnostics.length === 0) {\n const head = clip(collapsed, EVIDENCE_OTHER_CHARS);\n if (head.length > 0) {\n entries.push({ tool, text: `${tool}: ${head}`, priority: 'other', suspect: FAILURE_CUE.test(text) });\n }\n }\n return entries;\n}\n\n/**\n * Assemble the turn's evidence candidates into one budgeted string.\n *\n * Priority order is diagnostic → tail → other. A diagnostic line is the safety\n * floor and is never dropped; everything else competes for the budget and the\n * dropped characters are reported so the truncation is auditable.\n *\n * @param entries - candidates, oldest first.\n * @param budget - character budget of the assembled text.\n * @returns assembled text plus the kept/dropped character counts.\n */\nexport function assembleEvidence(\n entries: readonly EvidenceEntry[],\n budget: number\n): { text: string; retainedChars: number; truncatedChars: number } {\n const lines: string[] = [];\n let retained = 0;\n let truncated = 0;\n for (const priority of ['diagnostic', 'tail', 'other'] as const) {\n for (const entry of entries) {\n if (entry.priority !== priority) continue;\n const size = entry.text.length + (lines.length > 0 ? 1 : 0);\n const fits = priority === 'diagnostic' || retained + size <= budget;\n if (!fits) {\n truncated += size;\n continue;\n }\n lines.push(entry.text);\n retained += size;\n }\n }\n return { text: lines.join('\\n'), retainedChars: retained, truncatedChars: truncated };\n}\n\n/**\n * The floor decision of one reduction, computed from lengths alone.\n *\n * {@link pruneFloorPlan} returns the *decision*: whether the floor applies and\n * the size that decision was modelled on. {@link applyPruneFloor} returns the\n * same decision next to the size the composed text *really* has, because line\n * alignment and duplicate removal move that size. Callers account for the text\n * a mode really installs, so the composed numbers are the authoritative ones.\n */\nexport interface PruneFloorPlan {\n /** Whether the floor form replaces the judged candidate. */\n floored: boolean;\n /**\n * Whether the installed reduction fell short of the floor's promised share.\n *\n * True exactly when the composition could not build a form that both carries\n * `floorRatio` of the original and stays smaller than it, so the judged\n * candidate itself was installed. It is what separates \"nothing was reduced\"\n * from \"the reduction was real, but it did not reach the floor's promise\"; a\n * plan that never needed the floor reports `false`.\n */\n floorMissed: boolean;\n /** Characters the installed text carries: modelled by the plan, real once composed. */\n resultChars: number;\n /** Characters the installed form does not carry. */\n omittedChars: number;\n /** Context characters taken from the head of the original. */\n headChars: number;\n /** Context characters taken from the tail of the original. */\n tailChars: number;\n /**\n * Marker characters the installed form carries, summed over its sides.\n *\n * Zero when nothing is floored, one marker when only the mandatory locator side\n * fits, two when the share's budget can pay for a matching marker after the\n * candidate. Publishing it is what lets {@link applyPruneFloor} rebuild exactly\n * the form whose size the plan promised.\n */\n markerChars: number;\n /**\n * Whether a floor-missed install wanted the locator marker but could not carry it.\n *\n * The marker is what tells a reader that the reduction happened and where the\n * full payload lives, so a candidate that fits only *without* it is still\n * installed — the reduction is real — but the omission is recorded instead of\n * being silently dropped. Always `false` when `floorMissed` is false.\n */\n markerOmitted: boolean;\n}\n\n/** The floor options shared by the plan and the composition. */\nexport interface PruneFloorOptions {\n /** Lowest share of the original a reduction may keep. */\n floorRatio: number;\n /** Default split of the context budget, in characters. */\n headChars?: number;\n /** Default split of the context budget, in characters. */\n tailChars?: number;\n /**\n * Length of the marker the installed form carries per side.\n *\n * A caller that composes a locator-carrying form passes the real marker\n * length here; a caller that only accounts for it passes the same number. That\n * is what keeps the predicted size and the installed size identical in both\n * modes.\n */\n markerChars?: number;\n}\n\n/**\n * Decide the deterministic floor of one reduction from lengths alone.\n *\n * Lengths are enough because the floor form is fixed: context, marker, candidate,\n * marker, context. Deciding it this way is what lets `observe` account for the\n * *same* candidate `active` would install without building it.\n *\n * The floor is a *share*, not a suggestion. `pruneFloorRatio` says how much of\n * the original must survive, so the context budget is derived from it rather than\n * capped by the head/tail hints: a candidate that keeps 8% of a long payload is\n * not \"floored\" to 8% plus two small slices, it is widened until the installed\n * form really carries the promised share. The head/tail hints only decide how\n * that budget is split. A plan that cannot reach the share — because the marker\n * alone would eat the whole allowance — is refused, so a reduction never grows\n * the context.\n *\n * @param originalChars - length of the raw payload.\n * @param candidateChars - length of the judged candidate.\n * @param options - floor ratio, split hints, and marker length.\n * @returns the floor decision.\n */\nexport function pruneFloorPlan(\n originalChars: number,\n candidateChars: number,\n options: PruneFloorOptions\n): PruneFloorPlan {\n if (candidateChars === 0 || candidateChars >= originalChars) {\n return idleFloorPlan(originalChars);\n }\n const marker = Math.max(0, options.markerChars ?? 0);\n const head = Math.max(0, options.headChars ?? FLOOR_HEAD_CHARS);\n const tail = Math.max(0, options.tailChars ?? FLOOR_TAIL_CHARS);\n const share = Math.min(1, Math.max(0, options.floorRatio));\n const target = Math.ceil(originalChars * share);\n // The judged candidate is already the installed text when the floor does not\n // apply, and it carries no marker; only a deeper cut pays for the marker.\n if (candidateChars >= target) {\n return {\n floored: false,\n floorMissed: false,\n resultChars: candidateChars,\n omittedChars: originalChars - candidateChars,\n headChars: 0,\n tailChars: 0,\n markerChars: 0,\n markerOmitted: false\n };\n }\n // One marker side is mandatory: it carries the locator of the original. The\n // second is bought only when the share's budget leaves room for it. A candidate\n // that cannot even pay for the mandatory marker is still a real reduction, so\n // it is installed *without* the marker and the omission is recorded: dropping\n // it would trade a smaller answer for the whole payload over a missing line.\n if (candidateChars + marker >= originalChars) {\n return {\n floored: false,\n floorMissed: true,\n resultChars: candidateChars,\n omittedChars: originalChars - candidateChars,\n headChars: 0,\n tailChars: 0,\n markerChars: 0,\n markerOmitted: true\n };\n }\n let budget = Math.max(candidateChars + marker, Math.min(originalChars, target));\n let markerChars = marker;\n let context = budget - candidateChars - markerChars;\n if (context >= marker) {\n markerChars += marker;\n context -= marker;\n }\n const split = splitContext(context, head, tail);\n const resultChars = candidateChars + markerChars + context;\n if (resultChars >= originalChars) return idleFloorPlan(originalChars);\n return {\n floored: true,\n floorMissed: false,\n resultChars,\n omittedChars: originalChars - resultChars,\n headChars: split.head,\n tailChars: split.tail,\n markerChars,\n markerOmitted: false\n };\n}\n\n/**\n * Split one context budget between the head and the tail.\n *\n * The hints describe the *shape* of the context, not its ceiling, so a large\n * budget keeps their proportion instead of stopping at their sum. A zero-shaped\n * split degrades to an even one rather than dropping the context.\n * @param context - characters available for context.\n * @param head - head hint.\n * @param tail - tail hint.\n * @returns the two slice lengths, summing to the context.\n */\nfunction splitContext(context: number, head: number, tail: number): { head: number; tail: number } {\n const total = head + tail;\n const headChars = total <= 0 ? Math.ceil(context / 2) : Math.ceil((context * head) / total);\n return { head: Math.min(context, headChars), tail: context - Math.min(context, headChars) };\n}\n\n/** The plan of a reduction that is not happening. */\nfunction idleFloorPlan(originalChars: number): PruneFloorPlan {\n return {\n floored: false,\n floorMissed: false,\n resultChars: originalChars,\n omittedChars: 0,\n headChars: 0,\n tailChars: 0,\n markerChars: 0,\n markerOmitted: false\n };\n}\n\n/** The marker one floored reduction carries on each side of its candidate. */\nexport function pruneMarker(locator: string): string {\n return `\\n… [reflex prune: full original retrievable as ${locator}] …\\n`;\n}\n\n/**\n * The marker a floor-missed install appends after its candidate.\n *\n * The floored form opens with the marker because the head has just ended with a\n * newline. A candidate that already ends with one needs no blank line before the\n * marker, so only the leading newline is dropped in that case; the trailing\n * newline is the same one the floored form carries.\n * @param candidate - the judged candidate about to be installed.\n * @param marker - the locator marker.\n * @returns the suffix to append.\n */\nfunction pruneMarkerSuffix(candidate: string, marker: string): string {\n return candidate.endsWith('\\n') ? marker.slice(1) : marker;\n}\n\n/** Split one payload into whole lines, the terminator kept with its line. */\nfunction floorLines(text: string): string[] {\n return text.match(/[^\\n]*\\n|[^\\n]+$/g) ?? [];\n}\n\n/** The identity of one line for the duplicate test: its text without its terminator. */\nfunction floorLineIdentity(line: string): string {\n return line.replace(/\\r?\\n$/, '').replace(/\\r$/, '');\n}\n\n/**\n * How many whole lines of the head a budget can pay for.\n *\n * The head never crosses its budget and never stops inside a line: a cut that\n * cannot pay for the next line stops before it, so the kept prefix is always a\n * run of complete lines.\n * @param lines - the payload, split into whole lines.\n * @param budget - characters the head may spend.\n * @returns the number of lines to keep from the top.\n */\nfunction alignedHeadLines(lines: readonly string[], budget: number): number {\n let used = 0;\n let count = 0;\n for (const line of lines) {\n if (used + line.length > budget) break;\n used += line.length;\n count += 1;\n }\n return count;\n}\n\n/**\n * How many whole lines of the tail a budget needs.\n *\n * The tail is the *shortest* run of complete lines from the end that still\n * carries the budget. A payload whose lines are longer than the budget cannot\n * honour it with a line-aligned suffix; the caller refuses instead of cutting\n * one, because half a line is not a shorter answer but a broken one.\n * @param lines - the payload, split into whole lines.\n * @param budget - characters the tail must carry.\n * @returns the number of lines to keep from the bottom.\n */\nfunction alignedTailLines(lines: readonly string[], budget: number): number {\n if (budget <= 0) return 0;\n let used = 0;\n let count = 0;\n for (let index = lines.length - 1; index >= 0; index -= 1) {\n used += lines[index]!.length;\n count += 1;\n if (used >= budget) break;\n }\n return count;\n}\n\n/**\n * Drop the candidate lines the kept context already shows verbatim.\n *\n * The judgment reads the whole payload, so its extract repeats the lines a\n * reader can already see around it — `BEGIN`, `RESULT`, `END` in the trace that\n * prompted this. Repeating them is pure cost: the same line twice in one\n * message. Removal is per line and verbatim, so a diagnostic the context does\n * *not* carry always survives.\n * @param candidate - the judged extract.\n * @param head - the kept head.\n * @param tail - the kept tail.\n * @returns the candidate without the lines the context already shows.\n */\nfunction dedupeCandidateLines(candidate: string, head: string, tail: string): string {\n const seen = new Set([...floorLines(head), ...floorLines(tail)].map(floorLineIdentity));\n const lines = floorLines(candidate);\n if (seen.size === 0 || lines.length === 0) return candidate;\n return lines.filter((line) => !seen.has(floorLineIdentity(line))).join('');\n}\n\n/** One composed floor form and the sizes it really kept. */\ninterface ComposedFloor {\n text: string;\n headChars: number;\n tailChars: number;\n markerChars: number;\n}\n\n/**\n * Compose one floored form out of whole lines of the original.\n * @param lines - the original, split into whole lines.\n * @param headCount - lines kept from the top.\n * @param tailCount - lines kept from the bottom.\n * @param candidate - the judged extract.\n * @param marker - the locator marker.\n * @param secondMarker - the closing marker, or `''` when the share cannot pay for it.\n * @returns the installed text and the sizes it really carries.\n */\nfunction composeFloorLines(\n lines: readonly string[],\n headCount: number,\n tailCount: number,\n candidate: string,\n marker: string,\n secondMarker: string\n): ComposedFloor {\n const head = lines.slice(0, headCount).join('');\n const tail = tailCount === 0 ? '' : lines.slice(lines.length - tailCount).join('');\n const middle = dedupeCandidateLines(candidate, head, tail);\n // The marker opens with a newline so it sits on its own line after the head.\n // With no head there is nothing to separate it from, and a leading blank line\n // would be the first thing a reader sees.\n const lead = head.length === 0 ? marker.replace(/^\\n/, '') : marker;\n const closing = middle.length === 0 ? '' : secondMarker;\n return {\n text: `${head}${lead}${middle}${closing}${tail}`,\n headChars: head.length,\n tailChars: tail.length,\n markerChars: lead.length + closing.length\n };\n}\n\n/**\n * The plan of a floor the composition refused.\n *\n * A refusal is *not* a reason to throw the candidate away. The candidate is the\n * reduction the judgment already produced, and a floor that cannot widen it\n * without either breaking the share or growing past the original has simply\n * missed the floor, not invalidated the reduction: installing the candidate is\n * strictly better than carrying the whole payload. So the candidate is installed\n * with `floored: false` (no head/tail form was built) and `floorMissed: true`\n * (the promised share is not carried), and the sizes are booked against the text\n * that is really installed.\n *\n * The locator marker is appended when the candidate can still pay for it, so the\n * reader sees that a prune happened and where the full payload lives. When the\n * marker would push the install to the original's size or past it, the reduction\n * wins and the marker is omitted — recorded as `markerOmitted: true`, never\n * silently dropped.\n *\n * Only a candidate that is not actually smaller leaves the original untouched —\n * that is a real \"no reduction\", and the caller's own degradation path owns it.\n *\n * @param original - the raw payload.\n * @param candidate - the judged reduction the composition could not widen.\n * @param marker - the locator marker a floor-missed install wants to carry.\n * @returns the text to install and the floor decision that says why.\n */\nfunction refusedFloor(original: string, candidate: string, marker: string): PruneFloorPlan & { text: string } {\n if (candidate.length >= original.length) {\n return { ...idleFloorPlan(original.length), text: original };\n }\n const suffix = pruneMarkerSuffix(candidate, marker);\n if (candidate.length + suffix.length < original.length) {\n return {\n floored: false,\n floorMissed: true,\n resultChars: candidate.length + suffix.length,\n omittedChars: original.length - candidate.length - suffix.length,\n headChars: 0,\n tailChars: 0,\n markerChars: suffix.length,\n markerOmitted: false,\n text: `${candidate}${suffix}`\n };\n }\n return {\n floored: false,\n floorMissed: true,\n resultChars: candidate.length,\n omittedChars: original.length - candidate.length,\n headChars: 0,\n tailChars: 0,\n markerChars: 0,\n markerOmitted: true,\n text: candidate\n };\n}\n\n/**\n * Enforce the deterministic floor of a judged reduction.\n *\n * The judgment proposes; this floor disposes. A candidate that cut deeper than\n * {@link ResolvedInterventionsConfig.pruneFloorRatio} of the original is replaced\n * by a form that keeps the head and the tail — the two places a compiler error, a\n * stack-trace summary, and a final result usually are — around the judgment's own\n * extract, with explicit markers that name where the full original was retained.\n * A candidate that is not actually smaller is refused outright, so a \"reduction\"\n * can never grow the context.\n *\n * The context is composed out of *whole lines* of the original, never out of\n * character slices: a cut that lands mid-line leaves the reader a fragment like\n * `=] progress 092`, which is not a shorter answer but a broken one. The head is\n * the longest run of complete lines its budget can pay for, the tail the shortest\n * run of complete lines that still carries its own, and any candidate line the\n * kept context already shows verbatim is dropped as a duplicate. Alignment and\n * removal move the real size, so the decision's modelled size is replaced here by\n * the size the text really has: a form that would fall short of the promised\n * share, or that would not be smaller than the original at all, is refused. A\n * refusal installs the judgment's own candidate with `floorMissed: true` rather\n * than the original — the candidate is a real reduction, and dropping it would\n * trade a smaller answer for the whole payload just because the floor form could\n * not be built.\n *\n * @param original - the raw payload.\n * @param candidate - the judged reduction.\n * @param options - floor options plus the locator the replacement publishes.\n * @returns the text to install, the floor decision, and the sizes involved.\n */\nexport function applyPruneFloor(\n original: string,\n candidate: string,\n options: PruneFloorOptions & { locator: string }\n): PruneFloorPlan & { text: string } {\n const marker = pruneMarker(options.locator);\n const plan = pruneFloorPlan(original.length, candidate.length, { ...options, markerChars: marker.length });\n if (!plan.floored) {\n return { ...plan, text: plan.resultChars === candidate.length ? candidate : original };\n }\n const lines = floorLines(original);\n const share = Math.min(1, Math.max(0, options.floorRatio));\n const target = Math.ceil(original.length * share);\n const secondMarker = plan.markerChars > marker.length ? marker : '';\n let headCount = alignedHeadLines(lines, plan.headChars);\n if (headCount === 0 && plan.headChars > 0 && lines.length > 0) {\n // A first line longer than the head budget: taking it whole keeps a real line\n // where a cut could only produce a fragment. Whether the enlarged form is\n // installable at all is decided by the size checks below.\n headCount = 1;\n }\n let tailCount = alignedTailLines(lines, plan.tailChars);\n if (headCount + tailCount > lines.length) return refusedFloor(original, candidate, marker);\n let composed = composeFloorLines(lines, headCount, tailCount, candidate, marker, secondMarker);\n // The share is a promise, and rounding to a boundary or dropping duplicates can\n // fall short of it: widen by whole lines until the form really carries the\n // share. A payload with no room left is refused by the checks below, never\n // installed short.\n while (composed.text.length < target) {\n // Grow the smaller side first, so the two keep their configured proportion.\n const order = composed.headChars <= composed.tailChars ? [0, 1] : [1, 0];\n let grew = false;\n for (const side of order) {\n const nextHead = side === 0 ? headCount + 1 : headCount;\n const nextTail = side === 1 ? tailCount + 1 : tailCount;\n if (nextHead + nextTail > lines.length) continue;\n const next = composeFloorLines(lines, nextHead, nextTail, candidate, marker, secondMarker);\n if (next.text.length <= composed.text.length) continue;\n headCount = nextHead;\n tailCount = nextTail;\n composed = next;\n grew = true;\n break;\n }\n if (!grew) break;\n }\n if (composed.text.length >= original.length || composed.text.length < target) {\n return refusedFloor(original, candidate, marker);\n }\n return {\n ...plan,\n resultChars: composed.text.length,\n omittedChars: original.length - composed.text.length,\n headChars: composed.headChars,\n tailChars: composed.tailChars,\n markerChars: composed.markerChars,\n text: composed.text\n };\n}\n\n/**\n * Count the identical trailing repeats of one signature.\n * @param steps - observed steps, oldest first.\n * @param signature - the identity to count.\n * @returns the length of the trailing run of that signature.\n */\nexport function countTrailingRepeats(steps: readonly ObservedStep[], signature: string): number {\n let count = 0;\n for (let index = steps.length - 1; index >= 0; index -= 1) {\n if (steps[index]!.signature !== signature) break;\n count += 1;\n }\n return count;\n}\n\n/**\n * Count the trailing consecutive failures.\n * @param steps - observed steps, oldest first.\n * @returns the length of the trailing run of failing steps.\n */\nexport function countTrailingFailures(steps: readonly ObservedStep[]): number {\n let count = 0;\n for (let index = steps.length - 1; index >= 0; index -= 1) {\n if (!steps[index]!.failed) break;\n count += 1;\n }\n return count;\n}\n\n/**\n * Whether the window's tail alternates between exactly two call identities.\n *\n * `A B A B` is the cheapest loop to miss and among the most wasteful to run:\n * neither call repeats consecutively, so a consecutive-repeat trigger never\n * fires.\n * @param steps - observed steps, oldest first.\n * @param window - how many trailing steps to inspect.\n * @returns whether the tail oscillates.\n */\nexport function detectOscillation(steps: readonly ObservedStep[], window: number): boolean {\n const tail = steps.slice(Math.max(0, steps.length - window));\n if (tail.length < 4) return false;\n const signatures = new Set(tail.map((step) => step.signature));\n if (signatures.size !== 2) return false;\n for (let index = 2; index < tail.length; index += 1) {\n if (tail[index]!.signature !== tail[index - 2]!.signature) return false;\n }\n return true;\n}\n\n/** Why a deterministic pre-trigger wants a judgment. */\nexport interface StagnationSuspicion {\n suspicious: boolean;\n /** The pattern the trigger suspects, before System 1 confirms it. */\n pattern?: 'repetition' | 'oscillation' | 'failing_retry';\n /** Human-readable trigger facts, for the audit record. */\n note: string;\n /** How many steps the pattern was measured on. */\n repeats: number;\n}\n\n/**\n * Decide, locally and deterministically, whether a judgment is worth spending.\n *\n * This is the cost gate of the whole module: the expensive path is a System 1\n * call, and it only opens when the *cheap* path already sees a pattern. A single\n * distinctive call is never judged, however large its output.\n *\n * @param steps - observed steps, oldest first.\n * @param options - thresholds, window, and the current call identity.\n * @returns the suspicion, with `suspicious: false` when nothing justifies a call.\n */\nexport function suspicionOf(\n steps: readonly ObservedStep[],\n options: { repeatThreshold: number; failureThreshold: number; window: number; signature: string }\n): StagnationSuspicion {\n const window = steps.slice(Math.max(0, steps.length - options.window));\n const repeats = countTrailingRepeats(window, options.signature);\n if (repeats >= options.repeatThreshold) {\n return { suspicious: true, pattern: 'repetition', note: `identical call repeated ${repeats}x`, repeats };\n }\n const failures = countTrailingFailures(window);\n if (failures >= options.failureThreshold) {\n return { suspicious: true, pattern: 'failing_retry', note: `${failures} consecutive failing steps`, repeats: failures };\n }\n if (detectOscillation(window, options.window)) {\n return { suspicious: true, pattern: 'oscillation', note: `two calls alternating over ${window.length} steps`, repeats: window.length };\n }\n return { suspicious: false, note: 'no local pattern', repeats: 0 };\n}\n\n/** One memoized reduction, keyed by the payload's digest within one session. */\ninterface PruneMemo {\n /** The real reduction, absent until the mode that installs one has computed it. */\n text?: string;\n originalChars: number;\n prunedChars: number;\n tokensSaved: number;\n /** Whether the reduction was floored, so a memo hit reports the same plan. */\n floored: boolean;\n /** Whether the reduction missed the floor's promised share, replayed on a hit. */\n floorMissed?: boolean;\n /** Whether that miss installed without its locator marker, replayed on a hit. */\n markerOmitted?: boolean;\n /** Locator of the retained original, once a retention for this payload succeeded. */\n locator?: string;\n /**\n * Diagnostics of the judgment that composed this form.\n *\n * Replayed by a memo hit so its audit record keeps the provenance of the plan\n * that really judged the payload, instead of looking like a path that never\n * ran the judge. Observability only: no decision reads these back.\n */\n diagnostics?: Pick<\n PruneResponse,\n | 'judgePath'\n | 'judgedSegments'\n | 'unjudgedSegments'\n | 'keptSegments'\n | 'aggressiveChars'\n | 'balancedChars'\n | 'conservativeChars'\n | 'scoredSegments'\n | 'autoKeptSegments'\n | 'unparsedScoreAnswers'\n | 'fallbackReason'\n >;\n}\n\n/**\n * What the engine hands its retention sink before it replaces a payload.\n *\n * The request carries the payload *verbatim*, so a sink never has to reconstruct\n * it, and the digest, so the sink can name it the same way the judgment and the\n * replacement do.\n */\nexport interface PruneRetentionRequest {\n /** Payload identity: `digestOf(text)`. */\n digest: string;\n /** Identity and name of the call whose result is about to shrink. */\n callId: string;\n tool: string;\n /** Turn and step of the replacement. */\n turn: number;\n step: number;\n /** The replaced payload, verbatim. */\n text: string;\n}\n\n/** The controlled copy one retention produced. */\nexport interface PruneRetention {\n /** Locator the replacement publishes. */\n locator: string;\n /** Committed log position, when the sink can report one. */\n seq?: number;\n}\n\n/** What one judgment cost, charged exactly once per judgment. */\ninterface JudgmentCharge {\n judgments: number;\n memoHits: number;\n localLatencyMs: number;\n remoteLatencyMs: number;\n judgeTokens: number;\n}\n\n/** One charge against a mode's and a capability's account. */\ninterface Charge {\n judgments?: number;\n memoHits?: number;\n localLatencyMs?: number;\n remoteLatencyMs?: number;\n judgeTokens?: number;\n originalTokens?: number;\n candidateTokens?: number;\n potentialSavedTokens?: number;\n actualSavedTokens?: number;\n injectedTokens?: number;\n}\n\n/** The verdict that stands in when no judgment could be spent. */\nconst EMPTY_VERDICT: StagnationCheckResponse = { isStuck: false, confidence: 0, latencyMs: 0 };\n\n/**\n * The automatic-intervention engine of one plugin activation.\n *\n * One instance serves every agent in the process; all per-agent facts live in\n * {@link AgentState}, keyed by agent id, so isolation is structural rather than\n * conventional.\n */\nexport class InterventionEngine {\n /**\n * Resolved `interventions` block currently in force.\n *\n * Mutable through {@link updatePolicy}: the loader commits a config-only save\n * into the running activation, and every hook below reads this block per call,\n * so a threshold change is effective on the very next tool call without\n * rebuilding the engine (and without re-spending a schema run on the hot path).\n */\n #config: ResolvedInterventionsConfig;\n /** Character count above which a result is a pruning candidate (live). */\n #pruneThreshold: number;\n readonly #stagnation: Pick<StagnationDetector, 'check'>;\n readonly #prune: Pick<ToolResultPruner, 'prune'>;\n readonly #gate: Pick<ReflexGateService, 'verify' | 'classifyClaims'>;\n readonly #now: () => number;\n readonly #retain?: (session: unknown, request: PruneRetentionRequest) => PruneRetention | undefined;\n readonly #audit?: (record: InterventionAuditRecord, session: unknown) => void;\n\n readonly #states = new Map<string, AgentState>();\n #ownTools: ReadonlySet<string>;\n readonly #memo = new Map<string, PruneMemo>();\n readonly #costs: { observe: InterventionCostBucket; active: InterventionCostBucket };\n readonly #byCapability: Record<InterventionCapability, InterventionCostBucket>;\n readonly #baseline: InterventionBaseline = { results: 0, originalTokens: 0, failures: 0 };\n readonly #skips = new Map<string, number>();\n readonly #recent: InterventionAuditRecord[] = [];\n readonly #retained: string[] = [];\n readonly #evidenceStats = { retainedChars: 0, truncatedChars: 0 };\n #retainedCopies = 0;\n #counter = 0;\n\n /**\n * @param options - services, thresholds, clock, and audit sink.\n */\n constructor(options: InterventionEngineOptions) {\n this.#config = options.config;\n this.#pruneThreshold = options.pruneThreshold;\n this.#stagnation = options.stagnation;\n this.#prune = options.prune;\n this.#gate = options.gate;\n this.#now = options.now ?? (() => Date.now());\n this.#retain = options.retain;\n this.#audit = options.audit;\n this.#ownTools = new Set(options.ownTools ?? []);\n this.#costs = { observe: emptyBucket(), active: emptyBucket() };\n this.#byCapability = {\n stagnation: emptyBucket(),\n prune: emptyBucket(),\n gate: emptyBucket(),\n closing: emptyBucket()\n };\n }\n\n /** The resolved intervention block currently in force. */\n get config(): ResolvedInterventionsConfig {\n return this.#config;\n }\n\n /**\n * Replace the live policy.\n *\n * Called once per actual config commit (never per tool call). Detectors and\n * per-turn state are deliberately *not* reset: a turn that is already running\n * keeps its counters and latches, and only the values each hook reads change.\n * @param config - the freshly resolved `interventions` block.\n * @param pruneThreshold - the freshly resolved top-level prune threshold.\n * @param ownTools - the live `reflex_*` names of this activation. A prefix\n * edit renames every tool, so a frozen set would stop recognising the\n * plugin's own output and start judging it as foreign work.\n */\n updatePolicy(config: ResolvedInterventionsConfig, pruneThreshold: number, ownTools?: readonly string[]): void {\n this.#config = config;\n this.#pruneThreshold = pruneThreshold;\n if (ownTools !== undefined) this.#ownTools = new Set(ownTools);\n // The pruning service also carries a copy of the threshold (the explicit\n // `prune` tool reads it directly). Keep it in step, otherwise lowering the\n // threshold would still be shadowed by the activation-time value. Absent on\n // the test seams that only implement `prune()`.\n (this.#prune as { setMinCharsThreshold?: (value: number) => void }).setMinCharsThreshold?.(pruneThreshold);\n }\n\n /** The tool names this activation treats as its own (live). */\n get ownTools(): readonly string[] {\n return [...this.#ownTools];\n }\n\n /** Whether any capability may act at all. */\n get enabled(): boolean {\n return this.config.enabled;\n }\n\n /**\n * Effective mode of one capability.\n * @param capability - the capability to ask about.\n * @returns its resolved three-state mode.\n */\n modeOf(capability: InterventionCapability): InterventionMode {\n return this.config.capabilities[capability];\n }\n\n /**\n * Whether a hook serving one capability must be registered at all.\n * @param capabilities - capabilities the hook serves.\n * @returns whether at least one of them is not `off`.\n */\n serves(...capabilities: InterventionCapability[]): boolean {\n if (!this.config.enabled) return false;\n return capabilities.some((capability) => this.modeOf(capability) !== 'off');\n }\n\n /** The whole activation's accounting. */\n report(): InterventionReport {\n return {\n mode: this.config.mode,\n capabilities: { ...this.config.capabilities },\n baseline: { ...this.#baseline },\n observe: { ...this.#costs.observe },\n active: { ...this.#costs.active },\n byCapability: {\n stagnation: { ...this.#byCapability.stagnation },\n prune: { ...this.#byCapability.prune },\n gate: { ...this.#byCapability.gate },\n closing: { ...this.#byCapability.closing }\n },\n skips: Object.fromEntries([...this.#skips.entries()].sort()),\n recent: [...this.#recent],\n retained: { copies: this.#retainedCopies, locators: [...this.#retained] },\n evidence: { ...this.#evidenceStats }\n };\n }\n\n /**\n * Whether one capability already acted on one identity this turn.\n * @param agentId - agent identity.\n * @param key - capability-qualified identity.\n * @returns whether it already acted.\n */\n hasApplied(agentId: string, key: string): boolean {\n return this.#states.get(agentId)?.applied.has(key) ?? false;\n }\n\n /**\n * Detection state of one agent, for tests and diagnostics.\n * @param agentId - agent identity.\n * @returns the observable facts, or undefined for an agent never seen.\n */\n stateOf(\n agentId: string\n ): { turn: number; step: number; steps: number; interventions: number; judgmentsSession: number; claims: number; evidence: number } | undefined {\n const state = this.#states.get(agentId);\n if (!state) return undefined;\n return {\n turn: state.turn,\n step: state.step,\n steps: state.steps.length,\n interventions: state.interventions,\n judgmentsSession: state.judgmentsSession,\n claims: state.claims.length,\n evidence: state.evidence.length\n };\n }\n\n /**\n * Drop one agent's state — on disposal, so nothing outlives its session.\n * @param agentId - agent identity.\n */\n forget(agentId: string): void {\n this.#states.delete(agentId);\n }\n\n /** Drop every agent's state and every account, for a fresh measurement. */\n reset(): void {\n this.#states.clear();\n this.#memo.clear();\n this.#costs.observe = emptyBucket();\n this.#costs.active = emptyBucket();\n for (const capability of INTERVENTION_CAPABILITIES) this.#byCapability[capability] = emptyBucket();\n this.#baseline.results = 0;\n this.#baseline.originalTokens = 0;\n this.#baseline.failures = 0;\n this.#skips.clear();\n this.#recent.length = 0;\n this.#retained.length = 0;\n this.#retainedCopies = 0;\n this.#evidenceStats.retainedChars = 0;\n this.#evidenceStats.truncatedChars = 0;\n }\n\n // ── hook entry points ──────────────────────────────────────────────────────\n\n /**\n * `tools/pre-execute`: refuse a call the run is repeating.\n *\n * Delegates first and returns the downstream decision **by identity** whenever\n * that decision is not a plain `allow`. A later listener may already have sent\n * the call to an approval flow, denied it with its own structured error\n * identity, or cancelled it; overwriting any of those would drop information the\n * Host attached and could turn a stricter decision into a weaker one. The only\n * decision this hook ever *adds* is a `deny` on top of an `allow`, which is\n * strictly narrower than what the waterfall already permitted — permissions\n * here are monotone by construction, never escalated and never relaxed.\n *\n * @param exec - the tool call about to run.\n * @param next - the rest of the waterfall.\n * @returns the decision the Host dispatches on.\n */\n async toolCall(exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision> {\n const downstream = await next();\n const capability = this.modeOf('stagnation');\n if (capability === 'off' || !this.config.enabled) return downstream;\n if (this.#ownTools.has(exec.name)) return downstream;\n if (exec.signal?.aborted) return downstream;\n\n let waitSuspected = false;\n const started = this.#now();\n try {\n const agentId = agentKeyOf(exec.agent);\n const state = this.#state(agentId, exec.agent);\n const signature = callSignature(exec);\n // The call about to run is part of its own window: three identical calls\n // are a repetition at the moment the third one is proposed, and the\n // judgment has to see all three. The pending entry is local — it is not\n // committed to the agent's history, which the result records for real.\n const pending = this.#observed(state, exec, signature);\n const allWindow = [...state.steps, pending];\n // Wait queries already in the window are dropped from the *progress*\n // trigger: they are not progress the run could be repeating, and keeping\n // them would both hide a real loop that waits between its attempts and\n // manufacture an oscillation out of two identical polls.\n const window = progressSteps(allWindow);\n const waitShape = isWaitQuery(exec) ? 'wait-query' : pollShapeOf(exec);\n // A wait-suspect call that this turn already classified is answered by\n // that verdict, not re-asked; anything else is only worth a question when\n // it actually repeats (the same threshold as any other repetition).\n if (waitShape !== undefined && state.waited.has(signature)) {\n this.#skip('wait-query', { capability: 'stagnation', state, agent: exec.agent });\n return downstream;\n }\n const priorSame = allWindow.filter((step) => step.signature === signature).length - 1;\n let suspicion = suspicionOf(window, {\n repeatThreshold: this.config.repeatThreshold,\n failureThreshold: this.config.failureThreshold,\n window: this.config.windowSize,\n signature\n });\n if (waitShape !== undefined && priorSame + 1 >= this.config.repeatThreshold) {\n // The tool list only decides that this repetition is worth asking\n // about; it does not pass or refuse anything by itself.\n suspicion = {\n suspicious: true,\n pattern: 'repetition',\n note: `wait-suspect ${waitShape} repeated ${priorSame + 1}x`,\n repeats: priorSame + 1\n };\n waitSuspected = true;\n }\n if (!suspicion.suspicious || state.denied.has(signature)) return downstream;\n if (state.applied.has(`stagnation:${signature}`)) {\n this.#skip('duplicate-intervention', { capability: 'stagnation', state, agent: exec.agent });\n return downstream;\n }\n if (!this.#actionWithinBudget(state)) {\n this.#skip('intervention-cap', { capability: 'stagnation', state, agent: exec.agent });\n return downstream;\n }\n\n // A wait question is judged on the polls themselves (each labelled with\n // its place in the series, so the backend can read a wait rather than an\n // exact repeat); every other question keeps the progress-only window.\n const judgeSteps = waitSuspected ? annotateWaitHistory(allWindow, signature) : window;\n const verdict = await this.#judge(\n state,\n exec.signal,\n judgeSteps,\n waitSuspected ? waitGoalOf(exec, waitShape ?? 'poll-shape', priorSame + 1) : undefined\n );\n const judgment = this.#judgmentCharge(verdict, started, this.#now());\n // Denial is latched per signature whether or not it was applied: in observe\n // mode the refusal is what would have happened, and `denied` is what keeps\n // the *next* identical attempt from being judged again in the same turn.\n state.denied.add(signature);\n if (!verdict.useful) {\n this.#charge('stagnation', judgment);\n if (waitSuspected) state.waited.add(signature);\n // A budget/abort skip keeps its own reason; only a real \"not stuck\"\n // answer to a wait question is recorded as the wait outcome.\n this.#skip(verdict.skip ?? (waitSuspected ? 'wait-query' : 'unconfirmed'), {\n capability: 'stagnation',\n state,\n agent: exec.agent,\n judgment\n });\n return downstream;\n }\n\n const plan: InterventionPlan = {\n capability: 'stagnation',\n action: 'deny-call',\n reason: `System 1 confirmed ${verdict.response.patternType ?? suspicion.pattern} stagnation before ${exec.name}`,\n feedback: this.#denyFeedback(exec.name, suspicion, verdict.response),\n detail: {\n pattern: String(verdict.response.patternType ?? suspicion.pattern ?? 'unknown'),\n confidence: verdict.response.confidence,\n repeats: suspicion.repeats,\n turn: state.turn,\n step: state.step\n }\n };\n const applied = capability === 'active' && downstream.kind === 'allow';\n if (capability === 'active' && !applied) {\n this.#skip('downstream-decided', { capability: 'stagnation', state, agent: exec.agent });\n }\n // The decision is latched in both modes. Observe has to plan exactly what\n // active would do — one refusal per episode, subject to the same turn cap —\n // otherwise its column would over-count the very thing it is measuring.\n state.refused.add(callKeyOf(exec));\n state.applied.add(`stagnation:${signature}`);\n this.#bookAction(state);\n this.#conclude(plan, applied, exec.agent, { potentialSavedTokens: 0 }, judgment);\n return applied ? { kind: 'deny', reason: plan.feedback } : downstream;\n } catch {\n // FAIL-OPEN: a planning failure must never veto a call the rest of the\n // waterfall already allowed. A wait whose judge could not answer is\n // reported with its own reason instead of the generic one.\n this.#skip(waitSuspected ? 'wait-query-unavailable' : 'planning-error', {\n capability: 'stagnation',\n agent: exec.agent\n });\n return downstream;\n }\n }\n\n /**\n * `tools/post-execute`: reduce an oversized result, or correct a repeated\n * failure — and observe both without touching either.\n *\n * @param exec - the call that produced the result.\n * @param result - its canonical outcome.\n * @param next - the rest of the waterfall.\n * @returns the decision the Host commits.\n */\n async toolResult(\n exec: ToolExecution,\n result: Readonly<ToolExecutionResult>,\n next: () => Promise<PostToolDecision>\n ): Promise<PostToolDecision> {\n const downstream = await next();\n if (!this.config.enabled) return downstream;\n if (this.#ownTools.has(exec.name)) return downstream;\n const started = this.#now();\n try {\n const agentId = agentKeyOf(exec.agent);\n const state = this.#state(agentId, exec.agent);\n if (state.refused.has(callKeyOf(exec))) {\n // The result of a call this engine refused is the refusal itself. It is\n // neither evidence about the run nor a payload worth reducing, and\n // correcting it would bill one episode twice.\n this.#skip('refused-result', { capability: 'prune', state, agent: exec.agent });\n return downstream;\n }\n // The *effective* content: whatever the rest of the waterfall decided the\n // model will read, which is not the same thing as the result's own content.\n // An earlier listener may have replaced it, and the replacement is what this\n // hook must reason about and, in active mode, reduce.\n const content = 'content' in downstream && Array.isArray(downstream.content) ? downstream.content : result.content;\n const text = textOfContent(content);\n const failed = failureOf(result, text);\n const signature = callSignature(exec);\n this.#observe(state, {\n signature,\n tool: exec.name,\n input: clip(this.#argumentsOf(exec), STEP_CHARS),\n output: clip(text, STEP_CHARS),\n error: failed ? clip(this.#errorOf(result), STEP_CHARS) : '',\n failed,\n turn: state.turn,\n at: this.#now(),\n wait: isWaitQuery(exec)\n });\n\n this.#baseline.results += 1;\n this.#baseline.originalTokens += estimateTokens(text);\n if (failed) this.#baseline.failures += 1;\n\n // Every result contributes evidence candidates: a failure-marker line is\n // the safety floor, a tail summary carries the structured/status facts,\n // and the closing judgment — not a regex — decides what they mean.\n this.#rememberEvidence(state, exec.name, result, text, this.#errorOf(result));\n if (!failed) return await this.#pruneResult(exec, downstream, content, state, text, started);\n return await this.#correctFailure(exec, result, downstream, state, signature, started);\n } catch {\n // FAIL-OPEN: the result is handed on exactly as the waterfall produced it.\n this.#skip('planning-error', { capability: 'prune', agent: exec.agent });\n return downstream;\n }\n }\n\n /**\n * `agent/pre-step`: attach the correction to the step after the loop repeated\n * itself, and keep the turn and step bookkeeping every other hook shares.\n *\n * @param payload - the proposed step.\n * @param next - the rest of the waterfall.\n * @returns the decision the loop enters with.\n */\n async preStep(\n payload: { agent: unknown; messages: readonly UserMessage[]; turn: number; step: number; signal?: AbortSignal },\n next: () => Promise<PreStepDecision>\n ): Promise<PreStepDecision> {\n const downstream = await next();\n const started = this.#now();\n try {\n const agentId = agentKeyOf(payload.agent);\n const state = this.#state(agentId, payload.agent);\n // Turn bookkeeping is unconditional: the closing check needs the turn's own\n // words and evidence to exist even when stagnation is off.\n if (state.turn !== payload.turn) {\n state.turn = payload.turn;\n state.step = payload.step;\n state.interventions = 0;\n state.judgmentsCount = 0;\n state.judgmentsTurn = payload.turn;\n state.verdictTurn = payload.turn;\n state.verdictKey = '';\n state.verdict = undefined;\n state.claims = '';\n state.evidence = [];\n state.evidenceSuspect = false;\n state.waited.clear();\n state.applied.clear();\n state.denied.clear();\n state.refused.clear();\n }\n state.step = payload.step;\n\n const capability = this.modeOf('stagnation');\n if (capability === 'off' || !this.config.enabled) return downstream;\n if (payload.signal?.aborted || downstream.kind !== 'enter') return downstream;\n\n const last = state.steps[state.steps.length - 1];\n if (last === undefined) return downstream;\n // A poll that already passed the semantic wait judgment has nothing to\n // correct here: the run asked about a background job again, it did not\n // repeat its work. A poll this turn never judged was not a repetition, so\n // it is not a stagnation episode either.\n if (last.wait === true) {\n this.#skip(state.waited.has(last.signature) ? 'wait-query' : 'wait-query-unjudged', {\n capability: 'stagnation',\n state,\n agent: payload.agent\n });\n return downstream;\n }\n const signature = last.signature;\n if (state.applied.has(`stagnation:${signature}`)) {\n this.#skip('duplicate-intervention', { capability: 'stagnation', state, agent: payload.agent });\n return downstream;\n }\n if (!this.#actionWithinBudget(state)) {\n this.#skip('intervention-cap', { capability: 'stagnation', state, agent: payload.agent });\n return downstream;\n }\n // The same window the pre-execute trigger measures: waits are not progress\n // to count, so a real loop either side of them is still one loop.\n const window = progressSteps(state.steps);\n const suspicion = suspicionOf(window, {\n repeatThreshold: this.config.repeatThreshold,\n failureThreshold: this.config.failureThreshold,\n window: this.config.windowSize,\n signature\n });\n if (!suspicion.suspicious) return downstream;\n\n const verdict = await this.#judge(state, payload.signal, window);\n const judgment = this.#judgmentCharge(verdict, started, this.#now());\n if (!verdict.useful) {\n this.#charge('stagnation', judgment);\n this.#skip(verdict.skip ?? 'unconfirmed', {\n capability: 'stagnation',\n state,\n agent: payload.agent,\n judgment\n });\n return downstream;\n }\n\n const plan: InterventionPlan = {\n capability: 'stagnation',\n action: 'corrective-context',\n reason: `System 1 confirmed ${verdict.response.patternType ?? suspicion.pattern} stagnation before step ${payload.step}`,\n feedback: this.#contextFeedback(suspicion, verdict.response),\n detail: {\n pattern: String(verdict.response.patternType ?? suspicion.pattern ?? 'unknown'),\n confidence: verdict.response.confidence,\n repeats: suspicion.repeats,\n turn: state.turn,\n step: payload.step\n }\n };\n const applied = capability === 'active';\n // The latch is mode-independent on purpose. Observe has to consume the same\n // episode — one intervention per detected loop, one charge against the turn's\n // cap — or its accounting would describe a run nobody could reproduce;\n // installing the message is the only thing the mode gates.\n state.applied.add(`stagnation:${signature}`);\n this.#bookAction(state);\n this.#conclude(plan, applied, payload.agent, { potentialSavedTokens: 0 }, judgment);\n if (!applied) return downstream;\n return {\n ...downstream,\n messages: [...downstream.messages, this.#message(agentId, state.turn, payload.step, plan.feedback)]\n };\n } catch {\n // FAIL-OPEN: the step enters with exactly the messages it would have had.\n this.#skip('planning-error', { capability: 'stagnation', agent: payload.agent });\n return downstream;\n }\n }\n\n /**\n * `agent/turn-stopping`: object when the turn is about to close on evidence\n * that contradicts what the turn claims.\n *\n * The objection is *data*, not a veto: this method steers the corrective text\n * into the agent's inbox, and the loop's own rule decides. Steering is the only\n * way a listener may extend a turn, so a failure here can never block a turn\n * from closing.\n *\n * @param payload - the agent whose turn reached its stop boundary.\n */\n async turnStopping(payload: { agent: unknown; turn: number; signal?: AbortSignal }): Promise<void> {\n const capability = this.modeOf('closing');\n if (capability === 'off' || !this.config.enabled) return;\n const started = this.#now();\n try {\n const agentId = agentKeyOf(payload.agent);\n const state = this.#state(agentId, payload.agent);\n const claimsText = state.claims;\n // Two deterministic facts decide whether a closing judgment is worth\n // buying: the turn said something, and at least one result is a failure\n // suspicion. Neither fact concludes *which* sentence claims completion —\n // that is the System One question asked below.\n if (claimsText.length === 0 || !state.evidenceSuspect) return;\n const candidates = claimCandidates(claimsText);\n if (candidates.length === 0) return;\n if (state.applied.has(`closing:turn:${payload.turn}`)) {\n this.#skip('duplicate-intervention', { capability: 'closing', state, agent: payload.agent });\n return;\n }\n if (!this.#actionWithinBudget(state)) {\n this.#skip('intervention-cap', { capability: 'closing', state, agent: payload.agent });\n return;\n }\n if (payload.signal?.aborted) return;\n\n // Assemble what the judgment will read. Truncation is by priority and\n // never removes a failure-marker line; the amount dropped is reported.\n const assembled = assembleEvidence(state.evidence, this.config.closingEvidenceChars);\n this.#evidenceStats.retainedChars += assembled.retainedChars;\n this.#evidenceStats.truncatedChars += assembled.truncatedChars;\n if (assembled.truncatedChars > 0) {\n this.#skip('evidence-truncated', { capability: 'closing', state, agent: payload.agent });\n }\n\n // The closing classification is a judgment like any other: one request\n // with at most MAX_CLAIMS scored questions, bought from the same turn and\n // session budget as a stagnation check.\n const classifySkip = this.#spendJudgment(state);\n if (classifySkip) {\n this.#skip(classifySkip, { capability: 'closing', state, agent: payload.agent });\n return;\n }\n const classifyStarted = this.#now();\n let classification: Awaited<ReturnType<ReflexGateService['classifyClaims']>>;\n try {\n classification = await this.#gate.classifyClaims({\n statements: candidates,\n intent: this.config.intent,\n context: assembled.text.slice(0, 600)\n });\n } catch {\n // FAIL-OPEN: an unavailable classifier must not become a model-visible\n // objection, and it must never fall back to the retired word list.\n this.#skip('closing-claim-unavailable', { capability: 'closing', state, agent: payload.agent });\n return;\n }\n const claims = classification.results\n .filter((item) => item.isClaim && item.confidence >= this.config.claimMinConfidence)\n .map((item) => ({ statement: item.statement }));\n const classifyTokens = candidates.reduce((sum, statement) => sum + estimateTokens(statement), 0);\n const classificationCharge: JudgmentCharge = {\n judgments: 1,\n memoHits: 0,\n localLatencyMs: Math.max(0, this.#now() - classifyStarted - classification.latencyMs),\n remoteLatencyMs: classification.latencyMs,\n judgeTokens: classifyTokens\n };\n if (claims.length === 0) {\n this.#charge('closing', classificationCharge);\n this.#skip('closing-no-claim', {\n capability: 'closing',\n state,\n agent: payload.agent,\n judgment: classificationCharge\n });\n return;\n }\n\n // Classification and verification are one logical closing judgment: the\n // classification decides *whether* anything is worth verifying, and both\n // requests are charged (tokens and latency) against the one judgment the\n // turn budget allowed.\n const verdict = await this.#gate.verify(claims, assembled.text, {\n latchCacheKey: `reflex-closing:${agentId}:${payload.turn}`\n });\n const judgeTokens =\n classifyTokens + claims.reduce((sum, item) => sum + estimateTokens(item.statement), estimateTokens(assembled.text));\n const judgment: JudgmentCharge = {\n judgments: 1,\n memoHits: 0,\n localLatencyMs: Math.max(0, this.#now() - started - verdict.latencyMs - classification.latencyMs),\n remoteLatencyMs: classification.latencyMs + verdict.latencyMs,\n judgeTokens\n };\n // `escalate` is not a contradiction. It means the gate could not decide —\n // an unavailable backend degrades exactly this way — and steering a turn on\n // an undecided verdict would turn a backend failure into a model-visible\n // objection. Only a verdict that really contradicts the claim steers.\n const contradicted = verdict.results\n .filter((item) => item.outcome === 'contradicted')\n .map((item) => clip(item.statement, 160));\n const undecided = verdict.results.filter((item) => item.outcome === 'escalate').length;\n if (contradicted.length === 0) {\n this.#charge('closing', judgment);\n this.#skip(undecided > 0 ? 'closing-undecided' : verdict.passed ? 'closing-evidence-consistent' : 'closing-unconfirmed', {\n capability: 'closing',\n state,\n agent: payload.agent,\n judgment\n });\n return;\n }\n\n const plan: InterventionPlan = {\n capability: 'closing',\n action: 'steer-closing',\n reason: `closing evidence contradicts ${contradicted.length} completion claim(s)`,\n feedback: this.#closingFeedback(contradicted),\n detail: { confidence: verdict.results[0]?.confidence, turn: payload.turn, step: state.step }\n };\n const applied = capability === 'active';\n // Latched in both modes, for the same reason as the stagnation path: the\n // episode is consumed once, and only the steering is gated on the mode.\n state.applied.add(`closing:turn:${payload.turn}`);\n this.#bookAction(state);\n this.#conclude(plan, applied, payload.agent, { potentialSavedTokens: 0 }, judgment);\n if (applied) this.#steer(payload.agent, this.#message(agentId, payload.turn, state.step, plan.feedback));\n } catch {\n // FAIL-OPEN: a failed closing check leaves the turn boundary alone.\n this.#skip('planning-error', { capability: 'closing', agent: payload.agent });\n }\n }\n\n /**\n * `agent/assistant-stream`: retain the turn's own words for the closing check.\n *\n * Deliberately not model-visible: this is a read of what the model already\n * said, kept so the turn can be checked against its own evidence. Nothing is\n * published, and the text is bounded per turn.\n *\n * @param payload - one stream frame of one attempt.\n */\n observeAssistantStream(payload: { agent: unknown; frame?: { type?: string; chunk?: { type?: string; text?: string } } }): void {\n if (!this.serves('closing')) return;\n try {\n const frame = payload.frame;\n if (frame?.type !== 'chunk' || frame.chunk?.type !== 'text-delta') return;\n const text = frame.chunk.text ?? '';\n if (text.length === 0) return;\n const state = this.#state(agentKeyOf(payload.agent), payload.agent);\n state.claims = clip(`${state.claims}${text}`, CLAIM_CHARS);\n } catch {\n // Advisory only: a malformed frame must not disturb streaming.\n }\n }\n\n // ── capabilities ───────────────────────────────────────────────────────────\n\n /**\n * Plan, and in active mode apply, the reduction of one oversized result.\n *\n * The order of operations here *is* the safety property, so it is spelled out:\n * decide whether this payload is one the module is willing to rewrite, make sure\n * an original can be retained, buy a judgment from the shared budget, obtain the\n * real candidate, retain the original, build the replacement, check that the\n * replacement really shrank the text, and only then record a saving. Every \"no\"\n * on that path returns the downstream decision untouched, which is why an\n * unverifiable reduction can never be reported as applied.\n *\n * @param exec - the call that produced the result.\n * @param downstream - what the rest of the waterfall decided.\n * @param effective - the content the model will read (`downstream` first).\n * @param state - the deciding agent's state.\n * @param text - the effective text of that content.\n * @param started - clock reading at hook entry, for local latency.\n * @returns the decision the Host commits.\n */\n async #pruneResult(\n exec: ToolExecution,\n downstream: PostToolDecision,\n effective: readonly ContentBlock[] | undefined,\n state: AgentState,\n text: string,\n started: number\n ): Promise<PostToolDecision> {\n const capability = this.modeOf('prune');\n if (capability === 'off') return downstream;\n if (downstream.kind === 'block') return downstream;\n // The payload identity is taken once, before any branch can refuse it: every\n // skip below names the payload it was about, so the log answers \"which result\n // was not pruned\" as well as \"why\".\n const payloadDetail = prunePayloadDetail(text);\n if ('value' in downstream && downstream.value !== undefined) {\n // A value-shaped accept replaced the payload wholesale; nothing here knows\n // what its text is, so nothing here may touch it.\n this.#skip('value-shaped-accept', { capability: 'prune', state, agent: exec.agent });\n return downstream;\n }\n if (!hasTextBlock(effective)) {\n // Nothing to replace, and nothing that could be reported as replaced. Asked\n // before the size checks: an image-only payload is not \"small\", it is out of\n // scope, and the skip reason should say so.\n this.#skip('no-text-block', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });\n return downstream;\n }\n if (text.length < this.#pruneThreshold) {\n this.#skip('below-threshold', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });\n return downstream;\n }\n if ((text.match(/\\n/g)?.length ?? 0) < PRUNE_MIN_LINES) {\n // Not line-oriented output: the judge is asked to extract diagnostics, and a\n // payload with no lines does not have any to extract. Rewriting it would\n // destroy semantic data rather than compress a trace.\n this.#skip('unsupported-payload', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });\n return downstream;\n }\n if (text.length > MAX_RETAINED_CHARS) {\n // Retention is a precondition of replacing anything, so an oversized payload\n // is refused *before* it is judged or reported as a saving.\n this.#skip('retention-too-large', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });\n return downstream;\n }\n const retain = this.#retain;\n if (!retain) {\n // Without a retention sink nothing may be replaced: the module will not\n // destroy the only copy of a result it cannot give back.\n this.#skip('retention-unavailable', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });\n return downstream;\n }\n if (!this.#actionWithinBudget(state)) {\n // A reduction is an intervention like a refusal or a correction, so it draws\n // on the same per-turn allowance — and it is asked here, before a judgment is\n // bought, so a full turn costs nothing to refuse. Both modes are checked:\n // observe has to plan no more actions than active could take, including the\n // ones the memo would have answered for free.\n this.#skip('intervention-cap', { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });\n return downstream;\n }\n // Whether *this* agent can retain is the sink's answer, not this module's\n // guess: the production sink refuses a session-less agent by returning nothing,\n // which lands on the same fail-open path below.\n const session = sessionOf(exec.agent);\n\n const digest = digestOf(text);\n // The locator is derived from the payload, and the production sink names the\n // retained copy the same way — which is what makes the plan's size the size of\n // the form active will install, in both modes.\n const locator = pruneLocator(digest);\n const memo = this.#memoGet(state, digest);\n // A memo hit answers the question the judgment already answered; only a mode\n // that needs the reduction's *text* has to ask for it again.\n const needsCandidate = capability === 'active' && (memo?.text === undefined);\n if (!memo || needsCandidate) {\n const skip = this.#spendJudgment(state);\n if (skip) {\n this.#skip(skip, { capability: 'prune', state, agent: exec.agent, detail: payloadDetail });\n return downstream;\n }\n }\n\n const response: PruneResponse =\n memo && !needsCandidate\n ? {\n processedOutput: memo.text ?? text,\n originalChars: memo.originalChars,\n prunedChars: memo.prunedChars,\n estimatedTokensSaved: memo.tokensSaved,\n reductionPercentage: reductionPercentage(memo.originalChars, memo.prunedChars),\n shadow: memo.text === undefined,\n latencyMs: 0,\n ...(memo.diagnostics ?? {})\n }\n // Both modes take the *real* candidate, and both ask for it measure-only.\n // `shadow` only decides whether the backend hands its text back, while\n // `prunedChars` is that candidate's size either way; the text is what the floor\n // composes from, so a withheld measurement would not be the same input at all.\n // Whether the payload is installed is decided here, by the floor, *after* the\n // service has written its ledger entry — so this path never lets the service\n // declare a saving: it measures (`tokensSaved` 0, the candidate's size in\n // `details.potentialTokensSaved`) and the intervention record carries what was\n // really installed. The explicit `reflex_prune` tool, which does hand the\n // reduced text back to its caller, keeps booking the reduction it returns.\n : await this.#prune.prune(text, {\n intent: this.config.intent,\n measureOnly: true,\n // Per-segment System One judging starts at this size; below it the\n // backend's deterministic candidates run and no judgment is spent.\n pruneJudgeMinChars: this.config.pruneJudgeMinChars\n });\n\n const originalTokens = estimateTokens(text);\n // One composition, both modes: the floored text the plan describes is the text\n // active installs, byte for byte. Line alignment and duplicate removal move its\n // real size away from the modelled one, so the number both modes account for is\n // the length of the composed text — never a prediction about it.\n const composed = applyPruneFloor(text, response.processedOutput, {\n floorRatio: this.config.pruneFloorRatio,\n headChars: this.config.pruneHeadChars,\n tailChars: this.config.pruneTailChars,\n locator\n });\n const candidateTokens = Math.ceil(composed.text.length / 4);\n // What the judgment reported about its own path, plus the sizes both the plan\n // and a skip record quote. Recorded even when the candidate is not smaller,\n // because that is exactly the branch a real run cannot explain from its log.\n const diagnostics = pruneDiagnosticsOf(response);\n // A memo hit hands back a form that was composed for this payload already. It is\n // its own fixed point — it carries the share, so the plan of the same lengths\n // stays \"not floored\" and gives that text straight back — but its provenance is\n // not readable from those lengths any more. The memo, which was written by the\n // composition, answers for it: without this the audit would report a floored\n // install as an unfloored one and flip the wording of the feedback with it.\n const reusedFromMemo = !needsCandidate && memo?.text !== undefined ? memo : undefined;\n const floorApplied = reusedFromMemo ? reusedFromMemo.floored : composed.floored;\n const floorMissed = reusedFromMemo ? reusedFromMemo.floorMissed === true : composed.floorMissed;\n const markerOmitted = reusedFromMemo ? reusedFromMemo.markerOmitted === true : composed.markerOmitted;\n const measured: InterventionSkipDetail = {\n ...payloadDetail,\n ...diagnostics,\n originalTokens,\n candidateTokens,\n floored: floorApplied,\n floorMissed,\n markerOmitted,\n candidateChars: composed.text.length\n };\n const judged = !memo || needsCandidate;\n const judgment: JudgmentCharge = {\n judgments: judged ? 1 : 0,\n memoHits: judged ? 0 : 1,\n localLatencyMs: Math.max(0, this.#now() - started - (judged ? response.latencyMs : 0)),\n remoteLatencyMs: judged ? response.latencyMs : 0,\n // The pre-prune payload is what the pruner reasoned about; a backend call is\n // a judgment even when it returns locally in under a millisecond.\n judgeTokens: judged ? originalTokens : 0\n };\n if (candidateTokens >= originalTokens) {\n this.#charge('prune', { ...judgment, originalTokens });\n // The branch a real \"prune: active but nothing happened\" run lands in: the\n // judgment ran, and the candidate it produced was not smaller. The record\n // says so with the path that produced it and the sizes both sides had.\n this.#skip('no-reduction', {\n capability: 'prune',\n state,\n agent: exec.agent,\n detail: measured,\n judgment\n });\n return downstream;\n }\n\n const plan: InterventionPlan = {\n capability: 'prune',\n action: 'prune-result',\n reason: `${exec.name} returned ${originalTokens} tokens; the judged reduction carries ${candidateTokens}`,\n feedback: this.#pruneFeedback(exec.name, originalTokens, candidateTokens, {\n floored: floorApplied,\n floorMissed,\n markerOmitted,\n locator,\n keptSegments: diagnostics.keptSegments,\n judgedSegments: diagnostics.judgedSegments\n }),\n detail: {\n digest,\n floorApplied,\n floorMissed,\n markerOmitted,\n confidence: response.reductionPercentage,\n turn: state.turn,\n step: state.step,\n ...diagnostics,\n originalChars: text.length,\n candidateChars: composed.text.length\n }\n };\n const planCosts = { originalTokens, candidateTokens, potentialSavedTokens: originalTokens - candidateTokens };\n\n if (capability !== 'active') {\n // Observe: the plan is real and charged, the surface is untouched, and the\n // memo keeps the composed form — the same form active would install, from the\n // same candidate — so a later hit reports the reduction this mode really saw.\n // A plan this mode records is the action active would have taken, so it books\n // the slot active would have booked.\n this.#bookAction(state);\n this.#conclude(plan, false, exec.agent, planCosts, judgment);\n if (!memo) {\n this.#memoSet(state, digest, {\n text: composed.text,\n originalChars: text.length,\n prunedChars: composed.text.length,\n tokensSaved: originalTokens - candidateTokens,\n floored: floorApplied,\n floorMissed,\n markerOmitted,\n diagnostics\n });\n }\n return downstream;\n }\n\n // Active. The original is retained *before* anything is replaced, and only a\n // verified retention makes the replacement installable at all. A payload whose\n // copy is already retained keeps that copy instead of writing a second one.\n const alreadyRetained = memo?.locator;\n const retention = alreadyRetained\n ? { locator: alreadyRetained }\n : retain(session, {\n digest,\n callId: exec.callId,\n tool: exec.name,\n turn: state.turn,\n step: state.step,\n text\n });\n if (!retention || typeof retention.locator !== 'string' || retention.locator.length === 0) {\n // No controlled copy, no reduction. The result stays exactly as the rest of\n // the waterfall produced it, and no saving is recorded — but the judgment\n // that got this far was really made, so it is charged rather than hidden.\n this.#charge('prune', judgment);\n this.#skip('retention-failed', {\n capability: 'prune',\n state,\n agent: exec.agent,\n detail: measured,\n judgment\n });\n return downstream;\n }\n\n // The form both modes accounted for is the form that gets installed: the locator\n // is derived from the payload and the sink names its copy the same way, so the\n // composition already published is reused byte for byte — with the provenance the\n // plan gave it, rather than with what re-reading its own lengths would say. Only a\n // sink that named the copy differently forces a rebuild, and then the real length\n // and provenance of that rebuild are what gets accounted for.\n const installed =\n retention.locator === locator\n ? { ...composed, floored: floorApplied, floorMissed, markerOmitted }\n : applyPruneFloor(text, response.processedOutput, {\n floorRatio: this.config.pruneFloorRatio,\n headChars: this.config.pruneHeadChars,\n tailChars: this.config.pruneTailChars,\n locator: retention.locator\n });\n if (installed.text.length === 0 || installed.text.length >= text.length) {\n // The plan said the form is smaller; the form that was really built must be\n // too, or nothing is installed and nothing is saved.\n this.#skip('no-reduction', {\n capability: 'prune',\n state,\n agent: exec.agent,\n detail: {\n ...measured,\n floored: installed.floored,\n floorMissed: installed.floorMissed,\n markerOmitted: installed.markerOmitted,\n candidateChars: installed.text.length,\n candidateTokens: Math.max(0, Math.ceil(installed.text.length / 4))\n },\n judgment\n });\n return downstream;\n }\n const replacement = this.#replaceText(effective, installed.text);\n if (!replacement) {\n this.#skip('no-text-block', {\n capability: 'prune',\n state,\n agent: exec.agent,\n detail: {\n ...measured,\n floored: installed.floored,\n floorMissed: installed.floorMissed,\n markerOmitted: installed.markerOmitted,\n candidateChars: installed.text.length,\n candidateTokens: Math.max(0, Math.ceil(installed.text.length / 4))\n },\n judgment\n });\n return downstream;\n }\n\n // Only now is there a decision that really took effect, so only now is the\n // saving recorded — against the text that is really about to enter the context.\n const installedTokens = Math.max(0, Math.ceil(installed.text.length / 4));\n plan.detail.floorApplied = installed.floored;\n plan.detail.floorMissed = installed.floorMissed;\n plan.detail.markerOmitted = installed.markerOmitted;\n plan.detail.candidateChars = installed.text.length;\n plan.feedback = this.#pruneFeedback(exec.name, originalTokens, installedTokens, {\n floored: installed.floored,\n floorMissed: installed.floorMissed,\n markerOmitted: installed.markerOmitted,\n locator: retention.locator,\n keptSegments: diagnostics.keptSegments,\n judgedSegments: diagnostics.judgedSegments\n });\n // Booked only here: a candidate that was not smaller, a replacement that could\n // not be composed, and a retention that failed all returned above, so none of\n // them consumed the turn's allowance for an action that never happened.\n this.#bookAction(state);\n this.#conclude(\n plan,\n true,\n exec.agent,\n {\n originalTokens,\n candidateTokens: installedTokens,\n potentialSavedTokens: originalTokens - installedTokens,\n actualSavedTokens: originalTokens - installedTokens\n },\n judgment,\n retention.locator\n );\n // Retention is counted once per payload: a duplicate install reuses the copy\n // that is already in the log, and the locator naming it never changes.\n if (!this.#retained.includes(retention.locator)) {\n this.#retained.push(retention.locator);\n if (this.#retained.length > MAX_RECENT) this.#retained.shift();\n }\n this.#retainedCopies += 1;\n this.#memoSet(state, digest, {\n text: installed.text,\n originalChars: text.length,\n prunedChars: installed.text.length,\n tokensSaved: originalTokens - installedTokens,\n floored: installed.floored,\n floorMissed: installed.floorMissed,\n markerOmitted: installed.markerOmitted,\n locator: retention.locator,\n diagnostics\n });\n return {\n kind: 'accept',\n content: replacement,\n ...(downstream.additionalContexts && downstream.additionalContexts.length > 0\n ? { additionalContexts: [...downstream.additionalContexts] }\n : {})\n };\n }\n\n /** Plan, and in active mode apply, the correction of one repeated failure. */\n async #correctFailure(\n exec: ToolExecution,\n result: Readonly<ToolExecutionResult>,\n downstream: PostToolDecision,\n state: AgentState,\n signature: string,\n started: number\n ): Promise<PostToolDecision> {\n const capability = this.modeOf('gate');\n if (capability === 'off') return downstream;\n if (downstream.kind === 'block') return downstream;\n const suspicion = suspicionOf(state.steps, {\n repeatThreshold: this.config.repeatThreshold,\n failureThreshold: this.config.failureThreshold,\n window: this.config.windowSize,\n signature\n });\n if (!suspicion.suspicious || state.applied.has(`gate:${signature}`)) {\n if (suspicion.suspicious) {\n this.#skip('duplicate-intervention', { capability: 'gate', state, agent: exec.agent });\n }\n return downstream;\n }\n if (!this.#actionWithinBudget(state)) {\n this.#skip('intervention-cap', { capability: 'gate', state, agent: exec.agent });\n return downstream;\n }\n const agentId = agentKeyOf(exec.agent);\n const verdict = await this.#judge(state, exec.signal);\n const judgment = this.#judgmentCharge(verdict, started, this.#now());\n if (!verdict.useful) {\n this.#charge('gate', judgment);\n this.#skip(verdict.skip ?? 'unconfirmed', {\n capability: 'gate',\n state,\n agent: exec.agent,\n judgment\n });\n return downstream;\n }\n\n const plan: InterventionPlan = {\n capability: 'gate',\n action: 'corrective-feedback',\n reason: `${exec.name} failed ${suspicion.repeats} times; System 1 confirmed ${verdict.response.patternType ?? suspicion.pattern}`,\n feedback: this.#failureFeedback(exec.name, this.#errorOf(result), suspicion, verdict.response),\n detail: {\n pattern: String(verdict.response.patternType ?? suspicion.pattern ?? 'unknown'),\n confidence: verdict.response.confidence,\n repeats: suspicion.repeats,\n turn: state.turn,\n step: state.step\n }\n };\n const applied = capability === 'active';\n state.applied.add(`gate:${signature}`);\n this.#bookAction(state);\n this.#conclude(plan, applied, exec.agent, { potentialSavedTokens: 0 }, judgment);\n if (!applied) return downstream;\n return {\n kind: 'block',\n feedback: [{ type: 'text', text: plan.feedback }],\n ...(downstream.additionalContexts && downstream.additionalContexts.length > 0\n ? { additionalContexts: [...downstream.additionalContexts] }\n : {})\n };\n }\n\n // ── judgment, budgets, and memo ─────────────────────────────────────────────\n\n /**\n * Whether this turn still has room for one more planned action.\n *\n * This is the *action* ceiling, and it is deliberately not the judgment budget:\n * a judgment is the question System 1 was asked, this is the number of things\n * the run is allowed to do about the answer. Every capability draws on the same\n * allowance, and both modes draw on it the same way — the plan observe measures\n * is the action active would install, so an observe run that planned more than\n * the ceiling would be measuring a turn that cannot exist.\n *\n * Asked before a judgment is bought, so a turn that is already full is refused\n * for free.\n * @param state - the deciding agent's state.\n * @returns whether one more planned action fits this turn.\n */\n #actionWithinBudget(state: AgentState): boolean {\n return state.interventions < this.config.maxInterventionsPerTurn;\n }\n\n /**\n * Book one planned action against the turn's shared allowance.\n *\n * Called at the one point where a plan becomes real: observe books the plan it\n * records, active books the replacement its retention made installable. Never\n * called earlier — a plan abandoned by a failed judgment, a failed retention, or\n * a candidate that turned out not to be smaller must not consume the turn's\n * allowance, or a turn would be spent on actions that never happened.\n * @param state - the deciding agent's state.\n */\n #bookAction(state: AgentState): void {\n state.interventions += 1;\n }\n\n /**\n * Spend at most one System 1 stagnation judgment per agent and turn.\n *\n * Every hook of one turn shares the verdict — the pre-execute refusal, the\n * pre-step correction, and the failure correction all ask the same question\n * about the same window, so asking it three times would be three times the cost\n * for one answer.\n */\n async #judge(\n state: AgentState,\n signal?: AbortSignal,\n steps: readonly ObservedStep[] = state.steps,\n goal?: string\n ): Promise<{\n useful: boolean;\n paid: boolean;\n reused: boolean;\n judgeTokens: number;\n localLatencyMs: number;\n remoteLatencyMs: number;\n skip?: string;\n response: StagnationCheckResponse;\n }> {\n // The question is the trailing window plus the context it is asked in, so\n // the answer is cached against both: the same episode is never judged twice,\n // while a *different* episode or a different wait context in the same turn is\n // a new question — and therefore subject to the turn's budget.\n const key = `${goal ?? ''}\\u0000${steps\n .slice(-Math.max(1, this.config.repeatThreshold))\n .map((step) => step.signature)\n .join('|')}`;\n const cached = state.verdictTurn === state.turn && state.verdictKey === key ? state.verdict : undefined;\n if (cached) {\n return {\n useful: this.#useful(cached),\n paid: false,\n reused: true,\n judgeTokens: 0,\n localLatencyMs: 0,\n remoteLatencyMs: 0,\n response: cached\n };\n }\n if (state.judgmentsCount >= this.config.maxJudgmentsPerTurn) {\n return this.#noJudgment('judgment-turn-cap');\n }\n if (state.judgmentsSession >= this.config.maxJudgmentsPerSession) {\n return this.#noJudgment('judgment-session-cap');\n }\n if (signal?.aborted) return this.#noJudgment('aborted');\n this.#spendJudgment(state);\n\n const history: ActionStep[] = steps.map((step) => ({\n tool: step.tool,\n input: step.input,\n ...(step.output ? { output: step.output } : {}),\n ...(step.error ? { error: step.error } : {}),\n timestamp: step.at\n }));\n const judgeTokens = history.reduce(\n (sum, step) => sum + estimateTokens(`${step.tool}${step.input}${step.output ?? ''}${step.error ?? ''}`),\n 0\n );\n const started = this.#now();\n const response = await this.#stagnation.check(goal, history);\n const remoteLatencyMs = Number.isFinite(response.latencyMs) ? response.latencyMs : 0;\n state.verdict = response;\n state.verdictTurn = state.turn;\n state.verdictKey = key;\n return {\n useful: this.#useful(response),\n paid: true,\n reused: false,\n judgeTokens,\n localLatencyMs: Math.max(0, this.#now() - started - remoteLatencyMs),\n remoteLatencyMs,\n response\n };\n }\n\n /**\n * Charge one judgment against the turn's and the session's budget.\n *\n * Both budgets are spent at the one place a judgment is actually made, so a\n * capability cannot buy its way around them by calling a service directly. The\n * caller decides whether a refusal means \"plan nothing\" or \"do not act\"; what\n * matters here is that the count is never overrun and that a shadowed\n * application is charged like a real one — an observe run has to cost what the\n * active run would cost, or its column would flatter it.\n * @param state - the deciding agent's state.\n * @returns `undefined` when the judgment was spent, else the skip reason.\n */\n #spendJudgment(state: AgentState): string | undefined {\n if (state.judgmentsCount >= this.config.maxJudgmentsPerTurn) return 'judgment-turn-cap';\n if (state.judgmentsSession >= this.config.maxJudgmentsPerSession) return 'judgment-session-cap';\n state.judgmentsCount += 1;\n state.judgmentsSession += 1;\n return undefined;\n }\n\n /** The zero-cost verdict of a judgment that could not be spent. */\n #noJudgment(skip: string): { useful: boolean;\n paid: boolean;\n reused: boolean;\n judgeTokens: number;\n localLatencyMs: number;\n remoteLatencyMs: number;\n skip?: string;\n response: StagnationCheckResponse;\n } {\n // Not a memo hit: nothing was reused, the budget simply refused to spend.\n return {\n useful: false,\n paid: false,\n reused: false,\n judgeTokens: 0,\n localLatencyMs: 0,\n remoteLatencyMs: 0,\n skip,\n response: EMPTY_VERDICT\n };\n }\n\n /** The charge of one judgment, so every judgment is billed exactly once. */\n #judgmentCharge(\n verdict: { paid: boolean; reused: boolean; judgeTokens: number; localLatencyMs: number; remoteLatencyMs: number },\n started: number,\n finished: number\n ): JudgmentCharge {\n if (!verdict.paid) {\n return { judgments: 0, memoHits: verdict.reused ? 1 : 0, localLatencyMs: 0, remoteLatencyMs: 0, judgeTokens: 0 };\n }\n return {\n judgments: 1,\n memoHits: 0,\n localLatencyMs: Math.max(verdict.localLatencyMs, Math.max(0, finished - started - verdict.remoteLatencyMs)),\n remoteLatencyMs: verdict.remoteLatencyMs,\n judgeTokens: verdict.judgeTokens\n };\n }\n\n /** Whether a verdict justifies acting: stuck, confident, and about a pattern. */\n #useful(response: StagnationCheckResponse): boolean {\n return (\n response.isStuck === true &&\n response.confidence >= this.config.minConfidence &&\n (response.patternType ?? 'none') !== 'none'\n );\n }\n\n // ── accounting and audit ───────────────────────────────────────────────────\n\n /**\n * Record one planned decision and bill its plan side.\n *\n * The judgment is passed in rather than recomputed: it was already charged\n * (or is charged here for the first time) exactly once, and it appears in the\n * audit record so one decision's full cost is readable in one place.\n *\n * Two rules keep the record honest. `injectedTokens` counts only text that was\n * *really* injected — a reduction's explanatory note is never sent to the model,\n * so reducing costs no context. And `actualSavedTokens` is the caller's\n * measurement of the payload that really left the surface, not the plan's\n * intention; `#pruneResult` passes the size of the text it actually installed.\n *\n * @param plan - what was planned.\n * @param applied - whether active mode executed it.\n * @param agent - the agent it concerns, for isolation and the audit trail.\n * @param planCosts - the payload sizes of this decision.\n * @param judgment - the judgment this decision rode on.\n * @param originalLocator - locator of the retained original, when one exists.\n */\n #conclude(\n plan: InterventionPlan,\n applied: boolean,\n agent: unknown,\n planCosts: {\n originalTokens?: number;\n candidateTokens?: number;\n potentialSavedTokens: number;\n /** Tokens really removed; defaults to the plan's own estimate. */\n actualSavedTokens?: number;\n },\n judgment?: JudgmentCharge,\n originalLocator?: string\n ): void {\n const originalTokens = planCosts.originalTokens ?? 0;\n const candidateTokens = planCosts.candidateTokens ?? 0;\n const potentialSavedTokens = planCosts.potentialSavedTokens;\n // The injection column counts text handed to the model. A deny's reason and a\n // correction's feedback are injected; a prune's note travels in the audit\n // record only, so its plan never inflates the cost of the saving it made.\n const injects = applied && plan.action !== 'prune-result';\n const injectedTokens = injects ? estimateTokens(plan.feedback) : 0;\n const actualSavedTokens =\n applied && plan.action === 'prune-result'\n ? planCosts.actualSavedTokens ?? potentialSavedTokens\n : 0;\n const charge: Charge = {\n ...(judgment ?? { judgments: 0, memoHits: 0, localLatencyMs: 0, remoteLatencyMs: 0, judgeTokens: 0 }),\n originalTokens,\n candidateTokens,\n potentialSavedTokens,\n actualSavedTokens,\n injectedTokens\n };\n this.#charge(plan.capability, charge, 1, applied ? 1 : 0);\n\n const record: InterventionAuditRecord = {\n capability: plan.capability,\n action: plan.action,\n mode: this.modeOf(plan.capability),\n applied,\n reason: plan.reason,\n feedback: applied ? plan.feedback : '',\n localLatencyMs: judgment?.localLatencyMs ?? 0,\n remoteLatencyMs: judgment?.remoteLatencyMs ?? 0,\n judgeTokens: judgment?.judgeTokens ?? 0,\n originalTokens,\n candidateTokens,\n potentialSavedTokens,\n actualSavedTokens,\n injectedTokens,\n at: this.#now(),\n agentId: agentKeyOf(agent),\n ...(plan.detail.pattern === undefined ? {} : { pattern: plan.detail.pattern }),\n ...(plan.detail.confidence === undefined ? {} : { confidence: plan.detail.confidence }),\n ...(plan.detail.repeats === undefined ? {} : { repeats: plan.detail.repeats }),\n ...(plan.detail.digest === undefined ? {} : { digest: plan.detail.digest }),\n ...(plan.detail.floorApplied === undefined ? {} : { floorApplied: plan.detail.floorApplied, floored: plan.detail.floorApplied }),\n ...(plan.detail.floorMissed === undefined ? {} : { floorMissed: plan.detail.floorMissed }),\n ...(plan.detail.markerOmitted ? { markerOmitted: true } : {}),\n ...(judgment?.memoHits ? { memoHit: true } : {}),\n ...(originalLocator === undefined ? {} : { originalLocator }),\n ...(plan.detail.turn === undefined ? {} : { turn: plan.detail.turn }),\n ...(plan.detail.step === undefined ? {} : { step: plan.detail.step }),\n ...(plan.detail.judgePath === undefined ? {} : { judgePath: plan.detail.judgePath }),\n ...(plan.detail.judgedSegments === undefined ? {} : { judgedSegments: plan.detail.judgedSegments }),\n ...(plan.detail.unjudgedSegments === undefined ? {} : { unjudgedSegments: plan.detail.unjudgedSegments }),\n ...(plan.detail.keptSegments === undefined ? {} : { keptSegments: plan.detail.keptSegments }),\n ...(plan.detail.aggressiveChars === undefined ? {} : { aggressiveChars: plan.detail.aggressiveChars }),\n ...(plan.detail.balancedChars === undefined ? {} : { balancedChars: plan.detail.balancedChars }),\n ...(plan.detail.conservativeChars === undefined ? {} : { conservativeChars: plan.detail.conservativeChars }),\n ...(plan.detail.scoredSegments === undefined ? {} : { scoredSegments: plan.detail.scoredSegments }),\n ...(plan.detail.autoKeptSegments === undefined ? {} : { autoKeptSegments: plan.detail.autoKeptSegments }),\n ...(plan.detail.unparsedScoreAnswers === undefined ? {} : { unparsedScoreAnswers: plan.detail.unparsedScoreAnswers }),\n ...(plan.detail.originalChars === undefined ? {} : { originalChars: plan.detail.originalChars }),\n ...(plan.detail.candidateChars === undefined ? {} : { candidateChars: plan.detail.candidateChars }),\n ...(plan.detail.fallbackReason === undefined ? {} : { fallbackReason: plan.detail.fallbackReason })\n };\n this.#recent.push(record);\n if (this.#recent.length > MAX_RECENT) this.#recent.shift();\n try {\n this.#audit?.(record, (agent as { session?: unknown } | undefined)?.session);\n } catch {\n // An audit sink is never allowed to fail a turn.\n }\n }\n\n /**\n * Bill one decision against its mode's and its capability's account.\n *\n * Every counter has exactly one writer, so a reader can add the parts up\n * without meeting a number twice.\n */\n #charge(capability: InterventionCapability, charge: Charge, plans = 0, applied = 0): void {\n const mode = this.modeOf(capability) === 'active' ? 'active' : 'observe';\n for (const bucket of [this.#costs[mode], this.#byCapability[capability]]) {\n bucket.plans += plans;\n bucket.applied += applied;\n bucket.judgments += charge.judgments ?? 0;\n bucket.memoHits += charge.memoHits ?? 0;\n bucket.localLatencyMs += charge.localLatencyMs ?? 0;\n bucket.remoteLatencyMs += charge.remoteLatencyMs ?? 0;\n bucket.judgeTokens += charge.judgeTokens ?? 0;\n bucket.originalTokens += charge.originalTokens ?? 0;\n bucket.candidateTokens += charge.candidateTokens ?? 0;\n bucket.potentialSavedTokens += charge.potentialSavedTokens ?? 0;\n bucket.actualSavedTokens += charge.actualSavedTokens ?? 0;\n bucket.injectedTokens += charge.injectedTokens ?? 0;\n }\n }\n\n /**\n * Count one hook-level refusal by reason, and leave it in the session log.\n *\n * The counter is process-local and only answers \"what did this activation\n * skip\"; the record is the durable half, because the question a real run\n * raises is *why was nothing pruned* — and a branch that never planned\n * anything otherwise leaves no trace at all. The write is best-effort by\n * construction: no budget is charged, nothing is projected into the model's\n * context, and a sink that throws or a session that is missing leaves the\n * hook's own decision untouched.\n *\n * @param reason - the machine reason of the branch that abandoned the plan.\n * @param context - capability, deciding state, agent, and prune diagnostics.\n */\n #skip(reason: string, context: SkipContext): void {\n this.#skips.set(reason, (this.#skips.get(reason) ?? 0) + 1);\n this.#auditSkip(reason, context);\n }\n\n /** Write one abandoned plan to the audit channel, fail-open. */\n #auditSkip(reason: string, context: SkipContext): void {\n const audit = this.#audit;\n if (!audit) return;\n try {\n const detail = context.detail;\n const record: InterventionAuditRecord = {\n capability: context.capability,\n action: 'skip',\n mode: this.modeOf(context.capability),\n applied: false,\n reason,\n feedback: '',\n localLatencyMs: context.judgment?.localLatencyMs ?? 0,\n remoteLatencyMs: context.judgment?.remoteLatencyMs ?? 0,\n judgeTokens: context.judgment?.judgeTokens ?? 0,\n originalTokens: detail?.originalTokens ?? 0,\n candidateTokens: detail?.candidateTokens ?? 0,\n potentialSavedTokens: 0,\n actualSavedTokens: 0,\n injectedTokens: 0,\n at: this.#now(),\n skip: reason,\n ...(context.state === undefined ? {} : { turn: context.state.turn, step: context.state.step }),\n ...(detail?.digest === undefined ? {} : { digest: detail.digest }),\n ...(detail?.floored === undefined ? {} : { floored: detail.floored }),\n ...(detail?.floorMissed === undefined ? {} : { floorMissed: detail.floorMissed }),\n ...(detail?.markerOmitted ? { markerOmitted: true } : {}),\n ...(detail?.judgePath === undefined ? {} : { judgePath: detail.judgePath }),\n ...(detail?.judgedSegments === undefined ? {} : { judgedSegments: detail.judgedSegments }),\n ...(detail?.unjudgedSegments === undefined ? {} : { unjudgedSegments: detail.unjudgedSegments }),\n ...(detail?.keptSegments === undefined ? {} : { keptSegments: detail.keptSegments }),\n ...(detail?.aggressiveChars === undefined ? {} : { aggressiveChars: detail.aggressiveChars }),\n ...(detail?.balancedChars === undefined ? {} : { balancedChars: detail.balancedChars }),\n ...(detail?.conservativeChars === undefined ? {} : { conservativeChars: detail.conservativeChars }),\n ...(detail?.scoredSegments === undefined ? {} : { scoredSegments: detail.scoredSegments }),\n ...(detail?.autoKeptSegments === undefined ? {} : { autoKeptSegments: detail.autoKeptSegments }),\n ...(detail?.unparsedScoreAnswers === undefined ? {} : { unparsedScoreAnswers: detail.unparsedScoreAnswers }),\n ...(detail?.originalChars === undefined ? {} : { originalChars: detail.originalChars }),\n ...(detail?.candidateChars === undefined ? {} : { candidateChars: detail.candidateChars }),\n ...(detail?.fallbackReason === undefined ? {} : { fallbackReason: detail.fallbackReason })\n };\n audit(record, sessionOf(context.agent));\n } catch {\n // An audit sink is never allowed to fail a turn, and a skip is reported\n // even when the log refused it: the counter above is already committed.\n }\n }\n\n // ── state ─────────────────────────────────────────────────────────────────\n\n /** One agent's state, created on first sight and bounded overall. */\n #state(agentId: string, agent?: unknown): AgentState {\n const sessionKey = sessionKeyOf(agent);\n const existing = this.#states.get(agentId);\n if (existing && existing.sessionKey === sessionKey) {\n this.#states.delete(agentId);\n this.#states.set(agentId, existing);\n return existing;\n }\n // A new session for the same agent id is a new run: no window, verdict,\n // budget, or memoized reduction of the old one may leak into it.\n if (existing) this.#memoForget(existing.sessionKey);\n const state: AgentState = {\n sessionKey,\n turn: 0,\n step: 0,\n steps: [],\n claims: '',\n evidence: [],\n evidenceSuspect: false,\n interventions: 0,\n judgmentsTurn: 0,\n judgmentsCount: 0,\n judgmentsSession: 0,\n verdictTurn: 0,\n verdictKey: '',\n waited: new Set<string>(),\n applied: new Set<string>(),\n denied: new Set<string>(),\n refused: new Set<string>()\n };\n this.#states.set(agentId, state);\n if (this.#states.size > MAX_AGENTS) {\n const oldest = this.#states.keys().next().value;\n if (typeof oldest === 'string' && oldest !== agentId) this.#states.delete(oldest);\n }\n return state;\n }\n\n /**\n * The step a call about to run would add, without committing it.\n * @param state - the agent's bookkeeping.\n * @param exec - the proposed call.\n * @param signature - its identity.\n * @returns the step the result path will record once the call completes.\n */\n #observed(state: AgentState, exec: ToolExecution, signature: string): ObservedStep {\n return {\n signature,\n tool: exec.name,\n input: clip(this.#argumentsOf(exec), STEP_CHARS),\n output: '',\n error: '',\n // The call about to run is a retry exactly when this identity failed before.\n failed: state.steps.some((step) => step.signature === signature && step.failed),\n turn: state.turn,\n at: this.#now()\n };\n }\n\n /** Append one observed step, bounded. */\n #observe(state: AgentState, step: ObservedStep): void {\n state.steps.push(step);\n if (state.steps.length > MAX_STEPS) state.steps.shift();\n }\n\n /**\n * Retain one result's evidence candidates for the closing check.\n *\n * Called for every observed result, not only structurally failing ones: a\n * `{ok:false}`, a timeout, or a Chinese error has no exit code to prove it,\n * and the closing judgment must be able to see it. The regex only guarantees\n * that its own hits survive; it never decides that the rest is benign.\n * @param state - the agent's bookkeeping.\n * @param tool - tool name that produced the result.\n * @param result - the execution-local result.\n * @param text - the effective model-facing text.\n * @param error - the result's error message, when it has a distinct one.\n */\n #rememberEvidence(\n state: AgentState,\n tool: string,\n result: Readonly<ToolExecutionResult>,\n text: string,\n error: string\n ): void {\n const haystack = error.length > 0 && !text.includes(error) ? `${text}\\n${error}` : text;\n const entries = evidenceOf(tool, result, haystack);\n if (entries.length === 0) return;\n state.evidence.push(...entries);\n if (state.evidence.length > MAX_EVIDENCE) {\n state.evidence.splice(0, state.evidence.length - MAX_EVIDENCE);\n }\n if (entries.some((entry) => entry.suspect)) state.evidenceSuspect = true;\n }\n\n /** The arguments of one call, as the text a judgment and a digest see. */\n #argumentsOf(exec: ToolExecution): string {\n const args: unknown = exec.arguments;\n if (typeof args === 'string') return args;\n try {\n return JSON.stringify(args ?? {}) ?? '';\n } catch {\n return '';\n }\n }\n\n /** The failure text of one result. */\n #errorOf(result: Readonly<ToolExecutionResult>): string {\n const failure = (result as { error?: { message?: string } }).error;\n if (failure && typeof failure.message === 'string' && failure.message.length > 0) return failure.message;\n return textOfContent(result.content);\n }\n\n /** Replace the text blocks of one content list, preserving every other block. */\n #replaceText(content: readonly ContentBlock[] | undefined, text: string): ContentBlock[] | undefined {\n if (!content) return undefined;\n const out: ContentBlock[] = [];\n let placed = false;\n for (const block of content) {\n if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') {\n if (!placed) {\n out.push({ type: 'text', text } as ContentBlock);\n placed = true;\n }\n continue;\n }\n out.push(block);\n }\n return placed ? out : undefined;\n }\n\n /**\n * The explanatory note of one reduction.\n *\n * It travels in the audit record, never in the model's context: a prune is\n * supposed to *remove* context, so sending an explanation of the removal would\n * work against the thing it is accounting for.\n *\n * The wording follows the data: \"kept whole\" is only said when the judgment\n * really kept every segment it judged. A candidate that was floored says the\n * head/extract/tail form it carries, and a floor miss says how many segments\n * survived, how many were omitted, and that the promised share was not reached\n * — plus where the full payload can be read back, marker or no marker.\n *\n * @param tool - name of the reduced call.\n * @param originalTokens - tokens of the raw payload.\n * @param candidateTokens - tokens of the text really installed.\n * @param outcome - the floor's decision and the judgment's segment counts.\n * @returns the note, clipped to the audit's text budget.\n */\n #pruneFeedback(\n tool: string,\n originalTokens: number,\n candidateTokens: number,\n outcome: {\n floored: boolean;\n floorMissed: boolean;\n markerOmitted: boolean;\n locator: string;\n keptSegments?: number;\n judgedSegments?: number;\n }\n ): string {\n const kept = originalTokens === 0 ? 100 : Math.round((candidateTokens / originalTokens) * 100);\n const head = `Reflex reduced ${tool}: ${originalTokens} → ${candidateTokens} tokens (${kept}% kept). `;\n const keptSegments = outcome.keptSegments;\n const judgedSegments = outcome.judgedSegments;\n const segmentsShort =\n keptSegments !== undefined && judgedSegments !== undefined && keptSegments < judgedSegments;\n const segmentNote = segmentsShort\n ? `Kept ${keptSegments}/${judgedSegments} segments, omitted ${judgedSegments - keptSegments}. `\n : '';\n let body: string;\n if (outcome.floored) {\n body =\n 'The head, the judged extract and the tail were kept; ' +\n `the full output was retained in this session's log and is not in context.`;\n } else if (outcome.floorMissed) {\n const floorPercent = Math.round(this.config.pruneFloorRatio * 100);\n const install =\n outcome.markerOmitted\n ? 'no locator marker was added because it would not have kept the text smaller than the original'\n : 'the judged extract was installed as-is';\n body = `${segmentNote}The candidate fell short of the ${floorPercent}% floor, so ${install}; ` +\n `the full output is retrievable as ${outcome.locator}.`;\n } else if (segmentsShort) {\n body = `${segmentNote}The judged extract was installed as-is; ` +\n `the full output is retrievable as ${outcome.locator}.`;\n } else {\n body =\n 'The judged extract was kept whole; ' +\n `the full output was retained in this session's log and is not in context.`;\n }\n return clip(`${head}${body}`, FEEDBACK_CHARS);\n }\n\n /** The memoized reduction of one payload, when it is still remembered. */\n #memoGet(state: AgentState, digest: string): PruneMemo | undefined {\n const key = `${state.sessionKey}:${digest}`;\n const hit = this.#memo.get(key);\n if (!hit) return undefined;\n this.#memo.delete(key);\n this.#memo.set(key, hit);\n return hit;\n }\n\n /**\n * Remember one payload's reduction, bounded by least recent use.\n *\n * The entry records the *plan* — the sizes both modes report — and, once a mode\n * really computed it, the reduction's text. Observe never has that text (the\n * shadow service withholds it and reports only its size) and never pretends to:\n * a later active decision re-plans that payload for real instead of installing a\n * cached fragment it never saw.\n */\n #memoSet(state: AgentState, digest: string, memo: PruneMemo): void {\n const key = `${state.sessionKey}:${digest}`;\n this.#memo.set(key, memo);\n if (this.#memo.size > MAX_MEMO) {\n const oldest = this.#memo.keys().next().value;\n if (typeof oldest === 'string') this.#memo.delete(oldest);\n }\n }\n\n /** Drop the memo entries of one session, so a replaced run leaves nothing behind. */\n #memoForget(sessionKey: string): void {\n const prefix = `${sessionKey}:`;\n for (const key of [...this.#memo.keys()]) {\n if (key.startsWith(prefix)) this.#memo.delete(key);\n }\n }\n\n /** Build one model-facing message, attributed to this plugin. */\n #message(agentId: string, turn: number, step: number, text: string): UserMessage {\n this.#counter += 1;\n const summary = boundContextSummary(text.replace(/\\s+/g, ' ').trim());\n return {\n id: MessageId(`reflex-intervention-${agentId}-${turn}-${step}-${this.#counter}`),\n role: 'user',\n content: [{ type: 'text', text }],\n source: { kind: INTERVENTION_SOURCE_KIND, form: 'notice', summary }\n };\n }\n\n /** Steer one message into an agent's inbox, when the agent can receive it. */\n #steer(agent: unknown, message: UserMessage): void {\n const steer = (agent as { steer?: (message: UserMessage) => void } | undefined)?.steer;\n if (typeof steer !== 'function') return;\n steer.call(agent, message);\n }\n\n /** The refusal text handed to the model when a repeated call is denied. */\n #denyFeedback(tool: string, suspicion: StagnationSuspicion, verdict: StagnationCheckResponse): string {\n const advice = clip((verdict.recommendedIntervention ?? '').replace(/\\s+/g, ' ').trim(), 240);\n return clip(\n `Reflex intervention: ${tool} was called with identical arguments ${suspicion.repeats} times in this turn and System 1 confirms ` +\n `${verdict.patternType ?? suspicion.pattern} stagnation (confidence ${verdict.confidence.toFixed(2)}). The call was not executed. ` +\n `Change the approach: ${advice || 'use different arguments or a different tool, and inspect the previous result before retrying.'}`,\n FEEDBACK_CHARS\n );\n }\n\n /** The corrective context attached to the step after a repeated loop. */\n #contextFeedback(suspicion: StagnationSuspicion, verdict: StagnationCheckResponse): string {\n const advice = clip((verdict.recommendedIntervention ?? '').replace(/\\s+/g, ' ').trim(), 240);\n return clip(\n `Reflex intervention: the last steps repeated the same call ${suspicion.repeats} times (System 1: ${verdict.patternType ?? suspicion.pattern}, ` +\n `confidence ${verdict.confidence.toFixed(2)}). Stop the loop and change strategy: ` +\n `${advice || 're-read the last failure, then either fix the cause or try a different tool.'}`,\n FEEDBACK_CHARS\n );\n }\n\n /** The corrective feedback carried by a repeated failing result. */\n #failureFeedback(tool: string, error: string, suspicion: StagnationSuspicion, verdict: StagnationCheckResponse): string {\n const advice = clip((verdict.recommendedIntervention ?? '').replace(/\\s+/g, ' ').trim(), 240);\n return clip(\n `Reflex intervention: ${tool} failed ${suspicion.repeats} consecutive times with ${clip(error.replace(/\\s+/g, ' ').trim(), 160)}. ` +\n `System 1 confirms ${verdict.patternType ?? suspicion.pattern} (confidence ${verdict.confidence.toFixed(2)}). ` +\n `This result is treated as a policy failure: change the command or the code before retrying. ${advice}`,\n FEEDBACK_CHARS\n );\n }\n\n /** The objection steered into a turn that is closing on contradicted evidence. */\n #closingFeedback(contradicted: readonly string[]): string {\n return clip(\n `Reflex closing check: this turn is about to close while its own tool results carry failures that contradict what it claims ` +\n `(${contradicted.map((item) => `\"${item}\"`).join('; ')}). Before concluding, either fix the failing evidence or state the failure ` +\n `plainly instead of the completion claim.`,\n FEEDBACK_CHARS\n );\n }\n}\n\n/** The installer's product: the detachers, the engine behind them, and live reconfiguration. */\nexport interface InterventionInstallation {\n /** Detachers of every currently registered listener, in registration order. */\n disposers: Array<() => void>;\n /** The engine the listeners drive, for the panel and for tests. */\n engine: InterventionEngine;\n /**\n * Apply a freshly resolved intervention policy without a remount.\n *\n * Thresholds are swapped on the engine and the listener set is reconciled with\n * the new effective modes: a capability turned `off` loses its hooks (zero\n * listeners and zero per-call overhead), one turned back on gets them again.\n * The engine's per-agent turn state is deliberately preserved, so a settings\n * save in the middle of a turn does not restart that turn's counters.\n * @param config - freshly resolved `interventions` block.\n * @param pruneThreshold - freshly resolved top-level prune threshold.\n * @param ownTools - freshly resolved `reflex_*` names, so a prefix rename\n * keeps the plugin's own output out of its own judgments.\n */\n reconfigure(config: ResolvedInterventionsConfig, pruneThreshold: number, ownTools?: readonly string[]): void;\n /** The number of listeners currently attached (0 when every capability is off). */\n readonly listenerCount: number;\n /** Detach every listener; idempotent. */\n dispose(): void;\n}\n\n/**\n * Install the automatic interventions of one activation.\n *\n * Registration itself is mode-aware: a capability in `off` gets no listener at\n * all, so \"off\" is the absence of the feature rather than a flag every hook has\n * to remember to check. A Host missing one of these hooks is tolerated: the\n * registration is guarded, so a stripped-down embedder loses one capability\n * instead of failing to load.\n *\n * The set is reconciled at install *and* on every config-only save, because the\n * loader commits the new volatile values into the running activation instead of\n * remounting it: {@link InterventionInstallation.reconfigure} adds the hooks a\n * newly enabled capability needs and removes those of a capability switched off.\n *\n * What is *not* per-capability is the turn frame. One turn has one lifecycle\n * whatever combination of capabilities is enabled: `agent/pre-step` opens it —\n * the turn's counters, its step number, and its stale latches — and\n * `agent/disposed` closes it. A prune-only deployment used to get neither, so its\n * first result was counted against turn 0, its intervention cap never reset, and\n * nothing was disposed. Registering the frame once for every enabled capability is\n * what makes the budget a per-turn budget rather than an accident of which\n * capability happened to be on.\n *\n * @param ctx - registrant context.\n * @param options - engine options, including the audit sink.\n * @returns the detachers, the engine, and the live reconfiguration seam.\n */\nexport function installInterventions(ctx: Context, options: InterventionEngineOptions): InterventionInstallation {\n const engine = new InterventionEngine(options);\n const disposers: Array<() => void> = [];\n /** Attached hook groups, keyed by the capability set they serve. */\n const groups = new Map<'frame' | 'pipeline' | 'closing', Array<() => void>>();\n let disposed = false;\n\n /**\n * Register every hook of one group, tolerating a Host without that hook.\n * @param group - the group to attach.\n */\n const attach = (group: 'frame' | 'pipeline' | 'closing'): void => {\n if (groups.has(group)) return;\n const detachers: Array<() => void> = [];\n const guard = (register: () => unknown): void => {\n try {\n const detach = register();\n if (typeof detach === 'function') {\n const fn = detach as unknown as () => void;\n detachers.push(fn);\n disposers.push(fn);\n }\n } catch {\n // A Host without the hook simply does not get that intervention.\n }\n };\n\n if (group === 'frame') {\n // ── the turn frame, shared by every capability that acts inside a turn ──\n guard(() => ctx.on('agent/pre-step', (payload, next) => engine.preStep(payload, next)));\n guard(() =>\n ctx.on('agent/disposed', (payload) => {\n engine.forget(agentKeyOf(payload));\n })\n );\n } else if (group === 'pipeline') {\n // ── the result pipeline: stagnation evidence, pruning, failure evidence ─\n // Every capability reads this pipeline: stagnation needs the recorded\n // calls, pruning needs the payloads, the gate needs the failures, and the\n // closing check needs the failing evidence of the turn.\n guard(() => ctx.on('tools/pre-execute', (exec, next) => engine.toolCall(exec, next)));\n guard(() => ctx.on('tools/post-execute', (exec, result, next) => engine.toolResult(exec, result, next)));\n } else {\n // ── the closing check's own inputs and its turn boundary ────────────────\n guard(() => ctx.on('agent/turn-stopping', (payload) => engine.turnStopping(payload)));\n guard(() =>\n ctx.on('agent/assistant-stream', (payload) => {\n engine.observeAssistantStream(payload);\n })\n );\n }\n groups.set(group, detachers);\n };\n\n /**\n * Detach one group and drop its entries from the public detacher list.\n * @param group - the group to detach.\n */\n const detach = (group: 'frame' | 'pipeline' | 'closing'): void => {\n const detachers = groups.get(group);\n if (!detachers) return;\n groups.delete(group);\n for (const dispose of detachers.reverse()) {\n dispose();\n const index = disposers.lastIndexOf(dispose);\n if (index >= 0) disposers.splice(index, 1);\n }\n };\n\n /**\n * Reconcile the attached listeners with the effective capability modes.\n */\n const sync = (): void => {\n if (disposed) return;\n const wanted = new Set<'frame' | 'pipeline' | 'closing'>();\n if (engine.enabled) {\n wanted.add('frame');\n // The result pipeline feeds every capability; it is present whenever any\n // of them is, exactly as it was before the live path existed.\n wanted.add('pipeline');\n if (engine.serves('closing')) wanted.add('closing');\n }\n for (const group of ['closing', 'pipeline', 'frame'] as const) {\n if (!wanted.has(group)) detach(group);\n }\n for (const group of ['frame', 'pipeline', 'closing'] as const) {\n if (wanted.has(group)) attach(group);\n }\n };\n\n sync();\n\n return {\n disposers,\n engine,\n reconfigure(config: ResolvedInterventionsConfig, pruneThreshold: number, ownTools?: readonly string[]): void {\n if (disposed) return;\n engine.updatePolicy(config, pruneThreshold, ownTools);\n sync();\n },\n get listenerCount(): number {\n return disposers.length;\n },\n dispose(): void {\n if (disposed) return;\n disposed = true;\n detach('closing');\n detach('pipeline');\n detach('frame');\n }\n };\n}\n\n/**\n * The isolation key of one agent, tolerating a disposal payload that wraps it.\n * @param value - an agent, or a payload carrying one.\n * @returns its key; `anonymous` when no identity is available.\n */\nexport function agentKeyOf(value: unknown): string {\n const direct = value as { id?: unknown } | undefined;\n if (typeof direct?.id === 'string' && direct.id.length > 0) return direct.id;\n const wrapped = (value as { agent?: { id?: unknown } } | undefined)?.agent;\n if (typeof wrapped?.id === 'string' && wrapped.id.length > 0) return wrapped.id;\n return 'anonymous';\n}\n\n/**\n * The session one agent decides in.\n * @param value - an agent, or a payload carrying one.\n * @returns the session object, or `undefined` when the agent has none.\n */\nexport function sessionOf(value: unknown): unknown {\n const agent = (value as { agent?: unknown } | undefined)?.agent ?? value;\n const session = (agent as { session?: unknown } | undefined)?.session;\n return session && typeof session === 'object' ? session : undefined;\n}\n\n/**\n * The identity of the session one agent decides in.\n *\n * A memo of reductions is only valid inside the run that produced it: the same\n * agent id in a resumed or forked session is a different log, with different\n * retained originals behind the same payload digests. Keying by the session —\n * and falling back to the agent itself when no session is visible — is what keeps\n * one run's cached reduction from being installed into another run.\n * @param value - an agent, or a payload carrying one.\n * @returns the session identity, or the agent's own key when it has none.\n */\nexport function sessionKeyOf(value: unknown): string {\n const session = sessionOf(value) as { id?: unknown } | undefined;\n return typeof session?.id === 'string' && session.id.length > 0 ? session.id : `agent:${agentKeyOf(value)}`;\n}\n\n/** The identity a repeated call is measured on: its name and its arguments. */\nfunction callSignature(exec: ToolExecution): string {\n let args: string;\n const raw: unknown = exec.arguments;\n if (typeof raw === 'string') args = raw;\n else {\n try {\n args = JSON.stringify(raw ?? {}) ?? '';\n } catch {\n args = '';\n }\n }\n return `${exec.name}:${digestOf(args)}`;\n}\n\n/** The percentage one reduction reports, at the shared token rate. */\nfunction reductionPercentage(originalChars: number, prunedChars: number): number {\n return originalChars === 0 ? 0 : Math.round(((originalChars - prunedChars) / originalChars) * 1000) / 10;\n}\n\n/**\n * The *candidate* sentences of one turn's assistant text.\n *\n * Deterministic and semantic-free on purpose: splitting, de-duplication, the\n * length floor, and the last-{@link MAX_CLAIMS} bound are all the local work\n * this module may do. Whether a candidate really claims completion is System\n * One's answer — an English word list would miss 中文「全部通过」 and read\n * `not complete` as the opposite, so there is none here any more.\n *\n * @param text - the turn's assistant text.\n * @returns bounded, deduplicated candidates in their original order.\n */\nexport function claimCandidates(text: string): string[] {\n const candidates: string[] = [];\n const seen = new Set<string>();\n for (const raw of text.split(/(?<=[.!?。!?\\n])/)) {\n const sentence = raw.replace(/\\s+/g, ' ').trim();\n if (sentence.length < MIN_CLAIM_CHARS) continue;\n const statement = clip(sentence, 200);\n if (seen.has(statement)) continue;\n seen.add(statement);\n candidates.push(statement);\n }\n return candidates.length > MAX_CLAIMS ? candidates.slice(candidates.length - MAX_CLAIMS) : candidates;\n}\n\n// Re-exported so a Host attaching the session log does not have to import the\n// audit module directly.\nexport { appendInterventionRecord };\n"]}
1
+ {"version":3,"file":"interventions.js","sourceRoot":"","sources":["../src/interventions.ts"],"names":[],"mappings":"AAwEA,OAAO,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAKtE,OAAO,EACL,yBAAyB,EAI1B,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,wBAAwB,EAAE,YAAY,EAAgC,MAAM,oBAAoB,CAAC;AAK1G,OAAO,EAEL,UAAU,EACV,SAAS,EAEV,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,WAAW,EACX,WAAW,EAEX,WAAW,EAMZ,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAGL,MAAM,EACN,MAAM,IAAI,YAAY,EAEvB,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAAE,gBAAgB,EAA2B,MAAM,6CAA6C,CAAC;AACxG,OAAO,EACL,aAAa,EACb,kBAAkB,EAEnB,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EACL,wBAAwB,EACxB,yBAAyB,EACzB,aAAa,IAAI,mBAAmB,EAKrC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EAItB,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAC;AAEnH,iFAAiF;AACjF,wEAAwE;AACxE,OAAO,EAAE,eAAe,EAAE,MAAM,yCAAyC,CAAC;AAC1E,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,0CAA0C,CAAC;AACnH,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,uCAAuC,CAAC;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AAG,KAAK,QAAQ;QAAE,IAAI,GAAG,GAAG,CAAC;SACnC,CAAC;QACJ,IAAI,CAAC;YACH,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC;QACzC,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,GAAG,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;IACD,OAAO,GAAG,IAAI,CAAC,IAAI,IAAI,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;AAC1C,CAAC;AAED,sEAAsE;AACtE,SAAS,mBAAmB,CAAC,aAAqB,EAAE,WAAmB;IACrE,OAAO,aAAa,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,aAAa,GAAG,WAAW,CAAC,GAAG,aAAa,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAC3G,CAAC;AAGD,8EAA8E;AAC9E,yBAAyB;AACzB,OAAO,EAAE,wBAAwB,EAAE,CAAC","sourcesContent":["/**\n * Automatic interventions on the Host's native tool and agent lifecycle hooks.\n *\n * The plugin's eight MCP tools are pull-based: they act only when the *model*\n * decides to call one. This module is the push half — the same System 1\n * judgments, spent automatically at the four points where the Host already asks\n * its listeners a question:\n *\n * | Hook | Capability | What it may do |\n * | --- | --- | --- |\n * | `tools/pre-execute` | `stagnation` | deny a call the run is repeating |\n * | `tools/post-execute` | `prune` | replace an oversized result with its reduction |\n * | `tools/post-execute` | `gate` | turn a repeated failure into corrective feedback |\n * | `agent/pre-step` | `stagnation` | attach the correction to the next step |\n * | `agent/turn-stopping` | `closing` | object to a turn closing on contradicted evidence |\n *\n * ## The three-state discipline\n *\n * Every capability runs in one of three modes. The distinction is *not* \"on/off\n * with logging\": `observe` runs the same detection, the same judgment, and the\n * same plan as `active`, and withholds only the application. That is what makes\n * the mode worth having — what observe measures is exactly what active would\n * have done, on the same payloads, at the same cost.\n *\n * | Mode | Detection | Judgment | Application | Model-visible change |\n * | --- | --- | --- | --- | --- |\n * | `off` | none | none | none | none |\n * | `observe` | full | full | none | **none at all** |\n * | `active` | full | full | full | the planned text |\n *\n * `observe` is therefore *not* the reference plugin's shadow mode: that one\n * injects a model-visible notice saying it changed nothing. Here an observation\n * has no model-visible surface whatsoever — no message, no rewritten content, no\n * denial, no steering. The one thing it produces is an audit record in the\n * session log, which the model cannot read.\n *\n * ## Cost discipline\n *\n * A deterministic, local pre-trigger decides whether a *judgment* may be spent\n * at all, and judgments are budgeted per turn and per session: at most\n * {@link ResolvedInterventionsConfig.maxJudgmentsPerTurn} per turn and\n * {@link ResolvedInterventionsConfig.maxJudgmentsPerSession} per agent, with one\n * verdict reused by every hook of the same turn. A turn presenting twenty\n * similar results therefore costs one judgment, not twenty. Applied\n * interventions carry their own ceiling, so an intervention can never become the\n * loop it was meant to break.\n *\n * ## Fail-open and isolation\n *\n * Every hook delegates first (`await next()`), and every planning step is\n * wrapped: an exception, an aborted signal, or an unusable verdict leaves the\n * call, the result, the messages, and the turn exactly as the rest of the\n * waterfall left them. Detection state is keyed by agent id, so two agents in one\n * process can never see each other's history, verdicts, or budgets. Nothing here\n * grants a permission the Host would not have granted, and nothing here overrides\n * one either: a call the rest of the waterfall denied, cancelled, or routed to an\n * approval flow is returned untouched, so the only decision this module can add\n * is a strictly narrower one on top of a plain `allow`.\n *\n * ## Retained originals\n *\n * A reduction is installed only after the bytes it replaces have been retained\n * in the agent's own Session log, in the plugin-record channel the audit trail\n * already uses. The replacement publishes a locator derived from the payload's\n * digest, a reader resolves it back to the verbatim original, and a payload that\n * cannot be retained — too large, no session, a log that did not commit — is\n * never replaced: `saved` is reported only for a replacement that really\n * happened and can really be checked.\n *\n * @module dsh-reflex/interventions\n */\nimport type { Context } from '@deepseek-ai/cordis';\nimport { MessageId, boundContextSummary } from '@deepseek-ai/dsh-llm';\nimport type { ContentBlock, ContextFormed, UserMessage } from '@deepseek-ai/dsh-llm';\nimport type { PreStepDecision } from '@deepseek-ai/dsh-agent';\nimport type { PostToolDecision, PreToolDecision, ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools';\n\nimport {\n INTERVENTION_CAPABILITIES,\n type InterventionCapability,\n type InterventionMode,\n type ResolvedInterventionsConfig\n} from './config.js';\nimport { appendInterventionRecord, pruneLocator, type InterventionAuditRecord } from './session-audit.js';\nimport type { ReflexGateService, StagnationDetector, ToolResultPruner } from './vendor/harness-reflex/index.js';\nimport type { Attribution } from './attribution.js';\nimport type { PruneResponse, StagnationCheckResponse } from './vendor/harness-reflex/index.js';\nimport { claimCandidates } from './vendor/harness-reflex/core/closing.js';\nimport {\n assembleEvidence,\n evidenceOf,\n failureOf,\n type EvidenceEntry\n} from './vendor/harness-reflex/core/evidence.js';\nimport {\n applyCharge,\n emptyBucket,\n judgmentCharge,\n suspicionOf,\n type CostCharge,\n type InterventionCostBucket,\n type JudgmentCharge,\n type StagnationSuspicion,\n type ObservedStep\n} from './vendor/harness-reflex/core/judge.js';\nimport {\n actionWithinBudget,\n bookAction,\n modeOf,\n serves as policyServes,\n spendJudgment\n} from './vendor/harness-reflex/core/policy.js';\nimport { applyPruneFloor } from './vendor/harness-reflex/core/prune-plan.js';\nimport { orchestratePrune, type PruneFeedbackFacts } from './vendor/harness-reflex/core/orchestrate.js';\nimport {\n CLOSING_LATCH,\n orchestrateClosing,\n type HostClosingPort\n} from './vendor/harness-reflex/core/orchestrate-closing.js';\nimport {\n orchestrateStagnationPre,\n orchestrateStagnationStep,\n progressSteps as sharedProgressSteps,\n type HostStagnationPort,\n type JudgedCharge,\n type StagnationFeedbackFacts,\n type StagnationPlanRecord\n} from './vendor/harness-reflex/core/orchestrate-stagnation.js';\nimport {\n describeCorrection,\n orchestrateCorrection,\n type CorrectionFeedbackFacts,\n type CorrectionPlanRecord,\n type HostCorrectionPort\n} from './vendor/harness-reflex/core/orchestrate-correction.js';\nimport { clip, digestOf, estimateTokens, hasTextBlock, textOfContent } from './vendor/harness-reflex/core/text.js';\n\n// The decision primitives keep their historic import path: a caller that already\n// imports the intervention surface does not need a second one for them.\nexport { claimCandidates } from './vendor/harness-reflex/core/closing.js';\nexport { assembleEvidence, evidenceOf, FAILURE_MARKER, failureOf } from './vendor/harness-reflex/core/evidence.js';\nexport { countTrailingFailures, countTrailingRepeats, detectOscillation, suspicionOf } from './vendor/harness-reflex/core/judge.js';\nexport { applyPruneFloor, pruneFloorPlan, pruneMarker } from './vendor/harness-reflex/core/prune-plan.js';\nexport { digestOf, estimateTokens, textOfContent } from './vendor/harness-reflex/core/text.js';\nexport type { EvidenceEntry, EvidencePriority } from './vendor/harness-reflex/core/evidence.js';\nexport type { InterventionCostBucket } from './vendor/harness-reflex/core/judge.js';\nexport type { PruneFloorOptions, PruneFloorPlan } from './vendor/harness-reflex/core/prune-plan.js';\n\n/**\n * Producer-owned source kind of every message this plugin appends.\n *\n * Session format v4 has no catch-all `plugin` kind and refuses that literal\n * outright, so the producer names itself — the same identity this plugin already\n * uses for its audit records.\n */\nexport const INTERVENTION_SOURCE_KIND = 'plugin:dsh-reflex';\n\ndeclare module '@deepseek-ai/dsh-llm' {\n interface MessageSourceMap {\n /** One corrective context this plugin attached to a step. */\n 'plugin:dsh-reflex': { kind: 'plugin:dsh-reflex' } & ContextFormed;\n }\n}\n\n/** Characters of one observed step's input or output retained for judging. */\nconst STEP_CHARS = 600;\n/** Steps one agent's detection window may retain. */\nconst MAX_STEPS = 12;\n/** Characters of assistant text retained per turn for the closing check. */\nconst CLAIM_CHARS = 4000;\n/**\n * Evidence entries retained per turn for the closing check.\n *\n * Entries are candidates, not conclusions: every observed result contributes its\n * tail summary, and a failure-marker line is kept as a safety floor. The\n * character budget (not this count) decides what the judgment reads.\n */\nconst MAX_EVIDENCE = 16;\n/** Agent states retained before the least recently used is dropped. */\nconst MAX_AGENTS = 64;\n/** Reductions memoized per activation, bounded by least recent use. */\nconst MAX_MEMO = 128;\n/** Audit records retained for the panel, per activation. */\nconst MAX_RECENT = 20;\n/** Longest corrective text this module hands to the model, in characters. */\nconst FEEDBACK_CHARS = 600;\n/**\n * Line breaks a payload needs before it is treated as line-oriented output.\n *\n * A prune rewrites a *result* — command output, a test log, a build trace — and\n * the judgment is asked to extract the diagnostics from exactly that shape. A\n * payload with no line structure (one long JSON document, a single runaway\n * line) is not that shape: its value is semantic rather than diagnostic, and\n * cutting it in half would destroy it rather than compress it. Those payloads\n * are left alone, in both modes, and the skip is reported as\n * `unsupported-payload`.\n */\nconst PRUNE_MIN_LINES = 4;\n/**\n * Largest payload this module is willing to copy into the session log.\n *\n * Retention is what makes a reduction safe, so the cap is a *precondition* of\n * pruning rather than a fallback: above it the engine reports\n * `retention-too-large` and leaves the result untouched, so an oversized\n * payload can never be reported as saved on the strength of a copy that was\n * never kept. A hundred kilobyte log line stays readable and bounded.\n */\nconst MAX_RETAINED_CHARS = 100_000;\n\n/** The action names one plan may carry. */\nexport type InterventionAction =\n | 'deny-call'\n | 'prune-result'\n | 'corrective-feedback'\n | 'corrective-context'\n | 'steer-closing';\n\n/**\n * One planned intervention, before the mode decides whether it is applied.\n *\n * The plan is the *same* object in observe and active mode; only the audit\n * record's `applied` differs. That is what lets a reader compare what a mode\n * measured with what it did.\n */\nexport interface InterventionPlan {\n capability: InterventionCapability;\n action: InterventionAction;\n reason: string;\n /** Text the active path hands to the model; never empty. */\n feedback: string;\n detail: {\n pattern?: string;\n confidence?: number;\n repeats?: number;\n digest?: string;\n floorApplied?: boolean;\n /** Whether the reduction was installed short of the floor's promised share. */\n floorMissed?: boolean;\n /** Whether a floor miss had to omit its locator marker to stay smaller. */\n markerOmitted?: boolean;\n turn?: number;\n step?: number;\n /** Which judging path produced the prune candidate. */\n judgePath?: 'segmented' | 'local' | 'fallback';\n /** Segments handed to System One by the prune judgment. */\n judgedSegments?: number;\n /** Segments beyond the per-request limit, kept deterministically instead. */\n unjudgedSegments?: number;\n /** Segments the composed candidate kept whole. */\n keptSegments?: number;\n /** Characters of the aggressive-budget candidate the judgment built. */\n aggressiveChars?: number;\n /** Characters of the balanced-budget candidate the judgment built. */\n balancedChars?: number;\n /** Characters of the conservative-budget candidate the judgment built. */\n conservativeChars?: number;\n /** Segments System One really scored, out of the judged ones. */\n scoredSegments?: number;\n /** Segments kept whole without a score (the unjudged safety margin). */\n autoKeptSegments?: number;\n /** Answers returned for a judged segment that carried no usable score. */\n unparsedScoreAnswers?: number;\n /** Characters of the payload the plan was about. */\n originalChars?: number;\n /** Characters of the candidate the plan would install. */\n candidateChars?: number;\n /** Why the segmented judge fell back to the local candidates, when it did. */\n fallbackReason?: string;\n };\n}\n\n/**\n * Prune-path facts an abandoned plan carries into its audit record.\n *\n * The engine computes these on the way to a decision — the payload's identity\n * and size up front, the judged path and segment counts once the service has\n * answered — so a skip can say *which* decision path was abandoned instead of\n * only that one was. Nothing here is recomputed for the audit; the values are\n * the ones the decision itself used.\n */\nexport interface InterventionSkipDetail {\n /** Payload identity, when a payload was the subject of the decision. */\n digest?: string;\n /** Characters of that payload. */\n originalChars?: number;\n /** Characters of the candidate the decision would have installed. */\n candidateChars?: number;\n /** Tokens of that payload, when already known. */\n originalTokens?: number;\n /** Tokens of that candidate, when already known. */\n candidateTokens?: number;\n /** Whether the installed text carried the floor form (`floored` in the audit). */\n floored?: boolean;\n /** Whether the installed reduction fell short of the floor's promised share. */\n floorMissed?: boolean;\n /** Whether a floor miss had to omit its locator marker to stay smaller. */\n markerOmitted?: boolean;\n /** Which judging path produced the candidate. */\n judgePath?: 'segmented' | 'local' | 'fallback';\n /** Segments handed to System One by the judgment. */\n judgedSegments?: number;\n /** Segments beyond the per-request limit, kept deterministically instead. */\n unjudgedSegments?: number;\n /** Segments the candidate kept whole. */\n keptSegments?: number;\n /** Characters of the aggressive-budget candidate the judgment built. */\n aggressiveChars?: number;\n /** Characters of the balanced-budget candidate the judgment built. */\n balancedChars?: number;\n /** Characters of the conservative-budget candidate the judgment built. */\n conservativeChars?: number;\n /** Segments System One really scored, out of the judged ones. */\n scoredSegments?: number;\n /** Segments kept whole without a score (the unjudged safety margin). */\n autoKeptSegments?: number;\n /** Answers returned for a judged segment that carried no usable score. */\n unparsedScoreAnswers?: number;\n /** Why the segmented judge fell back to the local candidates. */\n fallbackReason?: string;\n}\n\n/** What one abandoned plan tells the audit sink about itself. */\ninterface SkipContext {\n /** Capability whose plan was abandoned. */\n capability: InterventionCapability;\n /** The deciding agent's bookkeeping, when the hook had it. */\n state?: AgentState;\n /** The agent (or payload carrying one) whose session receives the record. */\n agent?: unknown;\n /** Prune-path facts, when a payload was involved. */\n detail?: InterventionSkipDetail;\n /** The judgment this decision rode on, so a paid skip is not booked as free. */\n judgment?: JudgmentCharge;\n}\n\n/**\n * The identity of one tool call, stable across its pre- and post-execute hooks.\n * @param exec - the execution.\n * @returns the call's own identity, falling back to its name.\n */\nfunction callKeyOf(exec: ToolExecution): string {\n const token = (exec as { token?: unknown }).token;\n if (typeof token === 'string' && token.length > 0) return token;\n const callId = (exec as { callId?: unknown }).callId;\n return typeof callId === 'string' && callId.length > 0 ? callId : exec.name;\n}\n\n/**\n * The Host's background-job *query* tools, and the call shape each one needs\n * before it counts as a legitimate wait.\n *\n * This is the documented default of the stagnation exemption, and it is\n * deliberately identity-based rather than wording-based: the keys are the names\n * the DSH Host itself registers for background jobs — `@deepseek-ai/dsh-tool-jobs`\n * registers `job_output`, `job_list`, and `job_kill`, and the background modes\n * of the shell tools hand their jobs to the same `job_output` verb. The\n * tool's *description* is never parsed, and no result text is ever read, so an\n * output that happens to contain `wait`, `sleep`, or `poll` earns nothing.\n *\n * The shape is the structured job handle the call is about, in the Host's own\n * declared parameter name (`job_id`). `job_list` declares no parameters at all —\n * it lists the caller's own jobs — so its shape is the empty argument object.\n * `job_kill` is deliberately absent: it is a terminating action, not a query a\n * waiting run repeats, and a run that repeats it is not waiting for anything.\n */\nexport const WAIT_QUERY_TOOLS: Readonly<Record<string, { handles: readonly string[]; argumentless?: boolean }>> = {\n job_output: { handles: ['job_id'] },\n job_list: { handles: [], argumentless: true }\n};\n\n/**\n * One call's arguments as a plain object, or `undefined` when they are not one.\n * @param exec - the execution.\n * @returns the argument object, never an array or a primitive.\n */\nfunction structuredArguments(exec: ToolExecution): Record<string, unknown> | undefined {\n const raw: unknown = exec.arguments;\n let value: unknown = raw;\n if (typeof raw === 'string') {\n try {\n value = JSON.parse(raw);\n } catch {\n return undefined;\n }\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/**\n * Whether one call is a legitimate wait rather than a candidate repetition.\n *\n * Two structured facts decide it, and nothing else: the tool's identity in\n * {@link WAIT_QUERY_TOOLS}, and the argument shape that identity requires — a\n * non-empty job handle in a string field the Host itself declares. A call that\n * repeats the same handle is exactly the sanctioned poll of a background job, so\n * its repetition carries no information about progress, while any other tool\n * (however its output reads) is judged as before.\n *\n * @param exec - the call about to run.\n * @returns whether the call is a wait query.\n */\nexport function isWaitQuery(exec: ToolExecution): boolean {\n const shape = WAIT_QUERY_TOOLS[exec.name];\n if (!shape) return false;\n const args = structuredArguments(exec);\n if (!args) return false;\n if (shape.argumentless === true) return Object.keys(args).length === 0;\n return shape.handles.some((field) => typeof args[field] === 'string' && (args[field] as string).length > 0);\n}\n\n/** Field names that name a background handle a status query is about. */\nconst POLL_HANDLE_FIELD = /(?:^|_)(?:job|task|run|process|pid|handle|call|query|poll|id)$/i;\n\n/**\n * The argument shape that makes a *non-listed* repetition a wait suspect.\n *\n * The tool-name list is deliberately narrow (the Host's own job tools), but a\n * run can wait through another backend's poll verb. A non-empty handle-shaped\n * field is the cue that the repetition may be a status query; it only makes the\n * call worth asking about — System One still decides whether it is a wait.\n * @param exec - the call about to run.\n * @returns a shape label, or `undefined` when the arguments carry no handle.\n */\nexport function pollShapeOf(exec: ToolExecution): string | undefined {\n const args = structuredArguments(exec);\n if (!args) return undefined;\n for (const [key, value] of Object.entries(args)) {\n if (!POLL_HANDLE_FIELD.test(key)) continue;\n if (typeof value === 'string' && value.length > 0) return 'poll-handle';\n if (typeof value === 'number' && Number.isFinite(value)) return 'poll-handle';\n }\n return undefined;\n}\n\n/** A compact, bounded rendering of one call's arguments. */\nfunction argumentShapeOf(exec: ToolExecution): string {\n const args = structuredArguments(exec);\n if (!args) return 'non-object';\n const entries = Object.entries(args).map(([key, value]) => {\n const rendered = value === null || typeof value !== 'object' ? clip(String(value), 60) : '…';\n return `${key}=${rendered}`;\n });\n return entries.length > 0 ? entries.join(', ') : 'empty';\n}\n\n/**\n * The context one wait question carries into the stagnation judgment.\n *\n * It is *context*, not a verdict: the tool name, the argument shape, and the\n * repeat count let System One tell a sanctioned wait from a no-progress loop,\n * and nothing here allows or refuses the call by itself.\n */\nexport function waitGoalOf(exec: ToolExecution, shape: string, repeats: number): string {\n return [\n `suspect: ${shape}`,\n `tool: ${exec.name}`,\n `argument-shape: ${argumentShapeOf(exec)}`,\n `repeats: ${repeats}`,\n 'A repeated status/job query can be a legitimate wait for background work rather than a no-progress loop; decide from the action history and the polled outputs.'\n ].join('; ');\n}\n\n/**\n * Label each poll of one series with its place in it.\n *\n * The backend reasons about the run, not about string identity: two polls of the\n * same job are successive observations, and telling them apart keeps a\n * sanctioned wait from being read as the same action retried forever. Every\n * other step is passed through untouched.\n * @param steps - the window the question is about.\n * @param signature - identity of the poll being proposed.\n * @returns a copy with `[poll #n]` appended to each poll's input.\n */\nexport function annotateWaitHistory(steps: readonly ObservedStep[], signature: string): ObservedStep[] {\n let poll = 0;\n return steps.map((step) => {\n if (step.signature !== signature) return step;\n poll += 1;\n return { ...step, input: clip(`${step.input} [poll #${poll}]`, STEP_CHARS) };\n });\n}\n\n\n/**\n * The window a stagnation trigger and its judgment are measured on.\n *\n * A wait query is not progress the run can be repeating: an identically repeated\n * status/result query of the same background job is the sanctioned way to wait,\n * so those steps are dropped before the repetition, failure, and oscillation\n * triggers read the window. Genuine calls on either side of a wait stay adjacent\n * instead of being separated by it, which is what keeps a real loop visible\n * while a run is waiting.\n * @param steps - observed steps, oldest first.\n * @returns the steps that count as progress.\n */\nfunction progressSteps(steps: readonly ObservedStep[]): readonly ObservedStep[] {\n return sharedProgressSteps(steps);\n}\n\n/** One agent's detection state, budgets, and counters. */\ninterface AgentState {\n /** Session this agent's state belongs to; memoized reductions never cross it. */\n sessionKey: string;\n turn: number;\n step: number;\n steps: ObservedStep[];\n /** Assistant text of the current turn, for the closing check. */\n claims: string;\n /** Evidence candidates the current turn produced (see {@link EvidenceEntry}). */\n evidence: EvidenceEntry[];\n /** Whether any evidence candidate is a failure suspicion worth judging. */\n evidenceSuspect: boolean;\n /** Interventions applied in the current turn. */\n interventions: number;\n judgmentsTurn: number;\n judgmentsCount: number;\n judgmentsSession: number;\n verdictTurn: number;\n /** Identity of the window the cached verdict was about. */\n verdictKey: string;\n verdict?: StagnationCheckResponse;\n /** Wait-suspect call identities already classified this turn. */\n waited: Set<string>;\n /** Identities this turn already intervened on, so no action repeats itself. */\n applied: Set<string>;\n /** Call signatures already refused this turn. */\n denied: Set<string>;\n /** Calls this engine refused, keyed by the call identity. */\n refused: Set<string>;\n}\n\n/** The baseline side of the accounting: what the hooks were shown, untouched. */\nexport interface InterventionBaseline {\n /** Results the post-execute hook was shown. */\n results: number;\n /** Tokens those results carried. */\n originalTokens: number;\n /** Failing results the post-execute hook was shown. */\n failures: number;\n}\n\n/** One activation's intervention accounting, as the panel and tests read it. */\nexport interface InterventionReport {\n mode: InterventionMode;\n capabilities: Record<InterventionCapability, InterventionMode>;\n baseline: InterventionBaseline;\n observe: InterventionCostBucket;\n active: InterventionCostBucket;\n byCapability: Record<InterventionCapability, InterventionCostBucket>;\n /** Hook-level refusals, by reason, sorted. */\n skips: Record<string, number>;\n /** The most recent decisions, oldest first, bounded. */\n recent: InterventionAuditRecord[];\n /**\n * Originals this activation retained before replacing them.\n *\n * `copies` counts every verified retention; `locators` keeps the most recent\n * ones, so a reader can resolve a live replacement back to its bytes without\n * scanning the whole log.\n */\n retained: { copies: number; locators: string[] };\n /**\n * Closing-evidence bytes kept vs. dropped by the character budget.\n *\n * Truncation is by priority (diagnostic lines, then tail summaries, then the\n * rest); a diagnostic floor line is never dropped, so a nonzero `truncatedChars`\n * describes tail/other material only.\n */\n evidence: { retainedChars: number; truncatedChars: number };\n}\n\n/** Dependencies of one intervention engine. */\nexport interface InterventionEngineOptions {\n /** Resolved `interventions` block. */\n config: ResolvedInterventionsConfig;\n /** Character threshold above which a result is a pruning candidate. */\n pruneThreshold: number;\n stagnation: Pick<StagnationDetector, 'check'>;\n prune: Pick<ToolResultPruner, 'prune'>;\n /** Verification plus the closing-claim classification that precedes it. */\n gate: Pick<ReflexGateService, 'verify' | 'classifyClaims'>;\n /**\n * Run one outbound decision inside the runtime's per-call attribution.\n *\n * The engine spends real System One judgments at Host hook points, and g-068\n * requires every such call to be attributed on the ledger and in any payload\n * it returns. Absent for a bare construction (a test, an embedding Host), in\n * which case the call runs as it always did; the ledger then records it as\n * `unknown` rather than letting it read as a remote success.\n */\n attribute?: <T>(\n run: () => Promise<T>,\n options: { answered(value: T): boolean; localFallback?: (value: T) => boolean }\n ) => Promise<{ result: T; attribution: Attribution }>;\n /** Names of this plugin's own tools: their output is already optimized. */\n ownTools?: readonly string[];\n /** Clock seam. */\n now?: () => number;\n /**\n * Controlled retention of a payload a reduction is about to replace.\n *\n * Mandatory for pruning: the engine asks the sink to keep the original, and\n * only a *verifiable* copy — the locator the replacement will publish — makes\n * the reduction installable. A sink that returns `undefined`, throws, or is not\n * configured at all leaves the result untouched and the saving at zero, so a\n * deployment without controlled retention still runs, it just does not prune.\n */\n retain?: (session: unknown, request: PruneRetentionRequest) => PruneRetention | undefined;\n /** Audit sink; the plugin attaches the session log here. */\n audit?: (record: InterventionAuditRecord, session: unknown) => void;\n}\n\n\n/**\n * The payload half of a prune decision's audit fields.\n *\n * Taken before the service is asked, so a branch that refuses the payload early\n * still names the payload it refused. An empty payload has no identity worth\n * recording.\n * @param text - the effective text the decision is about.\n * @returns the digest and size of that text, or nothing for an empty payload.\n */\nfunction prunePayloadDetail(text: string): InterventionSkipDetail {\n return text.length === 0 ? {} : { digest: digestOf(text), originalChars: text.length };\n}\n\n/**\n * The judgment-path half of a prune decision's audit fields.\n *\n * Pure pass-through of what the prune service computed: which path produced the\n * candidate, how many segments it judged, and why it fell back when it did.\n * @param response - the service's answer.\n * @returns the diagnostics it reported.\n */\nfunction pruneDiagnosticsOf(response: PruneResponse): InterventionSkipDetail {\n return {\n ...(response.judgePath === undefined ? {} : { judgePath: response.judgePath }),\n ...(response.judgedSegments === undefined ? {} : { judgedSegments: response.judgedSegments }),\n ...(response.unjudgedSegments === undefined ? {} : { unjudgedSegments: response.unjudgedSegments }),\n ...(response.keptSegments === undefined ? {} : { keptSegments: response.keptSegments }),\n ...(response.aggressiveChars === undefined ? {} : { aggressiveChars: response.aggressiveChars }),\n ...(response.balancedChars === undefined ? {} : { balancedChars: response.balancedChars }),\n ...(response.conservativeChars === undefined ? {} : { conservativeChars: response.conservativeChars }),\n ...(response.scoredSegments === undefined ? {} : { scoredSegments: response.scoredSegments }),\n ...(response.autoKeptSegments === undefined ? {} : { autoKeptSegments: response.autoKeptSegments }),\n ...(response.unparsedScoreAnswers === undefined ? {} : { unparsedScoreAnswers: response.unparsedScoreAnswers }),\n ...(response.fallbackReason === undefined ? {} : { fallbackReason: response.fallbackReason })\n };\n}\n\ninterface PruneMemo {\n /** The real reduction, absent until the mode that installs one has computed it. */\n text?: string;\n originalChars: number;\n prunedChars: number;\n tokensSaved: number;\n /** Whether the reduction was floored, so a memo hit reports the same plan. */\n floored: boolean;\n /** Whether the reduction missed the floor's promised share, replayed on a hit. */\n floorMissed?: boolean;\n /** Whether that miss installed without its locator marker, replayed on a hit. */\n markerOmitted?: boolean;\n /** Locator of the retained original, once a retention for this payload succeeded. */\n locator?: string;\n /**\n * Diagnostics of the judgment that composed this form.\n *\n * Replayed by a memo hit so its audit record keeps the provenance of the plan\n * that really judged the payload, instead of looking like a path that never\n * ran the judge. Observability only: no decision reads these back.\n */\n diagnostics?: Pick<\n PruneResponse,\n | 'judgePath'\n | 'judgedSegments'\n | 'unjudgedSegments'\n | 'keptSegments'\n | 'aggressiveChars'\n | 'balancedChars'\n | 'conservativeChars'\n | 'scoredSegments'\n | 'autoKeptSegments'\n | 'unparsedScoreAnswers'\n | 'fallbackReason'\n >;\n}\n\n/**\n * What the engine hands its retention sink before it replaces a payload.\n *\n * The request carries the payload *verbatim*, so a sink never has to reconstruct\n * it, and the digest, so the sink can name it the same way the judgment and the\n * replacement do.\n */\nexport interface PruneRetentionRequest {\n /** Payload identity: `digestOf(text)`. */\n digest: string;\n /** Identity and name of the call whose result is about to shrink. */\n callId: string;\n tool: string;\n /** Turn and step of the replacement. */\n turn: number;\n step: number;\n /** The replaced payload, verbatim. */\n text: string;\n}\n\n/** The controlled copy one retention produced. */\nexport interface PruneRetention {\n /** Locator the replacement publishes. */\n locator: string;\n /** Committed log position, when the sink can report one. */\n seq?: number;\n}\n\n/**\n * The automatic-intervention engine of one plugin activation.\n *\n * One instance serves every agent in the process; all per-agent facts live in\n * {@link AgentState}, keyed by agent id, so isolation is structural rather than\n * conventional.\n */\nexport class InterventionEngine {\n /**\n * Resolved `interventions` block currently in force.\n *\n * Mutable through {@link updatePolicy}: the loader commits a config-only save\n * into the running activation, and every hook below reads this block per call,\n * so a threshold change is effective on the very next tool call without\n * rebuilding the engine (and without re-spending a schema run on the hot path).\n */\n #config: ResolvedInterventionsConfig;\n /** Character count above which a result is a pruning candidate (live). */\n #pruneThreshold: number;\n readonly #stagnation: Pick<StagnationDetector, 'check'>;\n readonly #prune: Pick<ToolResultPruner, 'prune'>;\n readonly #gate: Pick<ReflexGateService, 'verify' | 'classifyClaims'>;\n readonly #attribute: InterventionEngineOptions['attribute'];\n\n /**\n * Spend one decision inside the runtime's per-call attribution, when wired.\n *\n * Kept as one helper so every outbound judgment this engine makes — the three\n * stagnation purchases, the two closing-gate calls and the prune judge — goes\n * through the same seam. A construction without the seam runs the call\n * unchanged, which is what keeps a bare `InterventionEngine` (tests, embedding\n * Hosts) working.\n * @param run - the decision to make.\n * @param answered - whether the value counts as an answer.\n * @param localFallback - whether the value is a local answer produced after a\n * remote failure (prune's own judge path).\n * @returns whatever the decision returned.\n */\n async #decide<T>(\n run: () => Promise<T>,\n answered: (value: T) => boolean,\n localFallback?: (value: T) => boolean\n ): Promise<T> {\n if (this.#attribute === undefined) return run();\n const { result } = await this.#attribute(run, localFallback === undefined ? { answered } : { answered, localFallback });\n return result;\n }\n readonly #now: () => number;\n readonly #retain?: (session: unknown, request: PruneRetentionRequest) => PruneRetention | undefined;\n readonly #audit?: (record: InterventionAuditRecord, session: unknown) => void;\n\n readonly #states = new Map<string, AgentState>();\n #ownTools: ReadonlySet<string>;\n readonly #memo = new Map<string, PruneMemo>();\n readonly #costs: { observe: InterventionCostBucket; active: InterventionCostBucket };\n readonly #byCapability: Record<InterventionCapability, InterventionCostBucket>;\n readonly #baseline: InterventionBaseline = { results: 0, originalTokens: 0, failures: 0 };\n readonly #skips = new Map<string, number>();\n readonly #recent: InterventionAuditRecord[] = [];\n readonly #retained: string[] = [];\n readonly #evidenceStats = { retainedChars: 0, truncatedChars: 0 };\n #retainedCopies = 0;\n #counter = 0;\n\n /**\n * @param options - services, thresholds, clock, and audit sink.\n */\n constructor(options: InterventionEngineOptions) {\n this.#config = options.config;\n this.#pruneThreshold = options.pruneThreshold;\n this.#stagnation = options.stagnation;\n this.#prune = options.prune;\n this.#gate = options.gate;\n this.#attribute = options.attribute;\n this.#now = options.now ?? (() => Date.now());\n this.#retain = options.retain;\n this.#audit = options.audit;\n this.#ownTools = new Set(options.ownTools ?? []);\n this.#costs = { observe: emptyBucket(), active: emptyBucket() };\n this.#byCapability = {\n stagnation: emptyBucket(),\n prune: emptyBucket(),\n gate: emptyBucket(),\n closing: emptyBucket()\n };\n }\n\n /** The resolved intervention block currently in force. */\n get config(): ResolvedInterventionsConfig {\n return this.#config;\n }\n\n /**\n * Replace the live policy.\n *\n * Called once per actual config commit (never per tool call). Detectors and\n * per-turn state are deliberately *not* reset: a turn that is already running\n * keeps its counters and latches, and only the values each hook reads change.\n * @param config - the freshly resolved `interventions` block.\n * @param pruneThreshold - the freshly resolved top-level prune threshold.\n * @param ownTools - the live `reflex_*` names of this activation. A prefix\n * edit renames every tool, so a frozen set would stop recognising the\n * plugin's own output and start judging it as foreign work.\n */\n updatePolicy(config: ResolvedInterventionsConfig, pruneThreshold: number, ownTools?: readonly string[]): void {\n this.#config = config;\n this.#pruneThreshold = pruneThreshold;\n if (ownTools !== undefined) this.#ownTools = new Set(ownTools);\n // The pruning service also carries a copy of the threshold (the explicit\n // `prune` tool reads it directly). Keep it in step, otherwise lowering the\n // threshold would still be shadowed by the activation-time value. Absent on\n // the test seams that only implement `prune()`.\n (this.#prune as { setMinCharsThreshold?: (value: number) => void }).setMinCharsThreshold?.(pruneThreshold);\n }\n\n /** The tool names this activation treats as its own (live). */\n get ownTools(): readonly string[] {\n return [...this.#ownTools];\n }\n\n /** Whether any capability may act at all. */\n get enabled(): boolean {\n return this.config.enabled;\n }\n\n /**\n * Effective mode of one capability.\n * @param capability - the capability to ask about.\n * @returns its resolved three-state mode.\n */\n modeOf(capability: InterventionCapability): InterventionMode {\n return modeOf(this.#config, capability);\n }\n\n /**\n * Whether a hook serving one capability must be registered at all.\n * @param capabilities - capabilities the hook serves.\n * @returns whether at least one of them is not `off`.\n */\n serves(...capabilities: InterventionCapability[]): boolean {\n return policyServes(this.#config, ...capabilities);\n }\n\n /** The whole activation's accounting. */\n report(): InterventionReport {\n return {\n mode: this.config.mode,\n capabilities: { ...this.config.capabilities },\n baseline: { ...this.#baseline },\n observe: { ...this.#costs.observe },\n active: { ...this.#costs.active },\n byCapability: {\n stagnation: { ...this.#byCapability.stagnation },\n prune: { ...this.#byCapability.prune },\n gate: { ...this.#byCapability.gate },\n closing: { ...this.#byCapability.closing }\n },\n skips: Object.fromEntries([...this.#skips.entries()].sort()),\n recent: [...this.#recent],\n retained: { copies: this.#retainedCopies, locators: [...this.#retained] },\n evidence: { ...this.#evidenceStats }\n };\n }\n\n /**\n * Whether one capability already acted on one identity this turn.\n * @param agentId - agent identity.\n * @param key - capability-qualified identity.\n * @returns whether it already acted.\n */\n hasApplied(agentId: string, key: string): boolean {\n return this.#states.get(agentId)?.applied.has(key) ?? false;\n }\n\n /**\n * Detection state of one agent, for tests and diagnostics.\n * @param agentId - agent identity.\n * @returns the observable facts, or undefined for an agent never seen.\n */\n stateOf(\n agentId: string\n ): { turn: number; step: number; steps: number; interventions: number; judgmentsSession: number; claims: number; evidence: number } | undefined {\n const state = this.#states.get(agentId);\n if (!state) return undefined;\n return {\n turn: state.turn,\n step: state.step,\n steps: state.steps.length,\n interventions: state.interventions,\n judgmentsSession: state.judgmentsSession,\n claims: state.claims.length,\n evidence: state.evidence.length\n };\n }\n\n /**\n * Drop one agent's state — on disposal, so nothing outlives its session.\n * @param agentId - agent identity.\n */\n forget(agentId: string): void {\n this.#states.delete(agentId);\n }\n\n /** Drop every agent's state and every account, for a fresh measurement. */\n reset(): void {\n this.#states.clear();\n this.#memo.clear();\n this.#costs.observe = emptyBucket();\n this.#costs.active = emptyBucket();\n for (const capability of INTERVENTION_CAPABILITIES) this.#byCapability[capability] = emptyBucket();\n this.#baseline.results = 0;\n this.#baseline.originalTokens = 0;\n this.#baseline.failures = 0;\n this.#skips.clear();\n this.#recent.length = 0;\n this.#retained.length = 0;\n this.#retainedCopies = 0;\n this.#evidenceStats.retainedChars = 0;\n this.#evidenceStats.truncatedChars = 0;\n }\n\n // ── hook entry points ──────────────────────────────────────────────────────\n\n /**\n * `tools/pre-execute`: refuse a call the run is repeating.\n *\n * Delegates first and returns the downstream decision **by identity** whenever\n * that decision is not a plain `allow`. A later listener may already have sent\n * the call to an approval flow, denied it with its own structured error\n * identity, or cancelled it; overwriting any of those would drop information the\n * Host attached and could turn a stricter decision into a weaker one. The only\n * decision this hook ever *adds* is a `deny` on top of an `allow`, which is\n * strictly narrower than what the waterfall already permitted — permissions\n * here are monotone by construction, never escalated and never relaxed.\n *\n * @param exec - the tool call about to run.\n * @param next - the rest of the waterfall.\n * @returns the decision the Host dispatches on.\n */\n /**\n * How many recorded steps already carry one identity.\n *\n * The call about to run is counted separately by the shared layer, so this is\n * the count of the ones that really ran — which is what \"repeated N times\"\n * means to a reader.\n * @param state - the agent's bookkeeping.\n * @param signature - the identity to count.\n * @returns the number of recorded occurrences.\n */\n #priorSame(state: AgentState, signature: string): number {\n return state.steps.filter((step) => step.signature === signature).length;\n }\n\n async toolCall(exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision> {\n const downstream = await next();\n if (!this.config.enabled) return downstream;\n if (this.#ownTools.has(exec.name)) return downstream;\n // Checked here, outside the fail-open guard below, exactly as before: a call\n // whose signal is already aborted is not a planning failure and must not be\n // reported as one.\n if (exec.signal?.aborted) return downstream;\n\n const agentId = agentKeyOf(exec.agent);\n const state = this.#state(agentId, exec.agent);\n const signature = callSignature(exec);\n const waitShape = isWaitQuery(exec) ? 'wait-query' : pollShapeOf(exec);\n let waitSuspected = false;\n\n // The decision itself is the shared layer's (see\n // `core/orchestrate-stagnation.ts`); this method only answers the questions\n // this Host alone can answer. Everything that remains here is a DSH fact: the\n // agent's state slot, the call-signature algorithm, the job-tool list that\n // defines a wait, the message and decision types, and the wording the model\n // reads.\n const port: HostStagnationPort<PreToolDecision, PreStepDecision> = {\n policy: () => this.#config,\n budget: () => state,\n // One purchase: the service's answer, latency included. The purchase around\n // it (memo, budgets, latency split, charge) is the shared layer's.\n buy: async (step) => this.#decide(() => this.#stagnation.check(step.goal, [...step.history]), (value) => value !== undefined),\n clock: () => ({ now: () => this.#now() }),\n serves: () => this.#config.enabled,\n toolName: () => exec.name,\n window: () => state.steps,\n // The call about to run is a retry exactly when this identity failed before.\n pendingStep: () =>\n ({\n signature,\n tool: exec.name,\n input: clip(this.#argumentsOf(exec), STEP_CHARS),\n output: '',\n error: '',\n failed: state.steps.some((step) => step.signature === signature && step.failed),\n turn: state.turn,\n at: this.#now()\n }) satisfies ObservedStep,\n signature: () => signature,\n progressWindow: () => progressSteps(state.steps),\n suspicion: (steps) =>\n suspicionOf(steps, {\n repeatThreshold: this.config.repeatThreshold,\n failureThreshold: this.config.failureThreshold,\n window: this.config.windowSize,\n signature\n }),\n alreadyIntervened: () => state.applied.has(`stagnation:${signature}`),\n alreadyDenied: () => state.denied.has(signature),\n wasClassifiedAsWait: (stepSignature) => state.waited.has(stepSignature),\n latchDenied: () => state.denied.add(signature),\n latchIntervened: () => state.applied.add(`stagnation:${signature}`),\n passThrough: () => downstream,\n deny: (feedback) => ({ kind: 'deny', reason: feedback }),\n // Pre-execute never corrects a step: the correction belongs to the pre-step\n // hook, whose port answers this. Reaching it here would mean the shared\n // layer asked the wrong hook, so it is a programming error, not a branch.\n correct: (feedback) => {\n throw new Error(`toolCall cannot attach a correction (${feedback.length} chars)`);\n },\n denyFeedback: (facts) => this.#denyFeedback(exec.name, facts.suspicion, facts.verdict),\n contextFeedback: (facts) => this.#contextFeedback(facts.suspicion, facts.verdict),\n skip: (reason, charge) =>\n this.#skip(reason, {\n capability: 'stagnation',\n state,\n agent: exec.agent,\n ...(charge === undefined ? {} : { judgment: charge })\n }),\n chargeJudgment: (charge: JudgedCharge) => this.#charge('stagnation', charge),\n conclude: (plan: StagnationPlanRecord, applied: boolean, charge: JudgedCharge) =>\n this.#conclude(plan as InterventionPlan, applied, exec.agent, { potentialSavedTokens: 0 }, charge)\n };\n\n // Whether this call reached the wait question, which only decides the\n // fail-open reason: a wait whose judge could not answer is reported with its\n // own reason instead of the generic one.\n waitSuspected =\n waitShape !== undefined &&\n this.#priorSame(state, signature) + 1 >= this.config.repeatThreshold;\n try {\n const outcome = await orchestrateStagnationPre(\n {\n downstreamKind: downstream.kind,\n ...(exec.signal === undefined ? {} : { signal: exec.signal }),\n ...(waitShape === undefined\n ? {}\n : {\n waitShape: () => ({ shape: waitShape, repeats: this.#priorSame(state, signature) + 1 }),\n waitClassified: () => state.waited.has(signature),\n latchWait: () => state.waited.add(signature),\n // A wait question is judged on the polls themselves: the backend\n // reasons about the run, and labelling each poll with its place in\n // the series keeps a sanctioned wait from reading as an exact\n // repeat. How a poll is labelled is this Host's business.\n judgeSteps: () => annotateWaitHistory([...state.steps, port.pendingStep()], signature),\n waitQuestion: () => waitGoalOf(exec, waitShape, this.#priorSame(state, signature) + 1)\n }),\n noteRefused: () => state.refused.add(callKeyOf(exec))\n },\n port\n );\n return outcome.result;\n } catch {\n // FAIL-OPEN: a planning failure must never veto a call the rest of the\n // waterfall already allowed.\n this.#skip(waitSuspected ? 'wait-query-unavailable' : 'planning-error', {\n capability: 'stagnation',\n agent: exec.agent\n });\n return downstream;\n }\n }\n\n /**\n * `tools/post-execute`: reduce an oversized result, or correct a repeated\n * failure — and observe both without touching either.\n *\n * @param exec - the call that produced the result.\n * @param result - its canonical outcome.\n * @param next - the rest of the waterfall.\n * @returns the decision the Host commits.\n */\n async toolResult(\n exec: ToolExecution,\n result: Readonly<ToolExecutionResult>,\n next: () => Promise<PostToolDecision>\n ): Promise<PostToolDecision> {\n const downstream = await next();\n if (!this.config.enabled) return downstream;\n if (this.#ownTools.has(exec.name)) return downstream;\n const started = this.#now();\n try {\n const agentId = agentKeyOf(exec.agent);\n const state = this.#state(agentId, exec.agent);\n if (state.refused.has(callKeyOf(exec))) {\n // The result of a call this engine refused is the refusal itself. It is\n // neither evidence about the run nor a payload worth reducing, and\n // correcting it would bill one episode twice.\n this.#skip('refused-result', { capability: 'prune', state, agent: exec.agent });\n return downstream;\n }\n // The *effective* content: whatever the rest of the waterfall decided the\n // model will read, which is not the same thing as the result's own content.\n // An earlier listener may have replaced it, and the replacement is what this\n // hook must reason about and, in active mode, reduce.\n const content = 'content' in downstream && Array.isArray(downstream.content) ? downstream.content : result.content;\n const text = textOfContent(content);\n const failed = failureOf(result, text);\n const signature = callSignature(exec);\n this.#observe(state, {\n signature,\n tool: exec.name,\n input: clip(this.#argumentsOf(exec), STEP_CHARS),\n output: clip(text, STEP_CHARS),\n error: failed ? clip(this.#errorOf(result), STEP_CHARS) : '',\n failed,\n turn: state.turn,\n at: this.#now(),\n wait: isWaitQuery(exec)\n });\n\n this.#baseline.results += 1;\n this.#baseline.originalTokens += estimateTokens(text);\n if (failed) this.#baseline.failures += 1;\n\n // Every result contributes evidence candidates: a failure-marker line is\n // the safety floor, a tail summary carries the structured/status facts,\n // and the closing judgment — not a regex — decides what they mean.\n this.#rememberEvidence(state, exec.name, result, text, this.#errorOf(result));\n if (!failed) return await this.#pruneResult(exec, downstream, content, state, text, started);\n return await this.#correctFailure(exec, result, downstream, state, signature, started);\n } catch {\n // FAIL-OPEN: the result is handed on exactly as the waterfall produced it.\n this.#skip('planning-error', { capability: 'prune', agent: exec.agent });\n return downstream;\n }\n }\n\n /**\n * `agent/pre-step`: attach the correction to the step after the loop repeated\n * itself, and keep the turn and step bookkeeping every other hook shares.\n *\n * @param payload - the proposed step.\n * @param next - the rest of the waterfall.\n * @returns the decision the loop enters with.\n */\n async preStep(\n payload: { agent: unknown; messages: readonly UserMessage[]; turn: number; step: number; signal?: AbortSignal },\n next: () => Promise<PreStepDecision>\n ): Promise<PreStepDecision> {\n const downstream = await next();\n const started = this.#now();\n try {\n const agentId = agentKeyOf(payload.agent);\n const state = this.#state(agentId, payload.agent);\n // Turn bookkeeping is unconditional: the closing check needs the turn's own\n // words and evidence to exist even when stagnation is off.\n if (state.turn !== payload.turn) {\n state.turn = payload.turn;\n state.step = payload.step;\n state.interventions = 0;\n state.judgmentsCount = 0;\n state.judgmentsTurn = payload.turn;\n state.verdictTurn = payload.turn;\n state.verdictKey = '';\n state.verdict = undefined;\n state.claims = '';\n state.evidence = [];\n state.evidenceSuspect = false;\n state.waited.clear();\n state.applied.clear();\n state.denied.clear();\n state.refused.clear();\n }\n state.step = payload.step;\n\n // Turn bookkeeping above is this Host's and stays here: it is what the\n // closing check and the prune memo read, and it belongs to whoever owns\n // the turn boundary. What is shared is the *decision* that follows.\n const agentIdForCorrection = agentId;\n const port: HostStagnationPort<PreStepDecision, PreStepDecision> = {\n policy: () => this.#config,\n budget: () => state,\n buy: async (step) => this.#decide(() => this.#stagnation.check(step.goal, [...step.history]), (value) => value !== undefined),\n clock: () => ({ now: () => this.#now() }),\n serves: () => this.#config.enabled,\n toolName: () => state.steps[state.steps.length - 1]?.tool ?? '',\n window: () => state.steps,\n pendingStep: () => state.steps[state.steps.length - 1] as ObservedStep,\n signature: () => state.steps[state.steps.length - 1]?.signature ?? '',\n progressWindow: () => progressSteps(state.steps),\n suspicion: (steps) =>\n suspicionOf(steps, {\n repeatThreshold: this.config.repeatThreshold,\n failureThreshold: this.config.failureThreshold,\n window: this.config.windowSize,\n signature: state.steps[state.steps.length - 1]?.signature ?? ''\n }),\n alreadyIntervened: () => state.applied.has(`stagnation:${state.steps[state.steps.length - 1]?.signature ?? ''}`),\n alreadyDenied: () => false,\n wasClassifiedAsWait: (stepSignature) => state.waited.has(stepSignature),\n latchDenied: () => undefined,\n latchIntervened: () => state.applied.add(`stagnation:${state.steps[state.steps.length - 1]?.signature ?? ''}`),\n passThrough: () => downstream,\n deny: () => downstream,\n // The correction is appended to the messages the rest of the waterfall\n // admitted; the array it was given is not mutated in place.\n //\n // `downstream.messages` is read without a fallback on purpose. An `enter`\n // decision always carries the list, so an absent one means the rest of the\n // waterfall handed back something this Host cannot correct — and the\n // fail-open guard below is what should record that, not a silent\n // `messages: [correction]` that drops the very messages the step admitted.\n correct: (feedback) =>\n ({\n ...downstream,\n messages: [\n ...(downstream as unknown as { messages: UserMessage[] }).messages,\n this.#message(agentIdForCorrection, state.turn, payload.step, feedback)\n ]\n }) as PreStepDecision,\n denyFeedback: (facts) => this.#denyFeedback(facts.tool, facts.suspicion, facts.verdict),\n contextFeedback: (facts) => this.#contextFeedback(facts.suspicion, facts.verdict),\n skip: (reason, charge) =>\n this.#skip(reason, {\n capability: 'stagnation',\n state,\n agent: payload.agent,\n ...(charge === undefined ? {} : { judgment: charge })\n }),\n chargeJudgment: (charge: JudgedCharge) => this.#charge('stagnation', charge),\n conclude: (plan: StagnationPlanRecord, applied: boolean, charge: JudgedCharge) =>\n this.#conclude(plan as InterventionPlan, applied, payload.agent, { potentialSavedTokens: 0 }, charge)\n };\n\n // The abort is checked *before* the shared call and the catch below is\n // left to do what it always did: a pre-step that throws is reported as a\n // planning error, and that report is what a cancelled turn has always left\n // in the log. Passing the signal through instead would make the shared\n // layer answer `aborted` and leave no trace at all — a quieter outcome, but\n // a different one.\n if (payload.signal?.aborted === true) return downstream;\n const outcome = await orchestrateStagnationStep(\n {\n downstreamKind: downstream.kind,\n // `undefined` is not passed on: the shared layer only knows a signal it\n // can act on, and an absent one has to stay absent.\n signal: undefined\n },\n port\n );\n return outcome.result;\n } catch {\n // FAIL-OPEN: the step enters with exactly the messages it would have had.\n this.#skip('planning-error', { capability: 'stagnation', agent: payload.agent });\n return downstream;\n }\n }\n\n /**\n * `agent/turn-stopping`: object when the turn is about to close on evidence\n * that contradicts what the turn claims.\n *\n * The objection is *data*, not a veto: this method steers the corrective text\n * into the agent's inbox, and the loop's own rule decides. Steering is the only\n * way a listener may extend a turn, so a failure here can never block a turn\n * from closing.\n *\n * @param payload - the agent whose turn reached its stop boundary.\n */\n async turnStopping(payload: { agent: unknown; turn: number; signal?: AbortSignal }): Promise<void> {\n // The mode check happens in the shared layer, deliberately: \"off\" is not a\n // weaker decision, it is the absence of one, and a host that read the mode\n // here as well would be the second place the switch is interpreted.\n // The very first question is whether this decision exists at all. A turn that\n // closes while the capability is off (or the master switch is off) must leave\n // no trace — not even an empty per-agent state, which would show up in\n // `stateOf()` as an agent the engine has seen. Asking it before touching any\n // state is what keeps \"off\" the absence of a decision rather than a decision\n // that did nothing.\n if (this.modeOf('closing') === 'off' || !this.config.enabled) return;\n const started = this.#now();\n try {\n const agentId = agentKeyOf(payload.agent);\n const state = this.#state(agentId, payload.agent);\n const turn = payload.turn;\n const port: HostClosingPort = {\n policy: () => this.#config,\n budget: () => state,\n clock: () => ({ now: () => this.#now() }),\n serves: () => this.#config.enabled,\n mode: () => this.modeOf('closing'),\n claims: () => state.claims,\n evidenceSuspect: () => state.evidenceSuspect,\n evidence: () => state.evidence,\n evidenceBudget: () => this.config.closingEvidenceChars,\n aborted: () => payload.signal?.aborted === true,\n // The latch is *per turn*, not per signature: a closing episode is the\n // turn itself. This is the one latch that does not fit the `Host*Port`\n // shape the other capabilities use.\n alreadyObjected: () => state.applied.has(CLOSING_LATCH.applied(turn)),\n latchObjected: () => state.applied.add(CLOSING_LATCH.applied(turn)),\n agentId: () => agentId,\n classify: async (request) =>\n this.#decide(\n () =>\n this.#gate.classifyClaims({\n statements: [...request.statements],\n intent: this.config.intent,\n context: request.context\n }),\n (value) => value !== undefined\n ),\n verify: async (claims, evidence, options) =>\n this.#decide(() => this.#gate.verify([...claims], evidence, options), (value) => value !== undefined),\n claimMinConfidence: () => this.config.claimMinConfidence,\n describe: (facts) => this.#closingFeedback(facts.contradicted),\n // The action itself stays here. Steering is the only way a listener may\n // extend a turn, and the message it carries is this Host's to word.\n steer: (feedback) => this.#steer(payload.agent, this.#message(agentId, turn, state.step, feedback)),\n // `#evidenceStats` is engine-level, not per-agent: it counts what this\n // activation assembled, across every agent it served.\n noteEvidence: (stats) => {\n this.#evidenceStats.retainedChars += stats.retainedChars;\n this.#evidenceStats.truncatedChars += stats.truncatedChars;\n },\n skip: (reason, charge) =>\n this.#skip(reason, {\n capability: 'closing',\n state,\n agent: payload.agent,\n ...(charge === undefined ? {} : { judgment: charge })\n }),\n chargeJudgment: (charge) => this.#charge('closing', charge),\n conclude: (plan, applied, charge) =>\n this.#conclude(plan as InterventionPlan, applied, payload.agent, { potentialSavedTokens: 0 }, charge)\n };\n void started;\n // The position is an input of the closing decision, never a port accessor:\n // the turn is the boundary being closed (which can be a turn no step has\n // recorded yet), and the step is the one this engine last recorded.\n await orchestrateClosing({ position: { turn, step: state.step } }, port);\n } catch {\n // FAIL-OPEN: a failed closing check leaves the turn boundary alone.\n this.#skip('planning-error', { capability: 'closing', agent: payload.agent });\n }\n }\n\n /**\n * `agent/assistant-stream`: retain the turn's own words for the closing check.\n *\n * Deliberately not model-visible: this is a read of what the model already\n * said, kept so the turn can be checked against its own evidence. Nothing is\n * published, and the text is bounded per turn.\n *\n * @param payload - one stream frame of one attempt.\n */\n observeAssistantStream(payload: { agent: unknown; frame?: { type?: string; chunk?: { type?: string; text?: string } } }): void {\n if (!this.serves('closing')) return;\n try {\n const frame = payload.frame;\n if (frame?.type !== 'chunk' || frame.chunk?.type !== 'text-delta') return;\n const text = frame.chunk.text ?? '';\n if (text.length === 0) return;\n const state = this.#state(agentKeyOf(payload.agent), payload.agent);\n state.claims = clip(`${state.claims}${text}`, CLAIM_CHARS);\n } catch {\n // Advisory only: a malformed frame must not disturb streaming.\n }\n }\n\n // ── capabilities ───────────────────────────────────────────────────────────\n\n /**\n * Plan, and in active mode apply, the reduction of one oversized result.\n *\n * The order of operations here *is* the safety property, so it is spelled out:\n * decide whether this payload is one the module is willing to rewrite, make sure\n * an original can be retained, buy a judgment from the shared budget, obtain the\n * real candidate, retain the original, build the replacement, check that the\n * replacement really shrank the text, and only then record a saving. Every \"no\"\n * on that path returns the downstream decision untouched, which is why an\n * unverifiable reduction can never be reported as applied.\n *\n * @param exec - the call that produced the result.\n * @param downstream - what the rest of the waterfall decided.\n * @param effective - the content the model will read (`downstream` first).\n * @param state - the deciding agent's state.\n * @param text - the effective text of that content.\n * @param started - clock reading at hook entry, for local latency.\n * @returns the decision the Host commits.\n */\n async #pruneResult(\n exec: ToolExecution,\n downstream: PostToolDecision,\n effective: readonly ContentBlock[] | undefined,\n state: AgentState,\n text: string,\n started: number\n ): Promise<PostToolDecision> {\n // The decision itself is the shared layer's (see `core/orchestrate.ts`); this\n // method only answers the questions this Host alone can answer. Everything\n // that stays here is a DSH fact: the agent's state slot, the session log\n // sink, the content-block shape, and the wording the panel shows.\n const outcome = await orchestratePrune(\n {\n callId: exec.callId,\n tool: exec.name,\n text,\n blockedByDownstream: downstream.kind === 'block',\n valueShapedAccept: 'value' in downstream && downstream.value !== undefined,\n started\n },\n {\n policy: () => this.#config,\n budget: () => state,\n // The shared base asks \"does this capability apply\" the same way for every\n // capability; for pruning the answer is the effective mode. `mode()` stays\n // because the pruning decision needs the three-valued answer, not the\n // boolean.\n serves: () => this.modeOf('prune') !== 'off' && this.#config.enabled,\n clock: () => ({ now: () => this.#now() }),\n mode: () => this.modeOf('prune'),\n threshold: () => this.#pruneThreshold,\n floor: () => ({\n floorRatio: this.config.pruneFloorRatio,\n headChars: this.config.pruneHeadChars,\n tailChars: this.config.pruneTailChars\n }),\n now: () => this.#now(),\n memoKey: () => state.sessionKey,\n memoGet: (key) => this.#memoGetByKey(key),\n memoSet: (key, entry) => this.#memoSetByKey(key, entry),\n judge: async (raw) => {\n // Both modes ask for the *real* candidate, measure-only. The service\n // writes its own ledger entry first; whether the payload is installed is\n // decided afterwards, by the floor.\n const response = await this.#decide(\n () =>\n this.#prune.prune(raw, {\n intent: this.config.intent,\n measureOnly: true,\n pruneJudgeMinChars: this.config.pruneJudgeMinChars\n }),\n (value) => value !== undefined,\n // Prune is its own account of which path produced the text, so a\n // request that was tried and failed is reported as such.\n (value) => value.judgePath === 'fallback' || value.judgePath === 'local'\n );\n return {\n processedOutput: response.processedOutput,\n reductionPercentage: response.reductionPercentage,\n shadow: response.shadow,\n latencyMs: response.latencyMs,\n diagnostics: pruneDiagnosticsOf(response)\n };\n },\n // DSH's sink names a copy after the plugin record type, and the engine\n // must predict that name or every install would be rebuilt.\n locatorOf: (digest) => pruneLocator(digest),\n hasRetention: () => this.#retain !== undefined,\n retain: (request, session) => this.#retain?.(session, request),\n session: () => sessionOf(exec.agent),\n hasTextBlock: () => hasTextBlock(effective),\n install: (installedText) => {\n const replacement = this.#replaceText(effective, installedText);\n if (!replacement) return undefined;\n return {\n kind: 'accept',\n content: replacement,\n ...(downstream.additionalContexts && downstream.additionalContexts.length > 0\n ? { additionalContexts: [...downstream.additionalContexts] }\n : {})\n } satisfies PostToolDecision;\n },\n describe: (facts) => this.#pruneFeedback(facts),\n skip: (reason, detail, judgment) =>\n this.#skip(reason, {\n capability: 'prune',\n state,\n agent: exec.agent,\n ...(Object.keys(detail).length === 0 ? {} : { detail: detail as InterventionSkipDetail }),\n ...(judgment === undefined ? {} : { judgment })\n }),\n chargeJudgment: (judgment, originalTokens) =>\n this.#charge('prune', {\n ...judgment,\n originalTokens: originalTokens ?? 0,\n candidateTokens: 0,\n potentialSavedTokens: 0,\n actualSavedTokens: 0,\n injectedTokens: 0\n }),\n conclude: (plan, applied, costs, judgment, locator) =>\n this.#conclude(plan, applied, exec.agent, costs, judgment, locator),\n noteRetained: (locator) => this.#noteRetained(locator),\n passThrough: () => downstream\n }\n );\n // No cast: the port's `Result` is this host's decision type, so the generic\n // carries it from `passThrough`/`install` all the way out.\n return outcome.result;\n }\n\n /**\n * `tools/post-execute`: rewrite a result the run keeps failing to change.\n *\n * The *order* of this decision — the failure latch, the turn's allowance, the\n * judgment and its memo, the episode latch, the booking — is\n * `orchestrateCorrection`'s. What stays here is everything the shared layer\n * cannot know:\n *\n * - **the window**: `state.steps`, recorded by this engine. It is handed over\n * *unfiltered*, unlike the stagnation windows: a failing poll is a failure\n * even though a wait is not progress, so `progressSteps` would be the wrong\n * rule on this path;\n * - **the strength of the action**: `apply` answers with a `block` carrying the\n * feedback, which replaces the result outright. That is this Host's way of\n * showing a correction; a command hook would carry the same text as context\n * next to the untouched result, and the shared layer may not pick for it;\n * - **the wording**: `describeCorrection` is the product text, and it is this\n * plugin's, not the core's — the same decision read by a different host\n * should still read naturally to that host's user.\n *\n * @param exec - the call whose result failed.\n * @param result - the canonical outcome, for its error text.\n * @param downstream - what the rest of the waterfall decided for the result.\n * @param state - the deciding agent's bookkeeping.\n * @param signature - the identity of the failure episode.\n * @param started - clock reading at hook entry, for the latency split.\n * @returns the result the Host commits.\n */\n async #correctFailure(\n exec: ToolExecution,\n result: Readonly<ToolExecutionResult>,\n downstream: PostToolDecision,\n state: AgentState,\n signature: string,\n started: number\n ): Promise<PostToolDecision> {\n const agentId = agentKeyOf(exec.agent);\n const error = this.#errorOf(result);\n const port: HostCorrectionPort<PostToolDecision> = {\n policy: () => this.#config,\n budget: () => state,\n buy: async (step) => this.#decide(() => this.#stagnation.check(step.goal, [...step.history]), (value) => value !== undefined),\n clock: () => ({ now: () => this.#now() }),\n serves: () => this.#config.enabled,\n toolName: () => exec.name,\n error: () => error,\n // Deliberately the raw window, not the progress-only one: see the doc above.\n window: () => state.steps,\n signature: () => signature,\n suspicion: (steps) =>\n suspicionOf(steps, {\n repeatThreshold: this.config.repeatThreshold,\n failureThreshold: this.config.failureThreshold,\n window: this.config.windowSize,\n signature\n }),\n alreadyCorrected: () => state.applied.has(`gate:${signature}`),\n latchCorrected: () => state.applied.add(`gate:${signature}`),\n passThrough: () => downstream,\n // This Host's strength for a correction: the result is replaced by the\n // feedback. `additionalContexts` the rest of the waterfall attached are\n // carried over, so somebody else's context is not lost to ours.\n apply: (feedback) => ({\n kind: 'block',\n feedback: [{ type: 'text', text: feedback }],\n ...(downstream.additionalContexts && downstream.additionalContexts.length > 0\n ? { additionalContexts: [...downstream.additionalContexts] }\n : {})\n }),\n describe: (facts: CorrectionFeedbackFacts) =>\n describeCorrection(facts, { errorChars: 160, adviceChars: 240, totalChars: FEEDBACK_CHARS }),\n skip: (reason, charge) =>\n this.#skip(reason, {\n capability: 'gate',\n state,\n agent: exec.agent,\n ...(charge === undefined ? {} : { judgment: charge })\n }),\n chargeJudgment: (charge: JudgedCharge) => this.#charge('gate', charge),\n conclude: (plan: CorrectionPlanRecord, applied: boolean, charge: JudgedCharge) =>\n this.#conclude(plan as InterventionPlan, applied, exec.agent, { potentialSavedTokens: 0 }, charge)\n };\n // `started` is kept in the signature because it is what the *hook* measured,\n // and the shared layer takes its own reading at the moment the judgment is\n // bought. Both read the same clock, so the latency this decision reports is\n // unchanged by the lift; the parameter stays so a later local-latency rule\n // can still see the hook's own entry time.\n void started;\n void agentId;\n const outcome = await orchestrateCorrection({ failed: true, blockedByDownstream: downstream.kind === 'block' }, port);\n return outcome.result;\n }\n\n // ── accounting and audit ───────────────────────────────────────────────────\n\n /**\n * Record one planned decision and bill its plan side.\n *\n * The judgment is passed in rather than recomputed: it was already charged\n * (or is charged here for the first time) exactly once, and it appears in the\n * audit record so one decision's full cost is readable in one place.\n *\n * Two rules keep the record honest. `injectedTokens` counts only text that was\n * *really* injected — a reduction's explanatory note is never sent to the model,\n * so reducing costs no context. And `actualSavedTokens` is the caller's\n * measurement of the payload that really left the surface, not the plan's\n * intention; `#pruneResult` passes the size of the text it actually installed.\n *\n * @param plan - what was planned.\n * @param applied - whether active mode executed it.\n * @param agent - the agent it concerns, for isolation and the audit trail.\n * @param planCosts - the payload sizes of this decision.\n * @param judgment - the judgment this decision rode on.\n * @param originalLocator - locator of the retained original, when one exists.\n */\n #conclude(\n plan: InterventionPlan,\n applied: boolean,\n agent: unknown,\n planCosts: {\n originalTokens?: number;\n candidateTokens?: number;\n potentialSavedTokens: number;\n /** Tokens really removed; defaults to the plan's own estimate. */\n actualSavedTokens?: number;\n },\n judgment?: JudgmentCharge,\n originalLocator?: string\n ): void {\n const originalTokens = planCosts.originalTokens ?? 0;\n const candidateTokens = planCosts.candidateTokens ?? 0;\n const potentialSavedTokens = planCosts.potentialSavedTokens;\n // The injection column counts text handed to the model. A deny's reason and a\n // correction's feedback are injected; a prune's note travels in the audit\n // record only, so its plan never inflates the cost of the saving it made.\n const injects = applied && plan.action !== 'prune-result';\n const injectedTokens = injects ? estimateTokens(plan.feedback) : 0;\n const actualSavedTokens =\n applied && plan.action === 'prune-result'\n ? planCosts.actualSavedTokens ?? potentialSavedTokens\n : 0;\n const charge: CostCharge = {\n ...(judgment ?? { judgments: 0, memoHits: 0, localLatencyMs: 0, remoteLatencyMs: 0, judgeTokens: 0 }),\n originalTokens,\n candidateTokens,\n potentialSavedTokens,\n actualSavedTokens,\n injectedTokens\n };\n this.#charge(plan.capability, charge, 1, applied ? 1 : 0);\n\n const record: InterventionAuditRecord = {\n capability: plan.capability,\n action: plan.action,\n mode: this.modeOf(plan.capability),\n applied,\n reason: plan.reason,\n feedback: applied ? plan.feedback : '',\n localLatencyMs: judgment?.localLatencyMs ?? 0,\n remoteLatencyMs: judgment?.remoteLatencyMs ?? 0,\n judgeTokens: judgment?.judgeTokens ?? 0,\n originalTokens,\n candidateTokens,\n potentialSavedTokens,\n actualSavedTokens,\n injectedTokens,\n at: this.#now(),\n agentId: agentKeyOf(agent),\n ...(plan.detail.pattern === undefined ? {} : { pattern: plan.detail.pattern }),\n ...(plan.detail.confidence === undefined ? {} : { confidence: plan.detail.confidence }),\n ...(plan.detail.repeats === undefined ? {} : { repeats: plan.detail.repeats }),\n ...(plan.detail.digest === undefined ? {} : { digest: plan.detail.digest }),\n ...(plan.detail.floorApplied === undefined ? {} : { floorApplied: plan.detail.floorApplied, floored: plan.detail.floorApplied }),\n ...(plan.detail.floorMissed === undefined ? {} : { floorMissed: plan.detail.floorMissed }),\n ...(plan.detail.markerOmitted ? { markerOmitted: true } : {}),\n ...(judgment?.memoHits ? { memoHit: true } : {}),\n ...(originalLocator === undefined ? {} : { originalLocator }),\n ...(plan.detail.turn === undefined ? {} : { turn: plan.detail.turn }),\n ...(plan.detail.step === undefined ? {} : { step: plan.detail.step }),\n ...(plan.detail.judgePath === undefined ? {} : { judgePath: plan.detail.judgePath }),\n ...(plan.detail.judgedSegments === undefined ? {} : { judgedSegments: plan.detail.judgedSegments }),\n ...(plan.detail.unjudgedSegments === undefined ? {} : { unjudgedSegments: plan.detail.unjudgedSegments }),\n ...(plan.detail.keptSegments === undefined ? {} : { keptSegments: plan.detail.keptSegments }),\n ...(plan.detail.aggressiveChars === undefined ? {} : { aggressiveChars: plan.detail.aggressiveChars }),\n ...(plan.detail.balancedChars === undefined ? {} : { balancedChars: plan.detail.balancedChars }),\n ...(plan.detail.conservativeChars === undefined ? {} : { conservativeChars: plan.detail.conservativeChars }),\n ...(plan.detail.scoredSegments === undefined ? {} : { scoredSegments: plan.detail.scoredSegments }),\n ...(plan.detail.autoKeptSegments === undefined ? {} : { autoKeptSegments: plan.detail.autoKeptSegments }),\n ...(plan.detail.unparsedScoreAnswers === undefined ? {} : { unparsedScoreAnswers: plan.detail.unparsedScoreAnswers }),\n ...(plan.detail.originalChars === undefined ? {} : { originalChars: plan.detail.originalChars }),\n ...(plan.detail.candidateChars === undefined ? {} : { candidateChars: plan.detail.candidateChars }),\n ...(plan.detail.fallbackReason === undefined ? {} : { fallbackReason: plan.detail.fallbackReason })\n };\n this.#recent.push(record);\n if (this.#recent.length > MAX_RECENT) this.#recent.shift();\n try {\n this.#audit?.(record, (agent as { session?: unknown } | undefined)?.session);\n } catch {\n // An audit sink is never allowed to fail a turn.\n }\n }\n\n /**\n * Bill one decision against its mode's and its capability's account.\n *\n * Every counter has exactly one writer, so a reader can add the parts up\n * without meeting a number twice.\n */\n #charge(capability: InterventionCapability, charge: CostCharge, plans = 0, applied = 0): void {\n const mode = this.modeOf(capability) === 'active' ? 'active' : 'observe';\n for (const bucket of [this.#costs[mode], this.#byCapability[capability]]) {\n applyCharge(bucket, plans, applied, charge);\n }\n }\n\n /**\n * Count one hook-level refusal by reason, and leave it in the session log.\n *\n * The counter is process-local and only answers \"what did this activation\n * skip\"; the record is the durable half, because the question a real run\n * raises is *why was nothing pruned* — and a branch that never planned\n * anything otherwise leaves no trace at all. The write is best-effort by\n * construction: no budget is charged, nothing is projected into the model's\n * context, and a sink that throws or a session that is missing leaves the\n * hook's own decision untouched.\n *\n * @param reason - the machine reason of the branch that abandoned the plan.\n * @param context - capability, deciding state, agent, and prune diagnostics.\n */\n #skip(reason: string, context: SkipContext): void {\n this.#skips.set(reason, (this.#skips.get(reason) ?? 0) + 1);\n this.#auditSkip(reason, context);\n }\n\n /** Write one abandoned plan to the audit channel, fail-open. */\n #auditSkip(reason: string, context: SkipContext): void {\n const audit = this.#audit;\n if (!audit) return;\n try {\n const detail = context.detail;\n const record: InterventionAuditRecord = {\n capability: context.capability,\n action: 'skip',\n mode: this.modeOf(context.capability),\n applied: false,\n reason,\n feedback: '',\n localLatencyMs: context.judgment?.localLatencyMs ?? 0,\n remoteLatencyMs: context.judgment?.remoteLatencyMs ?? 0,\n judgeTokens: context.judgment?.judgeTokens ?? 0,\n originalTokens: detail?.originalTokens ?? 0,\n candidateTokens: detail?.candidateTokens ?? 0,\n potentialSavedTokens: 0,\n actualSavedTokens: 0,\n injectedTokens: 0,\n at: this.#now(),\n skip: reason,\n ...(context.state === undefined ? {} : { turn: context.state.turn, step: context.state.step }),\n ...(detail?.digest === undefined ? {} : { digest: detail.digest }),\n ...(detail?.floored === undefined ? {} : { floored: detail.floored }),\n ...(detail?.floorMissed === undefined ? {} : { floorMissed: detail.floorMissed }),\n ...(detail?.markerOmitted ? { markerOmitted: true } : {}),\n ...(detail?.judgePath === undefined ? {} : { judgePath: detail.judgePath }),\n ...(detail?.judgedSegments === undefined ? {} : { judgedSegments: detail.judgedSegments }),\n ...(detail?.unjudgedSegments === undefined ? {} : { unjudgedSegments: detail.unjudgedSegments }),\n ...(detail?.keptSegments === undefined ? {} : { keptSegments: detail.keptSegments }),\n ...(detail?.aggressiveChars === undefined ? {} : { aggressiveChars: detail.aggressiveChars }),\n ...(detail?.balancedChars === undefined ? {} : { balancedChars: detail.balancedChars }),\n ...(detail?.conservativeChars === undefined ? {} : { conservativeChars: detail.conservativeChars }),\n ...(detail?.scoredSegments === undefined ? {} : { scoredSegments: detail.scoredSegments }),\n ...(detail?.autoKeptSegments === undefined ? {} : { autoKeptSegments: detail.autoKeptSegments }),\n ...(detail?.unparsedScoreAnswers === undefined ? {} : { unparsedScoreAnswers: detail.unparsedScoreAnswers }),\n ...(detail?.originalChars === undefined ? {} : { originalChars: detail.originalChars }),\n ...(detail?.candidateChars === undefined ? {} : { candidateChars: detail.candidateChars }),\n ...(detail?.fallbackReason === undefined ? {} : { fallbackReason: detail.fallbackReason })\n };\n audit(record, sessionOf(context.agent));\n } catch {\n // An audit sink is never allowed to fail a turn, and a skip is reported\n // even when the log refused it: the counter above is already committed.\n }\n }\n\n // ── state ─────────────────────────────────────────────────────────────────\n\n /** One agent's state, created on first sight and bounded overall. */\n #state(agentId: string, agent?: unknown): AgentState {\n const sessionKey = sessionKeyOf(agent);\n const existing = this.#states.get(agentId);\n if (existing && existing.sessionKey === sessionKey) {\n this.#states.delete(agentId);\n this.#states.set(agentId, existing);\n return existing;\n }\n // A new session for the same agent id is a new run: no window, verdict,\n // budget, or memoized reduction of the old one may leak into it.\n if (existing) this.#memoForget(existing.sessionKey);\n const state: AgentState = {\n sessionKey,\n turn: 0,\n step: 0,\n steps: [],\n claims: '',\n evidence: [],\n evidenceSuspect: false,\n interventions: 0,\n judgmentsTurn: 0,\n judgmentsCount: 0,\n judgmentsSession: 0,\n verdictTurn: 0,\n verdictKey: '',\n waited: new Set<string>(),\n applied: new Set<string>(),\n denied: new Set<string>(),\n refused: new Set<string>()\n };\n this.#states.set(agentId, state);\n if (this.#states.size > MAX_AGENTS) {\n const oldest = this.#states.keys().next().value;\n if (typeof oldest === 'string' && oldest !== agentId) this.#states.delete(oldest);\n }\n return state;\n }\n\n /**\n * The step a call about to run would add, without committing it.\n * @param state - the agent's bookkeeping.\n * @param exec - the proposed call.\n * @param signature - its identity.\n * @returns the step the result path will record once the call completes.\n */\n #observed(state: AgentState, exec: ToolExecution, signature: string): ObservedStep {\n return {\n signature,\n tool: exec.name,\n input: clip(this.#argumentsOf(exec), STEP_CHARS),\n output: '',\n error: '',\n // The call about to run is a retry exactly when this identity failed before.\n failed: state.steps.some((step) => step.signature === signature && step.failed),\n turn: state.turn,\n at: this.#now()\n };\n }\n\n /** Append one observed step, bounded. */\n #observe(state: AgentState, step: ObservedStep): void {\n state.steps.push(step);\n if (state.steps.length > MAX_STEPS) state.steps.shift();\n }\n\n /**\n * Retain one result's evidence candidates for the closing check.\n *\n * Called for every observed result, not only structurally failing ones: a\n * `{ok:false}`, a timeout, or a Chinese error has no exit code to prove it,\n * and the closing judgment must be able to see it. The regex only guarantees\n * that its own hits survive; it never decides that the rest is benign.\n * @param state - the agent's bookkeeping.\n * @param tool - tool name that produced the result.\n * @param result - the execution-local result.\n * @param text - the effective model-facing text.\n * @param error - the result's error message, when it has a distinct one.\n */\n #rememberEvidence(\n state: AgentState,\n tool: string,\n result: Readonly<ToolExecutionResult>,\n text: string,\n error: string\n ): void {\n const haystack = error.length > 0 && !text.includes(error) ? `${text}\\n${error}` : text;\n const entries = evidenceOf(tool, result, haystack);\n if (entries.length === 0) return;\n state.evidence.push(...entries);\n if (state.evidence.length > MAX_EVIDENCE) {\n state.evidence.splice(0, state.evidence.length - MAX_EVIDENCE);\n }\n if (entries.some((entry) => entry.suspect)) state.evidenceSuspect = true;\n }\n\n /** The arguments of one call, as the text a judgment and a digest see. */\n #argumentsOf(exec: ToolExecution): string {\n const args: unknown = exec.arguments;\n if (typeof args === 'string') return args;\n try {\n return JSON.stringify(args ?? {}) ?? '';\n } catch {\n return '';\n }\n }\n\n /** The failure text of one result. */\n #errorOf(result: Readonly<ToolExecutionResult>): string {\n const failure = (result as { error?: { message?: string } }).error;\n if (failure && typeof failure.message === 'string' && failure.message.length > 0) return failure.message;\n return textOfContent(result.content);\n }\n\n /** Replace the text blocks of one content list, preserving every other block. */\n #replaceText(content: readonly ContentBlock[] | undefined, text: string): ContentBlock[] | undefined {\n if (!content) return undefined;\n const out: ContentBlock[] = [];\n let placed = false;\n for (const block of content) {\n if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') {\n if (!placed) {\n out.push({ type: 'text', text } as ContentBlock);\n placed = true;\n }\n continue;\n }\n out.push(block);\n }\n return placed ? out : undefined;\n }\n\n /**\n * The explanatory note of one reduction.\n *\n * It travels in the audit record, never in the model's context: a prune is\n * supposed to *remove* context, so sending an explanation of the removal would\n * work against the thing it is accounting for.\n *\n * The wording follows the data: \"kept whole\" is only said when the judgment\n * really kept every segment it judged. A candidate that was floored says the\n * head/extract/tail form it carries, and a floor miss says how many segments\n * survived, how many were omitted, and that the promised share was not reached\n * — plus where the full payload can be read back, marker or no marker.\n *\n * @param tool - name of the reduced call.\n * @param originalTokens - tokens of the raw payload.\n * @param candidateTokens - tokens of the text really installed.\n * @param outcome - the floor's decision and the judgment's segment counts.\n * @returns the note, clipped to the audit's text budget.\n */\n #pruneFeedback(facts: PruneFeedbackFacts): string {\n const { tool, originalTokens, candidateTokens, ...outcome } = facts;\n const kept = originalTokens === 0 ? 100 : Math.round((candidateTokens / originalTokens) * 100);\n const head = `Reflex reduced ${tool}: ${originalTokens} → ${candidateTokens} tokens (${kept}% kept). `;\n const keptSegments = outcome.keptSegments;\n const judgedSegments = outcome.judgedSegments;\n const segmentsShort =\n keptSegments !== undefined && judgedSegments !== undefined && keptSegments < judgedSegments;\n const segmentNote = segmentsShort\n ? `Kept ${keptSegments}/${judgedSegments} segments, omitted ${judgedSegments - keptSegments}. `\n : '';\n let body: string;\n if (outcome.floored) {\n body =\n 'The head, the judged extract and the tail were kept; ' +\n `the full output was retained in this session's log and is not in context.`;\n } else if (outcome.floorMissed) {\n const floorPercent = Math.round(this.config.pruneFloorRatio * 100);\n const install =\n outcome.markerOmitted\n ? 'no locator marker was added because it would not have kept the text smaller than the original'\n : 'the judged extract was installed as-is';\n body = `${segmentNote}The candidate fell short of the ${floorPercent}% floor, so ${install}; ` +\n `the full output is retrievable as ${outcome.locator}.`;\n } else if (segmentsShort) {\n body = `${segmentNote}The judged extract was installed as-is; ` +\n `the full output is retrievable as ${outcome.locator}.`;\n } else {\n body =\n 'The judged extract was kept whole; ' +\n `the full output was retained in this session's log and is not in context.`;\n }\n return clip(`${head}${body}`, FEEDBACK_CHARS);\n }\n\n /**\n * Count one retained copy for the panel, once per payload.\n *\n * A duplicate install reuses the copy that is already in the log, so the\n * locator naming it never changes and the recent list keeps one entry.\n * @param locator - the locator the replacement published.\n */\n #noteRetained(locator: string): void {\n if (!this.#retained.includes(locator)) {\n this.#retained.push(locator);\n if (this.#retained.length > MAX_RECENT) this.#retained.shift();\n }\n this.#retainedCopies += 1;\n }\n\n /** The memoized reduction under one already-namespaced key, when remembered. */\n #memoGetByKey(key: string): PruneMemo | undefined {\n const hit = this.#memo.get(key);\n if (!hit) return undefined;\n this.#memo.delete(key);\n this.#memo.set(key, hit);\n return hit;\n }\n\n /**\n * Remember one payload's reduction, bounded by least recent use.\n *\n * The entry records the *plan* — the sizes both modes report — and, once a mode\n * really computed it, the reduction's text. Observe never has that text (the\n * shadow service withholds it and reports only its size) and never pretends to:\n * a later active decision re-plans that payload for real instead of installing a\n * cached fragment it never saw.\n */\n #memoSetByKey(key: string, memo: PruneMemo): void {\n this.#memo.set(key, memo);\n if (this.#memo.size > MAX_MEMO) {\n const oldest = this.#memo.keys().next().value;\n if (typeof oldest === 'string') this.#memo.delete(oldest);\n }\n }\n\n /** Drop the memo entries of one session, so a replaced run leaves nothing behind. */\n #memoForget(sessionKey: string): void {\n const prefix = `${sessionKey}:`;\n for (const key of [...this.#memo.keys()]) {\n if (key.startsWith(prefix)) this.#memo.delete(key);\n }\n }\n\n /** Build one model-facing message, attributed to this plugin. */\n #message(agentId: string, turn: number, step: number, text: string): UserMessage {\n this.#counter += 1;\n const summary = boundContextSummary(text.replace(/\\s+/g, ' ').trim());\n return {\n id: MessageId(`reflex-intervention-${agentId}-${turn}-${step}-${this.#counter}`),\n role: 'user',\n content: [{ type: 'text', text }],\n source: { kind: INTERVENTION_SOURCE_KIND, form: 'notice', summary }\n };\n }\n\n /** Steer one message into an agent's inbox, when the agent can receive it. */\n #steer(agent: unknown, message: UserMessage): void {\n const steer = (agent as { steer?: (message: UserMessage) => void } | undefined)?.steer;\n if (typeof steer !== 'function') return;\n steer.call(agent, message);\n }\n\n /** The refusal text handed to the model when a repeated call is denied. */\n #denyFeedback(tool: string, suspicion: StagnationSuspicion, verdict: StagnationCheckResponse): string {\n const advice = clip((verdict.recommendedIntervention ?? '').replace(/\\s+/g, ' ').trim(), 240);\n return clip(\n `Reflex intervention: ${tool} was called with identical arguments ${suspicion.repeats} times in this turn and System 1 confirms ` +\n `${verdict.patternType ?? suspicion.pattern} stagnation (confidence ${verdict.confidence.toFixed(2)}). The call was not executed. ` +\n `Change the approach: ${advice || 'use different arguments or a different tool, and inspect the previous result before retrying.'}`,\n FEEDBACK_CHARS\n );\n }\n\n /** The corrective context attached to the step after a repeated loop. */\n #contextFeedback(suspicion: StagnationSuspicion, verdict: StagnationCheckResponse): string {\n const advice = clip((verdict.recommendedIntervention ?? '').replace(/\\s+/g, ' ').trim(), 240);\n return clip(\n `Reflex intervention: the last steps repeated the same call ${suspicion.repeats} times (System 1: ${verdict.patternType ?? suspicion.pattern}, ` +\n `confidence ${verdict.confidence.toFixed(2)}). Stop the loop and change strategy: ` +\n `${advice || 're-read the last failure, then either fix the cause or try a different tool.'}`,\n FEEDBACK_CHARS\n );\n }\n\n /** The objection steered into a turn that is closing on contradicted evidence. */\n #closingFeedback(contradicted: readonly string[]): string {\n return clip(\n `Reflex closing check: this turn is about to close while its own tool results carry failures that contradict what it claims ` +\n `(${contradicted.map((item) => `\"${item}\"`).join('; ')}). Before concluding, either fix the failing evidence or state the failure ` +\n `plainly instead of the completion claim.`,\n FEEDBACK_CHARS\n );\n }\n}\n\n/** The installer's product: the detachers, the engine behind them, and live reconfiguration. */\nexport interface InterventionInstallation {\n /** Detachers of every currently registered listener, in registration order. */\n disposers: Array<() => void>;\n /** The engine the listeners drive, for the panel and for tests. */\n engine: InterventionEngine;\n /**\n * Apply a freshly resolved intervention policy without a remount.\n *\n * Thresholds are swapped on the engine and the listener set is reconciled with\n * the new effective modes: a capability turned `off` loses its hooks (zero\n * listeners and zero per-call overhead), one turned back on gets them again.\n * The engine's per-agent turn state is deliberately preserved, so a settings\n * save in the middle of a turn does not restart that turn's counters.\n * @param config - freshly resolved `interventions` block.\n * @param pruneThreshold - freshly resolved top-level prune threshold.\n * @param ownTools - freshly resolved `reflex_*` names, so a prefix rename\n * keeps the plugin's own output out of its own judgments.\n */\n reconfigure(config: ResolvedInterventionsConfig, pruneThreshold: number, ownTools?: readonly string[]): void;\n /** The number of listeners currently attached (0 when every capability is off). */\n readonly listenerCount: number;\n /** Detach every listener; idempotent. */\n dispose(): void;\n}\n\n/**\n * Install the automatic interventions of one activation.\n *\n * Registration itself is mode-aware: a capability in `off` gets no listener at\n * all, so \"off\" is the absence of the feature rather than a flag every hook has\n * to remember to check. A Host missing one of these hooks is tolerated: the\n * registration is guarded, so a stripped-down embedder loses one capability\n * instead of failing to load.\n *\n * The set is reconciled at install *and* on every config-only save, because the\n * loader commits the new volatile values into the running activation instead of\n * remounting it: {@link InterventionInstallation.reconfigure} adds the hooks a\n * newly enabled capability needs and removes those of a capability switched off.\n *\n * What is *not* per-capability is the turn frame. One turn has one lifecycle\n * whatever combination of capabilities is enabled: `agent/pre-step` opens it —\n * the turn's counters, its step number, and its stale latches — and\n * `agent/disposed` closes it. A prune-only deployment used to get neither, so its\n * first result was counted against turn 0, its intervention cap never reset, and\n * nothing was disposed. Registering the frame once for every enabled capability is\n * what makes the budget a per-turn budget rather than an accident of which\n * capability happened to be on.\n *\n * @param ctx - registrant context.\n * @param options - engine options, including the audit sink.\n * @returns the detachers, the engine, and the live reconfiguration seam.\n */\nexport function installInterventions(ctx: Context, options: InterventionEngineOptions): InterventionInstallation {\n const engine = new InterventionEngine(options);\n const disposers: Array<() => void> = [];\n /** Attached hook groups, keyed by the capability set they serve. */\n const groups = new Map<'frame' | 'pipeline' | 'closing', Array<() => void>>();\n let disposed = false;\n\n /**\n * Register every hook of one group, tolerating a Host without that hook.\n * @param group - the group to attach.\n */\n const attach = (group: 'frame' | 'pipeline' | 'closing'): void => {\n if (groups.has(group)) return;\n const detachers: Array<() => void> = [];\n const guard = (register: () => unknown): void => {\n try {\n const detach = register();\n if (typeof detach === 'function') {\n const fn = detach as unknown as () => void;\n detachers.push(fn);\n disposers.push(fn);\n }\n } catch {\n // A Host without the hook simply does not get that intervention.\n }\n };\n\n if (group === 'frame') {\n // ── the turn frame, shared by every capability that acts inside a turn ──\n guard(() => ctx.on('agent/pre-step', (payload, next) => engine.preStep(payload, next)));\n guard(() =>\n ctx.on('agent/disposed', (payload) => {\n engine.forget(agentKeyOf(payload));\n })\n );\n } else if (group === 'pipeline') {\n // ── the result pipeline: stagnation evidence, pruning, failure evidence ─\n // Every capability reads this pipeline: stagnation needs the recorded\n // calls, pruning needs the payloads, the gate needs the failures, and the\n // closing check needs the failing evidence of the turn.\n guard(() => ctx.on('tools/pre-execute', (exec, next) => engine.toolCall(exec, next)));\n guard(() => ctx.on('tools/post-execute', (exec, result, next) => engine.toolResult(exec, result, next)));\n } else {\n // ── the closing check's own inputs and its turn boundary ────────────────\n guard(() => ctx.on('agent/turn-stopping', (payload) => engine.turnStopping(payload)));\n guard(() =>\n ctx.on('agent/assistant-stream', (payload) => {\n engine.observeAssistantStream(payload);\n })\n );\n }\n groups.set(group, detachers);\n };\n\n /**\n * Detach one group and drop its entries from the public detacher list.\n * @param group - the group to detach.\n */\n const detach = (group: 'frame' | 'pipeline' | 'closing'): void => {\n const detachers = groups.get(group);\n if (!detachers) return;\n groups.delete(group);\n for (const dispose of detachers.reverse()) {\n dispose();\n const index = disposers.lastIndexOf(dispose);\n if (index >= 0) disposers.splice(index, 1);\n }\n };\n\n /**\n * Reconcile the attached listeners with the effective capability modes.\n */\n const sync = (): void => {\n if (disposed) return;\n const wanted = new Set<'frame' | 'pipeline' | 'closing'>();\n if (engine.enabled) {\n wanted.add('frame');\n // The result pipeline feeds every capability; it is present whenever any\n // of them is, exactly as it was before the live path existed.\n wanted.add('pipeline');\n if (engine.serves('closing')) wanted.add('closing');\n }\n for (const group of ['closing', 'pipeline', 'frame'] as const) {\n if (!wanted.has(group)) detach(group);\n }\n for (const group of ['frame', 'pipeline', 'closing'] as const) {\n if (wanted.has(group)) attach(group);\n }\n };\n\n sync();\n\n return {\n disposers,\n engine,\n reconfigure(config: ResolvedInterventionsConfig, pruneThreshold: number, ownTools?: readonly string[]): void {\n if (disposed) return;\n engine.updatePolicy(config, pruneThreshold, ownTools);\n sync();\n },\n get listenerCount(): number {\n return disposers.length;\n },\n dispose(): void {\n if (disposed) return;\n disposed = true;\n detach('closing');\n detach('pipeline');\n detach('frame');\n }\n };\n}\n\n/**\n * The isolation key of one agent, tolerating a disposal payload that wraps it.\n * @param value - an agent, or a payload carrying one.\n * @returns its key; `anonymous` when no identity is available.\n */\nexport function agentKeyOf(value: unknown): string {\n const direct = value as { id?: unknown } | undefined;\n if (typeof direct?.id === 'string' && direct.id.length > 0) return direct.id;\n const wrapped = (value as { agent?: { id?: unknown } } | undefined)?.agent;\n if (typeof wrapped?.id === 'string' && wrapped.id.length > 0) return wrapped.id;\n return 'anonymous';\n}\n\n/**\n * The session one agent decides in.\n * @param value - an agent, or a payload carrying one.\n * @returns the session object, or `undefined` when the agent has none.\n */\nexport function sessionOf(value: unknown): unknown {\n const agent = (value as { agent?: unknown } | undefined)?.agent ?? value;\n const session = (agent as { session?: unknown } | undefined)?.session;\n return session && typeof session === 'object' ? session : undefined;\n}\n\n/**\n * The identity of the session one agent decides in.\n *\n * A memo of reductions is only valid inside the run that produced it: the same\n * agent id in a resumed or forked session is a different log, with different\n * retained originals behind the same payload digests. Keying by the session —\n * and falling back to the agent itself when no session is visible — is what keeps\n * one run's cached reduction from being installed into another run.\n * @param value - an agent, or a payload carrying one.\n * @returns the session identity, or the agent's own key when it has none.\n */\nexport function sessionKeyOf(value: unknown): string {\n const session = sessionOf(value) as { id?: unknown } | undefined;\n return typeof session?.id === 'string' && session.id.length > 0 ? session.id : `agent:${agentKeyOf(value)}`;\n}\n\n/** The identity a repeated call is measured on: its name and its arguments. */\nfunction callSignature(exec: ToolExecution): string {\n let args: string;\n const raw: unknown = exec.arguments;\n if (typeof raw === 'string') args = raw;\n else {\n try {\n args = JSON.stringify(raw ?? {}) ?? '';\n } catch {\n args = '';\n }\n }\n return `${exec.name}:${digestOf(args)}`;\n}\n\n/** The percentage one reduction reports, at the shared token rate. */\nfunction reductionPercentage(originalChars: number, prunedChars: number): number {\n return originalChars === 0 ? 0 : Math.round(((originalChars - prunedChars) / originalChars) * 1000) / 10;\n}\n\n\n// Re-exported so a Host attaching the session log does not have to import the\n// audit module directly.\nexport { appendInterventionRecord };\n"]}