open-multi-agent-kit 0.99.0 → 1.0.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 (271) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +3 -3
  3. package/dist/bun/cli.d.ts.map +1 -1
  4. package/dist/bun/cli.js +1 -0
  5. package/dist/bun/cli.js.map +1 -1
  6. package/dist/bun/register-bundled-coding-agent.d.ts +10 -0
  7. package/dist/bun/register-bundled-coding-agent.d.ts.map +1 -0
  8. package/dist/bun/register-bundled-coding-agent.js +12 -0
  9. package/dist/bun/register-bundled-coding-agent.js.map +1 -0
  10. package/dist/cli/args.d.ts +1 -1
  11. package/dist/cli/args.d.ts.map +1 -1
  12. package/dist/cli/args.js +1 -1
  13. package/dist/cli/args.js.map +1 -1
  14. package/dist/cli/help.d.ts.map +1 -1
  15. package/dist/cli/help.js +1 -1
  16. package/dist/cli/help.js.map +1 -1
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +14 -2
  19. package/dist/cli.js.map +1 -1
  20. package/dist/commands/neo-cli.d.ts +9 -0
  21. package/dist/commands/neo-cli.d.ts.map +1 -0
  22. package/dist/commands/neo-cli.js +61 -0
  23. package/dist/commands/neo-cli.js.map +1 -0
  24. package/dist/core/agent-session.d.ts +29 -2
  25. package/dist/core/agent-session.d.ts.map +1 -1
  26. package/dist/core/agent-session.js +107 -30
  27. package/dist/core/agent-session.js.map +1 -1
  28. package/dist/core/bundled-skills.d.ts +4 -0
  29. package/dist/core/bundled-skills.d.ts.map +1 -0
  30. package/dist/core/bundled-skills.js +32 -0
  31. package/dist/core/bundled-skills.js.map +1 -0
  32. package/dist/core/cli-diagnostics.d.ts +6 -0
  33. package/dist/core/cli-diagnostics.d.ts.map +1 -0
  34. package/dist/core/cli-diagnostics.js +20 -0
  35. package/dist/core/cli-diagnostics.js.map +1 -0
  36. package/dist/core/context-budget-headroom.d.ts +12 -0
  37. package/dist/core/context-budget-headroom.d.ts.map +1 -1
  38. package/dist/core/context-budget-headroom.js +35 -0
  39. package/dist/core/context-budget-headroom.js.map +1 -1
  40. package/dist/core/context-budget-v2-input-validation.d.ts +4 -0
  41. package/dist/core/context-budget-v2-input-validation.d.ts.map +1 -0
  42. package/dist/core/context-budget-v2-input-validation.js +79 -0
  43. package/dist/core/context-budget-v2-input-validation.js.map +1 -0
  44. package/dist/core/context-budget-v2-observability.d.ts +15 -0
  45. package/dist/core/context-budget-v2-observability.d.ts.map +1 -0
  46. package/dist/core/context-budget-v2-observability.js +35 -0
  47. package/dist/core/context-budget-v2-observability.js.map +1 -0
  48. package/dist/core/context-budget-v2-planned-items.d.ts +5 -0
  49. package/dist/core/context-budget-v2-planned-items.d.ts.map +1 -0
  50. package/dist/core/context-budget-v2-planned-items.js +40 -0
  51. package/dist/core/context-budget-v2-planned-items.js.map +1 -0
  52. package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
  53. package/dist/core/context-budget-v2-planner.js +57 -38
  54. package/dist/core/context-budget-v2-planner.js.map +1 -1
  55. package/dist/core/context-budget-v2-selection.d.ts +19 -3
  56. package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
  57. package/dist/core/context-budget-v2-selection.js +35 -57
  58. package/dist/core/context-budget-v2-selection.js.map +1 -1
  59. package/dist/core/context-budget-v2-tiers.d.ts.map +1 -1
  60. package/dist/core/context-budget-v2-tiers.js +9 -42
  61. package/dist/core/context-budget-v2-tiers.js.map +1 -1
  62. package/dist/core/context-budget-v2-types.d.ts +8 -1
  63. package/dist/core/context-budget-v2-types.d.ts.map +1 -1
  64. package/dist/core/context-budget-v2-types.js.map +1 -1
  65. package/dist/core/extensions/bundled-virtual-modules.d.ts +15 -0
  66. package/dist/core/extensions/bundled-virtual-modules.d.ts.map +1 -0
  67. package/dist/core/extensions/bundled-virtual-modules.js +63 -0
  68. package/dist/core/extensions/bundled-virtual-modules.js.map +1 -0
  69. package/dist/core/extensions/loader.d.ts.map +1 -1
  70. package/dist/core/extensions/loader.js +2 -42
  71. package/dist/core/extensions/loader.js.map +1 -1
  72. package/dist/core/extensions/runner.d.ts +1 -0
  73. package/dist/core/extensions/runner.d.ts.map +1 -1
  74. package/dist/core/extensions/runner.js +6 -0
  75. package/dist/core/extensions/runner.js.map +1 -1
  76. package/dist/core/extensions/types.d.ts +10 -0
  77. package/dist/core/extensions/types.d.ts.map +1 -1
  78. package/dist/core/extensions/types.js.map +1 -1
  79. package/dist/core/index.d.ts +2 -1
  80. package/dist/core/index.d.ts.map +1 -1
  81. package/dist/core/index.js +2 -1
  82. package/dist/core/index.js.map +1 -1
  83. package/dist/core/loadout-runtime.d.ts +2 -8
  84. package/dist/core/loadout-runtime.d.ts.map +1 -1
  85. package/dist/core/loadout-runtime.js.map +1 -1
  86. package/dist/core/mcp/client.d.ts +27 -6
  87. package/dist/core/mcp/client.d.ts.map +1 -1
  88. package/dist/core/mcp/client.js +80 -20
  89. package/dist/core/mcp/client.js.map +1 -1
  90. package/dist/core/mcp/manager.d.ts +10 -1
  91. package/dist/core/mcp/manager.d.ts.map +1 -1
  92. package/dist/core/mcp/manager.js +68 -9
  93. package/dist/core/mcp/manager.js.map +1 -1
  94. package/dist/core/mcp/protocol.d.ts +9 -3
  95. package/dist/core/mcp/protocol.d.ts.map +1 -1
  96. package/dist/core/mcp/protocol.js +61 -15
  97. package/dist/core/mcp/protocol.js.map +1 -1
  98. package/dist/core/mcp/stdio-transport.d.ts +12 -1
  99. package/dist/core/mcp/stdio-transport.d.ts.map +1 -1
  100. package/dist/core/mcp/stdio-transport.js +30 -2
  101. package/dist/core/mcp/stdio-transport.js.map +1 -1
  102. package/dist/core/mcp-descriptor-injection.d.ts +26 -0
  103. package/dist/core/mcp-descriptor-injection.d.ts.map +1 -0
  104. package/dist/core/mcp-descriptor-injection.js +25 -0
  105. package/dist/core/mcp-descriptor-injection.js.map +1 -0
  106. package/dist/core/mcp-public-presets.d.ts +1 -3
  107. package/dist/core/mcp-public-presets.d.ts.map +1 -1
  108. package/dist/core/mcp-public-presets.js +3 -15
  109. package/dist/core/mcp-public-presets.js.map +1 -1
  110. package/dist/core/model-registry.d.ts.map +1 -1
  111. package/dist/core/model-registry.js +24 -3
  112. package/dist/core/model-registry.js.map +1 -1
  113. package/dist/core/neo/catalog.d.ts +20 -0
  114. package/dist/core/neo/catalog.d.ts.map +1 -0
  115. package/dist/core/neo/catalog.js +50 -0
  116. package/dist/core/neo/catalog.js.map +1 -0
  117. package/dist/core/neo/setup.d.ts +3 -0
  118. package/dist/core/neo/setup.d.ts.map +1 -0
  119. package/dist/core/neo/setup.js +47 -0
  120. package/dist/core/neo/setup.js.map +1 -0
  121. package/dist/core/provider-default-models.d.ts +1 -0
  122. package/dist/core/provider-default-models.d.ts.map +1 -1
  123. package/dist/core/provider-default-models.js +1 -0
  124. package/dist/core/provider-default-models.js.map +1 -1
  125. package/dist/core/provider-display-names.d.ts.map +1 -1
  126. package/dist/core/provider-display-names.js +1 -0
  127. package/dist/core/provider-display-names.js.map +1 -1
  128. package/dist/core/provider-error-classification.d.ts +57 -0
  129. package/dist/core/provider-error-classification.d.ts.map +1 -0
  130. package/dist/core/provider-error-classification.js +103 -0
  131. package/dist/core/provider-error-classification.js.map +1 -0
  132. package/dist/core/provider-resilience.d.ts +10 -0
  133. package/dist/core/provider-resilience.d.ts.map +1 -1
  134. package/dist/core/provider-resilience.js +36 -3
  135. package/dist/core/provider-resilience.js.map +1 -1
  136. package/dist/core/provider-usage-commandcode.d.ts +9 -0
  137. package/dist/core/provider-usage-commandcode.d.ts.map +1 -0
  138. package/dist/core/provider-usage-commandcode.js +198 -0
  139. package/dist/core/provider-usage-commandcode.js.map +1 -0
  140. package/dist/core/provider-usage-devin.d.ts +5 -3
  141. package/dist/core/provider-usage-devin.d.ts.map +1 -1
  142. package/dist/core/provider-usage-devin.js +15 -5
  143. package/dist/core/provider-usage-devin.js.map +1 -1
  144. package/dist/core/provider-usage-types.d.ts +1 -1
  145. package/dist/core/provider-usage-types.d.ts.map +1 -1
  146. package/dist/core/provider-usage-types.js.map +1 -1
  147. package/dist/core/provider-usage.d.ts.map +1 -1
  148. package/dist/core/provider-usage.js +6 -0
  149. package/dist/core/provider-usage.js.map +1 -1
  150. package/dist/core/resource-admission.d.ts +36 -0
  151. package/dist/core/resource-admission.d.ts.map +1 -1
  152. package/dist/core/resource-admission.js +59 -0
  153. package/dist/core/resource-admission.js.map +1 -1
  154. package/dist/core/resource-loader.d.ts.map +1 -1
  155. package/dist/core/resource-loader.js +2 -2
  156. package/dist/core/resource-loader.js.map +1 -1
  157. package/dist/core/run-usage-ledger.d.ts +47 -0
  158. package/dist/core/run-usage-ledger.d.ts.map +1 -0
  159. package/dist/core/run-usage-ledger.js +162 -0
  160. package/dist/core/run-usage-ledger.js.map +1 -0
  161. package/dist/core/run-usage-operation.d.ts +8 -0
  162. package/dist/core/run-usage-operation.d.ts.map +1 -0
  163. package/dist/core/run-usage-operation.js +12 -0
  164. package/dist/core/run-usage-operation.js.map +1 -0
  165. package/dist/core/sdk.d.ts.map +1 -1
  166. package/dist/core/sdk.js +5 -6
  167. package/dist/core/sdk.js.map +1 -1
  168. package/dist/core/session-failure-cause.d.ts.map +1 -1
  169. package/dist/core/session-failure-cause.js +14 -5
  170. package/dist/core/session-failure-cause.js.map +1 -1
  171. package/dist/core/session-prompt-lifecycle.d.ts +6 -0
  172. package/dist/core/session-prompt-lifecycle.d.ts.map +1 -1
  173. package/dist/core/session-prompt-lifecycle.js +47 -2
  174. package/dist/core/session-prompt-lifecycle.js.map +1 -1
  175. package/dist/core/session-termination.d.ts.map +1 -1
  176. package/dist/core/session-termination.js +4 -2
  177. package/dist/core/session-termination.js.map +1 -1
  178. package/dist/core/subagent-lane-authority.d.ts +28 -0
  179. package/dist/core/subagent-lane-authority.d.ts.map +1 -0
  180. package/dist/core/subagent-lane-authority.js +119 -0
  181. package/dist/core/subagent-lane-authority.js.map +1 -0
  182. package/dist/core/subagent-lane-contract.d.ts +114 -0
  183. package/dist/core/subagent-lane-contract.d.ts.map +1 -0
  184. package/dist/core/subagent-lane-contract.js +18 -0
  185. package/dist/core/subagent-lane-contract.js.map +1 -0
  186. package/dist/core/subagent-lane-launcher.d.ts +3 -6
  187. package/dist/core/subagent-lane-launcher.d.ts.map +1 -1
  188. package/dist/core/subagent-lane-launcher.js +53 -12
  189. package/dist/core/subagent-lane-launcher.js.map +1 -1
  190. package/dist/core/subagent-orchestration.d.ts +4 -17
  191. package/dist/core/subagent-orchestration.d.ts.map +1 -1
  192. package/dist/core/subagent-orchestration.js.map +1 -1
  193. package/dist/core/verified-run/broker.d.ts.map +1 -1
  194. package/dist/core/verified-run/broker.js +4 -1
  195. package/dist/core/verified-run/broker.js.map +1 -1
  196. package/dist/core/workload-permit-pool.d.ts +1 -1
  197. package/dist/core/workload-permit-pool.d.ts.map +1 -1
  198. package/dist/core/workload-permit-pool.js +3 -0
  199. package/dist/core/workload-permit-pool.js.map +1 -1
  200. package/dist/guardrails/strict-evidence-approval-adapter.d.ts +34 -0
  201. package/dist/guardrails/strict-evidence-approval-adapter.d.ts.map +1 -0
  202. package/dist/guardrails/strict-evidence-approval-adapter.js +70 -0
  203. package/dist/guardrails/strict-evidence-approval-adapter.js.map +1 -0
  204. package/dist/index.d.ts +3 -0
  205. package/dist/index.d.ts.map +1 -1
  206. package/dist/index.js +1 -0
  207. package/dist/index.js.map +1 -1
  208. package/dist/main.d.ts.map +1 -1
  209. package/dist/main.js +11 -18
  210. package/dist/main.js.map +1 -1
  211. package/dist/modes/acp/acp-agent.d.ts +24 -0
  212. package/dist/modes/acp/acp-agent.d.ts.map +1 -0
  213. package/dist/modes/acp/acp-agent.js +133 -0
  214. package/dist/modes/acp/acp-agent.js.map +1 -0
  215. package/dist/modes/acp/acp-mode.d.ts +4 -0
  216. package/dist/modes/acp/acp-mode.d.ts.map +1 -0
  217. package/dist/modes/acp/acp-mode.js +34 -0
  218. package/dist/modes/acp/acp-mode.js.map +1 -0
  219. package/dist/modes/acp/acp-session.d.ts +4 -0
  220. package/dist/modes/acp/acp-session.d.ts.map +1 -0
  221. package/dist/modes/acp/acp-session.js +76 -0
  222. package/dist/modes/acp/acp-session.js.map +1 -0
  223. package/dist/modes/acp/acp-transport.d.ts +5 -0
  224. package/dist/modes/acp/acp-transport.d.ts.map +1 -0
  225. package/dist/modes/acp/acp-transport.js +90 -0
  226. package/dist/modes/acp/acp-transport.js.map +1 -0
  227. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  228. package/dist/modes/interactive/interactive-mode.js +1 -0
  229. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  230. package/docs/audit-revalidation-2026-09-17.md +77 -0
  231. package/docs/devin-harness.md +33 -4
  232. package/docs/ecraf-normalization.md +83 -0
  233. package/docs/model-catalog-refresh.md +51 -1
  234. package/docs/models.md +1 -1
  235. package/docs/neo.md +134 -0
  236. package/docs/providers.md +72 -6
  237. package/docs/run-usage-ledger.md +56 -0
  238. package/docs/runtime-algorithms.md +44 -0
  239. package/docs/skills.md +1 -1
  240. package/docs/usage.md +2 -1
  241. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  242. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  243. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  244. package/examples/extensions/gondolin/package-lock.json +2 -2
  245. package/examples/extensions/gondolin/package.json +1 -1
  246. package/examples/extensions/sandbox/package-lock.json +2 -2
  247. package/examples/extensions/sandbox/package.json +1 -1
  248. package/examples/extensions/subagent/adaptive-agent-runtime.ts +14 -1
  249. package/examples/extensions/subagent/graph-result.ts +48 -0
  250. package/examples/extensions/subagent/index.ts +246 -111
  251. package/examples/extensions/subagent/managed-process-tree.ts +42 -0
  252. package/examples/extensions/subagent/managed-process.test.ts +24 -0
  253. package/examples/extensions/subagent/managed-process.ts +93 -112
  254. package/examples/extensions/subagent/subagent-runtime-types.ts +17 -1
  255. package/examples/extensions/subagent/subagent-stream.ts +161 -0
  256. package/examples/extensions/terminal-browser/README.md +54 -0
  257. package/examples/extensions/terminal-browser/bridge-protocol.ts +29 -0
  258. package/examples/extensions/terminal-browser/bridge.ts +219 -0
  259. package/examples/extensions/terminal-browser/browser-surface.ts +288 -0
  260. package/examples/extensions/terminal-browser/index.ts +215 -0
  261. package/examples/extensions/terminal-browser/placeholders.ts +49 -0
  262. package/examples/extensions/with-deps/package-lock.json +2 -2
  263. package/examples/extensions/with-deps/package.json +1 -1
  264. package/npm-shrinkwrap.json +18 -18
  265. package/package.json +8 -7
  266. package/resources/neo/skills/omk-browser/SKILL.md +32 -0
  267. package/resources/neo/skills/omk-code-review/SKILL.md +24 -0
  268. package/resources/neo/skills/omk-computeruse/SKILL.md +34 -0
  269. package/resources/neo/skills/omk-mcp-setup/SKILL.md +48 -0
  270. package/resources/neo/skills/omk-research/SKILL.md +24 -0
  271. package/resources/neo/skills/omk-site/SKILL.md +28 -0
@@ -15,54 +15,21 @@ export function computeTierDemand(plannedItems) {
15
15
  }
16
16
  export function allocateTiers(available, policy, demand) {
17
17
  const out = new Map();
18
- const floors = {};
19
- const ceilings = {};
20
- const wants = {};
21
18
  for (const tier of ALL_TIERS_V2) {
22
19
  const floor = Math.max(0, Math.floor(policy[tier].floorPct * available));
23
20
  const ceiling = Math.max(floor, Math.floor(policy[tier].ceilingPct * available));
24
21
  const entry = demand.get(tier) ?? { demand: 0, hard: 0 };
25
22
  const want = Math.max(entry.demand, entry.hard);
26
- floors[tier] = floor;
27
- ceilings[tier] = ceiling;
28
- wants[tier] = want;
29
- out.set(tier, { floor, ceiling, allocated: Math.min(want, Math.max(ceiling, entry.hard)) });
30
- }
31
- let totalAllocated = 0;
32
- for (const tier of ALL_TIERS_V2) {
33
- totalAllocated += out.get(tier)?.allocated ?? 0;
34
- }
35
- let residual = available - totalAllocated;
36
- if (residual <= 0) {
37
- return out;
38
- }
39
- const shortfalls = collectShortfalls(out, wants);
40
- const totalGap = shortfalls.reduce((sum, shortfall) => sum + shortfall.gap, 0);
41
- if (totalGap <= 0) {
42
- return out;
43
- }
44
- for (const { tier, gap } of shortfalls) {
45
- const share = Math.min(gap, Math.floor((residual * gap) / totalGap));
46
- if (share <= 0)
47
- continue;
48
- const entry = out.get(tier);
49
- if (!entry)
50
- continue;
51
- out.set(tier, { ...entry, allocated: entry.allocated + share });
52
- residual -= share;
23
+ // `allocated` is the tier's guaranteed claim — what the floor pass is
24
+ // entitled to spend on this tier's own items before global competition:
25
+ // its hard demand (always admitted) or, beyond that, its demand capped
26
+ // at the floor. The previous residual-redistribution loop could never
27
+ // move this number on normal input (min(want, max(ceiling, hard)) makes
28
+ // want-allocated or ceiling-allocated zero), so it is removed rather
29
+ // than kept as dead code. Leftover budget competes globally in the
30
+ // ceiling-bounded selection pass instead.
31
+ out.set(tier, { floor, ceiling, allocated: Math.min(want, Math.max(floor, entry.hard)) });
53
32
  }
54
33
  return out;
55
34
  }
