open-multi-agent-kit 0.96.2 → 0.98.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (368) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +43 -9
  3. package/dist/cli/args.d.ts +2 -3
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +13 -189
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/cli/help.d.ts +3 -0
  8. package/dist/cli/help.d.ts.map +1 -0
  9. package/dist/cli/help.js +194 -0
  10. package/dist/cli/help.js.map +1 -0
  11. package/dist/cli/initial-message.d.ts.map +1 -1
  12. package/dist/cli/initial-message.js +2 -1
  13. package/dist/cli/initial-message.js.map +1 -1
  14. package/dist/cli/resource-paths.d.ts +4 -0
  15. package/dist/cli/resource-paths.d.ts.map +1 -0
  16. package/dist/cli/resource-paths.js +59 -0
  17. package/dist/cli/resource-paths.js.map +1 -0
  18. package/dist/commands/adaptorch-doctor-cli.d.ts +13 -0
  19. package/dist/commands/adaptorch-doctor-cli.d.ts.map +1 -0
  20. package/dist/commands/adaptorch-doctor-cli.js +115 -0
  21. package/dist/commands/adaptorch-doctor-cli.js.map +1 -0
  22. package/dist/commands/resource-doctor-cli.d.ts +4 -0
  23. package/dist/commands/resource-doctor-cli.d.ts.map +1 -1
  24. package/dist/commands/resource-doctor-cli.js +35 -5
  25. package/dist/commands/resource-doctor-cli.js.map +1 -1
  26. package/dist/core/adaptorch-bridge.d.ts +11 -13
  27. package/dist/core/adaptorch-bridge.d.ts.map +1 -1
  28. package/dist/core/adaptorch-bridge.js +11 -13
  29. package/dist/core/adaptorch-bridge.js.map +1 -1
  30. package/dist/core/agent-session-snapshot.d.ts +16 -0
  31. package/dist/core/agent-session-snapshot.d.ts.map +1 -0
  32. package/dist/core/agent-session-snapshot.js +111 -0
  33. package/dist/core/agent-session-snapshot.js.map +1 -0
  34. package/dist/core/agent-session.d.ts +14 -10
  35. package/dist/core/agent-session.d.ts.map +1 -1
  36. package/dist/core/agent-session.js +102 -217
  37. package/dist/core/agent-session.js.map +1 -1
  38. package/dist/core/agent-tool-settings.d.ts +10 -0
  39. package/dist/core/agent-tool-settings.d.ts.map +1 -1
  40. package/dist/core/agent-tool-settings.js +10 -1
  41. package/dist/core/agent-tool-settings.js.map +1 -1
  42. package/dist/core/attachment-store.d.ts +39 -0
  43. package/dist/core/attachment-store.d.ts.map +1 -0
  44. package/dist/core/attachment-store.js +81 -0
  45. package/dist/core/attachment-store.js.map +1 -0
  46. package/dist/core/command-safety.d.ts +8 -0
  47. package/dist/core/command-safety.d.ts.map +1 -1
  48. package/dist/core/command-safety.js +140 -14
  49. package/dist/core/command-safety.js.map +1 -1
  50. package/dist/core/compaction/compaction.d.ts +13 -1
  51. package/dist/core/compaction/compaction.d.ts.map +1 -1
  52. package/dist/core/compaction/compaction.js +60 -62
  53. package/dist/core/compaction/compaction.js.map +1 -1
  54. package/dist/core/compaction/index.d.ts +1 -0
  55. package/dist/core/compaction/index.d.ts.map +1 -1
  56. package/dist/core/compaction/index.js +1 -0
  57. package/dist/core/compaction/index.js.map +1 -1
  58. package/dist/core/compaction/knowledge-triage-format.d.ts +9 -0
  59. package/dist/core/compaction/knowledge-triage-format.d.ts.map +1 -0
  60. package/dist/core/compaction/knowledge-triage-format.js +71 -0
  61. package/dist/core/compaction/knowledge-triage-format.js.map +1 -0
  62. package/dist/core/compaction/knowledge-triage-types.d.ts +7 -0
  63. package/dist/core/compaction/knowledge-triage-types.d.ts.map +1 -0
  64. package/dist/core/compaction/knowledge-triage-types.js +2 -0
  65. package/dist/core/compaction/knowledge-triage-types.js.map +1 -0
  66. package/dist/core/compaction/knowledge-triage.d.ts +29 -0
  67. package/dist/core/compaction/knowledge-triage.d.ts.map +1 -0
  68. package/dist/core/compaction/knowledge-triage.js +189 -0
  69. package/dist/core/compaction/knowledge-triage.js.map +1 -0
  70. package/dist/core/compaction/transaction.d.ts.map +1 -1
  71. package/dist/core/compaction/transaction.js +1 -1
  72. package/dist/core/compaction/transaction.js.map +1 -1
  73. package/dist/core/compaction/utils.d.ts +4 -0
  74. package/dist/core/compaction/utils.d.ts.map +1 -1
  75. package/dist/core/compaction/utils.js +37 -0
  76. package/dist/core/compaction/utils.js.map +1 -1
  77. package/dist/core/completion-sound-io.d.ts +14 -0
  78. package/dist/core/completion-sound-io.d.ts.map +1 -0
  79. package/dist/core/completion-sound-io.js +64 -0
  80. package/dist/core/completion-sound-io.js.map +1 -0
  81. package/dist/core/completion-sound.d.ts +4 -10
  82. package/dist/core/completion-sound.d.ts.map +1 -1
  83. package/dist/core/completion-sound.js +28 -58
  84. package/dist/core/completion-sound.js.map +1 -1
  85. package/dist/core/context-budget-governor-v2.d.ts +1 -1
  86. package/dist/core/context-budget-governor-v2.d.ts.map +1 -1
  87. package/dist/core/context-budget-governor-v2.js +1 -1
  88. package/dist/core/context-budget-governor-v2.js.map +1 -1
  89. package/dist/core/context-budget-relevance.d.ts +15 -2
  90. package/dist/core/context-budget-relevance.d.ts.map +1 -1
  91. package/dist/core/context-budget-relevance.js +21 -9
  92. package/dist/core/context-budget-relevance.js.map +1 -1
  93. package/dist/core/context-budget-system-prompt-items.d.ts +1 -1
  94. package/dist/core/context-budget-system-prompt-items.d.ts.map +1 -1
  95. package/dist/core/context-budget-system-prompt-items.js.map +1 -1
  96. package/dist/core/context-budget-system-prompt.d.ts +1 -1
  97. package/dist/core/context-budget-system-prompt.d.ts.map +1 -1
  98. package/dist/core/context-budget-system-prompt.js.map +1 -1
  99. package/dist/core/context-budget-v2-cache-keys.d.ts +3 -0
  100. package/dist/core/context-budget-v2-cache-keys.d.ts.map +1 -1
  101. package/dist/core/context-budget-v2-cache-keys.js +2 -0
  102. package/dist/core/context-budget-v2-cache-keys.js.map +1 -1
  103. package/dist/core/context-budget-v2-plan-cache-keys.d.ts.map +1 -1
  104. package/dist/core/context-budget-v2-plan-cache-keys.js +3 -0
  105. package/dist/core/context-budget-v2-plan-cache-keys.js.map +1 -1
  106. package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
  107. package/dist/core/context-budget-v2-planner.js +2 -1
  108. package/dist/core/context-budget-v2-planner.js.map +1 -1
  109. package/dist/core/context-budget-v2-scoring.d.ts +17 -0
  110. package/dist/core/context-budget-v2-scoring.d.ts.map +1 -1
  111. package/dist/core/context-budget-v2-scoring.js +25 -8
  112. package/dist/core/context-budget-v2-scoring.js.map +1 -1
  113. package/dist/core/context-budget-v2-selection.d.ts +2 -2
  114. package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
  115. package/dist/core/context-budget-v2-selection.js +18 -1
  116. package/dist/core/context-budget-v2-selection.js.map +1 -1
  117. package/dist/core/context-budget-v2-types.d.ts +17 -0
  118. package/dist/core/context-budget-v2-types.d.ts.map +1 -1
  119. package/dist/core/context-budget-v2-types.js +15 -0
  120. package/dist/core/context-budget-v2-types.js.map +1 -1
  121. package/dist/core/context-file.d.ts +23 -0
  122. package/dist/core/context-file.d.ts.map +1 -0
  123. package/dist/core/context-file.js +17 -0
  124. package/dist/core/context-file.js.map +1 -0
  125. package/dist/core/extensions/builtin/command-safety-gate.d.ts +3 -1
  126. package/dist/core/extensions/builtin/command-safety-gate.d.ts.map +1 -1
  127. package/dist/core/extensions/builtin/command-safety-gate.js +7 -0
  128. package/dist/core/extensions/builtin/command-safety-gate.js.map +1 -1
  129. package/dist/core/extensions/types.d.ts +12 -1
  130. package/dist/core/extensions/types.d.ts.map +1 -1
  131. package/dist/core/extensions/types.js.map +1 -1
  132. package/dist/core/keybindings.d.ts +1 -1
  133. package/dist/core/keybindings.d.ts.map +1 -1
  134. package/dist/core/keybindings.js +6 -1
  135. package/dist/core/keybindings.js.map +1 -1
  136. package/dist/core/model-prompt-policy.d.ts +1 -1
  137. package/dist/core/model-prompt-policy.d.ts.map +1 -1
  138. package/dist/core/model-prompt-policy.js.map +1 -1
  139. package/dist/core/model-registry.d.ts +8 -3
  140. package/dist/core/model-registry.d.ts.map +1 -1
  141. package/dist/core/model-registry.js +71 -1
  142. package/dist/core/model-registry.js.map +1 -1
  143. package/dist/core/package-doctor-source-scan.d.ts +9 -0
  144. package/dist/core/package-doctor-source-scan.d.ts.map +1 -1
  145. package/dist/core/package-doctor-source-scan.js +77 -4
  146. package/dist/core/package-doctor-source-scan.js.map +1 -1
  147. package/dist/core/prompt-attachment.d.ts +51 -0
  148. package/dist/core/prompt-attachment.d.ts.map +1 -0
  149. package/dist/core/prompt-attachment.js +186 -0
  150. package/dist/core/prompt-attachment.js.map +1 -0
  151. package/dist/core/prompt-settlement.d.ts +6 -3
  152. package/dist/core/prompt-settlement.d.ts.map +1 -1
  153. package/dist/core/prompt-settlement.js +10 -14
  154. package/dist/core/prompt-settlement.js.map +1 -1
  155. package/dist/core/provider-resilience.d.ts +28 -0
  156. package/dist/core/provider-resilience.d.ts.map +1 -1
  157. package/dist/core/provider-resilience.js +50 -0
  158. package/dist/core/provider-resilience.js.map +1 -1
  159. package/dist/core/provider-retry.d.ts +1 -1
  160. package/dist/core/provider-retry.d.ts.map +1 -1
  161. package/dist/core/provider-retry.js +1 -1
  162. package/dist/core/provider-retry.js.map +1 -1
  163. package/dist/core/provider-usage.d.ts.map +1 -1
  164. package/dist/core/provider-usage.js +68 -2
  165. package/dist/core/provider-usage.js.map +1 -1
  166. package/dist/core/reasoning-router-promotion.d.ts +124 -0
  167. package/dist/core/reasoning-router-promotion.d.ts.map +1 -0
  168. package/dist/core/reasoning-router-promotion.js +121 -0
  169. package/dist/core/reasoning-router-promotion.js.map +1 -0
  170. package/dist/core/reasoning-router-replay-stability.d.ts +65 -0
  171. package/dist/core/reasoning-router-replay-stability.d.ts.map +1 -0
  172. package/dist/core/reasoning-router-replay-stability.js +67 -0
  173. package/dist/core/reasoning-router-replay-stability.js.map +1 -0
  174. package/dist/core/reasoning-router-v4-weights.d.ts +6 -6
  175. package/dist/core/reasoning-router-v4-weights.d.ts.map +1 -1
  176. package/dist/core/reasoning-router-v4-weights.js +3 -3
  177. package/dist/core/reasoning-router-v4-weights.js.map +1 -1
  178. package/dist/core/reasoning-router-v4.d.ts.map +1 -1
  179. package/dist/core/reasoning-router-v4.js +6 -6
  180. package/dist/core/reasoning-router-v4.js.map +1 -1
  181. package/dist/core/redaction.d.ts.map +1 -1
  182. package/dist/core/redaction.js +1 -1
  183. package/dist/core/redaction.js.map +1 -1
  184. package/dist/core/resource-admission.d.ts +2 -1
  185. package/dist/core/resource-admission.d.ts.map +1 -1
  186. package/dist/core/resource-admission.js +11 -0
  187. package/dist/core/resource-admission.js.map +1 -1
  188. package/dist/core/resource-governor-format.d.ts +1 -1
  189. package/dist/core/resource-governor-format.d.ts.map +1 -1
  190. package/dist/core/resource-governor-format.js.map +1 -1
  191. package/dist/core/resource-governor-settings.d.ts +6 -12
  192. package/dist/core/resource-governor-settings.d.ts.map +1 -1
  193. package/dist/core/resource-governor-settings.js.map +1 -1
  194. package/dist/core/resource-governor-types.d.ts +24 -0
  195. package/dist/core/resource-governor-types.d.ts.map +1 -0
  196. package/dist/core/resource-governor-types.js +15 -0
  197. package/dist/core/resource-governor-types.js.map +1 -0
  198. package/dist/core/resource-loader.d.ts +1 -7
  199. package/dist/core/resource-loader.d.ts.map +1 -1
  200. package/dist/core/resource-loader.js.map +1 -1
  201. package/dist/core/resource-observation-journal.d.ts +2 -1
  202. package/dist/core/resource-observation-journal.d.ts.map +1 -1
  203. package/dist/core/resource-observation-journal.js +4 -3
  204. package/dist/core/resource-observation-journal.js.map +1 -1
  205. package/dist/core/resource-observation-report-reader.d.ts +7 -0
  206. package/dist/core/resource-observation-report-reader.d.ts.map +1 -0
  207. package/dist/core/resource-observation-report-reader.js +157 -0
  208. package/dist/core/resource-observation-report-reader.js.map +1 -0
  209. package/dist/core/resource-observation-report.d.ts +24 -0
  210. package/dist/core/resource-observation-report.d.ts.map +1 -0
  211. package/dist/core/resource-observation-report.js +101 -0
  212. package/dist/core/resource-observation-report.js.map +1 -0
  213. package/dist/core/router-feedback-collector.d.ts +1 -1
  214. package/dist/core/router-feedback-collector.d.ts.map +1 -1
  215. package/dist/core/router-feedback-collector.js.map +1 -1
  216. package/dist/core/session-bash-service.d.ts.map +1 -1
  217. package/dist/core/session-bash-service.js +4 -3
  218. package/dist/core/session-bash-service.js.map +1 -1
  219. package/dist/core/session-failure-cause.d.ts +33 -0
  220. package/dist/core/session-failure-cause.d.ts.map +1 -0
  221. package/dist/core/session-failure-cause.js +141 -0
  222. package/dist/core/session-failure-cause.js.map +1 -0
  223. package/dist/core/session-system-prompt.d.ts +1 -1
  224. package/dist/core/session-system-prompt.d.ts.map +1 -1
  225. package/dist/core/session-system-prompt.js.map +1 -1
  226. package/dist/core/session-termination.d.ts +1 -1
  227. package/dist/core/session-termination.d.ts.map +1 -1
  228. package/dist/core/session-termination.js +11 -2
  229. package/dist/core/session-termination.js.map +1 -1
  230. package/dist/core/settings-manager.d.ts +1 -1
  231. package/dist/core/settings-manager.d.ts.map +1 -1
  232. package/dist/core/settings-manager.js.map +1 -1
  233. package/dist/core/system-prompt.d.ts +1 -1
  234. package/dist/core/system-prompt.d.ts.map +1 -1
  235. package/dist/core/system-prompt.js.map +1 -1
  236. package/dist/core/tools/bash.d.ts.map +1 -1
  237. package/dist/core/tools/bash.js +10 -14
  238. package/dist/core/tools/bash.js.map +1 -1
  239. package/dist/core/tools/grep.d.ts.map +1 -1
  240. package/dist/core/tools/grep.js +13 -48
  241. package/dist/core/tools/grep.js.map +1 -1
  242. package/dist/core/tools/read.d.ts.map +1 -1
  243. package/dist/core/tools/read.js +1 -34
  244. package/dist/core/tools/read.js.map +1 -1
  245. package/dist/core/workload-classifier.d.ts +2 -10
  246. package/dist/core/workload-classifier.d.ts.map +1 -1
  247. package/dist/core/workload-classifier.js +17 -0
  248. package/dist/core/workload-classifier.js.map +1 -1
  249. package/dist/core/workload-family-matcher.d.ts +1 -1
  250. package/dist/core/workload-family-matcher.d.ts.map +1 -1
  251. package/dist/core/workload-family-matcher.js.map +1 -1
  252. package/dist/core/workload-shard-execution-types.d.ts +40 -0
  253. package/dist/core/workload-shard-execution-types.d.ts.map +1 -0
  254. package/dist/core/workload-shard-execution-types.js +14 -0
  255. package/dist/core/workload-shard-execution-types.js.map +1 -0
  256. package/dist/core/workload-shard-executor.d.ts +3 -27
  257. package/dist/core/workload-shard-executor.d.ts.map +1 -1
  258. package/dist/core/workload-shard-executor.js.map +1 -1
  259. package/dist/core/workload-shard-runner.d.ts +1 -1
  260. package/dist/core/workload-shard-runner.d.ts.map +1 -1
  261. package/dist/core/workload-shard-runner.js.map +1 -1
  262. package/dist/core/workload-types.d.ts +24 -0
  263. package/dist/core/workload-types.d.ts.map +1 -0
  264. package/dist/core/workload-types.js +15 -0
  265. package/dist/core/workload-types.js.map +1 -0
  266. package/dist/index.d.ts +1 -1
  267. package/dist/index.d.ts.map +1 -1
  268. package/dist/index.js +1 -1
  269. package/dist/index.js.map +1 -1
  270. package/dist/main.d.ts +2 -0
  271. package/dist/main.d.ts.map +1 -1
  272. package/dist/main.js +27 -47
  273. package/dist/main.js.map +1 -1
  274. package/dist/modes/interactive/components/attachment-strip.d.ts +21 -0
  275. package/dist/modes/interactive/components/attachment-strip.d.ts.map +1 -0
  276. package/dist/modes/interactive/components/attachment-strip.js +136 -0
  277. package/dist/modes/interactive/components/attachment-strip.js.map +1 -0
  278. package/dist/modes/interactive/components/footer.d.ts +6 -0
  279. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  280. package/dist/modes/interactive/components/footer.js +26 -1
  281. package/dist/modes/interactive/components/footer.js.map +1 -1
  282. package/dist/modes/interactive/components/status-sidebar.d.ts.map +1 -1
  283. package/dist/modes/interactive/components/status-sidebar.js +12 -1
  284. package/dist/modes/interactive/components/status-sidebar.js.map +1 -1
  285. package/dist/modes/interactive/interactive-mode.d.ts +23 -4
  286. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  287. package/dist/modes/interactive/interactive-mode.js +174 -53
  288. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  289. package/dist/modes/interactive/theme/omk-control-panel.json +1 -1
  290. package/dist/utils/clipboard-image.d.ts.map +1 -1
  291. package/dist/utils/clipboard-image.js +42 -33
  292. package/dist/utils/clipboard-image.js.map +1 -1
  293. package/dist/utils/clipboard.d.ts.map +1 -1
  294. package/dist/utils/clipboard.js +14 -2
  295. package/dist/utils/clipboard.js.map +1 -1
  296. package/docs/adaptorch-preview-spec.md +20 -18
  297. package/docs/adaptorch-preview.md +9 -9
  298. package/docs/compaction.md +25 -4
  299. package/docs/correctness-wall.md +10 -10
  300. package/docs/docs.json +12 -0
  301. package/docs/environment-variables.md +9 -2
  302. package/docs/extensions.md +12 -3
  303. package/docs/index.md +7 -1
  304. package/docs/metrics.md +74 -2
  305. package/docs/provider-resilience.md +11 -0
  306. package/docs/runtime-algorithms.md +359 -0
  307. package/docs/sdk.md +2 -2
  308. package/docs/settings.md +11 -10
  309. package/docs/usage.md +19 -3
  310. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  311. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  312. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  313. package/examples/extensions/gondolin/package-lock.json +2 -2
  314. package/examples/extensions/gondolin/package.json +1 -1
  315. package/examples/extensions/sandbox/package-lock.json +2 -2
  316. package/examples/extensions/sandbox/package.json +1 -1
  317. package/examples/extensions/with-deps/package-lock.json +2 -2
  318. package/examples/extensions/with-deps/package.json +1 -1
  319. package/npm-shrinkwrap.json +18 -18
  320. package/package.json +7 -7
  321. package/dist/core/context-budget-governor.d.ts +0 -67
  322. package/dist/core/context-budget-governor.d.ts.map +0 -1
  323. package/dist/core/context-budget-governor.js +0 -224
  324. package/dist/core/context-budget-governor.js.map +0 -1
  325. package/dist/core/lean-ctx.d.ts +0 -99
  326. package/dist/core/lean-ctx.d.ts.map +0 -1
  327. package/dist/core/lean-ctx.js +0 -225
  328. package/dist/core/lean-ctx.js.map +0 -1
  329. package/dist/core/read-anchors.d.ts +0 -110
  330. package/dist/core/read-anchors.d.ts.map +0 -1
  331. package/dist/core/read-anchors.js +0 -193
  332. package/dist/core/read-anchors.js.map +0 -1
  333. package/dist/core/recovery-checkpoint.d.ts +0 -196
  334. package/dist/core/recovery-checkpoint.d.ts.map +0 -1
  335. package/dist/core/recovery-checkpoint.js +0 -382
  336. package/dist/core/recovery-checkpoint.js.map +0 -1
  337. package/dist/core/sandbox-policy-v2.d.ts +0 -49
  338. package/dist/core/sandbox-policy-v2.d.ts.map +0 -1
  339. package/dist/core/sandbox-policy-v2.js +0 -368
  340. package/dist/core/sandbox-policy-v2.js.map +0 -1
  341. package/dist/core/tools/omp-pure-seams.d.ts +0 -41
  342. package/dist/core/tools/omp-pure-seams.d.ts.map +0 -1
  343. package/dist/core/tools/omp-pure-seams.js +0 -142
  344. package/dist/core/tools/omp-pure-seams.js.map +0 -1
  345. package/dist/core/tools/omp-seam-runtime.d.ts +0 -100
  346. package/dist/core/tools/omp-seam-runtime.d.ts.map +0 -1
  347. package/dist/core/tools/omp-seam-runtime.js +0 -40
  348. package/dist/core/tools/omp-seam-runtime.js.map +0 -1
  349. package/dist/guardrails/audit-logger.d.ts +0 -4
  350. package/dist/guardrails/audit-logger.d.ts.map +0 -1
  351. package/dist/guardrails/audit-logger.js +0 -28
  352. package/dist/guardrails/audit-logger.js.map +0 -1
  353. package/dist/guardrails/freedomd-adapter.d.ts +0 -16
  354. package/dist/guardrails/freedomd-adapter.d.ts.map +0 -1
  355. package/dist/guardrails/freedomd-adapter.js +0 -87
  356. package/dist/guardrails/freedomd-adapter.js.map +0 -1
  357. package/dist/orchestration/lane-grant-auditor.d.ts +0 -4
  358. package/dist/orchestration/lane-grant-auditor.d.ts.map +0 -1
  359. package/dist/orchestration/lane-grant-auditor.js +0 -87
  360. package/dist/orchestration/lane-grant-auditor.js.map +0 -1
  361. package/dist/types/guardrails.d.ts +0 -61
  362. package/dist/types/guardrails.d.ts.map +0 -1
  363. package/dist/types/guardrails.js +0 -9
  364. package/dist/types/guardrails.js.map +0 -1
  365. package/dist/types/lane-grant.d.ts +0 -58
  366. package/dist/types/lane-grant.d.ts.map +0 -1
  367. package/dist/types/lane-grant.js +0 -9
  368. package/dist/types/lane-grant.js.map +0 -1
