rovecode 0.3.2

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 (334) hide show
  1. package/LICENSE +662 -0
  2. package/README.md +737 -0
  3. package/THIRD_PARTY_NOTICES.md +268 -0
  4. package/bin/rovecode.ts +21 -0
  5. package/package.json +56 -0
  6. package/src/acp/server.ts +374 -0
  7. package/src/cli/auth-login.ts +122 -0
  8. package/src/cli/connect.ts +244 -0
  9. package/src/cli/context-cmd.ts +199 -0
  10. package/src/cli/dispatch.ts +82 -0
  11. package/src/cli/doctor.ts +362 -0
  12. package/src/cli/export.ts +276 -0
  13. package/src/cli/help.ts +293 -0
  14. package/src/cli/is-tui-invocation.ts +8 -0
  15. package/src/cli/main.ts +583 -0
  16. package/src/cli/market-cmd.ts +658 -0
  17. package/src/cli/mcp-login.ts +141 -0
  18. package/src/cli/mcp-market-cmd.ts +302 -0
  19. package/src/cli/output.ts +382 -0
  20. package/src/cli/repl.ts +250 -0
  21. package/src/cli/repomap-root.ts +14 -0
  22. package/src/cli/resume.ts +57 -0
  23. package/src/cli/run-flags.ts +43 -0
  24. package/src/cli/run-limits.ts +78 -0
  25. package/src/cli/runtime.ts +931 -0
  26. package/src/cli/session-arg.ts +30 -0
  27. package/src/cli/sessions-cmd.ts +145 -0
  28. package/src/cli/setup.ts +153 -0
  29. package/src/cli/skills-cmd.ts +194 -0
  30. package/src/cli/start-chat.ts +65 -0
  31. package/src/cli/trust-cmd.ts +52 -0
  32. package/src/coding/bash.ts +148 -0
  33. package/src/coding/checkpoints.ts +327 -0
  34. package/src/coding/diff.ts +138 -0
  35. package/src/coding/files.ts +341 -0
  36. package/src/coding/hashline.ts +274 -0
  37. package/src/coding/lsp-gate.ts +254 -0
  38. package/src/coding/lsp-servers.ts +147 -0
  39. package/src/coding/lsp.ts +283 -0
  40. package/src/coding/repomap-cache.ts +99 -0
  41. package/src/coding/repomap-files.ts +192 -0
  42. package/src/coding/repomap.ts +481 -0
  43. package/src/core/agents.ts +255 -0
  44. package/src/core/compaction.ts +259 -0
  45. package/src/core/config.ts +289 -0
  46. package/src/core/context-report.ts +228 -0
  47. package/src/core/context.ts +60 -0
  48. package/src/core/count-remote.ts +107 -0
  49. package/src/core/execpolicy-rules.ts +196 -0
  50. package/src/core/execpolicy.ts +385 -0
  51. package/src/core/executor.ts +454 -0
  52. package/src/core/guardrails.ts +400 -0
  53. package/src/core/hooks.ts +411 -0
  54. package/src/core/images.ts +230 -0
  55. package/src/core/intro.ts +266 -0
  56. package/src/core/loop.ts +567 -0
  57. package/src/core/modes.ts +372 -0
  58. package/src/core/orchestrator.ts +245 -0
  59. package/src/core/proc-group.ts +48 -0
  60. package/src/core/project-trust.ts +98 -0
  61. package/src/core/reflection.ts +165 -0
  62. package/src/core/sandbox-config.ts +186 -0
  63. package/src/core/session-id.ts +24 -0
  64. package/src/core/session-images.ts +73 -0
  65. package/src/core/session-ops.ts +183 -0
  66. package/src/core/session-text.ts +29 -0
  67. package/src/core/session.ts +469 -0
  68. package/src/core/settings.ts +170 -0
  69. package/src/core/tasks.ts +646 -0
  70. package/src/core/token-scale.ts +108 -0
  71. package/src/core/tools.ts +309 -0
  72. package/src/core/trust.ts +104 -0
  73. package/src/core/types.ts +330 -0
  74. package/src/core/update-check.ts +171 -0
  75. package/src/core/usage.ts +204 -0
  76. package/src/core/validate.ts +121 -0
  77. package/src/core/verify-gate.ts +159 -0
  78. package/src/core/verify.ts +236 -0
  79. package/src/core/voice.ts +158 -0
  80. package/src/core/win-job.ts +183 -0
  81. package/src/core/workspace.ts +184 -0
  82. package/src/design/audit.ts +797 -0
  83. package/src/design/direction.ts +190 -0
  84. package/src/design/rules.ts +157 -0
  85. package/src/eval/bench.ts +150 -0
  86. package/src/eval/gauntlet-runner.ts +215 -0
  87. package/src/eval/gauntlet-support.ts +84 -0
  88. package/src/eval/gauntlet-wave3.ts +269 -0
  89. package/src/eval/gauntlet-wave4.ts +217 -0
  90. package/src/eval/gauntlet.ts +253 -0
  91. package/src/index.ts +17 -0
  92. package/src/lanes/agy.ts +95 -0
  93. package/src/lanes/approval.ts +24 -0
  94. package/src/lanes/claude.ts +129 -0
  95. package/src/lanes/codex.ts +127 -0
  96. package/src/lanes/events.ts +130 -0
  97. package/src/lanes/job.ts +142 -0
  98. package/src/lanes/opencode.ts +122 -0
  99. package/src/lanes/process.ts +184 -0
  100. package/src/lanes/progress.ts +183 -0
  101. package/src/lanes/registry.ts +178 -0
  102. package/src/lanes/runner.ts +124 -0
  103. package/src/lanes/types.ts +112 -0
  104. package/src/market/catalogs/mcp-docs.json +111 -0
  105. package/src/market/catalogs/plugins.json +111 -0
  106. package/src/market/catalogs/skills.json +478 -0
  107. package/src/market/clone.ts +72 -0
  108. package/src/market/context-cost.ts +121 -0
  109. package/src/market/digest.ts +106 -0
  110. package/src/market/index.ts +22 -0
  111. package/src/market/install.ts +578 -0
  112. package/src/market/manifest.ts +187 -0
  113. package/src/market/prereq.ts +145 -0
  114. package/src/market/registry.ts +363 -0
  115. package/src/market/resolve.ts +111 -0
  116. package/src/market/types.ts +236 -0
  117. package/src/market/validate.ts +227 -0
  118. package/src/mcp/client.ts +449 -0
  119. package/src/mcp/config.ts +252 -0
  120. package/src/mcp/local-package.ts +211 -0
  121. package/src/mcp/market-catalog.ts +84 -0
  122. package/src/mcp/market-install.ts +289 -0
  123. package/src/mcp/market.ts +362 -0
  124. package/src/mcp/oauth.ts +251 -0
  125. package/src/mcp/prompts-resources.ts +249 -0
  126. package/src/mcp/shared.ts +149 -0
  127. package/src/mcp/status.ts +67 -0
  128. package/src/mcp/tools.ts +275 -0
  129. package/src/mcp/transport.ts +122 -0
  130. package/src/mcp/trust.ts +25 -0
  131. package/src/memory/blocks.ts +278 -0
  132. package/src/memory/recall.ts +355 -0
  133. package/src/memory/scope.ts +182 -0
  134. package/src/memory/store.ts +105 -0
  135. package/src/memory/tools.ts +99 -0
  136. package/src/plugins/cli.ts +119 -0
  137. package/src/plugins/discover.ts +108 -0
  138. package/src/plugins/index.ts +50 -0
  139. package/src/plugins/install.ts +184 -0
  140. package/src/plugins/load.ts +124 -0
  141. package/src/plugins/manifest.ts +92 -0
  142. package/src/plugins/state.ts +83 -0
  143. package/src/providers/auth.ts +408 -0
  144. package/src/providers/cache.ts +223 -0
  145. package/src/providers/catalog-local.ts +160 -0
  146. package/src/providers/catalog.ts +421 -0
  147. package/src/providers/middleware-context.ts +86 -0
  148. package/src/providers/middleware.ts +373 -0
  149. package/src/providers/model-list.ts +23 -0
  150. package/src/providers/models-index.json +1 -0
  151. package/src/providers/oauth/common.ts +105 -0
  152. package/src/providers/oauth/device-code.ts +107 -0
  153. package/src/providers/oauth/github-copilot.ts +146 -0
  154. package/src/providers/oauth/loopback.ts +158 -0
  155. package/src/providers/oauth/openai.ts +163 -0
  156. package/src/providers/oauth/openrouter.ts +89 -0
  157. package/src/providers/oauth/pkce.ts +45 -0
  158. package/src/providers/oauth/registry.ts +39 -0
  159. package/src/providers/oauth/seam.ts +89 -0
  160. package/src/providers/profile-glm53.ts +111 -0
  161. package/src/providers/profile-sonnet5-persona.ts +65 -0
  162. package/src/providers/profile-sonnet5-voice.ts +23 -0
  163. package/src/providers/profiles.ts +156 -0
  164. package/src/providers/provider-config.ts +311 -0
  165. package/src/providers/registry.ts +333 -0
  166. package/src/providers/responses.ts +209 -0
  167. package/src/providers/retry.ts +234 -0
  168. package/src/providers/router.ts +294 -0
  169. package/src/providers/sse.ts +26 -0
  170. package/src/providers/stream-errors.ts +117 -0
  171. package/src/providers/stream.ts +566 -0
  172. package/src/providers/thinking.ts +189 -0
  173. package/src/providers/wire-messages.ts +129 -0
  174. package/src/providers/wire-responses.ts +79 -0
  175. package/src/providers/wire-select.ts +53 -0
  176. package/src/server/http.ts +291 -0
  177. package/src/server/openapi.ts +246 -0
  178. package/src/sextant/card-hits.ts +102 -0
  179. package/src/sextant/card-keys.ts +55 -0
  180. package/src/sextant/context-source.ts +157 -0
  181. package/src/sextant/crew-cards.ts +350 -0
  182. package/src/sextant/draw-agents.ts +273 -0
  183. package/src/sextant/draw-code.ts +388 -0
  184. package/src/sextant/draw-context.ts +222 -0
  185. package/src/sextant/draw-frame.ts +164 -0
  186. package/src/sextant/draw-market.ts +573 -0
  187. package/src/sextant/draw-messages.ts +386 -0
  188. package/src/sextant/draw-pet.ts +230 -0
  189. package/src/sextant/draw-plan.ts +187 -0
  190. package/src/sextant/draw-tabs.ts +85 -0
  191. package/src/sextant/draw-util.ts +65 -0
  192. package/src/sextant/draw-wizard.ts +378 -0
  193. package/src/sextant/engine.ts +230 -0
  194. package/src/sextant/frame-hits.ts +25 -0
  195. package/src/sextant/frame.ts +101 -0
  196. package/src/sextant/git-status.ts +197 -0
  197. package/src/sextant/grid.ts +59 -0
  198. package/src/sextant/input.ts +119 -0
  199. package/src/sextant/keys.ts +521 -0
  200. package/src/sextant/layout.ts +86 -0
  201. package/src/sextant/local-commands.ts +169 -0
  202. package/src/sextant/market-source.ts +287 -0
  203. package/src/sextant/mentions.ts +200 -0
  204. package/src/sextant/message-hits.ts +26 -0
  205. package/src/sextant/model.ts +387 -0
  206. package/src/sextant/overlays.ts +456 -0
  207. package/src/sextant/panel-hits.ts +38 -0
  208. package/src/sextant/pet.ts +399 -0
  209. package/src/sextant/screen.ts +324 -0
  210. package/src/sextant/scroll-hits.ts +66 -0
  211. package/src/sextant/scrollbar.ts +82 -0
  212. package/src/sextant/sextant-bridge.ts +174 -0
  213. package/src/sextant/sextant-cards.ts +142 -0
  214. package/src/sextant/sextant-diff-base.ts +63 -0
  215. package/src/sextant/sextant-files.ts +154 -0
  216. package/src/sextant/sextant-frame-loop.ts +335 -0
  217. package/src/sextant/sextant-renderer.ts +574 -0
  218. package/src/sextant/sextant-repo.ts +140 -0
  219. package/src/sextant/theme.ts +66 -0
  220. package/src/sextant/tool-rows.ts +189 -0
  221. package/src/sextant/types.ts +493 -0
  222. package/src/skills/index.ts +387 -0
  223. package/src/skills/pack.ts +220 -0
  224. package/src/skills/spec.ts +162 -0
  225. package/src/skills/tools.ts +69 -0
  226. package/src/skills/versioned.ts +227 -0
  227. package/src/telemetry/otel-export.ts +122 -0
  228. package/src/telemetry/otel-lanes.ts +89 -0
  229. package/src/telemetry/otel-logs.ts +131 -0
  230. package/src/telemetry/otel-metrics.ts +136 -0
  231. package/src/telemetry/otel.ts +397 -0
  232. package/src/telemetry/otlp.ts +76 -0
  233. package/src/tools/ask-user.ts +156 -0
  234. package/src/tools/bash-bg.ts +94 -0
  235. package/src/tools/bash-jobs.ts +237 -0
  236. package/src/tools/design.ts +151 -0
  237. package/src/tools/evalcell.ts +338 -0
  238. package/src/tools/html-text.ts +139 -0
  239. package/src/tools/provider.ts +149 -0
  240. package/src/tools/task.ts +250 -0
  241. package/src/tools/todo.ts +320 -0
  242. package/src/tools/webfetch.ts +332 -0
  243. package/src/tools/websearch.ts +359 -0
  244. package/src/tui/agents-cmd.ts +41 -0
  245. package/src/tui/app.ts +749 -0
  246. package/src/tui/attach.ts +127 -0
  247. package/src/tui/boot-notes.ts +41 -0
  248. package/src/tui/builtin-prompts.ts +59 -0
  249. package/src/tui/checkpoints-cmd.ts +70 -0
  250. package/src/tui/clipboard-image.ts +81 -0
  251. package/src/tui/clipboard.ts +78 -0
  252. package/src/tui/commands.ts +283 -0
  253. package/src/tui/config-view.ts +53 -0
  254. package/src/tui/context-cmds.ts +282 -0
  255. package/src/tui/cost.ts +108 -0
  256. package/src/tui/crash-guard.ts +173 -0
  257. package/src/tui/focus-terminal.ts +34 -0
  258. package/src/tui/git-cmds.ts +273 -0
  259. package/src/tui/git-plain.ts +58 -0
  260. package/src/tui/info-cmd.ts +150 -0
  261. package/src/tui/input-plain.ts +76 -0
  262. package/src/tui/mcp-cmd.ts +128 -0
  263. package/src/tui/memory-note.ts +77 -0
  264. package/src/tui/modes-cmd.ts +45 -0
  265. package/src/tui/notify-seq.ts +100 -0
  266. package/src/tui/notify.ts +318 -0
  267. package/src/tui/overlays.ts +97 -0
  268. package/src/tui/pi-renderer.ts +428 -0
  269. package/src/tui/providers-cmd.ts +377 -0
  270. package/src/tui/reasoning-view.ts +56 -0
  271. package/src/tui/renderer.ts +128 -0
  272. package/src/tui/replay-marker.ts +29 -0
  273. package/src/tui/session-cmd.ts +148 -0
  274. package/src/tui/session-manage.ts +95 -0
  275. package/src/tui/sextant-attach.ts +102 -0
  276. package/src/tui/sextant-io.ts +202 -0
  277. package/src/tui/sextant-smoke.ts +110 -0
  278. package/src/tui/shell-cmd.ts +158 -0
  279. package/src/tui/smoke.ts +72 -0
  280. package/src/tui/staged-terminal.ts +50 -0
  281. package/src/tui/startup.ts +12 -0
  282. package/src/tui/theme.ts +59 -0
  283. package/src/tui/todo-label.ts +7 -0
  284. package/src/tui/trust-card.ts +107 -0
  285. package/src/tui/tui-commands.ts +87 -0
  286. package/tsconfig.json +30 -0
  287. package/vendor/pi-tui/LICENSE +21 -0
  288. package/vendor/pi-tui/PATCHES.md +12 -0
  289. package/vendor/pi-tui/PROVENANCE.md +12 -0
  290. package/vendor/pi-tui/README.upstream.md +854 -0
  291. package/vendor/pi-tui/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
  292. package/vendor/pi-tui/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
  293. package/vendor/pi-tui/src/alt-screen-search.ts +158 -0
  294. package/vendor/pi-tui/src/autocomplete.ts +827 -0
  295. package/vendor/pi-tui/src/components/alt-screen-flash.ts +52 -0
  296. package/vendor/pi-tui/src/components/box.ts +138 -0
  297. package/vendor/pi-tui/src/components/cancellable-loader.ts +41 -0
  298. package/vendor/pi-tui/src/components/editor.ts +2364 -0
  299. package/vendor/pi-tui/src/components/h-stack.ts +45 -0
  300. package/vendor/pi-tui/src/components/image.ts +128 -0
  301. package/vendor/pi-tui/src/components/input.ts +448 -0
  302. package/vendor/pi-tui/src/components/loader.ts +93 -0
  303. package/vendor/pi-tui/src/components/markdown.ts +1016 -0
  304. package/vendor/pi-tui/src/components/scroll-view.ts +217 -0
  305. package/vendor/pi-tui/src/components/select-list.ts +230 -0
  306. package/vendor/pi-tui/src/components/settings-list.ts +277 -0
  307. package/vendor/pi-tui/src/components/spacer.ts +29 -0
  308. package/vendor/pi-tui/src/components/stack.ts +155 -0
  309. package/vendor/pi-tui/src/components/text.ts +108 -0
  310. package/vendor/pi-tui/src/components/truncated-text.ts +66 -0
  311. package/vendor/pi-tui/src/components/v-stack.ts +34 -0
  312. package/vendor/pi-tui/src/editor-component.ts +75 -0
  313. package/vendor/pi-tui/src/fuzzy.ts +138 -0
  314. package/vendor/pi-tui/src/index.ts +149 -0
  315. package/vendor/pi-tui/src/keybindings.ts +321 -0
  316. package/vendor/pi-tui/src/keys.ts +1402 -0
  317. package/vendor/pi-tui/src/kill-ring.ts +47 -0
  318. package/vendor/pi-tui/src/latex.ts +1381 -0
  319. package/vendor/pi-tui/src/layout-node.ts +52 -0
  320. package/vendor/pi-tui/src/layout.ts +411 -0
  321. package/vendor/pi-tui/src/native-modifiers.ts +60 -0
  322. package/vendor/pi-tui/src/native-module-path.ts +32 -0
  323. package/vendor/pi-tui/src/stdin-buffer.ts +445 -0
  324. package/vendor/pi-tui/src/terminal-colors.ts +74 -0
  325. package/vendor/pi-tui/src/terminal-image.ts +701 -0
  326. package/vendor/pi-tui/src/terminal.ts +554 -0
  327. package/vendor/pi-tui/src/tui-alt-screen.ts +1379 -0
  328. package/vendor/pi-tui/src/tui-main-screen.ts +655 -0
  329. package/vendor/pi-tui/src/tui.ts +1264 -0
  330. package/vendor/pi-tui/src/undo-stack.ts +29 -0
  331. package/vendor/pi-tui/src/utils.ts +1327 -0
  332. package/vendor/pi-tui/src/word-navigation.ts +118 -0
  333. package/vendor/pi-tui/test/test-themes.ts +39 -0
  334. package/vendor/pi-tui/test/virtual-terminal.ts +219 -0
