open-multi-agent-kit 0.90.4 → 0.90.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +8 -8
- package/dist/core/adaptorch-bridge.d.ts +14 -21
- package/dist/core/adaptorch-bridge.d.ts.map +1 -1
- package/dist/core/adaptorch-bridge.js +11 -18
- package/dist/core/adaptorch-bridge.js.map +1 -1
- package/dist/core/agent-session.d.ts +6 -39
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +7 -99
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
- package/dist/core/context-budget-v2-planner.js +10 -2
- package/dist/core/context-budget-v2-planner.js.map +1 -1
- package/dist/core/context-budget-v2-types.d.ts +7 -1
- package/dist/core/context-budget-v2-types.d.ts.map +1 -1
- package/dist/core/context-budget-v2-types.js.map +1 -1
- package/dist/core/reasoning-router-bias.d.ts +11 -23
- package/dist/core/reasoning-router-bias.d.ts.map +1 -1
- package/dist/core/reasoning-router-bias.js +9 -18
- package/dist/core/reasoning-router-bias.js.map +1 -1
- package/dist/core/reasoning-router-resolver.d.ts +44 -0
- package/dist/core/reasoning-router-resolver.d.ts.map +1 -0
- package/dist/core/reasoning-router-resolver.js +79 -0
- package/dist/core/reasoning-router-resolver.js.map +1 -0
- package/dist/core/reasoning-router-v4-weights.d.ts +28 -72
- package/dist/core/reasoning-router-v4-weights.d.ts.map +1 -1
- package/dist/core/reasoning-router-v4-weights.js +16 -60
- package/dist/core/reasoning-router-v4-weights.js.map +1 -1
- package/dist/core/reasoning-router-v4.d.ts +25 -70
- package/dist/core/reasoning-router-v4.d.ts.map +1 -1
- package/dist/core/reasoning-router-v4.js +46 -144
- package/dist/core/reasoning-router-v4.js.map +1 -1
- package/dist/core/router-feedback-collector.d.ts +13 -16
- package/dist/core/router-feedback-collector.d.ts.map +1 -1
- package/dist/core/router-feedback-collector.js +5 -8
- package/dist/core/router-feedback-collector.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +16 -98
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/docs/usage.md +11 -12
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/subagent/agent-capability-router.test.ts +123 -0
- package/examples/extensions/subagent/agent-capability-router.ts +274 -0
- package/examples/extensions/subagent/agents/planner.md +3 -0
- package/examples/extensions/subagent/agents/reviewer.md +3 -0
- package/examples/extensions/subagent/agents/scout.md +3 -0
- package/examples/extensions/subagent/agents/worker.md +2 -0
- package/examples/extensions/subagent/agents.ts +14 -0
- package/examples/extensions/subagent/capabilities.ts +368 -0
- package/examples/extensions/subagent/domain-profiles.ts +1089 -0
- package/examples/extensions/subagent/index.ts +71 -3
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
- package/dist/core/compactor.d.ts +0 -42
- package/dist/core/compactor.d.ts.map +0 -1
- package/dist/core/compactor.js +0 -128
- package/dist/core/compactor.js.map +0 -1
- package/dist/core/reasoning-router-v2.d.ts +0 -94
- package/dist/core/reasoning-router-v2.d.ts.map +0 -1
- package/dist/core/reasoning-router-v2.js +0 -288
- package/dist/core/reasoning-router-v2.js.map +0 -1
- package/dist/core/reasoning-router-v3.d.ts +0 -15
- package/dist/core/reasoning-router-v3.d.ts.map +0 -1
- package/dist/core/reasoning-router-v3.js +0 -193
- package/dist/core/reasoning-router-v3.js.map +0 -1
- package/dist/core/reasoning-router-weights.d.ts +0 -155
- package/dist/core/reasoning-router-weights.d.ts.map +0 -1
- package/dist/core/reasoning-router-weights.js +0 -204
- package/dist/core/reasoning-router-weights.js.map +0 -1
- package/dist/core/reasoning-router.d.ts +0 -44
- package/dist/core/reasoning-router.d.ts.map +0 -1
- package/dist/core/reasoning-router.js +0 -138
- package/dist/core/reasoning-router.js.map +0 -1
- package/dist/core/token-optimizer.d.ts +0 -58
- package/dist/core/token-optimizer.d.ts.map +0 -1
- package/dist/core/token-optimizer.js +0 -179
- package/dist/core/token-optimizer.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.90.5] - 2026-07-07
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Added `reasoning-router-resolver.ts` as the shared thinking-level resolver core for the v4 reasoning router, centralizing `resolveThinkingLevelCore`, `TASK_CLASS_THINKING_LEVELS`, lane-step adjustment, bounded bias/hint fusion, confidence escalation, and available-level clamping.
|
|
10
|
+
- Added deterministic capability routing to the subagent example extension, including catalog-backed capability parsing and validation, domain-profile derivation, assigned-capability preambles for bundled agents, optional skill enforcement, unit coverage, the read-only `scripts/derive-agent-capabilities.mjs` classify/audit CLI, and the `scripts/check-agent-capabilities.mjs` live-catalog guard.
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- Collapsed automatic reasoning-effort routing to a single `/think auto` backed by the v4 confidence-bearing router. The `/think auto-v1`, `/think auto-v2`, `/think auto-v3`, and `/think auto-v4` variants (plus their `auto vN` / `auto:vN` forms) are removed, and `/think auto` now routes via v4 instead of the former v1 classifier; those variants were opt-in experimental surface introduced in 0.90.4. Manual `/think <level>` still always takes precedence.
|
|
15
|
+
- Changed context-budget v2 observability to inline the legacy token-optimizer compatibility status in the planner/types instead of importing the removed optimizer module; telemetry still reports `optimizer_id="legacy-token-optimizer"`, `status="quarantined_compatibility"`, and `active_context_budget_optimizer="context-budget-v2"`.
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- Fixed v4 reasoning-router misclassification of real-world, out-of-gold-set phrasing by extending the keyword families with vocabulary the classifier previously had no signal for: review (`sanity-check`, `once-over`, `eyeball`), refactor (`tidy up`), plan (`map out`, `phases`, and Korean `계획 … 세워` with an intervening particle), debug (`track down`, `leak`), plus a narrow negation-aware review cue. An out-of-vocabulary adversarial probe improves from 22/30 to 30/30 while the frozen gold-set holdout and full set stay at 100%, guarded by the new `016-reasoning-router-v4-generalization` regression test.
|
|
20
|
+
|
|
21
|
+
### Removed
|
|
22
|
+
|
|
23
|
+
- Removed the v1, v2, and v3 reasoning-router modules (`reasoning-router.ts`, `reasoning-router-v2.ts`, `reasoning-router-v3.ts`, `reasoning-router-weights.ts`), their regression suites (`003`-`007`), and the v3 calibration script; only the v4 router remains, reachable via `/think auto`.
|
|
24
|
+
- Removed the unused `compactor.ts` module.
|
|
25
|
+
- Removed the legacy `token-optimizer.ts` runtime module and its dedicated test while retaining fixed compatibility telemetry in context-budget v2.
|
|
26
|
+
|
|
5
27
|
## [0.90.4] - 2026-07-04
|
|
6
28
|
|
|
7
29
|
### Added
|
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
<p align="center">
|
|
16
16
|
<a href="https://discord.com/invite/3cU7Bz4UPx"><img alt="Discord" src="https://img.shields.io/badge/discord-community-5865F2?style=flat-square&logo=discord&logoColor=white" /></a>
|
|
17
17
|
<a href="https://www.npmjs.com/package/open-multi-agent-kit"><img alt="npm" src="https://img.shields.io/npm/v/open-multi-agent-kit?style=flat-square" /></a>
|
|
18
|
-
<a href="https://github.com/dmae97/open-multi-agent-kit/releases/tag/v0.90.
|
|
18
|
+
<a href="https://github.com/dmae97/open-multi-agent-kit/releases/tag/v0.90.5"><img alt="Release" src="https://img.shields.io/badge/release-v0.90.5-00d7ff?style=flat-square" /></a>
|
|
19
19
|
</p>
|
|
20
20
|
|
|
21
21
|
> New issues and PRs from new contributors are auto-closed by default. Maintainers review auto-closed issues daily. See [CONTRIBUTING.md](https://github.com/dmae97/open-multi-agent-kit/blob/v0.90.4/CONTRIBUTING.md).
|
|
@@ -32,19 +32,19 @@ The OMK//CONTROL startup surface is the default operator view. The header reads
|
|
|
32
32
|
|
|
33
33
|
The default dark TUI theme uses the `omk-control-grid-dark` Night City palette and keeps the control sidebar focused on route, evidence, loop, MCP, runtime, skills, and context budget state.
|
|
34
34
|
|
|
35
|
-
## Release v0.90.
|
|
35
|
+
## Release v0.90.5
|
|
36
36
|
|
|
37
|
-
This release
|
|
37
|
+
This release collapses automatic reasoning routing to a single `/think auto` backed by the v4 confidence-bearing router, improves v4 real-world routing accuracy, and removes the legacy v1/v2/v3 routers and unused compaction modules.
|
|
38
38
|
|
|
39
39
|
| Area | What changed |
|
|
40
40
|
|------|--------------|
|
|
41
|
-
| Reasoning |
|
|
42
|
-
|
|
|
43
|
-
|
|
|
44
|
-
|
|
|
41
|
+
| Reasoning | Collapsed automatic reasoning-effort routing to a single `/think auto` backed by the v4 router; the `/think auto-v1/-v2/-v3/-v4` variants and the v1/v2/v3 routers are removed. Manual `/think <level>` still always takes precedence. |
|
|
42
|
+
| Accuracy | Extended the v4 keyword families (review/refactor/plan/debug vocabulary, Korean plan phrasing, negation-aware review) so real-world, out-of-gold-set prompts route correctly; an out-of-vocabulary probe improves from 22/30 to 30/30 while the frozen gold-set holdout and full set stay at 100%. |
|
|
43
|
+
| Internals | Consolidated the shared thinking-level resolver into `reasoning-router-resolver.ts` and removed the unused `compactor.ts` and legacy `token-optimizer.ts` modules, inlining compatibility telemetry in context-budget v2. |
|
|
44
|
+
| Subagent example | Added a deterministic capability router to the subagent example extension plus read-only `derive`/`check` capability scripts. |
|
|
45
45
|
| Pi+OMK | Shoutout to the Pi+OMK root-coordinator flow: DAG lanes, scoped grants, evidence, and verification stayed in the loop for this release. |
|
|
46
46
|
|
|
47
|
-
GitHub-focused release notes live in [RELEASE_NOTES_v0.90.
|
|
47
|
+
GitHub-focused release notes live in [RELEASE_NOTES_v0.90.5.md](https://github.com/dmae97/open-multi-agent-kit/blob/v0.90.5/.github/RELEASE_NOTES_v0.90.5.md). The GitHub release workflow also extracts the canonical release body from [packages/coding-agent/CHANGELOG.md](https://github.com/dmae97/open-multi-agent-kit/blob/v0.90.5/packages/coding-agent/CHANGELOG.md).
|
|
48
48
|
|
|
49
49
|
OMK is a minimal terminal coding harness. Adapt omk to your workflows, not the other way around, without having to fork and modify omk internals. Extend it with TypeScript [Extensions](#extensions), [Skills](#skills), [Prompt Templates](#prompt-templates), and [Themes](#themes). Put your extensions, skills, prompt templates, and themes in [OMK Packages](#omk-packages) and share them with others via npm or git.
|
|
50
50
|
|
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Reasoning-router AdaptOrch advisory bridge (Goal 009 Lane B).
|
|
3
3
|
*
|
|
4
|
-
* A default-off, advisory-only primitive for a future
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* this module from agent-session.ts.
|
|
4
|
+
* A default-off, advisory-only primitive for a future reasoning-router hint
|
|
5
|
+
* source. This module is intentionally NOT wired into agent-session.ts; it only
|
|
6
|
+
* implements the bridge's payload/result schema, sanitize/validate helpers, TTL
|
|
7
|
+
* cache, budget counter, circuit breaker, and timeout wrapper around a
|
|
8
|
+
* caller-injected advisory function. A future lane decides how (or whether) to
|
|
9
|
+
* fuse a returned hint into a resolved ThinkingLevel and to actually call this
|
|
10
|
+
* module from agent-session.ts.
|
|
12
11
|
*
|
|
13
12
|
* Grounded in the read-first plan at
|
|
14
13
|
* .omk/goals/008-reasoning-router-advanced-accuracy-plan/laneC-privacy-adaptorch.md
|
|
@@ -27,16 +26,10 @@
|
|
|
27
26
|
* `taskClass` and a `confidenceBand` - both closed enums - never a raw
|
|
28
27
|
* numeric confidence or a `ThinkingLevel` value. Fusing a hint into a
|
|
29
28
|
* resolved level is out of scope for this module.
|
|
30
|
-
* - No product source
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
* import, so this lane's narrow write scope (this file, its regression
|
|
35
|
-
* test, and its evidence file only) cannot be affected by - or affect -
|
|
36
|
-
* any concurrently-running Wave 1 lane's edits to the router modules. A
|
|
37
|
-
* future wiring lane should keep these enums in sync (or replace the
|
|
38
|
-
* local copies with a shared import) once it deliberately connects this
|
|
39
|
-
* bridge to the router.
|
|
29
|
+
* - No product source is imported here. `AdaptorchTaskClass` /
|
|
30
|
+
* `AdaptorchLaneType` intentionally mirror the v4 task/lane unions by
|
|
31
|
+
* value, not by import, so this bridge remains isolated until a future
|
|
32
|
+
* wiring lane deliberately connects it to the router.
|
|
40
33
|
* - Every outbound/inbound field is a closed enum, a boolean, or a bounded
|
|
41
34
|
* integer, derived from local features only. There is structurally no
|
|
42
35
|
* field shaped to carry prompt text, a prompt hash, a file/working-
|
|
@@ -56,15 +49,15 @@
|
|
|
56
49
|
* Pure aside from `Date.now`/`setTimeout` (both injectable/wrapped so tests
|
|
57
50
|
* never depend on real wall-clock time or a real MCP call).
|
|
58
51
|
*/
|
|
59
|
-
/** Closed set of task classes. Mirrors
|
|
52
|
+
/** Closed set of task classes. Mirrors the v4 task-class union by value (see file header). */
|
|
60
53
|
export type AdaptorchTaskClass = "trivial" | "simple-edit" | "code-gen" | "debug" | "refactor" | "review" | "plan";
|
|
61
|
-
/** Closed set of subagent lane types. Mirrors
|
|
54
|
+
/** Closed set of subagent lane types. Mirrors the v4 lane union by value. */
|
|
62
55
|
export type AdaptorchLaneType = "planner" | "security" | "explorer" | "coder" | "reviewer" | "tester";
|
|
63
56
|
/** Local top1-vs-runner-up score-margin bucket (plan 4.5 ConsultPayloadV1.marginBucket). */
|
|
64
57
|
export type AdaptorchMarginBucket = "tie" | "low" | "medium" | "high";
|
|
65
58
|
/** Locally-derived confidence band for a returned hint. Never a raw network-supplied float (plan 4.3). */
|
|
66
59
|
export type AdaptorchConfidenceBand = "low" | "medium" | "high";
|
|
67
|
-
/** floor(log2(trimmedPromptLen+1)) clamped to [0,7]
|
|
60
|
+
/** floor(log2(trimmedPromptLen+1)) clamped to [0,7]. */
|
|
68
61
|
export type AdaptorchLenBucket = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
|
|
69
62
|
/** Context-pressure band 0..3 - same bucketing as agent-session.ts's _computePressureBucket. */
|
|
70
63
|
export type AdaptorchPressureBucket = 0 | 1 | 2 | 3;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adaptorch-bridge.d.ts","sourceRoot":"","sources":["../../src/core/adaptorch-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AAEH,4GAA4G;AAC5G,MAAM,MAAM,kBAAkB,GAAG,SAAS,GAAG,aAAa,GAAG,UAAU,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEnH,yGAAyG;AACzG,MAAM,MAAM,iBAAiB,GAAG,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,CAAC;AAEtG,4FAA4F;AAC5F,MAAM,MAAM,qBAAqB,GAAG,KAAK,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEtE,0GAA0G;AAC1G,MAAM,MAAM,uBAAuB,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEhE,oHAAoH;AACpH,MAAM,MAAM,kBAAkB,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAA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BAAoB;IACpC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC;IAC9B,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;CACjC;AAED,MAAM,WAAW,eAAe;IAC/B;;;;;OAKG;IACH,YAAY,CAAC,OAAO,EAAE,uBAAuB,GAAG,uBAAuB,GAAG,IAAI,CAAC;IAC/E;;;;OAIG;IACH,cAAc,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI,CAAC;IACvD;;;;;OAKG;IACH,OAAO,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,uBAAuB,GAAG,IAAI,CAAC,CAAC;IACnF,4FAA4F;IAC5F,QAAQ,IAAI,oBAAoB,CAAC;CACjC;AAqJD,mGAAmG;AACnG,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,qBAAqB,GAAG,eAAe,CAEpF","sourcesContent":["/**\n * Reasoning-router AdaptOrch advisory bridge (Goal 009 Lane B).\n *\n * A default-off, advisory-only primitive for a future opt-in reasoning-router\n * hint source. This module is intentionally NOT wired into agent-session.ts,\n * reasoning-router-v2.ts, or reasoning-router-v3.ts by this lane - it only\n * implements the bridge's payload/result schema, sanitize/validate helpers,\n * TTL cache, budget counter, circuit breaker, and timeout wrapper around a\n * caller-injected advisory function. A future lane decides how (or whether)\n * to fuse a returned hint into a resolved ThinkingLevel and to actually call\n * this module from agent-session.ts.\n *\n * Grounded in the read-first plan at\n * .omk/goals/008-reasoning-router-advanced-accuracy-plan/laneC-privacy-adaptorch.md\n * (Part B, sections 4.1-4.11) and the real AdaptOrch MCP tool surface\n * documented in packages/adaptorch-wpl/src/adaptorch-client.ts. Key\n * constraints carried over from that plan:\n *\n * - The router's turn-start path is synchronous and I/O-free today (plan\n * 4.4). This module never calls an MCP transport directly and exposes a\n * synchronous, cache-read-only accessor (`getFreshHint`) plus a\n * fire-and-forget refresh (`requestRefresh`) so a future integration can\n * never block or await this module inline on the turn-start path.\n * - The real, documented AdaptOrch tool surface has no confidence or\n * reasoning-level field (plan 4.3); this module's inbound result type\n * (`AdaptorchAdvisoryResult`) therefore only carries a locally-relevant\n * `taskClass` and a `confidenceBand` - both closed enums - never a raw\n * numeric confidence or a `ThinkingLevel` value. Fusing a hint into a\n * resolved level is out of scope for this module.\n * - No product source (agent-session.ts, reasoning-router-v2/v3.ts,\n * reasoning-router-weights.ts) is imported here. `AdaptorchTaskClass` /\n * `AdaptorchLaneType` intentionally mirror `TaskClassV2` /\n * `ReasoningLaneTypeV2` from reasoning-router-v2.ts by value, not by\n * import, so this lane's narrow write scope (this file, its regression\n * test, and its evidence file only) cannot be affected by - or affect -\n * any concurrently-running Wave 1 lane's edits to the router modules. A\n * future wiring lane should keep these enums in sync (or replace the\n * local copies with a shared import) once it deliberately connects this\n * bridge to the router.\n * - Every outbound/inbound field is a closed enum, a boolean, or a bounded\n * integer, derived from local features only. There is structurally no\n * field shaped to carry prompt text, a prompt hash, a file/working-\n * directory path, a model/provider identifier, a session/user identifier,\n * a tool name, or hook output - the sanitize/validate helpers below also\n * reject any candidate object exposing such a field by name, and reject\n * any key outside the exact closed schema, so a hand-built or forged\n * payload can never smuggle one through either type.\n * - The router-bridge tool allowlist (`ADAPTORCH_READONLY_TOOL_ALLOWLIST`)\n * only ever contains the two read/local AdaptOrch tools the plan\n * identifies as in scope (the session-start capabilities probe and the\n * per-consult topology-classification call, plan 4.2/4.6); the\n * run-submission and run-cancellation tools (and any other mutating\n * tool) can never appear in it, checked both by an exact-value test and\n * by `looksMutatingToolName`'s verb-segment guard.\n *\n * Pure aside from `Date.now`/`setTimeout` (both injectable/wrapped so tests\n * never depend on real wall-clock time or a real MCP call).\n */\n\n/** Closed set of task classes. Mirrors TaskClassV2 in reasoning-router-v2.ts by value (see file header). */\nexport type AdaptorchTaskClass = \"trivial\" | \"simple-edit\" | \"code-gen\" | \"debug\" | \"refactor\" | \"review\" | \"plan\";\n\n/** Closed set of subagent lane types. Mirrors ReasoningLaneTypeV2 in reasoning-router-v2.ts by value. */\nexport type AdaptorchLaneType = \"planner\" | \"security\" | \"explorer\" | \"coder\" | \"reviewer\" | \"tester\";\n\n/** Local top1-vs-runner-up score-margin bucket (plan 4.5 ConsultPayloadV1.marginBucket). */\nexport type AdaptorchMarginBucket = \"tie\" | \"low\" | \"medium\" | \"high\";\n\n/** Locally-derived confidence band for a returned hint. Never a raw network-supplied float (plan 4.3). */\nexport type AdaptorchConfidenceBand = \"low\" | \"medium\" | \"high\";\n\n/** floor(log2(trimmedPromptLen+1)) clamped to [0,7] - same bucketing as reasoning-router-v2.ts's clampLenBucket. */\nexport type AdaptorchLenBucket = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;\n\n/** Context-pressure band 0..3 - same bucketing as agent-session.ts's _computePressureBucket. */\nexport type AdaptorchPressureBucket = 0 | 1 | 2 | 3;\n\n/**\n * Outbound advisory request (plan 4.5, field names adapted for this lane's\n * assignment: taskClass/runnerUp/marginBucket/lenBucket/hadFence/hadDiff/\n * pressureBucket/laneType). Every field is a closed enum, a boolean, or a\n * bounded integer built from local classifier features only. Structurally\n * excludes prompt text/hash, file paths, model/provider/session\n * identifiers, tool names, and hook output - there is no field shaped to\n * carry any of those.\n */\nexport interface AdaptorchConsultPayload {\n\treadonly schemaVersion: 1;\n\treadonly taskClass: AdaptorchTaskClass;\n\treadonly runnerUp: AdaptorchTaskClass;\n\treadonly marginBucket: AdaptorchMarginBucket;\n\treadonly lenBucket: AdaptorchLenBucket;\n\treadonly hadFence: boolean;\n\treadonly hadDiff: boolean;\n\treadonly pressureBucket: AdaptorchPressureBucket;\n\treadonly laneType?: AdaptorchLaneType;\n}\n\n/**\n * Inbound advisory result after local sanitation (plan 4.3, corrected\n * schema). `confidenceBand` is always synthesized/validated locally - the\n * real AdaptOrch tool contract carries no confidence or effort-level field,\n * so this type never trusts a raw numeric confidence from the advisory\n * function.\n */\nexport interface AdaptorchAdvisoryResult {\n\treadonly schemaVersion: 1;\n\treadonly taskClass: AdaptorchTaskClass;\n\treadonly confidenceBand: AdaptorchConfidenceBand;\n}\n\nconst TASK_CLASSES: readonly AdaptorchTaskClass[] = [\n\t\"trivial\",\n\t\"simple-edit\",\n\t\"code-gen\",\n\t\"debug\",\n\t\"refactor\",\n\t\"review\",\n\t\"plan\",\n];\nconst TASK_CLASS_SET: ReadonlySet<string> = new Set(TASK_CLASSES);\n\nconst LANE_TYPES: readonly AdaptorchLaneType[] = [\"planner\", \"security\", \"explorer\", \"coder\", \"reviewer\", \"tester\"];\nconst LANE_TYPE_SET: ReadonlySet<string> = new Set(LANE_TYPES);\n\nconst MARGIN_BUCKETS: readonly AdaptorchMarginBucket[] = [\"tie\", \"low\", \"medium\", \"high\"];\nconst MARGIN_BUCKET_SET: ReadonlySet<string> = new Set(MARGIN_BUCKETS);\n\nconst CONFIDENCE_BANDS: readonly AdaptorchConfidenceBand[] = [\"low\", \"medium\", \"high\"];\nconst CONFIDENCE_BAND_SET: ReadonlySet<string> = new Set(CONFIDENCE_BANDS);\n\nconst CONSULT_PAYLOAD_KEYS: ReadonlySet<string> = new Set([\n\t\"schemaVersion\",\n\t\"taskClass\",\n\t\"runnerUp\",\n\t\"marginBucket\",\n\t\"lenBucket\",\n\t\"hadFence\",\n\t\"hadDiff\",\n\t\"pressureBucket\",\n\t\"laneType\",\n]);\n\nconst ADVISORY_RESULT_KEYS: ReadonlySet<string> = new Set([\"schemaVersion\", \"taskClass\", \"confidenceBand\"]);\n\n/**\n * Field-name markers that must never appear on a payload or result object,\n * checked case-insensitively as a substring of every own key. This is\n * defense-in-depth alongside the exact-key allowlist below: even a candidate\n * that otherwise has every required field still fails if it also carries a\n * field shaped like a stored prompt, hash, path, model/provider identifier,\n * session identifier, tool name, or hook output.\n */\nconst FORBIDDEN_KEY_SUBSTRINGS: readonly string[] = [\n\t\"prompt\",\n\t\"hash\",\n\t\"path\",\n\t\"model\",\n\t\"session\",\n\t\"tool\",\n\t\"hook\",\n\t\"provider\",\n];\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * True if any own key of `record` contains a forbidden field-name marker\n * (case-insensitive). Typed `object` rather than `Record<string, unknown>` so\n * callers (including tests) can pass any concrete object shape - named\n * interface, ad-hoc literal, or an already-`Record`-typed value - without a\n * missing-index-signature type error; only `Object.keys` is used internally,\n * which accepts any `object`.\n */\nexport function containsForbiddenField(record: object): boolean {\n\tfor (const key of Object.keys(record)) {\n\t\tconst lowerKey = key.toLowerCase();\n\t\tif (FORBIDDEN_KEY_SUBSTRINGS.some((needle) => lowerKey.includes(needle))) return true;\n\t}\n\treturn false;\n}\n\nfunction hasOnlyAllowedKeys(record: Record<string, unknown>, allowed: ReadonlySet<string>): boolean {\n\treturn Object.keys(record).every((key) => allowed.has(key));\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n\tconst truncated = Number.isFinite(value) ? Math.trunc(value) : min;\n\tif (truncated < min) return min;\n\tif (truncated > max) return max;\n\treturn truncated;\n}\n\nfunction clampLenBucket(value: number): AdaptorchLenBucket {\n\treturn clampInt(value, 0, 7) as AdaptorchLenBucket;\n}\n\nfunction clampPressureBucket(value: number): AdaptorchPressureBucket {\n\treturn clampInt(value, 0, 3) as AdaptorchPressureBucket;\n}\n\n/** `value ?? fallback`, coerced to an integer and floored at `min` (used for config, not untrusted payloads). */\nfunction boundedIntOrDefault(value: number | undefined, fallback: number, min: number): number {\n\tconst raw = value ?? fallback;\n\tif (!Number.isFinite(raw)) return fallback;\n\treturn Math.max(min, Math.trunc(raw));\n}\n\n/**\n * Sanitize/validate an outbound advisory request. Returns `null` (never\n * throws) when `candidate` is not a plain object, carries a forbidden-named\n * field, carries any key outside the exact closed schema, or has a\n * wrong-typed/unknown-enum field. `lenBucket`/`pressureBucket` are clamped\n * into their bounded ranges rather than rejected, so a caller-side rounding\n * or edge-case computation can never smuggle an out-of-range integer through.\n */\nexport function sanitizeConsultPayload(candidate: unknown): AdaptorchConsultPayload | null {\n\tif (!isPlainObject(candidate)) return null;\n\tif (containsForbiddenField(candidate)) return null;\n\tif (!hasOnlyAllowedKeys(candidate, CONSULT_PAYLOAD_KEYS)) return null;\n\n\tif (candidate.schemaVersion !== 1) return null;\n\n\tconst taskClass = candidate.taskClass;\n\tif (typeof taskClass !== \"string\" || !TASK_CLASS_SET.has(taskClass)) return null;\n\n\tconst runnerUp = candidate.runnerUp;\n\tif (typeof runnerUp !== \"string\" || !TASK_CLASS_SET.has(runnerUp)) return null;\n\n\tconst marginBucket = candidate.marginBucket;\n\tif (typeof marginBucket !== \"string\" || !MARGIN_BUCKET_SET.has(marginBucket)) return null;\n\n\tconst lenBucketRaw = candidate.lenBucket;\n\tif (typeof lenBucketRaw !== \"number\") return null;\n\n\tconst pressureBucketRaw = candidate.pressureBucket;\n\tif (typeof pressureBucketRaw !== \"number\") return null;\n\n\tconst hadFence = candidate.hadFence;\n\tif (typeof hadFence !== \"boolean\") return null;\n\n\tconst hadDiff = candidate.hadDiff;\n\tif (typeof hadDiff !== \"boolean\") return null;\n\n\tconst laneTypeRaw = candidate.laneType;\n\tlet laneType: AdaptorchLaneType | undefined;\n\tif (laneTypeRaw !== undefined) {\n\t\tif (typeof laneTypeRaw !== \"string\" || !LANE_TYPE_SET.has(laneTypeRaw)) return null;\n\t\tlaneType = laneTypeRaw as AdaptorchLaneType;\n\t}\n\n\treturn {\n\t\tschemaVersion: 1,\n\t\ttaskClass: taskClass as AdaptorchTaskClass,\n\t\trunnerUp: runnerUp as AdaptorchTaskClass,\n\t\tmarginBucket: marginBucket as AdaptorchMarginBucket,\n\t\tlenBucket: clampLenBucket(lenBucketRaw),\n\t\thadFence,\n\t\thadDiff,\n\t\tpressureBucket: clampPressureBucket(pressureBucketRaw),\n\t\t...(laneType !== undefined ? { laneType } : {}),\n\t};\n}\n\n/**\n * Sanitize/validate an inbound advisory result (i.e. whatever the injected\n * advisory function returned). Returns `null` (never throws) on any shape,\n * forbidden-field, extra-key, or unknown-enum violation - the caller\n * (`AdaptorchBridge.consult`) treats `null` as \"no hint\" and falls back\n * silently, exactly like every other failure mode.\n */\nexport function sanitizeAdvisoryResult(candidate: unknown): AdaptorchAdvisoryResult | null {\n\tif (!isPlainObject(candidate)) return null;\n\tif (containsForbiddenField(candidate)) return null;\n\tif (!hasOnlyAllowedKeys(candidate, ADVISORY_RESULT_KEYS)) return null;\n\n\tif (candidate.schemaVersion !== 1) return null;\n\n\tconst taskClass = candidate.taskClass;\n\tif (typeof taskClass !== \"string\" || !TASK_CLASS_SET.has(taskClass)) return null;\n\n\tconst confidenceBand = candidate.confidenceBand;\n\tif (typeof confidenceBand !== \"string\" || !CONFIDENCE_BAND_SET.has(confidenceBand)) return null;\n\n\treturn {\n\t\tschemaVersion: 1,\n\t\ttaskClass: taskClass as AdaptorchTaskClass,\n\t\tconfidenceBand: confidenceBand as AdaptorchConfidenceBand,\n\t};\n}\n\n/**\n * Read-only/local AdaptOrch MCP tool names this bridge may ever reference,\n * grounded in the real 10-tool surface documented in\n * packages/adaptorch-wpl/src/adaptorch-client.ts (cross-checked there\n * against the AdaptOrch server's own docs) and narrowed to the two tools the\n * read-first plan puts in scope for a reasoning-effort hint (plan 4.2): the\n * session-start capabilities probe and the per-consult topology\n * classification call. This module does not call any MCP tool directly\n * today - the advisory function is fully caller-injected - so this\n * allowlist is not wired to a transport here; it exists so a future\n * transport, and this module's own tests, can assert by construction that\n * `adaptorch_run` (submit) and `adaptorch_cancel_run` (cancel), or any other\n * mutating tool, can never be reachable from router/bridge code.\n */\nexport const ADAPTORCH_READONLY_TOOL_ALLOWLIST = [\"adaptorch_capabilities\", \"adaptorch_route_topology\"] as const;\n\nexport type AdaptorchReadonlyToolName = (typeof ADAPTORCH_READONLY_TOOL_ALLOWLIST)[number];\n\n/** Underscore-segment verbs that mark an AdaptOrch-shaped tool name as mutating (write/execute/lifecycle). */\nconst MUTATING_TOOL_VERB_SEGMENTS: ReadonlySet<string> = new Set([\n\t\"run\",\n\t\"submit\",\n\t\"cancel\",\n\t\"dispatch\",\n\t\"delete\",\n\t\"execute\",\n\t\"mutate\",\n\t\"write\",\n\t\"create\",\n\t\"update\",\n\t\"remove\",\n]);\n\n/**\n * True if any underscore-delimited segment of an AdaptOrch-shaped tool name\n * is a known mutating verb. Segment-based rather than a raw substring/regex\n * match so \"adaptorch_route_topology\" is never falsely flagged (no segment\n * is a mutating verb), while \"adaptorch_run\" and \"adaptorch_cancel_run\" are\n * always caught regardless of future prefix/suffix changes.\n */\nexport function looksMutatingToolName(name: string): boolean {\n\treturn name\n\t\t.toLowerCase()\n\t\t.split(\"_\")\n\t\t.some((segment) => MUTATING_TOOL_VERB_SEGMENTS.has(segment));\n}\n\n/**\n * Type guard: true only for the two allowlisted read/local AdaptOrch tool\n * names. Also independently rejects any name `looksMutatingToolName` flags,\n * so a future accidental addition of a mutating name to the allowlist array\n * still cannot make this function report it as allowed.\n */\nexport function isAdaptorchToolAllowed(name: string): name is AdaptorchReadonlyToolName {\n\tif (looksMutatingToolName(name)) return false;\n\treturn (ADAPTORCH_READONLY_TOOL_ALLOWLIST as readonly string[]).includes(name);\n}\n\n/**\n * Timeout wrapper interface around any injected async advisory call. Races\n * the call against a timer; a slow or hung call rejects at `timeoutMs`\n * instead of leaving the caller waiting indefinitely. Always clears the\n * timer once the call settles (or once the timeout itself fires), and\n * always resolves/rejects exactly once - a synchronous throw from `run` is\n * treated the same as an asynchronous rejection.\n */\nexport type AdvisoryTimeoutWrapper = <T>(run: () => Promise<T>, timeoutMs: number) => Promise<T>;\n\nexport const withAdvisoryTimeout: AdvisoryTimeoutWrapper = <T>(\n\trun: () => Promise<T>,\n\ttimeoutMs: number,\n): Promise<T> => {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\treject(new Error(\"adaptorch-bridge: advisory call timed out\"));\n\t\t}, timeoutMs);\n\n\t\tlet pending: Promise<T>;\n\t\ttry {\n\t\t\tpending = run();\n\t\t} catch (err) {\n\t\t\tclearTimeout(timer);\n\t\t\treject(err instanceof Error ? err : new Error(String(err)));\n\t\t\treturn;\n\t\t}\n\n\t\tpending.then(\n\t\t\t(value) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(err: unknown) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(err instanceof Error ? err : new Error(String(err)));\n\t\t\t},\n\t\t);\n\t});\n};\n\nconst DEFAULT_TTL_MS = 5 * 60 * 1000;\nconst MIN_TTL_MS = 30 * 1000;\nconst MAX_TTL_MS = 5 * 60 * 1000;\nconst DEFAULT_MAX_TURNS_PER_ENTRY = 10;\nconst DEFAULT_CACHE_SIZE = 16;\nconst DEFAULT_MAX_CONSULTS_PER_SESSION = 5;\nconst DEFAULT_MIN_INTERVAL_MS = 60 * 1000;\nconst DEFAULT_TIMEOUT_MS = 1500;\nconst MIN_TIMEOUT_MS = 1;\nconst MAX_TIMEOUT_MS = 30 * 1000;\nconst DEFAULT_FAILURE_THRESHOLD = 3;\nconst DEFAULT_COOLDOWN_MS = 10 * 60 * 1000;\n\n/**\n * Exact TTL/cache/budget/circuit-breaker defaults from the read-first plan,\n * section 4.8. Exported so a security/review lane can confirm the shipped\n * numbers without reading this module's internals.\n */\nexport const ADAPTORCH_BRIDGE_DEFAULTS = {\n\tttlMs: DEFAULT_TTL_MS,\n\tminTtlMs: MIN_TTL_MS,\n\tmaxTtlMs: MAX_TTL_MS,\n\tmaxTurnsPerEntry: DEFAULT_MAX_TURNS_PER_ENTRY,\n\tcacheSize: DEFAULT_CACHE_SIZE,\n\tmaxConsultsPerSession: DEFAULT_MAX_CONSULTS_PER_SESSION,\n\tminIntervalMs: DEFAULT_MIN_INTERVAL_MS,\n\ttimeoutMs: DEFAULT_TIMEOUT_MS,\n\tminTimeoutMs: MIN_TIMEOUT_MS,\n\tmaxTimeoutMs: MAX_TIMEOUT_MS,\n\tfailureThreshold: DEFAULT_FAILURE_THRESHOLD,\n\tcooldownMs: DEFAULT_COOLDOWN_MS,\n} as const;\n\n/**\n * Bridge configuration. `advisoryFn` is the ONLY seam to any external\n * system - this module never imports or calls an MCP client/transport\n * itself, so it is impossible for a unit test (or a misconfigured caller)\n * to reach a real MCP server through this module by accident.\n */\nexport interface AdaptorchBridgeConfig {\n\t/**\n\t * Caller-injected advisory call. Its return value is untrusted: `consult`\n\t * always runs it through `sanitizeAdvisoryResult` before using or caching\n\t * it, and a rejected/thrown/timed-out/schema-invalid response is treated\n\t * as an ordinary failure (counts toward the circuit breaker), never as a\n\t * value to fuse.\n\t */\n\treadonly advisoryFn: (payload: AdaptorchConsultPayload) => Promise<unknown>;\n\t/** Injectable clock; defaults to `Date.now`. Tests supply a fake to avoid real wall-clock waits. */\n\treadonly now?: () => number;\n\t/** Cache TTL in ms; clamped to [30s, 5min] (plan 4.8). Default 5 minutes. */\n\treadonly ttlMs?: number;\n\t/** A cache entry also expires after this many `getFreshHint` calls (\"turns\"). Default 10. */\n\treadonly maxTurnsPerEntry?: number;\n\t/** Max distinct cached payload keys (LRU eviction beyond this). Default 16. */\n\treadonly cacheSize?: number;\n\t/** Max advisory attempts for this bridge instance's lifetime (\"session\"). Default 5. */\n\treadonly maxConsultsPerSession?: number;\n\t/** Minimum ms between advisory attempts. Default 60000 (60s). */\n\treadonly minIntervalMs?: number;\n\t/** Per-attempt timeout in ms; clamped to [1ms, 30s]. Default 1500 (1.5s). */\n\treadonly timeoutMs?: number;\n\t/** Consecutive failures before the circuit opens. Default 3. */\n\treadonly failureThreshold?: number;\n\t/** Circuit-open duration in ms once opened. Default 600000 (10min). */\n\treadonly cooldownMs?: number;\n}\n\n/** Read-only, non-sensitive introspection snapshot - never exposes payload/result content. */\nexport interface AdaptorchBridgeStats {\n\treadonly consultCount: number;\n\treadonly failureStreak: number;\n\treadonly circuitOpen: boolean;\n\treadonly circuitOpenUntilMs: number;\n\treadonly cacheEntryCount: number;\n}\n\nexport interface AdaptorchBridge {\n\t/**\n\t * Synchronous, cache-read-only. Never blocks, never throws, and never\n\t * calls the advisory function - a cache miss or an expired/invalid entry\n\t * silently returns `null` (\"no hint\"), matching the turn-start path's\n\t * synchronous, I/O-free contract (plan 4.4).\n\t */\n\tgetFreshHint(payload: AdaptorchConsultPayload): AdaptorchAdvisoryResult | null;\n\t/**\n\t * Fire-and-forget refresh for a LATER call to `getFreshHint`, never the\n\t * current one. Never throws synchronously and never rejects into the\n\t * caller - any failure is swallowed internally by `consult`.\n\t */\n\trequestRefresh(payload: AdaptorchConsultPayload): void;\n\t/**\n\t * The awaitable core operation `requestRefresh` fires without awaiting.\n\t * Gated by the circuit breaker, budget counter, and minimum interval (in\n\t * that order) before ever invoking `advisoryFn`; always resolves (never\n\t * rejects) to either a sanitized hint or `null`.\n\t */\n\tconsult(payload: AdaptorchConsultPayload): Promise<AdaptorchAdvisoryResult | null>;\n\t/** Read-only introspection for tests/diagnostics; contains no payload or result content. */\n\tgetStats(): AdaptorchBridgeStats;\n}\n\ninterface CacheEntry {\n\treadonly result: AdaptorchAdvisoryResult;\n\treadonly insertedAtMs: number;\n\treadonly insertedAtTurn: number;\n}\n\n/** Deterministic cache key built field-by-field from a sanitized payload - never from raw prompt text. */\nfunction cacheKeyFor(payload: AdaptorchConsultPayload): string {\n\treturn JSON.stringify({\n\t\ttaskClass: payload.taskClass,\n\t\trunnerUp: payload.runnerUp,\n\t\tmarginBucket: payload.marginBucket,\n\t\tlenBucket: payload.lenBucket,\n\t\thadFence: payload.hadFence,\n\t\thadDiff: payload.hadDiff,\n\t\tpressureBucket: payload.pressureBucket,\n\t\tlaneType: payload.laneType ?? null,\n\t});\n}\n\nclass AdaptorchBridgeImpl implements AdaptorchBridge {\n\tprivate readonly advisoryFn: (payload: AdaptorchConsultPayload) => Promise<unknown>;\n\tprivate readonly now: () => number;\n\tprivate readonly ttlMs: number;\n\tprivate readonly maxTurnsPerEntry: number;\n\tprivate readonly cacheSize: number;\n\tprivate readonly maxConsultsPerSession: number;\n\tprivate readonly minIntervalMs: number;\n\tprivate readonly timeoutMs: number;\n\tprivate readonly failureThreshold: number;\n\tprivate readonly cooldownMs: number;\n\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\tprivate turnCounter = 0;\n\tprivate consultCount = 0;\n\tprivate failureStreak = 0;\n\tprivate lastAttemptAtMs: number | null = null;\n\tprivate circuitOpenUntilMs = 0;\n\n\tconstructor(config: AdaptorchBridgeConfig) {\n\t\tthis.advisoryFn = config.advisoryFn;\n\t\tthis.now = config.now ?? Date.now;\n\t\tthis.ttlMs = clampInt(config.ttlMs ?? DEFAULT_TTL_MS, MIN_TTL_MS, MAX_TTL_MS);\n\t\tthis.maxTurnsPerEntry = boundedIntOrDefault(config.maxTurnsPerEntry, DEFAULT_MAX_TURNS_PER_ENTRY, 1);\n\t\tthis.cacheSize = boundedIntOrDefault(config.cacheSize, DEFAULT_CACHE_SIZE, 1);\n\t\tthis.maxConsultsPerSession = boundedIntOrDefault(\n\t\t\tconfig.maxConsultsPerSession,\n\t\t\tDEFAULT_MAX_CONSULTS_PER_SESSION,\n\t\t\t0,\n\t\t);\n\t\tthis.minIntervalMs = boundedIntOrDefault(config.minIntervalMs, DEFAULT_MIN_INTERVAL_MS, 0);\n\t\tthis.timeoutMs = clampInt(config.timeoutMs ?? DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS);\n\t\tthis.failureThreshold = boundedIntOrDefault(config.failureThreshold, DEFAULT_FAILURE_THRESHOLD, 1);\n\t\tthis.cooldownMs = boundedIntOrDefault(config.cooldownMs, DEFAULT_COOLDOWN_MS, 0);\n\t}\n\n\tgetFreshHint(payload: AdaptorchConsultPayload): AdaptorchAdvisoryResult | null {\n\t\tthis.turnCounter += 1;\n\t\tconst sanitizedPayload = sanitizeConsultPayload(payload);\n\t\tif (sanitizedPayload === null) return null;\n\n\t\tconst key = cacheKeyFor(sanitizedPayload);\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry === undefined) return null;\n\t\tif (!this.isEntryFresh(entry)) {\n\t\t\tthis.cache.delete(key);\n\t\t\treturn null;\n\t\t}\n\t\treturn entry.result;\n\t}\n\n\trequestRefresh(payload: AdaptorchConsultPayload): void {\n\t\tvoid this.consult(payload).catch(() => {\n\t\t\t// consult() already swallows every failure and always resolves; this\n\t\t\t// catch only guards a future refactor from letting one escape, so a\n\t\t\t// fire-and-forget refresh can never surface an unhandled rejection.\n\t\t});\n\t}\n\n\tasync consult(payload: AdaptorchConsultPayload): Promise<AdaptorchAdvisoryResult | null> {\n\t\tconst sanitizedPayload = sanitizeConsultPayload(payload);\n\t\tif (sanitizedPayload === null) return null;\n\n\t\tconst nowMs = this.now();\n\t\tif (nowMs < this.circuitOpenUntilMs) return null;\n\t\tif (this.consultCount >= this.maxConsultsPerSession) return null;\n\t\tif (this.lastAttemptAtMs !== null && nowMs - this.lastAttemptAtMs < this.minIntervalMs) return null;\n\n\t\tthis.consultCount += 1;\n\t\tthis.lastAttemptAtMs = nowMs;\n\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = await withAdvisoryTimeout(() => this.advisoryFn(sanitizedPayload), this.timeoutMs);\n\t\t} catch {\n\t\t\tthis.recordFailure();\n\t\t\treturn null;\n\t\t}\n\n\t\tconst result = sanitizeAdvisoryResult(raw);\n\t\tif (result === null) {\n\t\t\tthis.recordFailure();\n\t\t\treturn null;\n\t\t}\n\n\t\tthis.failureStreak = 0;\n\t\tthis.cacheResult(sanitizedPayload, result);\n\t\treturn result;\n\t}\n\n\tgetStats(): AdaptorchBridgeStats {\n\t\tconst nowMs = this.now();\n\t\treturn {\n\t\t\tconsultCount: this.consultCount,\n\t\t\tfailureStreak: this.failureStreak,\n\t\t\tcircuitOpen: nowMs < this.circuitOpenUntilMs,\n\t\t\tcircuitOpenUntilMs: this.circuitOpenUntilMs,\n\t\t\tcacheEntryCount: this.cache.size,\n\t\t};\n\t}\n\n\tprivate recordFailure(): void {\n\t\tthis.failureStreak += 1;\n\t\tif (this.failureStreak >= this.failureThreshold) {\n\t\t\tthis.circuitOpenUntilMs = this.now() + this.cooldownMs;\n\t\t}\n\t}\n\n\tprivate isEntryFresh(entry: CacheEntry): boolean {\n\t\tconst ageMs = this.now() - entry.insertedAtMs;\n\t\tconst ageTurns = this.turnCounter - entry.insertedAtTurn;\n\t\treturn ageMs < this.ttlMs && ageTurns < this.maxTurnsPerEntry;\n\t}\n\n\t/** Eviction favors entries last refreshed by a successful consult (write-time LRU, not read-time). */\n\tprivate cacheResult(payload: AdaptorchConsultPayload, result: AdaptorchAdvisoryResult): void {\n\t\tconst key = cacheKeyFor(payload);\n\t\tif (this.cache.has(key)) this.cache.delete(key);\n\t\tthis.cache.set(key, { result, insertedAtMs: this.now(), insertedAtTurn: this.turnCounter });\n\t\twhile (this.cache.size > this.cacheSize) {\n\t\t\tconst oldestKey = this.cache.keys().next().value;\n\t\t\tif (oldestKey === undefined) break;\n\t\t\tthis.cache.delete(oldestKey);\n\t\t}\n\t}\n}\n\n/** Construct a default-off AdaptOrch advisory bridge. See `AdaptorchBridgeConfig` for tunables. */\nexport function createAdaptorchBridge(config: AdaptorchBridgeConfig): AdaptorchBridge {\n\treturn new AdaptorchBridgeImpl(config);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"adaptorch-bridge.d.ts","sourceRoot":"","sources":["../../src/core/adaptorch-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AAEH,8FAA8F;AAC9F,MAAM,MAAM,kBAAkB,GAAG,SAAS,GAAG,aAAa,GAAG,UAAU,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEnH,6EAA6E;AAC7E,MAAM,MAAM,iBAAiB,GAAG,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,OAAO,GAAG,U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qBAAqB,CAAC,EAAE,MAAM,CAAC;IACxC,iEAAiE;IACjE,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,6EAA6E;IAC7E,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,gEAAgE;IAChE,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,uEAAuE;IACvE,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,8FAA8F;AAC9F,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC;IAC9B,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;CACjC;AAED,MAAM,WAAW,eAAe;IAC/B;;;;;OAKG;IACH,YAAY,CAAC,OAAO,EAAE,uBAAuB,GAAG,uBAAuB,GAAG,IAAI,CAAC;IAC/E;;;;OAIG;IACH,cAAc,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI,CAAC;IACvD;;;;;OAKG;IACH,OAAO,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,uBAAuB,GAAG,IAAI,CAAC,CAAC;IACnF,4FAA4F;IAC5F,QAAQ,IAAI,oBAAoB,CAAC;CACjC;AAqJD,mGAAmG;AACnG,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,qBAAqB,GAAG,eAAe,CAEpF","sourcesContent":["/**\n * Reasoning-router AdaptOrch advisory bridge (Goal 009 Lane B).\n *\n * A default-off, advisory-only primitive for a future reasoning-router hint\n * source. This module is intentionally NOT wired into agent-session.ts; it only\n * implements the bridge's payload/result schema, sanitize/validate helpers, TTL\n * cache, budget counter, circuit breaker, and timeout wrapper around a\n * caller-injected advisory function. A future lane decides how (or whether) to\n * fuse a returned hint into a resolved ThinkingLevel and to actually call this\n * module from agent-session.ts.\n *\n * Grounded in the read-first plan at\n * .omk/goals/008-reasoning-router-advanced-accuracy-plan/laneC-privacy-adaptorch.md\n * (Part B, sections 4.1-4.11) and the real AdaptOrch MCP tool surface\n * documented in packages/adaptorch-wpl/src/adaptorch-client.ts. Key\n * constraints carried over from that plan:\n *\n * - The router's turn-start path is synchronous and I/O-free today (plan\n * 4.4). This module never calls an MCP transport directly and exposes a\n * synchronous, cache-read-only accessor (`getFreshHint`) plus a\n * fire-and-forget refresh (`requestRefresh`) so a future integration can\n * never block or await this module inline on the turn-start path.\n * - The real, documented AdaptOrch tool surface has no confidence or\n * reasoning-level field (plan 4.3); this module's inbound result type\n * (`AdaptorchAdvisoryResult`) therefore only carries a locally-relevant\n * `taskClass` and a `confidenceBand` - both closed enums - never a raw\n * numeric confidence or a `ThinkingLevel` value. Fusing a hint into a\n * resolved level is out of scope for this module.\n * - No product source is imported here. `AdaptorchTaskClass` /\n * `AdaptorchLaneType` intentionally mirror the v4 task/lane unions by\n * value, not by import, so this bridge remains isolated until a future\n * wiring lane deliberately connects it to the router.\n * - Every outbound/inbound field is a closed enum, a boolean, or a bounded\n * integer, derived from local features only. There is structurally no\n * field shaped to carry prompt text, a prompt hash, a file/working-\n * directory path, a model/provider identifier, a session/user identifier,\n * a tool name, or hook output - the sanitize/validate helpers below also\n * reject any candidate object exposing such a field by name, and reject\n * any key outside the exact closed schema, so a hand-built or forged\n * payload can never smuggle one through either type.\n * - The router-bridge tool allowlist (`ADAPTORCH_READONLY_TOOL_ALLOWLIST`)\n * only ever contains the two read/local AdaptOrch tools the plan\n * identifies as in scope (the session-start capabilities probe and the\n * per-consult topology-classification call, plan 4.2/4.6); the\n * run-submission and run-cancellation tools (and any other mutating\n * tool) can never appear in it, checked both by an exact-value test and\n * by `looksMutatingToolName`'s verb-segment guard.\n *\n * Pure aside from `Date.now`/`setTimeout` (both injectable/wrapped so tests\n * never depend on real wall-clock time or a real MCP call).\n */\n\n/** Closed set of task classes. Mirrors the v4 task-class union by value (see file header). */\nexport type AdaptorchTaskClass = \"trivial\" | \"simple-edit\" | \"code-gen\" | \"debug\" | \"refactor\" | \"review\" | \"plan\";\n\n/** Closed set of subagent lane types. Mirrors the v4 lane union by value. */\nexport type AdaptorchLaneType = \"planner\" | \"security\" | \"explorer\" | \"coder\" | \"reviewer\" | \"tester\";\n\n/** Local top1-vs-runner-up score-margin bucket (plan 4.5 ConsultPayloadV1.marginBucket). */\nexport type AdaptorchMarginBucket = \"tie\" | \"low\" | \"medium\" | \"high\";\n\n/** Locally-derived confidence band for a returned hint. Never a raw network-supplied float (plan 4.3). */\nexport type AdaptorchConfidenceBand = \"low\" | \"medium\" | \"high\";\n\n/** floor(log2(trimmedPromptLen+1)) clamped to [0,7]. */\nexport type AdaptorchLenBucket = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;\n\n/** Context-pressure band 0..3 - same bucketing as agent-session.ts's _computePressureBucket. */\nexport type AdaptorchPressureBucket = 0 | 1 | 2 | 3;\n\n/**\n * Outbound advisory request (plan 4.5, field names adapted for this lane's\n * assignment: taskClass/runnerUp/marginBucket/lenBucket/hadFence/hadDiff/\n * pressureBucket/laneType). Every field is a closed enum, a boolean, or a\n * bounded integer built from local classifier features only. Structurally\n * excludes prompt text/hash, file paths, model/provider/session\n * identifiers, tool names, and hook output - there is no field shaped to\n * carry any of those.\n */\nexport interface AdaptorchConsultPayload {\n\treadonly schemaVersion: 1;\n\treadonly taskClass: AdaptorchTaskClass;\n\treadonly runnerUp: AdaptorchTaskClass;\n\treadonly marginBucket: AdaptorchMarginBucket;\n\treadonly lenBucket: AdaptorchLenBucket;\n\treadonly hadFence: boolean;\n\treadonly hadDiff: boolean;\n\treadonly pressureBucket: AdaptorchPressureBucket;\n\treadonly laneType?: AdaptorchLaneType;\n}\n\n/**\n * Inbound advisory result after local sanitation (plan 4.3, corrected\n * schema). `confidenceBand` is always synthesized/validated locally - the\n * real AdaptOrch tool contract carries no confidence or effort-level field,\n * so this type never trusts a raw numeric confidence from the advisory\n * function.\n */\nexport interface AdaptorchAdvisoryResult {\n\treadonly schemaVersion: 1;\n\treadonly taskClass: AdaptorchTaskClass;\n\treadonly confidenceBand: AdaptorchConfidenceBand;\n}\n\nconst TASK_CLASSES: readonly AdaptorchTaskClass[] = [\n\t\"trivial\",\n\t\"simple-edit\",\n\t\"code-gen\",\n\t\"debug\",\n\t\"refactor\",\n\t\"review\",\n\t\"plan\",\n];\nconst TASK_CLASS_SET: ReadonlySet<string> = new Set(TASK_CLASSES);\n\nconst LANE_TYPES: readonly AdaptorchLaneType[] = [\"planner\", \"security\", \"explorer\", \"coder\", \"reviewer\", \"tester\"];\nconst LANE_TYPE_SET: ReadonlySet<string> = new Set(LANE_TYPES);\n\nconst MARGIN_BUCKETS: readonly AdaptorchMarginBucket[] = [\"tie\", \"low\", \"medium\", \"high\"];\nconst MARGIN_BUCKET_SET: ReadonlySet<string> = new Set(MARGIN_BUCKETS);\n\nconst CONFIDENCE_BANDS: readonly AdaptorchConfidenceBand[] = [\"low\", \"medium\", \"high\"];\nconst CONFIDENCE_BAND_SET: ReadonlySet<string> = new Set(CONFIDENCE_BANDS);\n\nconst CONSULT_PAYLOAD_KEYS: ReadonlySet<string> = new Set([\n\t\"schemaVersion\",\n\t\"taskClass\",\n\t\"runnerUp\",\n\t\"marginBucket\",\n\t\"lenBucket\",\n\t\"hadFence\",\n\t\"hadDiff\",\n\t\"pressureBucket\",\n\t\"laneType\",\n]);\n\nconst ADVISORY_RESULT_KEYS: ReadonlySet<string> = new Set([\"schemaVersion\", \"taskClass\", \"confidenceBand\"]);\n\n/**\n * Field-name markers that must never appear on a payload or result object,\n * checked case-insensitively as a substring of every own key. This is\n * defense-in-depth alongside the exact-key allowlist below: even a candidate\n * that otherwise has every required field still fails if it also carries a\n * field shaped like a stored prompt, hash, path, model/provider identifier,\n * session identifier, tool name, or hook output.\n */\nconst FORBIDDEN_KEY_SUBSTRINGS: readonly string[] = [\n\t\"prompt\",\n\t\"hash\",\n\t\"path\",\n\t\"model\",\n\t\"session\",\n\t\"tool\",\n\t\"hook\",\n\t\"provider\",\n];\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * True if any own key of `record` contains a forbidden field-name marker\n * (case-insensitive). Typed `object` rather than `Record<string, unknown>` so\n * callers (including tests) can pass any concrete object shape - named\n * interface, ad-hoc literal, or an already-`Record`-typed value - without a\n * missing-index-signature type error; only `Object.keys` is used internally,\n * which accepts any `object`.\n */\nexport function containsForbiddenField(record: object): boolean {\n\tfor (const key of Object.keys(record)) {\n\t\tconst lowerKey = key.toLowerCase();\n\t\tif (FORBIDDEN_KEY_SUBSTRINGS.some((needle) => lowerKey.includes(needle))) return true;\n\t}\n\treturn false;\n}\n\nfunction hasOnlyAllowedKeys(record: Record<string, unknown>, allowed: ReadonlySet<string>): boolean {\n\treturn Object.keys(record).every((key) => allowed.has(key));\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n\tconst truncated = Number.isFinite(value) ? Math.trunc(value) : min;\n\tif (truncated < min) return min;\n\tif (truncated > max) return max;\n\treturn truncated;\n}\n\nfunction clampLenBucket(value: number): AdaptorchLenBucket {\n\treturn clampInt(value, 0, 7) as AdaptorchLenBucket;\n}\n\nfunction clampPressureBucket(value: number): AdaptorchPressureBucket {\n\treturn clampInt(value, 0, 3) as AdaptorchPressureBucket;\n}\n\n/** `value ?? fallback`, coerced to an integer and floored at `min` (used for config, not untrusted payloads). */\nfunction boundedIntOrDefault(value: number | undefined, fallback: number, min: number): number {\n\tconst raw = value ?? fallback;\n\tif (!Number.isFinite(raw)) return fallback;\n\treturn Math.max(min, Math.trunc(raw));\n}\n\n/**\n * Sanitize/validate an outbound advisory request. Returns `null` (never\n * throws) when `candidate` is not a plain object, carries a forbidden-named\n * field, carries any key outside the exact closed schema, or has a\n * wrong-typed/unknown-enum field. `lenBucket`/`pressureBucket` are clamped\n * into their bounded ranges rather than rejected, so a caller-side rounding\n * or edge-case computation can never smuggle an out-of-range integer through.\n */\nexport function sanitizeConsultPayload(candidate: unknown): AdaptorchConsultPayload | null {\n\tif (!isPlainObject(candidate)) return null;\n\tif (containsForbiddenField(candidate)) return null;\n\tif (!hasOnlyAllowedKeys(candidate, CONSULT_PAYLOAD_KEYS)) return null;\n\n\tif (candidate.schemaVersion !== 1) return null;\n\n\tconst taskClass = candidate.taskClass;\n\tif (typeof taskClass !== \"string\" || !TASK_CLASS_SET.has(taskClass)) return null;\n\n\tconst runnerUp = candidate.runnerUp;\n\tif (typeof runnerUp !== \"string\" || !TASK_CLASS_SET.has(runnerUp)) return null;\n\n\tconst marginBucket = candidate.marginBucket;\n\tif (typeof marginBucket !== \"string\" || !MARGIN_BUCKET_SET.has(marginBucket)) return null;\n\n\tconst lenBucketRaw = candidate.lenBucket;\n\tif (typeof lenBucketRaw !== \"number\") return null;\n\n\tconst pressureBucketRaw = candidate.pressureBucket;\n\tif (typeof pressureBucketRaw !== \"number\") return null;\n\n\tconst hadFence = candidate.hadFence;\n\tif (typeof hadFence !== \"boolean\") return null;\n\n\tconst hadDiff = candidate.hadDiff;\n\tif (typeof hadDiff !== \"boolean\") return null;\n\n\tconst laneTypeRaw = candidate.laneType;\n\tlet laneType: AdaptorchLaneType | undefined;\n\tif (laneTypeRaw !== undefined) {\n\t\tif (typeof laneTypeRaw !== \"string\" || !LANE_TYPE_SET.has(laneTypeRaw)) return null;\n\t\tlaneType = laneTypeRaw as AdaptorchLaneType;\n\t}\n\n\treturn {\n\t\tschemaVersion: 1,\n\t\ttaskClass: taskClass as AdaptorchTaskClass,\n\t\trunnerUp: runnerUp as AdaptorchTaskClass,\n\t\tmarginBucket: marginBucket as AdaptorchMarginBucket,\n\t\tlenBucket: clampLenBucket(lenBucketRaw),\n\t\thadFence,\n\t\thadDiff,\n\t\tpressureBucket: clampPressureBucket(pressureBucketRaw),\n\t\t...(laneType !== undefined ? { laneType } : {}),\n\t};\n}\n\n/**\n * Sanitize/validate an inbound advisory result (i.e. whatever the injected\n * advisory function returned). Returns `null` (never throws) on any shape,\n * forbidden-field, extra-key, or unknown-enum violation - the caller\n * (`AdaptorchBridge.consult`) treats `null` as \"no hint\" and falls back\n * silently, exactly like every other failure mode.\n */\nexport function sanitizeAdvisoryResult(candidate: unknown): AdaptorchAdvisoryResult | null {\n\tif (!isPlainObject(candidate)) return null;\n\tif (containsForbiddenField(candidate)) return null;\n\tif (!hasOnlyAllowedKeys(candidate, ADVISORY_RESULT_KEYS)) return null;\n\n\tif (candidate.schemaVersion !== 1) return null;\n\n\tconst taskClass = candidate.taskClass;\n\tif (typeof taskClass !== \"string\" || !TASK_CLASS_SET.has(taskClass)) return null;\n\n\tconst confidenceBand = candidate.confidenceBand;\n\tif (typeof confidenceBand !== \"string\" || !CONFIDENCE_BAND_SET.has(confidenceBand)) return null;\n\n\treturn {\n\t\tschemaVersion: 1,\n\t\ttaskClass: taskClass as AdaptorchTaskClass,\n\t\tconfidenceBand: confidenceBand as AdaptorchConfidenceBand,\n\t};\n}\n\n/**\n * Read-only/local AdaptOrch MCP tool names this bridge may ever reference,\n * grounded in the real 10-tool surface documented in\n * packages/adaptorch-wpl/src/adaptorch-client.ts (cross-checked there\n * against the AdaptOrch server's own docs) and narrowed to the two tools the\n * read-first plan puts in scope for a reasoning-effort hint (plan 4.2): the\n * session-start capabilities probe and the per-consult topology\n * classification call. This module does not call any MCP tool directly\n * today - the advisory function is fully caller-injected - so this\n * allowlist is not wired to a transport here; it exists so a future\n * transport, and this module's own tests, can assert by construction that\n * `adaptorch_run` (submit) and `adaptorch_cancel_run` (cancel), or any other\n * mutating tool, can never be reachable from router/bridge code.\n */\nexport const ADAPTORCH_READONLY_TOOL_ALLOWLIST = [\"adaptorch_capabilities\", \"adaptorch_route_topology\"] as const;\n\nexport type AdaptorchReadonlyToolName = (typeof ADAPTORCH_READONLY_TOOL_ALLOWLIST)[number];\n\n/** Underscore-segment verbs that mark an AdaptOrch-shaped tool name as mutating (write/execute/lifecycle). */\nconst MUTATING_TOOL_VERB_SEGMENTS: ReadonlySet<string> = new Set([\n\t\"run\",\n\t\"submit\",\n\t\"cancel\",\n\t\"dispatch\",\n\t\"delete\",\n\t\"execute\",\n\t\"mutate\",\n\t\"write\",\n\t\"create\",\n\t\"update\",\n\t\"remove\",\n]);\n\n/**\n * True if any underscore-delimited segment of an AdaptOrch-shaped tool name\n * is a known mutating verb. Segment-based rather than a raw substring/regex\n * match so \"adaptorch_route_topology\" is never falsely flagged (no segment\n * is a mutating verb), while \"adaptorch_run\" and \"adaptorch_cancel_run\" are\n * always caught regardless of future prefix/suffix changes.\n */\nexport function looksMutatingToolName(name: string): boolean {\n\treturn name\n\t\t.toLowerCase()\n\t\t.split(\"_\")\n\t\t.some((segment) => MUTATING_TOOL_VERB_SEGMENTS.has(segment));\n}\n\n/**\n * Type guard: true only for the two allowlisted read/local AdaptOrch tool\n * names. Also independently rejects any name `looksMutatingToolName` flags,\n * so a future accidental addition of a mutating name to the allowlist array\n * still cannot make this function report it as allowed.\n */\nexport function isAdaptorchToolAllowed(name: string): name is AdaptorchReadonlyToolName {\n\tif (looksMutatingToolName(name)) return false;\n\treturn (ADAPTORCH_READONLY_TOOL_ALLOWLIST as readonly string[]).includes(name);\n}\n\n/**\n * Timeout wrapper interface around any injected async advisory call. Races\n * the call against a timer; a slow or hung call rejects at `timeoutMs`\n * instead of leaving the caller waiting indefinitely. Always clears the\n * timer once the call settles (or once the timeout itself fires), and\n * always resolves/rejects exactly once - a synchronous throw from `run` is\n * treated the same as an asynchronous rejection.\n */\nexport type AdvisoryTimeoutWrapper = <T>(run: () => Promise<T>, timeoutMs: number) => Promise<T>;\n\nexport const withAdvisoryTimeout: AdvisoryTimeoutWrapper = <T>(\n\trun: () => Promise<T>,\n\ttimeoutMs: number,\n): Promise<T> => {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\treject(new Error(\"adaptorch-bridge: advisory call timed out\"));\n\t\t}, timeoutMs);\n\n\t\tlet pending: Promise<T>;\n\t\ttry {\n\t\t\tpending = run();\n\t\t} catch (err) {\n\t\t\tclearTimeout(timer);\n\t\t\treject(err instanceof Error ? err : new Error(String(err)));\n\t\t\treturn;\n\t\t}\n\n\t\tpending.then(\n\t\t\t(value) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(err: unknown) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(err instanceof Error ? err : new Error(String(err)));\n\t\t\t},\n\t\t);\n\t});\n};\n\nconst DEFAULT_TTL_MS = 5 * 60 * 1000;\nconst MIN_TTL_MS = 30 * 1000;\nconst MAX_TTL_MS = 5 * 60 * 1000;\nconst DEFAULT_MAX_TURNS_PER_ENTRY = 10;\nconst DEFAULT_CACHE_SIZE = 16;\nconst DEFAULT_MAX_CONSULTS_PER_SESSION = 5;\nconst DEFAULT_MIN_INTERVAL_MS = 60 * 1000;\nconst DEFAULT_TIMEOUT_MS = 1500;\nconst MIN_TIMEOUT_MS = 1;\nconst MAX_TIMEOUT_MS = 30 * 1000;\nconst DEFAULT_FAILURE_THRESHOLD = 3;\nconst DEFAULT_COOLDOWN_MS = 10 * 60 * 1000;\n\n/**\n * Exact TTL/cache/budget/circuit-breaker defaults from the read-first plan,\n * section 4.8. Exported so a security/review lane can confirm the shipped\n * numbers without reading this module's internals.\n */\nexport const ADAPTORCH_BRIDGE_DEFAULTS = {\n\tttlMs: DEFAULT_TTL_MS,\n\tminTtlMs: MIN_TTL_MS,\n\tmaxTtlMs: MAX_TTL_MS,\n\tmaxTurnsPerEntry: DEFAULT_MAX_TURNS_PER_ENTRY,\n\tcacheSize: DEFAULT_CACHE_SIZE,\n\tmaxConsultsPerSession: DEFAULT_MAX_CONSULTS_PER_SESSION,\n\tminIntervalMs: DEFAULT_MIN_INTERVAL_MS,\n\ttimeoutMs: DEFAULT_TIMEOUT_MS,\n\tminTimeoutMs: MIN_TIMEOUT_MS,\n\tmaxTimeoutMs: MAX_TIMEOUT_MS,\n\tfailureThreshold: DEFAULT_FAILURE_THRESHOLD,\n\tcooldownMs: DEFAULT_COOLDOWN_MS,\n} as const;\n\n/**\n * Bridge configuration. `advisoryFn` is the ONLY seam to any external\n * system - this module never imports or calls an MCP client/transport\n * itself, so it is impossible for a unit test (or a misconfigured caller)\n * to reach a real MCP server through this module by accident.\n */\nexport interface AdaptorchBridgeConfig {\n\t/**\n\t * Caller-injected advisory call. Its return value is untrusted: `consult`\n\t * always runs it through `sanitizeAdvisoryResult` before using or caching\n\t * it, and a rejected/thrown/timed-out/schema-invalid response is treated\n\t * as an ordinary failure (counts toward the circuit breaker), never as a\n\t * value to fuse.\n\t */\n\treadonly advisoryFn: (payload: AdaptorchConsultPayload) => Promise<unknown>;\n\t/** Injectable clock; defaults to `Date.now`. Tests supply a fake to avoid real wall-clock waits. */\n\treadonly now?: () => number;\n\t/** Cache TTL in ms; clamped to [30s, 5min] (plan 4.8). Default 5 minutes. */\n\treadonly ttlMs?: number;\n\t/** A cache entry also expires after this many `getFreshHint` calls (\"turns\"). Default 10. */\n\treadonly maxTurnsPerEntry?: number;\n\t/** Max distinct cached payload keys (LRU eviction beyond this). Default 16. */\n\treadonly cacheSize?: number;\n\t/** Max advisory attempts for this bridge instance's lifetime (\"session\"). Default 5. */\n\treadonly maxConsultsPerSession?: number;\n\t/** Minimum ms between advisory attempts. Default 60000 (60s). */\n\treadonly minIntervalMs?: number;\n\t/** Per-attempt timeout in ms; clamped to [1ms, 30s]. Default 1500 (1.5s). */\n\treadonly timeoutMs?: number;\n\t/** Consecutive failures before the circuit opens. Default 3. */\n\treadonly failureThreshold?: number;\n\t/** Circuit-open duration in ms once opened. Default 600000 (10min). */\n\treadonly cooldownMs?: number;\n}\n\n/** Read-only, non-sensitive introspection snapshot - never exposes payload/result content. */\nexport interface AdaptorchBridgeStats {\n\treadonly consultCount: number;\n\treadonly failureStreak: number;\n\treadonly circuitOpen: boolean;\n\treadonly circuitOpenUntilMs: number;\n\treadonly cacheEntryCount: number;\n}\n\nexport interface AdaptorchBridge {\n\t/**\n\t * Synchronous, cache-read-only. Never blocks, never throws, and never\n\t * calls the advisory function - a cache miss or an expired/invalid entry\n\t * silently returns `null` (\"no hint\"), matching the turn-start path's\n\t * synchronous, I/O-free contract (plan 4.4).\n\t */\n\tgetFreshHint(payload: AdaptorchConsultPayload): AdaptorchAdvisoryResult | null;\n\t/**\n\t * Fire-and-forget refresh for a LATER call to `getFreshHint`, never the\n\t * current one. Never throws synchronously and never rejects into the\n\t * caller - any failure is swallowed internally by `consult`.\n\t */\n\trequestRefresh(payload: AdaptorchConsultPayload): void;\n\t/**\n\t * The awaitable core operation `requestRefresh` fires without awaiting.\n\t * Gated by the circuit breaker, budget counter, and minimum interval (in\n\t * that order) before ever invoking `advisoryFn`; always resolves (never\n\t * rejects) to either a sanitized hint or `null`.\n\t */\n\tconsult(payload: AdaptorchConsultPayload): Promise<AdaptorchAdvisoryResult | null>;\n\t/** Read-only introspection for tests/diagnostics; contains no payload or result content. */\n\tgetStats(): AdaptorchBridgeStats;\n}\n\ninterface CacheEntry {\n\treadonly result: AdaptorchAdvisoryResult;\n\treadonly insertedAtMs: number;\n\treadonly insertedAtTurn: number;\n}\n\n/** Deterministic cache key built field-by-field from a sanitized payload - never from raw prompt text. */\nfunction cacheKeyFor(payload: AdaptorchConsultPayload): string {\n\treturn JSON.stringify({\n\t\ttaskClass: payload.taskClass,\n\t\trunnerUp: payload.runnerUp,\n\t\tmarginBucket: payload.marginBucket,\n\t\tlenBucket: payload.lenBucket,\n\t\thadFence: payload.hadFence,\n\t\thadDiff: payload.hadDiff,\n\t\tpressureBucket: payload.pressureBucket,\n\t\tlaneType: payload.laneType ?? null,\n\t});\n}\n\nclass AdaptorchBridgeImpl implements AdaptorchBridge {\n\tprivate readonly advisoryFn: (payload: AdaptorchConsultPayload) => Promise<unknown>;\n\tprivate readonly now: () => number;\n\tprivate readonly ttlMs: number;\n\tprivate readonly maxTurnsPerEntry: number;\n\tprivate readonly cacheSize: number;\n\tprivate readonly maxConsultsPerSession: number;\n\tprivate readonly minIntervalMs: number;\n\tprivate readonly timeoutMs: number;\n\tprivate readonly failureThreshold: number;\n\tprivate readonly cooldownMs: number;\n\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\tprivate turnCounter = 0;\n\tprivate consultCount = 0;\n\tprivate failureStreak = 0;\n\tprivate lastAttemptAtMs: number | null = null;\n\tprivate circuitOpenUntilMs = 0;\n\n\tconstructor(config: AdaptorchBridgeConfig) {\n\t\tthis.advisoryFn = config.advisoryFn;\n\t\tthis.now = config.now ?? Date.now;\n\t\tthis.ttlMs = clampInt(config.ttlMs ?? DEFAULT_TTL_MS, MIN_TTL_MS, MAX_TTL_MS);\n\t\tthis.maxTurnsPerEntry = boundedIntOrDefault(config.maxTurnsPerEntry, DEFAULT_MAX_TURNS_PER_ENTRY, 1);\n\t\tthis.cacheSize = boundedIntOrDefault(config.cacheSize, DEFAULT_CACHE_SIZE, 1);\n\t\tthis.maxConsultsPerSession = boundedIntOrDefault(\n\t\t\tconfig.maxConsultsPerSession,\n\t\t\tDEFAULT_MAX_CONSULTS_PER_SESSION,\n\t\t\t0,\n\t\t);\n\t\tthis.minIntervalMs = boundedIntOrDefault(config.minIntervalMs, DEFAULT_MIN_INTERVAL_MS, 0);\n\t\tthis.timeoutMs = clampInt(config.timeoutMs ?? DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS);\n\t\tthis.failureThreshold = boundedIntOrDefault(config.failureThreshold, DEFAULT_FAILURE_THRESHOLD, 1);\n\t\tthis.cooldownMs = boundedIntOrDefault(config.cooldownMs, DEFAULT_COOLDOWN_MS, 0);\n\t}\n\n\tgetFreshHint(payload: AdaptorchConsultPayload): AdaptorchAdvisoryResult | null {\n\t\tthis.turnCounter += 1;\n\t\tconst sanitizedPayload = sanitizeConsultPayload(payload);\n\t\tif (sanitizedPayload === null) return null;\n\n\t\tconst key = cacheKeyFor(sanitizedPayload);\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry === undefined) return null;\n\t\tif (!this.isEntryFresh(entry)) {\n\t\t\tthis.cache.delete(key);\n\t\t\treturn null;\n\t\t}\n\t\treturn entry.result;\n\t}\n\n\trequestRefresh(payload: AdaptorchConsultPayload): void {\n\t\tvoid this.consult(payload).catch(() => {\n\t\t\t// consult() already swallows every failure and always resolves; this\n\t\t\t// catch only guards a future refactor from letting one escape, so a\n\t\t\t// fire-and-forget refresh can never surface an unhandled rejection.\n\t\t});\n\t}\n\n\tasync consult(payload: AdaptorchConsultPayload): Promise<AdaptorchAdvisoryResult | null> {\n\t\tconst sanitizedPayload = sanitizeConsultPayload(payload);\n\t\tif (sanitizedPayload === null) return null;\n\n\t\tconst nowMs = this.now();\n\t\tif (nowMs < this.circuitOpenUntilMs) return null;\n\t\tif (this.consultCount >= this.maxConsultsPerSession) return null;\n\t\tif (this.lastAttemptAtMs !== null && nowMs - this.lastAttemptAtMs < this.minIntervalMs) return null;\n\n\t\tthis.consultCount += 1;\n\t\tthis.lastAttemptAtMs = nowMs;\n\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = await withAdvisoryTimeout(() => this.advisoryFn(sanitizedPayload), this.timeoutMs);\n\t\t} catch {\n\t\t\tthis.recordFailure();\n\t\t\treturn null;\n\t\t}\n\n\t\tconst result = sanitizeAdvisoryResult(raw);\n\t\tif (result === null) {\n\t\t\tthis.recordFailure();\n\t\t\treturn null;\n\t\t}\n\n\t\tthis.failureStreak = 0;\n\t\tthis.cacheResult(sanitizedPayload, result);\n\t\treturn result;\n\t}\n\n\tgetStats(): AdaptorchBridgeStats {\n\t\tconst nowMs = this.now();\n\t\treturn {\n\t\t\tconsultCount: this.consultCount,\n\t\t\tfailureStreak: this.failureStreak,\n\t\t\tcircuitOpen: nowMs < this.circuitOpenUntilMs,\n\t\t\tcircuitOpenUntilMs: this.circuitOpenUntilMs,\n\t\t\tcacheEntryCount: this.cache.size,\n\t\t};\n\t}\n\n\tprivate recordFailure(): void {\n\t\tthis.failureStreak += 1;\n\t\tif (this.failureStreak >= this.failureThreshold) {\n\t\t\tthis.circuitOpenUntilMs = this.now() + this.cooldownMs;\n\t\t}\n\t}\n\n\tprivate isEntryFresh(entry: CacheEntry): boolean {\n\t\tconst ageMs = this.now() - entry.insertedAtMs;\n\t\tconst ageTurns = this.turnCounter - entry.insertedAtTurn;\n\t\treturn ageMs < this.ttlMs && ageTurns < this.maxTurnsPerEntry;\n\t}\n\n\t/** Eviction favors entries last refreshed by a successful consult (write-time LRU, not read-time). */\n\tprivate cacheResult(payload: AdaptorchConsultPayload, result: AdaptorchAdvisoryResult): void {\n\t\tconst key = cacheKeyFor(payload);\n\t\tif (this.cache.has(key)) this.cache.delete(key);\n\t\tthis.cache.set(key, { result, insertedAtMs: this.now(), insertedAtTurn: this.turnCounter });\n\t\twhile (this.cache.size > this.cacheSize) {\n\t\t\tconst oldestKey = this.cache.keys().next().value;\n\t\t\tif (oldestKey === undefined) break;\n\t\t\tthis.cache.delete(oldestKey);\n\t\t}\n\t}\n}\n\n/** Construct a default-off AdaptOrch advisory bridge. See `AdaptorchBridgeConfig` for tunables. */\nexport function createAdaptorchBridge(config: AdaptorchBridgeConfig): AdaptorchBridge {\n\treturn new AdaptorchBridgeImpl(config);\n}\n"]}
|
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Reasoning-router AdaptOrch advisory bridge (Goal 009 Lane B).
|
|
3
3
|
*
|
|
4
|
-
* A default-off, advisory-only primitive for a future
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* this module from agent-session.ts.
|
|
4
|
+
* A default-off, advisory-only primitive for a future reasoning-router hint
|
|
5
|
+
* source. This module is intentionally NOT wired into agent-session.ts; it only
|
|
6
|
+
* implements the bridge's payload/result schema, sanitize/validate helpers, TTL
|
|
7
|
+
* cache, budget counter, circuit breaker, and timeout wrapper around a
|
|
8
|
+
* caller-injected advisory function. A future lane decides how (or whether) to
|
|
9
|
+
* fuse a returned hint into a resolved ThinkingLevel and to actually call this
|
|
10
|
+
* module from agent-session.ts.
|
|
12
11
|
*
|
|
13
12
|
* Grounded in the read-first plan at
|
|
14
13
|
* .omk/goals/008-reasoning-router-advanced-accuracy-plan/laneC-privacy-adaptorch.md
|
|
@@ -27,16 +26,10 @@
|
|
|
27
26
|
* `taskClass` and a `confidenceBand` - both closed enums - never a raw
|
|
28
27
|
* numeric confidence or a `ThinkingLevel` value. Fusing a hint into a
|
|
29
28
|
* resolved level is out of scope for this module.
|
|
30
|
-
* - No product source
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
* import, so this lane's narrow write scope (this file, its regression
|
|
35
|
-
* test, and its evidence file only) cannot be affected by - or affect -
|
|
36
|
-
* any concurrently-running Wave 1 lane's edits to the router modules. A
|
|
37
|
-
* future wiring lane should keep these enums in sync (or replace the
|
|
38
|
-
* local copies with a shared import) once it deliberately connects this
|
|
39
|
-
* bridge to the router.
|
|
29
|
+
* - No product source is imported here. `AdaptorchTaskClass` /
|
|
30
|
+
* `AdaptorchLaneType` intentionally mirror the v4 task/lane unions by
|
|
31
|
+
* value, not by import, so this bridge remains isolated until a future
|
|
32
|
+
* wiring lane deliberately connects it to the router.
|
|
40
33
|
* - Every outbound/inbound field is a closed enum, a boolean, or a bounded
|
|
41
34
|
* integer, derived from local features only. There is structurally no
|
|
42
35
|
* field shaped to carry prompt text, a prompt hash, a file/working-
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adaptorch-bridge.js","sourceRoot":"","sources":["../../src/core/adaptorch-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AAsDH,MAAM,YAAY,GAAkC;IACnD,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mB,CAAC,MAAM,CAAC,CAAC;AAAA,CACvC","sourcesContent":["/**\n * Reasoning-router AdaptOrch advisory bridge (Goal 009 Lane B).\n *\n * A default-off, advisory-only primitive for a future opt-in reasoning-router\n * hint source. This module is intentionally NOT wired into agent-session.ts,\n * reasoning-router-v2.ts, or reasoning-router-v3.ts by this lane - it only\n * implements the bridge's payload/result schema, sanitize/validate helpers,\n * TTL cache, budget counter, circuit breaker, and timeout wrapper around a\n * caller-injected advisory function. A future lane decides how (or whether)\n * to fuse a returned hint into a resolved ThinkingLevel and to actually call\n * this module from agent-session.ts.\n *\n * Grounded in the read-first plan at\n * .omk/goals/008-reasoning-router-advanced-accuracy-plan/laneC-privacy-adaptorch.md\n * (Part B, sections 4.1-4.11) and the real AdaptOrch MCP tool surface\n * documented in packages/adaptorch-wpl/src/adaptorch-client.ts. Key\n * constraints carried over from that plan:\n *\n * - The router's turn-start path is synchronous and I/O-free today (plan\n * 4.4). This module never calls an MCP transport directly and exposes a\n * synchronous, cache-read-only accessor (`getFreshHint`) plus a\n * fire-and-forget refresh (`requestRefresh`) so a future integration can\n * never block or await this module inline on the turn-start path.\n * - The real, documented AdaptOrch tool surface has no confidence or\n * reasoning-level field (plan 4.3); this module's inbound result type\n * (`AdaptorchAdvisoryResult`) therefore only carries a locally-relevant\n * `taskClass` and a `confidenceBand` - both closed enums - never a raw\n * numeric confidence or a `ThinkingLevel` value. Fusing a hint into a\n * resolved level is out of scope for this module.\n * - No product source (agent-session.ts, reasoning-router-v2/v3.ts,\n * reasoning-router-weights.ts) is imported here. `AdaptorchTaskClass` /\n * `AdaptorchLaneType` intentionally mirror `TaskClassV2` /\n * `ReasoningLaneTypeV2` from reasoning-router-v2.ts by value, not by\n * import, so this lane's narrow write scope (this file, its regression\n * test, and its evidence file only) cannot be affected by - or affect -\n * any concurrently-running Wave 1 lane's edits to the router modules. A\n * future wiring lane should keep these enums in sync (or replace the\n * local copies with a shared import) once it deliberately connects this\n * bridge to the router.\n * - Every outbound/inbound field is a closed enum, a boolean, or a bounded\n * integer, derived from local features only. There is structurally no\n * field shaped to carry prompt text, a prompt hash, a file/working-\n * directory path, a model/provider identifier, a session/user identifier,\n * a tool name, or hook output - the sanitize/validate helpers below also\n * reject any candidate object exposing such a field by name, and reject\n * any key outside the exact closed schema, so a hand-built or forged\n * payload can never smuggle one through either type.\n * - The router-bridge tool allowlist (`ADAPTORCH_READONLY_TOOL_ALLOWLIST`)\n * only ever contains the two read/local AdaptOrch tools the plan\n * identifies as in scope (the session-start capabilities probe and the\n * per-consult topology-classification call, plan 4.2/4.6); the\n * run-submission and run-cancellation tools (and any other mutating\n * tool) can never appear in it, checked both by an exact-value test and\n * by `looksMutatingToolName`'s verb-segment guard.\n *\n * Pure aside from `Date.now`/`setTimeout` (both injectable/wrapped so tests\n * never depend on real wall-clock time or a real MCP call).\n */\n\n/** Closed set of task classes. Mirrors TaskClassV2 in reasoning-router-v2.ts by value (see file header). */\nexport type AdaptorchTaskClass = \"trivial\" | \"simple-edit\" | \"code-gen\" | \"debug\" | \"refactor\" | \"review\" | \"plan\";\n\n/** Closed set of subagent lane types. Mirrors ReasoningLaneTypeV2 in reasoning-router-v2.ts by value. */\nexport type AdaptorchLaneType = \"planner\" | \"security\" | \"explorer\" | \"coder\" | \"reviewer\" | \"tester\";\n\n/** Local top1-vs-runner-up score-margin bucket (plan 4.5 ConsultPayloadV1.marginBucket). */\nexport type AdaptorchMarginBucket = \"tie\" | \"low\" | \"medium\" | \"high\";\n\n/** Locally-derived confidence band for a returned hint. Never a raw network-supplied float (plan 4.3). */\nexport type AdaptorchConfidenceBand = \"low\" | \"medium\" | \"high\";\n\n/** floor(log2(trimmedPromptLen+1)) clamped to [0,7] - same bucketing as reasoning-router-v2.ts's clampLenBucket. */\nexport type AdaptorchLenBucket = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;\n\n/** Context-pressure band 0..3 - same bucketing as agent-session.ts's _computePressureBucket. */\nexport type AdaptorchPressureBucket = 0 | 1 | 2 | 3;\n\n/**\n * Outbound advisory request (plan 4.5, field names adapted for this lane's\n * assignment: taskClass/runnerUp/marginBucket/lenBucket/hadFence/hadDiff/\n * pressureBucket/laneType). Every field is a closed enum, a boolean, or a\n * bounded integer built from local classifier features only. Structurally\n * excludes prompt text/hash, file paths, model/provider/session\n * identifiers, tool names, and hook output - there is no field shaped to\n * carry any of those.\n */\nexport interface AdaptorchConsultPayload {\n\treadonly schemaVersion: 1;\n\treadonly taskClass: AdaptorchTaskClass;\n\treadonly runnerUp: AdaptorchTaskClass;\n\treadonly marginBucket: AdaptorchMarginBucket;\n\treadonly lenBucket: AdaptorchLenBucket;\n\treadonly hadFence: boolean;\n\treadonly hadDiff: boolean;\n\treadonly pressureBucket: AdaptorchPressureBucket;\n\treadonly laneType?: AdaptorchLaneType;\n}\n\n/**\n * Inbound advisory result after local sanitation (plan 4.3, corrected\n * schema). `confidenceBand` is always synthesized/validated locally - the\n * real AdaptOrch tool contract carries no confidence or effort-level field,\n * so this type never trusts a raw numeric confidence from the advisory\n * function.\n */\nexport interface AdaptorchAdvisoryResult {\n\treadonly schemaVersion: 1;\n\treadonly taskClass: AdaptorchTaskClass;\n\treadonly confidenceBand: AdaptorchConfidenceBand;\n}\n\nconst TASK_CLASSES: readonly AdaptorchTaskClass[] = [\n\t\"trivial\",\n\t\"simple-edit\",\n\t\"code-gen\",\n\t\"debug\",\n\t\"refactor\",\n\t\"review\",\n\t\"plan\",\n];\nconst TASK_CLASS_SET: ReadonlySet<string> = new Set(TASK_CLASSES);\n\nconst LANE_TYPES: readonly AdaptorchLaneType[] = [\"planner\", \"security\", \"explorer\", \"coder\", \"reviewer\", \"tester\"];\nconst LANE_TYPE_SET: ReadonlySet<string> = new Set(LANE_TYPES);\n\nconst MARGIN_BUCKETS: readonly AdaptorchMarginBucket[] = [\"tie\", \"low\", \"medium\", \"high\"];\nconst MARGIN_BUCKET_SET: ReadonlySet<string> = new Set(MARGIN_BUCKETS);\n\nconst CONFIDENCE_BANDS: readonly AdaptorchConfidenceBand[] = [\"low\", \"medium\", \"high\"];\nconst CONFIDENCE_BAND_SET: ReadonlySet<string> = new Set(CONFIDENCE_BANDS);\n\nconst CONSULT_PAYLOAD_KEYS: ReadonlySet<string> = new Set([\n\t\"schemaVersion\",\n\t\"taskClass\",\n\t\"runnerUp\",\n\t\"marginBucket\",\n\t\"lenBucket\",\n\t\"hadFence\",\n\t\"hadDiff\",\n\t\"pressureBucket\",\n\t\"laneType\",\n]);\n\nconst ADVISORY_RESULT_KEYS: ReadonlySet<string> = new Set([\"schemaVersion\", \"taskClass\", \"confidenceBand\"]);\n\n/**\n * Field-name markers that must never appear on a payload or result object,\n * checked case-insensitively as a substring of every own key. This is\n * defense-in-depth alongside the exact-key allowlist below: even a candidate\n * that otherwise has every required field still fails if it also carries a\n * field shaped like a stored prompt, hash, path, model/provider identifier,\n * session identifier, tool name, or hook output.\n */\nconst FORBIDDEN_KEY_SUBSTRINGS: readonly string[] = [\n\t\"prompt\",\n\t\"hash\",\n\t\"path\",\n\t\"model\",\n\t\"session\",\n\t\"tool\",\n\t\"hook\",\n\t\"provider\",\n];\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * True if any own key of `record` contains a forbidden field-name marker\n * (case-insensitive). Typed `object` rather than `Record<string, unknown>` so\n * callers (including tests) can pass any concrete object shape - named\n * interface, ad-hoc literal, or an already-`Record`-typed value - without a\n * missing-index-signature type error; only `Object.keys` is used internally,\n * which accepts any `object`.\n */\nexport function containsForbiddenField(record: object): boolean {\n\tfor (const key of Object.keys(record)) {\n\t\tconst lowerKey = key.toLowerCase();\n\t\tif (FORBIDDEN_KEY_SUBSTRINGS.some((needle) => lowerKey.includes(needle))) return true;\n\t}\n\treturn false;\n}\n\nfunction hasOnlyAllowedKeys(record: Record<string, unknown>, allowed: ReadonlySet<string>): boolean {\n\treturn Object.keys(record).every((key) => allowed.has(key));\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n\tconst truncated = Number.isFinite(value) ? Math.trunc(value) : min;\n\tif (truncated < min) return min;\n\tif (truncated > max) return max;\n\treturn truncated;\n}\n\nfunction clampLenBucket(value: number): AdaptorchLenBucket {\n\treturn clampInt(value, 0, 7) as AdaptorchLenBucket;\n}\n\nfunction clampPressureBucket(value: number): AdaptorchPressureBucket {\n\treturn clampInt(value, 0, 3) as AdaptorchPressureBucket;\n}\n\n/** `value ?? fallback`, coerced to an integer and floored at `min` (used for config, not untrusted payloads). */\nfunction boundedIntOrDefault(value: number | undefined, fallback: number, min: number): number {\n\tconst raw = value ?? fallback;\n\tif (!Number.isFinite(raw)) return fallback;\n\treturn Math.max(min, Math.trunc(raw));\n}\n\n/**\n * Sanitize/validate an outbound advisory request. Returns `null` (never\n * throws) when `candidate` is not a plain object, carries a forbidden-named\n * field, carries any key outside the exact closed schema, or has a\n * wrong-typed/unknown-enum field. `lenBucket`/`pressureBucket` are clamped\n * into their bounded ranges rather than rejected, so a caller-side rounding\n * or edge-case computation can never smuggle an out-of-range integer through.\n */\nexport function sanitizeConsultPayload(candidate: unknown): AdaptorchConsultPayload | null {\n\tif (!isPlainObject(candidate)) return null;\n\tif (containsForbiddenField(candidate)) return null;\n\tif (!hasOnlyAllowedKeys(candidate, CONSULT_PAYLOAD_KEYS)) return null;\n\n\tif (candidate.schemaVersion !== 1) return null;\n\n\tconst taskClass = candidate.taskClass;\n\tif (typeof taskClass !== \"string\" || !TASK_CLASS_SET.has(taskClass)) return null;\n\n\tconst runnerUp = candidate.runnerUp;\n\tif (typeof runnerUp !== \"string\" || !TASK_CLASS_SET.has(runnerUp)) return null;\n\n\tconst marginBucket = candidate.marginBucket;\n\tif (typeof marginBucket !== \"string\" || !MARGIN_BUCKET_SET.has(marginBucket)) return null;\n\n\tconst lenBucketRaw = candidate.lenBucket;\n\tif (typeof lenBucketRaw !== \"number\") return null;\n\n\tconst pressureBucketRaw = candidate.pressureBucket;\n\tif (typeof pressureBucketRaw !== \"number\") return null;\n\n\tconst hadFence = candidate.hadFence;\n\tif (typeof hadFence !== \"boolean\") return null;\n\n\tconst hadDiff = candidate.hadDiff;\n\tif (typeof hadDiff !== \"boolean\") return null;\n\n\tconst laneTypeRaw = candidate.laneType;\n\tlet laneType: AdaptorchLaneType | undefined;\n\tif (laneTypeRaw !== undefined) {\n\t\tif (typeof laneTypeRaw !== \"string\" || !LANE_TYPE_SET.has(laneTypeRaw)) return null;\n\t\tlaneType = laneTypeRaw as AdaptorchLaneType;\n\t}\n\n\treturn {\n\t\tschemaVersion: 1,\n\t\ttaskClass: taskClass as AdaptorchTaskClass,\n\t\trunnerUp: runnerUp as AdaptorchTaskClass,\n\t\tmarginBucket: marginBucket as AdaptorchMarginBucket,\n\t\tlenBucket: clampLenBucket(lenBucketRaw),\n\t\thadFence,\n\t\thadDiff,\n\t\tpressureBucket: clampPressureBucket(pressureBucketRaw),\n\t\t...(laneType !== undefined ? { laneType } : {}),\n\t};\n}\n\n/**\n * Sanitize/validate an inbound advisory result (i.e. whatever the injected\n * advisory function returned). Returns `null` (never throws) on any shape,\n * forbidden-field, extra-key, or unknown-enum violation - the caller\n * (`AdaptorchBridge.consult`) treats `null` as \"no hint\" and falls back\n * silently, exactly like every other failure mode.\n */\nexport function sanitizeAdvisoryResult(candidate: unknown): AdaptorchAdvisoryResult | null {\n\tif (!isPlainObject(candidate)) return null;\n\tif (containsForbiddenField(candidate)) return null;\n\tif (!hasOnlyAllowedKeys(candidate, ADVISORY_RESULT_KEYS)) return null;\n\n\tif (candidate.schemaVersion !== 1) return null;\n\n\tconst taskClass = candidate.taskClass;\n\tif (typeof taskClass !== \"string\" || !TASK_CLASS_SET.has(taskClass)) return null;\n\n\tconst confidenceBand = candidate.confidenceBand;\n\tif (typeof confidenceBand !== \"string\" || !CONFIDENCE_BAND_SET.has(confidenceBand)) return null;\n\n\treturn {\n\t\tschemaVersion: 1,\n\t\ttaskClass: taskClass as AdaptorchTaskClass,\n\t\tconfidenceBand: confidenceBand as AdaptorchConfidenceBand,\n\t};\n}\n\n/**\n * Read-only/local AdaptOrch MCP tool names this bridge may ever reference,\n * grounded in the real 10-tool surface documented in\n * packages/adaptorch-wpl/src/adaptorch-client.ts (cross-checked there\n * against the AdaptOrch server's own docs) and narrowed to the two tools the\n * read-first plan puts in scope for a reasoning-effort hint (plan 4.2): the\n * session-start capabilities probe and the per-consult topology\n * classification call. This module does not call any MCP tool directly\n * today - the advisory function is fully caller-injected - so this\n * allowlist is not wired to a transport here; it exists so a future\n * transport, and this module's own tests, can assert by construction that\n * `adaptorch_run` (submit) and `adaptorch_cancel_run` (cancel), or any other\n * mutating tool, can never be reachable from router/bridge code.\n */\nexport const ADAPTORCH_READONLY_TOOL_ALLOWLIST = [\"adaptorch_capabilities\", \"adaptorch_route_topology\"] as const;\n\nexport type AdaptorchReadonlyToolName = (typeof ADAPTORCH_READONLY_TOOL_ALLOWLIST)[number];\n\n/** Underscore-segment verbs that mark an AdaptOrch-shaped tool name as mutating (write/execute/lifecycle). */\nconst MUTATING_TOOL_VERB_SEGMENTS: ReadonlySet<string> = new Set([\n\t\"run\",\n\t\"submit\",\n\t\"cancel\",\n\t\"dispatch\",\n\t\"delete\",\n\t\"execute\",\n\t\"mutate\",\n\t\"write\",\n\t\"create\",\n\t\"update\",\n\t\"remove\",\n]);\n\n/**\n * True if any underscore-delimited segment of an AdaptOrch-shaped tool name\n * is a known mutating verb. Segment-based rather than a raw substring/regex\n * match so \"adaptorch_route_topology\" is never falsely flagged (no segment\n * is a mutating verb), while \"adaptorch_run\" and \"adaptorch_cancel_run\" are\n * always caught regardless of future prefix/suffix changes.\n */\nexport function looksMutatingToolName(name: string): boolean {\n\treturn name\n\t\t.toLowerCase()\n\t\t.split(\"_\")\n\t\t.some((segment) => MUTATING_TOOL_VERB_SEGMENTS.has(segment));\n}\n\n/**\n * Type guard: true only for the two allowlisted read/local AdaptOrch tool\n * names. Also independently rejects any name `looksMutatingToolName` flags,\n * so a future accidental addition of a mutating name to the allowlist array\n * still cannot make this function report it as allowed.\n */\nexport function isAdaptorchToolAllowed(name: string): name is AdaptorchReadonlyToolName {\n\tif (looksMutatingToolName(name)) return false;\n\treturn (ADAPTORCH_READONLY_TOOL_ALLOWLIST as readonly string[]).includes(name);\n}\n\n/**\n * Timeout wrapper interface around any injected async advisory call. Races\n * the call against a timer; a slow or hung call rejects at `timeoutMs`\n * instead of leaving the caller waiting indefinitely. Always clears the\n * timer once the call settles (or once the timeout itself fires), and\n * always resolves/rejects exactly once - a synchronous throw from `run` is\n * treated the same as an asynchronous rejection.\n */\nexport type AdvisoryTimeoutWrapper = <T>(run: () => Promise<T>, timeoutMs: number) => Promise<T>;\n\nexport const withAdvisoryTimeout: AdvisoryTimeoutWrapper = <T>(\n\trun: () => Promise<T>,\n\ttimeoutMs: number,\n): Promise<T> => {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\treject(new Error(\"adaptorch-bridge: advisory call timed out\"));\n\t\t}, timeoutMs);\n\n\t\tlet pending: Promise<T>;\n\t\ttry {\n\t\t\tpending = run();\n\t\t} catch (err) {\n\t\t\tclearTimeout(timer);\n\t\t\treject(err instanceof Error ? err : new Error(String(err)));\n\t\t\treturn;\n\t\t}\n\n\t\tpending.then(\n\t\t\t(value) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(err: unknown) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(err instanceof Error ? err : new Error(String(err)));\n\t\t\t},\n\t\t);\n\t});\n};\n\nconst DEFAULT_TTL_MS = 5 * 60 * 1000;\nconst MIN_TTL_MS = 30 * 1000;\nconst MAX_TTL_MS = 5 * 60 * 1000;\nconst DEFAULT_MAX_TURNS_PER_ENTRY = 10;\nconst DEFAULT_CACHE_SIZE = 16;\nconst DEFAULT_MAX_CONSULTS_PER_SESSION = 5;\nconst DEFAULT_MIN_INTERVAL_MS = 60 * 1000;\nconst DEFAULT_TIMEOUT_MS = 1500;\nconst MIN_TIMEOUT_MS = 1;\nconst MAX_TIMEOUT_MS = 30 * 1000;\nconst DEFAULT_FAILURE_THRESHOLD = 3;\nconst DEFAULT_COOLDOWN_MS = 10 * 60 * 1000;\n\n/**\n * Exact TTL/cache/budget/circuit-breaker defaults from the read-first plan,\n * section 4.8. Exported so a security/review lane can confirm the shipped\n * numbers without reading this module's internals.\n */\nexport const ADAPTORCH_BRIDGE_DEFAULTS = {\n\tttlMs: DEFAULT_TTL_MS,\n\tminTtlMs: MIN_TTL_MS,\n\tmaxTtlMs: MAX_TTL_MS,\n\tmaxTurnsPerEntry: DEFAULT_MAX_TURNS_PER_ENTRY,\n\tcacheSize: DEFAULT_CACHE_SIZE,\n\tmaxConsultsPerSession: DEFAULT_MAX_CONSULTS_PER_SESSION,\n\tminIntervalMs: DEFAULT_MIN_INTERVAL_MS,\n\ttimeoutMs: DEFAULT_TIMEOUT_MS,\n\tminTimeoutMs: MIN_TIMEOUT_MS,\n\tmaxTimeoutMs: MAX_TIMEOUT_MS,\n\tfailureThreshold: DEFAULT_FAILURE_THRESHOLD,\n\tcooldownMs: DEFAULT_COOLDOWN_MS,\n} as const;\n\n/**\n * Bridge configuration. `advisoryFn` is the ONLY seam to any external\n * system - this module never imports or calls an MCP client/transport\n * itself, so it is impossible for a unit test (or a misconfigured caller)\n * to reach a real MCP server through this module by accident.\n */\nexport interface AdaptorchBridgeConfig {\n\t/**\n\t * Caller-injected advisory call. Its return value is untrusted: `consult`\n\t * always runs it through `sanitizeAdvisoryResult` before using or caching\n\t * it, and a rejected/thrown/timed-out/schema-invalid response is treated\n\t * as an ordinary failure (counts toward the circuit breaker), never as a\n\t * value to fuse.\n\t */\n\treadonly advisoryFn: (payload: AdaptorchConsultPayload) => Promise<unknown>;\n\t/** Injectable clock; defaults to `Date.now`. Tests supply a fake to avoid real wall-clock waits. */\n\treadonly now?: () => number;\n\t/** Cache TTL in ms; clamped to [30s, 5min] (plan 4.8). Default 5 minutes. */\n\treadonly ttlMs?: number;\n\t/** A cache entry also expires after this many `getFreshHint` calls (\"turns\"). Default 10. */\n\treadonly maxTurnsPerEntry?: number;\n\t/** Max distinct cached payload keys (LRU eviction beyond this). Default 16. */\n\treadonly cacheSize?: number;\n\t/** Max advisory attempts for this bridge instance's lifetime (\"session\"). Default 5. */\n\treadonly maxConsultsPerSession?: number;\n\t/** Minimum ms between advisory attempts. Default 60000 (60s). */\n\treadonly minIntervalMs?: number;\n\t/** Per-attempt timeout in ms; clamped to [1ms, 30s]. Default 1500 (1.5s). */\n\treadonly timeoutMs?: number;\n\t/** Consecutive failures before the circuit opens. Default 3. */\n\treadonly failureThreshold?: number;\n\t/** Circuit-open duration in ms once opened. Default 600000 (10min). */\n\treadonly cooldownMs?: number;\n}\n\n/** Read-only, non-sensitive introspection snapshot - never exposes payload/result content. */\nexport interface AdaptorchBridgeStats {\n\treadonly consultCount: number;\n\treadonly failureStreak: number;\n\treadonly circuitOpen: boolean;\n\treadonly circuitOpenUntilMs: number;\n\treadonly cacheEntryCount: number;\n}\n\nexport interface AdaptorchBridge {\n\t/**\n\t * Synchronous, cache-read-only. Never blocks, never throws, and never\n\t * calls the advisory function - a cache miss or an expired/invalid entry\n\t * silently returns `null` (\"no hint\"), matching the turn-start path's\n\t * synchronous, I/O-free contract (plan 4.4).\n\t */\n\tgetFreshHint(payload: AdaptorchConsultPayload): AdaptorchAdvisoryResult | null;\n\t/**\n\t * Fire-and-forget refresh for a LATER call to `getFreshHint`, never the\n\t * current one. Never throws synchronously and never rejects into the\n\t * caller - any failure is swallowed internally by `consult`.\n\t */\n\trequestRefresh(payload: AdaptorchConsultPayload): void;\n\t/**\n\t * The awaitable core operation `requestRefresh` fires without awaiting.\n\t * Gated by the circuit breaker, budget counter, and minimum interval (in\n\t * that order) before ever invoking `advisoryFn`; always resolves (never\n\t * rejects) to either a sanitized hint or `null`.\n\t */\n\tconsult(payload: AdaptorchConsultPayload): Promise<AdaptorchAdvisoryResult | null>;\n\t/** Read-only introspection for tests/diagnostics; contains no payload or result content. */\n\tgetStats(): AdaptorchBridgeStats;\n}\n\ninterface CacheEntry {\n\treadonly result: AdaptorchAdvisoryResult;\n\treadonly insertedAtMs: number;\n\treadonly insertedAtTurn: number;\n}\n\n/** Deterministic cache key built field-by-field from a sanitized payload - never from raw prompt text. */\nfunction cacheKeyFor(payload: AdaptorchConsultPayload): string {\n\treturn JSON.stringify({\n\t\ttaskClass: payload.taskClass,\n\t\trunnerUp: payload.runnerUp,\n\t\tmarginBucket: payload.marginBucket,\n\t\tlenBucket: payload.lenBucket,\n\t\thadFence: payload.hadFence,\n\t\thadDiff: payload.hadDiff,\n\t\tpressureBucket: payload.pressureBucket,\n\t\tlaneType: payload.laneType ?? null,\n\t});\n}\n\nclass AdaptorchBridgeImpl implements AdaptorchBridge {\n\tprivate readonly advisoryFn: (payload: AdaptorchConsultPayload) => Promise<unknown>;\n\tprivate readonly now: () => number;\n\tprivate readonly ttlMs: number;\n\tprivate readonly maxTurnsPerEntry: number;\n\tprivate readonly cacheSize: number;\n\tprivate readonly maxConsultsPerSession: number;\n\tprivate readonly minIntervalMs: number;\n\tprivate readonly timeoutMs: number;\n\tprivate readonly failureThreshold: number;\n\tprivate readonly cooldownMs: number;\n\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\tprivate turnCounter = 0;\n\tprivate consultCount = 0;\n\tprivate failureStreak = 0;\n\tprivate lastAttemptAtMs: number | null = null;\n\tprivate circuitOpenUntilMs = 0;\n\n\tconstructor(config: AdaptorchBridgeConfig) {\n\t\tthis.advisoryFn = config.advisoryFn;\n\t\tthis.now = config.now ?? Date.now;\n\t\tthis.ttlMs = clampInt(config.ttlMs ?? DEFAULT_TTL_MS, MIN_TTL_MS, MAX_TTL_MS);\n\t\tthis.maxTurnsPerEntry = boundedIntOrDefault(config.maxTurnsPerEntry, DEFAULT_MAX_TURNS_PER_ENTRY, 1);\n\t\tthis.cacheSize = boundedIntOrDefault(config.cacheSize, DEFAULT_CACHE_SIZE, 1);\n\t\tthis.maxConsultsPerSession = boundedIntOrDefault(\n\t\t\tconfig.maxConsultsPerSession,\n\t\t\tDEFAULT_MAX_CONSULTS_PER_SESSION,\n\t\t\t0,\n\t\t);\n\t\tthis.minIntervalMs = boundedIntOrDefault(config.minIntervalMs, DEFAULT_MIN_INTERVAL_MS, 0);\n\t\tthis.timeoutMs = clampInt(config.timeoutMs ?? DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS);\n\t\tthis.failureThreshold = boundedIntOrDefault(config.failureThreshold, DEFAULT_FAILURE_THRESHOLD, 1);\n\t\tthis.cooldownMs = boundedIntOrDefault(config.cooldownMs, DEFAULT_COOLDOWN_MS, 0);\n\t}\n\n\tgetFreshHint(payload: AdaptorchConsultPayload): AdaptorchAdvisoryResult | null {\n\t\tthis.turnCounter += 1;\n\t\tconst sanitizedPayload = sanitizeConsultPayload(payload);\n\t\tif (sanitizedPayload === null) return null;\n\n\t\tconst key = cacheKeyFor(sanitizedPayload);\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry === undefined) return null;\n\t\tif (!this.isEntryFresh(entry)) {\n\t\t\tthis.cache.delete(key);\n\t\t\treturn null;\n\t\t}\n\t\treturn entry.result;\n\t}\n\n\trequestRefresh(payload: AdaptorchConsultPayload): void {\n\t\tvoid this.consult(payload).catch(() => {\n\t\t\t// consult() already swallows every failure and always resolves; this\n\t\t\t// catch only guards a future refactor from letting one escape, so a\n\t\t\t// fire-and-forget refresh can never surface an unhandled rejection.\n\t\t});\n\t}\n\n\tasync consult(payload: AdaptorchConsultPayload): Promise<AdaptorchAdvisoryResult | null> {\n\t\tconst sanitizedPayload = sanitizeConsultPayload(payload);\n\t\tif (sanitizedPayload === null) return null;\n\n\t\tconst nowMs = this.now();\n\t\tif (nowMs < this.circuitOpenUntilMs) return null;\n\t\tif (this.consultCount >= this.maxConsultsPerSession) return null;\n\t\tif (this.lastAttemptAtMs !== null && nowMs - this.lastAttemptAtMs < this.minIntervalMs) return null;\n\n\t\tthis.consultCount += 1;\n\t\tthis.lastAttemptAtMs = nowMs;\n\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = await withAdvisoryTimeout(() => this.advisoryFn(sanitizedPayload), this.timeoutMs);\n\t\t} catch {\n\t\t\tthis.recordFailure();\n\t\t\treturn null;\n\t\t}\n\n\t\tconst result = sanitizeAdvisoryResult(raw);\n\t\tif (result === null) {\n\t\t\tthis.recordFailure();\n\t\t\treturn null;\n\t\t}\n\n\t\tthis.failureStreak = 0;\n\t\tthis.cacheResult(sanitizedPayload, result);\n\t\treturn result;\n\t}\n\n\tgetStats(): AdaptorchBridgeStats {\n\t\tconst nowMs = this.now();\n\t\treturn {\n\t\t\tconsultCount: this.consultCount,\n\t\t\tfailureStreak: this.failureStreak,\n\t\t\tcircuitOpen: nowMs < this.circuitOpenUntilMs,\n\t\t\tcircuitOpenUntilMs: this.circuitOpenUntilMs,\n\t\t\tcacheEntryCount: this.cache.size,\n\t\t};\n\t}\n\n\tprivate recordFailure(): void {\n\t\tthis.failureStreak += 1;\n\t\tif (this.failureStreak >= this.failureThreshold) {\n\t\t\tthis.circuitOpenUntilMs = this.now() + this.cooldownMs;\n\t\t}\n\t}\n\n\tprivate isEntryFresh(entry: CacheEntry): boolean {\n\t\tconst ageMs = this.now() - entry.insertedAtMs;\n\t\tconst ageTurns = this.turnCounter - entry.insertedAtTurn;\n\t\treturn ageMs < this.ttlMs && ageTurns < this.maxTurnsPerEntry;\n\t}\n\n\t/** Eviction favors entries last refreshed by a successful consult (write-time LRU, not read-time). */\n\tprivate cacheResult(payload: AdaptorchConsultPayload, result: AdaptorchAdvisoryResult): void {\n\t\tconst key = cacheKeyFor(payload);\n\t\tif (this.cache.has(key)) this.cache.delete(key);\n\t\tthis.cache.set(key, { result, insertedAtMs: this.now(), insertedAtTurn: this.turnCounter });\n\t\twhile (this.cache.size > this.cacheSize) {\n\t\t\tconst oldestKey = this.cache.keys().next().value;\n\t\t\tif (oldestKey === undefined) break;\n\t\t\tthis.cache.delete(oldestKey);\n\t\t}\n\t}\n}\n\n/** Construct a default-off AdaptOrch advisory bridge. See `AdaptorchBridgeConfig` for tunables. */\nexport function createAdaptorchBridge(config: AdaptorchBridgeConfig): AdaptorchBridge {\n\treturn new AdaptorchBridgeImpl(config);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"adaptorch-bridge.js","sourceRoot":"","sources":["../../src/core/adaptorch-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AAsDH,MAAM,YAAY,GAAkC;IACnD,SAAS;IACT,aAAa;IACb,UAAU;IACV,OAAO;IACP,UAAU;IACV,QAAQ;IACR,MAAM;CACN,CAAC;AACF,MAAM,cAAc,GAAwB,IAAI,GAAG,CAAC,YAAY,CAAC,CAAC;AAElE,MAAM,UAAU,GAAiC,CAAC,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC;AACpH,MAAM,aAAa,GAAwB,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC;AAE/D,MAAM,cAAc,GAAqC,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AAC1F,MAAM,iBAAiB,GAAwB,IAAI,GAAG,CAAC,cAAc,CAAC,CAAC;AAEvE,MAAM,gBAAgB,GAAuC,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AACvF,MAAM,mBAAmB,GAAwB,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;AAE3E,MAAM,oBAAoB,GAAwB,IAAI,GAAG,CAAC;IACzD,eAAe;IACf,WAAW;IACX,UAAU;IACV,cAAc;IACd,WAAW;IACX,UAAU;IACV,SAAS;IACT,gBAAgB;IAChB,UAAU;CACV,CAAC,CAAC;AAEH,MAAM,oBAAoB,GAAwB,IAAI,GAAG,CAAC,CA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E,CAAC,CAAC;QAC5F,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;YACzC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;YACjD,IAAI,SAAS,KAAK,SAAS;gBAAE,MAAM;YACnC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC9B,CAAC;IAAA,CACD;CACD;AAED,mGAAmG;AACnG,MAAM,UAAU,qBAAqB,CAAC,MAA6B,EAAmB;IACrF,OAAO,IAAI,mBAAmB,CAAC,MAAM,CAAC,CAAC;AAAA,CACvC","sourcesContent":["/**\n * Reasoning-router AdaptOrch advisory bridge (Goal 009 Lane B).\n *\n * A default-off, advisory-only primitive for a future reasoning-router hint\n * source. This module is intentionally NOT wired into agent-session.ts; it only\n * implements the bridge's payload/result schema, sanitize/validate helpers, TTL\n * cache, budget counter, circuit breaker, and timeout wrapper around a\n * caller-injected advisory function. A future lane decides how (or whether) to\n * fuse a returned hint into a resolved ThinkingLevel and to actually call this\n * module from agent-session.ts.\n *\n * Grounded in the read-first plan at\n * .omk/goals/008-reasoning-router-advanced-accuracy-plan/laneC-privacy-adaptorch.md\n * (Part B, sections 4.1-4.11) and the real AdaptOrch MCP tool surface\n * documented in packages/adaptorch-wpl/src/adaptorch-client.ts. Key\n * constraints carried over from that plan:\n *\n * - The router's turn-start path is synchronous and I/O-free today (plan\n * 4.4). This module never calls an MCP transport directly and exposes a\n * synchronous, cache-read-only accessor (`getFreshHint`) plus a\n * fire-and-forget refresh (`requestRefresh`) so a future integration can\n * never block or await this module inline on the turn-start path.\n * - The real, documented AdaptOrch tool surface has no confidence or\n * reasoning-level field (plan 4.3); this module's inbound result type\n * (`AdaptorchAdvisoryResult`) therefore only carries a locally-relevant\n * `taskClass` and a `confidenceBand` - both closed enums - never a raw\n * numeric confidence or a `ThinkingLevel` value. Fusing a hint into a\n * resolved level is out of scope for this module.\n * - No product source is imported here. `AdaptorchTaskClass` /\n * `AdaptorchLaneType` intentionally mirror the v4 task/lane unions by\n * value, not by import, so this bridge remains isolated until a future\n * wiring lane deliberately connects it to the router.\n * - Every outbound/inbound field is a closed enum, a boolean, or a bounded\n * integer, derived from local features only. There is structurally no\n * field shaped to carry prompt text, a prompt hash, a file/working-\n * directory path, a model/provider identifier, a session/user identifier,\n * a tool name, or hook output - the sanitize/validate helpers below also\n * reject any candidate object exposing such a field by name, and reject\n * any key outside the exact closed schema, so a hand-built or forged\n * payload can never smuggle one through either type.\n * - The router-bridge tool allowlist (`ADAPTORCH_READONLY_TOOL_ALLOWLIST`)\n * only ever contains the two read/local AdaptOrch tools the plan\n * identifies as in scope (the session-start capabilities probe and the\n * per-consult topology-classification call, plan 4.2/4.6); the\n * run-submission and run-cancellation tools (and any other mutating\n * tool) can never appear in it, checked both by an exact-value test and\n * by `looksMutatingToolName`'s verb-segment guard.\n *\n * Pure aside from `Date.now`/`setTimeout` (both injectable/wrapped so tests\n * never depend on real wall-clock time or a real MCP call).\n */\n\n/** Closed set of task classes. Mirrors the v4 task-class union by value (see file header). */\nexport type AdaptorchTaskClass = \"trivial\" | \"simple-edit\" | \"code-gen\" | \"debug\" | \"refactor\" | \"review\" | \"plan\";\n\n/** Closed set of subagent lane types. Mirrors the v4 lane union by value. */\nexport type AdaptorchLaneType = \"planner\" | \"security\" | \"explorer\" | \"coder\" | \"reviewer\" | \"tester\";\n\n/** Local top1-vs-runner-up score-margin bucket (plan 4.5 ConsultPayloadV1.marginBucket). */\nexport type AdaptorchMarginBucket = \"tie\" | \"low\" | \"medium\" | \"high\";\n\n/** Locally-derived confidence band for a returned hint. Never a raw network-supplied float (plan 4.3). */\nexport type AdaptorchConfidenceBand = \"low\" | \"medium\" | \"high\";\n\n/** floor(log2(trimmedPromptLen+1)) clamped to [0,7]. */\nexport type AdaptorchLenBucket = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;\n\n/** Context-pressure band 0..3 - same bucketing as agent-session.ts's _computePressureBucket. */\nexport type AdaptorchPressureBucket = 0 | 1 | 2 | 3;\n\n/**\n * Outbound advisory request (plan 4.5, field names adapted for this lane's\n * assignment: taskClass/runnerUp/marginBucket/lenBucket/hadFence/hadDiff/\n * pressureBucket/laneType). Every field is a closed enum, a boolean, or a\n * bounded integer built from local classifier features only. Structurally\n * excludes prompt text/hash, file paths, model/provider/session\n * identifiers, tool names, and hook output - there is no field shaped to\n * carry any of those.\n */\nexport interface AdaptorchConsultPayload {\n\treadonly schemaVersion: 1;\n\treadonly taskClass: AdaptorchTaskClass;\n\treadonly runnerUp: AdaptorchTaskClass;\n\treadonly marginBucket: AdaptorchMarginBucket;\n\treadonly lenBucket: AdaptorchLenBucket;\n\treadonly hadFence: boolean;\n\treadonly hadDiff: boolean;\n\treadonly pressureBucket: AdaptorchPressureBucket;\n\treadonly laneType?: AdaptorchLaneType;\n}\n\n/**\n * Inbound advisory result after local sanitation (plan 4.3, corrected\n * schema). `confidenceBand` is always synthesized/validated locally - the\n * real AdaptOrch tool contract carries no confidence or effort-level field,\n * so this type never trusts a raw numeric confidence from the advisory\n * function.\n */\nexport interface AdaptorchAdvisoryResult {\n\treadonly schemaVersion: 1;\n\treadonly taskClass: AdaptorchTaskClass;\n\treadonly confidenceBand: AdaptorchConfidenceBand;\n}\n\nconst TASK_CLASSES: readonly AdaptorchTaskClass[] = [\n\t\"trivial\",\n\t\"simple-edit\",\n\t\"code-gen\",\n\t\"debug\",\n\t\"refactor\",\n\t\"review\",\n\t\"plan\",\n];\nconst TASK_CLASS_SET: ReadonlySet<string> = new Set(TASK_CLASSES);\n\nconst LANE_TYPES: readonly AdaptorchLaneType[] = [\"planner\", \"security\", \"explorer\", \"coder\", \"reviewer\", \"tester\"];\nconst LANE_TYPE_SET: ReadonlySet<string> = new Set(LANE_TYPES);\n\nconst MARGIN_BUCKETS: readonly AdaptorchMarginBucket[] = [\"tie\", \"low\", \"medium\", \"high\"];\nconst MARGIN_BUCKET_SET: ReadonlySet<string> = new Set(MARGIN_BUCKETS);\n\nconst CONFIDENCE_BANDS: readonly AdaptorchConfidenceBand[] = [\"low\", \"medium\", \"high\"];\nconst CONFIDENCE_BAND_SET: ReadonlySet<string> = new Set(CONFIDENCE_BANDS);\n\nconst CONSULT_PAYLOAD_KEYS: ReadonlySet<string> = new Set([\n\t\"schemaVersion\",\n\t\"taskClass\",\n\t\"runnerUp\",\n\t\"marginBucket\",\n\t\"lenBucket\",\n\t\"hadFence\",\n\t\"hadDiff\",\n\t\"pressureBucket\",\n\t\"laneType\",\n]);\n\nconst ADVISORY_RESULT_KEYS: ReadonlySet<string> = new Set([\"schemaVersion\", \"taskClass\", \"confidenceBand\"]);\n\n/**\n * Field-name markers that must never appear on a payload or result object,\n * checked case-insensitively as a substring of every own key. This is\n * defense-in-depth alongside the exact-key allowlist below: even a candidate\n * that otherwise has every required field still fails if it also carries a\n * field shaped like a stored prompt, hash, path, model/provider identifier,\n * session identifier, tool name, or hook output.\n */\nconst FORBIDDEN_KEY_SUBSTRINGS: readonly string[] = [\n\t\"prompt\",\n\t\"hash\",\n\t\"path\",\n\t\"model\",\n\t\"session\",\n\t\"tool\",\n\t\"hook\",\n\t\"provider\",\n];\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * True if any own key of `record` contains a forbidden field-name marker\n * (case-insensitive). Typed `object` rather than `Record<string, unknown>` so\n * callers (including tests) can pass any concrete object shape - named\n * interface, ad-hoc literal, or an already-`Record`-typed value - without a\n * missing-index-signature type error; only `Object.keys` is used internally,\n * which accepts any `object`.\n */\nexport function containsForbiddenField(record: object): boolean {\n\tfor (const key of Object.keys(record)) {\n\t\tconst lowerKey = key.toLowerCase();\n\t\tif (FORBIDDEN_KEY_SUBSTRINGS.some((needle) => lowerKey.includes(needle))) return true;\n\t}\n\treturn false;\n}\n\nfunction hasOnlyAllowedKeys(record: Record<string, unknown>, allowed: ReadonlySet<string>): boolean {\n\treturn Object.keys(record).every((key) => allowed.has(key));\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n\tconst truncated = Number.isFinite(value) ? Math.trunc(value) : min;\n\tif (truncated < min) return min;\n\tif (truncated > max) return max;\n\treturn truncated;\n}\n\nfunction clampLenBucket(value: number): AdaptorchLenBucket {\n\treturn clampInt(value, 0, 7) as AdaptorchLenBucket;\n}\n\nfunction clampPressureBucket(value: number): AdaptorchPressureBucket {\n\treturn clampInt(value, 0, 3) as AdaptorchPressureBucket;\n}\n\n/** `value ?? fallback`, coerced to an integer and floored at `min` (used for config, not untrusted payloads). */\nfunction boundedIntOrDefault(value: number | undefined, fallback: number, min: number): number {\n\tconst raw = value ?? fallback;\n\tif (!Number.isFinite(raw)) return fallback;\n\treturn Math.max(min, Math.trunc(raw));\n}\n\n/**\n * Sanitize/validate an outbound advisory request. Returns `null` (never\n * throws) when `candidate` is not a plain object, carries a forbidden-named\n * field, carries any key outside the exact closed schema, or has a\n * wrong-typed/unknown-enum field. `lenBucket`/`pressureBucket` are clamped\n * into their bounded ranges rather than rejected, so a caller-side rounding\n * or edge-case computation can never smuggle an out-of-range integer through.\n */\nexport function sanitizeConsultPayload(candidate: unknown): AdaptorchConsultPayload | null {\n\tif (!isPlainObject(candidate)) return null;\n\tif (containsForbiddenField(candidate)) return null;\n\tif (!hasOnlyAllowedKeys(candidate, CONSULT_PAYLOAD_KEYS)) return null;\n\n\tif (candidate.schemaVersion !== 1) return null;\n\n\tconst taskClass = candidate.taskClass;\n\tif (typeof taskClass !== \"string\" || !TASK_CLASS_SET.has(taskClass)) return null;\n\n\tconst runnerUp = candidate.runnerUp;\n\tif (typeof runnerUp !== \"string\" || !TASK_CLASS_SET.has(runnerUp)) return null;\n\n\tconst marginBucket = candidate.marginBucket;\n\tif (typeof marginBucket !== \"string\" || !MARGIN_BUCKET_SET.has(marginBucket)) return null;\n\n\tconst lenBucketRaw = candidate.lenBucket;\n\tif (typeof lenBucketRaw !== \"number\") return null;\n\n\tconst pressureBucketRaw = candidate.pressureBucket;\n\tif (typeof pressureBucketRaw !== \"number\") return null;\n\n\tconst hadFence = candidate.hadFence;\n\tif (typeof hadFence !== \"boolean\") return null;\n\n\tconst hadDiff = candidate.hadDiff;\n\tif (typeof hadDiff !== \"boolean\") return null;\n\n\tconst laneTypeRaw = candidate.laneType;\n\tlet laneType: AdaptorchLaneType | undefined;\n\tif (laneTypeRaw !== undefined) {\n\t\tif (typeof laneTypeRaw !== \"string\" || !LANE_TYPE_SET.has(laneTypeRaw)) return null;\n\t\tlaneType = laneTypeRaw as AdaptorchLaneType;\n\t}\n\n\treturn {\n\t\tschemaVersion: 1,\n\t\ttaskClass: taskClass as AdaptorchTaskClass,\n\t\trunnerUp: runnerUp as AdaptorchTaskClass,\n\t\tmarginBucket: marginBucket as AdaptorchMarginBucket,\n\t\tlenBucket: clampLenBucket(lenBucketRaw),\n\t\thadFence,\n\t\thadDiff,\n\t\tpressureBucket: clampPressureBucket(pressureBucketRaw),\n\t\t...(laneType !== undefined ? { laneType } : {}),\n\t};\n}\n\n/**\n * Sanitize/validate an inbound advisory result (i.e. whatever the injected\n * advisory function returned). Returns `null` (never throws) on any shape,\n * forbidden-field, extra-key, or unknown-enum violation - the caller\n * (`AdaptorchBridge.consult`) treats `null` as \"no hint\" and falls back\n * silently, exactly like every other failure mode.\n */\nexport function sanitizeAdvisoryResult(candidate: unknown): AdaptorchAdvisoryResult | null {\n\tif (!isPlainObject(candidate)) return null;\n\tif (containsForbiddenField(candidate)) return null;\n\tif (!hasOnlyAllowedKeys(candidate, ADVISORY_RESULT_KEYS)) return null;\n\n\tif (candidate.schemaVersion !== 1) return null;\n\n\tconst taskClass = candidate.taskClass;\n\tif (typeof taskClass !== \"string\" || !TASK_CLASS_SET.has(taskClass)) return null;\n\n\tconst confidenceBand = candidate.confidenceBand;\n\tif (typeof confidenceBand !== \"string\" || !CONFIDENCE_BAND_SET.has(confidenceBand)) return null;\n\n\treturn {\n\t\tschemaVersion: 1,\n\t\ttaskClass: taskClass as AdaptorchTaskClass,\n\t\tconfidenceBand: confidenceBand as AdaptorchConfidenceBand,\n\t};\n}\n\n/**\n * Read-only/local AdaptOrch MCP tool names this bridge may ever reference,\n * grounded in the real 10-tool surface documented in\n * packages/adaptorch-wpl/src/adaptorch-client.ts (cross-checked there\n * against the AdaptOrch server's own docs) and narrowed to the two tools the\n * read-first plan puts in scope for a reasoning-effort hint (plan 4.2): the\n * session-start capabilities probe and the per-consult topology\n * classification call. This module does not call any MCP tool directly\n * today - the advisory function is fully caller-injected - so this\n * allowlist is not wired to a transport here; it exists so a future\n * transport, and this module's own tests, can assert by construction that\n * `adaptorch_run` (submit) and `adaptorch_cancel_run` (cancel), or any other\n * mutating tool, can never be reachable from router/bridge code.\n */\nexport const ADAPTORCH_READONLY_TOOL_ALLOWLIST = [\"adaptorch_capabilities\", \"adaptorch_route_topology\"] as const;\n\nexport type AdaptorchReadonlyToolName = (typeof ADAPTORCH_READONLY_TOOL_ALLOWLIST)[number];\n\n/** Underscore-segment verbs that mark an AdaptOrch-shaped tool name as mutating (write/execute/lifecycle). */\nconst MUTATING_TOOL_VERB_SEGMENTS: ReadonlySet<string> = new Set([\n\t\"run\",\n\t\"submit\",\n\t\"cancel\",\n\t\"dispatch\",\n\t\"delete\",\n\t\"execute\",\n\t\"mutate\",\n\t\"write\",\n\t\"create\",\n\t\"update\",\n\t\"remove\",\n]);\n\n/**\n * True if any underscore-delimited segment of an AdaptOrch-shaped tool name\n * is a known mutating verb. Segment-based rather than a raw substring/regex\n * match so \"adaptorch_route_topology\" is never falsely flagged (no segment\n * is a mutating verb), while \"adaptorch_run\" and \"adaptorch_cancel_run\" are\n * always caught regardless of future prefix/suffix changes.\n */\nexport function looksMutatingToolName(name: string): boolean {\n\treturn name\n\t\t.toLowerCase()\n\t\t.split(\"_\")\n\t\t.some((segment) => MUTATING_TOOL_VERB_SEGMENTS.has(segment));\n}\n\n/**\n * Type guard: true only for the two allowlisted read/local AdaptOrch tool\n * names. Also independently rejects any name `looksMutatingToolName` flags,\n * so a future accidental addition of a mutating name to the allowlist array\n * still cannot make this function report it as allowed.\n */\nexport function isAdaptorchToolAllowed(name: string): name is AdaptorchReadonlyToolName {\n\tif (looksMutatingToolName(name)) return false;\n\treturn (ADAPTORCH_READONLY_TOOL_ALLOWLIST as readonly string[]).includes(name);\n}\n\n/**\n * Timeout wrapper interface around any injected async advisory call. Races\n * the call against a timer; a slow or hung call rejects at `timeoutMs`\n * instead of leaving the caller waiting indefinitely. Always clears the\n * timer once the call settles (or once the timeout itself fires), and\n * always resolves/rejects exactly once - a synchronous throw from `run` is\n * treated the same as an asynchronous rejection.\n */\nexport type AdvisoryTimeoutWrapper = <T>(run: () => Promise<T>, timeoutMs: number) => Promise<T>;\n\nexport const withAdvisoryTimeout: AdvisoryTimeoutWrapper = <T>(\n\trun: () => Promise<T>,\n\ttimeoutMs: number,\n): Promise<T> => {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\treject(new Error(\"adaptorch-bridge: advisory call timed out\"));\n\t\t}, timeoutMs);\n\n\t\tlet pending: Promise<T>;\n\t\ttry {\n\t\t\tpending = run();\n\t\t} catch (err) {\n\t\t\tclearTimeout(timer);\n\t\t\treject(err instanceof Error ? err : new Error(String(err)));\n\t\t\treturn;\n\t\t}\n\n\t\tpending.then(\n\t\t\t(value) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(err: unknown) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(err instanceof Error ? err : new Error(String(err)));\n\t\t\t},\n\t\t);\n\t});\n};\n\nconst DEFAULT_TTL_MS = 5 * 60 * 1000;\nconst MIN_TTL_MS = 30 * 1000;\nconst MAX_TTL_MS = 5 * 60 * 1000;\nconst DEFAULT_MAX_TURNS_PER_ENTRY = 10;\nconst DEFAULT_CACHE_SIZE = 16;\nconst DEFAULT_MAX_CONSULTS_PER_SESSION = 5;\nconst DEFAULT_MIN_INTERVAL_MS = 60 * 1000;\nconst DEFAULT_TIMEOUT_MS = 1500;\nconst MIN_TIMEOUT_MS = 1;\nconst MAX_TIMEOUT_MS = 30 * 1000;\nconst DEFAULT_FAILURE_THRESHOLD = 3;\nconst DEFAULT_COOLDOWN_MS = 10 * 60 * 1000;\n\n/**\n * Exact TTL/cache/budget/circuit-breaker defaults from the read-first plan,\n * section 4.8. Exported so a security/review lane can confirm the shipped\n * numbers without reading this module's internals.\n */\nexport const ADAPTORCH_BRIDGE_DEFAULTS = {\n\tttlMs: DEFAULT_TTL_MS,\n\tminTtlMs: MIN_TTL_MS,\n\tmaxTtlMs: MAX_TTL_MS,\n\tmaxTurnsPerEntry: DEFAULT_MAX_TURNS_PER_ENTRY,\n\tcacheSize: DEFAULT_CACHE_SIZE,\n\tmaxConsultsPerSession: DEFAULT_MAX_CONSULTS_PER_SESSION,\n\tminIntervalMs: DEFAULT_MIN_INTERVAL_MS,\n\ttimeoutMs: DEFAULT_TIMEOUT_MS,\n\tminTimeoutMs: MIN_TIMEOUT_MS,\n\tmaxTimeoutMs: MAX_TIMEOUT_MS,\n\tfailureThreshold: DEFAULT_FAILURE_THRESHOLD,\n\tcooldownMs: DEFAULT_COOLDOWN_MS,\n} as const;\n\n/**\n * Bridge configuration. `advisoryFn` is the ONLY seam to any external\n * system - this module never imports or calls an MCP client/transport\n * itself, so it is impossible for a unit test (or a misconfigured caller)\n * to reach a real MCP server through this module by accident.\n */\nexport interface AdaptorchBridgeConfig {\n\t/**\n\t * Caller-injected advisory call. Its return value is untrusted: `consult`\n\t * always runs it through `sanitizeAdvisoryResult` before using or caching\n\t * it, and a rejected/thrown/timed-out/schema-invalid response is treated\n\t * as an ordinary failure (counts toward the circuit breaker), never as a\n\t * value to fuse.\n\t */\n\treadonly advisoryFn: (payload: AdaptorchConsultPayload) => Promise<unknown>;\n\t/** Injectable clock; defaults to `Date.now`. Tests supply a fake to avoid real wall-clock waits. */\n\treadonly now?: () => number;\n\t/** Cache TTL in ms; clamped to [30s, 5min] (plan 4.8). Default 5 minutes. */\n\treadonly ttlMs?: number;\n\t/** A cache entry also expires after this many `getFreshHint` calls (\"turns\"). Default 10. */\n\treadonly maxTurnsPerEntry?: number;\n\t/** Max distinct cached payload keys (LRU eviction beyond this). Default 16. */\n\treadonly cacheSize?: number;\n\t/** Max advisory attempts for this bridge instance's lifetime (\"session\"). Default 5. */\n\treadonly maxConsultsPerSession?: number;\n\t/** Minimum ms between advisory attempts. Default 60000 (60s). */\n\treadonly minIntervalMs?: number;\n\t/** Per-attempt timeout in ms; clamped to [1ms, 30s]. Default 1500 (1.5s). */\n\treadonly timeoutMs?: number;\n\t/** Consecutive failures before the circuit opens. Default 3. */\n\treadonly failureThreshold?: number;\n\t/** Circuit-open duration in ms once opened. Default 600000 (10min). */\n\treadonly cooldownMs?: number;\n}\n\n/** Read-only, non-sensitive introspection snapshot - never exposes payload/result content. */\nexport interface AdaptorchBridgeStats {\n\treadonly consultCount: number;\n\treadonly failureStreak: number;\n\treadonly circuitOpen: boolean;\n\treadonly circuitOpenUntilMs: number;\n\treadonly cacheEntryCount: number;\n}\n\nexport interface AdaptorchBridge {\n\t/**\n\t * Synchronous, cache-read-only. Never blocks, never throws, and never\n\t * calls the advisory function - a cache miss or an expired/invalid entry\n\t * silently returns `null` (\"no hint\"), matching the turn-start path's\n\t * synchronous, I/O-free contract (plan 4.4).\n\t */\n\tgetFreshHint(payload: AdaptorchConsultPayload): AdaptorchAdvisoryResult | null;\n\t/**\n\t * Fire-and-forget refresh for a LATER call to `getFreshHint`, never the\n\t * current one. Never throws synchronously and never rejects into the\n\t * caller - any failure is swallowed internally by `consult`.\n\t */\n\trequestRefresh(payload: AdaptorchConsultPayload): void;\n\t/**\n\t * The awaitable core operation `requestRefresh` fires without awaiting.\n\t * Gated by the circuit breaker, budget counter, and minimum interval (in\n\t * that order) before ever invoking `advisoryFn`; always resolves (never\n\t * rejects) to either a sanitized hint or `null`.\n\t */\n\tconsult(payload: AdaptorchConsultPayload): Promise<AdaptorchAdvisoryResult | null>;\n\t/** Read-only introspection for tests/diagnostics; contains no payload or result content. */\n\tgetStats(): AdaptorchBridgeStats;\n}\n\ninterface CacheEntry {\n\treadonly result: AdaptorchAdvisoryResult;\n\treadonly insertedAtMs: number;\n\treadonly insertedAtTurn: number;\n}\n\n/** Deterministic cache key built field-by-field from a sanitized payload - never from raw prompt text. */\nfunction cacheKeyFor(payload: AdaptorchConsultPayload): string {\n\treturn JSON.stringify({\n\t\ttaskClass: payload.taskClass,\n\t\trunnerUp: payload.runnerUp,\n\t\tmarginBucket: payload.marginBucket,\n\t\tlenBucket: payload.lenBucket,\n\t\thadFence: payload.hadFence,\n\t\thadDiff: payload.hadDiff,\n\t\tpressureBucket: payload.pressureBucket,\n\t\tlaneType: payload.laneType ?? null,\n\t});\n}\n\nclass AdaptorchBridgeImpl implements AdaptorchBridge {\n\tprivate readonly advisoryFn: (payload: AdaptorchConsultPayload) => Promise<unknown>;\n\tprivate readonly now: () => number;\n\tprivate readonly ttlMs: number;\n\tprivate readonly maxTurnsPerEntry: number;\n\tprivate readonly cacheSize: number;\n\tprivate readonly maxConsultsPerSession: number;\n\tprivate readonly minIntervalMs: number;\n\tprivate readonly timeoutMs: number;\n\tprivate readonly failureThreshold: number;\n\tprivate readonly cooldownMs: number;\n\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\tprivate turnCounter = 0;\n\tprivate consultCount = 0;\n\tprivate failureStreak = 0;\n\tprivate lastAttemptAtMs: number | null = null;\n\tprivate circuitOpenUntilMs = 0;\n\n\tconstructor(config: AdaptorchBridgeConfig) {\n\t\tthis.advisoryFn = config.advisoryFn;\n\t\tthis.now = config.now ?? Date.now;\n\t\tthis.ttlMs = clampInt(config.ttlMs ?? DEFAULT_TTL_MS, MIN_TTL_MS, MAX_TTL_MS);\n\t\tthis.maxTurnsPerEntry = boundedIntOrDefault(config.maxTurnsPerEntry, DEFAULT_MAX_TURNS_PER_ENTRY, 1);\n\t\tthis.cacheSize = boundedIntOrDefault(config.cacheSize, DEFAULT_CACHE_SIZE, 1);\n\t\tthis.maxConsultsPerSession = boundedIntOrDefault(\n\t\t\tconfig.maxConsultsPerSession,\n\t\t\tDEFAULT_MAX_CONSULTS_PER_SESSION,\n\t\t\t0,\n\t\t);\n\t\tthis.minIntervalMs = boundedIntOrDefault(config.minIntervalMs, DEFAULT_MIN_INTERVAL_MS, 0);\n\t\tthis.timeoutMs = clampInt(config.timeoutMs ?? DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS);\n\t\tthis.failureThreshold = boundedIntOrDefault(config.failureThreshold, DEFAULT_FAILURE_THRESHOLD, 1);\n\t\tthis.cooldownMs = boundedIntOrDefault(config.cooldownMs, DEFAULT_COOLDOWN_MS, 0);\n\t}\n\n\tgetFreshHint(payload: AdaptorchConsultPayload): AdaptorchAdvisoryResult | null {\n\t\tthis.turnCounter += 1;\n\t\tconst sanitizedPayload = sanitizeConsultPayload(payload);\n\t\tif (sanitizedPayload === null) return null;\n\n\t\tconst key = cacheKeyFor(sanitizedPayload);\n\t\tconst entry = this.cache.get(key);\n\t\tif (entry === undefined) return null;\n\t\tif (!this.isEntryFresh(entry)) {\n\t\t\tthis.cache.delete(key);\n\t\t\treturn null;\n\t\t}\n\t\treturn entry.result;\n\t}\n\n\trequestRefresh(payload: AdaptorchConsultPayload): void {\n\t\tvoid this.consult(payload).catch(() => {\n\t\t\t// consult() already swallows every failure and always resolves; this\n\t\t\t// catch only guards a future refactor from letting one escape, so a\n\t\t\t// fire-and-forget refresh can never surface an unhandled rejection.\n\t\t});\n\t}\n\n\tasync consult(payload: AdaptorchConsultPayload): Promise<AdaptorchAdvisoryResult | null> {\n\t\tconst sanitizedPayload = sanitizeConsultPayload(payload);\n\t\tif (sanitizedPayload === null) return null;\n\n\t\tconst nowMs = this.now();\n\t\tif (nowMs < this.circuitOpenUntilMs) return null;\n\t\tif (this.consultCount >= this.maxConsultsPerSession) return null;\n\t\tif (this.lastAttemptAtMs !== null && nowMs - this.lastAttemptAtMs < this.minIntervalMs) return null;\n\n\t\tthis.consultCount += 1;\n\t\tthis.lastAttemptAtMs = nowMs;\n\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = await withAdvisoryTimeout(() => this.advisoryFn(sanitizedPayload), this.timeoutMs);\n\t\t} catch {\n\t\t\tthis.recordFailure();\n\t\t\treturn null;\n\t\t}\n\n\t\tconst result = sanitizeAdvisoryResult(raw);\n\t\tif (result === null) {\n\t\t\tthis.recordFailure();\n\t\t\treturn null;\n\t\t}\n\n\t\tthis.failureStreak = 0;\n\t\tthis.cacheResult(sanitizedPayload, result);\n\t\treturn result;\n\t}\n\n\tgetStats(): AdaptorchBridgeStats {\n\t\tconst nowMs = this.now();\n\t\treturn {\n\t\t\tconsultCount: this.consultCount,\n\t\t\tfailureStreak: this.failureStreak,\n\t\t\tcircuitOpen: nowMs < this.circuitOpenUntilMs,\n\t\t\tcircuitOpenUntilMs: this.circuitOpenUntilMs,\n\t\t\tcacheEntryCount: this.cache.size,\n\t\t};\n\t}\n\n\tprivate recordFailure(): void {\n\t\tthis.failureStreak += 1;\n\t\tif (this.failureStreak >= this.failureThreshold) {\n\t\t\tthis.circuitOpenUntilMs = this.now() + this.cooldownMs;\n\t\t}\n\t}\n\n\tprivate isEntryFresh(entry: CacheEntry): boolean {\n\t\tconst ageMs = this.now() - entry.insertedAtMs;\n\t\tconst ageTurns = this.turnCounter - entry.insertedAtTurn;\n\t\treturn ageMs < this.ttlMs && ageTurns < this.maxTurnsPerEntry;\n\t}\n\n\t/** Eviction favors entries last refreshed by a successful consult (write-time LRU, not read-time). */\n\tprivate cacheResult(payload: AdaptorchConsultPayload, result: AdaptorchAdvisoryResult): void {\n\t\tconst key = cacheKeyFor(payload);\n\t\tif (this.cache.has(key)) this.cache.delete(key);\n\t\tthis.cache.set(key, { result, insertedAtMs: this.now(), insertedAtTurn: this.turnCounter });\n\t\twhile (this.cache.size > this.cacheSize) {\n\t\t\tconst oldestKey = this.cache.keys().next().value;\n\t\t\tif (oldestKey === undefined) break;\n\t\t\tthis.cache.delete(oldestKey);\n\t\t}\n\t}\n}\n\n/** Construct a default-off AdaptOrch advisory bridge. See `AdaptorchBridgeConfig` for tunables. */\nexport function createAdaptorchBridge(config: AdaptorchBridgeConfig): AdaptorchBridge {\n\treturn new AdaptorchBridgeImpl(config);\n}\n"]}
|