@@ -0,0 +1,115 @@
1
+ import { AdaptOrchApiError, createAdaptOrchApiClientFromEnv, } from "omk-adaptorch-wpl";
2
+ /**
3
+ * Headless AdaptOrch connectivity check:
4
+ *
5
+ * omk doctor adaptorch [--json]
6
+ *
7
+ * One command answers the only question that blocks getting started: does the
8
+ * configured key reach the hosted API? It calls `GET /v1/whoami`, which is the
9
+ * cheapest authenticated read in the contract, and reports the principal it
10
+ * resolved to.
11
+ *
12
+ * The exit code carries the verdict so a script can branch without parsing
13
+ * prose: 0 verified, 1 not configured, 2 configured but unreachable. Those are
14
+ * genuinely different states — "no key" is a setup step, while "key rejected"
15
+ * is a broken setup, and collapsing them would make the command useless in CI.
16
+ *
17
+ * The credential is never printed. `omk-adaptorch-wpl` already scrubs it from
18
+ * its own errors; this command additionally never echoes the configured value.
19
+ */
20
+ const USAGE = "Usage: omk doctor adaptorch [--json]";
21
+ /**
22
+ * Where to obtain a key. This is the one moment in the CLI where the reader has
23
+ * explicitly asked about AdaptOrch, so answering "which key, from where" here
24
+ * is help rather than promotion. It carries its own attribution so this
25
+ * touchpoint stays distinguishable from the README links.
26
+ */
27
+ const ADAPTORCH_SIGNUP_URL = "https://adaptorch.com/?utm_source=omk-cli&utm_medium=doctor&utm_campaign=omk#pricing";
28
+ function describe(report) {
29
+ if (!report.configured) {
30
+ return [
31
+ "AdaptOrch: not configured",
32
+ " Set ADAPTORCH_API_KEY to enable it. Optionally set ADAPTORCH_API_URL.",
33
+ ` Get a key: ${ADAPTORCH_SIGNUP_URL}`,
34
+ " AdaptOrch is a separate product; OMK does not require it.",
35
+ ];
36
+ }
37
+ if (!report.reachable) {
38
+ const detail = report.status === undefined ? "" : ` (HTTP ${report.status}${report.code ? ` ${report.code}` : ""})`;
39
+ return [`AdaptOrch: unreachable${detail}`, ` ${report.error ?? "the request did not complete"}`];
40
+ }
41
+ const scope = report.projectId ? `, project ${report.projectId}` : "";
42
+ return [`AdaptOrch: verified`, ` Authenticated as ${report.subjectId ?? "(unknown subject)"}${scope}`];
43
+ }
44
+ async function probe(client) {
45
+ try {
46
+ const principal = await client.whoami();
47
+ return {
48
+ configured: true,
49
+ reachable: true,
50
+ subjectId: principal.subject_id,
51
+ ...(principal.project_id === undefined ? {} : { projectId: principal.project_id }),
52
+ };
53
+ }
54
+ catch (error) {
55
+ if (error instanceof AdaptOrchApiError) {
56
+ return {
57
+ configured: true,
58
+ reachable: false,
59
+ status: error.status,
60
+ ...(error.code === undefined ? {} : { code: error.code }),
61
+ error: error.message,
62
+ };
63
+ }
64
+ return {
65
+ configured: true,
66
+ reachable: false,
67
+ error: error instanceof Error ? error.message : String(error),
68
+ };
69
+ }
70
+ }
71
+ export async function runAdaptOrchDoctorCli(args, overrides = {}) {
72
+ if (args[0] !== "doctor" || args[1] !== "adaptorch") {
73
+ return { handled: false, exitCode: 0 };
74
+ }
75
+ const writeLine = overrides.writeLine ?? ((line) => console.log(line));
76
+ let json = false;
77
+ for (const arg of args.slice(2)) {
78
+ if (arg === "--json") {
79
+ json = true;
80
+ continue;
81
+ }
82
+ if (arg === "--help" || arg === "-h") {
83
+ writeLine(USAGE);
84
+ return { handled: true, exitCode: 0 };
85
+ }
86
+ writeLine(`Unknown option: ${arg}`);
87
+ writeLine(USAGE);
88
+ return { handled: true, exitCode: 2 };
89
+ }
90
+ const env = overrides.env ?? process.env;
91
+ const fetchImpl = overrides.fetch ?? globalThis.fetch;
92
+ let report;
93
+ try {
94
+ const client = createAdaptOrchApiClientFromEnv(fetchImpl, env);
95
+ report = client ? await probe(client) : { configured: false, reachable: false };
96
+ }
97
+ catch (error) {
98
+ // A configured but invalid setup (an unsafe ADAPTORCH_API_URL, for
99
+ // example) is a broken setup, not an absent one.
100
+ report = {
101
+ configured: true,
102
+ reachable: false,
103
+ error: error instanceof Error ? error.message : String(error),
104
+ };
105
+ }
106
+ if (json)
107
+ writeLine(JSON.stringify(report, null, 2));
108
+ else
109
+ for (const line of describe(report))
110
+ writeLine(line);
111
+ if (!report.configured)
112
+ return { handled: true, exitCode: 1 };
113
+ return { handled: true, exitCode: report.reachable ? 0 : 2 };
114
+ }
115
+ //# sourceMappingURL=adaptorch-doctor-cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adaptorch-doctor-cli.js","sourceRoot":"","sources":["../../src/commands/adaptorch-doctor-cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,iBAAiB,EAEjB,+BAA+B,GAC/B,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;;;;;;;;;;;GAiBG;AAEH,MAAM,KAAK,GAAG,sCAAsC,CAAC;AAErD;;;;;GAKG;AACH,MAAM,oBAAoB,GAAG,sFAAsF,CAAC;AAyBpH,SAAS,QAAQ,CAAC,MAA6B,EAAY;IAC1D,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;QACxB,OAAO;YACN,2BAA2B;YAC3B,yEAAyE;YACzE,gBAAgB,oBAAoB,EAAE;YACtC,6DAA6D;SAC7D,CAAC;IACH,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;QACvB,MAAM,MAAM,GACX,MAAM,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC;QACtG,OAAO,CAAC,yBAAyB,MAAM,EAAE,EAAE,KAAK,MAAM,CAAC,KAAK,IAAI,8BAA8B,EAAE,CAAC,CAAC;IACnG,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,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;IACjF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,mEAAmE;QACnE,iDAAiD;QACjD,MAAM,GAAG;YACR,UAAU,EAAE,IAAI;YAChB,SAAS,EAAE,KAAK;YAChB,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;SAC7D,CAAC;IACH,CAAC;IAED,IAAI,IAAI;QAAE,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;;QAChD,KAAK,MAAM,IAAI,IAAI,QAAQ,CAAC,MAAM,CAAC;YAAE,SAAS,CAAC,IAAI,CAAC,CAAC;IAE1D,IAAI,CAAC,MAAM,CAAC,UAAU;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;IAC9D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAAA,CAC7D","sourcesContent":["import {\n\ttype AdaptOrchApiClient,\n\tAdaptOrchApiError,\n\ttype AdaptOrchFetch,\n\tcreateAdaptOrchApiClientFromEnv,\n} from \"omk-adaptorch-wpl\";\n\n/**\n * Headless AdaptOrch connectivity check:\n *\n * omk doctor adaptorch [--json]\n *\n * One command answers the only question that blocks getting started: does the\n * configured key reach the hosted API? It calls `GET /v1/whoami`, which is the\n * cheapest authenticated read in the contract, and reports the principal it\n * resolved to.\n *\n * The exit code carries the verdict so a script can branch without parsing\n * prose: 0 verified, 1 not configured, 2 configured but unreachable. Those are\n * genuinely different states — \"no key\" is a setup step, while \"key rejected\"\n * is a broken setup, and collapsing them would make the command useless in CI.\n *\n * The credential is never printed. `omk-adaptorch-wpl` already scrubs it from\n * its own errors; this command additionally never echoes the configured value.\n */\n\nconst USAGE = \"Usage: omk doctor adaptorch [--json]\";\n\n/**\n * Where to obtain a key. This is the one moment in the CLI where the reader has\n * explicitly asked about AdaptOrch, so answering \"which key, from where\" here\n * is help rather than promotion. It carries its own attribution so this\n * touchpoint stays distinguishable from the README links.\n */\nconst ADAPTORCH_SIGNUP_URL = \"https://adaptorch.com/?utm_source=omk-cli&utm_medium=doctor&utm_campaign=omk#pricing\";\n\nexport interface AdaptOrchDoctorCliOverrides {\n\treadonly env?: NodeJS.ProcessEnv;\n\treadonly writeLine?: (line: string) => void;\n\t/** Test seam: replaces the injected HTTP boundary (defaults to global fetch). */\n\treadonly fetch?: AdaptOrchFetch;\n}\n\nexport interface AdaptOrchDoctorCliOutcome {\n\treadonly handled: boolean;\n\treadonly exitCode: number;\n}\n\n/** Bounded report shape. Carries no credential, URL credentials, or raw error bodies. */\ninterface AdaptOrchDoctorReport {\n\treadonly configured: boolean;\n\treadonly reachable: boolean;\n\treadonly subjectId?: string;\n\treadonly projectId?: string;\n\treadonly status?: number;\n\treadonly code?: string;\n\treadonly error?: string;\n}\n\nfunction describe(report: AdaptOrchDoctorReport): string[] {\n\tif (!report.configured) {\n\t\treturn [\n\t\t\t\"AdaptOrch: not configured\",\n\t\t\t\" Set ADAPTORCH_API_KEY to enable it. Optionally set ADAPTORCH_API_URL.\",\n\t\t\t` Get a key: ${ADAPTORCH_SIGNUP_URL}`,\n\t\t\t\" AdaptOrch is a separate product; OMK does not require it.\",\n\t\t];\n\t}\n\tif (!report.reachable) {\n\t\tconst detail =\n\t\t\treport.status === undefined ? \"\" : ` (HTTP ${report.status}${report.code ? ` ${report.code}` : \"\"})`;\n\t\treturn [`AdaptOrch: unreachable${detail}`, ` ${report.error ?? \"the request did not complete\"}`];\n\t}\n\tconst scope = report.projectId ? `, project ${report.projectId}` : \"\";\n\treturn [`AdaptOrch: verified`, ` Authenticated as ${report.subjectId ?? \"(unknown subject)\"}${scope}`];\n}\n\nasync function probe(client: AdaptOrchApiClient): Promise<AdaptOrchDoctorReport> {\n\ttry {\n\t\tconst principal = await client.whoami();\n\t\treturn {\n\t\t\tconfigured: true,\n\t\t\treachable: true,\n\t\t\tsubjectId: principal.subject_id,\n\t\t\t...(principal.project_id === undefined ? {} : { projectId: principal.project_id }),\n\t\t};\n\t} catch (error) {\n\t\tif (error instanceof AdaptOrchApiError) {\n\t\t\treturn {\n\t\t\t\tconfigured: true,\n\t\t\t\treachable: false,\n\t\t\t\tstatus: error.status,\n\t\t\t\t...(error.code === undefined ? {} : { code: error.code }),\n\t\t\t\terror: error.message,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tconfigured: true,\n\t\t\treachable: false,\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t};\n\t}\n}\n\nexport async function runAdaptOrchDoctorCli(\n\targs: readonly string[],\n\toverrides: AdaptOrchDoctorCliOverrides = {},\n): Promise<AdaptOrchDoctorCliOutcome> {\n\tif (args[0] !== \"doctor\" || args[1] !== \"adaptorch\") {\n\t\treturn { handled: false, exitCode: 0 };\n\t}\n\tconst writeLine = overrides.writeLine ?? ((line: string) => console.log(line));\n\n\tlet json = false;\n\tfor (const arg of args.slice(2)) {\n\t\tif (arg === \"--json\") {\n\t\t\tjson = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--help\" || arg === \"-h\") {\n\t\t\twriteLine(USAGE);\n\t\t\treturn { handled: true, exitCode: 0 };\n\t\t}\n\t\twriteLine(`Unknown option: ${arg}`);\n\t\twriteLine(USAGE);\n\t\treturn { handled: true, exitCode: 2 };\n\t}\n\n\tconst env = overrides.env ?? process.env;\n\tconst fetchImpl = overrides.fetch ?? (globalThis.fetch as unknown as AdaptOrchFetch);\n\n\tlet report: AdaptOrchDoctorReport;\n\ttry {\n\t\tconst client = createAdaptOrchApiClientFromEnv(fetchImpl, env);\n\t\treport = client ? await probe(client) : { configured: false, reachable: false };\n\t} catch (error) {\n\t\t// A configured but invalid setup (an unsafe ADAPTORCH_API_URL, for\n\t\t// example) is a broken setup, not an absent one.\n\t\treport = {\n\t\t\tconfigured: true,\n\t\t\treachable: false,\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t};\n\t}\n\n\tif (json) writeLine(JSON.stringify(report, null, 2));\n\telse for (const line of describe(report)) writeLine(line);\n\n\tif (!report.configured) return { handled: true, exitCode: 1 };\n\treturn { handled: true, exitCode: report.reachable ? 0 : 2 };\n}\n"]}
@@ -1,5 +1,7 @@
1
1
  import { captureHostResourceSnapshot } from "../core/host-resource-snapshot.ts";