56
- function collectShortfalls(allocations, wants) {
57
- const shortfalls = [];
58
- for (const tier of ALL_TIERS_V2) {
59
- const entry = allocations.get(tier);
60
- if (!entry)
61
- continue;
62
- const gap = Math.min(Math.max(0, wants[tier] - entry.allocated), Math.max(0, entry.ceiling - entry.allocated));
63
- if (gap > 0)
64
- shortfalls.push({ tier, gap });
65
- }
66
- return shortfalls;
67
- }
68
35
  //# sourceMappingURL=context-budget-v2-tiers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-budget-v2-tiers.js","sourceRoot":"","sources":["../../src/core/context-budget-v2-tiers.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAA2B,MAAM,8BAA8B,CAAC;AAarF,MAAM,UAAU,iBAAiB,CAAC,YAAsC,EAA2C;IAClH,MAAM,MAAM,GAAG,IAAI,GAAG,EAAsC,CAAC;IAC7D,KAAK,MAAM,IAAI,IAAI,YAAY,EAAE,CAAC;QACjC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;IAC1C,CAAC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AAQ,GAAG,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC;QACrE,IAAI,KAAK,IAAI,CAAC;YAAE,SAAS;QACzB,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,CAAC,KAAK;YAAE,SAAS;QACrB,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,KAAK,CAAC,SAAS,GAAG,KAAK,EAAE,CAAC,CAAC;QAChE,QAAQ,IAAI,KAAK,CAAC;IACnB,CAAC;IACD,OAAO,GAAG,CAAC;AAAA,CACX;AAED,SAAS,iBAAiB,CACzB,WAAgE,EAChE,KAA0C,EACK;IAC/C,MAAM,UAAU,GAAiD,EAAE,CAAC;IACpE,KAAK,MAAM,IAAI,IAAI,YAAY,EAAE,CAAC;QACjC,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,CAAC,KAAK;YAAE,SAAS;QACrB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC;QAC/G,IAAI,GAAG,GAAG,CAAC;YAAE,UAAU,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,UAAU,CAAC;AAAA,CAClB","sourcesContent":["import type { ContextBudgetTierV2 } from \"./context-budget-headroom.ts\";\nimport type { PlannedItemV2 } from \"./context-budget-v2-scoring.ts\";\nimport { ALL_TIERS_V2, type TierBudgetPolicyV2 } from \"./context-budget-v2-types.ts\";\n\nexport interface RawTierDemand {\n\treadonly demand: number;\n\treadonly hard: number;\n}\n\nexport interface RawTierAllocation {\n\treadonly floor: number;\n\treadonly ceiling: number;\n\treadonly allocated: number;\n}\n\nexport function computeTierDemand(plannedItems: readonly PlannedItemV2[]): Map<ContextBudgetTierV2, RawTierDemand> {\n\tconst demand = new Map<ContextBudgetTierV2, RawTierDemand>();\n\tfor (const tier of ALL_TIERS_V2) {\n\t\tdemand.set(tier, { demand: 0, hard: 0 });\n\t}\n\tfor (const planned of plannedItems) {\n\t\tconst entry = demand.get(planned.item.tier) ?? { demand: 0, hard: 0 };\n\t\tdemand.set(planned.item.tier, {\n\t\t\tdemand: entry.demand + planned.fullTokens,\n\t\t\thard: entry.hard + (planned.isHard ? planned.fullTokens : 0),\n\t\t});\n\t}\n\treturn demand;\n}\n\nexport function allocateTiers(\n\tavailable: number,\n\tpolicy: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>,\n\tdemand: Map<ContextBudgetTierV2, RawTierDemand>,\n): Map<ContextBudgetTierV2, RawTierAllocation> {\n\tconst out = new Map<ContextBudgetTierV2, RawTierAllocation>();\n\tconst floors = {} as Record<ContextBudgetTierV2, number>;\n\tconst ceilings = {} as Record<ContextBudgetTierV2, number>;\n\tconst wants = {} as Record<ContextBudgetTierV2, number>;\n\n\tfor (const tier of ALL_TIERS_V2) {\n\t\tconst floor = Math.max(0, Math.floor(policy[tier].floorPct * available));\n\t\tconst ceiling = Math.max(floor, Math.floor(policy[tier].ceilingPct * available));\n\t\tconst entry = demand.get(tier) ?? { demand: 0, hard: 0 };\n\t\tconst want = Math.max(entry.demand, entry.hard);\n\t\tfloors[tier] = floor;\n\t\tceilings[tier] = ceiling;\n\t\twants[tier] = want;\n\t\tout.set(tier, { floor, ceiling, allocated: Math.min(want, Math.max(ceiling, entry.hard)) });\n\t}\n\n\tlet totalAllocated = 0;\n\tfor (const tier of ALL_TIERS_V2) {\n\t\ttotalAllocated += out.get(tier)?.allocated ?? 0;\n\t}\n\tlet residual = available - totalAllocated;\n\tif (residual <= 0) {\n\t\treturn out;\n\t}\n\n\tconst shortfalls = collectShortfalls(out, wants);\n\tconst totalGap = shortfalls.reduce((sum, shortfall) => sum + shortfall.gap, 0);\n\tif (totalGap <= 0) {\n\t\treturn out;\n\t}\n\tfor (const { tier, gap } of shortfalls) {\n\t\tconst share = Math.min(gap, Math.floor((residual * gap) / totalGap));\n\t\tif (share <= 0) continue;\n\t\tconst entry = out.get(tier);\n\t\tif (!entry) continue;\n\t\tout.set(tier, { ...entry, allocated: entry.allocated + share });\n\t\tresidual -= share;\n\t}\n\treturn out;\n}\n\nfunction collectShortfalls(\n\tallocations: ReadonlyMap<ContextBudgetTierV2, RawTierAllocation>,\n\twants: Record<ContextBudgetTierV2, number>,\n): { tier: ContextBudgetTierV2; gap: number }[] {\n\tconst shortfalls: { tier: ContextBudgetTierV2; gap: number }[] = [];\n\tfor (const tier of ALL_TIERS_V2) {\n\t\tconst entry = allocations.get(tier);\n\t\tif (!entry) continue;\n\t\tconst gap = Math.min(Math.max(0, wants[tier] - entry.allocated), Math.max(0, entry.ceiling - entry.allocated));\n\t\tif (gap > 0) shortfalls.push({ tier, gap });\n\t}\n\treturn shortfalls;\n}\n"]}
