@iowarp/clio-coder 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/CONTRIBUTING.md +1 -1
  3. package/README.md +3 -3
  4. package/dist/{acp-P2AQILE2.js → acp-S5R4RR5B.js} +7 -6
  5. package/dist/{agents-72W3BI7I.js → agents-P6DMMVZY.js} +24 -21
  6. package/dist/assets/codewiki.json +1 -1
  7. package/dist/{auth-5TWEIYDN.js → auth-2XCZLPKS.js} +12 -8
  8. package/dist/{chunk-GGXXDWE4.js → chunk-22NAGB7X.js} +2 -2
  9. package/dist/{chunk-2DJ2KNFG.js → chunk-2LZI5CAG.js} +133 -13
  10. package/dist/{chunk-OAO4GE4M.js → chunk-2TZWSW76.js} +2 -2
  11. package/dist/{chunk-OOJYHWRB.js → chunk-34475P3I.js} +2 -2
  12. package/dist/{chunk-4XUGQOHA.js → chunk-35MKKU5R.js} +4 -4
  13. package/dist/{chunk-LM5TQCJZ.js → chunk-3HZ5RWN2.js} +5 -5
  14. package/dist/{chunk-AGYYIBLL.js → chunk-3JLKSKD7.js} +2 -2
  15. package/dist/{chunk-KZWTDYJF.js → chunk-4JUF2NNX.js} +7 -7
  16. package/dist/{chunk-ZDOOVTXZ.js → chunk-4OC57DA6.js} +27 -4
  17. package/dist/chunk-5M54SPOL.js +926 -0
  18. package/dist/{chunk-STBPMHSX.js → chunk-7RXG6QRZ.js} +51 -11
  19. package/dist/{chunk-X6IAEBZR.js → chunk-A2GZF7DC.js} +5 -5
  20. package/dist/{chunk-A3CYT5EX.js → chunk-AD2SYQYC.js} +55 -2
  21. package/dist/chunk-AOCYTWAV.js +449 -0
  22. package/dist/chunk-BEY543CS.js +258 -0
  23. package/dist/{chunk-6N5PTWMY.js → chunk-BP4OYD6A.js} +32 -13
  24. package/dist/chunk-BPGS2WCQ.js +612 -0
  25. package/dist/{chunk-V6RTAOC2.js → chunk-BRXQQJFP.js} +8 -8
  26. package/dist/chunk-CFGTUFWB.js +67 -0
  27. package/dist/{chunk-CBCAPZAA.js → chunk-E25LMLRW.js} +2 -2
  28. package/dist/{chunk-DUYJ5IO6.js → chunk-EDRHSCIE.js} +4 -4
  29. package/dist/{chunk-XBXAASKX.js → chunk-EFADSJET.js} +2 -2
  30. package/dist/{chunk-M6SHUN7Q.js → chunk-FO5ZOVUY.js} +2 -2
  31. package/dist/chunk-FYYLNIL5.js +313 -0
  32. package/dist/{chunk-FNTMWMX5.js → chunk-HV5X7OR2.js} +14 -12
  33. package/dist/{chunk-TZTZS7QK.js → chunk-HXG4IURW.js} +5 -3
  34. package/dist/{chunk-5UFT4SUX.js → chunk-K6WL7QZT.js} +3 -3
  35. package/dist/chunk-K7VKOLQQ.js +15 -0
  36. package/dist/{chunk-BMEMKKIT.js → chunk-KOHPCX4K.js} +2 -2
  37. package/dist/{chunk-OC7FIQPC.js → chunk-KRPY7NTG.js} +10 -7
  38. package/dist/chunk-LL4KHSZI.js +22 -0
  39. package/dist/{chunk-DSELYM6W.js → chunk-MEQ45TQ4.js} +15 -9
  40. package/dist/{chunk-5UUP6MWO.js → chunk-MV3K5QF2.js} +5 -436
  41. package/dist/{chunk-6SGHMWE3.js → chunk-N4CZJQRK.js} +5 -5
  42. package/dist/{chunk-TZK7PACC.js → chunk-NILBFAPG.js} +14 -8
  43. package/dist/chunk-OZNBF4L3.js +23 -0
  44. package/dist/{verify-375KUB3Y.js → chunk-PCZJO5TI.js} +127 -42
  45. package/dist/chunk-QQK64KLB.js +1360 -0
  46. package/dist/{chunk-SRDMMSEP.js → chunk-QQL5RT5M.js} +979 -1619
  47. package/dist/{chunk-LZSJBIVT.js → chunk-QWU7ZBO7.js} +70 -720
  48. package/dist/{chunk-2TLUCQVG.js → chunk-RD5U66HV.js} +3 -3
  49. package/dist/{chunk-OKGUZO2U.js → chunk-SPULKLCF.js} +4 -3
  50. package/dist/{chunk-OQ33BKR3.js → chunk-TTNYS3EA.js} +3 -60
  51. package/dist/chunk-TW3WDMVS.js +677 -0
  52. package/dist/chunk-TZSKNMZG.js +434 -0
  53. package/dist/{chunk-7MNJORFF.js → chunk-UL3WSD3F.js} +6 -1
  54. package/dist/{chunk-PIWWS5BL.js → chunk-UZHIZC5S.js} +7 -7
  55. package/dist/{chunk-UFIIWP2H.js → chunk-VAWWTKDP.js} +8 -8
  56. package/dist/{chunk-COU2UHX6.js → chunk-VEZEGCGW.js} +170 -2
  57. package/dist/{chunk-LW6DSM3M.js → chunk-VMNQ6OZA.js} +98 -202
  58. package/dist/chunk-VSNATDE6.js +122 -0
  59. package/dist/chunk-W6GROXXM.js +69 -0
  60. package/dist/chunk-WPQLXFOZ.js +375 -0
  61. package/dist/{chunk-ORBHGJC5.js → chunk-WR67VIZY.js} +3 -3
  62. package/dist/{chunk-PAJK6MAQ.js → chunk-X6COSD2O.js} +5 -5
  63. package/dist/chunk-ZGVHUX3M.js +66 -0
  64. package/dist/{chunk-LWLEKMDQ.js → chunk-ZYKPLLNQ.js} +510 -547
  65. package/dist/cli/index.js +27 -23
  66. package/dist/{clio-JOU4FXVA.js → clio-J5JIOIDS.js} +7 -6
  67. package/dist/{code-nav-7AX6FYE6.js → code-nav-AXCXSBHX.js} +5 -3
  68. package/dist/{config-XCDVKR23.js → config-OEBMIN2U.js} +37 -27
  69. package/dist/{configure-4GAP54ZW.js → configure-PUQOSIXQ.js} +16 -13
  70. package/dist/{context-5VKGUVJJ.js → context-EKDCKUUZ.js} +82 -7
  71. package/dist/{context-4UOGGLQ5.js → context-MGSE4Z2T.js} +33 -23
  72. package/dist/{context-77FM5DV5.js → context-URSXPBCK.js} +17 -9
  73. package/dist/{context-clear-XXJRLCJJ.js → context-clear-KDAJRNUK.js} +33 -23
  74. package/dist/context-working-set-SBKMPPI2.js +1552 -0
  75. package/dist/{dispatch-runner-QPRDDBDX.js → dispatch-runner-MSWN72NK.js} +43 -29
  76. package/dist/{doctor-HR46URBJ.js → doctor-7BSE27PJ.js} +10 -10
  77. package/dist/{eval-XSSNATB4.js → eval-IZGDOO4H.js} +9 -8
  78. package/dist/{evidence-6HG2PY2B.js → evidence-SR7WXB5B.js} +51 -23
  79. package/dist/{evolve-K7YU3NCY.js → evolve-K7VE2CBX.js} +30 -20
  80. package/dist/{fleet-VY3HHKN6.js → fleet-7XMJNQNF.js} +48 -38
  81. package/dist/{fleet-preflight-DDN536IT.js → fleet-preflight-AQNAH644.js} +3 -3
  82. package/dist/{init-JYGXI3FK.js → init-JGNPAYXT.js} +41 -31
  83. package/dist/{memory-WFZMGYHX.js → memory-4ALKDJ4Q.js} +32 -22
  84. package/dist/{models-I5QWSEOM.js → models-ZMMLFJNN.js} +22 -19
  85. package/dist/{monitor-GE4ID3IA.js → monitor-2F3T5KHP.js} +55 -43
  86. package/dist/{orchestrator-EM5MC3HM.js → orchestrator-ORHT43JB.js} +572 -388
  87. package/dist/{reset-L2FQEE3E.js → reset-NXGTYNUO.js} +4 -3
  88. package/dist/{run-ZU3QMZPZ.js → run-RF4WJGMT.js} +51 -41
  89. package/dist/{share-S5BZQC5I.js → share-UT3W6E4M.js} +5 -4
  90. package/dist/{skills-X5VXCRNQ.js → skills-PSACKC5Q.js} +2 -2
  91. package/dist/{skills-eval-WKIHWTHR.js → skills-eval-WJSI55RZ.js} +34 -24
  92. package/dist/{targets-SNCPI2NR.js → targets-PIIRAOYS.js} +23 -20
  93. package/dist/{terminal-lease-BNAHVHBS.js → terminal-lease-ULWXWNVY.js} +4 -3
  94. package/dist/{upgrade-JQHHPQ4K.js → upgrade-346TZ6AV.js} +18 -17
  95. package/dist/{usage-OR4O5SMZ.js → usage-6KKXR32N.js} +34 -24
  96. package/dist/verifiers-4UUM6TEE.js +1214 -0
  97. package/dist/verify-X5HDROLA.js +25 -0
  98. package/dist/{wiki-generate-UEXP2ARI.js → wiki-generate-7STOCIFZ.js} +42 -31
  99. package/dist/worker/entry.js +33 -24
  100. package/docs/README.md +7 -6
  101. package/docs/acp.md +1 -1
  102. package/docs/alcf-provider.md +1 -1
  103. package/docs/architecture.md +2 -2
  104. package/docs/artifact-versions.md +1 -1
  105. package/docs/built-in-agents.md +1 -1
  106. package/docs/capacity-and-scheduling.md +1 -1
  107. package/docs/commands-and-modes.md +53 -21
  108. package/docs/config-knobs-audit.md +1 -2
  109. package/docs/configuration-and-targets.md +15 -1
  110. package/docs/context-engine.md +64 -12
  111. package/docs/context-working-set.md +194 -0
  112. package/docs/development-pipeline.md +1 -1
  113. package/docs/documentation-coverage.md +5 -5
  114. package/docs/documentation-guide.md +6 -5
  115. package/docs/environment-variables.md +2 -1
  116. package/docs/eval-runner.md +1 -1
  117. package/docs/evals-internal.md +14 -1
  118. package/docs/evidence-and-memory.md +74 -2
  119. package/docs/evolution.md +1 -1
  120. package/docs/exit-codes-and-output.md +1 -1
  121. package/docs/extensions-and-sharing.md +2 -2
  122. package/docs/fleet-dispatch.md +22 -7
  123. package/docs/glossary.md +21 -1
  124. package/docs/installation-and-lifecycle.md +2 -2
  125. package/docs/middleware-and-components.md +1 -1
  126. package/docs/model-catalog.md +7 -9
  127. package/docs/observability.md +4 -4
  128. package/docs/proactive-memory.md +1 -1
  129. package/docs/prompt-envelope-and-tools.md +4 -4
  130. package/docs/provider-adapter-cookbook.md +1 -1
  131. package/docs/release-cut-checklist.md +31 -31
  132. package/docs/safety-model.md +23 -4
  133. package/docs/scientific-validation.md +21 -3
  134. package/docs/session-lifecycle.md +3 -3
  135. package/docs/skills-marketplace.md +1 -1
  136. package/docs/tool-usage.md +79 -12
  137. package/docs/trace-store.md +1 -1
  138. package/docs/troubleshooting.md +1 -1
  139. package/docs/tui-design.md +1 -1
  140. package/docs/worker-dispatch-mechanics.md +11 -1
  141. package/package.json +8 -11
  142. package/skills/meta/clio-test/SKILL.md +20 -17
  143. package/skills/meta/clio-test/evals.md +3 -3
  144. package/skills/meta/clio-test/references/harness.md +35 -6
  145. package/skills/meta/clio-test/references/test-map.md +20 -10
  146. package/skills/registry.yaml +2 -2
  147. package/skills/skill-marketplace.json +1 -1
  148. package/src/cli/context-working-set.ts +513 -0
  149. package/src/cli/context.ts +8 -0
  150. package/src/cli/evidence.ts +20 -2
  151. package/src/cli/index.ts +4 -0
  152. package/src/cli/verifiers.ts +325 -0
  153. package/src/core/bash-exec.ts +39 -14
  154. package/src/core/bus-events.ts +19 -4
  155. package/src/core/config.ts +54 -0
  156. package/src/core/defaults.ts +50 -3
  157. package/src/core/verification-scripts.ts +6 -0
  158. package/src/domains/agents/builtins/verifier.md +3 -0
  159. package/src/domains/config/classify.ts +1 -0
  160. package/src/domains/context/working-set/contract.ts +161 -0
  161. package/src/domains/context/working-set/defaults.ts +28 -0
  162. package/src/domains/context/working-set/engine.ts +203 -0
  163. package/src/domains/context/working-set/fold.ts +62 -0
  164. package/src/domains/context/working-set/horizon.ts +38 -0
  165. package/src/domains/context/working-set/marker.ts +103 -0
  166. package/src/domains/context/working-set/path-index.ts +436 -0
  167. package/src/domains/context/working-set/payload.ts +152 -0
  168. package/src/domains/context/working-set/policies/age-horizon.ts +55 -0
  169. package/src/domains/context/working-set/policies/index.ts +21 -0
  170. package/src/domains/context/working-set/policies/structural.ts +160 -0
  171. package/src/domains/context/working-set/project.ts +132 -0
  172. package/src/domains/context/working-set/protect.ts +109 -0
  173. package/src/domains/context/working-set/recall.ts +177 -0
  174. package/src/domains/context/working-set/replay/controls.ts +112 -0
  175. package/src/domains/context/working-set/replay/load-clio.ts +199 -0
  176. package/src/domains/context/working-set/replay/metrics.ts +185 -0
  177. package/src/domains/context/working-set/replay/reference-graph.ts +79 -0
  178. package/src/domains/context/working-set/replay/report.ts +139 -0
  179. package/src/domains/context/working-set/replay/runner.ts +325 -0
  180. package/src/domains/context/working-set/replay/synthetic.ts +422 -0
  181. package/src/domains/context/working-set/replay/trace.ts +21 -0
  182. package/src/domains/context/working-set/visible.ts +54 -0
  183. package/src/domains/evidence/build.ts +112 -45
  184. package/src/domains/evidence/eval.ts +24 -7
  185. package/src/domains/evidence/index.ts +53 -0
  186. package/src/domains/evidence/ordering.ts +12 -0
  187. package/src/domains/evidence/run-trust.ts +221 -0
  188. package/src/domains/evidence/store.ts +46 -6
  189. package/src/domains/evidence/trust-status.ts +854 -0
  190. package/src/domains/evidence/types.ts +26 -0
  191. package/src/domains/middleware/memory-intervention.ts +3 -0
  192. package/src/domains/middleware/stalled-turn.ts +165 -4
  193. package/src/domains/safety/autonomy.ts +1 -1
  194. package/src/domains/safety/default-path-policy.ts +8 -0
  195. package/src/domains/safety/finish-contract.ts +4 -3
  196. package/src/domains/safety/policy-engine.ts +48 -6
  197. package/src/domains/session/compaction/compact.ts +23 -1
  198. package/src/domains/session/compaction/cut-point.ts +2 -0
  199. package/src/domains/session/compaction/tokens.ts +16 -1
  200. package/src/domains/session/context-ledger.ts +2 -0
  201. package/src/domains/session/entries.ts +107 -1
  202. package/src/domains/session/manager.ts +9 -2
  203. package/src/domains/session/migrations/index.ts +22 -3
  204. package/src/engine/acp/server.ts +3 -0
  205. package/src/engine/agent.ts +18 -1
  206. package/src/engine/session.ts +9 -3
  207. package/src/entry/orchestrator.ts +16 -4
  208. package/src/interactive/chat-loop-messages.ts +18 -6
  209. package/src/interactive/chat-panel.ts +17 -1
  210. package/src/interactive/chat-renderer.ts +30 -21
  211. package/src/interactive/context-meter.ts +10 -0
  212. package/src/interactive/context-overlay.ts +81 -6
  213. package/src/interactive/context-recall-command.ts +110 -0
  214. package/src/interactive/interactive-slash-runtime.ts +37 -1
  215. package/src/interactive/model-session-replay.ts +21 -0
  216. package/src/interactive/overlay-general-openers.ts +6 -0
  217. package/src/interactive/overlay-session-lifecycle.ts +8 -4
  218. package/src/interactive/renderers/tool-execution.ts +18 -2
  219. package/src/interactive/session-transcript.ts +2 -2
  220. package/src/interactive/slash-commands.ts +29 -2
  221. package/src/interactive/turn-context.ts +238 -88
  222. package/src/interactive/turn-middleware.ts +6 -6
  223. package/src/tools/agent-tools.ts +11 -4
  224. package/src/tools/bash.ts +144 -82
  225. package/src/tools/builtin-tool-catalog.ts +11 -5
  226. package/src/tools/context/index.ts +105 -3
  227. package/src/tools/context/surface.ts +3 -2
  228. package/src/tools/core-bootstrap.ts +21 -0
  229. package/src/tools/dispatch-runner.ts +9 -7
  230. package/src/tools/monitor.ts +28 -20
  231. package/src/tools/registry.ts +59 -7
  232. package/src/tools/result-disposition.ts +550 -0
  233. package/src/tools/result-shaping.ts +262 -19
  234. package/src/tools/safe-exec.ts +2 -0
  235. package/src/tools/verify/authoring.ts +1119 -0
  236. package/src/tools/verify/catalog.ts +346 -0
  237. package/src/tools/verify/index.ts +13 -3
  238. package/src/tools/verify/scripts.ts +135 -37
  239. package/src/tools/verify/surface.ts +9 -5
  240. package/src/tools/worker-evidence.ts +35 -12
  241. package/dist/chunk-J7CWMCQD.js +0 -255
  242. package/dist/chunk-T6YILFSB.js +0 -80
  243. package/dist/chunk-VAKQQHWR.js +0 -434
  244. package/dist/chunk-VPAYEGVX.js +0 -184
