moi-computer 0.9.0 → 0.9.1-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/client/assets/hermes.png +0 -0
  2. package/client/components/shared/IconGhost.tsx +15 -18
  3. package/client/components/ui/button.tsx +2 -2
  4. package/client/components/ui/hover-card.tsx +1 -1
  5. package/client/components/ui/popover.tsx +3 -1
  6. package/client/features/chat/ChatEmptyState.tsx +25 -7
  7. package/client/features/chat/ChatPanel.tsx +70 -28
  8. package/client/features/chat/ChatPopup.tsx +3 -2
  9. package/client/features/chat/ChatPromptBubbles.tsx +1 -1
  10. package/client/features/chat/MarkdownContent.tsx +1 -1
  11. package/client/features/chat/attachment-staging.ts +153 -0
  12. package/client/features/chat/chat-send.ts +55 -0
  13. package/client/features/chat/chat-store.ts +32 -8
  14. package/client/features/chat/composer/ChatComposer.tsx +190 -77
  15. package/client/features/chat/{ModelPicker.tsx → composer/ModelPicker.tsx} +29 -25
  16. package/client/features/chat/composer/banners/ComposerBanner.tsx +1 -1
  17. package/client/features/chat/composer/banners/WorkspaceAgentAvailabilityBanner.tsx +4 -13
  18. package/client/features/chat/{model-order.ts → composer/model-order.ts} +16 -0
  19. package/client/features/chat/composer/useWorkspaceComposerState.tsx +9 -4
  20. package/client/features/chat/tool-group/format/claude.ts +48 -0
  21. package/client/features/chat/tool-group/format/codex.ts +126 -0
  22. package/client/features/chat/tool-group/format/hermes.ts +68 -0
  23. package/client/features/chat/tool-group/format/index.ts +34 -0
  24. package/client/features/chat/tool-group/format/mcp.ts +64 -0
  25. package/client/features/chat/tool-group/format/openclaw.ts +116 -0
  26. package/client/features/chat/tool-group/format/shared.ts +49 -0
  27. package/client/features/chat/useChat.ts +5 -10
  28. package/client/features/drawings/DrawingLayer.tsx +49 -0
  29. package/client/features/drawings/DrawingToolbar.tsx +95 -0
  30. package/client/features/drawings/annotation-availability.ts +10 -0
  31. package/client/features/drawings/capture-element.ts +45 -0
  32. package/client/features/drawings/useChatAnnotation.ts +222 -0
  33. package/client/features/drawings/useDrawingLayer.ts +758 -0
  34. package/client/features/drawings/useViewBuilderSketch.ts +151 -0
  35. package/client/features/home/workspace-presentation.tsx +6 -2
  36. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +12 -6
  37. package/client/features/scratchpad/ScratchpadControls.tsx +19 -5
  38. package/client/features/views/ViewBuilder.tsx +224 -0
  39. package/client/features/views/api.ts +1 -0
  40. package/client/features/views/useViewBuilderActions.ts +24 -3
  41. package/client/features/views/useViewBuilderDrafts.ts +66 -0
  42. package/client/features/widgets/Widgets.tsx +23 -39
  43. package/client/features/workspace/CustomizePanel.tsx +1 -1
  44. package/client/features/workspace/WorkspaceScreen.tsx +157 -57
  45. package/client/features/workspace/WorkspaceTabs.tsx +3 -3
  46. package/client/features/workspace/useFitsSplitLayout.ts +14 -8
  47. package/client/index.css +8 -0
  48. package/client/store/ui.ts +19 -0
  49. package/client/theme.css +33 -8
  50. package/dist/chunk-3becmq75.js +81 -0
  51. package/dist/{chunk-kkj86722.js → chunk-6w6j9g4b.js} +78 -78
  52. package/dist/{chunk-xeyxk7ep.js → chunk-8ew39cvq.js} +4 -4
  53. package/dist/chunk-c8gtrjwp.js +1 -0
  54. package/dist/{chunk-2vaafjp4.js → chunk-pp62fnxh.js} +1 -1
  55. package/dist/{chunk-35fq49qa.js → chunk-sxc24vfp.js} +1 -1
  56. package/dist/{chunk-3b3rkjet.js → chunk-v964b5g7.js} +1 -1
  57. package/dist/chunk-zx33ts9d.css +1 -0
  58. package/dist/hermes-pznd63x9.png +0 -0
  59. package/dist/index.html +1 -1
  60. package/lib/format.ts +1 -1
  61. package/lib/themes.ts +8 -8
  62. package/lib/types.ts +8 -1
  63. package/lib/workspace-types.ts +2 -1
  64. package/package.json +2 -1
  65. package/server/api.ts +21 -2
  66. package/server/cli.ts +188 -3
  67. package/server/harness/README.md +64 -17
  68. package/server/harness/acp/adapter.ts +220 -0
  69. package/server/harness/acp/archived.ts +88 -0
  70. package/server/harness/acp/client.ts +328 -0
  71. package/server/harness/acp/discovery.ts +130 -0
  72. package/server/harness/acp/run-durations.ts +68 -0
  73. package/server/harness/acp/session.ts +788 -0
  74. package/server/harness/acp/wire.ts +132 -0
  75. package/server/harness/executable.ts +15 -1
  76. package/server/harness/hermes/NOTES.md +815 -0
  77. package/server/harness/hermes/discovery.ts +155 -0
  78. package/server/harness/hermes/index.ts +155 -0
  79. package/server/harness/hermes/models.ts +79 -0
  80. package/server/harness/registry.ts +3 -1
  81. package/server/view-builders.ts +4 -2
  82. package/server/workspace-import.ts +30 -1
  83. package/client/features/chat/tool-group/format.ts +0 -384
  84. package/client/features/views/ViewBuilderTab.tsx +0 -152
  85. package/dist/chunk-gt7n06ef.js +0 -1
  86. package/dist/chunk-ty1sqbmn.js +0 -80
  87. package/dist/chunk-yz6wd5vc.css +0 -1