2
2
  import { type ResourceGovernorSettings } from "../core/resource-governor-settings.ts";
3
+ import { collectResourceObservationReport, RESOURCE_REPORT_MIN_ADMISSIONS, type ResourceObservationReport } from "../core/resource-observation-report.ts";
4
+ export { collectResourceObservationReport, RESOURCE_REPORT_MIN_ADMISSIONS, type ResourceObservationReport };
3
5
  export interface ResourceDoctorCliOverrides {
4
6
  readonly cwd?: string;
5
7
  readonly env?: NodeJS.ProcessEnv;
@@ -13,6 +15,8 @@ export interface ResourceDoctorCliOverrides {
13
15
  readonly capture?: typeof captureHostResourceSnapshot;
14
16
  /** Test seam: monotonic clock for probeDurationMs. */
15
17
  readonly now?: () => number;
18
+ /** Test seam: replaces local observation aggregation. */
19
+ readonly collectReport?: (cwd: string) => ResourceObservationReport;
16
20
  }
17
21
  export interface ResourceDoctorCliOutcome {
18
22
  readonly handled: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"resource-doctor-cli.d.ts","sourceRoot":"","sources":["../../src/commands/resource-doctor-cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAA6B,MAAM,mCAAmC,CAAC;AAE3G,OAAO,EAIN,KAAK,wBAAwB,EAE7B,MAAM,uCAAuC,CAAC;AAiB/C,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACjC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5C,sFAAsF;IACtF,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM;QAC7B,QAAQ,CAAC,gBAAgB,CAAC,EAAE,wBAAwB,CAAC;QACrD,QAAQ,CAAC,4BAA4B,CAAC,EAAE,MAAM,CAAC;KAC/C,CAAC;IACF,0CAA0C;IAC1C,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,2BAA2B,CAAC;IACtD,sDAAsD;IACtD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC1B;AAED,wBAAsB,oBAAoB,CACzC,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,SAAS,GAAE,0BAA+B,GACxC,OAAO,CAAC,wBAAwB,CAAC,CAsCnC","sourcesContent":["import { captureHostResourceSnapshot, type HostResourceSnapshot } from \"../core/host-resource-snapshot.ts\";\nimport { decideResourceAdmission } from \"../core/resource-admission.ts\";\nimport {\n\tbuildResourceDoctorReport,\n\tformatResourceProbeLines,\n\tformatResourceSummaryLines,\n\ttype ResourceGovernorSettings,\n\tresolveResourceGovernorSettings,\n} from \"../core/resource-governor-settings.ts\";\nimport { SettingsManager } from \"../core/settings-manager.ts\";\n\n/**\n * Headless resource diagnostic (OMK v0.97.x roadmap §19.2, M1/PR2):\n *\n * omk doctor resources [--json]\n *\n * Observe-only: probes the host, evaluates the admission policy, and prints\n * either aligned human output or the bounded §19.2 JSON schema. This command\n * is the sanctioned local surface for raw capacity values (§11.3); it still\n * never prints usernames, hostnames, or paths (§6.2). The doctor probes even\n * when the governor mode is `off` because it only runs on explicit request.\n */\n\nconst USAGE = \"Usage: omk doctor resources [--json]\";\n\nexport interface ResourceDoctorCliOverrides {\n\treadonly cwd?: string;\n\treadonly env?: NodeJS.ProcessEnv;\n\treadonly writeLine?: (line: string) => void;\n\t/** Test seam: replaces settings loading (defaults to SettingsManager.create(cwd)). */\n\treadonly loadSettings?: () => {\n\t\treadonly resourceGovernor?: ResourceGovernorSettings;\n\t\treadonly configuredMaxToolConcurrency?: number;\n\t};\n\t/** Test seam: replaces the host probe. */\n\treadonly capture?: typeof captureHostResourceSnapshot;\n\t/** Test seam: monotonic clock for probeDurationMs. */\n\treadonly now?: () => number;\n}\n\nexport interface ResourceDoctorCliOutcome {\n\treadonly handled: boolean;\n\treadonly exitCode: number;\n}\n\nexport async function runResourceDoctorCli(\n\targs: readonly string[],\n\toverrides: ResourceDoctorCliOverrides = {},\n): Promise<ResourceDoctorCliOutcome> {\n\tif (args[0] !== \"doctor\" || args[1] !== \"resources\") {\n\t\treturn { handled: false, exitCode: 0 };\n\t}\n\tconst writeLine = overrides.writeLine ?? ((line: string) => console.log(line));\n\n\tconst flags = parseDoctorFlags(args.slice(2), writeLine);\n\tif (flags.exit !== null) {\n\t\treturn { handled: true, exitCode: flags.exit };\n\t}\n\tconst json = flags.json;\n\n\tconst settings = (overrides.loadSettings ?? (() => loadSettingsFromDisk(overrides.cwd)))();\n\tconst resolved = resolveResourceGovernorSettings(settings.resourceGovernor, overrides.env ?? process.env);\n\n\tconst capture = overrides.capture ?? captureHostResourceSnapshot;\n\tconst now = overrides.now ?? (() => performance.now());\n\tconst startedAt = now();\n\tconst snapshot: HostResourceSnapshot = await capture({\n\t\tcwd: overrides.cwd,\n\t\tmaxProbeMs: resolved.maxProbeMs,\n\t\tcpuSampleMs: resolved.cpuSampleMs,\n\t});\n\tconst probeDurationMs = Math.max(0, now() - startedAt);\n\n\tconst decision = decideResourceAdmission({\n\t\tsnapshot,\n\t\tconfig: resolved.admission,\n\t\tconfiguredCaps: { maxToolConcurrency: settings.configuredMaxToolConcurrency },\n\t});\n\n\tif (json) {\n\t\tconst report = buildResourceDoctorReport({ snapshot, decision, resolved, probeDurationMs });\n\t\twriteLine(JSON.stringify(report, null, 2));\n\t\treturn { handled: true, exitCode: 0 };\n\t}\n\trenderHumanReport({ writeLine, resolved, decision, snapshot, probeDurationMs });\n\treturn { handled: true, exitCode: 0 };\n}\n\nfunction parseDoctorFlags(\n\targs: readonly string[],\n\twriteLine: (line: string) => void,\n): { readonly json: boolean; readonly exit: number | null } {\n\tlet json = false;\n\tfor (const arg of args) {\n\t\tif (arg === \"--json\") {\n\t\t\tjson = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--help\" || arg === \"-h\") {\n\t\t\twriteLine(USAGE);\n\t\t\treturn { json, exit: 0 };\n\t\t}\n\t\twriteLine(`Unknown argument: ${arg}`);\n\t\twriteLine(USAGE);\n\t\treturn { json, exit: 2 };\n\t}\n\treturn { json, exit: null };\n}\n\nfunction renderHumanReport(input: {\n\treadonly writeLine: (line: string) => void;\n\treadonly resolved: ReturnType<typeof resolveResourceGovernorSettings>;\n\treadonly decision: ReturnType<typeof decideResourceAdmission>;\n\treadonly snapshot: HostResourceSnapshot;\n\treadonly probeDurationMs: number;\n}): void {\n\tconst { writeLine, resolved, decision, snapshot, probeDurationMs } = input;\n\twriteLine(\"Resource doctor\");\n\twriteLine(\"\");\n\tfor (const line of formatResourceSummaryLines(resolved.mode, decision)) {\n\t\twriteLine(line);\n\t}\n\twriteLine(\"\");\n\tfor (const line of formatResourceProbeLines(snapshot)) {\n\t\twriteLine(line);\n\t}\n\twriteLine(\"\");\n\twriteLine(`probe duration: ${Math.round(probeDurationMs)} ms`);\n\tfor (const error of resolved.errors) {\n\t\twriteLine(`settings error: ${error}`);\n\t}\n}\n\nfunction loadSettingsFromDisk(cwd: string | undefined): {\n\treadonly resourceGovernor?: ResourceGovernorSettings;\n\treadonly configuredMaxToolConcurrency?: number;\n} {\n\ttry {\n\t\tconst manager = SettingsManager.create(cwd ?? process.cwd());\n\t\treturn {\n\t\t\tresourceGovernor: manager.getResourceGovernorSettings(),\n\t\t\tconfiguredMaxToolConcurrency: manager.getAgentRuntimeSettings().maxToolConcurrency,\n\t\t};\n\t} catch {\n\t\t// A broken settings file must not block the diagnostic; defaults apply.\n\t\treturn {};\n\t}\n}\n"]}
1
+ {"version":3,"file":"resource-doctor-cli.d.ts","sourceRoot":"","sources":["../../src/commands/resource-doctor-cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAA6B,MAAM,mCAAmC,CAAC;AAE3G,OAAO,EAIN,KAAK,wBAAwB,EAE7B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACN,gCAAgC,EAChC,8BAA8B,EAC9B,KAAK,yBAAyB,EAC9B,MAAM,wCAAwC,CAAC;AAGhD,OAAO,EAAE,gCAAgC,EAAE,8BAA8B,EAAE,KAAK,yBAAyB,EAAE,CAAC;AAgB5G,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACjC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5C,sFAAsF;IACtF,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM;QAC7B,QAAQ,CAAC,gBAAgB,CAAC,EAAE,wBAAwB,CAAC;QACrD,QAAQ,CAAC,4BAA4B,CAAC,EAAE,MAAM,CAAC;KAC/C,CAAC;IACF,0CAA0C;IAC1C,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,2BAA2B,CAAC;IACtD,sDAAsD;IACtD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IAC5B,yDAAyD;IACzD,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,yBAAyB,CAAC;CACpE;AAED,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC1B;AAED,wBAAsB,oBAAoB,CACzC,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,SAAS,GAAE,0BAA+B,GACxC,OAAO,CAAC,wBAAwB,CAAC,CA4CnC","sourcesContent":["import { captureHostResourceSnapshot, type HostResourceSnapshot } from \"../core/host-resource-snapshot.ts\";\nimport { decideResourceAdmission } from \"../core/resource-admission.ts\";\nimport {\n\tbuildResourceDoctorReport,\n\tformatResourceProbeLines,\n\tformatResourceSummaryLines,\n\ttype ResourceGovernorSettings,\n\tresolveResourceGovernorSettings,\n} from \"../core/resource-governor-settings.ts\";\nimport {\n\tcollectResourceObservationReport,\n\tRESOURCE_REPORT_MIN_ADMISSIONS,\n\ttype ResourceObservationReport,\n} from \"../core/resource-observation-report.ts\";\nimport { SettingsManager } from \"../core/settings-manager.ts\";\n\nexport { collectResourceObservationReport, RESOURCE_REPORT_MIN_ADMISSIONS, type ResourceObservationReport };\n\n/**\n * Headless resource diagnostic (OMK v0.97.x roadmap §19.2, M1/PR2):\n *\n * omk doctor resources [--json] [--report]\n *\n * Observe-only: probes the host, evaluates the admission policy, and prints\n * either aligned human output or the bounded §19.2 JSON schema. This command\n * is the sanctioned local surface for raw capacity values (§11.3); it still\n * never prints usernames, hostnames, or paths (§6.2). The doctor probes even\n * when the governor mode is `off` because it only runs on explicit request.\n */\n\nconst USAGE = \"Usage: omk doctor resources [--json] [--report]\";\n\nexport interface ResourceDoctorCliOverrides {\n\treadonly cwd?: string;\n\treadonly env?: NodeJS.ProcessEnv;\n\treadonly writeLine?: (line: string) => void;\n\t/** Test seam: replaces settings loading (defaults to SettingsManager.create(cwd)). */\n\treadonly loadSettings?: () => {\n\t\treadonly resourceGovernor?: ResourceGovernorSettings;\n\t\treadonly configuredMaxToolConcurrency?: number;\n\t};\n\t/** Test seam: replaces the host probe. */\n\treadonly capture?: typeof captureHostResourceSnapshot;\n\t/** Test seam: monotonic clock for probeDurationMs. */\n\treadonly now?: () => number;\n\t/** Test seam: replaces local observation aggregation. */\n\treadonly collectReport?: (cwd: string) => ResourceObservationReport;\n}\n\nexport interface ResourceDoctorCliOutcome {\n\treadonly handled: boolean;\n\treadonly exitCode: number;\n}\n\nexport async function runResourceDoctorCli(\n\targs: readonly string[],\n\toverrides: ResourceDoctorCliOverrides = {},\n): Promise<ResourceDoctorCliOutcome> {\n\tif (args[0] !== \"doctor\" || args[1] !== \"resources\") {\n\t\treturn { handled: false, exitCode: 0 };\n\t}\n\tconst writeLine = overrides.writeLine ?? ((line: string) => console.log(line));\n\n\tconst flags = parseDoctorFlags(args.slice(2), writeLine);\n\tif (flags.exit !== null) {\n\t\treturn { handled: true, exitCode: flags.exit };\n\t}\n\tconst json = flags.json;\n\tif (flags.report) {\n\t\tconst report = (overrides.collectReport ?? collectResourceObservationReport)(overrides.cwd ?? process.cwd());\n\t\tif (json) writeLine(JSON.stringify(report, null, 2));\n\t\telse renderObservationReport(report, writeLine);\n\t\treturn { handled: true, exitCode: 0 };\n\t}\n\n\tconst settings = (overrides.loadSettings ?? (() => loadSettingsFromDisk(overrides.cwd)))();\n\tconst resolved = resolveResourceGovernorSettings(settings.resourceGovernor, overrides.env ?? process.env);\n\n\tconst capture = overrides.capture ?? captureHostResourceSnapshot;\n\tconst now = overrides.now ?? (() => performance.now());\n\tconst startedAt = now();\n\tconst snapshot: HostResourceSnapshot = await capture({\n\t\tcwd: overrides.cwd,\n\t\tmaxProbeMs: resolved.maxProbeMs,\n\t\tcpuSampleMs: resolved.cpuSampleMs,\n\t});\n\tconst probeDurationMs = Math.max(0, now() - startedAt);\n\n\tconst decision = decideResourceAdmission({\n\t\tsnapshot,\n\t\tconfig: resolved.admission,\n\t\tconfiguredCaps: { maxToolConcurrency: settings.configuredMaxToolConcurrency },\n\t});\n\n\tif (json) {\n\t\tconst report = buildResourceDoctorReport({ snapshot, decision, resolved, probeDurationMs });\n\t\twriteLine(JSON.stringify(report, null, 2));\n\t\treturn { handled: true, exitCode: 0 };\n\t}\n\trenderHumanReport({ writeLine, resolved, decision, snapshot, probeDurationMs });\n\treturn { handled: true, exitCode: 0 };\n}\n\nfunction parseDoctorFlags(\n\targs: readonly string[],\n\twriteLine: (line: string) => void,\n): { readonly json: boolean; readonly report: boolean; readonly exit: number | null } {\n\tlet json = false;\n\tlet report = false;\n\tfor (const arg of args) {\n\t\tif (arg === \"--json\") {\n\t\t\tjson = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--report\") {\n\t\t\treport = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--help\" || arg === \"-h\") {\n\t\t\twriteLine(USAGE);\n\t\t\treturn { json, report, exit: 0 };\n\t\t}\n\t\twriteLine(`Unknown argument: ${arg}`);\n\t\twriteLine(USAGE);\n\t\treturn { json, report, exit: 2 };\n\t}\n\treturn { json, report, exit: null };\n}\n\nfunction renderObservationReport(report: ResourceObservationReport, writeLine: (line: string) => void): void {\n\twriteLine(\"Resource observation report\");\n\twriteLine(`journals scanned: ${report.journalsScanned}${report.truncated ? \" (truncated)\" : \"\"}`);\n\twriteLine(`admission records: ${report.admissionRecords}`);\n\twriteLine(`reason-qualified records: ${report.reasonRecords}`);\n\twriteLine(\n\t\t`pressure: normal ${report.pressure.normal}, constrained ${report.pressure.constrained}, critical ${report.pressure.critical}`,\n\t);\n\twriteLine(\n\t\t`actions: allow ${report.actions.allow}, throttle ${report.actions.throttle}, defer-heavy ${report.actions[\"defer-heavy\"]}`,\n\t);\n\twriteLine(`would have throttled: ${report.wouldHaveThrottled}`);\n\twriteLine(`probe partial/timeout: ${report.probePartial}/${report.probeTimeout}`);\n\twriteLine(\n\t\t`minimum sample: ${report.reasonRecords}/${report.minimumSampleSize} (${report.minimumSampleMet ? \"met\" : \"not met\"})`,\n\t);\n\twriteLine(`reason coverage complete: ${report.reasonCoverageComplete ? \"yes\" : \"no\"}`);\n\twriteLine(\"human review: required\");\n\tif (report.diagnostics > 0) writeLine(`diagnostics: ${report.diagnostics}`);\n}\n\nfunction renderHumanReport(input: {\n\treadonly writeLine: (line: string) => void;\n\treadonly resolved: ReturnType<typeof resolveResourceGovernorSettings>;\n\treadonly decision: ReturnType<typeof decideResourceAdmission>;\n\treadonly snapshot: HostResourceSnapshot;\n\treadonly probeDurationMs: number;\n}): void {\n\tconst { writeLine, resolved, decision, snapshot, probeDurationMs } = input;\n\twriteLine(\"Resource doctor\");\n\twriteLine(\"\");\n\tfor (const line of formatResourceSummaryLines(resolved.mode, decision)) {\n\t\twriteLine(line);\n\t}\n\twriteLine(\"\");\n\tfor (const line of formatResourceProbeLines(snapshot)) {\n\t\twriteLine(line);\n\t}\n\twriteLine(\"\");\n\twriteLine(`probe duration: ${Math.round(probeDurationMs)} ms`);\n\tfor (const error of resolved.errors) {\n\t\twriteLine(`settings error: ${error}`);\n\t}\n}\n\nfunction loadSettingsFromDisk(cwd: string | undefined): {\n\treadonly resourceGovernor?: ResourceGovernorSettings;\n\treadonly configuredMaxToolConcurrency?: number;\n} {\n\ttry {\n\t\tconst manager = SettingsManager.create(cwd ?? process.cwd());\n\t\treturn {\n\t\t\tresourceGovernor: manager.getResourceGovernorSettings(),\n\t\t\tconfiguredMaxToolConcurrency: manager.getAgentRuntimeSettings().maxToolConcurrency,\n\t\t};\n\t} catch {\n\t\t// A broken settings file must not block the diagnostic; defaults apply.\n\t\treturn {};\n\t}\n}\n"]}
@@ -1,11 +1,13 @@
1
1
  import { captureHostResourceSnapshot } from "../core/host-resource-snapshot.js";
2
2
  import { decideResourceAdmission } from "../core/resource-admission.js";
3
3
  import { buildResourceDoctorReport, formatResourceProbeLines, formatResourceSummaryLines, resolveResourceGovernorSettings, } from "../core/resource-governor-settings.js";
4
+ import { collectResourceObservationReport, RESOURCE_REPORT_MIN_ADMISSIONS, } from "../core/resource-observation-report.js";
4
5
  import { SettingsManager } from "../core/settings-manager.js";
6
+ export { collectResourceObservationReport, RESOURCE_REPORT_MIN_ADMISSIONS };
5
7
  /**
6
8
  * Headless resource diagnostic (OMK v0.97.x roadmap §19.2, M1/PR2):
7
9
  *
8
- * omk doctor resources [--json]
10
+ * omk doctor resources [--json] [--report]
9
11
  *
10
12
  * Observe-only: probes the host, evaluates the admission policy, and prints
11
13
  * either aligned human output or the bounded §19.2 JSON schema. This command
@@ -13,7 +15,7 @@ import { SettingsManager } from "../core/settings-manager.js";
13
15
  * never prints usernames, hostnames, or paths (§6.2). The doctor probes even
14
16
  * when the governor mode is `off` because it only runs on explicit request.
15
17
  */
16
- const USAGE = "Usage: omk doctor resources [--json]";
18
+ const USAGE = "Usage: omk doctor resources [--json] [--report]";
17
19
  export async function runResourceDoctorCli(args, overrides = {}) {
18
20
  if (args[0] !== "doctor" || args[1] !== "resources") {
19
21
  return { handled: false, exitCode: 0 };
@@ -24,6 +26,14 @@ export async function runResourceDoctorCli(args, overrides = {}) {
24
26
  return { handled: true, exitCode: flags.exit };
25
27
  }
26
28
  const json = flags.json;
29
+ if (flags.report) {
30
+ const report = (overrides.collectReport ?? collectResourceObservationReport)(overrides.cwd ?? process.cwd());
31
+ if (json)
32
+ writeLine(JSON.stringify(report, null, 2));
33
+ else
34
+ renderObservationReport(report, writeLine);
35
+ return { handled: true, exitCode: 0 };
36
+ }
27
37
  const settings = (overrides.loadSettings ?? (() => loadSettingsFromDisk(overrides.cwd)))();
28
38
  const resolved = resolveResourceGovernorSettings(settings.resourceGovernor, overrides.env ?? process.env);
29
39
  const capture = overrides.capture ?? captureHostResourceSnapshot;
@@ -50,20 +60,40 @@ export async function runResourceDoctorCli(args, overrides = {}) {
50
60
  }
51
61
  function parseDoctorFlags(args, writeLine) {
52
62
  let json = false;
63
+ let report = false;
53
64
  for (const arg of args) {
54
65
  if (arg === "--json") {
55
66
  json = true;
56
67
  continue;
57
68
  }
69
+ if (arg === "--report") {
70
+ report = true;
71
+ continue;
72
+ }
58
73
  if (arg === "--help" || arg === "-h") {
59
74
  writeLine(USAGE);
60
- return { json, exit: 0 };
75
+ return { json, report, exit: 0 };
61
76
  }
62
77
  writeLine(`Unknown argument: ${arg}`);
63
78
  writeLine(USAGE);
64
- return { json, exit: 2 };
79
+ return { json, report, exit: 2 };
65
80
  }
66
- return { json, exit: null };
81
+ return { json, report, exit: null };
82
+ }
83
+ function renderObservationReport(report, writeLine) {
84
+ writeLine("Resource observation report");
85
+ writeLine(`journals scanned: ${report.journalsScanned}${report.truncated ? " (truncated)" : ""}`);
86
+ writeLine(`admission records: ${report.admissionRecords}`);
87
+ writeLine(`reason-qualified records: ${report.reasonRecords}`);
88
+ writeLine(`pressure: normal ${report.pressure.normal}, constrained ${report.pressure.constrained}, critical ${report.pressure.critical}`);
89
+ writeLine(`actions: allow ${report.actions.allow}, throttle ${report.actions.throttle}, defer-heavy ${report.actions["defer-heavy"]}`);
90
+ writeLine(`would have throttled: ${report.wouldHaveThrottled}`);
91
+ writeLine(`probe partial/timeout: ${report.probePartial}/${report.probeTimeout}`);
92
+ writeLine(`minimum sample: ${report.reasonRecords}/${report.minimumSampleSize} (${report.minimumSampleMet ? "met" : "not met"})`);
93
+ writeLine(`reason coverage complete: ${report.reasonCoverageComplete ? "yes" : "no"}`);
94
+ writeLine("human review: required");
95
+ if (report.diagnostics > 0)
96
+ writeLine(`diagnostics: ${report.diagnostics}`);
67
97
  }
68
98
  function renderHumanReport(input) {
69
99
  const { writeLine, resolved, decision, snapshot, probeDurationMs } = input;
@@ -1 +1 @@
1
- {"version":3,"file":"resource-doctor-cli.js","sourceRoot":"","sources":["../../src/commands/resource-doctor-cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAA6B,MAAM,mCAAmC,CAAC;AAC3G,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EACN,yBAAyB,EACzB,wBAAwB,EACxB,0BAA0B,EAE1B,+BAA+B,GAC/B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAE9D;;;;;;;;;;GAUG;AAEH,MAAM,KAAK,GAAG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C;QAC7D,OAAO;YACN,gBAAgB,EAAE,OAAO,CAAC,2BAA2B,EAAE;YACvD,4BAA4B,EAAE,OAAO,CAAC,uBAAuB,EAAE,CAAC,kBAAkB;SAClF,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACR,wEAAwE;QACxE,OAAO,EAAE,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["import { captureHostResourceSnapshot, type HostResourceSnapshot } from \"../core/host-resource-snapshot.ts\";\nimport { decideResourceAdmission } from \"../core/resource-admission.ts\";\nimport {\n\tbuildResourceDoctorReport,\n\tformatResourceProbeLines,\n\tformatResourceSummaryLines,\n\ttype ResourceGovernorSettings,\n\tresolveResourceGovernorSettings,\n} from \"../core/resource-governor-settings.ts\";\nimport { SettingsManager } from \"../core/settings-manager.ts\";\n\n/**\n * Headless resource diagnostic (OMK v0.97.x roadmap §19.2, M1/PR2):\n *\n * omk doctor resources [--json]\n *\n * Observe-only: probes the host, evaluates the admission policy, and prints\n * either aligned human output or the bounded §19.2 JSON schema. This command\n * is the sanctioned local surface for raw capacity values (§11.3); it still\n * never prints usernames, hostnames, or paths (§6.2). The doctor probes even\n * when the governor mode is `off` because it only runs on explicit request.\n */\n\nconst USAGE = \"Usage: omk doctor resources [--json]\";\n\nexport interface ResourceDoctorCliOverrides {\n\treadonly cwd?: string;\n\treadonly env?: NodeJS.ProcessEnv;\n\treadonly writeLine?: (line: string) => void;\n\t/** Test seam: replaces settings loading (defaults to SettingsManager.create(cwd)). */\n\treadonly loadSettings?: () => {\n\t\treadonly resourceGovernor?: ResourceGovernorSettings;\n\t\treadonly configuredMaxToolConcurrency?: number;\n\t};\n\t/** Test seam: replaces the host probe. */\n\treadonly capture?: typeof captureHostResourceSnapshot;\n\t/** Test seam: monotonic clock for probeDurationMs. */\n\treadonly now?: () => number;\n}\n\nexport interface ResourceDoctorCliOutcome {\n\treadonly handled: boolean;\n\treadonly exitCode: number;\n}\n\nexport async function runResourceDoctorCli(\n\targs: readonly string[],\n\toverrides: ResourceDoctorCliOverrides = {},\n): Promise<ResourceDoctorCliOutcome> {\n\tif (args[0] !== \"doctor\" || args[1] !== \"resources\") {\n\t\treturn { handled: false, exitCode: 0 };\n\t}\n\tconst writeLine = overrides.writeLine ?? ((line: string) => console.log(line));\n\n\tconst flags = parseDoctorFlags(args.slice(2), writeLine);\n\tif (flags.exit !== null) {\n\t\treturn { handled: true, exitCode: flags.exit };\n\t}\n\tconst json = flags.json;\n\n\tconst settings = (overrides.loadSettings ?? (() => loadSettingsFromDisk(overrides.cwd)))();\n\tconst resolved = resolveResourceGovernorSettings(settings.resourceGovernor, overrides.env ?? process.env);\n\n\tconst capture = overrides.capture ?? captureHostResourceSnapshot;\n\tconst now = overrides.now ?? (() => performance.now());\n\tconst startedAt = now();\n\tconst snapshot: HostResourceSnapshot = await capture({\n\t\tcwd: overrides.cwd,\n\t\tmaxProbeMs: resolved.maxProbeMs,\n\t\tcpuSampleMs: resolved.cpuSampleMs,\n\t});\n\tconst probeDurationMs = Math.max(0, now() - startedAt);\n\n\tconst decision = decideResourceAdmission({\n\t\tsnapshot,\n\t\tconfig: resolved.admission,\n\t\tconfiguredCaps: { maxToolConcurrency: settings.configuredMaxToolConcurrency },\n\t});\n\n\tif (json) {\n\t\tconst report = buildResourceDoctorReport({ snapshot, decision, resolved, probeDurationMs });\n\t\twriteLine(JSON.stringify(report, null, 2));\n\t\treturn { handled: true, exitCode: 0 };\n\t}\n\trenderHumanReport({ writeLine, resolved, decision, snapshot, probeDurationMs });\n\treturn { handled: true, exitCode: 0 };\n}\n\nfunction parseDoctorFlags(\n\targs: readonly string[],\n\twriteLine: (line: string) => void,\n): { readonly json: boolean; readonly exit: number | null } {\n\tlet json = false;\n\tfor (const arg of args) {\n\t\tif (arg === \"--json\") {\n\t\t\tjson = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--help\" || arg === \"-h\") {\n\t\t\twriteLine(USAGE);\n\t\t\treturn { json, exit: 0 };\n\t\t}\n\t\twriteLine(`Unknown argument: ${arg}`);\n\t\twriteLine(USAGE);\n\t\treturn { json, exit: 2 };\n\t}\n\treturn { json, exit: null };\n}\n\nfunction renderHumanReport(input: {\n\treadonly writeLine: (line: string) => void;\n\treadonly resolved: ReturnType<typeof resolveResourceGovernorSettings>;\n\treadonly decision: ReturnType<typeof decideResourceAdmission>;\n\treadonly snapshot: HostResourceSnapshot;\n\treadonly probeDurationMs: number;\n}): void {\n\tconst { writeLine, resolved, decision, snapshot, probeDurationMs } = input;\n\twriteLine(\"Resource doctor\");\n\twriteLine(\"\");\n\tfor (const line of formatResourceSummaryLines(resolved.mode, decision)) {\n\t\twriteLine(line);\n\t}\n\twriteLine(\"\");\n\tfor (const line of formatResourceProbeLines(snapshot)) {\n\t\twriteLine(line);\n\t}\n\twriteLine(\"\");\n\twriteLine(`probe duration: ${Math.round(probeDurationMs)} ms`);\n\tfor (const error of resolved.errors) {\n\t\twriteLine(`settings error: ${error}`);\n\t}\n}\n\nfunction loadSettingsFromDisk(cwd: string | undefined): {\n\treadonly resourceGovernor?: ResourceGovernorSettings;\n\treadonly configuredMaxToolConcurrency?: number;\n} {\n\ttry {\n\t\tconst manager = SettingsManager.create(cwd ?? process.cwd());\n\t\treturn {\n\t\t\tresourceGovernor: manager.getResourceGovernorSettings(),\n\t\t\tconfiguredMaxToolConcurrency: manager.getAgentRuntimeSettings().maxToolConcurrency,\n\t\t};\n\t} catch {\n\t\t// A broken settings file must not block the diagnostic; defaults apply.\n\t\treturn {};\n\t}\n}\n"]}
1
+ {"version":3,"file":"resource-doctor-cli.js","sourceRoot":"","sources":["../../src/commands/resource-doctor-cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAA6B,MAAM,mCAAmC,CAAC;AAC3G,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EACN,yBAAyB,EACzB,wBAAwB,EACxB,0BAA0B,EAE1B,+BAA+B,GAC/B,MAAM,uCAAuC,CAAC;A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E,QAAQ,EAAE,eAAe,EAAE,GAAG,KAAK,CAAC;IAC3E,SAAS,CAAC,iBAAiB,CAAC,CAAC;IAC7B,SAAS,CAAC,EAAE,CAAC,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,0BAA0B,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,CAAC;QACxE,SAAS,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;IACD,SAAS,CAAC,EAAE,CAAC,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,wBAAwB,CAAC,QAAQ,CAAC,EAAE,CAAC;QACvD,SAAS,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;IACD,SAAS,CAAC,EAAE,CAAC,CAAC;IACd,SAAS,CAAC,mBAAmB,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IAC/D,KAAK,MAAM,KAAK,IAAI,QAAQ,CAAC,MAAM,EAAE,CAAC;QACrC,SAAS,CAAC,mBAAmB,KAAK,EAAE,CAAC,CAAC;IACvC,CAAC;AAAA,CACD;AAED,SAAS,oBAAoB,CAAC,GAAuB,EAGnD;IACD,IAAI,CAAC;QACJ,MAAM,OAAO,GAAG,eAAe,CAAC,MAAM,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;QAC7D,OAAO;YACN,gBAAgB,EAAE,OAAO,CAAC,2BAA2B,EAAE;YACvD,4BAA4B,EAAE,OAAO,CAAC,uBAAuB,EAAE,CAAC,kBAAkB;SAClF,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACR,wEAAwE;QACxE,OAAO,EAAE,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["import { captureHostResourceSnapshot, type HostResourceSnapshot } from \"../core/host-resource-snapshot.ts\";\nimport { decideResourceAdmission } from \"../core/resource-admission.ts\";\nimport {\n\tbuildResourceDoctorReport,\n\tformatResourceProbeLines,\n\tformatResourceSummaryLines,\n\ttype ResourceGovernorSettings,\n\tresolveResourceGovernorSettings,\n} from \"../core/resource-governor-settings.ts\";\nimport {\n\tcollectResourceObservationReport,\n\tRESOURCE_REPORT_MIN_ADMISSIONS,\n\ttype ResourceObservationReport,\n} from \"../core/resource-observation-report.ts\";\nimport { SettingsManager } from \"../core/settings-manager.ts\";\n\nexport { collectResourceObservationReport, RESOURCE_REPORT_MIN_ADMISSIONS, type ResourceObservationReport };\n\n/**\n * Headless resource diagnostic (OMK v0.97.x roadmap §19.2, M1/PR2):\n *\n * omk doctor resources [--json] [--report]\n *\n * Observe-only: probes the host, evaluates the admission policy, and prints\n * either aligned human output or the bounded §19.2 JSON schema. This command\n * is the sanctioned local surface for raw capacity values (§11.3); it still\n * never prints usernames, hostnames, or paths (§6.2). The doctor probes even\n * when the governor mode is `off` because it only runs on explicit request.\n */\n\nconst USAGE = \"Usage: omk doctor resources [--json] [--report]\";\n\nexport interface ResourceDoctorCliOverrides {\n\treadonly cwd?: string;\n\treadonly env?: NodeJS.ProcessEnv;\n\treadonly writeLine?: (line: string) => void;\n\t/** Test seam: replaces settings loading (defaults to SettingsManager.create(cwd)). */\n\treadonly loadSettings?: () => {\n\t\treadonly resourceGovernor?: ResourceGovernorSettings;\n\t\treadonly configuredMaxToolConcurrency?: number;\n\t};\n\t/** Test seam: replaces the host probe. */\n\treadonly capture?: typeof captureHostResourceSnapshot;\n\t/** Test seam: monotonic clock for probeDurationMs. */\n\treadonly now?: () => number;\n\t/** Test seam: replaces local observation aggregation. */\n\treadonly collectReport?: (cwd: string) => ResourceObservationReport;\n}\n\nexport interface ResourceDoctorCliOutcome {\n\treadonly handled: boolean;\n\treadonly exitCode: number;\n}\n\nexport async function runResourceDoctorCli(\n\targs: readonly string[],\n\toverrides: ResourceDoctorCliOverrides = {},\n): Promise<ResourceDoctorCliOutcome> {\n\tif (args[0] !== \"doctor\" || args[1] !== \"resources\") {\n\t\treturn { handled: false, exitCode: 0 };\n\t}\n\tconst writeLine = overrides.writeLine ?? ((line: string) => console.log(line));\n\n\tconst flags = parseDoctorFlags(args.slice(2), writeLine);\n\tif (flags.exit !== null) {\n\t\treturn { handled: true, exitCode: flags.exit };\n\t}\n\tconst json = flags.json;\n\tif (flags.report) {\n\t\tconst report = (overrides.collectReport ?? collectResourceObservationReport)(overrides.cwd ?? process.cwd());\n\t\tif (json) writeLine(JSON.stringify(report, null, 2));\n\t\telse renderObservationReport(report, writeLine);\n\t\treturn { handled: true, exitCode: 0 };\n\t}\n\n\tconst settings = (overrides.loadSettings ?? (() => loadSettingsFromDisk(overrides.cwd)))();\n\tconst resolved = resolveResourceGovernorSettings(settings.resourceGovernor, overrides.env ?? process.env);\n\n\tconst capture = overrides.capture ?? captureHostResourceSnapshot;\n\tconst now = overrides.now ?? (() => performance.now());\n\tconst startedAt = now();\n\tconst snapshot: HostResourceSnapshot = await capture({\n\t\tcwd: overrides.cwd,\n\t\tmaxProbeMs: resolved.maxProbeMs,\n\t\tcpuSampleMs: resolved.cpuSampleMs,\n\t});\n\tconst probeDurationMs = Math.max(0, now() - startedAt);\n\n\tconst decision = decideResourceAdmission({\n\t\tsnapshot,\n\t\tconfig: resolved.admission,\n\t\tconfiguredCaps: { maxToolConcurrency: settings.configuredMaxToolConcurrency },\n\t});\n\n\tif (json) {\n\t\tconst report = buildResourceDoctorReport({ snapshot, decision, resolved, probeDurationMs });\n\t\twriteLine(JSON.stringify(report, null, 2));\n\t\treturn { handled: true, exitCode: 0 };\n\t}\n\trenderHumanReport({ writeLine, resolved, decision, snapshot, probeDurationMs });\n\treturn { handled: true, exitCode: 0 };\n}\n\nfunction parseDoctorFlags(\n\targs: readonly string[],\n\twriteLine: (line: string) => void,\n): { readonly json: boolean; readonly report: boolean; readonly exit: number | null } {\n\tlet json = false;\n\tlet report = false;\n\tfor (const arg of args) {\n\t\tif (arg === \"--json\") {\n\t\t\tjson = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--report\") {\n\t\t\treport = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--help\" || arg === \"-h\") {\n\t\t\twriteLine(USAGE);\n\t\t\treturn { json, report, exit: 0 };\n\t\t}\n\t\twriteLine(`Unknown argument: ${arg}`);\n\t\twriteLine(USAGE);\n\t\treturn { json, report, exit: 2 };\n\t}\n\treturn { json, report, exit: null };\n}\n\nfunction renderObservationReport(report: ResourceObservationReport, writeLine: (line: string) => void): void {\n\twriteLine(\"Resource observation report\");\n\twriteLine(`journals scanned: ${report.journalsScanned}${report.truncated ? \" (truncated)\" : \"\"}`);\n\twriteLine(`admission records: ${report.admissionRecords}`);\n\twriteLine(`reason-qualified records: ${report.reasonRecords}`);\n\twriteLine(\n\t\t`pressure: normal ${report.pressure.normal}, constrained ${report.pressure.constrained}, critical ${report.pressure.critical}`,\n\t);\n\twriteLine(\n\t\t`actions: allow ${report.actions.allow}, throttle ${report.actions.throttle}, defer-heavy ${report.actions[\"defer-heavy\"]}`,\n\t);\n\twriteLine(`would have throttled: ${report.wouldHaveThrottled}`);\n\twriteLine(`probe partial/timeout: ${report.probePartial}/${report.probeTimeout}`);\n\twriteLine(\n\t\t`minimum sample: ${report.reasonRecords}/${report.minimumSampleSize} (${report.minimumSampleMet ? \"met\" : \"not met\"})`,\n\t);\n\twriteLine(`reason coverage complete: ${report.reasonCoverageComplete ? \"yes\" : \"no\"}`);\n\twriteLine(\"human review: required\");\n\tif (report.diagnostics > 0) writeLine(`diagnostics: ${report.diagnostics}`);\n}\n\nfunction renderHumanReport(input: {\n\treadonly writeLine: (line: string) => void;\n\treadonly resolved: ReturnType<typeof resolveResourceGovernorSettings>;\n\treadonly decision: ReturnType<typeof decideResourceAdmission>;\n\treadonly snapshot: HostResourceSnapshot;\n\treadonly probeDurationMs: number;\n}): void {\n\tconst { writeLine, resolved, decision, snapshot, probeDurationMs } = input;\n\twriteLine(\"Resource doctor\");\n\twriteLine(\"\");\n\tfor (const line of formatResourceSummaryLines(resolved.mode, decision)) {\n\t\twriteLine(line);\n\t}\n\twriteLine(\"\");\n\tfor (const line of formatResourceProbeLines(snapshot)) {\n\t\twriteLine(line);\n\t}\n\twriteLine(\"\");\n\twriteLine(`probe duration: ${Math.round(probeDurationMs)} ms`);\n\tfor (const error of resolved.errors) {\n\t\twriteLine(`settings error: ${error}`);\n\t}\n}\n\nfunction loadSettingsFromDisk(cwd: string | undefined): {\n\treadonly resourceGovernor?: ResourceGovernorSettings;\n\treadonly configuredMaxToolConcurrency?: number;\n} {\n\ttry {\n\t\tconst manager = SettingsManager.create(cwd ?? process.cwd());\n\t\treturn {\n\t\t\tresourceGovernor: manager.getResourceGovernorSettings(),\n\t\t\tconfiguredMaxToolConcurrency: manager.getAgentRuntimeSettings().maxToolConcurrency,\n\t\t};\n\t} catch {\n\t\t// A broken settings file must not block the diagnostic; defaults apply.\n\t\treturn {};\n\t}\n}\n"]}
@@ -1,13 +1,12 @@
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 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.
4
+ * A default-off, advisory-only primitive wired into AgentSession's v4 resolver.
5
+ * AgentSession reads only the bridge's bounded cache and uses a caller-injected
6
+ * advisory function for refresh; the current production transport is a no-op,
7
+ * so it returns no hint. This module owns payload/result validation, TTL cache,
8
+ * budget counter, circuit breaker, and timeout handling. It never calls an MCP
9
+ * transport directly or receives execution authority.
11
10
  *
12
11
  * Grounded in the read-first plan at
13
12
  * .omk/goals/008-reasoning-router-advanced-accuracy-plan/laneC-privacy-adaptorch.md
@@ -18,18 +17,17 @@
18
17
  * - The router's turn-start path is synchronous and I/O-free today (plan
19
18
  * 4.4). This module never calls an MCP transport directly and exposes a
20
19
  * synchronous, cache-read-only accessor (`getFreshHint`) plus a
21
- * fire-and-forget refresh (`requestRefresh`) so a future integration can
22
- * never block or await this module inline on the turn-start path.
20
+ * fire-and-forget refresh (`requestRefresh`) so the AgentSession integration
21
+ * never blocks or awaits advisory I/O on the turn-start path.
23
22
  * - The real, documented AdaptOrch tool surface has no confidence or
24
23
  * reasoning-level field (plan 4.3); this module's inbound result type
25
24
  * (`AdaptorchAdvisoryResult`) therefore only carries a locally-relevant
26
25
  * `taskClass` and a `confidenceBand` - both closed enums - never a raw
27
- * numeric confidence or a `ThinkingLevel` value. Fusing a hint into a
28
- * resolved level is out of scope for this module.
26
+ * numeric confidence or a `ThinkingLevel` value. AgentSession owns the
27
+ * bounded fusion from this advisory shape into the v4 resolver.
29
28
  * - No product source is imported here. `AdaptorchTaskClass` /
30
29
  * `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.
30
+ * value, while AgentSession adapts them at the integration boundary.
33
31
  * - Every outbound/inbound field is a closed enum, a boolean, or a bounded
34
32
  * integer, derived from local features only. There is structurally no
35
33
  * field shaped to carry prompt text, a prompt hash, a file/working-
@@ -1 +1 @@
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,UAAU,GAAG,QAAQ,CAAC;AAEtG,4FAA4F;AAC5F,MAAM,MAAM,qBAAqB,GAAG,KAAK,GAAG,KAAK,G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AC;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
+ {"version":3,"file":"adaptorch-bridge.d.ts","sourceRoot":"","sources":["../../src/core/adaptorch-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;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,UAAU,GAAG,QAAQ,CAAC;AAEtG,4FAA4F;AAC5F,MAAM,MAAM,qBAAqB,GAAG,KAAK,GAAG,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AAM,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 wired into AgentSession's v4 resolver.\n * AgentSession reads only the bridge's bounded cache and uses a caller-injected\n * advisory function for refresh; the current production transport is a no-op,\n * so it returns no hint. This module owns payload/result validation, TTL cache,\n * budget counter, circuit breaker, and timeout handling. It never calls an MCP\n * transport directly or receives execution authority.\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 the AgentSession integration\n * never blocks or awaits advisory I/O 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. AgentSession owns the\n * bounded fusion from this advisory shape into the v4 resolver.\n * - No product source is imported here. `AdaptorchTaskClass` /\n * `AdaptorchLaneType` intentionally mirror the v4 task/lane unions by\n * value, while AgentSession adapts them at the integration boundary.\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,13 +1,12 @@
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 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.
4
+ * A default-off, advisory-only primitive wired into AgentSession's v4 resolver.
5
+ * AgentSession reads only the bridge's bounded cache and uses a caller-injected
6
+ * advisory function for refresh; the current production transport is a no-op,
7
+ * so it returns no hint. This module owns payload/result validation, TTL cache,
8
+ * budget counter, circuit breaker, and timeout handling. It never calls an MCP
9
+ * transport directly or receives execution authority.
11
10
  *
12
11
  * Grounded in the read-first plan at
13
12
  * .omk/goals/008-reasoning-router-advanced-accuracy-plan/laneC-privacy-adaptorch.md
@@ -18,18 +17,17 @@
18
17
  * - The router's turn-start path is synchronous and I/O-free today (plan
19
18
  * 4.4). This module never calls an MCP transport directly and exposes a
20
19
  * synchronous, cache-read-only accessor (`getFreshHint`) plus a
21
- * fire-and-forget refresh (`requestRefresh`) so a future integration can
22
- * never block or await this module inline on the turn-start path.
20
+ * fire-and-forget refresh (`requestRefresh`) so the AgentSession integration
21
+ * never blocks or awaits advisory I/O on the turn-start path.
23
22
  * - The real, documented AdaptOrch tool surface has no confidence or
24
23
  * reasoning-level field (plan 4.3); this module's inbound result type
25
24
  * (`AdaptorchAdvisoryResult`) therefore only carries a locally-relevant
26
25
  * `taskClass` and a `confidenceBand` - both closed enums - never a raw
27
- * numeric confidence or a `ThinkingLevel` value. Fusing a hint into a
28
- * resolved level is out of scope for this module.
26
+ * numeric confidence or a `ThinkingLevel` value. AgentSession owns the
27
+ * bounded fusion from this advisory shape into the v4 resolver.
29
28
  * - No product source is imported here. `AdaptorchTaskClass` /
30
29
  * `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.
30
+ * value, while AgentSession adapts them at the integration boundary.
33
31
  * - Every outbound/inbound field is a closed enum, a boolean, or a bounded
34
32
  * integer, derived from local features only. There is structurally no
35
33
  * field shaped to carry prompt text, a prompt hash, a file/working-