@@ -1,10 +1,14 @@
1
1
  import { createRequire as __clioCreateRequire } from "node:module"; const require = __clioCreateRequire(import.meta.url);
2
+ import {
3
+ createSentinelStripper,
4
+ stripTokenizerSentinels
5
+ } from "./chunk-CFGTUFWB.js";
2
6
  import {
3
7
  readSettings
4
- } from "./chunk-A3CYT5EX.js";
8
+ } from "./chunk-AD2SYQYC.js";
5
9
  import {
6
10
  THINKING_LEVELS
7
- } from "./chunk-ZDOOVTXZ.js";
11
+ } from "./chunk-4OC57DA6.js";
8
12
  import {
9
13
  authNotRequiredStatus,
10
14
  openAuthStorage,
@@ -13,10 +17,6 @@ import {
13
17
  resolveRuntimeAuthTarget,
14
18
  targetRequiresAuth
15
19
  } from "./chunk-4VP4KH3K.js";
16
- import {
17
- cwdHash,
18
- sessionPaths
19
- } from "./chunk-M6SHUN7Q.js";
20
20
  import {
21
21
  sleep
22
22
  } from "./chunk-FQ4SKYE4.js";
@@ -24,8 +24,10 @@ import {
24
24
  withStateFileLock
25
25
  } from "./chunk-IKCO5N3L.js";
26
26
  import {
27
- require_dist
28
- } from "./chunk-APJ265NV.js";
27
+ ceilChars,
28
+ estimateAgentMessageTokens,
29
+ toolSchemaChars
30
+ } from "./chunk-BPGS2WCQ.js";
29
31
  import {
30
32
  activateExternalPluginApiBridge,
31
33
  calculateEngineCost,
@@ -34,15 +36,20 @@ import {
34
36
  getEngineSupportedThinkingLevels,
35
37
  registerEngineApiProvider
36
38
  } from "./chunk-FCSXB6T2.js";
39
+ import {
40
+ require_dist
41
+ } from "./chunk-APJ265NV.js";
37
42
  import {
38
43
  clioConfigDir,
39
44
  clioStatePath,
40
45
  resolveClioDirs
41
46
  } from "./chunk-BNAZZHFG.js";
42
47
  import {
43
- BusChannels,
44
48
  getSharedBus
45
- } from "./chunk-OQ33BKR3.js";
49
+ } from "./chunk-ZGVHUX3M.js";
50
+ import {
51
+ BusChannels
52
+ } from "./chunk-TTNYS3EA.js";
46
53
  import {
47
54
  __toESM,
48
55
  init_esm_shims
@@ -363,597 +370,15 @@ function credentialsPresent() {
363
370
  return present;
364
371
  }
365
372
 
366
- // src/domains/session/context-accounting.ts
367
- init_esm_shims();
368
- import { appendFileSync, existsSync, readFileSync } from "node:fs";
369
- import { dirname, join as join2 } from "node:path";
370
-
371
- // src/domains/session/compaction/auto.ts
372
- init_esm_shims();
373
- var DEFAULT_COMPACTION_THRESHOLD = 0.8;
374
- function shouldCompact(contextTokens, threshold, contextWindow) {
375
- const base = {
376
- shouldCompact: false,
377
- pressure: null,
378
- contextTokens,
379
- contextWindow,
380
- threshold
381
- };
382
- if (!Number.isFinite(threshold) || threshold <= 0 || threshold > 1) return base;
383
- if (!Number.isFinite(contextTokens) || contextTokens <= 0) return base;
384
- if (!Number.isFinite(contextWindow) || contextWindow <= 0) return base;
385
- const pressure = contextTokens / contextWindow;
386
- return {
387
- shouldCompact: pressure >= threshold,
388
- pressure,
389
- contextTokens,
390
- contextWindow,
391
- threshold
392
- };
393
- }
394
- var AutoCompactionTrigger = class {
395
- inFlight = null;
396
- /** True while a task is in flight. Callers can short-circuit on this. */
397
- isBusy() {
398
- return this.inFlight !== null;
399
- }
400
- /**
401
- * Run `task` unless one is already in flight. Returns the Promise the
402
- * task is running under. Callers always get the eventual result of the
403
- * first task, never a second call. Rejections clear the slot so a later
404
- * fire can start fresh.
405
- */
406
- fire(task) {
407
- if (this.inFlight) return this.inFlight;
408
- const run = task().finally(() => {
409
- this.inFlight = null;
410
- });
411
- this.inFlight = run;
412
- return run;
413
- }
414
- };
415
-
416
- // src/domains/session/context-ledger.ts
417
- init_esm_shims();
418
- var SEGMENT_CATEGORY = {
419
- identity: "system",
420
- "operating-contract": "system",
421
- delegation: "agents",
422
- skills: "skills",
423
- safety: "system",
424
- runtime: "system",
425
- "tool-contract": "system",
426
- "retrieval-hints": "system",
427
- "tool-catalog": "tools",
428
- "tools-and-agents": "agents",
429
- "agent-fleet-deltas": "agents",
430
- "skills-catalog": "skills",
431
- memory: "memory",
432
- "project-context": "project",
433
- "context.project-rules": "project",
434
- "context.operator-profile": "memory",
435
- "context.clio-repo-awareness": "system",
436
- "history-summary": "messages"
437
- };
438
- var CONTEXT_CATEGORY_LABEL = {
439
- system: "System prompt",
440
- tools: "Tool definitions",
441
- agents: "Agent fleet",
442
- skills: "Skills",
443
- memory: "Memory",
444
- project: "Project context",
445
- messages: "Messages",
446
- pending: "Pending input",
447
- reserve: "Autocompact reserve",
448
- free: "Free space",
449
- streaming: "Streaming output"
450
- };
451
- var CONTENT_ORDER = [
452
- "system",
453
- "tools",
454
- "agents",
455
- "skills",
456
- "memory",
457
- "project",
458
- "messages",
459
- "pending",
460
- "streaming"
461
- ];
462
- function categoryForSegment(id) {
463
- return SEGMENT_CATEGORY[id] ?? "system";
464
- }
465
- function finiteNonNegative(value) {
466
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
467
- }
468
- function percentOf(tokens, window) {
469
- if (window <= 0) return null;
470
- return Math.min(100, tokens / window * 100);
471
- }
472
- function buildContextLedger(input) {
473
- const window = finiteNonNegative(input.contextWindow);
474
- const raw = {
475
- system: 0,
476
- tools: 0,
477
- agents: 0,
478
- skills: 0,
479
- memory: 0,
480
- project: 0,
481
- messages: 0,
482
- pending: 0,
483
- reserve: 0,
484
- free: 0,
485
- streaming: 0
486
- };
487
- const segments = input.promptSegments ?? [];
488
- if (segments.length > 0) {
489
- for (const segment of segments) {
490
- raw[categoryForSegment(segment.id)] += finiteNonNegative(segment.tokenEstimate);
491
- }
492
- } else {
493
- raw.system += finiteNonNegative(input.systemPromptTokens);
494
- }
495
- raw.tools += finiteNonNegative(input.toolSchemaTokens);
496
- raw.messages += finiteNonNegative(input.messageTokens);
497
- raw.pending += finiteNonNegative(input.pendingTokens);
498
- raw.streaming += finiteNonNegative(input.streamingTokens);
499
- raw.agents += finiteNonNegative(input.agentsTokens);
500
- raw.skills += finiteNonNegative(input.skillsTokens);
501
- raw.memory += finiteNonNegative(input.memoryTokens);
502
- raw.project += finiteNonNegative(input.projectTokens);
503
- const decomposed = CONTENT_ORDER.reduce((sum, category) => sum + raw[category], 0);
504
- const liveTotal = finiteNonNegative(input.liveTotalTokens);
505
- if (liveTotal > decomposed) {
506
- raw.messages += liveTotal - decomposed;
507
- }
508
- const usedTokens = Math.max(decomposed, liveTotal);
509
- const effectiveThreshold = typeof input.compactionThreshold === "number" && input.compactionThreshold > 0 && input.compactionThreshold < 1 ? input.compactionThreshold : input.compactionAuto ? DEFAULT_COMPACTION_THRESHOLD : null;
510
- let reserveTokens = 0;
511
- let freeTokens = 0;
512
- if (window > 0) {
513
- const remaining = Math.max(0, window - usedTokens);
514
- reserveTokens = effectiveThreshold !== null ? Math.min(Math.round(window * (1 - effectiveThreshold)), remaining) : 0;
515
- freeTokens = Math.max(0, window - usedTokens - reserveTokens);
516
- }
517
- const groups = [];
518
- for (const category of CONTENT_ORDER) {
519
- const tokens = raw[category];
520
- if (tokens <= 0) continue;
521
- groups.push({
522
- category,
523
- label: CONTEXT_CATEGORY_LABEL[category],
524
- tokens,
525
- percent: percentOf(tokens, window)
526
- });
527
- }
528
- const meter = [...groups];
529
- if (reserveTokens > 0) {
530
- meter.push({
531
- category: "reserve",
532
- label: CONTEXT_CATEGORY_LABEL.reserve,
533
- tokens: reserveTokens,
534
- percent: percentOf(reserveTokens, window)
535
- });
536
- }
537
- if (window > 0) {
538
- meter.push({
539
- category: "free",
540
- label: CONTEXT_CATEGORY_LABEL.free,
541
- tokens: freeTokens,
542
- percent: percentOf(freeTokens, window)
543
- });
544
- }
545
- return {
546
- provider: input.provider ?? null,
547
- model: input.model ?? null,
548
- contextWindow: window,
549
- contextWindowSource: input.contextWindowSource ?? null,
550
- usedTokens,
551
- reserveTokens,
552
- freeTokens,
553
- percent: percentOf(usedTokens, window),
554
- measured: input.measured === true && liveTotal > 0,
555
- compactionThreshold: effectiveThreshold,
556
- compactionAuto: input.compactionAuto === true,
557
- projectPreload: input.projectPreload ?? null,
558
- projectHandbookFiles: input.projectHandbookFiles ?? null,
559
- toolCount: Math.max(0, Math.floor(input.toolCount ?? 0)),
560
- groups,
561
- meter,
562
- lastCompaction: input.lastCompaction ?? null,
563
- promptCache: input.promptCache ?? null
564
- };
565
- }
566
-
567
- // src/domains/session/context-accounting.ts
568
- var IMAGE_CHAR_ESTIMATE = 4800;
569
- var TOKEN_CHARS = 4;
570
- var MESSAGE_OVERHEAD_TOKENS = 16;
571
- function ceilChars(chars) {
572
- return Math.ceil(Math.max(0, chars) / TOKEN_CHARS);
573
- }
574
- function isRecord(value) {
575
- return !!value && typeof value === "object" && !Array.isArray(value);
576
- }
577
- function jsonLength(value) {
578
- if (value === void 0 || value === null) return 0;
579
- if (typeof value === "string") return value.length;
580
- if (typeof value === "number" || typeof value === "boolean") return String(value).length;
581
- try {
582
- return JSON.stringify(value).length;
583
- } catch {
584
- return String(value).length;
585
- }
586
- }
587
- function argsLength(value) {
588
- if (value === void 0 || value === null) return 0;
589
- return typeof value === "string" ? value.length : jsonLength(value);
590
- }
591
- function blockChars(block) {
592
- if (typeof block === "string") return block.length;
593
- if (!isRecord(block)) return jsonLength(block);
594
- if (block.type === "text" && typeof block.text === "string") return block.text.length;
595
- if (block.type === "thinking" && typeof block.thinking === "string") return block.thinking.length;
596
- if (block.type === "image") return IMAGE_CHAR_ESTIMATE;
597
- if (block.type === "toolCall") {
598
- const name = typeof block.name === "string" ? block.name : "";
599
- const id = typeof block.id === "string" ? block.id : "";
600
- return id.length + name.length + argsLength(block.arguments ?? block.args ?? block.input);
601
- }
602
- if (Array.isArray(block.content)) return contentChars(block.content);
603
- if (typeof block.text === "string") return block.text.length;
604
- if (typeof block.thinking === "string") return block.thinking.length;
605
- return jsonLength(block);
606
- }
607
- function contentChars(content) {
608
- if (typeof content === "string") return content.length;
609
- if (!Array.isArray(content)) return jsonLength(content);
610
- return content.reduce((sum, block) => sum + blockChars(block), 0);
611
- }
612
- function messageChars(message) {
613
- if (!isRecord(message)) return jsonLength(message);
614
- let chars = 0;
615
- chars += typeof message.role === "string" ? message.role.length : 0;
616
- const payload = message.payload !== void 0 ? message.payload : message.content;
617
- chars += contentChars(payload);
618
- chars += typeof message.toolCallId === "string" ? message.toolCallId.length : 0;
619
- chars += typeof message.toolName === "string" ? message.toolName.length : 0;
620
- chars += typeof message.errorMessage === "string" ? message.errorMessage.length : 0;
621
- return chars;
622
- }
623
- function toolSchemaChars(tool) {
624
- if (!isRecord(tool)) return jsonLength(tool);
625
- const name = typeof tool.name === "string" ? tool.name.length : 0;
626
- const description = typeof tool.description === "string" ? tool.description.length : 0;
627
- const parameters = jsonLength(tool.parameters);
628
- return name + description + parameters;
629
- }
630
- function usageTotalTokens(usage) {
631
- if (!isRecord(usage)) return null;
632
- const total = usage.totalTokens;
633
- if (typeof total === "number" && Number.isFinite(total) && total > 0) return total;
634
- const input = typeof usage.input === "number" && Number.isFinite(usage.input) ? usage.input : 0;
635
- const output = typeof usage.output === "number" && Number.isFinite(usage.output) ? usage.output : 0;
636
- const cacheRead = typeof usage.cacheRead === "number" && Number.isFinite(usage.cacheRead) ? usage.cacheRead : 0;
637
- const cacheWrite = typeof usage.cacheWrite === "number" && Number.isFinite(usage.cacheWrite) ? usage.cacheWrite : 0;
638
- const sum = input + output + cacheRead + cacheWrite;
639
- return sum > 0 ? sum : null;
640
- }
641
- function usageInvalidated(message) {
642
- return message.contextUsageInvalidated === true;
643
- }
644
- function latestUsableAssistantUsage(messages) {
645
- for (let i = messages.length - 1; i >= 0; i -= 1) {
646
- const message = messages[i];
647
- if (message?.role !== "assistant") continue;
648
- if (usageInvalidated(message)) continue;
649
- const stopReason = message.stopReason;
650
- if (stopReason === "error" || stopReason === "aborted") continue;
651
- const tokens = usageTotalTokens(message.usage);
652
- if (tokens !== null) return { index: i, tokens };
653
- }
654
- return null;
655
- }
656
- function finiteNonNegative2(value) {
657
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
658
- }
659
- function nestedNumber(root, path) {
660
- let current = root;
661
- for (const key of path) {
662
- if (!isRecord(current)) return null;
663
- current = current[key];
664
- }
665
- return finiteNonNegative2(current);
666
- }
667
- function estimateReasoningTextTokens(text) {
668
- if (typeof text !== "string" || text.trim().length === 0) return null;
669
- return Math.max(1, Math.round(text.length / TOKEN_CHARS));
670
- }
671
- function extractReasoningTokens(usage) {
672
- if (!isRecord(usage)) return null;
673
- const direct = finiteNonNegative2(usage.reasoningTokens) ?? finiteNonNegative2(usage.reasoning_tokens) ?? finiteNonNegative2(usage.reasoning);
674
- if (direct !== null) return direct;
675
- const paths = [
676
- ["outputDetails", "reasoningTokens"],
677
- ["output_details", "reasoning_tokens"],
678
- ["output_tokens_details", "reasoning_tokens"],
679
- ["completion_tokens_details", "reasoning_tokens"],
680
- ["completionTokensDetails", "reasoningTokens"],
681
- ["details", "reasoningTokens"]
682
- ];
683
- for (const path of paths) {
684
- const value = nestedNumber(usage, path);
685
- if (value !== null) return value;
686
- }
687
- return null;
688
- }
689
- function estimateAgentMessageTokens(message) {
690
- return ceilChars(messageChars(message)) + MESSAGE_OVERHEAD_TOKENS;
691
- }
692
- function estimateAgentContextBreakdown(input) {
693
- return {
694
- systemPromptTokens: input.systemPrompt ? ceilChars(input.systemPrompt.length) : 0,
695
- messageTokens: input.messages.reduce((sum, message) => sum + estimateAgentMessageTokens(message), 0),
696
- pendingUserTokens: input.pendingUserText ? ceilChars(input.pendingUserText.length) : 0,
697
- toolSchemaTokens: (input.tools ?? []).reduce((sum, tool) => sum + ceilChars(toolSchemaChars(tool)), 0)
698
- };
699
- }
700
- function estimateAgentContextTokens(input) {
701
- const breakdown = estimateAgentContextBreakdown(input);
702
- const projection = breakdown.systemPromptTokens + breakdown.messageTokens + breakdown.pendingUserTokens + breakdown.toolSchemaTokens;
703
- const usage = latestUsableAssistantUsage(input.messages);
704
- if (!usage) return projection;
705
- const trailingTokens = input.messages.slice(usage.index + 1).reduce((sum, message) => sum + estimateAgentMessageTokens(message), 0);
706
- const anchored = usage.tokens + trailingTokens + breakdown.pendingUserTokens + breakdown.toolSchemaTokens;
707
- return Math.max(projection, anchored);
708
- }
709
- function contextUsageSnapshot(tokens, contextWindow, breakdown) {
710
- const window = typeof contextWindow === "number" && Number.isFinite(contextWindow) ? Math.max(0, contextWindow) : 0;
711
- const base = tokens === null || tokens <= 0 || window <= 0 ? { tokens, contextWindow: window, percent: null } : { tokens, contextWindow: window, percent: Math.min(100, tokens / window * 100) };
712
- return breakdown ? { ...base, breakdown } : base;
713
- }
714
- function getSnapshotsFilePath(meta) {
715
- const safeMeta = {
716
- ...meta,
717
- cwdHash: meta.cwdHash || cwdHash(meta.cwd || process.cwd())
718
- };
719
- const paths = sessionPaths(safeMeta);
720
- return join2(dirname(paths.current), "context-snapshots.jsonl");
721
- }
722
- function persistableSnapshot(snapshot) {
723
- const {
724
- systemPrompt: _systemPrompt,
725
- conversationMessages: _messages,
726
- activeToolSchemas: _tools,
727
- pendingUserInput: _pending,
728
- images: _images,
729
- ...slim
730
- } = snapshot;
731
- return slim;
732
- }
733
- function appendContextSnapshot(meta, snapshot) {
734
- try {
735
- const file = getSnapshotsFilePath(meta);
736
- appendFileSync(file, `${JSON.stringify(persistableSnapshot(snapshot))}
737
- `, "utf8");
738
- } catch {
739
- }
740
- }
741
- function getContextSnapshots(meta) {
742
- try {
743
- const file = getSnapshotsFilePath(meta);
744
- if (!existsSync(file)) return [];
745
- const content = readFileSync(file, "utf8");
746
- const snapshots = [];
747
- for (const line of content.split("\n")) {
748
- if (line.trim().length === 0) continue;
749
- try {
750
- snapshots.push(JSON.parse(line));
751
- } catch {
752
- }
753
- }
754
- return snapshots;
755
- } catch {
756
- return [];
757
- }
758
- }
759
- function getLatestContextSnapshot(meta) {
760
- const list = getContextSnapshots(meta);
761
- return list.at(-1) ?? null;
762
- }
763
- function buildSnapshotCategories(inputs) {
764
- const raw = {
765
- system: 0,
766
- tools: 0,
767
- agents: 0,
768
- skills: 0,
769
- memory: 0,
770
- project: 0,
771
- messages: 0
772
- };
773
- if (inputs.promptSegments && inputs.promptSegments.length > 0) {
774
- for (const segment of inputs.promptSegments) {
775
- const cat = categoryForSegment(segment.id);
776
- raw[cat] = (raw[cat] ?? 0) + segment.tokenEstimate;
777
- }
778
- } else if (inputs.systemPrompt) {
779
- raw.system += ceilChars(inputs.systemPrompt.length);
780
- }
781
- if (inputs.tools) {
782
- for (const tool of inputs.tools) {
783
- raw.tools += ceilChars(toolSchemaChars(tool));
784
- }
785
- }
786
- if (inputs.messages) {
787
- for (const msg of inputs.messages) {
788
- raw.messages += estimateAgentMessageTokens(msg);
789
- }
790
- }
791
- const decomposed = Object.keys(raw).reduce((sum, k) => sum + (raw[k] ?? 0), 0);
792
- const window = inputs.effectiveContextWindow;
793
- const threshold = inputs.compactionThreshold ?? DEFAULT_COMPACTION_THRESHOLD;
794
- let reserve = 0;
795
- let free = 0;
796
- if (window > 0) {
797
- const remaining = Math.max(0, window - decomposed);
798
- reserve = Math.min(Math.round(window * (1 - threshold)), remaining);
799
- free = Math.max(0, window - decomposed - reserve);
800
- }
801
- return {
802
- system: raw.system,
803
- tools: raw.tools,
804
- agents: raw.agents,
805
- skills: raw.skills,
806
- memory: raw.memory,
807
- project: raw.project,
808
- messages: raw.messages,
809
- reserve,
810
- free,
811
- streaming: 0
812
- };
813
- }
814
- var SNAPSHOT_SPLIT_KEYS = ["system", "tools", "agents", "skills", "memory", "project", "messages"];
815
- function estimatedSplitSources() {
816
- const splits = {};
817
- for (const key of SNAPSHOT_SPLIT_KEYS) splits[key] = "estimated";
818
- return splits;
819
- }
820
- var snapshotCounter = 0;
821
- function nextSnapshotId() {
822
- snapshotCounter += 1;
823
- return `snap-${Date.now()}-${snapshotCounter.toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
824
- }
825
- function captureContextSnapshot(input) {
826
- const categories = buildSnapshotCategories({
827
- systemPrompt: input.systemPrompt,
828
- promptSegments: input.promptSegments,
829
- tools: input.activeToolSchemas,
830
- messages: input.conversationMessages,
831
- effectiveContextWindow: input.effectiveContextWindow,
832
- compactionThreshold: input.compactionThreshold
833
- });
834
- return {
835
- snapshotId: nextSnapshotId(),
836
- sessionId: input.sessionId,
837
- turnId: input.turnId,
838
- providerId: input.providerId,
839
- runtimeId: input.runtimeId,
840
- modelId: input.modelId,
841
- systemPrompt: input.systemPrompt,
842
- promptSegments: input.promptSegments ? [...input.promptSegments] : void 0,
843
- conversationMessages: [...input.conversationMessages],
844
- activeToolSchemas: [...input.activeToolSchemas],
845
- pendingUserInput: input.pendingUserInput,
846
- images: input.images ? [...input.images] : void 0,
847
- desiredContextWindow: input.desiredContextWindow,
848
- effectiveContextWindow: input.effectiveContextWindow,
849
- contextWindowSource: input.contextWindowSource,
850
- categories,
851
- sources: { total: "estimated", splits: estimatedSplitSources() },
852
- promptHash: input.promptHash,
853
- toolSignature: input.toolSignature,
854
- messageRange: input.conversationMessages.length > 0 ? { start: 0, end: input.conversationMessages.length - 1 } : void 0
855
- };
856
- }
857
- function snapshotInputTokens(snapshot) {
858
- return SNAPSHOT_SPLIT_KEYS.reduce((sum, key) => sum + (snapshot.categories[key] ?? 0), 0);
859
- }
860
- function reconcileSnapshot(snapshot, usage) {
861
- const exactInput = (usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
862
- const exactOutput = usage.output || 0;
863
- if (exactInput <= 0) {
864
- const updatedCategories2 = {
865
- ...snapshot.categories,
866
- streaming: exactOutput
867
- };
868
- const window2 = snapshot.effectiveContextWindow;
869
- const used2 = snapshotInputTokens(snapshot) + exactOutput;
870
- let reserve2 = snapshot.categories.reserve;
871
- let free2 = 0;
872
- if (window2 > 0) {
873
- const remaining = Math.max(0, window2 - used2);
874
- reserve2 = Math.min(reserve2, remaining);
875
- free2 = Math.max(0, window2 - used2 - reserve2);
876
- }
877
- updatedCategories2.reserve = reserve2;
878
- updatedCategories2.free = free2;
879
- return {
880
- ...snapshot,
881
- categories: updatedCategories2,
882
- sources: {
883
- total: "estimated",
884
- splits: snapshot.sources.splits
885
- }
886
- };
887
- }
888
- const keys = SNAPSHOT_SPLIT_KEYS;
889
- const currentCategories = { ...snapshot.categories };
890
- const sum = keys.reduce((s, k) => s + (currentCategories[k] ?? 0), 0);
891
- let normalized;
892
- if (sum === 0) {
893
- normalized = keys.reduce(
894
- (acc, k) => {
895
- acc[k] = k === "messages" ? exactInput : 0;
896
- return acc;
897
- },
898
- {}
899
- );
900
- } else {
901
- normalized = {};
902
- let newSum = 0;
903
- for (const key of keys) {
904
- const val = currentCategories[key] ?? 0;
905
- const norm = Math.round(val / sum * exactInput);
906
- normalized[key] = norm;
907
- newSum += norm;
908
- }
909
- const diff = exactInput - newSum;
910
- if (diff !== 0) {
911
- const largestKey = keys.reduce((a, b) => (normalized[a] ?? 0) >= (normalized[b] ?? 0) ? a : b);
912
- normalized[largestKey] = (normalized[largestKey] ?? 0) + diff;
913
- }
914
- }
915
- const updatedCategories = {
916
- ...snapshot.categories,
917
- ...normalized,
918
- streaming: exactOutput
919
- };
920
- const window = snapshot.effectiveContextWindow;
921
- const used = exactInput + exactOutput;
922
- let reserve = snapshot.categories.reserve;
923
- let free = 0;
924
- if (window > 0) {
925
- const remaining = Math.max(0, window - used);
926
- reserve = Math.min(reserve, remaining);
927
- free = Math.max(0, window - used - reserve);
928
- }
929
- updatedCategories.reserve = reserve;
930
- updatedCategories.free = free;
931
- const splitsSources = keys.reduce(
932
- (acc, k) => {
933
- acc[k] = "reconciled";
934
- return acc;
935
- },
936
- {}
937
- );
938
- return {
939
- ...snapshot,
940
- categories: updatedCategories,
941
- sources: {
942
- total: "reconciled",
943
- splits: splitsSources
944
- }
945
- };
946
- }
947
-
948
373
  // src/engine/apis/residency.ts
949
374
  init_esm_shims();
950
375
 
951
376
  // src/engine/apis/residency-lock.ts
952
377
  init_esm_shims();
953
- import { join as join3 } from "node:path";
378
+ import { join as join2 } from "node:path";
954
379
  var LOCK_WAIT_MS = 12e4;
955
380
  function lockTargetFor(targetKey) {
956
- return join3(clioStatePath(), "residency-locks", targetKey.replace(/[^a-zA-Z0-9._-]+/g, "_"));
381
+ return join2(clioStatePath(), "residency-locks", targetKey.replace(/[^a-zA-Z0-9._-]+/g, "_"));
957
382
  }
958
383
  async function withResidencyLock(targetKey, fn) {
959
384
  return withStateFileLock(lockTargetFor(targetKey), fn, {
@@ -1506,7 +931,7 @@ init_esm_shims();
1506
931
  // src/domains/providers/types/local-model-quirks.ts
1507
932
  init_esm_shims();
1508
933
  var KV_CACHE_QUANTS = ["f32", "f16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"];
1509
- function isRecord2(value) {
934
+ function isRecord(value) {
1510
935
  return value !== null && typeof value === "object" && !Array.isArray(value);
1511
936
  }
1512
937
  function asKvCacheQuant(value) {
@@ -1525,7 +950,7 @@ function asPenalty(value) {
1525
950
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
1526
951
  }
1527
952
  function extractKvCache(raw) {
1528
- if (!isRecord2(raw)) return void 0;
953
+ if (!isRecord(raw)) return void 0;
1529
954
  const out = {};
1530
955
  const k = asKvCacheQuant(raw.kQuant);
1531
956
  if (k !== void 0) out.kQuant = k;
@@ -1535,7 +960,7 @@ function extractKvCache(raw) {
1535
960
  return Object.keys(out).length > 0 ? out : void 0;
1536
961
  }
1537
962
  function extractSamplingProfile(raw) {
1538
- if (!isRecord2(raw)) return void 0;
963
+ if (!isRecord(raw)) return void 0;
1539
964
  const out = {};
1540
965
  const temperature = asPositive(raw.temperature);
1541
966
  if (temperature !== void 0) out.temperature = temperature;
@@ -1556,7 +981,7 @@ function extractSamplingProfile(raw) {
1556
981
  return Object.keys(out).length > 0 ? out : void 0;
1557
982
  }
1558
983
  function extractSampling(raw) {
1559
- if (!isRecord2(raw)) return void 0;
984
+ if (!isRecord(raw)) return void 0;
1560
985
  const out = {};
1561
986
  const thinking = extractSamplingProfile(raw.thinking);
1562
987
  if (thinking) out.thinking = thinking;
@@ -1576,7 +1001,7 @@ function asThinkingMechanism(value) {
1576
1001
  return THINKING_MECHANISMS.includes(value) ? value : void 0;
1577
1002
  }
1578
1003
  function extractBudgetByLevel(raw) {
1579
- if (!isRecord2(raw)) return void 0;
1004
+ if (!isRecord(raw)) return void 0;
1580
1005
  const out = {};
1581
1006
  const minimal = asInteger(raw.minimal);
1582
1007
  if (minimal !== void 0) out.minimal = minimal;
@@ -1591,7 +1016,7 @@ function extractBudgetByLevel(raw) {
1591
1016
  return Object.keys(out).length > 0 ? out : void 0;
1592
1017
  }
1593
1018
  function extractEffortByLevel(raw) {
1594
- if (!isRecord2(raw)) return void 0;
1019
+ if (!isRecord(raw)) return void 0;
1595
1020
  const out = {};
1596
1021
  if (typeof raw.off === "string" && raw.off.length > 0) out.off = raw.off;
1597
1022
  if (typeof raw.minimal === "string" && raw.minimal.length > 0) out.minimal = raw.minimal;
@@ -1602,7 +1027,7 @@ function extractEffortByLevel(raw) {
1602
1027
  return Object.keys(out).length > 0 ? out : void 0;
1603
1028
  }
1604
1029
  function extractThinkingQuirks(raw) {
1605
- if (!isRecord2(raw)) return void 0;
1030
+ if (!isRecord(raw)) return void 0;
1606
1031
  const mechanism = asThinkingMechanism(raw.mechanism);
1607
1032
  if (!mechanism) return void 0;
1608
1033
  const out = { mechanism };
@@ -1614,7 +1039,7 @@ function extractThinkingQuirks(raw) {
1614
1039
  return out;
1615
1040
  }
1616
1041
  function extractLocalModelQuirks(raw) {
1617
- if (!isRecord2(raw)) return void 0;
1042
+ if (!isRecord(raw)) return void 0;
1618
1043
  const out = {};
1619
1044
  const kvCache = extractKvCache(raw.kvCache);
1620
1045
  if (kvCache) out.kvCache = kvCache;
@@ -2279,7 +1704,7 @@ function targetRootUrl(target) {
2279
1704
 
2280
1705
  // src/domains/providers/runtimes/common/lmstudio-http.ts
2281
1706
  var catalogsByHost = /* @__PURE__ */ new Map();
2282
- function isRecord3(value) {
1707
+ function isRecord2(value) {
2283
1708
  return value !== null && typeof value === "object" && !Array.isArray(value);
2284
1709
  }
2285
1710
  function positiveNumber(value) {
@@ -2339,7 +1764,7 @@ async function requestLmStudioJson(url2, init, timeoutMs, signal) {
2339
1764
  };
2340
1765
  if (data !== void 0) result.data = data;
2341
1766
  if (!response.ok) {
2342
- const message = isRecord3(data) ? nonEmptyString(data.error) : void 0;
1767
+ const message = isRecord2(data) ? nonEmptyString(data.error) : void 0;
2343
1768
  result.error = message ?? `HTTP ${response.status}`;
2344
1769
  }
2345
1770
  return result;
@@ -2358,28 +1783,28 @@ function loadedInstances(value) {
2358
1783
  if (!Array.isArray(value)) return [];
2359
1784
  const instances = [];
2360
1785
  for (const raw of value) {
2361
- if (!isRecord3(raw)) continue;
1786
+ if (!isRecord2(raw)) continue;
2362
1787
  const id = nonEmptyString(raw.id);
2363
1788
  if (!id) continue;
2364
- instances.push({ id, config: isRecord3(raw.config) ? { ...raw.config } : {} });
1789
+ instances.push({ id, config: isRecord2(raw.config) ? { ...raw.config } : {} });
2365
1790
  }
2366
1791
  return instances;
2367
1792
  }
2368
1793
  function reasoningOptions(capabilities2) {
2369
- if (!isRecord3(capabilities2) || !isRecord3(capabilities2.reasoning)) return void 0;
1794
+ if (!isRecord2(capabilities2) || !isRecord2(capabilities2.reasoning)) return void 0;
2370
1795
  const allowed = capabilities2.reasoning.allowed_options;
2371
1796
  if (!Array.isArray(allowed)) return void 0;
2372
1797
  const options = allowed.filter((entry) => typeof entry === "string");
2373
1798
  return options.length > 0 ? options : void 0;
2374
1799
  }
2375
1800
  function parseLmStudioV1Models(data) {
2376
- if (!isRecord3(data) || !Array.isArray(data.models)) return null;
1801
+ if (!isRecord2(data) || !Array.isArray(data.models)) return null;
2377
1802
  const models = [];
2378
1803
  for (const raw of data.models) {
2379
- if (!isRecord3(raw)) continue;
1804
+ if (!isRecord2(raw)) continue;
2380
1805
  const key = nonEmptyString(raw.key);
2381
1806
  if (!key) continue;
2382
- const capabilities2 = isRecord3(raw.capabilities) ? raw.capabilities : void 0;
1807
+ const capabilities2 = isRecord2(raw.capabilities) ? raw.capabilities : void 0;
2383
1808
  const info = {
2384
1809
  key,
2385
1810
  loadedInstances: loadedInstances(raw.loaded_instances),
@@ -2397,7 +1822,7 @@ function parseLmStudioV1Models(data) {
2397
1822
  const options = reasoningOptions(capabilities2);
2398
1823
  if (options) info.reasoningOptions = options;
2399
1824
  if (capabilities2 && "reasoning" in capabilities2) {
2400
- info.reasoning = capabilities2.reasoning === true || isRecord3(capabilities2.reasoning);
1825
+ info.reasoning = capabilities2.reasoning === true || isRecord2(capabilities2.reasoning);
2401
1826
  }
2402
1827
  models.push(info);
2403
1828
  }
@@ -2495,10 +1920,10 @@ function lmStudioReasoningEffort(level, options) {
2495
1920
  return "low";
2496
1921
  }
2497
1922
  function v0Models(data) {
2498
- if (!isRecord3(data) || !Array.isArray(data.data)) return null;
1923
+ if (!isRecord2(data) || !Array.isArray(data.data)) return null;
2499
1924
  const models = [];
2500
1925
  for (const raw of data.data) {
2501
- if (!isRecord3(raw)) continue;
1926
+ if (!isRecord2(raw)) continue;
2502
1927
  const key = nonEmptyString(raw.id);
2503
1928
  if (!key) continue;
2504
1929
  const state = nonEmptyString(raw.state);
@@ -2522,10 +1947,10 @@ function v0Models(data) {
2522
1947
  return models;
2523
1948
  }
2524
1949
  function openAIModels(data) {
2525
- if (!isRecord3(data) || !Array.isArray(data.data)) return null;
1950
+ if (!isRecord2(data) || !Array.isArray(data.data)) return null;
2526
1951
  const models = [];
2527
1952
  for (const raw of data.data) {
2528
- if (!isRecord3(raw)) continue;
1953
+ if (!isRecord2(raw)) continue;
2529
1954
  const key = nonEmptyString(raw.id);
2530
1955
  if (key) models.push({ key, loadedInstances: [], metadata: { ...raw } });
2531
1956
  }
@@ -2585,7 +2010,7 @@ async function greetLmStudio(target, ctx) {
2585
2010
  ctx.httpTimeoutMs,
2586
2011
  ctx.signal
2587
2012
  );
2588
- if (result.ok && isRecord3(result.data) && result.data.lmstudio === true) {
2013
+ if (result.ok && isRecord2(result.data) && result.data.lmstudio === true) {
2589
2014
  return { ok: true, latencyMs: result.latencyMs };
2590
2015
  }
2591
2016
  return { ok: false, latencyMs: result.latencyMs, error: result.error ?? "endpoint did not return {lmstudio:true}" };
@@ -2962,7 +2387,7 @@ async function probeOpenAIModelCatalog(base, ctx, modelsPath = "/v1/models") {
2962
2387
  }
2963
2388
  return { models, modelCapabilities, modelStates };
2964
2389
  }
2965
- function isRecord4(value) {
2390
+ function isRecord3(value) {
2966
2391
  return value !== null && typeof value === "object" && !Array.isArray(value);
2967
2392
  }
2968
2393
  function positiveNumber2(value) {
@@ -2989,7 +2414,7 @@ function booleanFromAny(record, keys) {
2989
2414
  }
2990
2415
  function nestedRecord(record, key) {
2991
2416
  const value = record[key];
2992
- return isRecord4(value) ? value : null;
2417
+ return isRecord3(value) ? value : null;
2993
2418
  }
2994
2419
  function firstString(record, keys) {
2995
2420
  if (!record) return void 0;
@@ -3101,7 +2526,7 @@ async function probeOpenAIModelEntries(base, ctx) {
3101
2526
  return modelEntries(result.data);
3102
2527
  }
3103
2528
  function argsFromStatus(status) {
3104
- if (!isRecord4(status)) return [];
2529
+ if (!isRecord3(status)) return [];
3105
2530
  const args = status.args;
3106
2531
  if (Array.isArray(args)) return args.filter((entry) => typeof entry === "string");
3107
2532
  if (typeof args === "string") return args.trim().split(/\s+/).filter(Boolean);
@@ -3168,7 +2593,7 @@ function selectedModelEntry(entries, target) {
3168
2593
  return entries[0] ?? null;
3169
2594
  }
3170
2595
  function statusNotes(id, status) {
3171
- if (!isRecord4(status)) return [];
2596
+ if (!isRecord3(status)) return [];
3172
2597
  const notes = [];
3173
2598
  if (status.failed === true) notes.push(`llama.cpp router marks ${id} as failed`);
3174
2599
  const state = typeof status.state === "string" ? status.state : void 0;
@@ -5837,63 +5262,6 @@ function filterGemmaChannelStream(source, enabled) {
5837
5262
  return filtered;
5838
5263
  }
5839
5264
 
5840
- // src/engine/strip-tokenizer-sentinels.ts
5841
- init_esm_shims();
5842
- var KNOWN_SENTINELS = [
5843
- "<|endoftext|>",
5844
- "<|im_start|>",
5845
- "<|im_end|>",
5846
- "<|eot_id|>",
5847
- "<|end_of_turn|>",
5848
- "<|fim_prefix|>",
5849
- "<|fim_middle|>",
5850
- "<|fim_suffix|>",
5851
- "<|file_separator|>",
5852
- "<s>",
5853
- "</s>"
5854
- ];
5855
- var SENTINEL_RE = new RegExp(KNOWN_SENTINELS.map((s) => s.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&")).join("|"), "g");
5856
- var MAX_SENTINEL_LEN = KNOWN_SENTINELS.reduce((max, s) => s.length > max ? s.length : max, 0);
5857
- function stripTokenizerSentinels(text) {
5858
- if (text.length === 0) return text;
5859
- return text.replace(SENTINEL_RE, "");
5860
- }
5861
- function isSentinelPrefix(tail) {
5862
- if (tail.length === 0) return false;
5863
- for (const sentinel of KNOWN_SENTINELS) {
5864
- if (sentinel.length > tail.length && sentinel.startsWith(tail)) return true;
5865
- }
5866
- return false;
5867
- }
5868
- function createSentinelStripper() {
5869
- let buffer = "";
5870
- return {
5871
- push(chunk) {
5872
- if (chunk.length === 0) return "";
5873
- buffer += chunk;
5874
- const stripped = buffer.replace(SENTINEL_RE, "");
5875
- const holdMax = Math.min(stripped.length, MAX_SENTINEL_LEN - 1);
5876
- let hold = 0;
5877
- for (let take = holdMax; take > 0; take--) {
5878
- const tail = stripped.slice(stripped.length - take);
5879
- if (isSentinelPrefix(tail)) {
5880
- hold = take;
5881
- break;
5882
- }
5883
- }
5884
- const safe = hold === 0 ? stripped : stripped.slice(0, stripped.length - hold);
5885
- buffer = hold === 0 ? "" : stripped.slice(stripped.length - hold);
5886
- return safe;
5887
- },
5888
- flush() {
5889
- if (buffer.length === 0) return "";
5890
- const remainder = buffer.replace(SENTINEL_RE, "");
5891
- buffer = "";
5892
- return remainder;
5893
- }
5894
- };
5895
- }
5896
-
5897
5265
  // src/engine/apis/output-budget.ts
5898
5266
  init_esm_shims();
5899
5267
  var CONTEXT_BUDGET_SAFETY_TOKENS = 1024;
@@ -6472,24 +5840,24 @@ var POLL_INTERVAL_MS = 500;
6472
5840
  function isResidentState(state) {
6473
5841
  return state === "loaded" || state === "loading" || state === "sleeping";
6474
5842
  }
6475
- function isRecord5(value) {
5843
+ function isRecord4(value) {
6476
5844
  return value !== null && typeof value === "object" && !Array.isArray(value);
6477
5845
  }
6478
5846
  function routerModelState(entry) {
6479
5847
  const status = entry.status;
6480
- const state = isRecord5(status) ? status.value : status;
5848
+ const state = isRecord4(status) ? status.value : status;
6481
5849
  if (state === "loaded" || state === "loading" || state === "sleeping" || state === "unloaded" || state === "failed") {
6482
5850
  return state;
6483
5851
  }
6484
5852
  return "unknown";
6485
5853
  }
6486
5854
  function parseRouterModels(payload) {
6487
- if (!isRecord5(payload)) return [];
5855
+ if (!isRecord4(payload)) return [];
6488
5856
  const data = payload.data;
6489
5857
  if (!Array.isArray(data)) return [];
6490
5858
  const models = [];
6491
5859
  for (const entry of data) {
6492
- if (!isRecord5(entry) || typeof entry.id !== "string") continue;
5860
+ if (!isRecord4(entry) || typeof entry.id !== "string") continue;
6493
5861
  const tags = Array.isArray(entry.tags) ? entry.tags.filter((tag) => typeof tag === "string") : [];
6494
5862
  models.push({ id: entry.id, state: routerModelState(entry), tags });
6495
5863
  }
@@ -6499,7 +5867,7 @@ function residentModel(model) {
6499
5867
  return isResidentState(model.state);
6500
5868
  }
6501
5869
  function parseLlamaCppRouterProps(payload) {
6502
- if (!isRecord5(payload)) return {};
5870
+ if (!isRecord4(payload)) return {};
6503
5871
  const maxInstances = payload.max_instances;
6504
5872
  return typeof maxInstances === "number" && Number.isFinite(maxInstances) && maxInstances > 0 ? { maxInstances: Math.floor(maxInstances) } : {};
6505
5873
  }
@@ -7404,8 +6772,8 @@ function registerClioApiProviders() {
7404
6772
 
7405
6773
  // src/domains/providers/knowledge-base-path.ts
7406
6774
  init_esm_shims();
7407
- import { existsSync as existsSync2, statSync as statSync2 } from "node:fs";
7408
- import { delimiter, dirname as dirname2, join as join4 } from "node:path";
6775
+ import { existsSync, statSync as statSync2 } from "node:fs";
6776
+ import { delimiter, dirname, join as join3 } from "node:path";
7409
6777
  import { fileURLToPath } from "node:url";
7410
6778
  var MODEL_CATALOG_OVERLAY_DIR = "model-catalog.d";
7411
6779
  var MODEL_CATALOG_DIRS_ENV = "CLIO_CODER_MODEL_CATALOG_DIRS";
@@ -7417,25 +6785,25 @@ function isDirectory(path) {
7417
6785
  }
7418
6786
  }
7419
6787
  function resolveProvidersModelsDir(importMetaUrl) {
7420
- const start = dirname2(fileURLToPath(importMetaUrl));
6788
+ const start = dirname(fileURLToPath(importMetaUrl));
7421
6789
  const directCandidates = [
7422
- join4(start, "models"),
7423
- join4(start, "..", "domains", "providers", "models"),
7424
- join4(start, "..", "providers-models")
6790
+ join3(start, "models"),
6791
+ join3(start, "..", "domains", "providers", "models"),
6792
+ join3(start, "..", "providers-models")
7425
6793
  ];
7426
6794
  for (const candidate of directCandidates) {
7427
6795
  if (isDirectory(candidate)) return candidate;
7428
6796
  }
7429
6797
  let cursor = start;
7430
6798
  for (let i = 0; i < 8; i++) {
7431
- const packageJson = join4(cursor, "package.json");
7432
- const sourceModels = join4(cursor, "src", "domains", "providers", "models");
7433
- const distModels = join4(cursor, "dist", "providers-models");
7434
- if (existsSync2(packageJson)) {
6799
+ const packageJson = join3(cursor, "package.json");
6800
+ const sourceModels = join3(cursor, "src", "domains", "providers", "models");
6801
+ const distModels = join3(cursor, "dist", "providers-models");
6802
+ if (existsSync(packageJson)) {
7435
6803
  if (isDirectory(sourceModels)) return sourceModels;
7436
6804
  if (isDirectory(distModels)) return distModels;
7437
6805
  }
7438
- const parent = dirname2(cursor);
6806
+ const parent = dirname(cursor);
7439
6807
  if (parent === cursor) break;
7440
6808
  cursor = parent;
7441
6809
  }
@@ -7461,8 +6829,8 @@ function resolveProviderModelCatalogDirs(importMetaUrl, options = {}) {
7461
6829
  const bundled = resolveProvidersModelsDir(importMetaUrl);
7462
6830
  const cwd = options.cwd ?? process.cwd();
7463
6831
  const overlays = uniqueExistingDirs([
7464
- join4(resolveClioDirs().config, MODEL_CATALOG_OVERLAY_DIR),
7465
- join4(cwd, ".clio-coder", MODEL_CATALOG_OVERLAY_DIR),
6832
+ join3(resolveClioDirs().config, MODEL_CATALOG_OVERLAY_DIR),
6833
+ join3(cwd, ".clio-coder", MODEL_CATALOG_OVERLAY_DIR),
7466
6834
  ...envOverlayDirs()
7467
6835
  ]);
7468
6836
  return {
@@ -7481,7 +6849,7 @@ function resolveProviderKnowledgeBaseRoots(importMetaUrl, options = {}) {
7481
6849
 
7482
6850
  // src/domains/providers/plugins.ts
7483
6851
  init_esm_shims();
7484
- import { join as join5 } from "node:path";
6852
+ import { join as join4 } from "node:path";
7485
6853
  function extractPluginPackages(settings) {
7486
6854
  if (!settings || typeof settings !== "object") return [];
7487
6855
  const raw = settings.runtimePlugins;
@@ -7490,7 +6858,7 @@ function extractPluginPackages(settings) {
7490
6858
  }
7491
6859
  async function loadPluginRuntimes(registry, settings) {
7492
6860
  const loaded = [];
7493
- const pluginDir = join5(clioConfigDir(), "runtimes");
6861
+ const pluginDir = join4(clioConfigDir(), "runtimes");
7494
6862
  const packages = extractPluginPackages(settings);
7495
6863
  try {
7496
6864
  const ids = await registry.loadFromDir(pluginDir, activateExternalPluginApiBridge);
@@ -7518,8 +6886,8 @@ async function loadPluginRuntimes(registry, settings) {
7518
6886
  // src/domains/providers/types/knowledge-base.ts
7519
6887
  init_esm_shims();
7520
6888
  var import_yaml = __toESM(require_dist(), 1);
7521
- import { readdirSync as readdirSync2, readFileSync as readFileSync2, statSync as statSync3 } from "node:fs";
7522
- import { join as join6 } from "node:path";
6889
+ import { readdirSync as readdirSync2, readFileSync, statSync as statSync3 } from "node:fs";
6890
+ import { join as join5 } from "node:path";
7523
6891
  var FileKnowledgeBase = class {
7524
6892
  roots;
7525
6893
  loaded = [];
@@ -7533,7 +6901,7 @@ var FileKnowledgeBase = class {
7533
6901
  const files = collectYamlFiles(root.dir);
7534
6902
  for (const file of files) {
7535
6903
  const name = root.label ? `${root.label}:${file.name}` : file.name;
7536
- const raw = readFileSync2(file.path, "utf8");
6904
+ const raw = readFileSync(file.path, "utf8");
7537
6905
  const parsed = (0, import_yaml.parse)(raw);
7538
6906
  if (!Array.isArray(parsed)) {
7539
6907
  throw new Error(`knowledge base file ${name} must be a YAML list of KnowledgeBaseEntry`);
@@ -7591,7 +6959,7 @@ function collectYamlFiles(dir, prefix = "") {
7591
6959
  const out = [];
7592
6960
  const entries = readdirSync2(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
7593
6961
  for (const entry of entries) {
7594
- const path = join6(dir, entry.name);
6962
+ const path = join5(dir, entry.name);
7595
6963
  const name = prefix ? `${prefix}/${entry.name}` : entry.name;
7596
6964
  if (entry.isDirectory()) {
7597
6965
  out.push(...collectYamlFiles(path, name));
@@ -8171,24 +7539,6 @@ export {
8171
7539
  getCatalogModelForRuntime,
8172
7540
  getRuntimeRegistry,
8173
7541
  credentialsPresent,
8174
- stripTokenizerSentinels,
8175
- DEFAULT_COMPACTION_THRESHOLD,
8176
- shouldCompact,
8177
- AutoCompactionTrigger,
8178
- buildContextLedger,
8179
- ceilChars,
8180
- contentChars,
8181
- estimateReasoningTextTokens,
8182
- extractReasoningTokens,
8183
- estimateAgentMessageTokens,
8184
- estimateAgentContextBreakdown,
8185
- estimateAgentContextTokens,
8186
- contextUsageSnapshot,
8187
- appendContextSnapshot,
8188
- getLatestContextSnapshot,
8189
- captureContextSnapshot,
8190
- snapshotInputTokens,
8191
- reconcileSnapshot,
8192
7542
  setGlobalDefaultMaxOutputTokens,
8193
7543
  resolveReservedOutputTokens,
8194
7544
  setResidencyNoticeSink,
@@ -8231,4 +7581,4 @@ export {
8231
7581
  normalizeCostProvenance,
8232
7582
  ProvidersDomainModule
8233
7583
  };
8234
- //# sourceMappingURL=chunk-LZSJBIVT.js.map
7584
+ //# sourceMappingURL=chunk-QWU7ZBO7.js.map