@@ -0,0 +1,220 @@
1
+ // ACP wire (layer 1) → moi display format (layer 2). Pure mapping, no I/O.
2
+ //
3
+ // ACP streams *chunks*, not discrete messages: assistant text and thinking
4
+ // arrive token-by-token with no message boundary, and tool calls interleave.
5
+ // The shape moi renders is turn-based, so this module owns the accumulation
6
+ // rule: consecutive text/thought chunks build one assistant turn, and a tool
7
+ // call both closes the open assistant turn and becomes a turn of its own —
8
+ // the same item-per-turn model the Codex adapter produces.
9
+
10
+ import { splitAttachmentNote } from '@/lib/attachment-note'
11
+ import type { Part, ToolCall, ToolState, Turn, TurnMeta } from '@/lib/format'
12
+ import { stripMoiContext } from '@/lib/moi-context'
13
+
14
+ import {
15
+ type AcpSessionListEntry,
16
+ type ToolCallStatus,
17
+ type ToolCallUpdate,
18
+ type Usage,
19
+ toolContentToText
20
+ } from './wire'
21
+ import type { SessionInfo } from '@/lib/types'
22
+
23
+ export type AcpProviderId = NonNullable<ToolCall['provider']>
24
+
25
+ export function toolStatusToState(status: ToolCallStatus | undefined): ToolState {
26
+ switch (status) {
27
+ case 'completed':
28
+ return 'success'
29
+ case 'failed':
30
+ return 'error'
31
+ case 'in_progress':
32
+ return 'running'
33
+ default:
34
+ // ACP defaults an omitted status to `pending`; moi renders that as a
35
+ // spinner-less card, so treat a started call as running instead.
36
+ return 'running'
37
+ }
38
+ }
39
+
40
+ // Tool-call turn ids must be stable across the `tool_call` → `tool_call_update`
41
+ // pair (upsert-by-id) and across live-vs-replay, where the backend may hand out
42
+ // different ids for the same call (Hermes does — see ../hermes/NOTES.md §3.4).
43
+ export function toolTurnId(sessionId: string, toolCallId: string): string {
44
+ return `${sessionId}:tool:${toolCallId}`
45
+ }
46
+
47
+ export function assistantTurnId(sessionId: string, runIndex: number): string {
48
+ return `${sessionId}:msg:${runIndex}`
49
+ }
50
+
51
+ // ACP tool calls carry a semantic `kind` and a human `title` instead of a raw
52
+ // function name. Prefer the title (it is already display-ready, e.g.
53
+ // "terminal: echo hi"); only the opening `tool_call` carries one, so the name
54
+ // already on the card outranks the bare `kind` a `tool_call_update` falls back
55
+ // to — otherwise the label degrades from "terminal: echo hi" to "execute"
56
+ // the moment the call completes.
57
+ export function toolCallName(update: ToolCallUpdate, previousName?: string): string {
58
+ return update.title?.trim() || previousName || update.kind || 'tool'
59
+ }
60
+
61
+ export function acpToolCallToTurn(input: {
62
+ update: ToolCallUpdate
63
+ sessionId: string
64
+ provider: AcpProviderId
65
+ previous?: Turn
66
+ timestamp?: string
67
+ }): Turn {
68
+ const { update, sessionId, provider, previous } = input
69
+ const prevCall =
70
+ previous?.parts.find((p): p is Extract<Part, { type: 'tool-call' }> => p.type === 'tool-call')
71
+ ?.call ?? undefined
72
+
73
+ const text = toolContentToText(update.content)
74
+ const locations = update.locations?.map(l => l.path).filter(Boolean) ?? []
75
+ const call: ToolCall = {
76
+ toolCallId: update.toolCallId,
77
+ name: toolCallName(update, prevCall?.name),
78
+ caller: 'model',
79
+ provider,
80
+ state: update.status ? toolStatusToState(update.status) : (prevCall?.state ?? 'running'),
81
+ input: update.rawInput ?? prevCall?.input ?? (locations.length ? { path: locations[0] } : {}),
82
+ ...(locations.length
83
+ ? { sidecar: { locations } }
84
+ : prevCall?.sidecar
85
+ ? { sidecar: prevCall.sidecar }
86
+ : {})
87
+ }
88
+ // `tool_call` announces with a preview blurb and `tool_call_update` carries
89
+ // the result; keep whichever text we have most recently seen.
90
+ const output = text || (typeof prevCall?.output === 'string' ? prevCall.output : '')
91
+ if (output) call.output = output
92
+ if (call.state === 'error' && output) call.errorText = output
93
+
94
+ return {
95
+ id: toolTurnId(sessionId, update.toolCallId),
96
+ role: 'assistant',
97
+ origin: { kind: 'user-input' },
98
+ parts: [{ type: 'tool-call', call }],
99
+ timestamp: previous?.timestamp ?? input.timestamp ?? new Date().toISOString()
100
+ }
101
+ }
102
+
103
+ export function acpUsageToTurnMeta(usage: Usage | null | undefined): TurnMeta['usage'] | undefined {
104
+ if (!usage) return undefined
105
+ const { inputTokens, outputTokens, totalTokens } = usage
106
+ if (inputTokens === undefined && outputTokens === undefined && totalTokens === undefined) {
107
+ return undefined
108
+ }
109
+ return { inputTokens, outputTokens, totalTokens }
110
+ }
111
+
112
+ // Replayed `user_message_chunk` text is the persisted prompt verbatim: the
113
+ // typed text plus everything the sender appended to it — the attachment note
114
+ // and the `<moi-context>` envelope (see sendAcpMessage in ./session.ts). Fold
115
+ // that machinery back out so a reloaded bubble matches the live one. Envelope
116
+ // first: it is appended after the note, and `splitAttachmentNote` parses the
117
+ // note as the text's tail. An envelope-only block (an attachment-only send
118
+ // carries the envelope as its lone text) folds to no parts — the caller skips
119
+ // the bubble entirely.
120
+ export function replayedUserParts(raw: string): Part[] {
121
+ const split = splitAttachmentNote(stripMoiContext(raw))
122
+ const parts: Part[] = split.files.map(f => ({
123
+ type: 'file',
124
+ mediaType: 'application/octet-stream',
125
+ url: f.path,
126
+ filename: f.filename
127
+ }))
128
+ if (split.text.trim()) parts.push({ type: 'text', text: split.text })
129
+ return parts
130
+ }
131
+
132
+ export function acpSessionToSessionInfo(entry: AcpSessionListEntry): SessionInfo {
133
+ const updated = entry.updatedAt ? Date.parse(entry.updatedAt) : NaN
134
+ return {
135
+ sessionId: entry.sessionId,
136
+ summary: entry.title?.trim() || 'Untitled session',
137
+ lastModified: Number.isNaN(updated) ? 0 : updated,
138
+ ...(entry.cwd ? { cwd: entry.cwd } : {})
139
+ }
140
+ }
141
+
142
+ // Accumulates chunk streams into assistant turns. One instance per live
143
+ // session (and one per replay pass) — see the module header for the rule.
144
+ export class AssistantTurnAccumulator {
145
+ private text = ''
146
+ private reasoning = ''
147
+ private runIndex = 0
148
+ private startedAt: string | null = null
149
+
150
+ constructor(
151
+ private sessionId: string,
152
+ private model?: string,
153
+ private provider?: string
154
+ ) {}
155
+
156
+ setModel(model: string | undefined) {
157
+ this.model = model
158
+ }
159
+
160
+ get isOpen(): boolean {
161
+ return this.text.length > 0 || this.reasoning.length > 0
162
+ }
163
+
164
+ // The id the open run will be emitted under. Also used as the preview's
165
+ // `apiMessageId`, so the client clears the preview when the turn lands.
166
+ get currentId(): string {
167
+ return assistantTurnId(this.sessionId, this.runIndex)
168
+ }
169
+
170
+ append(kind: 'text' | 'reasoning', delta: string) {
171
+ if (!delta) return
172
+ if (!this.startedAt) this.startedAt = new Date().toISOString()
173
+ if (kind === 'text') this.text += delta
174
+ else this.reasoning += delta
175
+ }
176
+
177
+ // Snapshot of the open run as preview blocks (cumulative text, never diffs).
178
+ previewBlocks(): { index: number; kind: 'text' | 'reasoning'; text: string }[] {
179
+ const blocks: { index: number; kind: 'text' | 'reasoning'; text: string }[] = []
180
+ if (this.reasoning)
181
+ blocks.push({ index: blocks.length, kind: 'reasoning', text: this.reasoning })
182
+ if (this.text) blocks.push({ index: blocks.length, kind: 'text', text: this.text })
183
+ return blocks
184
+ }
185
+
186
+ // Close the open run and return its Turn, or null when nothing accumulated.
187
+ // `meta` is folded in so the final turn of a prompt carries usage/stopReason.
188
+ flush(meta?: TurnMeta): Turn | null {
189
+ if (!this.isOpen) return null
190
+ const parts: Part[] = []
191
+ if (this.reasoning) parts.push({ type: 'reasoning', text: this.reasoning })
192
+ if (this.text) parts.push({ type: 'text', text: this.text })
193
+ const turn: Turn = {
194
+ id: this.currentId,
195
+ role: 'assistant',
196
+ origin: { kind: 'user-input' },
197
+ parts,
198
+ timestamp: this.startedAt ?? new Date().toISOString(),
199
+ meta: {
200
+ ...(this.model ? { model: this.model } : {}),
201
+ ...(this.provider ? { provider: this.provider } : {}),
202
+ apiMessageId: this.currentId,
203
+ ...meta
204
+ }
205
+ }
206
+ this.text = ''
207
+ this.reasoning = ''
208
+ this.startedAt = null
209
+ this.runIndex++
210
+ return turn
211
+ }
212
+
213
+ // Abandon the open run without emitting (used when a replay pass restarts).
214
+ reset() {
215
+ this.text = ''
216
+ this.reasoning = ''
217
+ this.startedAt = null
218
+ this.runIndex = 0
219
+ }
220
+ }
@@ -0,0 +1,88 @@
1
+ // Archived-chat bookkeeping for ACP backends.
2
+ //
3
+ // ACP specifies `session/delete`, but agents do not implement it — Hermes 0.20
4
+ // answers it with JSON-RPC -32601 "Method not found", and its per-session
5
+ // archive flag is reachable only through the `hermes serve` HTTP routes, a
6
+ // daemon moi deliberately does not run. So moi hides archived chats on its own
7
+ // side, exactly like the Claude Code harness (which tags a session
8
+ // `moi:archived` and filters the list rather than deleting anything).
9
+ //
10
+ // Nothing is destroyed: the chat stays in the backend's own store and remains
11
+ // visible to that agent's CLI, which is the correct boundary — moi hides a chat
12
+ // from moi, not from the user's agent.
13
+ //
14
+ // Stored OUTSIDE the workspace (no repo churn) in ONE global JSON file in moi's
15
+ // data dir, keyed by workspace path then session id:
16
+ // { "<workspacePath>": ["<sessionId>", …] }
17
+ // Path (not registry id) is the key so the list survives re-registration, the
18
+ // same choice session-config.ts makes.
19
+ import { mkdir, rename } from 'node:fs/promises'
20
+ import { join } from 'node:path'
21
+
22
+ import { DATA_DIR } from '../../data-dir'
23
+
24
+ type Store = Record<string, string[]>
25
+
26
+ export const DEFAULT_ARCHIVED_SESSIONS_PATH = join(DATA_DIR, 'acp-archived-sessions.json')
27
+
28
+ let storePath = DEFAULT_ARCHIVED_SESSIONS_PATH
29
+
30
+ // Test seam: point the store at a scratch file (mirrors setSessionConfigPath).
31
+ export function setArchivedSessionsPath(path: string): void {
32
+ storePath = path
33
+ }
34
+
35
+ async function readStore(): Promise<Store> {
36
+ try {
37
+ const parsed = JSON.parse(await Bun.file(storePath).text())
38
+ return parsed && typeof parsed === 'object' ? (parsed as Store) : {}
39
+ } catch {
40
+ return {}
41
+ }
42
+ }
43
+
44
+ async function writeStore(store: Store): Promise<void> {
45
+ await mkdir(join(storePath, '..'), { recursive: true })
46
+ const tmp = `${storePath}.${process.pid}.tmp`
47
+ await Bun.write(tmp, JSON.stringify(store, null, 2))
48
+ await rename(tmp, storePath)
49
+ }
50
+
51
+ // Serialize read-modify-write so concurrent archive calls can't clobber the
52
+ // single shared file (last writer would otherwise drop the other's update).
53
+ let writeChain: Promise<unknown> = Promise.resolve()
54
+ function locked<T>(fn: () => Promise<T>): Promise<T> {
55
+ const run = writeChain.then(fn, fn)
56
+ writeChain = run.catch(() => {})
57
+ return run
58
+ }
59
+
60
+ export async function archivedAcpSessions(workspacePath: string): Promise<Set<string>> {
61
+ return locked(async () => new Set((await readStore())[workspacePath] ?? []))
62
+ }
63
+
64
+ export async function archiveAcpSession(workspacePath: string, sessionId: string): Promise<void> {
65
+ if (!sessionId) return
66
+ await locked(async () => {
67
+ const store = await readStore()
68
+ const ids = store[workspacePath] ?? []
69
+ if (ids.includes(sessionId)) return
70
+ store[workspacePath] = [...ids, sessionId]
71
+ await writeStore(store)
72
+ })
73
+ }
74
+
75
+ // Not wired to a route yet — chats are archived, never unarchived, in the UI.
76
+ // Kept because the store is only a hide, so undoing it is a one-liner and the
77
+ // asymmetry would otherwise look like data loss.
78
+ export async function unarchiveAcpSession(workspacePath: string, sessionId: string): Promise<void> {
79
+ await locked(async () => {
80
+ const store = await readStore()
81
+ const ids = store[workspacePath]
82
+ if (!ids?.includes(sessionId)) return
83
+ const next = ids.filter(id => id !== sessionId)
84
+ if (next.length) store[workspacePath] = next
85
+ else delete store[workspacePath]
86
+ await writeStore(store)
87
+ })
88
+ }
@@ -0,0 +1,328 @@
1
+ // Long-lived ACP client, one process per workspace.
2
+ //
3
+ // ACP agents are JSON-RPC 2.0 servers over stdio (newline-delimited JSON) that
4
+ // serve every session of one workspace: sessions carry their own cwd, but env
5
+ // is process-level, so per-workspace env injection (moi's `workspaceEnv`)
6
+ // forces one process per workspace — same frozen-at-spawn semantics as the
7
+ // Codex app-server and the Claude Code subprocess.
8
+ //
9
+ // Provider-agnostic: `AcpSpawnSpec` says what to spawn, everything else here
10
+ // is protocol. See ./wire.ts for the message shapes.
11
+ import type { InitializeResponse, RequestPermissionRequest } from './wire'
12
+
13
+ import { debug } from '../../debug'
14
+ import { tapWire } from '../debug'
15
+ import { resolveWorkspaceEnv } from '../../workspace-env'
16
+
17
+ const REQUEST_TIMEOUT_MS = 120_000
18
+
19
+ // `session/prompt` stays pending for the whole agent turn by design — a turn
20
+ // can legitimately run for many minutes. Timing it out would reject the call
21
+ // while the backend keeps going, then let the next send start a second turn
22
+ // against the same session (overlapping runs, corrupted transcript). A dead
23
+ // agent still settles these: readLoop rejects everything pending on exit, and
24
+ // `session/cancel` resolves the turn with stopReason `cancelled`.
25
+ const UNBOUNDED_METHODS = new Set(['session/prompt'])
26
+
27
+ // null = never time this call out.
28
+ export function rpcTimeoutMs(method: string): number | null {
29
+ return UNBOUNDED_METHODS.has(method) ? null : REQUEST_TIMEOUT_MS
30
+ }
31
+
32
+ type Json = Record<string, unknown>
33
+ type NotificationListener = (method: string, params: Json) => void
34
+
35
+ export type AcpSpawnSpec = {
36
+ // Provider id, used for log prefixes and the wire tap scope.
37
+ provider: string
38
+ // Absolute path to the agent binary (already resolved through PATH).
39
+ command: string
40
+ args: readonly string[]
41
+ workspacePath: string
42
+ // Extra env layered over process env + the workspace env.
43
+ env?: Record<string, string>
44
+ }
45
+
46
+ export type AcpClient = {
47
+ rpc: <T>(method: string, params?: Json) => Promise<T>
48
+ notify: (method: string, params?: Json) => void
49
+ onNotification: (l: NotificationListener) => () => void
50
+ isAlive: () => boolean
51
+ workspacePath: string
52
+ // Null until the initialize handshake resolves.
53
+ initializeResult: InitializeResponse | null
54
+ }
55
+
56
+ export type AcpProcessInfo = {
57
+ running: boolean
58
+ pid?: number
59
+ binary: string | null
60
+ agent?: string
61
+ }
62
+
63
+ type ClientRecord = {
64
+ client: AcpClient
65
+ proc: ReturnType<typeof Bun.spawn>
66
+ }
67
+
68
+ const clients = new Map<string, Promise<ClientRecord>>() // key: workspacePath
69
+
70
+ // Client capabilities moi actually honours. We do NOT advertise fs access:
71
+ // ACP agents that can't read files themselves would delegate to us, and moi's
72
+ // agents run with full workspace access already. Terminal is likewise the
73
+ // agent's own business.
74
+ const CLIENT_CAPABILITIES = { fs: { readTextFile: false, writeTextFile: false } }
75
+
76
+ async function startClient(spec: AcpSpawnSpec): Promise<ClientRecord> {
77
+ const { provider, command, args, workspacePath } = spec
78
+ const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
79
+ const proc = Bun.spawn([command, ...args], {
80
+ cwd: workspacePath,
81
+ stdin: 'pipe',
82
+ stdout: 'pipe',
83
+ stderr: 'pipe',
84
+ // MOI_AGENT marks the agent's shells as agent-driven for the moi CLI
85
+ // (see agent-caller.ts).
86
+ env: { ...process.env, ...workspaceEnv, ...spec.env, MOI_AGENT: '1' }
87
+ })
88
+
89
+ let alive = true
90
+ let nextId = 1
91
+ const pending = new Map<
92
+ number,
93
+ { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: Timer | null }
94
+ >()
95
+ const listeners = new Set<NotificationListener>()
96
+
97
+ function send(obj: Json) {
98
+ tapWire(workspacePath, 'send', obj)
99
+ proc.stdin.write(JSON.stringify(obj) + '\n')
100
+ proc.stdin.flush()
101
+ }
102
+
103
+ function rpc<T>(method: string, params: Json = {}): Promise<T> {
104
+ if (!alive) return Promise.reject(new Error(`${provider} agent not running`))
105
+ const id = nextId++
106
+ send({ jsonrpc: '2.0', id, method, params })
107
+ return new Promise<T>((resolve, reject) => {
108
+ const timeoutMs = rpcTimeoutMs(method)
109
+ const timer =
110
+ timeoutMs === null
111
+ ? null
112
+ : setTimeout(() => {
113
+ pending.delete(id)
114
+ reject(new Error(`${provider} rpc timeout: ${method}`))
115
+ }, timeoutMs)
116
+ pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer })
117
+ })
118
+ }
119
+
120
+ function fanout(method: string, params: Json) {
121
+ for (const l of listeners) {
122
+ try {
123
+ l(method, params)
124
+ } catch (err) {
125
+ console.error(`[${provider}] notification listener threw`, err)
126
+ }
127
+ }
128
+ }
129
+
130
+ // Server→client requests MUST be answered or the turn hangs. Sessions run in
131
+ // the backend's no-prompt mode (see session.ts), so permission requests
132
+ // should not occur — approve defensively if one does, matching moi's
133
+ // bypass-permissions trust model. Everything else is refused as unsupported.
134
+ function answerServerRequest(msg: Json) {
135
+ const method = msg.method as string
136
+ if (method === 'session/request_permission') {
137
+ const params = (msg.params ?? {}) as RequestPermissionRequest
138
+ const options = params.options ?? []
139
+ const allow = options.find(o => o.kind?.startsWith('allow')) ?? options[0]
140
+ send({
141
+ jsonrpc: '2.0',
142
+ id: msg.id,
143
+ result: allow
144
+ ? { outcome: { outcome: 'selected', optionId: allow.optionId } }
145
+ : { outcome: { outcome: 'cancelled' } }
146
+ })
147
+ return
148
+ }
149
+ send({
150
+ jsonrpc: '2.0',
151
+ id: msg.id,
152
+ error: { code: -32601, message: `moi does not handle ${method}` }
153
+ })
154
+ }
155
+
156
+ function handleLine(line: string) {
157
+ if (!line.trim()) return
158
+ let msg: Json
159
+ try {
160
+ msg = JSON.parse(line) as Json
161
+ } catch {
162
+ // ACP reserves stdout for JSON-RPC, but a misbehaving agent can still
163
+ // print — drop the line rather than killing the connection.
164
+ return
165
+ }
166
+ tapWire(workspacePath, 'recv', msg)
167
+ if ('id' in msg && 'method' in msg) {
168
+ answerServerRequest(msg)
169
+ } else if ('id' in msg) {
170
+ const p = pending.get(msg.id as number)
171
+ if (!p) return
172
+ pending.delete(msg.id as number)
173
+ if (p.timer) clearTimeout(p.timer)
174
+ if ('error' in msg) {
175
+ const e = msg.error as { message?: string } | undefined
176
+ p.reject(new Error(e?.message ?? JSON.stringify(msg.error)))
177
+ } else {
178
+ p.resolve(msg.result)
179
+ }
180
+ } else if (typeof msg.method === 'string') {
181
+ fanout(msg.method, (msg.params ?? {}) as Json)
182
+ }
183
+ }
184
+
185
+ async function readLoop() {
186
+ const reader = (proc.stdout as ReadableStream<Uint8Array>).getReader()
187
+ const decoder = new TextDecoder()
188
+ let buf = ''
189
+ try {
190
+ while (true) {
191
+ const { done, value } = await reader.read()
192
+ if (done) break
193
+ buf += decoder.decode(value, { stream: true })
194
+ let nl: number
195
+ while ((nl = buf.indexOf('\n')) >= 0) {
196
+ handleLine(buf.slice(0, nl))
197
+ buf = buf.slice(nl + 1)
198
+ }
199
+ }
200
+ } finally {
201
+ alive = false
202
+ if (clients.get(workspacePath) === recordPromise) clients.delete(workspacePath)
203
+ for (const [, p] of pending) {
204
+ if (p.timer) clearTimeout(p.timer)
205
+ p.reject(new Error(`${provider} agent exited`))
206
+ }
207
+ pending.clear()
208
+ fanout('__exit', {})
209
+ debug(`${provider} acp exited ws=${workspacePath}`)
210
+ }
211
+ }
212
+
213
+ async function drainStderr() {
214
+ const reader = (proc.stderr as ReadableStream<Uint8Array>).getReader()
215
+ const decoder = new TextDecoder()
216
+ while (true) {
217
+ const { done, value } = await reader.read()
218
+ if (done) break
219
+ const text = decoder.decode(value).trim()
220
+ // ACP agents log operational INFO/WARNING to stderr by design; only
221
+ // surface it under debug so a normal run stays quiet.
222
+ if (text) debug(`[${provider} stderr] ${text}`)
223
+ }
224
+ }
225
+
226
+ const client: AcpClient = {
227
+ rpc,
228
+ notify: (method, params = {}) => send({ jsonrpc: '2.0', method, params }),
229
+ onNotification(l) {
230
+ listeners.add(l)
231
+ return () => listeners.delete(l)
232
+ },
233
+ isAlive: () => alive,
234
+ workspacePath,
235
+ initializeResult: null
236
+ }
237
+ const record: ClientRecord = { client, proc }
238
+ const recordPromise = Promise.resolve(record)
239
+
240
+ void readLoop()
241
+ void drainStderr()
242
+
243
+ // A failed handshake leaves a live subprocess behind unless we kill it: the
244
+ // caller only drops the registry entry, so the next request would spawn a
245
+ // second agent while this one keeps running.
246
+ try {
247
+ client.initializeResult = await rpc<InitializeResponse>('initialize', {
248
+ protocolVersion: 1,
249
+ clientCapabilities: CLIENT_CAPABILITIES
250
+ })
251
+ } catch (err) {
252
+ proc.kill()
253
+ throw err
254
+ }
255
+ const info = client.initializeResult?.agentInfo
256
+ debug(
257
+ `${provider} acp started ws=${workspacePath} bin=${command} agent=${info?.name ?? '?'}/${info?.version ?? '?'}`
258
+ )
259
+ return record
260
+ }
261
+
262
+ export async function getAcpClient(spec: AcpSpawnSpec): Promise<AcpClient> {
263
+ const existing = clients.get(spec.workspacePath)
264
+ if (existing) {
265
+ const rec = await existing
266
+ if (rec.client.isAlive()) return rec.client
267
+ clients.delete(spec.workspacePath)
268
+ }
269
+ const started = startClient(spec)
270
+ clients.set(spec.workspacePath, started)
271
+ try {
272
+ return (await started).client
273
+ } catch (err) {
274
+ clients.delete(spec.workspacePath)
275
+ throw err
276
+ }
277
+ }
278
+
279
+ // Preview reads must not spawn an agent — home-page cards render for every
280
+ // workspace, and ACP agents are slow to start (Hermes takes seconds). Returns
281
+ // the workspace's client only if one is already running.
282
+ export async function peekAcpClient(workspacePath: string): Promise<AcpClient | null> {
283
+ const existing = clients.get(workspacePath)
284
+ if (!existing) return null
285
+ try {
286
+ const rec = await existing
287
+ return rec.client.isAlive() ? rec.client : null
288
+ } catch {
289
+ return null
290
+ }
291
+ }
292
+
293
+ export async function getAcpProcessInfo(
294
+ workspacePath: string,
295
+ binary: string | null
296
+ ): Promise<AcpProcessInfo> {
297
+ const rec = clients.get(workspacePath)
298
+ if (!rec) return { running: false, binary }
299
+ try {
300
+ const r = await rec
301
+ const info = r.client.initializeResult?.agentInfo
302
+ return {
303
+ running: r.client.isAlive(),
304
+ pid: r.proc.pid,
305
+ binary,
306
+ agent: info ? `${info.name ?? '?'}/${info.version ?? '?'}` : undefined
307
+ }
308
+ } catch {
309
+ return { running: false, binary }
310
+ }
311
+ }
312
+
313
+ // Kill a workspace's agent so the next message respawns it with fresh env (env
314
+ // is process-level and frozen at spawn). In-flight turns are lost.
315
+ export function killAcpWorkspace(workspacePath: string): void {
316
+ const rec = clients.get(workspacePath)
317
+ if (!rec) return
318
+ clients.delete(workspacePath)
319
+ void rec.then(r => r.proc.kill()).catch(() => {})
320
+ }
321
+
322
+ // Server shutdown: kill every agent so nothing is orphaned.
323
+ export function killAllAcpClients(): void {
324
+ for (const [path, rec] of clients) {
325
+ clients.delete(path)
326
+ void rec.then(r => r.proc.kill()).catch(() => {})
327
+ }
328
+ }