@@ -0,0 +1,255 @@
1
+ /** Custom subagent definitions (ported from the Nimbus harness, PORT #62): `.rovecode/agents/<name>.md` (project) and
2
+ * `~/.rovecode/agents/<name>.md` (user scope, ROVECODE_HOME-aware — providers/auth.ts rovecodeHome) become agent
3
+ * names the `task` tool can start: `task start {agent:"<name>"}` runs the child with the definition's model, mode
4
+ * and a tool registry RESTRICTED to its allow-list — through the existing TaskManager / child registry (no second
5
+ * loop, no second registry; the allow-list is a FILTER over the child tool table, never wider than the parent's).
6
+ * This module is the pure half — file format, discovery, the filter. cli/runtime.ts wires it (discovery at boot,
7
+ * the defs map beside `main`, the filtered child registry); core/orchestrator.ts honours `mode`.
8
+ *
9
+ * Pattern source: opencode @ ebece6e (MIT), packages/opencode/src/config/agent.ts — markdown files under an
10
+ * `agent(s)/` config dir, name = path sans extension, frontmatter = the agent's fields and the body its prompt
11
+ * (`{ name, ...md.data, prompt: md.content.trim() }`, :23-28); the global config dir is merged before the project's,
12
+ * so a project entry replaces a user one (config.ts:474-475 mergeDeep). Its field set (description, model, mode,
13
+ * tools {name: bool}, permission, temperature, steps …) is reduced to the four knobs below; `tools` is a plain
14
+ * allow-list (permissions come from the parent's rules via orchestrator deriveChildRules and are NOT configurable
15
+ * per agent).
16
+ *
17
+ * File format (YAML-lite frontmatter — skills/index.ts parseFrontmatter):
18
+ * ---
19
+ * description: Fast codebase explorer (optional; ≤ 200 chars in listings; default "custom agent (<file>)")
20
+ * model: openai/gpt-4o-mini (optional; "provider/model" = the router grammar, split on the
21
+ * FIRST slash; a bare id runs on the starting run's provider. A
22
+ * child streams over the RUN's endpoint, so a provider other than
23
+ * the configured one cannot be honoured and is refused at
24
+ * discovery — DiscoverAgentsOptions.validateModel)
25
+ * mode: plan (optional; plan|act; plan = the plan rule set + prompt section)
26
+ * tools: read, grep, glob (optional allow-list; comma/space separated, [brackets] allowed;
27
+ * ABSENT or "*" = every tool the child table offers; PRESENT but
28
+ * empty — `tools:`, `tools: []`, `tools: ''` — is an error, and so
29
+ * is a YAML block list (`- read` lines): the file is skipped, it
30
+ * never fails open to every tool)
31
+ * ---
32
+ * <body = the child's system prompt; empty → the runtime's own prompt>
33
+ * Frontmatter lines are `key: value` only (blank and `#` comment lines allowed); any other line is an error. Keys
34
+ * outside description/model/mode/tools are IGNORED with a warning (the file still loads) — a typo like `tool:` is
35
+ * never silent. Names: filename sans `.md`, lowercased, [a-z0-9_-]+; `main` (the built-in child) and the external-lane
36
+ * adapter ids are RESERVED: a `codex.md` is refused with a line naming the file, and `task start codex` stays the
37
+ * lane — neither is silently preferred. Every problem is a warning (never a throw): unterminated frontmatter, a
38
+ * `mode` outside plan|act, a malformed `tools` or `model` value, a model the run cannot honour, an unreadable file,
39
+ * a bad or reserved name. Missing dirs are silent. */
40
+
41
+ import { readdirSync, readFileSync, statSync } from "node:fs";
42
+ import { join, resolve } from "node:path";
43
+ import type { Tool } from "./types.ts";
44
+ import { rovecodeHome } from "../providers/auth.ts";
45
+ import { parseFrontmatter } from "../skills/index.ts";
46
+ import { ADAPTER_IDS } from "../lanes/types.ts";
47
+
48
+ export type AgentScope = "project" | "user";
49
+ export type CustomAgentMode = "plan" | "act";
50
+
51
+ export interface CustomAgent {
52
+ /** the filename sans `.md`, lowercased; matches [a-z0-9_-]+ */
53
+ name: string;
54
+ description: string;
55
+ /** frontmatter `model:` — "provider/model" (router grammar) or a bare model id (the starting run's provider) */
56
+ model?: string;
57
+ /** frontmatter `mode:` — the child runs in this plan/act mode (orchestrator runChild applies it) */
58
+ mode?: CustomAgentMode;
59
+ /** tool allow-list; ["*"] = every tool the child table offers (the default) */
60
+ tools: string[];
61
+ /** the markdown body: the child's system prompt ("" → the runtime's own prompt) */
62
+ body: string;
63
+ path: string;
64
+ scope: AgentScope;
65
+ }
66
+
67
+ export interface ParsedAgentFile {
68
+ description?: string; model?: string; mode?: CustomAgentMode; tools: string[]; body: string;
69
+ /** frontmatter keys outside the four known ones (present only when there are some) — the file loads, discovery warns */
70
+ unknown?: string[];
71
+ }
72
+
73
+ export interface DiscoveredAgents { agents: CustomAgent[]; warnings: string[] }
74
+
75
+ export interface DiscoverAgentsOptions {
76
+ /** user-scope home; default rovecodeHome() (ROVECODE_HOME → ~/.rovecode). Definitions: `<home>/agents` */
77
+ home?: string;
78
+ /** names a definition may not take; default DEFAULT_RESERVED_AGENT_NAMES */
79
+ reserved?: readonly string[];
80
+ /** false skips the PROJECT dir (an untrusted checkout's definitions never reach the `task` schema); the user dir still
81
+ * loads. Default true. */
82
+ project?: boolean;
83
+ /** why a `model:` selector cannot be honoured by THIS runtime, or undefined when it can — the runtime knows which
84
+ * provider the run streams over; a refused file is skipped with the reason (cli/runtime.ts modelProblemFor) */
85
+ validateModel?: (selector: string) => string | undefined;
86
+ }
87
+
88
+ /** the built-in child definition + the external-lane ids (core/tasks.ts treats the lane ids as lanes, never agents) */
89
+ export const DEFAULT_RESERVED_AGENT_NAMES: readonly string[] = ["main", ...ADAPTER_IDS];
90
+ /** the sub-directory of a state dir that holds the definitions */
91
+ export const AGENTS_DIR = "agents";
92
+ /** the project state dir the definitions live under */
93
+ export const PROJECT_STATE_DIR = ".rovecode";
94
+
95
+ const NAME_RE = /^[a-z0-9_-]+$/;
96
+ const TOOL_NAME_RE = /^[A-Za-z0-9_*-]+$/;
97
+ const MAX_DESCRIPTION_CHARS = 200;
98
+
99
+ function clip(s: string, max: number): string {
100
+ return s.length > max ? s.slice(0, max - 1) + "…" : s;
101
+ }
102
+
103
+ // ---------- file format ----------
104
+
105
+ /** `tools:` value → allow-list. Comma/space separated, optional [brackets] and quotes; "*" anywhere = all;
106
+ * a token outside [A-Za-z0-9_*-]+ is an error (never a silent partial list). Empty → ["*"]. */
107
+ export function parseToolList(value: string | undefined): string[] | { error: string } {
108
+ const raw = (value ?? "").trim().replace(/^\[|\]$/g, "").trim();
109
+ if (raw === "") return ["*"];
110
+ const names = raw.split(/[\s,]+/).map((t) => t.replace(/^["']|["']$/g, "")).filter((t) => t !== "");
111
+ const bad = names.find((n) => !TOOL_NAME_RE.test(n));
112
+ if (bad !== undefined) return { error: `tools: "${clip(bad, 40)}" is not a tool name (letters, digits, _ - or *)` };
113
+ if (names.includes("*")) return ["*"];
114
+ return [...new Set(names)];
115
+ }
116
+
117
+ /** Optional `---` frontmatter + body → agent fields. `{ error }` names why a file must be skipped. Never throws. */
118
+ export function parseAgentFile(text: string): ParsedAgentFile | { error: string } {
119
+ let src = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text; // drop a UTF-8 BOM
120
+ let fm: Record<string, string> = {};
121
+ let body = src;
122
+ if (src.startsWith("---")) {
123
+ if (!src.endsWith("\n")) src += "\n"; // parseFrontmatter finds the closing fence by its line end
124
+ const parsed = parseFrontmatter(src);
125
+ if (!parsed) return { error: "unterminated frontmatter (no closing ---)" };
126
+ // parseFrontmatter silently DROPS lines without a colon — a YAML block list (`tools:` + `- read` lines) or a
127
+ // multi-line value would leave `tools` empty and fail OPEN to "*"; reject the file instead (blank / `#` lines are fine)
128
+ const shape = checkFrontmatterLines(src.slice(4, src.indexOf("\n---", 3)));
129
+ if (shape !== undefined) return { error: shape };
130
+ fm = parsed.fm; body = parsed.body;
131
+ }
132
+ const field = (k: string): string | undefined => { const v = fm[k]?.trim(); return v ? v : undefined; };
133
+ const mode = field("mode");
134
+ if (mode !== undefined && mode !== "plan" && mode !== "act") return { error: `mode must be "plan" or "act" (got "${clip(mode, 40)}")` };
135
+ const model = field("model");
136
+ if (model !== undefined && /\s/.test(model)) return { error: `model must be one selector ("provider/model" or a model id; got "${clip(model, 40)}")` };
137
+ // a PRESENT `tools:` with nothing in it (`tools:`, `tools: []`, `tools: ''`) is an error — only an ABSENT key means "*"
138
+ if (fm["tools"] !== undefined && fm["tools"].trim().replace(/^\[|\]$/g, "").trim() === "") return { error: "tools: empty value (write `tools: *` for every tool, or list names — `tools:` alone never means all)" };
139
+ const tools = parseToolList(fm["tools"]);
140
+ if (!Array.isArray(tools)) return { error: tools.error };
141
+ const unknown = Object.keys(fm).filter((k) => !KNOWN_KEYS.has(k));
142
+ return { description: field("description"), model, mode, tools, body: body.trim(), ...(unknown.length > 0 ? { unknown } : {}) };
143
+ }
144
+
145
+ const KNOWN_KEYS: ReadonlySet<string> = new Set(["description", "model", "mode", "tools"]);
146
+
147
+ /** Every non-blank, non-comment frontmatter line must be `key: value`; the first offender names the reason. */
148
+ function checkFrontmatterLines(block: string): string | undefined {
149
+ for (const line of block.split(/\r?\n/)) {
150
+ const t = line.trim();
151
+ if (t === "" || t.startsWith("#")) continue;
152
+ if (/^-(\s|$)/.test(t)) return `frontmatter uses a YAML block list ("${clip(t, 30)}") — not supported: write \`tools: read, grep\` on one line`;
153
+ if (t.indexOf(":") === -1) return `frontmatter line is not \`key: value\` ("${clip(t, 30)}")`;
154
+ }
155
+ return undefined;
156
+ }
157
+
158
+ /** The runtime's model check (DiscoverAgentsOptions.validateModel): a `provider/model` selector whose provider is not the
159
+ * one this session streams over cannot be honoured — every child runs on the run's endpoint. A bare id, or the same
160
+ * provider, is fine; an unknown model ID is not judged here (the catalog is advisory everywhere else). `configured` =
161
+ * the run's provider id, or null when nothing is configured (then nothing is refused on this ground). */
162
+ export function modelProblemFor(configured: string | null): (selector: string) => string | undefined {
163
+ return (selector) => {
164
+ const slash = selector.indexOf("/");
165
+ if (slash <= 0 || configured === null) return undefined;
166
+ const provider = selector.slice(0, slash);
167
+ return provider === configured ? undefined : `model "${clip(selector, 60)}" names provider "${provider}" but this session streams over "${configured}" — a child cannot switch providers; write the bare model id, or "${configured}/<model>"`;
168
+ };
169
+ }
170
+
171
+ // ---------- discovery ----------
172
+
173
+ /** Scan `<home>/agents` then `<cwd>/.rovecode/agents`; a later (project) entry replaces an earlier (user) one of the
174
+ * same name. Missing dirs are silent; every other problem is a warning for the boot transcript, never a throw.
175
+ * Sorted by name. */
176
+ export function discoverAgents(cwd: string, opts: DiscoverAgentsOptions = {}): DiscoveredAgents {
177
+ const warnings: string[] = [];
178
+ const reserved = new Set(opts.reserved ?? DEFAULT_RESERVED_AGENT_NAMES);
179
+ const userDir = join(opts.home ?? rovecodeHome(), AGENTS_DIR);
180
+ const projectDir = join(cwd, PROJECT_STATE_DIR, AGENTS_DIR);
181
+ // the project state dir IS the user home: one directory, scanned once; untrusted → the user dir only
182
+ const dirs: [AgentScope, string][] = opts.project === false ? [["user", userDir]]
183
+ : resolve(userDir) === resolve(projectDir) ? [["project", projectDir]]
184
+ : [["user", userDir], ["project", projectDir]];
185
+ const byName = new Map<string, CustomAgent>();
186
+ for (const [scope, dir] of dirs) {
187
+ for (const a of scanAgentDir(dir, scope, warnings, opts.validateModel)) {
188
+ if (reserved.has(a.name)) { warnings.push(`${a.path}: skipped — "${a.name}" is a reserved agent name${ADAPTER_IDS.includes(a.name as (typeof ADAPTER_IDS)[number]) ? ` (the ${a.name} external lane keeps it; \`task start ${a.name}\` runs the lane, never this file)` : ""}`); continue; }
189
+ const prev = byName.get(a.name);
190
+ if (prev?.scope === scope) { warnings.push(`${a.path}: agent "${a.name}" already defined by ${prev.path} — first kept`); continue; }
191
+ byName.set(a.name, a); // project (scanned second) shadows user
192
+ }
193
+ }
194
+ return { agents: [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)), warnings };
195
+ }
196
+
197
+ /** a symlinked `*.md` counts when its target is a file; a dangling link stays so the read reports it */
198
+ function linksToFile(path: string): boolean {
199
+ try { return statSync(path).isFile(); } catch { return true; }
200
+ }
201
+
202
+ /** One directory's `*.md` files (top level only, sorted), each parsed or warned about. */
203
+ function scanAgentDir(dir: string, scope: AgentScope, warnings: string[], validateModel?: (selector: string) => string | undefined): CustomAgent[] {
204
+ let files: string[];
205
+ try {
206
+ files = readdirSync(dir, { withFileTypes: true })
207
+ .filter((e) => /\.md$/i.test(e.name) && (e.isFile() || (e.isSymbolicLink() && linksToFile(join(dir, e.name)))))
208
+ .map((e) => e.name).sort();
209
+ } catch {
210
+ return []; // no such directory — silent, like the skills store and custom commands
211
+ }
212
+ const out: CustomAgent[] = [];
213
+ for (const file of files) {
214
+ const path = join(dir, file);
215
+ const name = file.slice(0, -3).toLowerCase();
216
+ if (!NAME_RE.test(name)) { warnings.push(`${path}: skipped — agent name "${name}" must match [a-z0-9_-]+`); continue; }
217
+ let text: string;
218
+ try {
219
+ text = readFileSync(path, "utf8");
220
+ } catch (e) {
221
+ warnings.push(`${path}: skipped — unreadable (${e instanceof Error ? e.message : String(e)})`);
222
+ continue;
223
+ }
224
+ const parsed = parseAgentFile(text);
225
+ if ("error" in parsed) { warnings.push(`${path}: skipped — ${parsed.error}`); continue; }
226
+ // a model this runtime cannot honour is refused HERE, with the file named — not at run time inside a child
227
+ const modelProblem = parsed.model !== undefined && validateModel ? validateModel(parsed.model) : undefined;
228
+ if (modelProblem !== undefined) { warnings.push(`${path}: skipped — ${modelProblem}`); continue; }
229
+ // unknown keys load fine but are never silent (a `tool:` typo would otherwise grant every tool without a word)
230
+ if (parsed.unknown) warnings.push(`${path}: loaded — ignored unknown frontmatter key${parsed.unknown.length > 1 ? "s" : ""} ${parsed.unknown.map((k) => `"${clip(k, 30)}"`).join(", ")} (known: description, model, mode, tools)`);
231
+ out.push({
232
+ name, description: clip(parsed.description ?? `custom agent (${file})`, MAX_DESCRIPTION_CHARS),
233
+ ...(parsed.model !== undefined ? { model: parsed.model } : {}), ...(parsed.mode !== undefined ? { mode: parsed.mode } : {}),
234
+ tools: parsed.tools, body: parsed.body, path, scope,
235
+ });
236
+ }
237
+ return out;
238
+ }
239
+
240
+ // ---------- the child registry filter ----------
241
+
242
+ /** The tools a child may be given: the candidate table filtered by the definition's allow-list ("*" keeps it
243
+ * all) AND clamped to names the PARENT registry holds — a definition can never widen a child beyond its
244
+ * parent's set, and a name outside the child table (mcp_call, web_fetch, memory_edit …) is simply dropped.
245
+ * Pure; the caller registers the result into the ONE child ToolRegistry it constructs (cli/runtime.ts). */
246
+ export function restrictTools(table: readonly Tool[], allow: readonly string[], parentNames: ReadonlySet<string>): Tool[] {
247
+ const all = allow.includes("*");
248
+ const wanted = new Set(allow);
249
+ return table.filter((t) => (all || wanted.has(t.schema.name)) && parentNames.has(t.schema.name));
250
+ }
251
+
252
+ /** `name — description` rows for the `task` tool's schema (tools/task.ts enumerates the loaded definitions). */
253
+ export function agentRows(d: DiscoveredAgents): { name: string; description: string }[] {
254
+ return d.agents.map((a) => ({ name: a.name, description: a.description }));
255
+ }
@@ -0,0 +1,259 @@
1
+ /** Compaction strategy seam + adaptive trigger (port #25; ADR-007 history compaction).
2
+ *
3
+ * Strategies — oh-my-pi compaction/compaction.ts:167-231 @ 65f79e7 (MIT) keeps a strategy enum
4
+ * on the settings object and decides provider-native vs local per model; same split here:
5
+ * head-summarize the pre-#25 path, byte-for-byte: summarize the head with the weak model,
6
+ * keep the tail under half budget (aider history.py:41 via context.ts).
7
+ * keep-window deterministic, NO model call: keep the last N user turns + everything
8
+ * since the last user message, under a token cap; tool_call/tool_result
9
+ * pairs leave or stay TOGETHER (senpi deterministic-fallback.ts:28-33
10
+ * @ a0f26a6 rejects an "atomic-tool-chain-cut"; opencode message-v2.ts:
11
+ * 349-360 — every tool_use needs its tool_result on the wire). When the
12
+ * current turn alone overflows, the user's request survives and the cut
13
+ * lands inside its tool traffic (opencode compaction.ts:340-356 replays
14
+ * the last user message after an overflow compaction).
15
+ * provider-native delegate to a server-side compaction capability when the active provider
16
+ * advertises one (oh-my-pi :222-231 shouldUseProviderNativeCompaction;
17
+ * :1264-1281 local summary when remote is off/unsupported). HONESTY: none
18
+ * of rovecode's adapters advertise it today — the seam (LoopDeps.compactNative)
19
+ * and a test double ship; absent or declining → head-summarize fallback.
20
+ *
21
+ * Trigger (senpi a0f26a6): "speculative" when the ESTIMATE crosses budget × threshold, before
22
+ * the provider call (compaction-settings.ts:22-24 speculativeFraction; agent-session.ts:5874
23
+ * "Threshold: compact, NO auto-retry"). "emergency" when the provider REJECTS the request as
24
+ * a context overflow (agent-session.ts:5873 "Overflow: LLM returned context overflow error …
25
+ * compact, auto-retry"; :6061-6080 exactly ONE compact-and-retry; opencode processor.ts:
26
+ * 607-617 ContextOverflowError → needsCompaction → prompt.ts:1320-1327 create({overflow}) →
27
+ * the loop restarts the turn). Emergency plans against the OBSERVED size, not the configured
28
+ * window — the estimator just proved optimistic.
29
+ *
30
+ * Pure over Messages. The loop owns token accounting (ctx.tokenText = partsTokenText, so the
31
+ * numbers match its trigger) and persistence (SessionStore.appendEvent). No loop import here:
32
+ * loop.ts imports this module. Without a summarizer, speculative compaction stays off exactly
33
+ * as before #25; an emergency still shrinks via the deterministic window (senpi deterministic-
34
+ * fallback.ts:111 createRequiredCompactionFallback — a required compaction never wedges). */
35
+
36
+ import { randomUUID } from "node:crypto";
37
+ import type { Message, ModelRef, RunConfig } from "./types.ts";
38
+ import { estimateTokens, planCompaction as planHeadTail } from "./context.ts";
39
+
40
+ export type CompactionStrategy = "head-summarize" | "keep-window" | "provider-native";
41
+ export type CompactionTrigger = "speculative" | "emergency";
42
+
43
+ export const COMPACTION_STRATEGIES: readonly CompactionStrategy[] = ["head-summarize", "keep-window", "provider-native"];
44
+ export const DEFAULT_COMPACTION_STRATEGY: CompactionStrategy = "head-summarize";
45
+ /** keep-window: user turns retained BEFORE the current one when RunConfig.compactionKeepTurns is unset */
46
+ export const DEFAULT_KEEP_TURNS = 2;
47
+
48
+ /** `ROVECODE_COMPACTION=<strategy>`, case-insensitive — unset/blank → undefined (the caller applies the
49
+ * default). An unknown name is ALSO undefined (→ default) plus ONE stderr note per process and value:
50
+ * createRuntime has no warnings channel, and buildCfg re-parses the env before every run. */
51
+ const unknownStrategyNoted = new Set<string>();
52
+ export function parseCompactionStrategy(raw: string | undefined): CompactionStrategy | undefined {
53
+ const v = (raw ?? "").trim().toLowerCase();
54
+ if (v === "") return undefined;
55
+ if ((COMPACTION_STRATEGIES as readonly string[]).includes(v)) return v as CompactionStrategy;
56
+ if (!unknownStrategyNoted.has(v)) {
57
+ unknownStrategyNoted.add(v);
58
+ console.error(`rovecode: unknown ROVECODE_COMPACTION "${(raw ?? "").trim()}" — using ${DEFAULT_COMPACTION_STRATEGY} (known: ${COMPACTION_STRATEGIES.join(", ")})`);
59
+ }
60
+ return undefined;
61
+ }
62
+
63
+ /** Server-side compaction capability. Resolve to the replacement history, or null to decline
64
+ * (unsupported model, endpoint error) — the seam then falls back locally. Contract: the
65
+ * returned history's LAST message must be one the store already holds (the loop parents the
66
+ * next message on it). */
67
+ export type NativeCompactor = (
68
+ history: Message[],
69
+ opts: { model?: ModelRef; budgetTokens: number; trigger: CompactionTrigger; signal?: AbortSignal },
70
+ ) => Promise<Message[] | null>;
71
+
72
+ export interface CompactionCtx {
73
+ trigger: CompactionTrigger;
74
+ /** token-bearing text of ONE message, all parts (loop.ts partsTokenText) — tokens = estimateTokens(tokenText) */
75
+ tokenText: (m: Message) => string;
76
+ summarize?: (texts: string[]) => Promise<string>;
77
+ native?: NativeCompactor;
78
+ model?: ModelRef;
79
+ signal?: AbortSignal;
80
+ }
81
+
82
+ export interface CompactionPlan {
83
+ strategy: CompactionStrategy;
84
+ /** the configured strategy when it could not run and `strategy` is its fallback */
85
+ fallbackFrom?: CompactionStrategy;
86
+ keep: Message[];
87
+ drop: Message[];
88
+ /** head-summarize: a summarizer call is required before the history can be rebuilt */
89
+ summaryNeeded: boolean;
90
+ tokensBefore: number;
91
+ /** planning budget in force: the window (speculative) or half the observed size (emergency) */
92
+ budgetTokens: number;
93
+ }
94
+
95
+ export interface CompactionOutcome { history: Message[]; strategy: CompactionStrategy; fallbackFrom?: CompactionStrategy }
96
+
97
+ // ---------- trigger ----------
98
+
99
+ /** Adaptive trigger. Strictly GREATER than budget × threshold: AT the threshold nothing fires
100
+ * (pinned). A provider overflow rejection is an emergency whatever the estimate says. */
101
+ export function compactionTrigger(histTokens: number, cfg: RunConfig, overflow: boolean): CompactionTrigger | null {
102
+ if (overflow) return "emergency";
103
+ return histTokens > cfg.contextBudgetTokens * cfg.compactionThreshold ? "speculative" : null;
104
+ }
105
+
106
+ /** Provider phrasings of "the prompt does not fit" — opencode-2026 llm/provider-error.ts:4-38
107
+ * @ ebece6e (MIT), minus the throttling exclusions; plus HTTP 413 (provider/error.ts:175).
108
+ * rovecode error text is "HTTP <status>: <body>" (stream-errors.ts httpErrorTurn; router.ts
109
+ * classifyStreamError reads the same prefix) or a bare transport message. 429/5xx are the
110
+ * retry classes (port #23) and never an overflow, whatever their body says. */
111
+ const OVERFLOW_PATTERNS = [
112
+ /prompt is too long/i, /request_too_large/i, /input is too long for requested model/i,
113
+ /exceeds the context window/i, /maximum context length/i, /context[_ ]length[_ ]exceeded/i,
114
+ /input token count.*exceeds the maximum/i, /tokens in request more than max tokens allowed/i,
115
+ /maximum prompt length is \d+/i, /reduce the length of the messages/i, /request entity too large/i,
116
+ /model_context_window_exceeded/i, /too many tokens/i, /token limit exceeded/i,
117
+ /exceeds the available context size/i, /greater than the context length/i,
118
+ ];
119
+ const OVERFLOW_EXCLUSIONS = [/rate limit/i, /too many requests/i, /throttling/i, /service unavailable/i];
120
+
121
+ export function isContextOverflow(error: string | undefined): boolean {
122
+ if (!error || OVERFLOW_EXCLUSIONS.some((p) => p.test(error))) return false;
123
+ // the status may sit behind the router's exhausted-chain rewrite ("model chain 'x' exhausted
124
+ // (N candidates failed); last: HTTP 500: …", router.ts) — a 5xx body that mentions tokens is
125
+ // still a 5xx, never an overflow
126
+ const status = /(?:^|last: )HTTP (\d{3})\b/.exec(error)?.[1];
127
+ if (status === "413") return true;
128
+ if (status === "429" || status?.startsWith("5")) return false;
129
+ return OVERFLOW_PATTERNS.some((p) => p.test(error));
130
+ }
131
+
132
+ // ---------- planning ----------
133
+
134
+ /** Speculative plans against the window. Emergency halves the smaller of window and OBSERVED
135
+ * history, so the kept tail lands ≤ a quarter of what just overflowed (senpi shrinks the
136
+ * summarization input geometrically per overflow retry — overflow-retry-bound.test.ts:126-142;
137
+ * we get ONE retry, so one aggressive step). */
138
+ export function planningBudget(cfg: RunConfig, observedTokens: number, trigger: CompactionTrigger): number {
139
+ if (trigger === "speculative") return cfg.contextBudgetTokens;
140
+ return Math.max(1, Math.floor(Math.min(cfg.contextBudgetTokens, observedTokens) / 2));
141
+ }
142
+
143
+ function resolveStrategy(requested: CompactionStrategy, ctx: CompactionCtx): CompactionStrategy | null {
144
+ if (requested === "keep-window") return "keep-window";
145
+ if (requested === "provider-native" && ctx.native) return "provider-native";
146
+ if (ctx.summarize) return "head-summarize";
147
+ // no summarizer: speculative stays off (pre-#25 gate); an emergency must still shrink
148
+ return ctx.trigger === "emergency" ? "keep-window" : null;
149
+ }
150
+
151
+ export function planCompaction(history: Message[], cfg: RunConfig, ctx: CompactionCtx): CompactionPlan | null {
152
+ const requested = cfg.compactionStrategy ?? DEFAULT_COMPACTION_STRATEGY;
153
+ const strategy = resolveStrategy(requested, ctx);
154
+ if (!strategy) return null;
155
+ const tokens = (m: Message) => estimateTokens(ctx.tokenText(m));
156
+ const tokensBefore = history.reduce((n, m) => n + tokens(m), 0);
157
+ const budgetTokens = planningBudget(cfg, tokensBefore, ctx.trigger);
158
+ const base = { strategy, tokensBefore, budgetTokens, ...(strategy !== requested ? { fallbackFrom: requested } : {}) };
159
+ if (strategy === "provider-native") return { ...base, keep: history, drop: [], summaryNeeded: false };
160
+ if (strategy === "keep-window") {
161
+ const turns = ctx.trigger === "emergency" ? 0 : (cfg.compactionKeepTurns ?? DEFAULT_KEEP_TURNS);
162
+ return { ...base, ...keepWindow(history, tokens, budgetTokens, turns), summaryNeeded: false };
163
+ }
164
+ // head-summarize: the aider head/tail plan over {id,tokens,text} projections, mapped back to
165
+ // the real messages (loop.test.ts "rebuilds history from real messages, not projections")
166
+ const plan = planHeadTail(history.map((m) => ({ id: m.id, tokens: tokens(m), text: ctx.tokenText(m) })), budgetTokens);
167
+ const keepIds = new Set(plan.keep.map((k) => k.id));
168
+ // never an empty tail: the summary message is working-history only (never persisted), so the next
169
+ // assistant must parent on a REAL message or the store reloads with an orphan chain. When the last
170
+ // message alone exceeds half the budget the aider plan keeps nothing — keep it anyway, and when it
171
+ // is a tool result keep the assistant that issued the call too (over cap accepted over an orphan,
172
+ // exactly keepWindow's alignCut rule; the plan's ordinary cut stays prose-oriented, as before)
173
+ if (keepIds.size === 0 && history.length > 0) {
174
+ let i = history.length - 1;
175
+ while (i > 0 && history[i]!.role === "tool") i--;
176
+ for (const m of history.slice(i)) keepIds.add(m.id);
177
+ }
178
+ return { ...base, keep: history.filter((m) => keepIds.has(m.id)), drop: history.filter((m) => !keepIds.has(m.id)), summaryNeeded: true };
179
+ }
180
+
181
+ /** Deterministic window. Turn-level cuts land on user messages; when the current turn alone
182
+ * exceeds the cap (half the planning budget), the user's request is kept and the cut moves
183
+ * through its tool traffic one assistant+results group at a time (alignCut). */
184
+ export function keepWindow(history: Message[], tokens: (m: Message) => number, budgetTokens: number, keepTurns: number): { keep: Message[]; drop: Message[] } {
185
+ const cap = Math.floor(budgetTokens / 2);
186
+ const sum = (ms: Message[]) => ms.reduce((n, m) => n + tokens(m), 0);
187
+ const userIdx = history.flatMap((m, i) => (m.role === "user" ? [i] : []));
188
+ let ui = Math.max(0, userIdx.length - 1 - Math.max(0, keepTurns));
189
+ let start = userIdx.length > 0 ? userIdx[ui]! : 0;
190
+ while (sum(history.slice(start)) > cap && ui < userIdx.length - 1) start = userIdx[++ui]!;
191
+ const lastUser = userIdx.at(-1);
192
+ if (lastUser !== undefined && start === lastUser && sum(history.slice(start)) > cap) {
193
+ // the current turn alone overflows: keep the request, cut inside the traffic after it
194
+ let inner = lastUser + 1;
195
+ while (inner < history.length && tokens(history[lastUser]!) + sum(history.slice(inner)) > cap) {
196
+ const next = alignCut(history, inner + 1);
197
+ if (next <= inner || next >= history.length) break;
198
+ inner = next;
199
+ }
200
+ return { keep: [history[lastUser]!, ...history.slice(inner)], drop: [...history.slice(0, lastUser), ...history.slice(lastUser + 1, inner)] };
201
+ }
202
+ if (userIdx.length === 0) {
203
+ // no user turn at all (foreign history): plain message-level cut, pairs still intact
204
+ while (sum(history.slice(start)) > cap) {
205
+ const next = alignCut(history, start + 1);
206
+ if (next <= start || next >= history.length) break;
207
+ start = next;
208
+ }
209
+ }
210
+ return { keep: history.slice(start), drop: history.slice(0, start) };
211
+ }
212
+
213
+ /** A cut on a tool message would orphan results whose call sits in the dropped head: advance
214
+ * past the result run so call + results leave together. Returns history.length when only
215
+ * results remain — the caller stops there and keeps the calling assistant with them. */
216
+ function alignCut(history: Message[], i: number): number {
217
+ let j = i;
218
+ while (j < history.length && history[j]!.role === "tool") j++;
219
+ return j;
220
+ }
221
+
222
+ // ---------- apply ----------
223
+
224
+ /** Rebuild the working history per plan. null = nothing to compact (keep-window found nothing
225
+ * droppable; a native decline with no local fallback) — the caller yields no event then. */
226
+ export async function applyCompaction(history: Message[], plan: CompactionPlan, cfg: RunConfig, ctx: CompactionCtx): Promise<CompactionOutcome | null> {
227
+ const tag = plan.fallbackFrom ? { fallbackFrom: plan.fallbackFrom } : {};
228
+ if (plan.strategy === "provider-native") {
229
+ let out: Message[] | null = null;
230
+ if (ctx.native) {
231
+ try { out = await ctx.native(history, { model: ctx.model, budgetTokens: plan.budgetTokens, trigger: ctx.trigger, signal: ctx.signal }); } catch { out = null; }
232
+ }
233
+ if (out) return { history: out, strategy: "provider-native", ...tag };
234
+ // declined at apply time: re-plan locally (oh-my-pi :1264 keeps a portable local summary
235
+ // rather than strand the history); the local plan is never provider-native — bounded
236
+ const local = planCompaction(history, { ...cfg, compactionStrategy: DEFAULT_COMPACTION_STRATEGY }, { ...ctx, native: undefined });
237
+ if (!local) return null;
238
+ const res = await applyCompaction(history, local, cfg, { ...ctx, native: undefined });
239
+ return res ? { ...res, fallbackFrom: "provider-native" } : null;
240
+ }
241
+ if (plan.strategy === "keep-window") {
242
+ if (plan.drop.length === 0) return null;
243
+ const dropped = plan.drop.reduce((n, m) => n + estimateTokens(ctx.tokenText(m)), 0);
244
+ const marker: Message = {
245
+ id: randomUUID(), role: "system",
246
+ parts: [{ kind: "text", text: `[context compacted (keep-window): ${plan.drop.length} earlier messages, ~${dropped} tokens, removed from the working context]` }],
247
+ parentId: plan.keep[0]?.id ?? null, createdAt: Date.now(),
248
+ };
249
+ return { history: [marker, ...plan.keep], strategy: "keep-window", ...tag };
250
+ }
251
+ if (!ctx.summarize) return null;
252
+ const summary = await ctx.summarize(plan.drop.map((m) => ctx.tokenText(m)));
253
+ const compactMsg: Message = {
254
+ id: randomUUID(), role: "system",
255
+ parts: [{ kind: "text", text: `Summary of earlier conversation:\n${summary}` }],
256
+ parentId: history[0]?.id ?? null, createdAt: Date.now(),
257
+ };
258
+ return { history: [compactMsg, ...plan.keep], strategy: "head-summarize", ...tag };
259
+ }