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,374 @@
1
+ /** ACP agent endpoint (port #15): `rovecode acp` speaks Agent Client Protocol v1
2
+ * over stdio via the official SDK (@zed-industries/agent-client-protocol@0.4.5,
3
+ * Apache-2.0), mapped onto the ONE agentLoop (ADR-003).
4
+ *
5
+ * Mapping:
6
+ * initialize → protocol v1 + capabilities (no loadSession; text + image prompts, port #34)
7
+ * prompt image blocks → ImagePart via imageFromBase64 (the bytes decide the type; the TUI's
8
+ * per-image size cap and ≤8-per-message count cap apply), staged on the
9
+ * session store so the loop's user message carries them (no loop change);
10
+ * any bad block → JSON-RPC invalid params {error} before a run starts
11
+ * session/new → bootRuntime (same stores/tools/config as repl/tui); a sandbox
12
+ * misconfig / unavailable rung in the client's cwd (port #27)
13
+ * → JSON-RPC invalid params {cwd, error: one-line message}
14
+ * session/prompt → agentLoop run; RunEvents stream out as session/update
15
+ * message_update → agent_message_chunk
16
+ * tool_execution_* → tool_call / tool_call_update
17
+ * tool_call_failed → tool_call created directly in "failed" status
18
+ * approval (ADR-005) → session/request_permission; declined/cancelled/unsupported → deny
19
+ * run_end done/budget → stopReason end_turn / max_turn_requests
20
+ * run_end error → JSON-RPC error response (RequestError is the ACP error
21
+ * channel — the SDK converts it to a wire-level response,
22
+ * so the never-throw seam ends at this boundary by design)
23
+ * session/cancel → aborts the run's AbortController (kills the in-flight
24
+ * provider fetch and tool subprocesses mid-turn — port #21),
25
+ * races any outstanding permission ask to deny, then closes
26
+ * the generator → "cancelled"
27
+ */
28
+
29
+ import {
30
+ AgentSideConnection, RequestError, PROTOCOL_VERSION, ndJsonStream,
31
+ type Agent, type Stream,
32
+ type InitializeRequest, type InitializeResponse,
33
+ type AuthenticateRequest, type AuthenticateResponse,
34
+ type NewSessionRequest, type NewSessionResponse,
35
+ type PromptRequest, type PromptResponse, type CancelNotification,
36
+ type ContentBlock, type SessionNotification, type ToolCallContent,
37
+ type ToolKind as AcpToolKind,
38
+ } from "@zed-industries/agent-client-protocol";
39
+ import { basename } from "node:path";
40
+ import { noModelHint } from "../core/voice.ts";
41
+ import { Readable, Writable } from "node:stream";
42
+ import { agentLoop, SteeringQueue } from "../core/loop.ts";
43
+ import { bootRuntime, type Runtime } from "../cli/runtime.ts";
44
+ import { checkImageCount, imageFromBase64 } from "../core/images.ts";
45
+ import { SandboxConfigError } from "../core/sandbox-config.ts";
46
+ import type { ApprovalFn, ImagePart, RunEvent, StreamFn } from "../core/types.ts";
47
+
48
+ export interface AcpOptions {
49
+ /** test/dev override threaded into createRuntime; undefined = provider from env */
50
+ stream?: StreamFn | null;
51
+ /** allow-all permissions: no ACP permission round-trips (ROVECODE_YOLO parity) */
52
+ yolo?: boolean;
53
+ }
54
+
55
+ type SessionUpdate = SessionNotification["update"];
56
+ type RunStatus = "done" | "stopped" | "error" | "budget";
57
+
58
+ interface AcpSessionState {
59
+ rt: Runtime;
60
+ steering: SteeringQueue;
61
+ active: {
62
+ gen: AsyncGenerator<RunEvent>;
63
+ cancelled: boolean;
64
+ /** per-run controller (port #21): session/cancel aborts it, killing the
65
+ * in-flight provider fetch and every ToolContext.signal consumer */
66
+ abort: AbortController;
67
+ /** resolves null when session/cancel lands — raced against an outstanding
68
+ * request_permission so a hung client cannot wedge the session (HIGH-G2) */
69
+ onCancel: Promise<null>;
70
+ fireCancel: () => void;
71
+ } | null;
72
+ permSeq: number;
73
+ }
74
+
75
+ // ---------- translation helpers (RunEvent / house shapes → ACP shapes) ----------
76
+
77
+ export interface PromptParts {
78
+ /** the loop's goal text: text blocks, resource links, inlined embedded text resources */
79
+ goal: string;
80
+ /** port #34: decoded image blocks, in prompt order */
81
+ images: ImagePart[];
82
+ /** the FIRST problem (unsupported/mismatched mime, oversize, more than 8 images) — the caller
83
+ * rejects the whole prompt, nothing is half-sent */
84
+ error?: string;
85
+ }
86
+
87
+ /** Prompt content blocks → goal text + image parts. Baseline blocks (text, resource_link) per
88
+ * spec; embedded text resources are inlined; image blocks decode through imageFromBase64 (the
89
+ * bytes decide the type — a disagreeing mimeType is an error, like the TUI's loader) under the
90
+ * same per-image size cap and per-message count cap as /attach; audio stays unsupported. */
91
+ export function promptParts(blocks: ContentBlock[]): PromptParts {
92
+ const parts: string[] = [];
93
+ const images: ImagePart[] = [];
94
+ let error: string | undefined;
95
+ for (const b of blocks) {
96
+ if (b.type === "text") parts.push(b.text);
97
+ else if (b.type === "resource_link") parts.push(`[resource: ${b.uri}]`);
98
+ else if (b.type === "resource" && "text" in b.resource) {
99
+ parts.push(`<context uri="${b.resource.uri}">\n${b.resource.text}\n</context>`);
100
+ } else if (b.type === "image") {
101
+ const name = b.uri && !b.uri.startsWith("data:") ? basename(b.uri) : undefined; // display name: the file the client sent
102
+ const res = imageFromBase64(b.data, b.mimeType, name !== undefined ? { name } : {});
103
+ if ("error" in res) error ??= res.error; else images.push(res);
104
+ } else parts.push(`[unsupported ${b.type} content omitted]`);
105
+ }
106
+ error ??= checkImageCount(images.length);
107
+ const goal = parts.join("\n");
108
+ return error === undefined ? { goal, images } : { goal, images, error };
109
+ }
110
+
111
+ /** Text-only view of a prompt (image blocks travel separately — promptParts). */
112
+ export function promptText(blocks: ContentBlock[]): string { return promptParts(blocks).goal; }
113
+
114
+ const TOOL_KINDS: Record<string, AcpToolKind> = {
115
+ read: "read", edit: "edit", write: "edit", bash: "execute",
116
+ skill_view: "read", skills_list: "search", mcp_list: "search",
117
+ mcp_call: "other", memory_edit: "other", web_fetch: "fetch",
118
+ };
119
+
120
+ export function kindFor(tool: string): AcpToolKind {
121
+ return TOOL_KINDS[tool] ?? "other";
122
+ }
123
+
124
+ /** Human title for a tool call: name plus the most salient argument. */
125
+ export function titleFor(tool: string, args: unknown): string {
126
+ if (args && typeof args === "object") {
127
+ const a = args as Record<string, unknown>;
128
+ const salient = a.path ?? a.command ?? a.name ?? a.url;
129
+ if (salient !== undefined) return `${tool}: ${String(salient).slice(0, 120)}`;
130
+ }
131
+ return tool;
132
+ }
133
+
134
+ function asRawInput(args: unknown): Record<string, unknown> {
135
+ if (args && typeof args === "object" && !Array.isArray(args)) return args as Record<string, unknown>;
136
+ return args === undefined ? {} : { value: args };
137
+ }
138
+
139
+ function textContent(text: string): ToolCallContent[] {
140
+ return [{ type: "content", content: { type: "text", text } }];
141
+ }
142
+
143
+ /** RunEvent → session/update payload; null for events with no ACP counterpart
144
+ * (run_start, turn_start/end, steer, compaction — lifecycle stays house-side). */
145
+ export function updateForEvent(ev: RunEvent): SessionUpdate | null {
146
+ switch (ev.type) {
147
+ case "message_update":
148
+ return { sessionUpdate: "agent_message_chunk", content: { type: "text", text: ev.delta } };
149
+ case "tool_execution_start":
150
+ return {
151
+ sessionUpdate: "tool_call", toolCallId: ev.callId, title: titleFor(ev.tool, ev.args),
152
+ kind: kindFor(ev.tool), status: "in_progress", rawInput: asRawInput(ev.args),
153
+ };
154
+ case "tool_execution_update":
155
+ return { sessionUpdate: "tool_call_update", toolCallId: ev.callId, content: textContent(ev.note) };
156
+ case "tool_execution_end":
157
+ return {
158
+ sessionUpdate: "tool_call_update", toolCallId: ev.callId,
159
+ status: ev.ok ? "completed" : "failed",
160
+ content: textContent(ev.output), rawOutput: { output: ev.output },
161
+ };
162
+ case "tool_call_failed":
163
+ // calls rejected before execution (permission_denied / truncated / not_found /
164
+ // invalid_args) never got a tool_call create — create directly in failed status
165
+ return {
166
+ sessionUpdate: "tool_call", toolCallId: ev.callId, title: `tool call failed (${ev.reason})`,
167
+ kind: "other", status: "failed", content: textContent(ev.detail),
168
+ };
169
+ default:
170
+ return null;
171
+ }
172
+ }
173
+
174
+ // ---------- the ACP agent ----------
175
+
176
+ export class RovecodeAcpAgent implements Agent {
177
+ private readonly sessions = new Map<string, AcpSessionState>();
178
+
179
+ constructor(private readonly conn: AgentSideConnection, private readonly opts: AcpOptions = {}) {}
180
+
181
+ async initialize(_params: InitializeRequest): Promise<InitializeResponse> {
182
+ // we implement exactly v1: reply with our version; older clients disconnect (spec rule)
183
+ return {
184
+ protocolVersion: PROTOCOL_VERSION,
185
+ agentCapabilities: {
186
+ loadSession: false,
187
+ promptCapabilities: { image: true, audio: false, embeddedContext: true }, // image: port #34 (promptParts)
188
+ },
189
+ authMethods: [],
190
+ };
191
+ }
192
+
193
+ async authenticate(_params: AuthenticateRequest): Promise<AuthenticateResponse> {
194
+ return {}; // no auth methods advertised; provider credentials come from env
195
+ }
196
+
197
+ async newSession(params: NewSessionRequest): Promise<NewSessionResponse> {
198
+ // v1 scope: params.mcpServers is not wired into the runtime — the runtime
199
+ // already loads project-level .rovecode/mcp.json + .mcp.json (port #3)
200
+ let rt: Runtime;
201
+ try {
202
+ rt = await bootRuntime({ cwd: params.cwd, stream: this.opts.stream });
203
+ } catch (e) {
204
+ // port #27: the client's cwd asked for a rung this machine cannot provide (or
205
+ // its sandbox.json is broken) — invalid params carrying the one-line message,
206
+ // the same shape as "unknown session" below (the parameter names something
207
+ // we cannot serve); the agent process stays up for the next session/new
208
+ if (e instanceof SandboxConfigError) throw RequestError.invalidParams({ cwd: params.cwd, error: e.message });
209
+ throw e;
210
+ }
211
+ // live registry: once the user runs `rovecode provider add` / `rovecode auth set`, the next
212
+ // session/new succeeds without restarting the agent process
213
+ const noProvider = rt.noProviderReason();
214
+ if (!rt.stream || noProvider !== null) {
215
+ throw RequestError.authRequired({
216
+ details: noProvider ?? noModelHint("cli"),
217
+ });
218
+ }
219
+ this.sessions.set(rt.sessionId, { rt, steering: rt.steering, active: null, permSeq: 0 }); // port #26: runtime queue → task notes reach the next prompt
220
+ return { sessionId: rt.sessionId };
221
+ }
222
+
223
+ async prompt(params: PromptRequest): Promise<PromptResponse> {
224
+ const s = this.sessions.get(params.sessionId);
225
+ if (!s) throw RequestError.invalidParams({ sessionId: params.sessionId, error: "unknown session" });
226
+ if (s.active) throw RequestError.invalidRequest({ error: "a prompt is already running for this session" });
227
+ const stream = s.rt.stream;
228
+ const noProvider = s.rt.noProviderReason();
229
+ if (!stream || noProvider !== null) throw RequestError.authRequired(noProvider !== null ? { details: noProvider } : undefined);
230
+
231
+ const { goal, images, error } = promptParts(params.prompt);
232
+ // port #34: a bad image block (not png/jpeg/gif/webp, mime disagrees with the bytes, oversize,
233
+ // 9+ images) rejects the prompt as invalid params BEFORE any run — same "nothing staged" outcome
234
+ // as the TUI's error note; the session stays usable for the corrected prompt
235
+ if (error !== undefined) throw RequestError.invalidParams({ error });
236
+ const model = { provider: s.rt.provider?.id ?? "mock", model: s.rt.defaultModel || "default" };
237
+ const def = s.rt.buildDef(model);
238
+ const cfg = s.rt.buildCfg(this.opts.yolo ?? false, this.approvalFor(params.sessionId, s));
239
+ const abort = new AbortController(); // port #21: one controller per run
240
+ s.rt.tasks.bindRun(abort.signal); // port #26: session/cancel also cancels the run's background tasks
241
+ const deps = {
242
+ stream, registry: s.rt.registry, store: s.rt.store,
243
+ tools: s.rt.registry.list().map((t) => t.schema), guard: s.rt.guard,
244
+ hooks: s.rt.hooks, // port #29: .rovecode/hooks.{ts,js} of the session cwd
245
+ cwd: s.rt.cwd, // HIGH-G1: the client's authoritative session cwd reaches ToolContext
246
+ signal: abort.signal, // port #21: session/cancel kills in-flight fetch/tools mid-turn
247
+ };
248
+
249
+ // port #34: the store folds the staged images into the loop's user message when it lands in
250
+ // append() — the same seam TUI /attach uses; the active guard above means no other user entry
251
+ // can slip in between (task steers drain AFTER the goal message, loop.ts)
252
+ if (images.length > 0) s.rt.store.stageAttachments(images);
253
+ const gen = agentLoop(def, goal, {}, cfg, deps, s.steering);
254
+ let fireCancel: () => void = () => {};
255
+ const onCancel = new Promise<null>((resolve) => { fireCancel = () => resolve(null); });
256
+ const active = { gen, cancelled: false, abort, onCancel, fireCancel };
257
+ s.active = active;
258
+ let end: { status: RunStatus; summary: string } | null = null;
259
+ try {
260
+ for await (const ev of gen) {
261
+ if (active.cancelled) break; // session/cancel landed; loop finally aborts tools
262
+ if (ev.type === "run_end") { end = { status: ev.status, summary: ev.summary }; break; }
263
+ const update = updateForEvent(ev);
264
+ if (update) await this.conn.sessionUpdate({ sessionId: params.sessionId, update });
265
+ }
266
+ } finally {
267
+ s.active = null;
268
+ }
269
+
270
+ if (active.cancelled || end === null) return { stopReason: "cancelled" };
271
+ switch (end.status) {
272
+ case "done": return { stopReason: "end_turn" };
273
+ case "budget": return { stopReason: "max_turn_requests" };
274
+ case "stopped": return { stopReason: "cancelled" };
275
+ case "error": throw RequestError.internalError({ details: end.summary });
276
+ }
277
+ }
278
+
279
+ async cancel(params: CancelNotification): Promise<void> {
280
+ const active = this.sessions.get(params.sessionId)?.active;
281
+ if (!active) return;
282
+ active.cancelled = true;
283
+ // port #21: abort the run's controller FIRST — the in-flight provider fetch
284
+ // dies and tool subprocesses are killed mid-turn, so the generator below
285
+ // reaches a settle point quickly instead of finishing the turn.
286
+ active.abort.abort();
287
+ // HIGH-G2: unblock an outstanding request_permission (→ deny) — without
288
+ // this a crashed client / closed popup leaves the run suspended inside the
289
+ // approval await forever and the session permanently "already running".
290
+ active.fireCancel();
291
+ // close the generator as the follow-through: runs the loop's finally blocks.
292
+ // Queues behind any pending next(), so the settle stays cooperative.
293
+ await active.gen.return(undefined as never).then(() => undefined, () => undefined);
294
+ }
295
+
296
+ /** MED-G3: close every session runtime's MCP children. runAcpStdio calls this
297
+ * when stdin closes — without it, `rovecode acp` in an MCP-configured project
298
+ * outlives the client (children keep running until the parent is killed). */
299
+ async shutdown(): Promise<void> {
300
+ const closing: Promise<unknown>[] = [];
301
+ for (const s of this.sessions.values()) {
302
+ s.rt.tasks.cancelAll(); // port #26: background children die with the agent, never after it
303
+ s.rt.bashJobs.dispose(); // #55: background shell jobs die with their session
304
+ closing.push(s.rt.hooks.close()); // port #29: session_close per session runtime
305
+ if (s.rt.mcp) closing.push(s.rt.mcp.close().catch(() => {}));
306
+ }
307
+ await Promise.all(closing);
308
+ }
309
+
310
+ /** ADR-005 approval seam → session/request_permission. Deny is the safe default:
311
+ * declined, cancelled, unknown option, or a client that errors (unsupported). */
312
+ private approvalFor(sessionId: string, s: AcpSessionState): ApprovalFn {
313
+ return async (req) => {
314
+ const toolCallId = `perm-${++s.permSeq}`;
315
+ let outcome: { outcome: "cancelled" } | { outcome: "selected"; optionId: string };
316
+ try {
317
+ const ask = this.conn.requestPermission({
318
+ sessionId,
319
+ toolCall: {
320
+ toolCallId, title: titleFor(req.tool, req.revisedArgs), kind: kindFor(req.tool),
321
+ status: "pending", rawInput: asRawInput(req.revisedArgs),
322
+ },
323
+ options: [
324
+ { optionId: "allow-once", name: "Allow once", kind: "allow_once" },
325
+ { optionId: "allow-always", name: "Allow always", kind: "allow_always" },
326
+ { optionId: "reject-once", name: "Deny", kind: "reject_once" },
327
+ ],
328
+ });
329
+ void ask.then(() => undefined, () => undefined); // raced loser must not surface as unhandled
330
+ // HIGH-G2: session/cancel must be able to interrupt an outstanding ask
331
+ // (client crash / closed popup) — cancel wins the race and maps to deny
332
+ const resp = s.active ? await Promise.race([ask, s.active.onCancel]) : await ask;
333
+ if (resp === null) return "deny"; // cancelled mid-permission
334
+ outcome = resp.outcome;
335
+ } catch {
336
+ return "deny"; // client rejected the request itself → unsupported → deny
337
+ }
338
+ if (outcome.outcome !== "selected") return "deny";
339
+ if (outcome.optionId === "allow-once") return "once";
340
+ if (outcome.optionId === "allow-always") return "always";
341
+ return "deny";
342
+ };
343
+ }
344
+ }
345
+
346
+ // ---------- wiring ----------
347
+
348
+ /** Attach an ACP agent to a bidirectional message stream (tests use an
349
+ * in-process duplex; the CLI uses stdio via runAcpStdio). The agent handle is
350
+ * returned alongside the connection so callers can shutdown() its sessions. */
351
+ export function serveAcp(io: Stream, opts: AcpOptions = {}): { conn: AgentSideConnection; agent: RovecodeAcpAgent } {
352
+ let agent!: RovecodeAcpAgent; // the factory runs synchronously inside the ctor
353
+ const conn = new AgentSideConnection((c) => (agent = new RovecodeAcpAgent(c, opts)), io);
354
+ return { conn, agent };
355
+ }
356
+
357
+ /** `rovecode acp`: serve ACP v1 over stdio until the client closes stdin.
358
+ * stdout carries protocol frames only — nothing else may print there. */
359
+ export function runAcpStdio(opts: AcpOptions = {}): Promise<void> {
360
+ // node:stream/web and lib.dom stream types diverge on getReader() overloads;
361
+ // the runtime objects are the same web streams, so bridge via unknown
362
+ const io = ndJsonStream(
363
+ Writable.toWeb(process.stdout) as unknown as WritableStream<Uint8Array>,
364
+ Readable.toWeb(process.stdin) as unknown as ReadableStream<Uint8Array>,
365
+ );
366
+ const { agent } = serveAcp(io, opts);
367
+ return new Promise<void>((resolve) => {
368
+ // MED-G3: reap MCP children before resolving, or the process outlives a
369
+ // closed editor in MCP-configured projects (children hold the event loop)
370
+ const done = () => { void agent.shutdown().then(() => resolve(), () => resolve()); };
371
+ process.stdin.once("end", done);
372
+ process.stdin.once("close", done);
373
+ });
374
+ }
@@ -0,0 +1,122 @@
1
+ /** `rovecode auth login <provider>` and the `rovecode auth list` renderer (port #66). All of the auth
2
+ * CLI's OAuth logic lives here; main.ts only dispatches.
3
+ *
4
+ * login: github-copilot (GitHub device code), openrouter (PKCE + loopback callback), openai (device
5
+ * code) — src/providers/oauth/registry.ts. The flow talks to the terminal only through notices
6
+ * rendered here: the device code + URL to open, the auth URL + callback address, progress. The
7
+ * credential goes to the credentials store (providers/auth.ts, `type: "oauth"`); the final line
8
+ * names the file and the expiry. `anthropic` is refused with the owner-decision note. Ctrl-C aborts
9
+ * the flow (exit 130). Nothing here prints, throws or logs a token: notices carry none by
10
+ * construction (oauth/common.ts) and the only value echoed from a credential is its expiry.
11
+ *
12
+ * list: one row per stored entry — provider, kind (api | oauth), key name, redacted prefix, and
13
+ * for oauth the expiry (`expires <ISO>`, `EXPIRED <ISO>`, or `never expires`). */
14
+
15
+ import { credentialsPath, listProviders, saveOAuthCredential, type ProviderListing, type StoredOAuthCredential } from "../providers/auth.ts";
16
+ import type { OAuthDeps, OAuthNotice, OAuthProvider } from "../providers/oauth/common.ts";
17
+ import { OAUTH_PROVIDER_IDS, OAUTH_REFUSED, defaultOAuthDeps, oauthProvider } from "../providers/oauth/registry.ts";
18
+
19
+ export const AUTH_LOGIN_USAGE = `usage: rovecode auth login <${OAUTH_PROVIDER_IDS.join("|")}>`;
20
+
21
+ export interface AuthLoginDeps {
22
+ out: (line: string) => void;
23
+ err: (line: string) => void;
24
+ /** provider lookup (tests inject fake-endpoint instances); default: the registry */
25
+ provider?: (id: string) => OAuthProvider | undefined;
26
+ /** network/clock/timer overrides for the flow */
27
+ oauth?: Partial<OAuthDeps>;
28
+ /** Ctrl-C */
29
+ signal?: AbortSignal;
30
+ /** credential sink; default: providers/auth.ts saveOAuthCredential */
31
+ save?: (id: string, cred: StoredOAuthCredential) => void;
32
+ }
33
+
34
+ /** `expires 2026-09-03T12:00:00.000Z` | `EXPIRED …` | `never expires` (MAX_SAFE_INTEGER / beyond Date's range).
35
+ * Never throws: a value below Date's range (or NaN) renders as EXPIRED instead of a RangeError (#66 fix). */
36
+ export function expiryText(expires: number, now: number = Date.now()): string {
37
+ if (expires >= Number.MAX_SAFE_INTEGER || expires > 8.64e15) return "never expires";
38
+ if (!(expires >= -8.64e15)) return "EXPIRED (invalid expiry)";
39
+ const iso = new Date(expires).toISOString();
40
+ return expires <= now ? `EXPIRED ${iso}` : `expires ${iso}`;
41
+ }
42
+
43
+ /** Rows for `rovecode auth list`. Secrets never enter: the entries are already redacted. */
44
+ export function formatAuthList(entries: ProviderListing[] = listProviders(), now: number = Date.now()): string[] {
45
+ return entries.map((e) => {
46
+ const tail = e.kind === "oauth" && e.expires !== undefined ? ` ${expiryText(e.expires, now)}` : "";
47
+ return `${e.provider.padEnd(14)} ${e.kind.padEnd(6)} ${e.keyName.padEnd(24)} ${e.redacted}${tail}`;
48
+ });
49
+ }
50
+
51
+ export function printAuthList(): void {
52
+ const rows = formatAuthList();
53
+ if (rows.length === 0) {
54
+ console.log(`no stored credentials (${credentialsPath()}) — run: rovecode auth set <provider> | rovecode auth login <provider>`);
55
+ return;
56
+ }
57
+ for (const row of rows) console.log(row);
58
+ }
59
+
60
+ /** What the terminal shows for a flow notice (indented by the caller). */
61
+ export function describeNotice(n: OAuthNotice): string[] {
62
+ switch (n.type) {
63
+ case "device_code":
64
+ return [
65
+ `open ${n.verificationUri}`,
66
+ `enter ${n.userCode}`,
67
+ `waiting for authorization — polling every ${n.intervalSeconds}s, up to ${Math.max(1, Math.round(n.expiresInSeconds / 60))} min (Ctrl-C cancels)`,
68
+ ];
69
+ case "auth_url":
70
+ return [
71
+ `open ${n.url}`,
72
+ `waiting for the browser to return to ${n.callbackUrl} (loopback — the browser must run on this machine; Ctrl-C cancels)`,
73
+ ];
74
+ case "progress":
75
+ return [n.message];
76
+ }
77
+ }
78
+
79
+ /** Run one login. Returns the exit code: 0 stored · 1 refused/unknown/failed · 130 cancelled. */
80
+ export async function runAuthLogin(id: string, deps: AuthLoginDeps): Promise<number> {
81
+ // the refusals belong to the production registry; an injected `provider` (tests driving a flow against a
82
+ // fake server, or a build that has the missing wire) replaces the registry, refusals included
83
+ const refusal = deps.provider === undefined ? OAUTH_REFUSED[id] : undefined;
84
+ if (refusal !== undefined) {
85
+ deps.err(`rovecode auth login ${id}: refused — ${refusal}`);
86
+ return 1;
87
+ }
88
+ const provider = (deps.provider ?? oauthProvider)(id);
89
+ if (!provider) {
90
+ if (id.length > 0) deps.err(`error: no OAuth login for "${id}"`);
91
+ deps.err(AUTH_LOGIN_USAGE);
92
+ return 1;
93
+ }
94
+ const signal = deps.signal ?? new AbortController().signal;
95
+ const oauth: OAuthDeps = { ...defaultOAuthDeps(), ...deps.oauth };
96
+ deps.out(`rovecode auth login ${id} — ${provider.label}`);
97
+ try {
98
+ const cred = await provider.login({ notify: (n) => { for (const line of describeNotice(n)) deps.out(` ${line}`); }, signal }, oauth);
99
+ (deps.save ?? saveOAuthCredential)(id, cred);
100
+ deps.out(`stored OAuth token for ${id} in ${credentialsPath()} (${expiryText(cred.expires, oauth.now())})`);
101
+ return 0;
102
+ } catch (e) {
103
+ if (signal.aborted) {
104
+ deps.err("login cancelled");
105
+ return 130;
106
+ }
107
+ deps.err(`error: ${e instanceof Error ? e.message : String(e)}`);
108
+ return 1;
109
+ }
110
+ }
111
+
112
+ /** argv entry (main.ts `auth login …`): console output, SIGINT → abort. */
113
+ export async function cmdAuthLogin(args: string[]): Promise<number> {
114
+ const ac = new AbortController();
115
+ const onSigint = () => ac.abort();
116
+ process.once("SIGINT", onSigint);
117
+ try {
118
+ return await runAuthLogin(args[0] ?? "", { out: (l) => console.log(l), err: (l) => console.error(l), signal: ac.signal });
119
+ } finally {
120
+ process.removeListener("SIGINT", onSigint);
121
+ }
122
+ }