1
+ {"version":3,"file":"context-budget-v2-tiers.js","sourceRoot":"","sources":["../../src/core/context-budget-v2-tiers.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAA2B,MAAM,8BAA8B,CAAC;AAarF,MAAM,UAAU,iBAAiB,CAAC,YAAsC,EAA2C;IAClH,MAAM,MAAM,GAAG,IAAI,GAAG,EAAsC,CAAC;IAC7D,KAAK,MAAM,IAAI,IAAI,YAAY,EAAE,CAAC;QACjC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;IAC1C,CAAC;IACD,KAAK,MAAM,OAAO,IAAI,YAAY,EAAE,CAAC;QACpC,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,OAA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AA0C;QAC1C,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC;IAC3F,CAAC;IACD,OAAO,GAAG,CAAC;AAAA,CACX","sourcesContent":["import type { ContextBudgetTierV2 } from \"./context-budget-headroom.ts\";\nimport type { PlannedItemV2 } from \"./context-budget-v2-scoring.ts\";\nimport { ALL_TIERS_V2, type TierBudgetPolicyV2 } from \"./context-budget-v2-types.ts\";\n\nexport interface RawTierDemand {\n\treadonly demand: number;\n\treadonly hard: number;\n}\n\nexport interface RawTierAllocation {\n\treadonly floor: number;\n\treadonly ceiling: number;\n\treadonly allocated: number;\n}\n\nexport function computeTierDemand(plannedItems: readonly PlannedItemV2[]): Map<ContextBudgetTierV2, RawTierDemand> {\n\tconst demand = new Map<ContextBudgetTierV2, RawTierDemand>();\n\tfor (const tier of ALL_TIERS_V2) {\n\t\tdemand.set(tier, { demand: 0, hard: 0 });\n\t}\n\tfor (const planned of plannedItems) {\n\t\tconst entry = demand.get(planned.item.tier) ?? { demand: 0, hard: 0 };\n\t\tdemand.set(planned.item.tier, {\n\t\t\tdemand: entry.demand + planned.fullTokens,\n\t\t\thard: entry.hard + (planned.isHard ? planned.fullTokens : 0),\n\t\t});\n\t}\n\treturn demand;\n}\n\nexport function allocateTiers(\n\tavailable: number,\n\tpolicy: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>,\n\tdemand: Map<ContextBudgetTierV2, RawTierDemand>,\n): Map<ContextBudgetTierV2, RawTierAllocation> {\n\tconst out = new Map<ContextBudgetTierV2, RawTierAllocation>();\n\n\tfor (const tier of ALL_TIERS_V2) {\n\t\tconst floor = Math.max(0, Math.floor(policy[tier].floorPct * available));\n\t\tconst ceiling = Math.max(floor, Math.floor(policy[tier].ceilingPct * available));\n\t\tconst entry = demand.get(tier) ?? { demand: 0, hard: 0 };\n\t\tconst want = Math.max(entry.demand, entry.hard);\n\t\t// `allocated` is the tier's guaranteed claim — what the floor pass is\n\t\t// entitled to spend on this tier's own items before global competition:\n\t\t// its hard demand (always admitted) or, beyond that, its demand capped\n\t\t// at the floor. The previous residual-redistribution loop could never\n\t\t// move this number on normal input (min(want, max(ceiling, hard)) makes\n\t\t// want-allocated or ceiling-allocated zero), so it is removed rather\n\t\t// than kept as dead code. Leftover budget competes globally in the\n\t\t// ceiling-bounded selection pass instead.\n\t\tout.set(tier, { floor, ceiling, allocated: Math.min(want, Math.max(floor, entry.hard)) });\n\t}\n\treturn out;\n}\n"]}
@@ -26,7 +26,14 @@ export interface TokenOptimizerRuntimeStatus {
26
26
  readonly compatibilityOnly: true;
27
27
  }
28
28
  export interface TierBudgetPolicyV2 {
29
+ /**
30
+ * Guaranteed share of the available budget the floor-reservation pass
31
+ * spends on this tier's own items before leftovers compete globally.
32
+ * A real reservation — not merely a lower bound on the ceiling — so a
33
+ * higher-scored item in another tier cannot starve this tier's minimum.
34
+ */
29
35
  readonly floorPct: number;
36
+ /** Hard cap on this tier's share; selection above it is omitted. */
30
37
  readonly ceilingPct: number;
31
38
  }
32
39
  export declare const DEFAULT_TIER_POLICY_V2: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>;
@@ -75,7 +82,7 @@ export interface TierBudgetAllocationV2 {
75
82
  readonly usedTokens: number;
76
83
  readonly hardTokens: number;
77
84
  }
78
- export type QualityDiagnosticReasonV2 = "omitted_high_priority" | "retrieval_miss_risk" | "restore_on_demand_hint" | "hard_pin_over_capacity" | "coverage_gap" | "tier_ceiling_exceeded" | "invalid_budget";
85
+ export type QualityDiagnosticReasonV2 = "omitted_high_priority" | "retrieval_miss_risk" | "restore_on_demand_hint" | "hard_pin_over_capacity" | "coverage_gap" | "tier_ceiling_exceeded" | "tier_floor_over_budget" | "invalid_input" | "invalid_budget";
79
86
  export interface QualityDiagnosticV2 {
80
87
  readonly reason: QualityDiagnosticReasonV2;
81
88
  readonly itemId?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"context-budget-v2-types.d.ts","sourceRoot":"","sources":["../../src/core/context-budget-v2-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,mBAAmB,EACnB,mBAAmB,EACnB,oCAAoC,EACpC,gCAAgC,EAChC,2BAA2B,EAC3B,kBAAkB,EAClB,uBAAuB,EACvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAC7E,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,2CAA2C,CAAC;AAElG;;;GAGG;AACH,eAAO,MAAM,gCAAgC,sBAAsB,CAAC;AAEpE;;;;;;;;;GASG;AACH,eAAO,MAAM,kCAAkC,UAAU,CAAC;AAE1D,4EAA4E;AAC5E,MAAM,WAAW,2BAA2B;IAC3C,QAAQ,CAAC,WAAW,EAAE,wBAAwB,CAAC;IAC/C,QAAQ,CAAC,MAAM,EAAE,2BAA2B,CAAC;IAC7C,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;IACvB,QAAQ,CAAC,4BAA4B,EAAE,mBAAmB,CAAC;IAC3D,QAAQ,CAAC,iBAAiB,EAAE,IAAI,CAAC;CACjC;AAED,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC5B;AAED,eAAO,MAAM,sBAAsB,EAAE,QAAQ,CAAC,MAAM,CAAC,mBAAmB,EAAE,kBAAkB,CAAC,CAU5F,CAAC;AAEF,eAAO,MAAM,YAAY,EAAE,SAAS,mBAAmB,EAUtD,CAAC;AAEF,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,CAAC;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AAC;IAC/B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC;IACvC,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,mBAAmB,EAAE,OAAO,CAAC;IACtC,QAAQ,CAAC,eAAe,EAAE,SAAS,sBAAsB,EAAE,CAAC;IAC5D,QAAQ,CAAC,uBAAuB,EAAE,SAAS,wBAAwB,EAAE,CAAC;IACtE,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,QAAQ,CAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,QAAQ,CAAC,WAAW,EAAE,SAAS,mBAAmB,EAAE,CAAC;IACrD,QAAQ,CAAC,kBAAkB,EAAE,SAAS,kBAAkB,EAAE,CAAC;IAC3D,QAAQ,CAAC,aAAa,EAAE,kCAAkC,CAAC;CAC3D","sourcesContent":["import type {\n\tContextBudgetItemV2,\n\tContextBudgetTierV2,\n\tContextRepresentationCacheMetadataV2,\n\tContextRepresentationCandidateV2,\n\tContextRepresentationKindV2,\n\tContextSourceRefV2,\n\tHeadroomQualityPolicyV2,\n} from \"./context-budget-headroom.ts\";\nimport type { TokenCounterAdapter } from \"./context-budget-token-counter.ts\";\nimport type { ContextCacheInvalidationSnapshot } from \"./context-budget-v2-cache-invalidation.ts\";\n\n/**\n * Public optimizer identifier. It is reported in the system prompt and used as a\n * cache namespace, so it must stay stable across internal policy changes.\n */\nexport const CONTEXT_BUDGET_POLICY_VERSION_V2 = \"context-budget-v2\";\n\n/**\n * Internal token for the optional-item selection policy, kept separate from the\n * public identifier so a scoring or ordering change can invalidate cached plans\n * without renaming the optimizer. Bump it whenever the selected set can differ\n * for identical inputs; otherwise plans built under the previous policy keep\n * being served for the whole cache TTL, including from disk.\n *\n * `sel-2`: density-ordered selection over the cheapest admissible representation\n * (previously priority-class-ordered over full-text tokens).\n */\nexport const CONTEXT_BUDGET_SELECTION_POLICY_V2 = \"sel-2\";\n\n/** Fixed compatibility telemetry for the removed legacy token optimizer. */\nexport interface TokenOptimizerRuntimeStatus {\n\treadonly optimizerId: \"legacy-token-optimizer\";\n\treadonly status: \"quarantined_compatibility\";\n\treadonly active: false;\n\treadonly activeContextBudgetOptimizer: \"context-budget-v2\";\n\treadonly compatibilityOnly: true;\n}\n\nexport interface TierBudgetPolicyV2 {\n\treadonly floorPct: number;\n\treadonly ceilingPct: number;\n}\n\nexport const DEFAULT_TIER_POLICY_V2: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\tsystem: { floorPct: 0.25, ceilingPct: 0.45 },\n\t\"active-goal\": { floorPct: 0.1, ceilingPct: 0.25 },\n\t\"current-files\": { floorPct: 0.08, ceilingPct: 0.2 },\n\ttools: { floorPct: 0.04, ceilingPct: 0.12 },\n\tskills: { floorPct: 0.03, ceilingPct: 0.12 },\n\tmcp: { floorPct: 0.02, ceilingPct: 0.08 },\n\thistory: { floorPct: 0.1, ceilingPct: 0.3 },\n\tevidence: { floorPct: 0.08, ceilingPct: 0.25 },\n\tscratch: { floorPct: 0, ceilingPct: 0.05 },\n};\n\nexport const ALL_TIERS_V2: readonly ContextBudgetTierV2[] = [\n\t\"system\",\n\t\"active-goal\",\n\t\"current-files\",\n\t\"tools\",\n\t\"skills\",\n\t\"mcp\",\n\t\"history\",\n\t\"evidence\",\n\t\"scratch\",\n];\n\nexport interface PromptContextBudgetInputV2 {\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens?: number;\n\treadonly safetyMarginTokens?: number;\n\treadonly modelId?: string;\n\treadonly tokenizerId?: string;\n\treadonly policyVersion?: string;\n\t/** Overrides {@link CONTEXT_BUDGET_SELECTION_POLICY_V2}. */\n\treadonly selectionPolicyVersion?: string;\n\treadonly promptHash?: string;\n\treadonly query?: string;\n\treadonly items: readonly ContextBudgetItemV2[];\n\treadonly tokenCounter?: TokenCounterAdapter;\n\treadonly tierPolicy?: Partial<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>;\n\treadonly qualityPolicy?: HeadroomQualityPolicyV2;\n\treadonly cacheProvider?: ContextBudgetCacheProviderV2;\n\treadonly cacheNamespace?: string;\n\treadonly queryIntentHash?: string;\n\treadonly cacheBudgetBucket?: string;\n\treadonly redactionPolicyHash?: string;\n\treadonly safetyProfileHash?: string;\n\treadonly cacheNowEpochMs?: number;\n\treadonly cacheTtlMs?: number;\n\treadonly cacheInvalidationSnapshot?: ContextCacheInvalidationSnapshot;\n}\n\nexport interface SelectedRepresentationV2 {\n\treadonly itemId: string;\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly cache?: ContextRepresentationCacheMetadataV2;\n}\n\nexport interface TierBudgetAllocationV2 {\n\treadonly tier: ContextBudgetTierV2;\n\treadonly floorTokens: number;\n\treadonly ceilingTokens: number;\n\treadonly allocatedTokens: number;\n\treadonly usedTokens: number;\n\treadonly hardTokens: number;\n}\n\nexport type QualityDiagnosticReasonV2 =\n\t| \"omitted_high_priority\"\n\t| \"retrieval_miss_risk\"\n\t| \"restore_on_demand_hint\"\n\t| \"hard_pin_over_capacity\"\n\t| \"coverage_gap\"\n\t| \"tier_ceiling_exceeded\"\n\t| \"invalid_budget\";\n\nexport interface QualityDiagnosticV2 {\n\treadonly reason: QualityDiagnosticReasonV2;\n\treadonly itemId?: string;\n\treadonly detail: string;\n}\n\nexport interface ContextBudgetObservabilityCountsV2 {\n\treadonly selected: number;\n\treadonly omitted: number;\n\treadonly pointer: number;\n\treadonly compressed: number;\n\treadonly full: number;\n\treadonly retrievalFallback: number;\n}\n\nexport interface ContextBudgetObservabilityTokensV2 {\n\treadonly available: number;\n\treadonly used: number;\n\treadonly raw: number;\n\treadonly omitted: number;\n\treadonly tokenSavings: number;\n}\n\nexport type ContextBudgetCacheLayerV2 = \"turn\" | \"session\" | \"workspace\" | \"shared\";\n\nexport type ContextBudgetRepresentationCacheRejectReasonV2 =\n\t| \"fingerprint_mismatch\"\n\t| \"kind_mismatch\"\n\t| \"model_mismatch\"\n\t| \"negative\"\n\t| \"policy_mismatch\"\n\t| \"poisoned\"\n\t| \"source_hash_mismatch\"\n\t| \"stale\"\n\t| \"token_invalid\"\n\t| \"tokenizer_mismatch\";\n\nexport type ContextBudgetRepresentationCacheKeyKindV2 = \"exact\" | \"materialized\";\n\nexport interface ContextBudgetMaterializedVerificationV2 {\n\treadonly queryCoverage?: number;\n\treadonly sourceCoverage?: number;\n\treadonly secretLeakScore?: number;\n\treadonly poisonScore?: number;\n\treadonly validatorVersion?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheEntryV2 {\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceHash: string;\n\treadonly representationFingerprint: string;\n\treadonly keyKind?: ContextBudgetRepresentationCacheKeyKindV2;\n\treadonly modelId: string;\n\treadonly tokenizerId: string;\n\treadonly policyVersion: string;\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly compressorPolicyHash?: string;\n\treadonly qualityPolicyHash?: string;\n\treadonly queryIntentCluster?: string;\n\treadonly outputTextHash?: string;\n\treadonly targetTokenBucket?: number;\n\treadonly verification?: ContextBudgetMaterializedVerificationV2;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetRepresentationCacheReadV2 {\n\treadonly entry: ContextBudgetRepresentationCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetNegativeCacheEntryV2 {\n\treadonly reason: string;\n\treadonly createdAtEpochMs?: number;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetPlanCacheEntryV2 {\n\treadonly plan: PromptContextBudgetPlanV2;\n\treadonly sourceHashes: Readonly<Record<string, string>>;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetPlanCacheReadV2 {\n\treadonly entry: ContextBudgetPlanCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetCacheProviderV2 {\n\tgetInvalidationSnapshot?(): ContextCacheInvalidationSnapshot | undefined;\n\tsetInvalidationSnapshot?(snapshot: ContextCacheInvalidationSnapshot): void;\n\treadRepresentation(key: string): ContextBudgetRepresentationCacheReadV2 | undefined;\n\twriteRepresentation(input: { readonly key: string; readonly entry: ContextBudgetRepresentationCacheEntryV2 }): void;\n\tdeleteRepresentation?(key: string): void;\n\treadNegativeRepresentation(key: string): ContextBudgetNegativeCacheEntryV2 | undefined;\n\twriteNegativeRepresentation(input: { readonly key: string; readonly reason: string }): void;\n\tdeleteNegativeRepresentation?(key: string): void;\n\treadPlan(key: string): ContextBudgetPlanCacheReadV2 | undefined;\n\twritePlan(input: { readonly key: string; readonly entry: ContextBudgetPlanCacheEntryV2 }): void;\n\tdeletePlan?(key: string): void;\n}\n\nexport interface ContextBudgetPlanCacheTelemetryV2 {\n\treadonly hit: boolean;\n\treadonly key: string;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n\treadonly rejectedReason?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheTelemetryV2 {\n\treadonly exactHits: number;\n\treadonly semanticHits: number;\n\treadonly pointerHits: number;\n\treadonly misses: number;\n\treadonly staleRejects: number;\n\treadonly poisonRejects: number;\n\treadonly negativeHits: number;\n\treadonly writes: number;\n}\n\nexport interface ContextBudgetCacheTokenTelemetryV2 {\n\treadonly raw: number;\n\treadonly rendered: number;\n\treadonly savedByCache: number;\n\treadonly savedByCompression: number;\n\treadonly savedByOmission: number;\n}\n\nexport interface TokenCacheTelemetryV2 {\n\treadonly planCache: ContextBudgetPlanCacheTelemetryV2;\n\treadonly representationCache: ContextBudgetRepresentationCacheTelemetryV2;\n\treadonly tokens: ContextBudgetCacheTokenTelemetryV2;\n}\n\nexport interface PromptContextBudgetObservabilityV2 {\n\treadonly counts: ContextBudgetObservabilityCountsV2;\n\treadonly diagnosticReasons: readonly QualityDiagnosticReasonV2[];\n\treadonly tokens: ContextBudgetObservabilityTokensV2;\n\treadonly planHash: string;\n\treadonly cache: TokenCacheTelemetryV2;\n\treadonly tokenOptimizer: TokenOptimizerRuntimeStatus;\n}\n\nexport interface PromptContextBudgetPlanV2 {\n\treadonly policyVersion: string;\n\treadonly promptHash?: string;\n\treadonly planHash: string;\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly availableTokens: number;\n\treadonly usedTokens: number;\n\treadonly omittedTokens: number;\n\treadonly rawTokens: number;\n\treadonly tokenSavingsRatio: number;\n\treadonly emergency: boolean;\n\treadonly omittedHighPriority: boolean;\n\treadonly tierAllocations: readonly TierBudgetAllocationV2[];\n\treadonly selectedRepresentations: readonly SelectedRepresentationV2[];\n\treadonly includedItemIds: readonly string[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly observability: PromptContextBudgetObservabilityV2;\n}\n"]}
1
+ {"version":3,"file":"context-budget-v2-types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;IAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC;IACvC,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,mBAAmB,EAAE,OAAO,CAAC;IACtC,QAAQ,CAAC,eAAe,EAAE,SAAS,sBAAsB,EAAE,CAAC;IAC5D,QAAQ,CAAC,uBAAuB,EAAE,SAAS,wBAAwB,EAAE,CAAC;IACtE,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,QAAQ,CAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,QAAQ,CAAC,WAAW,EAAE,SAAS,mBAAmB,EAAE,CAAC;IACrD,QAAQ,CAAC,kBAAkB,EAAE,SAAS,kBAAkB,EAAE,CAAC;IAC3D,QAAQ,CAAC,aAAa,EAAE,kCAAkC,CAAC;CAC3D","sourcesContent":["import type {\n\tContextBudgetItemV2,\n\tContextBudgetTierV2,\n\tContextRepresentationCacheMetadataV2,\n\tContextRepresentationCandidateV2,\n\tContextRepresentationKindV2,\n\tContextSourceRefV2,\n\tHeadroomQualityPolicyV2,\n} from \"./context-budget-headroom.ts\";\nimport type { TokenCounterAdapter } from \"./context-budget-token-counter.ts\";\nimport type { ContextCacheInvalidationSnapshot } from \"./context-budget-v2-cache-invalidation.ts\";\n\n/**\n * Public optimizer identifier. It is reported in the system prompt and used as a\n * cache namespace, so it must stay stable across internal policy changes.\n */\nexport const CONTEXT_BUDGET_POLICY_VERSION_V2 = \"context-budget-v2\";\n\n/**\n * Internal token for the optional-item selection policy, kept separate from the\n * public identifier so a scoring or ordering change can invalidate cached plans\n * without renaming the optimizer. Bump it whenever the selected set can differ\n * for identical inputs; otherwise plans built under the previous policy keep\n * being served for the whole cache TTL, including from disk.\n *\n * `sel-2`: density-ordered selection over the cheapest admissible representation\n * (previously priority-class-ordered over full-text tokens).\n */\nexport const CONTEXT_BUDGET_SELECTION_POLICY_V2 = \"sel-2\";\n\n/** Fixed compatibility telemetry for the removed legacy token optimizer. */\nexport interface TokenOptimizerRuntimeStatus {\n\treadonly optimizerId: \"legacy-token-optimizer\";\n\treadonly status: \"quarantined_compatibility\";\n\treadonly active: false;\n\treadonly activeContextBudgetOptimizer: \"context-budget-v2\";\n\treadonly compatibilityOnly: true;\n}\n\nexport interface TierBudgetPolicyV2 {\n\t/**\n\t * Guaranteed share of the available budget the floor-reservation pass\n\t * spends on this tier's own items before leftovers compete globally.\n\t * A real reservation — not merely a lower bound on the ceiling — so a\n\t * higher-scored item in another tier cannot starve this tier's minimum.\n\t */\n\treadonly floorPct: number;\n\t/** Hard cap on this tier's share; selection above it is omitted. */\n\treadonly ceilingPct: number;\n}\n\nexport const DEFAULT_TIER_POLICY_V2: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\tsystem: { floorPct: 0.25, ceilingPct: 0.45 },\n\t\"active-goal\": { floorPct: 0.1, ceilingPct: 0.25 },\n\t\"current-files\": { floorPct: 0.08, ceilingPct: 0.2 },\n\ttools: { floorPct: 0.04, ceilingPct: 0.12 },\n\tskills: { floorPct: 0.03, ceilingPct: 0.12 },\n\tmcp: { floorPct: 0.02, ceilingPct: 0.08 },\n\thistory: { floorPct: 0.1, ceilingPct: 0.3 },\n\tevidence: { floorPct: 0.08, ceilingPct: 0.25 },\n\tscratch: { floorPct: 0, ceilingPct: 0.05 },\n};\n\nexport const ALL_TIERS_V2: readonly ContextBudgetTierV2[] = [\n\t\"system\",\n\t\"active-goal\",\n\t\"current-files\",\n\t\"tools\",\n\t\"skills\",\n\t\"mcp\",\n\t\"history\",\n\t\"evidence\",\n\t\"scratch\",\n];\n\nexport interface PromptContextBudgetInputV2 {\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens?: number;\n\treadonly safetyMarginTokens?: number;\n\treadonly modelId?: string;\n\treadonly tokenizerId?: string;\n\treadonly policyVersion?: string;\n\t/** Overrides {@link CONTEXT_BUDGET_SELECTION_POLICY_V2}. */\n\treadonly selectionPolicyVersion?: string;\n\treadonly promptHash?: string;\n\treadonly query?: string;\n\treadonly items: readonly ContextBudgetItemV2[];\n\treadonly tokenCounter?: TokenCounterAdapter;\n\treadonly tierPolicy?: Partial<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>;\n\treadonly qualityPolicy?: HeadroomQualityPolicyV2;\n\treadonly cacheProvider?: ContextBudgetCacheProviderV2;\n\treadonly cacheNamespace?: string;\n\treadonly queryIntentHash?: string;\n\treadonly cacheBudgetBucket?: string;\n\treadonly redactionPolicyHash?: string;\n\treadonly safetyProfileHash?: string;\n\treadonly cacheNowEpochMs?: number;\n\treadonly cacheTtlMs?: number;\n\treadonly cacheInvalidationSnapshot?: ContextCacheInvalidationSnapshot;\n}\n\nexport interface SelectedRepresentationV2 {\n\treadonly itemId: string;\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly cache?: ContextRepresentationCacheMetadataV2;\n}\n\nexport interface TierBudgetAllocationV2 {\n\treadonly tier: ContextBudgetTierV2;\n\treadonly floorTokens: number;\n\treadonly ceilingTokens: number;\n\treadonly allocatedTokens: number;\n\treadonly usedTokens: number;\n\treadonly hardTokens: number;\n}\n\nexport type QualityDiagnosticReasonV2 =\n\t| \"omitted_high_priority\"\n\t| \"retrieval_miss_risk\"\n\t| \"restore_on_demand_hint\"\n\t| \"hard_pin_over_capacity\"\n\t| \"coverage_gap\"\n\t| \"tier_ceiling_exceeded\"\n\t| \"tier_floor_over_budget\"\n\t| \"invalid_input\"\n\t| \"invalid_budget\";\n\nexport interface QualityDiagnosticV2 {\n\treadonly reason: QualityDiagnosticReasonV2;\n\treadonly itemId?: string;\n\treadonly detail: string;\n}\n\nexport interface ContextBudgetObservabilityCountsV2 {\n\treadonly selected: number;\n\treadonly omitted: number;\n\treadonly pointer: number;\n\treadonly compressed: number;\n\treadonly full: number;\n\treadonly retrievalFallback: number;\n}\n\nexport interface ContextBudgetObservabilityTokensV2 {\n\treadonly available: number;\n\treadonly used: number;\n\treadonly raw: number;\n\treadonly omitted: number;\n\treadonly tokenSavings: number;\n}\n\nexport type ContextBudgetCacheLayerV2 = \"turn\" | \"session\" | \"workspace\" | \"shared\";\n\nexport type ContextBudgetRepresentationCacheRejectReasonV2 =\n\t| \"fingerprint_mismatch\"\n\t| \"kind_mismatch\"\n\t| \"model_mismatch\"\n\t| \"negative\"\n\t| \"policy_mismatch\"\n\t| \"poisoned\"\n\t| \"source_hash_mismatch\"\n\t| \"stale\"\n\t| \"token_invalid\"\n\t| \"tokenizer_mismatch\";\n\nexport type ContextBudgetRepresentationCacheKeyKindV2 = \"exact\" | \"materialized\";\n\nexport interface ContextBudgetMaterializedVerificationV2 {\n\treadonly queryCoverage?: number;\n\treadonly sourceCoverage?: number;\n\treadonly secretLeakScore?: number;\n\treadonly poisonScore?: number;\n\treadonly validatorVersion?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheEntryV2 {\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceHash: string;\n\treadonly representationFingerprint: string;\n\treadonly keyKind?: ContextBudgetRepresentationCacheKeyKindV2;\n\treadonly modelId: string;\n\treadonly tokenizerId: string;\n\treadonly policyVersion: string;\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly compressorPolicyHash?: string;\n\treadonly qualityPolicyHash?: string;\n\treadonly queryIntentCluster?: string;\n\treadonly outputTextHash?: string;\n\treadonly targetTokenBucket?: number;\n\treadonly verification?: ContextBudgetMaterializedVerificationV2;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetRepresentationCacheReadV2 {\n\treadonly entry: ContextBudgetRepresentationCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetNegativeCacheEntryV2 {\n\treadonly reason: string;\n\treadonly createdAtEpochMs?: number;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetPlanCacheEntryV2 {\n\treadonly plan: PromptContextBudgetPlanV2;\n\treadonly sourceHashes: Readonly<Record<string, string>>;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetPlanCacheReadV2 {\n\treadonly entry: ContextBudgetPlanCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetCacheProviderV2 {\n\tgetInvalidationSnapshot?(): ContextCacheInvalidationSnapshot | undefined;\n\tsetInvalidationSnapshot?(snapshot: ContextCacheInvalidationSnapshot): void;\n\treadRepresentation(key: string): ContextBudgetRepresentationCacheReadV2 | undefined;\n\twriteRepresentation(input: { readonly key: string; readonly entry: ContextBudgetRepresentationCacheEntryV2 }): void;\n\tdeleteRepresentation?(key: string): void;\n\treadNegativeRepresentation(key: string): ContextBudgetNegativeCacheEntryV2 | undefined;\n\twriteNegativeRepresentation(input: { readonly key: string; readonly reason: string }): void;\n\tdeleteNegativeRepresentation?(key: string): void;\n\treadPlan(key: string): ContextBudgetPlanCacheReadV2 | undefined;\n\twritePlan(input: { readonly key: string; readonly entry: ContextBudgetPlanCacheEntryV2 }): void;\n\tdeletePlan?(key: string): void;\n}\n\nexport interface ContextBudgetPlanCacheTelemetryV2 {\n\treadonly hit: boolean;\n\treadonly key: string;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n\treadonly rejectedReason?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheTelemetryV2 {\n\treadonly exactHits: number;\n\treadonly semanticHits: number;\n\treadonly pointerHits: number;\n\treadonly misses: number;\n\treadonly staleRejects: number;\n\treadonly poisonRejects: number;\n\treadonly negativeHits: number;\n\treadonly writes: number;\n}\n\nexport interface ContextBudgetCacheTokenTelemetryV2 {\n\treadonly raw: number;\n\treadonly rendered: number;\n\treadonly savedByCache: number;\n\treadonly savedByCompression: number;\n\treadonly savedByOmission: number;\n}\n\nexport interface TokenCacheTelemetryV2 {\n\treadonly planCache: ContextBudgetPlanCacheTelemetryV2;\n\treadonly representationCache: ContextBudgetRepresentationCacheTelemetryV2;\n\treadonly tokens: ContextBudgetCacheTokenTelemetryV2;\n}\n\nexport interface PromptContextBudgetObservabilityV2 {\n\treadonly counts: ContextBudgetObservabilityCountsV2;\n\treadonly diagnosticReasons: readonly QualityDiagnosticReasonV2[];\n\treadonly tokens: ContextBudgetObservabilityTokensV2;\n\treadonly planHash: string;\n\treadonly cache: TokenCacheTelemetryV2;\n\treadonly tokenOptimizer: TokenOptimizerRuntimeStatus;\n}\n\nexport interface PromptContextBudgetPlanV2 {\n\treadonly policyVersion: string;\n\treadonly promptHash?: string;\n\treadonly planHash: string;\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly availableTokens: number;\n\treadonly usedTokens: number;\n\treadonly omittedTokens: number;\n\treadonly rawTokens: number;\n\treadonly tokenSavingsRatio: number;\n\treadonly emergency: boolean;\n\treadonly omittedHighPriority: boolean;\n\treadonly tierAllocations: readonly TierBudgetAllocationV2[];\n\treadonly selectedRepresentations: readonly SelectedRepresentationV2[];\n\treadonly includedItemIds: readonly string[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly observability: PromptContextBudgetObservabilityV2;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"context-budget-v2-types.js","sourceRoot":"","sources":["../../src/core/context-budget-v2-types.ts"],"names":[],"mappings":"AAYA;;;GAGG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,mBAAmB,CAAC;AAEpE;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAG,OAAO,CAAC;AAgB1D,MAAM,CAAC,MAAM,sBAAsB,GAA8D;IAChG,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,aAAa,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE;IAClD,eAAe,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE;IACpD,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC3C,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,GAAG,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IACzC,OAAO,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE;IAC3C,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC9C,OAAO,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE;CAC1C,CAAC;AAEF,MAAM,CAAC,MAAM,YAAY,GAAmC;IAC3D,QAAQ;IACR,aAAa;IACb,eAAe;IACf,OAAO;IACP,QAAQ;IACR,KAAK;IACL,SAAS;IACT,UAAU;IACV,SAAS;CACT,CAAC","sourcesContent":["import type {\n\tContextBudgetItemV2,\n\tContextBudgetTierV2,\n\tContextRepresentationCacheMetadataV2,\n\tContextRepresentationCandidateV2,\n\tContextRepresentationKindV2,\n\tContextSourceRefV2,\n\tHeadroomQualityPolicyV2,\n} from \"./context-budget-headroom.ts\";\nimport type { TokenCounterAdapter } from \"./context-budget-token-counter.ts\";\nimport type { ContextCacheInvalidationSnapshot } from \"./context-budget-v2-cache-invalidation.ts\";\n\n/**\n * Public optimizer identifier. It is reported in the system prompt and used as a\n * cache namespace, so it must stay stable across internal policy changes.\n */\nexport const CONTEXT_BUDGET_POLICY_VERSION_V2 = \"context-budget-v2\";\n\n/**\n * Internal token for the optional-item selection policy, kept separate from the\n * public identifier so a scoring or ordering change can invalidate cached plans\n * without renaming the optimizer. Bump it whenever the selected set can differ\n * for identical inputs; otherwise plans built under the previous policy keep\n * being served for the whole cache TTL, including from disk.\n *\n * `sel-2`: density-ordered selection over the cheapest admissible representation\n * (previously priority-class-ordered over full-text tokens).\n */\nexport const CONTEXT_BUDGET_SELECTION_POLICY_V2 = \"sel-2\";\n\n/** Fixed compatibility telemetry for the removed legacy token optimizer. */\nexport interface TokenOptimizerRuntimeStatus {\n\treadonly optimizerId: \"legacy-token-optimizer\";\n\treadonly status: \"quarantined_compatibility\";\n\treadonly active: false;\n\treadonly activeContextBudgetOptimizer: \"context-budget-v2\";\n\treadonly compatibilityOnly: true;\n}\n\nexport interface TierBudgetPolicyV2 {\n\treadonly floorPct: number;\n\treadonly ceilingPct: number;\n}\n\nexport const DEFAULT_TIER_POLICY_V2: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\tsystem: { floorPct: 0.25, ceilingPct: 0.45 },\n\t\"active-goal\": { floorPct: 0.1, ceilingPct: 0.25 },\n\t\"current-files\": { floorPct: 0.08, ceilingPct: 0.2 },\n\ttools: { floorPct: 0.04, ceilingPct: 0.12 },\n\tskills: { floorPct: 0.03, ceilingPct: 0.12 },\n\tmcp: { floorPct: 0.02, ceilingPct: 0.08 },\n\thistory: { floorPct: 0.1, ceilingPct: 0.3 },\n\tevidence: { floorPct: 0.08, ceilingPct: 0.25 },\n\tscratch: { floorPct: 0, ceilingPct: 0.05 },\n};\n\nexport const ALL_TIERS_V2: readonly ContextBudgetTierV2[] = [\n\t\"system\",\n\t\"active-goal\",\n\t\"current-files\",\n\t\"tools\",\n\t\"skills\",\n\t\"mcp\",\n\t\"history\",\n\t\"evidence\",\n\t\"scratch\",\n];\n\nexport interface PromptContextBudgetInputV2 {\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens?: number;\n\treadonly safetyMarginTokens?: number;\n\treadonly modelId?: string;\n\treadonly tokenizerId?: string;\n\treadonly policyVersion?: string;\n\t/** Overrides {@link CONTEXT_BUDGET_SELECTION_POLICY_V2}. */\n\treadonly selectionPolicyVersion?: string;\n\treadonly promptHash?: string;\n\treadonly query?: string;\n\treadonly items: readonly ContextBudgetItemV2[];\n\treadonly tokenCounter?: TokenCounterAdapter;\n\treadonly tierPolicy?: Partial<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>;\n\treadonly qualityPolicy?: HeadroomQualityPolicyV2;\n\treadonly cacheProvider?: ContextBudgetCacheProviderV2;\n\treadonly cacheNamespace?: string;\n\treadonly queryIntentHash?: string;\n\treadonly cacheBudgetBucket?: string;\n\treadonly redactionPolicyHash?: string;\n\treadonly safetyProfileHash?: string;\n\treadonly cacheNowEpochMs?: number;\n\treadonly cacheTtlMs?: number;\n\treadonly cacheInvalidationSnapshot?: ContextCacheInvalidationSnapshot;\n}\n\nexport interface SelectedRepresentationV2 {\n\treadonly itemId: string;\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly cache?: ContextRepresentationCacheMetadataV2;\n}\n\nexport interface TierBudgetAllocationV2 {\n\treadonly tier: ContextBudgetTierV2;\n\treadonly floorTokens: number;\n\treadonly ceilingTokens: number;\n\treadonly allocatedTokens: number;\n\treadonly usedTokens: number;\n\treadonly hardTokens: number;\n}\n\nexport type QualityDiagnosticReasonV2 =\n\t| \"omitted_high_priority\"\n\t| \"retrieval_miss_risk\"\n\t| \"restore_on_demand_hint\"\n\t| \"hard_pin_over_capacity\"\n\t| \"coverage_gap\"\n\t| \"tier_ceiling_exceeded\"\n\t| \"invalid_budget\";\n\nexport interface QualityDiagnosticV2 {\n\treadonly reason: QualityDiagnosticReasonV2;\n\treadonly itemId?: string;\n\treadonly detail: string;\n}\n\nexport interface ContextBudgetObservabilityCountsV2 {\n\treadonly selected: number;\n\treadonly omitted: number;\n\treadonly pointer: number;\n\treadonly compressed: number;\n\treadonly full: number;\n\treadonly retrievalFallback: number;\n}\n\nexport interface ContextBudgetObservabilityTokensV2 {\n\treadonly available: number;\n\treadonly used: number;\n\treadonly raw: number;\n\treadonly omitted: number;\n\treadonly tokenSavings: number;\n}\n\nexport type ContextBudgetCacheLayerV2 = \"turn\" | \"session\" | \"workspace\" | \"shared\";\n\nexport type ContextBudgetRepresentationCacheRejectReasonV2 =\n\t| \"fingerprint_mismatch\"\n\t| \"kind_mismatch\"\n\t| \"model_mismatch\"\n\t| \"negative\"\n\t| \"policy_mismatch\"\n\t| \"poisoned\"\n\t| \"source_hash_mismatch\"\n\t| \"stale\"\n\t| \"token_invalid\"\n\t| \"tokenizer_mismatch\";\n\nexport type ContextBudgetRepresentationCacheKeyKindV2 = \"exact\" | \"materialized\";\n\nexport interface ContextBudgetMaterializedVerificationV2 {\n\treadonly queryCoverage?: number;\n\treadonly sourceCoverage?: number;\n\treadonly secretLeakScore?: number;\n\treadonly poisonScore?: number;\n\treadonly validatorVersion?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheEntryV2 {\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceHash: string;\n\treadonly representationFingerprint: string;\n\treadonly keyKind?: ContextBudgetRepresentationCacheKeyKindV2;\n\treadonly modelId: string;\n\treadonly tokenizerId: string;\n\treadonly policyVersion: string;\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly compressorPolicyHash?: string;\n\treadonly qualityPolicyHash?: string;\n\treadonly queryIntentCluster?: string;\n\treadonly outputTextHash?: string;\n\treadonly targetTokenBucket?: number;\n\treadonly verification?: ContextBudgetMaterializedVerificationV2;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetRepresentationCacheReadV2 {\n\treadonly entry: ContextBudgetRepresentationCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetNegativeCacheEntryV2 {\n\treadonly reason: string;\n\treadonly createdAtEpochMs?: number;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetPlanCacheEntryV2 {\n\treadonly plan: PromptContextBudgetPlanV2;\n\treadonly sourceHashes: Readonly<Record<string, string>>;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetPlanCacheReadV2 {\n\treadonly entry: ContextBudgetPlanCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetCacheProviderV2 {\n\tgetInvalidationSnapshot?(): ContextCacheInvalidationSnapshot | undefined;\n\tsetInvalidationSnapshot?(snapshot: ContextCacheInvalidationSnapshot): void;\n\treadRepresentation(key: string): ContextBudgetRepresentationCacheReadV2 | undefined;\n\twriteRepresentation(input: { readonly key: string; readonly entry: ContextBudgetRepresentationCacheEntryV2 }): void;\n\tdeleteRepresentation?(key: string): void;\n\treadNegativeRepresentation(key: string): ContextBudgetNegativeCacheEntryV2 | undefined;\n\twriteNegativeRepresentation(input: { readonly key: string; readonly reason: string }): void;\n\tdeleteNegativeRepresentation?(key: string): void;\n\treadPlan(key: string): ContextBudgetPlanCacheReadV2 | undefined;\n\twritePlan(input: { readonly key: string; readonly entry: ContextBudgetPlanCacheEntryV2 }): void;\n\tdeletePlan?(key: string): void;\n}\n\nexport interface ContextBudgetPlanCacheTelemetryV2 {\n\treadonly hit: boolean;\n\treadonly key: string;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n\treadonly rejectedReason?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheTelemetryV2 {\n\treadonly exactHits: number;\n\treadonly semanticHits: number;\n\treadonly pointerHits: number;\n\treadonly misses: number;\n\treadonly staleRejects: number;\n\treadonly poisonRejects: number;\n\treadonly negativeHits: number;\n\treadonly writes: number;\n}\n\nexport interface ContextBudgetCacheTokenTelemetryV2 {\n\treadonly raw: number;\n\treadonly rendered: number;\n\treadonly savedByCache: number;\n\treadonly savedByCompression: number;\n\treadonly savedByOmission: number;\n}\n\nexport interface TokenCacheTelemetryV2 {\n\treadonly planCache: ContextBudgetPlanCacheTelemetryV2;\n\treadonly representationCache: ContextBudgetRepresentationCacheTelemetryV2;\n\treadonly tokens: ContextBudgetCacheTokenTelemetryV2;\n}\n\nexport interface PromptContextBudgetObservabilityV2 {\n\treadonly counts: ContextBudgetObservabilityCountsV2;\n\treadonly diagnosticReasons: readonly QualityDiagnosticReasonV2[];\n\treadonly tokens: ContextBudgetObservabilityTokensV2;\n\treadonly planHash: string;\n\treadonly cache: TokenCacheTelemetryV2;\n\treadonly tokenOptimizer: TokenOptimizerRuntimeStatus;\n}\n\nexport interface PromptContextBudgetPlanV2 {\n\treadonly policyVersion: string;\n\treadonly promptHash?: string;\n\treadonly planHash: string;\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly availableTokens: number;\n\treadonly usedTokens: number;\n\treadonly omittedTokens: number;\n\treadonly rawTokens: number;\n\treadonly tokenSavingsRatio: number;\n\treadonly emergency: boolean;\n\treadonly omittedHighPriority: boolean;\n\treadonly tierAllocations: readonly TierBudgetAllocationV2[];\n\treadonly selectedRepresentations: readonly SelectedRepresentationV2[];\n\treadonly includedItemIds: readonly string[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly observability: PromptContextBudgetObservabilityV2;\n}\n"]}
1
+ {"version":3,"file":"context-budget-v2-types.js","sourceRoot":"","sources":["../../src/core/context-budget-v2-types.ts"],"names":[],"mappings":"AAYA;;;GAGG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,mBAAmB,CAAC;AAEpE;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAG,OAAO,CAAC;AAuB1D,MAAM,CAAC,MAAM,sBAAsB,GAA8D;IAChG,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,aAAa,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE;IAClD,eAAe,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE;IACpD,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC3C,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5C,GAAG,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IACzC,OAAO,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE;IAC3C,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE;IAC9C,OAAO,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE;CAC1C,CAAC;AAEF,MAAM,CAAC,MAAM,YAAY,GAAmC;IAC3D,QAAQ;IACR,aAAa;IACb,eAAe;IACf,OAAO;IACP,QAAQ;IACR,KAAK;IACL,SAAS;IACT,UAAU;IACV,SAAS;CACT,CAAC","sourcesContent":["import type {\n\tContextBudgetItemV2,\n\tContextBudgetTierV2,\n\tContextRepresentationCacheMetadataV2,\n\tContextRepresentationCandidateV2,\n\tContextRepresentationKindV2,\n\tContextSourceRefV2,\n\tHeadroomQualityPolicyV2,\n} from \"./context-budget-headroom.ts\";\nimport type { TokenCounterAdapter } from \"./context-budget-token-counter.ts\";\nimport type { ContextCacheInvalidationSnapshot } from \"./context-budget-v2-cache-invalidation.ts\";\n\n/**\n * Public optimizer identifier. It is reported in the system prompt and used as a\n * cache namespace, so it must stay stable across internal policy changes.\n */\nexport const CONTEXT_BUDGET_POLICY_VERSION_V2 = \"context-budget-v2\";\n\n/**\n * Internal token for the optional-item selection policy, kept separate from the\n * public identifier so a scoring or ordering change can invalidate cached plans\n * without renaming the optimizer. Bump it whenever the selected set can differ\n * for identical inputs; otherwise plans built under the previous policy keep\n * being served for the whole cache TTL, including from disk.\n *\n * `sel-2`: density-ordered selection over the cheapest admissible representation\n * (previously priority-class-ordered over full-text tokens).\n */\nexport const CONTEXT_BUDGET_SELECTION_POLICY_V2 = \"sel-2\";\n\n/** Fixed compatibility telemetry for the removed legacy token optimizer. */\nexport interface TokenOptimizerRuntimeStatus {\n\treadonly optimizerId: \"legacy-token-optimizer\";\n\treadonly status: \"quarantined_compatibility\";\n\treadonly active: false;\n\treadonly activeContextBudgetOptimizer: \"context-budget-v2\";\n\treadonly compatibilityOnly: true;\n}\n\nexport interface TierBudgetPolicyV2 {\n\t/**\n\t * Guaranteed share of the available budget the floor-reservation pass\n\t * spends on this tier's own items before leftovers compete globally.\n\t * A real reservation — not merely a lower bound on the ceiling — so a\n\t * higher-scored item in another tier cannot starve this tier's minimum.\n\t */\n\treadonly floorPct: number;\n\t/** Hard cap on this tier's share; selection above it is omitted. */\n\treadonly ceilingPct: number;\n}\n\nexport const DEFAULT_TIER_POLICY_V2: Readonly<Record<ContextBudgetTierV2, TierBudgetPolicyV2>> = {\n\tsystem: { floorPct: 0.25, ceilingPct: 0.45 },\n\t\"active-goal\": { floorPct: 0.1, ceilingPct: 0.25 },\n\t\"current-files\": { floorPct: 0.08, ceilingPct: 0.2 },\n\ttools: { floorPct: 0.04, ceilingPct: 0.12 },\n\tskills: { floorPct: 0.03, ceilingPct: 0.12 },\n\tmcp: { floorPct: 0.02, ceilingPct: 0.08 },\n\thistory: { floorPct: 0.1, ceilingPct: 0.3 },\n\tevidence: { floorPct: 0.08, ceilingPct: 0.25 },\n\tscratch: { floorPct: 0, ceilingPct: 0.05 },\n};\n\nexport const ALL_TIERS_V2: readonly ContextBudgetTierV2[] = [\n\t\"system\",\n\t\"active-goal\",\n\t\"current-files\",\n\t\"tools\",\n\t\"skills\",\n\t\"mcp\",\n\t\"history\",\n\t\"evidence\",\n\t\"scratch\",\n];\n\nexport interface PromptContextBudgetInputV2 {\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens?: number;\n\treadonly safetyMarginTokens?: number;\n\treadonly modelId?: string;\n\treadonly tokenizerId?: string;\n\treadonly policyVersion?: string;\n\t/** Overrides {@link CONTEXT_BUDGET_SELECTION_POLICY_V2}. */\n\treadonly selectionPolicyVersion?: string;\n\treadonly promptHash?: string;\n\treadonly query?: string;\n\treadonly items: readonly ContextBudgetItemV2[];\n\treadonly tokenCounter?: TokenCounterAdapter;\n\treadonly tierPolicy?: Partial<Record<ContextBudgetTierV2, TierBudgetPolicyV2>>;\n\treadonly qualityPolicy?: HeadroomQualityPolicyV2;\n\treadonly cacheProvider?: ContextBudgetCacheProviderV2;\n\treadonly cacheNamespace?: string;\n\treadonly queryIntentHash?: string;\n\treadonly cacheBudgetBucket?: string;\n\treadonly redactionPolicyHash?: string;\n\treadonly safetyProfileHash?: string;\n\treadonly cacheNowEpochMs?: number;\n\treadonly cacheTtlMs?: number;\n\treadonly cacheInvalidationSnapshot?: ContextCacheInvalidationSnapshot;\n}\n\nexport interface SelectedRepresentationV2 {\n\treadonly itemId: string;\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly cache?: ContextRepresentationCacheMetadataV2;\n}\n\nexport interface TierBudgetAllocationV2 {\n\treadonly tier: ContextBudgetTierV2;\n\treadonly floorTokens: number;\n\treadonly ceilingTokens: number;\n\treadonly allocatedTokens: number;\n\treadonly usedTokens: number;\n\treadonly hardTokens: number;\n}\n\nexport type QualityDiagnosticReasonV2 =\n\t| \"omitted_high_priority\"\n\t| \"retrieval_miss_risk\"\n\t| \"restore_on_demand_hint\"\n\t| \"hard_pin_over_capacity\"\n\t| \"coverage_gap\"\n\t| \"tier_ceiling_exceeded\"\n\t| \"tier_floor_over_budget\"\n\t| \"invalid_input\"\n\t| \"invalid_budget\";\n\nexport interface QualityDiagnosticV2 {\n\treadonly reason: QualityDiagnosticReasonV2;\n\treadonly itemId?: string;\n\treadonly detail: string;\n}\n\nexport interface ContextBudgetObservabilityCountsV2 {\n\treadonly selected: number;\n\treadonly omitted: number;\n\treadonly pointer: number;\n\treadonly compressed: number;\n\treadonly full: number;\n\treadonly retrievalFallback: number;\n}\n\nexport interface ContextBudgetObservabilityTokensV2 {\n\treadonly available: number;\n\treadonly used: number;\n\treadonly raw: number;\n\treadonly omitted: number;\n\treadonly tokenSavings: number;\n}\n\nexport type ContextBudgetCacheLayerV2 = \"turn\" | \"session\" | \"workspace\" | \"shared\";\n\nexport type ContextBudgetRepresentationCacheRejectReasonV2 =\n\t| \"fingerprint_mismatch\"\n\t| \"kind_mismatch\"\n\t| \"model_mismatch\"\n\t| \"negative\"\n\t| \"policy_mismatch\"\n\t| \"poisoned\"\n\t| \"source_hash_mismatch\"\n\t| \"stale\"\n\t| \"token_invalid\"\n\t| \"tokenizer_mismatch\";\n\nexport type ContextBudgetRepresentationCacheKeyKindV2 = \"exact\" | \"materialized\";\n\nexport interface ContextBudgetMaterializedVerificationV2 {\n\treadonly queryCoverage?: number;\n\treadonly sourceCoverage?: number;\n\treadonly secretLeakScore?: number;\n\treadonly poisonScore?: number;\n\treadonly validatorVersion?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheEntryV2 {\n\treadonly kind: ContextRepresentationKindV2;\n\treadonly text: string;\n\treadonly estimatedTokens: number;\n\treadonly fidelity: ContextRepresentationCandidateV2[\"fidelity\"];\n\treadonly sourceHash: string;\n\treadonly representationFingerprint: string;\n\treadonly keyKind?: ContextBudgetRepresentationCacheKeyKindV2;\n\treadonly modelId: string;\n\treadonly tokenizerId: string;\n\treadonly policyVersion: string;\n\treadonly sourceRef?: ContextSourceRefV2;\n\treadonly summaryHash?: string;\n\treadonly compressorId?: string;\n\treadonly compressorPolicyHash?: string;\n\treadonly qualityPolicyHash?: string;\n\treadonly queryIntentCluster?: string;\n\treadonly outputTextHash?: string;\n\treadonly targetTokenBucket?: number;\n\treadonly verification?: ContextBudgetMaterializedVerificationV2;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetRepresentationCacheReadV2 {\n\treadonly entry: ContextBudgetRepresentationCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetNegativeCacheEntryV2 {\n\treadonly reason: string;\n\treadonly createdAtEpochMs?: number;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetPlanCacheEntryV2 {\n\treadonly plan: PromptContextBudgetPlanV2;\n\treadonly sourceHashes: Readonly<Record<string, string>>;\n\treadonly createdAtEpochMs?: number;\n}\n\nexport interface ContextBudgetPlanCacheReadV2 {\n\treadonly entry: ContextBudgetPlanCacheEntryV2;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n}\n\nexport interface ContextBudgetCacheProviderV2 {\n\tgetInvalidationSnapshot?(): ContextCacheInvalidationSnapshot | undefined;\n\tsetInvalidationSnapshot?(snapshot: ContextCacheInvalidationSnapshot): void;\n\treadRepresentation(key: string): ContextBudgetRepresentationCacheReadV2 | undefined;\n\twriteRepresentation(input: { readonly key: string; readonly entry: ContextBudgetRepresentationCacheEntryV2 }): void;\n\tdeleteRepresentation?(key: string): void;\n\treadNegativeRepresentation(key: string): ContextBudgetNegativeCacheEntryV2 | undefined;\n\twriteNegativeRepresentation(input: { readonly key: string; readonly reason: string }): void;\n\tdeleteNegativeRepresentation?(key: string): void;\n\treadPlan(key: string): ContextBudgetPlanCacheReadV2 | undefined;\n\twritePlan(input: { readonly key: string; readonly entry: ContextBudgetPlanCacheEntryV2 }): void;\n\tdeletePlan?(key: string): void;\n}\n\nexport interface ContextBudgetPlanCacheTelemetryV2 {\n\treadonly hit: boolean;\n\treadonly key: string;\n\treadonly layer?: ContextBudgetCacheLayerV2;\n\treadonly rejectedReason?: string;\n}\n\nexport interface ContextBudgetRepresentationCacheTelemetryV2 {\n\treadonly exactHits: number;\n\treadonly semanticHits: number;\n\treadonly pointerHits: number;\n\treadonly misses: number;\n\treadonly staleRejects: number;\n\treadonly poisonRejects: number;\n\treadonly negativeHits: number;\n\treadonly writes: number;\n}\n\nexport interface ContextBudgetCacheTokenTelemetryV2 {\n\treadonly raw: number;\n\treadonly rendered: number;\n\treadonly savedByCache: number;\n\treadonly savedByCompression: number;\n\treadonly savedByOmission: number;\n}\n\nexport interface TokenCacheTelemetryV2 {\n\treadonly planCache: ContextBudgetPlanCacheTelemetryV2;\n\treadonly representationCache: ContextBudgetRepresentationCacheTelemetryV2;\n\treadonly tokens: ContextBudgetCacheTokenTelemetryV2;\n}\n\nexport interface PromptContextBudgetObservabilityV2 {\n\treadonly counts: ContextBudgetObservabilityCountsV2;\n\treadonly diagnosticReasons: readonly QualityDiagnosticReasonV2[];\n\treadonly tokens: ContextBudgetObservabilityTokensV2;\n\treadonly planHash: string;\n\treadonly cache: TokenCacheTelemetryV2;\n\treadonly tokenOptimizer: TokenOptimizerRuntimeStatus;\n}\n\nexport interface PromptContextBudgetPlanV2 {\n\treadonly policyVersion: string;\n\treadonly promptHash?: string;\n\treadonly planHash: string;\n\treadonly maxTokens: number;\n\treadonly responseReserveTokens: number;\n\treadonly safetyMarginTokens: number;\n\treadonly availableTokens: number;\n\treadonly usedTokens: number;\n\treadonly omittedTokens: number;\n\treadonly rawTokens: number;\n\treadonly tokenSavingsRatio: number;\n\treadonly emergency: boolean;\n\treadonly omittedHighPriority: boolean;\n\treadonly tierAllocations: readonly TierBudgetAllocationV2[];\n\treadonly selectedRepresentations: readonly SelectedRepresentationV2[];\n\treadonly includedItemIds: readonly string[];\n\treadonly omittedItemIds: readonly string[];\n\treadonly diagnostics: readonly QualityDiagnosticV2[];\n\treadonly retrievalFallbacks: readonly ContextSourceRefV2[];\n\treadonly observability: PromptContextBudgetObservabilityV2;\n}\n"]}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Virtual modules for compiled Bun binaries — the extension-facing view of the
3
+ * bundled package namespaces.
4
+ *
5
+ * Extracted from loader.ts: the table resolves the bundled
6
+ * `open-multi-agent-kit` namespace that the binary entry registers at startup
7
+ * (src/bun/register-bundled-coding-agent.ts). loader.ts itself must not import
8
+ * `../../index.ts` — that edge put it inside the index↔core import cycle
9
+ * (scripts/check-import-cycles.mjs).
10
+ */
11
+ /** Registration point for the compiled binary's bundled `open-multi-agent-kit` namespace. */
12
+ export declare function registerBundledCodingAgentNamespace(namespace: unknown): void;
13
+ /** Modules available to extensions via virtualModules (compiled Bun binary only). */
14
+ export declare function buildVirtualModules(): Record<string, unknown>;
15
+ //# sourceMappingURL=bundled-virtual-modules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundled-virtual-modules.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/bundled-virtual-modules.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAsBH,6FAA6F;AAC7F,wBAAgB,mCAAmC,CAAC,SAAS,EAAE,OAAO,GAAG,IAAI,CAE5E;AAUD,qFAAqF;AACrF,wBAAgB,mBAAmB,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAuB7D","sourcesContent":["/**\n * Virtual modules for compiled Bun binaries — the extension-facing view of the\n * bundled package namespaces.\n *\n * Extracted from loader.ts: the table resolves the bundled\n * `open-multi-agent-kit` namespace that the binary entry registers at startup\n * (src/bun/register-bundled-coding-agent.ts). loader.ts itself must not import\n * `../../index.ts` — that edge put it inside the index↔core import cycle\n * (scripts/check-import-cycles.mjs).\n */\n\n// Static imports of packages that extensions may use.\n// These MUST be static so Bun bundles them into the compiled binary.\n// The virtualModules option then makes them available to extensions.\nimport * as _bundledOmkAgentCore from \"omk-agent-core\";\nimport * as _bundledOmkAgentCoreNode from \"omk-agent-core/node\";\nimport * as _bundledOmkAi from \"omk-ai\";\nimport * as _bundledOmkAiOauth from \"omk-ai/oauth\";\nimport * as _bundledOmkTui from \"omk-tui\";\nimport * as _bundledTypebox from \"typebox\";\nimport * as _bundledTypeboxCompile from \"typebox/compile\";\nimport * as _bundledTypeboxValue from \"typebox/value\";\nimport { LEGACY_PI_RUNTIME_ALIASES, type PiCompatibilityTarget } from \"../pi-compat.ts\";\n\n/**\n * The compiled-binary entry registers the bundled package namespace here before\n * any extension resolves. loader.ts cannot import `../../index.ts` directly\n * (cycle), so this module is the injection point instead.\n */\nlet _bundledCodingAgentNamespace: unknown;\n\n/** Registration point for the compiled binary's bundled `open-multi-agent-kit` namespace. */\nexport function registerBundledCodingAgentNamespace(namespace: unknown): void {\n\t_bundledCodingAgentNamespace = namespace;\n}\n\nconst LEGACY_PI_VIRTUAL_TARGETS: Record<Exclude<PiCompatibilityTarget, \"coding-agent\">, unknown> = {\n\t\"agent-core\": _bundledOmkAgentCore,\n\t\"agent-core-node\": _bundledOmkAgentCoreNode,\n\tai: _bundledOmkAi,\n\t\"ai-oauth\": _bundledOmkAiOauth,\n\ttui: _bundledOmkTui,\n};\n\n/** Modules available to extensions via virtualModules (compiled Bun binary only). */\nexport function buildVirtualModules(): Record<string, unknown> {\n\tconst bundledCodingAgent = _bundledCodingAgentNamespace;\n\tconst legacyTargets: Record<PiCompatibilityTarget, unknown> = {\n\t\t...LEGACY_PI_VIRTUAL_TARGETS,\n\t\t\"coding-agent\": bundledCodingAgent,\n\t};\n\treturn {\n\t\t...Object.fromEntries(\n\t\t\tObject.entries(LEGACY_PI_RUNTIME_ALIASES).map(([specifier, target]) => [specifier, legacyTargets[target]]),\n\t\t),\n\t\ttypebox: _bundledTypebox,\n\t\t\"typebox/compile\": _bundledTypeboxCompile,\n\t\t\"typebox/value\": _bundledTypeboxValue,\n\t\t\"@sinclair/typebox\": _bundledTypebox,\n\t\t\"@sinclair/typebox/compile\": _bundledTypeboxCompile,\n\t\t\"@sinclair/typebox/value\": _bundledTypeboxValue,\n\t\t\"omk-agent-core\": _bundledOmkAgentCore,\n\t\t\"omk-agent-core/node\": _bundledOmkAgentCoreNode,\n\t\t\"omk-tui\": _bundledOmkTui,\n\t\t\"omk-ai\": _bundledOmkAi,\n\t\t\"omk-ai/oauth\": _bundledOmkAiOauth,\n\t\t\"open-multi-agent-kit\": bundledCodingAgent,\n\t};\n}\n"]}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Virtual modules for compiled Bun binaries — the extension-facing view of the
3
+ * bundled package namespaces.
4
+ *
5
+ * Extracted from loader.ts: the table resolves the bundled
6
+ * `open-multi-agent-kit` namespace that the binary entry registers at startup
7
+ * (src/bun/register-bundled-coding-agent.ts). loader.ts itself must not import
8
+ * `../../index.ts` — that edge put it inside the index↔core import cycle
9
+ * (scripts/check-import-cycles.mjs).
10
+ */
11
+ // Static imports of packages that extensions may use.
12
+ // These MUST be static so Bun bundles them into the compiled binary.
13
+ // The virtualModules option then makes them available to extensions.
14
+ import * as _bundledOmkAgentCore from "omk-agent-core";
15
+ import * as _bundledOmkAgentCoreNode from "omk-agent-core/node";
16
+ import * as _bundledOmkAi from "omk-ai";
17
+ import * as _bundledOmkAiOauth from "omk-ai/oauth";
18
+ import * as _bundledOmkTui from "omk-tui";
19
+ import * as _bundledTypebox from "typebox";
20
+ import * as _bundledTypeboxCompile from "typebox/compile";
21
+ import * as _bundledTypeboxValue from "typebox/value";
22
+ import { LEGACY_PI_RUNTIME_ALIASES } from "../pi-compat.js";
23
+ /**
24
+ * The compiled-binary entry registers the bundled package namespace here before
25
+ * any extension resolves. loader.ts cannot import `../../index.ts` directly
26
+ * (cycle), so this module is the injection point instead.
27
+ */
28
+ let _bundledCodingAgentNamespace;
29
+ /** Registration point for the compiled binary's bundled `open-multi-agent-kit` namespace. */
30
+ export function registerBundledCodingAgentNamespace(namespace) {
31
+ _bundledCodingAgentNamespace = namespace;
32
+ }
33
+ const LEGACY_PI_VIRTUAL_TARGETS = {
34
+ "agent-core": _bundledOmkAgentCore,
35
+ "agent-core-node": _bundledOmkAgentCoreNode,
36
+ ai: _bundledOmkAi,
37
+ "ai-oauth": _bundledOmkAiOauth,
38
+ tui: _bundledOmkTui,
39
+ };
40
+ /** Modules available to extensions via virtualModules (compiled Bun binary only). */
41
+ export function buildVirtualModules() {
42
+ const bundledCodingAgent = _bundledCodingAgentNamespace;
43
+ const legacyTargets = {
44
+ ...LEGACY_PI_VIRTUAL_TARGETS,
45
+ "coding-agent": bundledCodingAgent,
46
+ };
47
+ return {
48
+ ...Object.fromEntries(Object.entries(LEGACY_PI_RUNTIME_ALIASES).map(([specifier, target]) => [specifier, legacyTargets[target]])),
49
+ typebox: _bundledTypebox,
50
+ "typebox/compile": _bundledTypeboxCompile,
51
+ "typebox/value": _bundledTypeboxValue,
52
+ "@sinclair/typebox": _bundledTypebox,
53
+ "@sinclair/typebox/compile": _bundledTypeboxCompile,
54
+ "@sinclair/typebox/value": _bundledTypeboxValue,
55
+ "omk-agent-core": _bundledOmkAgentCore,
56
+ "omk-agent-core/node": _bundledOmkAgentCoreNode,
57
+ "omk-tui": _bundledOmkTui,
58
+ "omk-ai": _bundledOmkAi,
59
+ "omk-ai/oauth": _bundledOmkAiOauth,
60
+ "open-multi-agent-kit": bundledCodingAgent,
61
+ };
62
+ }
63
+ //# sourceMappingURL=bundled-virtual-modules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundled-virtual-modules.js","sourceRoot":"","sources":["../../../src/core/extensions/bundled-virtual-modules.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,sDAAsD;AACtD,qEAAqE;AACrE,qEAAqE;AACrE,OAAO,KAAK,oBAAoB,MAAM,gBAAgB,CAAC;AACvD,OAAO,KAAK,wBAAwB,MAAM,qBAAqB,CAAC;AAChE,OAAO,KAAK,aAAa,MAAM,QAAQ,CAAC;AACxC,OAAO,KAAK,kBAAkB,MAAM,cAAc,CAAC;AACnD,OAAO,KAAK,cAAc,MAAM,SAAS,CAAC;AAC1C,OAAO,KAAK,eAAe,MAAM,SAAS,CAAC;AAC3C,OAAO,KAAK,sBAAsB,MAAM,iBAAiB,CAAC;AAC1D,OAAO,KAAK,oBAAoB,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,yBAAyB,EAA8B,MAAM,iBAAiB,CAAC;AAExF;;;;GAIG;AACH,IAAI,4BAAqC,CAAC;AAE1C,6FAA6F;AAC7F,MAAM,UAAU,mCAAmC,CAAC,SAAkB,EAAQ;IAC7E,4BAA4B,GAAG,SAAS,CAAC;AAAA,CACzC;AAED,MAAM,yBAAyB,GAAoE;IAClG,YAAY,EAAE,oBAAoB;IAClC,iBAAiB,EAAE,wBAAwB;IAC3C,EAAE,EAAE,aAAa;IACjB,UAAU,EAAE,kBAAkB;IAC9B,GAAG,EAAE,cAAc;CACnB,CAAC;AAEF,qFAAqF;AACrF,MAAM,UAAU,mBAAmB,GAA4B;IAC9D,MAAM,kBAAkB,GAAG,4BAA4B,CAAC;IACxD,MAAM,aAAa,GAA2C;QAC7D,GAAG,yBAAyB;QAC5B,cAAc,EAAE,kBAAkB;KAClC,CAAC;IACF,OAAO;QACN,GAAG,MAAM,CAAC,WAAW,CACpB,MAAM,CAAC,OAAO,CAAC,yBAAyB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,SAAS,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAC1G;QACD,OAAO,EAAE,eAAe;QACxB,iBAAiB,EAAE,sBAAsB;QACzC,eAAe,EAAE,oBAAoB;QACrC,mBAAmB,EAAE,eAAe;QACpC,2BAA2B,EAAE,sBAAsB;QACnD,yBAAyB,EAAE,oBAAoB;QAC/C,gBAAgB,EAAE,oBAAoB;QACtC,qBAAqB,EAAE,wBAAwB;QAC/C,SAAS,EAAE,cAAc;QACzB,QAAQ,EAAE,aAAa;QACvB,cAAc,EAAE,kBAAkB;QAClC,sBAAsB,EAAE,kBAAkB;KAC1C,CAAC;AAAA,CACF","sourcesContent":["/**\n * Virtual modules for compiled Bun binaries — the extension-facing view of the\n * bundled package namespaces.\n *\n * Extracted from loader.ts: the table resolves the bundled\n * `open-multi-agent-kit` namespace that the binary entry registers at startup\n * (src/bun/register-bundled-coding-agent.ts). loader.ts itself must not import\n * `../../index.ts` — that edge put it inside the index↔core import cycle\n * (scripts/check-import-cycles.mjs).\n */\n\n// Static imports of packages that extensions may use.\n// These MUST be static so Bun bundles them into the compiled binary.\n// The virtualModules option then makes them available to extensions.\nimport * as _bundledOmkAgentCore from \"omk-agent-core\";\nimport * as _bundledOmkAgentCoreNode from \"omk-agent-core/node\";\nimport * as _bundledOmkAi from \"omk-ai\";\nimport * as _bundledOmkAiOauth from \"omk-ai/oauth\";\nimport * as _bundledOmkTui from \"omk-tui\";\nimport * as _bundledTypebox from \"typebox\";\nimport * as _bundledTypeboxCompile from \"typebox/compile\";\nimport * as _bundledTypeboxValue from \"typebox/value\";\nimport { LEGACY_PI_RUNTIME_ALIASES, type PiCompatibilityTarget } from \"../pi-compat.ts\";\n\n/**\n * The compiled-binary entry registers the bundled package namespace here before\n * any extension resolves. loader.ts cannot import `../../index.ts` directly\n * (cycle), so this module is the injection point instead.\n */\nlet _bundledCodingAgentNamespace: unknown;\n\n/** Registration point for the compiled binary's bundled `open-multi-agent-kit` namespace. */\nexport function registerBundledCodingAgentNamespace(namespace: unknown): void {\n\t_bundledCodingAgentNamespace = namespace;\n}\n\nconst LEGACY_PI_VIRTUAL_TARGETS: Record<Exclude<PiCompatibilityTarget, \"coding-agent\">, unknown> = {\n\t\"agent-core\": _bundledOmkAgentCore,\n\t\"agent-core-node\": _bundledOmkAgentCoreNode,\n\tai: _bundledOmkAi,\n\t\"ai-oauth\": _bundledOmkAiOauth,\n\ttui: _bundledOmkTui,\n};\n\n/** Modules available to extensions via virtualModules (compiled Bun binary only). */\nexport function buildVirtualModules(): Record<string, unknown> {\n\tconst bundledCodingAgent = _bundledCodingAgentNamespace;\n\tconst legacyTargets: Record<PiCompatibilityTarget, unknown> = {\n\t\t...LEGACY_PI_VIRTUAL_TARGETS,\n\t\t\"coding-agent\": bundledCodingAgent,\n\t};\n\treturn {\n\t\t...Object.fromEntries(\n\t\t\tObject.entries(LEGACY_PI_RUNTIME_ALIASES).map(([specifier, target]) => [specifier, legacyTargets[target]]),\n\t\t),\n\t\ttypebox: _bundledTypebox,\n\t\t\"typebox/compile\": _bundledTypeboxCompile,\n\t\t\"typebox/value\": _bundledTypeboxValue,\n\t\t\"@sinclair/typebox\": _bundledTypebox,\n\t\t\"@sinclair/typebox/compile\": _bundledTypeboxCompile,\n\t\t\"@sinclair/typebox/value\": _bundledTypeboxValue,\n\t\t\"omk-agent-core\": _bundledOmkAgentCore,\n\t\t\"omk-agent-core/node\": _bundledOmkAgentCoreNode,\n\t\t\"omk-tui\": _bundledOmkTui,\n\t\t\"omk-ai\": _bundledOmkAi,\n\t\t\"omk-ai/oauth\": _bundledOmkAiOauth,\n\t\t\"open-multi-agent-kit\": bundledCodingAgent,\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"loader.d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,CAAC,CA2C/B","sourcesContent":["/**\n * Extension loader - loads TypeScript extension modules using jiti.\n *\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createJiti } from \"jiti/static\";\nimport * as _bundledOmkAgentCore from \"omk-agent-core\";\nimport * as _bundledOmkAgentCoreNode from \"omk-agent-core/node\";\nimport * as _bundledOmkAi from \"omk-ai\";\nimport * as _bundledOmkAiOauth from \"omk-ai/oauth\";\nimport type { KeyId } from \"omk-tui\";\nimport * as _bundledOmkTui from \"omk-tui\";\n// Static imports of packages that extensions may use.\n// These MUST be static so Bun bundles them into the compiled binary.\n// The virtualModules option then makes them available to extensions.\nimport * as _bundledTypebox from \"typebox\";\nimport * as _bundledTypeboxCompile from \"typebox/compile\";\nimport * as _bundledTypeboxValue from \"typebox/value\";\nimport { CONFIG_DIR_NAME, getAgentDir, isBunBinary } from \"../../config.ts\";\n// NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n// avoiding a circular dependency. Extensions can import from open-multi-agent-kit.\nimport * as _bundledOmkCodingAgent from \"../../index.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions } from \"../exec.ts\";\nimport { execCommand } from \"../exec.ts\";\nimport { readPackageManifest } from \"../package-manifest.ts\";\nimport { LEGACY_PI_RUNTIME_ALIASES, type PiCompatibilityTarget } from \"../pi-compat.ts\";\nimport { createSyntheticSourceInfo } from \"../source-info.ts\";\nimport type {\n\tExtension,\n\tExtensionAPI,\n\tExtensionFactory,\n\tExtensionRuntime,\n\tLoadExtensionsResult,\n\tMessageRenderer,\n\tProviderConfig,\n\tRegisteredCommand,\n\tToolDefinition,\n} from \"./types.ts\";\n\nconst LEGACY_PI_VIRTUAL_TARGETS: Record<PiCompatibilityTarget, unknown> = {\n\t\"coding-agent\": _bundledOmkCodingAgent,\n\t\"agent-core\": _bundledOmkAgentCore,\n\t\"agent-core-node\": _bundledOmkAgentCoreNode,\n\tai: _bundledOmkAi,\n\t\"ai-oauth\": _bundledOmkAiOauth,\n\ttui: _bundledOmkTui,\n};\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary) */\nconst VIRTUAL_MODULES: Record<string, unknown> = {\n\t...Object.fromEntries(\n\t\tObject.entries(LEGACY_PI_RUNTIME_ALIASES).map(([specifier, target]) => [\n\t\t\tspecifier,\n\t\t\tLEGACY_PI_VIRTUAL_TARGETS[target],\n\t\t]),\n\t),\n\ttypebox: _bundledTypebox,\n\t\"typebox/compile\": _bundledTypeboxCompile,\n\t\"typebox/value\": _bundledTypeboxValue,\n\t\"@sinclair/typebox\": _bundledTypebox,\n\t\"@sinclair/typebox/compile\": _bundledTypeboxCompile,\n\t\"@sinclair/typebox/value\": _bundledTypeboxValue,\n\t\"omk-agent-core\": _bundledOmkAgentCore,\n\t\"omk-agent-core/node\": _bundledOmkAgentCoreNode,\n\t\"omk-tui\": _bundledOmkTui,\n\t\"omk-ai\": _bundledOmkAi,\n\t\"omk-ai/oauth\": _bundledOmkAiOauth,\n\t\"open-multi-agent-kit\": _bundledOmkCodingAgent,\n};\n\nconst require = createRequire(import.meta.url);\n\nlet _aliases: Record<string, string> | null = null;\n\ntype PackageJsonResolver = (id: string) => string;\ntype ExistsSync = (path: string) => boolean;\n\nfunction findPackageJsonPath(\n\tspecifier: string,\n\tstartDir: string,\n\tresolvePackageJson: PackageJsonResolver = require.resolve,\n\texistsSync: ExistsSync = fs.existsSync,\n): string {\n\ttry {\n\t\treturn resolvePackageJson(`${specifier}/package.json`);\n\t} catch {\n\t\tlet current = startDir;\n\t\twhile (true) {\n\t\t\tconst candidate = path.join(current, \"node_modules\", ...specifier.split(\"/\"), \"package.json\");\n\t\t\tif (existsSync(candidate)) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t\tconst parent = path.dirname(current);\n\t\t\tif (parent === current) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Unable to resolve package.json for ${specifier}. Install ${specifier} or run OMK from a workspace containing its built package.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcurrent = parent;\n\t\t}\n\t}\n}\n\nfunction resolveWorkspaceOrPackageFile(\n\tworkspaceRelativePath: string,\n\tspecifier: string,\n\tpackageRelativePath: string,\n\tpackagesRoot: string,\n\tresolvePackageJson: PackageJsonResolver,\n\texistsSync: ExistsSync,\n\tstartDir: string,\n): string {\n\tconst workspacePath = path.join(packagesRoot, workspaceRelativePath);\n\tif (existsSync(workspacePath)) {\n\t\treturn workspacePath;\n\t}\n\tconst packageJsonPath = findPackageJsonPath(specifier, startDir, resolvePackageJson, existsSync);\n\treturn path.join(path.dirname(packageJsonPath), packageRelativePath);\n}\n\n/** Internal test seam for omk-agent-core/node resolution branches. */\nexport function resolveOmkAgentCoreNodeEntryForTests(options: {\n\tpackagesRoot: string;\n\tstartDir: string;\n\tresolvePackageJson: PackageJsonResolver;\n\texistsSync: ExistsSync;\n}): string {\n\treturn resolveWorkspaceOrPackageFile(\n\t\t\"agent/dist/node.js\",\n\t\t\"omk-agent-core\",\n\t\t\"dist/node.js\",\n\t\toptions.packagesRoot,\n\t\toptions.resolvePackageJson,\n\t\toptions.existsSync,\n\t\toptions.startDir,\n\t);\n}\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nfunction getAliases(): Record<string, string> {\n\tif (_aliases) return _aliases;\n\n\tconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\tconst packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n\tconst typeboxEntry = require.resolve(\"typebox\");\n\tconst typeboxCompileEntry = require.resolve(\"typebox/compile\");\n\tconst typeboxValueEntry = require.resolve(\"typebox/value\");\n\n\tconst packagesRoot = path.resolve(__dirname, \"../../../../\");\n\tconst omkCodingAgentEntry = packageIndex;\n\tconst omkAgentCoreEntry = resolveWorkspaceOrPackageFile(\n\t\t\"agent/dist/index.js\",\n\t\t\"omk-agent-core\",\n\t\t\"dist/index.js\",\n\t\tpackagesRoot,\n\t\trequire.resolve,\n\t\tfs.existsSync,\n\t\t__dirname,\n\t);\n\tconst omkAgentCoreNodeEntry = resolveWorkspaceOrPackageFile(\n\t\t\"agent/dist/node.js\",\n\t\t\"omk-agent-core\",\n\t\t\"dist/node.js\",\n\t\tpackagesRoot,\n\t\trequire.resolve,\n\t\tfs.existsSync,\n\t\t__dirname,\n\t);\n\tconst omkTuiEntry = resolveWorkspaceOrPackageFile(\n\t\t\"tui/dist/index.js\",\n\t\t\"omk-tui\",\n\t\t\"dist/index.js\",\n\t\tpackagesRoot,\n\t\trequire.resolve,\n\t\tfs.existsSync,\n\t\t__dirname,\n\t);\n\tconst omkAiEntry = resolveWorkspaceOrPackageFile(\n\t\t\"ai/dist/index.js\",\n\t\t\"omk-ai\",\n\t\t\"dist/index.js\",\n\t\tpackagesRoot,\n\t\trequire.resolve,\n\t\tfs.existsSync,\n\t\t__dirname,\n\t);\n\tconst omkAiOauthEntry = resolveWorkspaceOrPackageFile(\n\t\t\"ai/dist/oauth.js\",\n\t\t\"omk-ai\",\n\t\t\"dist/oauth.js\",\n\t\tpackagesRoot,\n\t\trequire.resolve,\n\t\tfs.existsSync,\n\t\t__dirname,\n\t);\n\n\tconst legacyPiAliasTargets: Record<PiCompatibilityTarget, string> = {\n\t\t\"coding-agent\": omkCodingAgentEntry,\n\t\t\"agent-core\": omkAgentCoreEntry,\n\t\t\"agent-core-node\": omkAgentCoreNodeEntry,\n\t\tai: omkAiEntry,\n\t\t\"ai-oauth\": omkAiOauthEntry,\n\t\ttui: omkTuiEntry,\n\t};\n\t_aliases = {\n\t\t...Object.fromEntries(\n\t\t\tObject.entries(LEGACY_PI_RUNTIME_ALIASES).map(([specifier, target]) => [\n\t\t\t\tspecifier,\n\t\t\t\tlegacyPiAliasTargets[target],\n\t\t\t]),\n\t\t),\n\t\t\"open-multi-agent-kit\": omkCodingAgentEntry,\n\t\t\"omk-agent-core\": omkAgentCoreEntry,\n\t\t\"omk-agent-core/node\": omkAgentCoreNodeEntry,\n\t\t\"omk-tui\": omkTuiEntry,\n\t\t\"omk-ai\": omkAiEntry,\n\t\t\"omk-ai/oauth\": omkAiOauthEntry,\n\t\ttypebox: typeboxEntry,\n\t\t\"typebox/compile\": typeboxCompileEntry,\n\t\t\"typebox/value\": typeboxValueEntry,\n\t\t\"@sinclair/typebox\": typeboxEntry,\n\t\t\"@sinclair/typebox/compile\": typeboxCompileEntry,\n\t\t\"@sinclair/typebox/value\": typeboxValueEntry,\n\t};\n\n\treturn _aliases;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\n/**\n * Create a runtime with throwing stubs for action methods.\n * Runner.bindCore() replaces these with real implementations.\n */\nexport function createExtensionRuntime(): ExtensionRuntime {\n\tconst notInitialized = () => {\n\t\tthrow new Error(\"Extension runtime not initialized. Action methods cannot be called during extension loading.\");\n\t};\n\tconst state: { staleMessage?: string } = {};\n\tconst assertActive = () => {\n\t\tif (state.staleMessage) {\n\t\t\tthrow new Error(state.staleMessage);\n\t\t}\n\t};\n\n\tconst runtime: ExtensionRuntime = {\n\t\tsendMessage: notInitialized,\n\t\tsendUserMessage: notInitialized,\n\t\tappendEntry: notInitialized,\n\t\tsetSessionName: notInitialized,\n\t\tgetSessionName: notInitialized,\n\t\tsetLabel: notInitialized,\n\t\tgetActiveTools: notInitialized,\n\t\tgetAllTools: notInitialized,\n\t\tsetActiveTools: notInitialized,\n\t\t// registerTool() is valid during extension load; refresh is only needed post-bind.\n\t\trefreshTools: () => {},\n\t\tgetCommands: notInitialized,\n\t\tsetModel: () => Promise.reject(new Error(\"Extension runtime not initialized\")),\n\t\tgetThinkingLevel: notInitialized,\n\t\tsetThinkingLevel: notInitialized,\n\t\t// Optional; replaced by bindCore when the session provides a handler.\n\t\tcallMcpTool: undefined,\n\t\tflagValues: new Map(),\n\t\tpendingProviderRegistrations: [],\n\t\tassertActive,\n\t\tinvalidate: (message) => {\n\t\t\tstate.staleMessage ??=\n\t\t\t\tmessage ??\n\t\t\t\t\"This extension ctx is stale after session replacement or reload. Do not use a captured extension API or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\";\n\t\t},\n\t\t// Pre-bind: queue registrations so bindCore() can flush them once the\n\t\t// model registry is available. bindCore() replaces both with direct calls.\n\t\tregisterProvider: (name, config, extensionPath = \"<unknown>\") => {\n\t\t\truntime.pendingProviderRegistrations.push({ name, config, extensionPath });\n\t\t},\n\t\tunregisterProvider: (name) => {\n\t\t\truntime.pendingProviderRegistrations = runtime.pendingProviderRegistrations.filter((r) => r.name !== name);\n\t\t},\n\t};\n\n\treturn runtime;\n}\n\n/**\n * Create the ExtensionAPI for an extension.\n * Registration methods write to the extension object.\n * Action methods delegate to the shared runtime.\n */\nfunction createExtensionAPI(\n\textension: Extension,\n\truntime: ExtensionRuntime,\n\tcwd: string,\n\teventBus: EventBus,\n): ExtensionAPI {\n\tconst api = {\n\t\t// Registration methods - write to extension\n\t\ton(event: string, handler: HandlerFn): void {\n\t\t\truntime.assertActive();\n\t\t\tconst list = extension.handlers.get(event) ?? [];\n\t\t\tlist.push(handler);\n\t\t\textension.handlers.set(event, list);\n\t\t},\n\n\t\tregisterTool(tool: ToolDefinition): void {\n\t\t\truntime.assertActive();\n\t\t\textension.tools.set(tool.name, {\n\t\t\t\tdefinition: tool,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t});\n\t\t\truntime.refreshTools();\n\t\t},\n\n\t\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void {\n\t\t\truntime.assertActive();\n\t\t\textension.commands.set(name, {\n\t\t\t\tname,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\n\t\tregisterShortcut(\n\t\t\tshortcut: KeyId,\n\t\t\toptions: {\n\t\t\t\tdescription?: string;\n\t\t\t\thandler: (ctx: import(\"./types.ts\").ExtensionContext) => Promise<void> | void;\n\t\t\t},\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.shortcuts.set(shortcut, { shortcut, extensionPath: extension.path, ...options });\n\t\t},\n\n\t\tregisterFlag(\n\t\t\tname: string,\n\t\t\toptions: { description?: string; type: \"boolean\" | \"string\"; default?: boolean | string },\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.flags.set(name, { name, extensionPath: extension.path, ...options });\n\t\t\tif (options.default !== undefined && !runtime.flagValues.has(name)) {\n\t\t\t\truntime.flagValues.set(name, options.default);\n\t\t\t}\n\t\t},\n\n\t\tregisterMessageRenderer<T>(customType: string, renderer: MessageRenderer<T>): void {\n\t\t\truntime.assertActive();\n\t\t\textension.messageRenderers.set(customType, renderer as MessageRenderer);\n\t\t},\n\n\t\t// Flag access - checks extension registered it, reads from runtime\n\t\tgetFlag(name: string): boolean | string | undefined {\n\t\t\truntime.assertActive();\n\t\t\tif (!extension.flags.has(name)) return undefined;\n\t\t\treturn runtime.flagValues.get(name);\n\t\t},\n\n\t\t// Action methods - delegate to shared runtime\n\t\tsendMessage(message, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendMessage(message, options);\n\t\t},\n\n\t\tsendUserMessage(content, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendUserMessage(content, options);\n\t\t},\n\n\t\tappendEntry(customType: string, data?: unknown): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.appendEntry(customType, data);\n\t\t},\n\n\t\tsetSessionName(name: string): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setSessionName(name);\n\t\t},\n\n\t\tgetSessionName(): string | undefined {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getSessionName();\n\t\t},\n\n\t\tsetLabel(entryId: string, label: string | undefined): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setLabel(entryId, label);\n\t\t},\n\n\t\texec(command: string, args: string[], options?: ExecOptions) {\n\t\t\truntime.assertActive();\n\t\t\treturn execCommand(command, args, options?.cwd ?? cwd, options);\n\t\t},\n\n\t\t// Always expose the method so load-time factories can capture it (typeof === \"function\").\n\t\t// The bound handler is resolved at call time after bindCore; until then callers get a clear error.\n\t\tasync callMcpTool(server: string, name: string, args: Record<string, unknown>): Promise<unknown> {\n\t\t\truntime.assertActive();\n\t\t\tconst handler = runtime.callMcpTool;\n\t\t\tif (typeof handler !== \"function\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Extension callMcpTool is not bound. The session must provide a callMcpTool handler via bindCore.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn handler(server, name, args);\n\t\t},\n\n\t\tisMcpToolBound(): boolean {\n\t\t\truntime.assertActive();\n\t\t\treturn typeof runtime.callMcpTool === \"function\";\n\t\t},\n\n\t\tgetActiveTools(): string[] {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getActiveTools();\n\t\t},\n\n\t\tgetAllTools() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getAllTools();\n\t\t},\n\n\t\tsetActiveTools(toolNames: string[]): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setActiveTools(toolNames);\n\t\t},\n\n\t\tgetCommands() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getCommands();\n\t\t},\n\n\t\tsetModel(model) {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.setModel(model);\n\t\t},\n\n\t\tgetThinkingLevel() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getThinkingLevel();\n\t\t},\n\n\t\tsetThinkingLevel(level) {\n\t\t\truntime.assertActive();\n\t\t\truntime.setThinkingLevel(level);\n\t\t},\n\n\t\tregisterProvider(name: string, config: ProviderConfig) {\n\t\t\truntime.assertActive();\n\t\t\truntime.registerProvider(name, config, extension.path);\n\t\t},\n\n\t\tunregisterProvider(name: string) {\n\t\t\truntime.assertActive();\n\t\t\truntime.unregisterProvider(name, extension.path);\n\t\t},\n\n\t\t// Track extension event subscriptions so they can be\n\t\t// unsubscribed on reload instead of stacking duplicate listeners\n\t\t// on the shared event bus.\n\t\tevents: {\n\t\t\temit: (channel, data) => {\n\t\t\t\teventBus.emit(channel, data);\n\t\t\t},\n\t\t\ton: (channel, handler) => {\n\t\t\t\tconst unsubscribe = eventBus.on(channel, handler);\n\t\t\t\textension.eventBusSubscriptions?.push(unsubscribe);\n\t\t\t\treturn unsubscribe;\n\t\t\t},\n\t\t},\n\t} as ExtensionAPI;\n\n\treturn api;\n}\n\nasync function loadExtensionModule(extensionPath: string, binaryMode = isBunBinary) {\n\tconst jiti = createJiti(import.meta.url, {\n\t\tmoduleCache: false,\n\t\t// In Bun binary: use virtualModules for bundled packages (no filesystem resolution)\n\t\t// Also disable tryNative so jiti handles ALL imports (not just the entry point)\n\t\t// In Node.js/dev: use aliases to resolve to node_modules paths\n\t\t...(binaryMode ? { virtualModules: VIRTUAL_MODULES, tryNative: false } : { alias: getAliases() }),\n\t});\n\n\tconst module = await jiti.import(extensionPath, { default: true });\n\tconst factory = module as ExtensionFactory;\n\treturn typeof factory !== \"function\" ? undefined : factory;\n}\n/** Internal test seam for loading extensions through Bun binary virtual modules. */\nexport async function loadExtensionModuleWithVirtualModulesForTests(extensionPath: string) {\n\treturn loadExtensionModule(extensionPath, true);\n}\n\n/**\n * Create an Extension object with empty collections.\n */\nfunction createExtension(extensionPath: string, resolvedPath: string): Extension {\n\tconst source =\n\t\textensionPath.startsWith(\"<\") && extensionPath.endsWith(\">\")\n\t\t\t? extensionPath.slice(1, -1).split(\":\")[0] || \"temporary\"\n\t\t\t: \"local\";\n\tconst baseDir = extensionPath.startsWith(\"<\") ? undefined : path.dirname(resolvedPath);\n\n\treturn {\n\t\tpath: extensionPath,\n\t\tresolvedPath,\n\t\tsourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }),\n\t\thandlers: new Map(),\n\t\ttools: new Map(),\n\t\tmessageRenderers: new Map(),\n\t\tcommands: new Map(),\n\t\tflags: new Map(),\n\t\tshortcuts: new Map(),\n\t\teventBusSubscriptions: [],\n\t};\n}\n\nasync function loadExtension(\n\textensionPath: string,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n): Promise<{ extension: Extension | null; error: string | null }> {\n\tconst resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });\n\n\ttry {\n\t\tconst factory = await loadExtensionModule(resolvedPath);\n\t\tif (!factory) {\n\t\t\treturn { extension: null, error: `Extension does not export a valid factory function: ${extensionPath}` };\n\t\t}\n\n\t\tconst extension = createExtension(extensionPath, resolvedPath);\n\t\tconst api = createExtensionAPI(extension, runtime, cwd, eventBus);\n\t\tawait factory(api);\n\n\t\treturn { extension, error: null };\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\treturn { extension: null, error: `Failed to load extension: ${message}` };\n\t}\n}\n\n/**\n * Create an Extension from an inline factory function.\n */\nexport async function loadExtensionFromFactory(\n\tfactory: ExtensionFactory,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\textensionPath = \"<inline>\",\n): Promise<Extension> {\n\tconst extension = createExtension(extensionPath, extensionPath);\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst api = createExtensionAPI(extension, runtime, resolvedCwd, eventBus);\n\tawait factory(api);\n\treturn extension;\n}\n\n/**\n * Load extensions from paths.\n */\nexport async function loadExtensions(paths: string[], cwd: string, eventBus?: EventBus): Promise<LoadExtensionsResult> {\n\tconst extensions: Extension[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedEventBus = eventBus ?? createEventBus();\n\tconst runtime = createExtensionRuntime();\n\n\tfor (const extPath of paths) {\n\t\tconst { extension, error } = await loadExtension(extPath, resolvedCwd, resolvedEventBus, runtime);\n\n\t\tif (error) {\n\t\t\terrors.push({ path: extPath, error });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (extension) {\n\t\t\textensions.push(extension);\n\t\t}\n\t}\n\n\treturn {\n\t\textensions,\n\t\terrors,\n\t\truntime,\n\t};\n}\n\nfunction isExtensionFile(name: string): boolean {\n\treturn name.endsWith(\".ts\") || name.endsWith(\".js\");\n}\n\n/**\n * Resolve extension entry points from a directory.\n *\n * Checks for:\n * 1. package.json with \"omk.extensions\" or \"pi.extensions\" (omk wins)\n * 2. index.ts or index.js -> returns the index file\n *\n * Returns resolved paths or null if no entry points found.\n */\nfunction resolveExtensionEntries(dir: string): string[] | null {\n\tconst packageJsonPath = path.join(dir, \"package.json\");\n\tif (fs.existsSync(packageJsonPath)) {\n\t\tconst resolvedManifest = readPackageManifest(packageJsonPath);\n\t\tif (resolvedManifest && (resolvedManifest.key !== null || resolvedManifest.diagnostics.length > 0)) {\n\t\t\tconst entries: string[] = [];\n\t\t\tfor (const extPath of resolvedManifest.manifest?.extensions ?? []) {\n\t\t\t\tconst candidate = path.resolve(dir, extPath);\n\t\t\t\tif (!fs.existsSync(candidate)) continue;\n\t\t\t\tif (fs.statSync(candidate).isDirectory()) {\n\t\t\t\t\tfor (const indexName of [\"index.ts\", \"index.js\", \"index.mjs\", \"index.cjs\"]) {\n\t\t\t\t\t\tconst indexPath = path.join(candidate, indexName);\n\t\t\t\t\t\tif (fs.existsSync(indexPath)) {\n\t\t\t\t\t\t\tentries.push(indexPath);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tentries.push(candidate);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn entries;\n\t\t}\n\t}\n\n\t// Check for index.ts or index.js\n\tconst indexTs = path.join(dir, \"index.ts\");\n\tconst indexJs = path.join(dir, \"index.js\");\n\tif (fs.existsSync(indexTs)) {\n\t\treturn [indexTs];\n\t}\n\tif (fs.existsSync(indexJs)) {\n\t\treturn [indexJs];\n\t}\n\n\treturn null;\n}\n\n/**\n * Discover extensions in a directory.\n *\n * Discovery rules:\n * 1. Direct files: `extensions/*.ts` or `*.js` → load\n * 2. Subdirectory with index: `extensions/* /index.ts` or `index.js` → load\n * 3. Subdirectory with package.json: `extensions/* /package.json` with OMK manifest → load what it declares\n *\n * No recursion beyond one level. Complex packages must use package.json manifest.\n */\nfunction discoverExtensionsInDir(dir: string): string[] {\n\tif (!fs.existsSync(dir)) {\n\t\treturn [];\n\t}\n\n\tconst discovered: string[] = [];\n\n\ttry {\n\t\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tconst entryPath = path.join(dir, entry.name);\n\n\t\t\t// 1. Direct files: *.ts or *.js\n\t\t\tif ((entry.isFile() || entry.isSymbolicLink()) && isExtensionFile(entry.name)) {\n\t\t\t\tdiscovered.push(entryPath);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// 2 & 3. Subdirectories\n\t\t\tif (entry.isDirectory() || entry.isSymbolicLink()) {\n\t\t\t\tconst entries = resolveExtensionEntries(entryPath);\n\t\t\t\tif (entries) {\n\t\t\t\t\tdiscovered.push(...entries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn [];\n\t}\n\n\treturn discovered;\n}\n\n/**\n * Discover and load extensions from standard locations.\n */\nexport async function discoverAndLoadExtensions(\n\tconfiguredPaths: string[],\n\tcwd: string,\n\tagentDir: string = getAgentDir(),\n\teventBus?: EventBus,\n): Promise<LoadExtensionsResult> {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir);\n\tconst allPaths: string[] = [];\n\tconst seen = new Set<string>();\n\n\tconst addPaths = (paths: string[]) => {\n\t\tfor (const p of paths) {\n\t\t\tconst resolved = path.resolve(p);\n\t\t\tif (!seen.has(resolved)) {\n\t\t\t\tseen.add(resolved);\n\t\t\t\tallPaths.push(p);\n\t\t\t}\n\t\t}\n\t};\n\n\t// 1. Project-local extensions: cwd/${CONFIG_DIR_NAME}/extensions/\n\tconst localExtDir = path.join(resolvedCwd, CONFIG_DIR_NAME, \"extensions\");\n\taddPaths(discoverExtensionsInDir(localExtDir));\n\n\t// 2. Global extensions: agentDir/extensions/\n\tconst globalExtDir = path.join(resolvedAgentDir, \"extensions\");\n\taddPaths(discoverExtensionsInDir(globalExtDir));\n\n\t// 3. Explicitly configured paths\n\tfor (const p of configuredPaths) {\n\t\tconst resolved = resolvePath(p, resolvedCwd, { normalizeUnicodeSpaces: true });\n\t\tif (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {\n\t\t\t// Check for package.json with omk manifest or index.ts\n\t\t\tconst entries = resolveExtensionEntries(resolved);\n\t\t\tif (entries) {\n\t\t\t\taddPaths(entries);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// No explicit entries - discover individual files in directory\n\t\t\taddPaths(discoverExtensionsInDir(resolved));\n\t\t\tcontinue;\n\t\t}\n\n\t\taddPaths([resolved]);\n\t}\n\n\treturn loadExtensions(allPaths, resolvedCwd, eventBus);\n}\n"]}
1
+ {"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAUH,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAOhE,OAAO,KAAK,EACX,SAAS,EAET,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,EAKpB,MAAM,YAAY,CAAC;AAMpB,KAAK,mBAAmB,GAAG,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;AAClD,KAAK,UAAU,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;AA6C5C,sEAAsE;AACtE,wBAAgB,oCAAoC,CAAC,OAAO,EAAE;IAC7D,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,kBAAkB,EAAE,mBAAmB,CAAC;IACxC,UAAU,EAAE,UAAU,CAAC;CACvB,GAAG,MAAM,CAUT;AAkGD;;;GAGG;AACH,wBAAgB,sBAAsB,IAAI,gBAAgB,CAgDzD;AA4MD,oFAAoF;AACpF,wBAAsB,6CAA6C,CAAC,aAAa,EAAE,MAAM,yCAExF;AAmDD;;GAEG;AACH,wBAAsB,wBAAwB,CAC7C,OAAO,EAAE,gBAAgB,EACzB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,gBAAgB,EACzB,aAAa,SAAa,GACxB,OAAO,CAAC,SAAS,CAAC,CAMpB;AAED;;GAEG;AACH,wBAAsB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAyBrH;AAiGD;;GAEG;AACH,wBAAsB,yBAAyB,CAC9C,eAAe,EAAE,MAAM,EAAE,EACzB,GAAG,EAAE,MAAM,EACX,QAAQ,GAAE,MAAsB,EAChC,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,oBAAoB,CAAC,CA2C/B","sourcesContent":["/**\n * Extension loader - loads TypeScript extension modules using jiti.\n *\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createJiti } from \"jiti/static\";\nimport type { KeyId } from \"omk-tui\";\nimport { CONFIG_DIR_NAME, getAgentDir, isBunBinary } from \"../../config.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions } from \"../exec.ts\";\nimport { execCommand } from \"../exec.ts\";\nimport { readPackageManifest } from \"../package-manifest.ts\";\nimport { LEGACY_PI_RUNTIME_ALIASES, type PiCompatibilityTarget } from \"../pi-compat.ts\";\nimport { createSyntheticSourceInfo } from \"../source-info.ts\";\nimport { buildVirtualModules } from \"./bundled-virtual-modules.ts\";\nimport type {\n\tExtension,\n\tExtensionAPI,\n\tExtensionFactory,\n\tExtensionRuntime,\n\tLoadExtensionsResult,\n\tMessageRenderer,\n\tProviderConfig,\n\tRegisteredCommand,\n\tToolDefinition,\n} from \"./types.ts\";\n\nconst require = createRequire(import.meta.url);\n\nlet _aliases: Record<string, string> | null = null;\n\ntype PackageJsonResolver = (id: string) => string;\ntype ExistsSync = (path: string) => boolean;\n\nfunction findPackageJsonPath(\n\tspecifier: string,\n\tstartDir: string,\n\tresolvePackageJson: PackageJsonResolver = require.resolve,\n\texistsSync: ExistsSync = fs.existsSync,\n): string {\n\ttry {\n\t\treturn resolvePackageJson(`${specifier}/package.json`);\n\t} catch {\n\t\tlet current = startDir;\n\t\twhile (true) {\n\t\t\tconst candidate = path.join(current, \"node_modules\", ...specifier.split(\"/\"), \"package.json\");\n\t\t\tif (existsSync(candidate)) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t\tconst parent = path.dirname(current);\n\t\t\tif (parent === current) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Unable to resolve package.json for ${specifier}. Install ${specifier} or run OMK from a workspace containing its built package.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tcurrent = parent;\n\t\t}\n\t}\n}\n\nfunction resolveWorkspaceOrPackageFile(\n\tworkspaceRelativePath: string,\n\tspecifier: string,\n\tpackageRelativePath: string,\n\tpackagesRoot: string,\n\tresolvePackageJson: PackageJsonResolver,\n\texistsSync: ExistsSync,\n\tstartDir: string,\n): string {\n\tconst workspacePath = path.join(packagesRoot, workspaceRelativePath);\n\tif (existsSync(workspacePath)) {\n\t\treturn workspacePath;\n\t}\n\tconst packageJsonPath = findPackageJsonPath(specifier, startDir, resolvePackageJson, existsSync);\n\treturn path.join(path.dirname(packageJsonPath), packageRelativePath);\n}\n\n/** Internal test seam for omk-agent-core/node resolution branches. */\nexport function resolveOmkAgentCoreNodeEntryForTests(options: {\n\tpackagesRoot: string;\n\tstartDir: string;\n\tresolvePackageJson: PackageJsonResolver;\n\texistsSync: ExistsSync;\n}): string {\n\treturn resolveWorkspaceOrPackageFile(\n\t\t\"agent/dist/node.js\",\n\t\t\"omk-agent-core\",\n\t\t\"dist/node.js\",\n\t\toptions.packagesRoot,\n\t\toptions.resolvePackageJson,\n\t\toptions.existsSync,\n\t\toptions.startDir,\n\t);\n}\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nfunction getAliases(): Record<string, string> {\n\tif (_aliases) return _aliases;\n\n\tconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\tconst packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n\tconst typeboxEntry = require.resolve(\"typebox\");\n\tconst typeboxCompileEntry = require.resolve(\"typebox/compile\");\n\tconst typeboxValueEntry = require.resolve(\"typebox/value\");\n\n\tconst packagesRoot = path.resolve(__dirname, \"../../../../\");\n\tconst omkCodingAgentEntry = packageIndex;\n\tconst omkAgentCoreEntry = resolveWorkspaceOrPackageFile(\n\t\t\"agent/dist/index.js\",\n\t\t\"omk-agent-core\",\n\t\t\"dist/index.js\",\n\t\tpackagesRoot,\n\t\trequire.resolve,\n\t\tfs.existsSync,\n\t\t__dirname,\n\t);\n\tconst omkAgentCoreNodeEntry = resolveWorkspaceOrPackageFile(\n\t\t\"agent/dist/node.js\",\n\t\t\"omk-agent-core\",\n\t\t\"dist/node.js\",\n\t\tpackagesRoot,\n\t\trequire.resolve,\n\t\tfs.existsSync,\n\t\t__dirname,\n\t);\n\tconst omkTuiEntry = resolveWorkspaceOrPackageFile(\n\t\t\"tui/dist/index.js\",\n\t\t\"omk-tui\",\n\t\t\"dist/index.js\",\n\t\tpackagesRoot,\n\t\trequire.resolve,\n\t\tfs.existsSync,\n\t\t__dirname,\n\t);\n\tconst omkAiEntry = resolveWorkspaceOrPackageFile(\n\t\t\"ai/dist/index.js\",\n\t\t\"omk-ai\",\n\t\t\"dist/index.js\",\n\t\tpackagesRoot,\n\t\trequire.resolve,\n\t\tfs.existsSync,\n\t\t__dirname,\n\t);\n\tconst omkAiOauthEntry = resolveWorkspaceOrPackageFile(\n\t\t\"ai/dist/oauth.js\",\n\t\t\"omk-ai\",\n\t\t\"dist/oauth.js\",\n\t\tpackagesRoot,\n\t\trequire.resolve,\n\t\tfs.existsSync,\n\t\t__dirname,\n\t);\n\n\tconst legacyPiAliasTargets: Record<PiCompatibilityTarget, string> = {\n\t\t\"coding-agent\": omkCodingAgentEntry,\n\t\t\"agent-core\": omkAgentCoreEntry,\n\t\t\"agent-core-node\": omkAgentCoreNodeEntry,\n\t\tai: omkAiEntry,\n\t\t\"ai-oauth\": omkAiOauthEntry,\n\t\ttui: omkTuiEntry,\n\t};\n\t_aliases = {\n\t\t...Object.fromEntries(\n\t\t\tObject.entries(LEGACY_PI_RUNTIME_ALIASES).map(([specifier, target]) => [\n\t\t\t\tspecifier,\n\t\t\t\tlegacyPiAliasTargets[target],\n\t\t\t]),\n\t\t),\n\t\t\"open-multi-agent-kit\": omkCodingAgentEntry,\n\t\t\"omk-agent-core\": omkAgentCoreEntry,\n\t\t\"omk-agent-core/node\": omkAgentCoreNodeEntry,\n\t\t\"omk-tui\": omkTuiEntry,\n\t\t\"omk-ai\": omkAiEntry,\n\t\t\"omk-ai/oauth\": omkAiOauthEntry,\n\t\ttypebox: typeboxEntry,\n\t\t\"typebox/compile\": typeboxCompileEntry,\n\t\t\"typebox/value\": typeboxValueEntry,\n\t\t\"@sinclair/typebox\": typeboxEntry,\n\t\t\"@sinclair/typebox/compile\": typeboxCompileEntry,\n\t\t\"@sinclair/typebox/value\": typeboxValueEntry,\n\t};\n\n\treturn _aliases;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\n/**\n * Create a runtime with throwing stubs for action methods.\n * Runner.bindCore() replaces these with real implementations.\n */\nexport function createExtensionRuntime(): ExtensionRuntime {\n\tconst notInitialized = () => {\n\t\tthrow new Error(\"Extension runtime not initialized. Action methods cannot be called during extension loading.\");\n\t};\n\tconst state: { staleMessage?: string } = {};\n\tconst assertActive = () => {\n\t\tif (state.staleMessage) {\n\t\t\tthrow new Error(state.staleMessage);\n\t\t}\n\t};\n\n\tconst runtime: ExtensionRuntime = {\n\t\tsendMessage: notInitialized,\n\t\tsendUserMessage: notInitialized,\n\t\tappendEntry: notInitialized,\n\t\tsetSessionName: notInitialized,\n\t\tgetSessionName: notInitialized,\n\t\tsetLabel: notInitialized,\n\t\tgetActiveTools: notInitialized,\n\t\tgetAllTools: notInitialized,\n\t\tsetActiveTools: notInitialized,\n\t\t// registerTool() is valid during extension load; refresh is only needed post-bind.\n\t\trefreshTools: () => {},\n\t\tgetCommands: notInitialized,\n\t\tsetModel: () => Promise.reject(new Error(\"Extension runtime not initialized\")),\n\t\tgetThinkingLevel: notInitialized,\n\t\tsetThinkingLevel: notInitialized,\n\t\t// Optional; replaced by bindCore when the session provides a handler.\n\t\tcallMcpTool: undefined,\n\t\tflagValues: new Map(),\n\t\tpendingProviderRegistrations: [],\n\t\tassertActive,\n\t\tinvalidate: (message) => {\n\t\t\tstate.staleMessage ??=\n\t\t\t\tmessage ??\n\t\t\t\t\"This extension ctx is stale after session replacement or reload. Do not use a captured extension API or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\";\n\t\t},\n\t\t// Pre-bind: queue registrations so bindCore() can flush them once the\n\t\t// model registry is available. bindCore() replaces both with direct calls.\n\t\tregisterProvider: (name, config, extensionPath = \"<unknown>\") => {\n\t\t\truntime.pendingProviderRegistrations.push({ name, config, extensionPath });\n\t\t},\n\t\tunregisterProvider: (name) => {\n\t\t\truntime.pendingProviderRegistrations = runtime.pendingProviderRegistrations.filter((r) => r.name !== name);\n\t\t},\n\t};\n\n\treturn runtime;\n}\n\n/**\n * Create the ExtensionAPI for an extension.\n * Registration methods write to the extension object.\n * Action methods delegate to the shared runtime.\n */\nfunction createExtensionAPI(\n\textension: Extension,\n\truntime: ExtensionRuntime,\n\tcwd: string,\n\teventBus: EventBus,\n): ExtensionAPI {\n\tconst api = {\n\t\t// Registration methods - write to extension\n\t\ton(event: string, handler: HandlerFn): void {\n\t\t\truntime.assertActive();\n\t\t\tconst list = extension.handlers.get(event) ?? [];\n\t\t\tlist.push(handler);\n\t\t\textension.handlers.set(event, list);\n\t\t},\n\n\t\tregisterTool(tool: ToolDefinition): void {\n\t\t\truntime.assertActive();\n\t\t\textension.tools.set(tool.name, {\n\t\t\t\tdefinition: tool,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t});\n\t\t\truntime.refreshTools();\n\t\t},\n\n\t\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void {\n\t\t\truntime.assertActive();\n\t\t\textension.commands.set(name, {\n\t\t\t\tname,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\n\t\tregisterShortcut(\n\t\t\tshortcut: KeyId,\n\t\t\toptions: {\n\t\t\t\tdescription?: string;\n\t\t\t\thandler: (ctx: import(\"./types.ts\").ExtensionContext) => Promise<void> | void;\n\t\t\t},\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.shortcuts.set(shortcut, { shortcut, extensionPath: extension.path, ...options });\n\t\t},\n\n\t\tregisterFlag(\n\t\t\tname: string,\n\t\t\toptions: { description?: string; type: \"boolean\" | \"string\"; default?: boolean | string },\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.flags.set(name, { name, extensionPath: extension.path, ...options });\n\t\t\tif (options.default !== undefined && !runtime.flagValues.has(name)) {\n\t\t\t\truntime.flagValues.set(name, options.default);\n\t\t\t}\n\t\t},\n\n\t\tregisterMessageRenderer<T>(customType: string, renderer: MessageRenderer<T>): void {\n\t\t\truntime.assertActive();\n\t\t\textension.messageRenderers.set(customType, renderer as MessageRenderer);\n\t\t},\n\n\t\t// Flag access - checks extension registered it, reads from runtime\n\t\tgetFlag(name: string): boolean | string | undefined {\n\t\t\truntime.assertActive();\n\t\t\tif (!extension.flags.has(name)) return undefined;\n\t\t\treturn runtime.flagValues.get(name);\n\t\t},\n\n\t\t// Action methods - delegate to shared runtime\n\t\tsendMessage(message, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendMessage(message, options);\n\t\t},\n\n\t\tsendUserMessage(content, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendUserMessage(content, options);\n\t\t},\n\n\t\tappendEntry(customType: string, data?: unknown): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.appendEntry(customType, data);\n\t\t},\n\n\t\tsetSessionName(name: string): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setSessionName(name);\n\t\t},\n\n\t\tgetSessionName(): string | undefined {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getSessionName();\n\t\t},\n\n\t\tsetLabel(entryId: string, label: string | undefined): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setLabel(entryId, label);\n\t\t},\n\n\t\texec(command: string, args: string[], options?: ExecOptions) {\n\t\t\truntime.assertActive();\n\t\t\treturn execCommand(command, args, options?.cwd ?? cwd, options);\n\t\t},\n\n\t\t// Always expose the method so load-time factories can capture it (typeof === \"function\").\n\t\t// The bound handler is resolved at call time after bindCore; until then callers get a clear error.\n\t\tasync callMcpTool(server: string, name: string, args: Record<string, unknown>): Promise<unknown> {\n\t\t\truntime.assertActive();\n\t\t\tconst handler = runtime.callMcpTool;\n\t\t\tif (typeof handler !== \"function\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Extension callMcpTool is not bound. The session must provide a callMcpTool handler via bindCore.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn handler(server, name, args);\n\t\t},\n\n\t\tisMcpToolBound(): boolean {\n\t\t\truntime.assertActive();\n\t\t\treturn typeof runtime.callMcpTool === \"function\";\n\t\t},\n\n\t\tgetActiveTools(): string[] {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getActiveTools();\n\t\t},\n\n\t\tgetAllTools() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getAllTools();\n\t\t},\n\n\t\tsetActiveTools(toolNames: string[]): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setActiveTools(toolNames);\n\t\t},\n\n\t\tgetCommands() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getCommands();\n\t\t},\n\n\t\tsetModel(model) {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.setModel(model);\n\t\t},\n\n\t\tgetThinkingLevel() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getThinkingLevel();\n\t\t},\n\n\t\tsetThinkingLevel(level) {\n\t\t\truntime.assertActive();\n\t\t\truntime.setThinkingLevel(level);\n\t\t},\n\n\t\tregisterProvider(name: string, config: ProviderConfig) {\n\t\t\truntime.assertActive();\n\t\t\truntime.registerProvider(name, config, extension.path);\n\t\t},\n\n\t\tunregisterProvider(name: string) {\n\t\t\truntime.assertActive();\n\t\t\truntime.unregisterProvider(name, extension.path);\n\t\t},\n\n\t\t// Track extension event subscriptions so they can be\n\t\t// unsubscribed on reload instead of stacking duplicate listeners\n\t\t// on the shared event bus.\n\t\tevents: {\n\t\t\temit: (channel, data) => {\n\t\t\t\teventBus.emit(channel, data);\n\t\t\t},\n\t\t\ton: (channel, handler) => {\n\t\t\t\tconst unsubscribe = eventBus.on(channel, handler);\n\t\t\t\textension.eventBusSubscriptions?.push(unsubscribe);\n\t\t\t\treturn unsubscribe;\n\t\t\t},\n\t\t},\n\t} as ExtensionAPI;\n\n\treturn api;\n}\n\nasync function loadExtensionModule(extensionPath: string, binaryMode = isBunBinary) {\n\tconst jiti = createJiti(import.meta.url, {\n\t\tmoduleCache: false,\n\t\t// In Bun binary: use virtualModules for bundled packages (no filesystem resolution)\n\t\t// Also disable tryNative so jiti handles ALL imports (not just the entry point)\n\t\t// In Node.js/dev: use aliases to resolve to node_modules paths\n\t\t...(binaryMode ? { virtualModules: buildVirtualModules(), tryNative: false } : { alias: getAliases() }),\n\t});\n\n\tconst module = await jiti.import(extensionPath, { default: true });\n\tconst factory = module as ExtensionFactory;\n\treturn typeof factory !== \"function\" ? undefined : factory;\n}\n/** Internal test seam for loading extensions through Bun binary virtual modules. */\nexport async function loadExtensionModuleWithVirtualModulesForTests(extensionPath: string) {\n\treturn loadExtensionModule(extensionPath, true);\n}\n\n/**\n * Create an Extension object with empty collections.\n */\nfunction createExtension(extensionPath: string, resolvedPath: string): Extension {\n\tconst source =\n\t\textensionPath.startsWith(\"<\") && extensionPath.endsWith(\">\")\n\t\t\t? extensionPath.slice(1, -1).split(\":\")[0] || \"temporary\"\n\t\t\t: \"local\";\n\tconst baseDir = extensionPath.startsWith(\"<\") ? undefined : path.dirname(resolvedPath);\n\n\treturn {\n\t\tpath: extensionPath,\n\t\tresolvedPath,\n\t\tsourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }),\n\t\thandlers: new Map(),\n\t\ttools: new Map(),\n\t\tmessageRenderers: new Map(),\n\t\tcommands: new Map(),\n\t\tflags: new Map(),\n\t\tshortcuts: new Map(),\n\t\teventBusSubscriptions: [],\n\t};\n}\n\nasync function loadExtension(\n\textensionPath: string,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n): Promise<{ extension: Extension | null; error: string | null }> {\n\tconst resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });\n\n\ttry {\n\t\tconst factory = await loadExtensionModule(resolvedPath);\n\t\tif (!factory) {\n\t\t\treturn { extension: null, error: `Extension does not export a valid factory function: ${extensionPath}` };\n\t\t}\n\n\t\tconst extension = createExtension(extensionPath, resolvedPath);\n\t\tconst api = createExtensionAPI(extension, runtime, cwd, eventBus);\n\t\tawait factory(api);\n\n\t\treturn { extension, error: null };\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\treturn { extension: null, error: `Failed to load extension: ${message}` };\n\t}\n}\n\n/**\n * Create an Extension from an inline factory function.\n */\nexport async function loadExtensionFromFactory(\n\tfactory: ExtensionFactory,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\textensionPath = \"<inline>\",\n): Promise<Extension> {\n\tconst extension = createExtension(extensionPath, extensionPath);\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst api = createExtensionAPI(extension, runtime, resolvedCwd, eventBus);\n\tawait factory(api);\n\treturn extension;\n}\n\n/**\n * Load extensions from paths.\n */\nexport async function loadExtensions(paths: string[], cwd: string, eventBus?: EventBus): Promise<LoadExtensionsResult> {\n\tconst extensions: Extension[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedEventBus = eventBus ?? createEventBus();\n\tconst runtime = createExtensionRuntime();\n\n\tfor (const extPath of paths) {\n\t\tconst { extension, error } = await loadExtension(extPath, resolvedCwd, resolvedEventBus, runtime);\n\n\t\tif (error) {\n\t\t\terrors.push({ path: extPath, error });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (extension) {\n\t\t\textensions.push(extension);\n\t\t}\n\t}\n\n\treturn {\n\t\textensions,\n\t\terrors,\n\t\truntime,\n\t};\n}\n\nfunction isExtensionFile(name: string): boolean {\n\treturn name.endsWith(\".ts\") || name.endsWith(\".js\");\n}\n\n/**\n * Resolve extension entry points from a directory.\n *\n * Checks for:\n * 1. package.json with \"omk.extensions\" or \"pi.extensions\" (omk wins)\n * 2. index.ts or index.js -> returns the index file\n *\n * Returns resolved paths or null if no entry points found.\n */\nfunction resolveExtensionEntries(dir: string): string[] | null {\n\tconst packageJsonPath = path.join(dir, \"package.json\");\n\tif (fs.existsSync(packageJsonPath)) {\n\t\tconst resolvedManifest = readPackageManifest(packageJsonPath);\n\t\tif (resolvedManifest && (resolvedManifest.key !== null || resolvedManifest.diagnostics.length > 0)) {\n\t\t\tconst entries: string[] = [];\n\t\t\tfor (const extPath of resolvedManifest.manifest?.extensions ?? []) {\n\t\t\t\tconst candidate = path.resolve(dir, extPath);\n\t\t\t\tif (!fs.existsSync(candidate)) continue;\n\t\t\t\tif (fs.statSync(candidate).isDirectory()) {\n\t\t\t\t\tfor (const indexName of [\"index.ts\", \"index.js\", \"index.mjs\", \"index.cjs\"]) {\n\t\t\t\t\t\tconst indexPath = path.join(candidate, indexName);\n\t\t\t\t\t\tif (fs.existsSync(indexPath)) {\n\t\t\t\t\t\t\tentries.push(indexPath);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tentries.push(candidate);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn entries;\n\t\t}\n\t}\n\n\t// Check for index.ts or index.js\n\tconst indexTs = path.join(dir, \"index.ts\");\n\tconst indexJs = path.join(dir, \"index.js\");\n\tif (fs.existsSync(indexTs)) {\n\t\treturn [indexTs];\n\t}\n\tif (fs.existsSync(indexJs)) {\n\t\treturn [indexJs];\n\t}\n\n\treturn null;\n}\n\n/**\n * Discover extensions in a directory.\n *\n * Discovery rules:\n * 1. Direct files: `extensions/*.ts` or `*.js` → load\n * 2. Subdirectory with index: `extensions/* /index.ts` or `index.js` → load\n * 3. Subdirectory with package.json: `extensions/* /package.json` with OMK manifest → load what it declares\n *\n * No recursion beyond one level. Complex packages must use package.json manifest.\n */\nfunction discoverExtensionsInDir(dir: string): string[] {\n\tif (!fs.existsSync(dir)) {\n\t\treturn [];\n\t}\n\n\tconst discovered: string[] = [];\n\n\ttry {\n\t\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tconst entryPath = path.join(dir, entry.name);\n\n\t\t\t// 1. Direct files: *.ts or *.js\n\t\t\tif ((entry.isFile() || entry.isSymbolicLink()) && isExtensionFile(entry.name)) {\n\t\t\t\tdiscovered.push(entryPath);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// 2 & 3. Subdirectories\n\t\t\tif (entry.isDirectory() || entry.isSymbolicLink()) {\n\t\t\t\tconst entries = resolveExtensionEntries(entryPath);\n\t\t\t\tif (entries) {\n\t\t\t\t\tdiscovered.push(...entries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn [];\n\t}\n\n\treturn discovered;\n}\n\n/**\n * Discover and load extensions from standard locations.\n */\nexport async function discoverAndLoadExtensions(\n\tconfiguredPaths: string[],\n\tcwd: string,\n\tagentDir: string = getAgentDir(),\n\teventBus?: EventBus,\n): Promise<LoadExtensionsResult> {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir);\n\tconst allPaths: string[] = [];\n\tconst seen = new Set<string>();\n\n\tconst addPaths = (paths: string[]) => {\n\t\tfor (const p of paths) {\n\t\t\tconst resolved = path.resolve(p);\n\t\t\tif (!seen.has(resolved)) {\n\t\t\t\tseen.add(resolved);\n\t\t\t\tallPaths.push(p);\n\t\t\t}\n\t\t}\n\t};\n\n\t// 1. Project-local extensions: cwd/${CONFIG_DIR_NAME}/extensions/\n\tconst localExtDir = path.join(resolvedCwd, CONFIG_DIR_NAME, \"extensions\");\n\taddPaths(discoverExtensionsInDir(localExtDir));\n\n\t// 2. Global extensions: agentDir/extensions/\n\tconst globalExtDir = path.join(resolvedAgentDir, \"extensions\");\n\taddPaths(discoverExtensionsInDir(globalExtDir));\n\n\t// 3. Explicitly configured paths\n\tfor (const p of configuredPaths) {\n\t\tconst resolved = resolvePath(p, resolvedCwd, { normalizeUnicodeSpaces: true });\n\t\tif (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {\n\t\t\t// Check for package.json with omk manifest or index.ts\n\t\t\tconst entries = resolveExtensionEntries(resolved);\n\t\t\tif (entries) {\n\t\t\t\taddPaths(entries);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// No explicit entries - discover individual files in directory\n\t\t\taddPaths(discoverExtensionsInDir(resolved));\n\t\t\tcontinue;\n\t\t}\n\n\t\taddPaths([resolved]);\n\t}\n\n\treturn loadExtensions(allPaths, resolvedCwd, eventBus);\n}\n"]}
@@ -7,54 +7,14 @@ import { createRequire } from "node:module";
7
7
  import * as path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { createJiti } from "jiti/static";
10
- import * as _bundledOmkAgentCore from "omk-agent-core";
11
- import * as _bundledOmkAgentCoreNode from "omk-agent-core/node";
12
- import * as _bundledOmkAi from "omk-ai";
13
- import * as _bundledOmkAiOauth from "omk-ai/oauth";
14
- import * as _bundledOmkTui from "omk-tui";
15
- // Static imports of packages that extensions may use.
16
- // These MUST be static so Bun bundles them into the compiled binary.
17
- // The virtualModules option then makes them available to extensions.
18
- import * as _bundledTypebox from "typebox";
19
- import * as _bundledTypeboxCompile from "typebox/compile";
20
- import * as _bundledTypeboxValue from "typebox/value";
21
10
  import { CONFIG_DIR_NAME, getAgentDir, isBunBinary } from "../../config.js";
22
- // NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,
23
- // avoiding a circular dependency. Extensions can import from open-multi-agent-kit.
24
- import * as _bundledOmkCodingAgent from "../../index.js";
25
11
  import { resolvePath } from "../../utils/paths.js";
26
12
  import { createEventBus } from "../event-bus.js";
27
13
  import { execCommand } from "../exec.js";
28
14
  import { readPackageManifest } from "../package-manifest.js";
29
15
  import { LEGACY_PI_RUNTIME_ALIASES } from "../pi-compat.js";
30
16
  import { createSyntheticSourceInfo } from "../source-info.js";
31
- const LEGACY_PI_VIRTUAL_TARGETS = {
32
- "coding-agent": _bundledOmkCodingAgent,
33
- "agent-core": _bundledOmkAgentCore,
34
- "agent-core-node": _bundledOmkAgentCoreNode,
35
- ai: _bundledOmkAi,
36
- "ai-oauth": _bundledOmkAiOauth,
37
- tui: _bundledOmkTui,
38
- };
39
- /** Modules available to extensions via virtualModules (for compiled Bun binary) */
40
- const VIRTUAL_MODULES = {
41
- ...Object.fromEntries(Object.entries(LEGACY_PI_RUNTIME_ALIASES).map(([specifier, target]) => [
42
- specifier,
43
- LEGACY_PI_VIRTUAL_TARGETS[target],
44
- ])),
45
- typebox: _bundledTypebox,
46
- "typebox/compile": _bundledTypeboxCompile,
47
- "typebox/value": _bundledTypeboxValue,
48
- "@sinclair/typebox": _bundledTypebox,
49
- "@sinclair/typebox/compile": _bundledTypeboxCompile,
50
- "@sinclair/typebox/value": _bundledTypeboxValue,
51
- "omk-agent-core": _bundledOmkAgentCore,
52
- "omk-agent-core/node": _bundledOmkAgentCoreNode,
53
- "omk-tui": _bundledOmkTui,
54
- "omk-ai": _bundledOmkAi,
55
- "omk-ai/oauth": _bundledOmkAiOauth,
56
- "open-multi-agent-kit": _bundledOmkCodingAgent,
57
- };
17
+ import { buildVirtualModules } from "./bundled-virtual-modules.js";
58
18
  const require = createRequire(import.meta.url);
59
19
  let _aliases = null;
60
20
  function findPackageJsonPath(specifier, startDir, resolvePackageJson = require.resolve, existsSync = fs.existsSync) {
@@ -339,7 +299,7 @@ async function loadExtensionModule(extensionPath, binaryMode = isBunBinary) {
339
299
  // In Bun binary: use virtualModules for bundled packages (no filesystem resolution)
340
300
  // Also disable tryNative so jiti handles ALL imports (not just the entry point)
341
301
  // In Node.js/dev: use aliases to resolve to node_modules paths
342
- ...(binaryMode ? { virtualModules: VIRTUAL_MODULES, tryNative: false } : { alias: getAliases() }),
302
+ ...(binaryMode ? { virtualModules: buildVirtualModules(), tryNative: false } : { alias: getAliases() }),
343
303
  });
344
304
  const module = await jiti.import(extensionPath, { default: true });
345
305
  const factory = module;