open-multi-agent-kit 0.90.3 → 0.90.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +16 -14
  3. package/dist/config.d.ts +3 -6
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +27 -19
  6. package/dist/config.js.map +1 -1
  7. package/dist/core/adaptorch-bridge.d.ts +257 -0
  8. package/dist/core/adaptorch-bridge.d.ts.map +1 -0
  9. package/dist/core/adaptorch-bridge.js +473 -0
  10. package/dist/core/adaptorch-bridge.js.map +1 -0
  11. package/dist/core/agent-session.d.ts +130 -0
  12. package/dist/core/agent-session.d.ts.map +1 -1
  13. package/dist/core/agent-session.js +286 -0
  14. package/dist/core/agent-session.js.map +1 -1
  15. package/dist/core/bang-skill-invocation.d.ts.map +1 -1
  16. package/dist/core/bang-skill-invocation.js +149 -0
  17. package/dist/core/bang-skill-invocation.js.map +1 -1
  18. package/dist/core/compaction/utils.d.ts.map +1 -1
  19. package/dist/core/compaction/utils.js +15 -2
  20. package/dist/core/compaction/utils.js.map +1 -1
  21. package/dist/core/domain-loadouts.d.ts.map +1 -1
  22. package/dist/core/domain-loadouts.js +1 -1
  23. package/dist/core/domain-loadouts.js.map +1 -1
  24. package/dist/core/reasoning-router-bias.d.ts +119 -0
  25. package/dist/core/reasoning-router-bias.d.ts.map +1 -0
  26. package/dist/core/reasoning-router-bias.js +287 -0
  27. package/dist/core/reasoning-router-bias.js.map +1 -0
  28. package/dist/core/reasoning-router-v2.d.ts +94 -0
  29. package/dist/core/reasoning-router-v2.d.ts.map +1 -0
  30. package/dist/core/reasoning-router-v2.js +288 -0
  31. package/dist/core/reasoning-router-v2.js.map +1 -0
  32. package/dist/core/reasoning-router-v3.d.ts +15 -0
  33. package/dist/core/reasoning-router-v3.d.ts.map +1 -0
  34. package/dist/core/reasoning-router-v3.js +193 -0
  35. package/dist/core/reasoning-router-v3.js.map +1 -0
  36. package/dist/core/reasoning-router-v4-weights.d.ts +124 -0
  37. package/dist/core/reasoning-router-v4-weights.d.ts.map +1 -0
  38. package/dist/core/reasoning-router-v4-weights.js +112 -0
  39. package/dist/core/reasoning-router-v4-weights.js.map +1 -0
  40. package/dist/core/reasoning-router-v4.d.ts +163 -0
  41. package/dist/core/reasoning-router-v4.d.ts.map +1 -0
  42. package/dist/core/reasoning-router-v4.js +683 -0
  43. package/dist/core/reasoning-router-v4.js.map +1 -0
  44. package/dist/core/reasoning-router-weights.d.ts +155 -0
  45. package/dist/core/reasoning-router-weights.d.ts.map +1 -0
  46. package/dist/core/reasoning-router-weights.js +204 -0
  47. package/dist/core/reasoning-router-weights.js.map +1 -0
  48. package/dist/core/reasoning-router.d.ts +44 -0
  49. package/dist/core/reasoning-router.d.ts.map +1 -0
  50. package/dist/core/reasoning-router.js +138 -0
  51. package/dist/core/reasoning-router.js.map +1 -0
  52. package/dist/core/router-feedback-collector.d.ts +101 -0
  53. package/dist/core/router-feedback-collector.d.ts.map +1 -0
  54. package/dist/core/router-feedback-collector.js +239 -0
  55. package/dist/core/router-feedback-collector.js.map +1 -0
  56. package/dist/core/settings-manager.d.ts +28 -0
  57. package/dist/core/settings-manager.d.ts.map +1 -1
  58. package/dist/core/settings-manager.js +16 -0
  59. package/dist/core/settings-manager.js.map +1 -1
  60. package/dist/core/slash-commands.d.ts.map +1 -1
  61. package/dist/core/slash-commands.js +4 -1
  62. package/dist/core/slash-commands.js.map +1 -1
  63. package/dist/modes/interactive/components/control-panel-runtime-status.d.ts +15 -0
  64. package/dist/modes/interactive/components/control-panel-runtime-status.d.ts.map +1 -1
  65. package/dist/modes/interactive/components/control-panel-runtime-status.js +95 -5
  66. package/dist/modes/interactive/components/control-panel-runtime-status.js.map +1 -1
  67. package/dist/modes/interactive/interactive-mode.d.ts +4 -0
  68. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  69. package/dist/modes/interactive/interactive-mode.js +143 -18
  70. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  71. package/docs/loadout-domains/README.md +8 -6
  72. package/docs/loadout-domains/ai-agent-ops.md +3 -2
  73. package/docs/loadout-domains/backend-api.md +3 -2
  74. package/docs/loadout-domains/data-science.md +3 -2
  75. package/docs/loadout-domains/devops-infra.md +2 -1
  76. package/docs/loadout-domains/docs-writing.md +7 -2
  77. package/docs/loadout-domains/frontend-ui.md +42 -11
  78. package/docs/loadout-domains/korean-document.md +83 -0
  79. package/docs/loadout-domains/mobile.md +1 -1
  80. package/docs/loadout-domains/qa-testing.md +4 -2
  81. package/docs/loadout-domains/security-audit.md +2 -1
  82. package/docs/loadout-domains/visual-qa.md +94 -0
  83. package/docs/skills.md +4 -1
  84. package/docs/usage.md +37 -3
  85. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  86. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  87. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  88. package/examples/extensions/gondolin/package-lock.json +2 -2
  89. package/examples/extensions/gondolin/package.json +1 -1
  90. package/examples/extensions/sandbox/package-lock.json +2 -2
  91. package/examples/extensions/sandbox/package.json +1 -1
  92. package/examples/extensions/with-deps/package-lock.json +2 -2
  93. package/examples/extensions/with-deps/package.json +1 -1
  94. package/npm-shrinkwrap.json +12 -12
  95. package/package.json +4 -4
  96. package/dist/agents/jailbreak/index.d.ts +0 -7
  97. package/dist/agents/jailbreak/index.d.ts.map +0 -1
  98. package/dist/agents/jailbreak/index.js +0 -7
  99. package/dist/agents/jailbreak/index.js.map +0 -1
  100. package/dist/agents/jailbreak/subagent-f.d.ts +0 -44
  101. package/dist/agents/jailbreak/subagent-f.d.ts.map +0 -1
  102. package/dist/agents/jailbreak/subagent-f.js +0 -60
  103. package/dist/agents/jailbreak/subagent-f.js.map +0 -1
  104. package/dist/cli/jailbreak-args.d.ts +0 -26
  105. package/dist/cli/jailbreak-args.d.ts.map +0 -1
  106. package/dist/cli/jailbreak-args.js +0 -86
  107. package/dist/cli/jailbreak-args.js.map +0 -1
  108. package/dist/commands/jailbreak.d.ts +0 -49
  109. package/dist/commands/jailbreak.d.ts.map +0 -1
  110. package/dist/commands/jailbreak.js +0 -201
  111. package/dist/commands/jailbreak.js.map +0 -1
  112. package/dist/encoding/index.d.ts +0 -6
  113. package/dist/encoding/index.d.ts.map +0 -1
  114. package/dist/encoding/index.js +0 -6
  115. package/dist/encoding/index.js.map +0 -1
  116. package/dist/encoding/l4-encoder.d.ts +0 -96
  117. package/dist/encoding/l4-encoder.d.ts.map +0 -1
  118. package/dist/encoding/l4-encoder.js +0 -474
  119. package/dist/encoding/l4-encoder.js.map +0 -1
  120. package/dist/fuzzing/index.d.ts +0 -6
  121. package/dist/fuzzing/index.d.ts.map +0 -1
  122. package/dist/fuzzing/index.js +0 -6
  123. package/dist/fuzzing/index.js.map +0 -1
  124. package/dist/fuzzing/mutation-engine.d.ts +0 -93
  125. package/dist/fuzzing/mutation-engine.d.ts.map +0 -1
  126. package/dist/fuzzing/mutation-engine.js +0 -244
  127. package/dist/fuzzing/mutation-engine.js.map +0 -1
  128. package/dist/jailbreak-extension.d.ts +0 -48
  129. package/dist/jailbreak-extension.d.ts.map +0 -1
  130. package/dist/jailbreak-extension.js +0 -47
  131. package/dist/jailbreak-extension.js.map +0 -1
  132. package/dist/modules/index.d.ts +0 -8
  133. package/dist/modules/index.d.ts.map +0 -1
  134. package/dist/modules/index.js +0 -7
  135. package/dist/modules/index.js.map +0 -1
  136. package/dist/modules/lrl-bypass.d.ts +0 -40
  137. package/dist/modules/lrl-bypass.d.ts.map +0 -1
  138. package/dist/modules/lrl-bypass.js +0 -84
  139. package/dist/modules/lrl-bypass.js.map +0 -1
  140. package/dist/modules/lrl-deps.d.ts +0 -38
  141. package/dist/modules/lrl-deps.d.ts.map +0 -1
  142. package/dist/modules/lrl-deps.js +0 -128
  143. package/dist/modules/lrl-deps.js.map +0 -1
  144. package/dist/multiturn/easl-chain.d.ts +0 -113
  145. package/dist/multiturn/easl-chain.d.ts.map +0 -1
  146. package/dist/multiturn/easl-chain.js +0 -351
  147. package/dist/multiturn/easl-chain.js.map +0 -1
  148. package/dist/multiturn/index.d.ts +0 -6
  149. package/dist/multiturn/index.d.ts.map +0 -1
  150. package/dist/multiturn/index.js +0 -6
  151. package/dist/multiturn/index.js.map +0 -1
  152. package/dist/routing/fallback-router.d.ts +0 -123
  153. package/dist/routing/fallback-router.d.ts.map +0 -1
  154. package/dist/routing/fallback-router.js +0 -355
  155. package/dist/routing/fallback-router.js.map +0 -1
  156. package/dist/routing/index.d.ts +0 -6
  157. package/dist/routing/index.d.ts.map +0 -1
  158. package/dist/routing/index.js +0 -6
  159. package/dist/routing/index.js.map +0 -1
  160. package/dist/types/jailbreak.d.ts +0 -246
  161. package/dist/types/jailbreak.d.ts.map +0 -1
  162. package/dist/types/jailbreak.js +0 -8
  163. package/dist/types/jailbreak.js.map +0 -1
  164. package/dist/utils/jailbreak/common.d.ts +0 -63
  165. package/dist/utils/jailbreak/common.d.ts.map +0 -1
  166. package/dist/utils/jailbreak/common.js +0 -130
  167. package/dist/utils/jailbreak/common.js.map +0 -1
  168. package/dist/utils/jailbreak/index.d.ts +0 -7
  169. package/dist/utils/jailbreak/index.d.ts.map +0 -1
  170. package/dist/utils/jailbreak/index.js +0 -7
  171. package/dist/utils/jailbreak/index.js.map +0 -1
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Reasoning-router AdaptOrch advisory bridge (Goal 009 Lane B).
3
+ *
4
+ * A default-off, advisory-only primitive for a future opt-in reasoning-router
5
+ * hint source. This module is intentionally NOT wired into agent-session.ts,
6
+ * reasoning-router-v2.ts, or reasoning-router-v3.ts by this lane - it only
7
+ * implements the bridge's payload/result schema, sanitize/validate helpers,
8
+ * TTL cache, budget counter, circuit breaker, and timeout wrapper around a
9
+ * caller-injected advisory function. A future lane decides how (or whether)
10
+ * to fuse a returned hint into a resolved ThinkingLevel and to actually call
11
+ * this module from agent-session.ts.
12
+ *
13
+ * Grounded in the read-first plan at
14
+ * .omk/goals/008-reasoning-router-advanced-accuracy-plan/laneC-privacy-adaptorch.md
15
+ * (Part B, sections 4.1-4.11) and the real AdaptOrch MCP tool surface
16
+ * documented in packages/adaptorch-wpl/src/adaptorch-client.ts. Key
17
+ * constraints carried over from that plan:
18
+ *
19
+ * - The router's turn-start path is synchronous and I/O-free today (plan
20
+ * 4.4). This module never calls an MCP transport directly and exposes a
21
+ * synchronous, cache-read-only accessor (`getFreshHint`) plus a
22
+ * fire-and-forget refresh (`requestRefresh`) so a future integration can
23
+ * never block or await this module inline on the turn-start path.
24
+ * - The real, documented AdaptOrch tool surface has no confidence or
25
+ * reasoning-level field (plan 4.3); this module's inbound result type
26
+ * (`AdaptorchAdvisoryResult`) therefore only carries a locally-relevant
27
+ * `taskClass` and a `confidenceBand` - both closed enums - never a raw
28
+ * numeric confidence or a `ThinkingLevel` value. Fusing a hint into a
29
+ * resolved level is out of scope for this module.
30
+ * - No product source (agent-session.ts, reasoning-router-v2/v3.ts,
31
+ * reasoning-router-weights.ts) is imported here. `AdaptorchTaskClass` /
32
+ * `AdaptorchLaneType` intentionally mirror `TaskClassV2` /
33
+ * `ReasoningLaneTypeV2` from reasoning-router-v2.ts by value, not by
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.
40
+ * - Every outbound/inbound field is a closed enum, a boolean, or a bounded
41
+ * integer, derived from local features only. There is structurally no
42
+ * field shaped to carry prompt text, a prompt hash, a file/working-
43
+ * directory path, a model/provider identifier, a session/user identifier,
44
+ * a tool name, or hook output - the sanitize/validate helpers below also
45
+ * reject any candidate object exposing such a field by name, and reject
46
+ * any key outside the exact closed schema, so a hand-built or forged
47
+ * payload can never smuggle one through either type.
48
+ * - The router-bridge tool allowlist (`ADAPTORCH_READONLY_TOOL_ALLOWLIST`)
49
+ * only ever contains the two read/local AdaptOrch tools the plan
50
+ * identifies as in scope (the session-start capabilities probe and the
51
+ * per-consult topology-classification call, plan 4.2/4.6); the
52
+ * run-submission and run-cancellation tools (and any other mutating
53
+ * tool) can never appear in it, checked both by an exact-value test and
54
+ * by `looksMutatingToolName`'s verb-segment guard.
55
+ *
56
+ * Pure aside from `Date.now`/`setTimeout` (both injectable/wrapped so tests
57
+ * never depend on real wall-clock time or a real MCP call).
58
+ */
59
+ /** Closed set of task classes. Mirrors TaskClassV2 in reasoning-router-v2.ts by value (see file header). */
60
+ export type AdaptorchTaskClass = "trivial" | "simple-edit" | "code-gen" | "debug" | "refactor" | "review" | "plan";
61
+ /** Closed set of subagent lane types. Mirrors ReasoningLaneTypeV2 in reasoning-router-v2.ts by value. */
62
+ export type AdaptorchLaneType = "planner" | "security" | "explorer" | "coder" | "reviewer" | "tester";
63
+ /** Local top1-vs-runner-up score-margin bucket (plan 4.5 ConsultPayloadV1.marginBucket). */
64
+ export type AdaptorchMarginBucket = "tie" | "low" | "medium" | "high";
65
+ /** Locally-derived confidence band for a returned hint. Never a raw network-supplied float (plan 4.3). */
66
+ export type AdaptorchConfidenceBand = "low" | "medium" | "high";
67
+ /** floor(log2(trimmedPromptLen+1)) clamped to [0,7] - same bucketing as reasoning-router-v2.ts's clampLenBucket. */
68
+ export type AdaptorchLenBucket = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
69
+ /** Context-pressure band 0..3 - same bucketing as agent-session.ts's _computePressureBucket. */
70
+ export type AdaptorchPressureBucket = 0 | 1 | 2 | 3;
71
+ /**
72
+ * Outbound advisory request (plan 4.5, field names adapted for this lane's
73
+ * assignment: taskClass/runnerUp/marginBucket/lenBucket/hadFence/hadDiff/
74
+ * pressureBucket/laneType). Every field is a closed enum, a boolean, or a
75
+ * bounded integer built from local classifier features only. Structurally
76
+ * excludes prompt text/hash, file paths, model/provider/session
77
+ * identifiers, tool names, and hook output - there is no field shaped to
78
+ * carry any of those.
79
+ */
80
+ export interface AdaptorchConsultPayload {
81
+ readonly schemaVersion: 1;
82
+ readonly taskClass: AdaptorchTaskClass;
83
+ readonly runnerUp: AdaptorchTaskClass;
84
+ readonly marginBucket: AdaptorchMarginBucket;
85
+ readonly lenBucket: AdaptorchLenBucket;
86
+ readonly hadFence: boolean;
87
+ readonly hadDiff: boolean;
88
+ readonly pressureBucket: AdaptorchPressureBucket;
89
+ readonly laneType?: AdaptorchLaneType;
90
+ }
91
+ /**
92
+ * Inbound advisory result after local sanitation (plan 4.3, corrected
93
+ * schema). `confidenceBand` is always synthesized/validated locally - the
94
+ * real AdaptOrch tool contract carries no confidence or effort-level field,
95
+ * so this type never trusts a raw numeric confidence from the advisory
96
+ * function.
97
+ */
98
+ export interface AdaptorchAdvisoryResult {
99
+ readonly schemaVersion: 1;
100
+ readonly taskClass: AdaptorchTaskClass;
101
+ readonly confidenceBand: AdaptorchConfidenceBand;
102
+ }
103
+ /**
104
+ * True if any own key of `record` contains a forbidden field-name marker
105
+ * (case-insensitive). Typed `object` rather than `Record<string, unknown>` so
106
+ * callers (including tests) can pass any concrete object shape - named
107
+ * interface, ad-hoc literal, or an already-`Record`-typed value - without a
108
+ * missing-index-signature type error; only `Object.keys` is used internally,
109
+ * which accepts any `object`.
110
+ */
111
+ export declare function containsForbiddenField(record: object): boolean;
112
+ /**
113
+ * Sanitize/validate an outbound advisory request. Returns `null` (never
114
+ * throws) when `candidate` is not a plain object, carries a forbidden-named
115
+ * field, carries any key outside the exact closed schema, or has a
116
+ * wrong-typed/unknown-enum field. `lenBucket`/`pressureBucket` are clamped
117
+ * into their bounded ranges rather than rejected, so a caller-side rounding
118
+ * or edge-case computation can never smuggle an out-of-range integer through.
119
+ */
120
+ export declare function sanitizeConsultPayload(candidate: unknown): AdaptorchConsultPayload | null;
121
+ /**
122
+ * Sanitize/validate an inbound advisory result (i.e. whatever the injected
123
+ * advisory function returned). Returns `null` (never throws) on any shape,
124
+ * forbidden-field, extra-key, or unknown-enum violation - the caller
125
+ * (`AdaptorchBridge.consult`) treats `null` as "no hint" and falls back
126
+ * silently, exactly like every other failure mode.
127
+ */
128
+ export declare function sanitizeAdvisoryResult(candidate: unknown): AdaptorchAdvisoryResult | null;
129
+ /**
130
+ * Read-only/local AdaptOrch MCP tool names this bridge may ever reference,
131
+ * grounded in the real 10-tool surface documented in
132
+ * packages/adaptorch-wpl/src/adaptorch-client.ts (cross-checked there
133
+ * against the AdaptOrch server's own docs) and narrowed to the two tools the
134
+ * read-first plan puts in scope for a reasoning-effort hint (plan 4.2): the
135
+ * session-start capabilities probe and the per-consult topology
136
+ * classification call. This module does not call any MCP tool directly
137
+ * today - the advisory function is fully caller-injected - so this
138
+ * allowlist is not wired to a transport here; it exists so a future
139
+ * transport, and this module's own tests, can assert by construction that
140
+ * `adaptorch_run` (submit) and `adaptorch_cancel_run` (cancel), or any other
141
+ * mutating tool, can never be reachable from router/bridge code.
142
+ */
143
+ export declare const ADAPTORCH_READONLY_TOOL_ALLOWLIST: readonly ["adaptorch_capabilities", "adaptorch_route_topology"];
144
+ export type AdaptorchReadonlyToolName = (typeof ADAPTORCH_READONLY_TOOL_ALLOWLIST)[number];
145
+ /**
146
+ * True if any underscore-delimited segment of an AdaptOrch-shaped tool name
147
+ * is a known mutating verb. Segment-based rather than a raw substring/regex
148
+ * match so "adaptorch_route_topology" is never falsely flagged (no segment
149
+ * is a mutating verb), while "adaptorch_run" and "adaptorch_cancel_run" are
150
+ * always caught regardless of future prefix/suffix changes.
151
+ */
152
+ export declare function looksMutatingToolName(name: string): boolean;
153
+ /**
154
+ * Type guard: true only for the two allowlisted read/local AdaptOrch tool
155
+ * names. Also independently rejects any name `looksMutatingToolName` flags,
156
+ * so a future accidental addition of a mutating name to the allowlist array
157
+ * still cannot make this function report it as allowed.
158
+ */
159
+ export declare function isAdaptorchToolAllowed(name: string): name is AdaptorchReadonlyToolName;
160
+ /**
161
+ * Timeout wrapper interface around any injected async advisory call. Races
162
+ * the call against a timer; a slow or hung call rejects at `timeoutMs`
163
+ * instead of leaving the caller waiting indefinitely. Always clears the
164
+ * timer once the call settles (or once the timeout itself fires), and
165
+ * always resolves/rejects exactly once - a synchronous throw from `run` is
166
+ * treated the same as an asynchronous rejection.
167
+ */
168
+ export type AdvisoryTimeoutWrapper = <T>(run: () => Promise<T>, timeoutMs: number) => Promise<T>;
169
+ export declare const withAdvisoryTimeout: AdvisoryTimeoutWrapper;
170
+ /**
171
+ * Exact TTL/cache/budget/circuit-breaker defaults from the read-first plan,
172
+ * section 4.8. Exported so a security/review lane can confirm the shipped
173
+ * numbers without reading this module's internals.
174
+ */
175
+ export declare const ADAPTORCH_BRIDGE_DEFAULTS: {
176
+ readonly ttlMs: number;
177
+ readonly minTtlMs: number;
178
+ readonly maxTtlMs: number;
179
+ readonly maxTurnsPerEntry: 10;
180
+ readonly cacheSize: 16;
181
+ readonly maxConsultsPerSession: 5;
182
+ readonly minIntervalMs: number;
183
+ readonly timeoutMs: 1500;
184
+ readonly minTimeoutMs: 1;
185
+ readonly maxTimeoutMs: number;
186
+ readonly failureThreshold: 3;
187
+ readonly cooldownMs: number;
188
+ };
189
+ /**
190
+ * Bridge configuration. `advisoryFn` is the ONLY seam to any external
191
+ * system - this module never imports or calls an MCP client/transport
192
+ * itself, so it is impossible for a unit test (or a misconfigured caller)
193
+ * to reach a real MCP server through this module by accident.
194
+ */
195
+ export interface AdaptorchBridgeConfig {
196
+ /**
197
+ * Caller-injected advisory call. Its return value is untrusted: `consult`
198
+ * always runs it through `sanitizeAdvisoryResult` before using or caching
199
+ * it, and a rejected/thrown/timed-out/schema-invalid response is treated
200
+ * as an ordinary failure (counts toward the circuit breaker), never as a
201
+ * value to fuse.
202
+ */
203
+ readonly advisoryFn: (payload: AdaptorchConsultPayload) => Promise<unknown>;
204
+ /** Injectable clock; defaults to `Date.now`. Tests supply a fake to avoid real wall-clock waits. */
205
+ readonly now?: () => number;
206
+ /** Cache TTL in ms; clamped to [30s, 5min] (plan 4.8). Default 5 minutes. */
207
+ readonly ttlMs?: number;
208
+ /** A cache entry also expires after this many `getFreshHint` calls ("turns"). Default 10. */
209
+ readonly maxTurnsPerEntry?: number;
210
+ /** Max distinct cached payload keys (LRU eviction beyond this). Default 16. */
211
+ readonly cacheSize?: number;
212
+ /** Max advisory attempts for this bridge instance's lifetime ("session"). Default 5. */
213
+ readonly maxConsultsPerSession?: number;
214
+ /** Minimum ms between advisory attempts. Default 60000 (60s). */
215
+ readonly minIntervalMs?: number;
216
+ /** Per-attempt timeout in ms; clamped to [1ms, 30s]. Default 1500 (1.5s). */
217
+ readonly timeoutMs?: number;
218
+ /** Consecutive failures before the circuit opens. Default 3. */
219
+ readonly failureThreshold?: number;
220
+ /** Circuit-open duration in ms once opened. Default 600000 (10min). */
221
+ readonly cooldownMs?: number;
222
+ }
223
+ /** Read-only, non-sensitive introspection snapshot - never exposes payload/result content. */
224
+ export interface AdaptorchBridgeStats {
225
+ readonly consultCount: number;
226
+ readonly failureStreak: number;
227
+ readonly circuitOpen: boolean;
228
+ readonly circuitOpenUntilMs: number;
229
+ readonly cacheEntryCount: number;
230
+ }
231
+ export interface AdaptorchBridge {
232
+ /**
233
+ * Synchronous, cache-read-only. Never blocks, never throws, and never
234
+ * calls the advisory function - a cache miss or an expired/invalid entry
235
+ * silently returns `null` ("no hint"), matching the turn-start path's
236
+ * synchronous, I/O-free contract (plan 4.4).
237
+ */
238
+ getFreshHint(payload: AdaptorchConsultPayload): AdaptorchAdvisoryResult | null;
239
+ /**
240
+ * Fire-and-forget refresh for a LATER call to `getFreshHint`, never the
241
+ * current one. Never throws synchronously and never rejects into the
242
+ * caller - any failure is swallowed internally by `consult`.
243
+ */
244
+ requestRefresh(payload: AdaptorchConsultPayload): void;
245
+ /**
246
+ * The awaitable core operation `requestRefresh` fires without awaiting.
247
+ * Gated by the circuit breaker, budget counter, and minimum interval (in
248
+ * that order) before ever invoking `advisoryFn`; always resolves (never
249
+ * rejects) to either a sanitized hint or `null`.
250
+ */
251
+ consult(payload: AdaptorchConsultPayload): Promise<AdaptorchAdvisoryResult | null>;
252
+ /** Read-only introspection for tests/diagnostics; contains no payload or result content. */
253
+ getStats(): AdaptorchBridgeStats;
254
+ }
255
+ /** Construct a default-off AdaptOrch advisory bridge. See `AdaptorchBridgeConfig` for tunables. */
256
+ export declare function createAdaptorchBridge(config: AdaptorchBridgeConfig): AdaptorchBridge;
257
+ //# sourceMappingURL=adaptorch-bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adaptorch-bridge.d.ts","sourceRoot":"","sources":["../../src/core/adaptorch-bridge.ts"],"names":[],"mappings":"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","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"]}