moi-computer 0.8.1-next.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 (103) 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/dev/ChatStatesPage.tsx +40 -2
  29. package/client/features/drawings/DrawingLayer.tsx +49 -0
  30. package/client/features/drawings/DrawingToolbar.tsx +95 -0
  31. package/client/features/drawings/annotation-availability.ts +10 -0
  32. package/client/features/drawings/capture-element.ts +45 -0
  33. package/client/features/drawings/useChatAnnotation.ts +222 -0
  34. package/client/features/drawings/useDrawingLayer.ts +758 -0
  35. package/client/features/drawings/useViewBuilderSketch.ts +151 -0
  36. package/client/features/home/workspace-presentation.tsx +6 -2
  37. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +12 -6
  38. package/client/features/scratchpad/ScratchpadControls.tsx +19 -5
  39. package/client/features/views/ViewBuilder.tsx +224 -0
  40. package/client/features/views/api.ts +1 -0
  41. package/client/features/views/useViewBuilderActions.ts +24 -3
  42. package/client/features/views/useViewBuilderDrafts.ts +66 -0
  43. package/client/features/widgets/Widgets.tsx +23 -39
  44. package/client/features/workspace/CustomizePanel.tsx +1 -1
  45. package/client/features/workspace/WorkspaceScreen.tsx +157 -57
  46. package/client/features/workspace/WorkspaceTabs.tsx +3 -3
  47. package/client/features/workspace/useFitsSplitLayout.ts +14 -8
  48. package/client/index.css +8 -0
  49. package/client/store/ui.ts +19 -0
  50. package/client/theme.css +33 -8
  51. package/dist/chunk-3becmq75.js +81 -0
  52. package/dist/{chunk-kkj86722.js → chunk-6w6j9g4b.js} +78 -78
  53. package/dist/{chunk-xeyxk7ep.js → chunk-8ew39cvq.js} +4 -4
  54. package/dist/chunk-c8gtrjwp.js +1 -0
  55. package/dist/{chunk-2vaafjp4.js → chunk-pp62fnxh.js} +1 -1
  56. package/dist/{chunk-35fq49qa.js → chunk-sxc24vfp.js} +1 -1
  57. package/dist/{chunk-xzx7c9hq.js → chunk-v964b5g7.js} +1 -1
  58. package/dist/chunk-zx33ts9d.css +1 -0
  59. package/dist/hermes-pznd63x9.png +0 -0
  60. package/dist/index.html +1 -1
  61. package/lib/format.ts +21 -7
  62. package/lib/themes.ts +8 -8
  63. package/lib/types.ts +8 -1
  64. package/lib/workspace-types.ts +2 -1
  65. package/package.json +6 -4
  66. package/server/api.ts +21 -2
  67. package/server/bundler/build-applet.ts +35 -44
  68. package/server/cli-env.ts +2 -2
  69. package/server/cli.ts +227 -56
  70. package/server/constants.ts +8 -0
  71. package/server/control-client.ts +124 -0
  72. package/server/control.ts +2 -2
  73. package/server/harness/README.md +74 -23
  74. package/server/harness/acp/adapter.ts +220 -0
  75. package/server/harness/acp/archived.ts +88 -0
  76. package/server/harness/acp/client.ts +328 -0
  77. package/server/harness/acp/discovery.ts +130 -0
  78. package/server/harness/acp/run-durations.ts +68 -0
  79. package/server/harness/acp/session.ts +788 -0
  80. package/server/harness/acp/wire.ts +132 -0
  81. package/server/harness/executable.ts +15 -1
  82. package/server/harness/hermes/NOTES.md +815 -0
  83. package/server/harness/hermes/discovery.ts +155 -0
  84. package/server/harness/hermes/index.ts +155 -0
  85. package/server/harness/hermes/models.ts +79 -0
  86. package/server/harness/openclaw/NOTES.md +196 -94
  87. package/server/harness/openclaw/adapter.ts +28 -55
  88. package/server/harness/openclaw/compat.ts +4 -8
  89. package/server/harness/openclaw/session.ts +257 -238
  90. package/server/harness/openclaw/strip.ts +10 -34
  91. package/server/harness/openclaw/thinking.ts +5 -53
  92. package/server/harness/registry.ts +3 -1
  93. package/server/service.ts +2 -2
  94. package/server/view-builders.ts +4 -2
  95. package/server/workspace-import.ts +30 -1
  96. package/workspace/.claude/skills/moi-workspace/SKILL.md +6 -6
  97. package/client/features/chat/tool-group/format.ts +0 -359
  98. package/client/features/views/ViewBuilderTab.tsx +0 -152
  99. package/dist/chunk-gny990qx.css +0 -1
  100. package/dist/chunk-gt7n06ef.js +0 -1
  101. package/dist/chunk-n7pga5x3.js +0 -80
  102. /package/workspace/.claude/skills/moi-workspace/{DESIGN.md → references/DESIGN.md} +0 -0
  103. /package/workspace/.claude/skills/moi-workspace/{SCRATCHPAD.md → references/SCRATCHPAD.md} +0 -0
@@ -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
+ }
@@ -0,0 +1,130 @@
1
+ // Session list, model catalog and home-card preview over ACP. Provider-agnostic.
2
+ import type { Model, SessionInfo } from '@/lib/types'
3
+
4
+ import { type AcpProviderConfig, type AcpSpawnContext } from './session'
5
+ import { acpSessionToSessionInfo } from './adapter'
6
+ import { archivedAcpSessions } from './archived'
7
+ import { getAcpClient, peekAcpClient } from './client'
8
+ import type { ListSessionsResponse, AcpModelInfo, AcpModelState, AcpNewSessionResult } from './wire'
9
+ import type { WorkspaceActivityPreview } from '../types'
10
+ import { debug } from '../../debug'
11
+
12
+ const PAGE_LIMIT = 5
13
+
14
+ // Sessions whose recorded cwd is this workspace, newest first. `cwd` filtering
15
+ // and cursor pagination are both server-side in ACP.
16
+ export async function listAcpSessions(
17
+ config: AcpProviderConfig,
18
+ ctx: AcpSpawnContext
19
+ ): Promise<SessionInfo[]> {
20
+ try {
21
+ const client = await getAcpClient(await config.spawn(ctx))
22
+ // Archiving is moi-side (see ./archived.ts) — the backend still lists the
23
+ // chat, so it is filtered here rather than by the agent.
24
+ const archived = await archivedAcpSessions(ctx.workspacePath)
25
+ const out: SessionInfo[] = []
26
+ let cursor: string | undefined
27
+ for (let page = 0; page < PAGE_LIMIT; page++) {
28
+ const res: ListSessionsResponse = await client.rpc('session/list', {
29
+ cwd: ctx.workspacePath,
30
+ ...(cursor ? { cursor } : {})
31
+ })
32
+ for (const entry of res.sessions ?? []) {
33
+ if (entry.sessionId && !archived.has(entry.sessionId)) {
34
+ out.push(acpSessionToSessionInfo(entry))
35
+ }
36
+ }
37
+ if (!res.nextCursor) break
38
+ cursor = res.nextCursor
39
+ }
40
+ return out.sort((a, b) => b.lastModified - a.lastModified)
41
+ } catch (err) {
42
+ debug(`${config.id} session/list failed: ${err instanceof Error ? err.message : String(err)}`)
43
+ return []
44
+ }
45
+ }
46
+
47
+ // Home-page card preview. Peek-only: ACP agents are slow to start (seconds),
48
+ // and this runs for every card on the home screen. With no live process the
49
+ // card simply omits the activity fields until the workspace is opened once.
50
+ export async function acpWorkspacePreview(
51
+ config: AcpProviderConfig,
52
+ ctx: AcpSpawnContext,
53
+ includeFirstUserMessage: boolean
54
+ ): Promise<WorkspaceActivityPreview> {
55
+ const client = await peekAcpClient(ctx.workspacePath)
56
+ if (!client) return {}
57
+ try {
58
+ const res: ListSessionsResponse = await client.rpc('session/list', { cwd: ctx.workspacePath })
59
+ const archived = await archivedAcpSessions(ctx.workspacePath)
60
+ const rows = (res.sessions ?? []).filter(s => s.sessionId && !archived.has(s.sessionId))
61
+ if (rows.length === 0) return {}
62
+ const newest = rows.reduce((a, b) =>
63
+ Date.parse(b.updatedAt ?? '') > Date.parse(a.updatedAt ?? '') ? b : a
64
+ )
65
+ const updated = Date.parse(newest.updatedAt ?? '')
66
+ // The oldest session's title stands in for its first user message — ACP
67
+ // exposes no message preview, and titles are generated from that message.
68
+ const oldest = rows.reduce((a, b) =>
69
+ Date.parse(b.updatedAt ?? '') < Date.parse(a.updatedAt ?? '') ? b : a
70
+ )
71
+ return {
72
+ ...(Number.isNaN(updated) ? {} : { updatedAt: updated }),
73
+ ...(includeFirstUserMessage && oldest.title ? { firstUserMessage: oldest.title } : {})
74
+ }
75
+ } catch {
76
+ return {}
77
+ }
78
+ }
79
+
80
+ // The model catalog arrives inline on `session/new`, so there is no standalone
81
+ // list RPC. Cache it per workspace: creating a session just to read models is
82
+ // wasteful, and an empty session is invisible to `session/list` anyway (agents
83
+ // skip zero-history rows).
84
+ const modelCatalogs = new Map<string, Promise<AcpModelState | undefined>>()
85
+
86
+ export function cacheAcpModelState(workspacePath: string, models: AcpModelState | undefined): void {
87
+ if (models?.availableModels?.length) {
88
+ modelCatalogs.set(workspacePath, Promise.resolve(models))
89
+ }
90
+ }
91
+
92
+ export function clearAcpModelCache(workspacePath: string): void {
93
+ modelCatalogs.delete(workspacePath)
94
+ }
95
+
96
+ export async function listAcpModels(
97
+ config: AcpProviderConfig,
98
+ ctx: AcpSpawnContext
99
+ ): Promise<Model[]> {
100
+ let cached: Promise<AcpModelState | undefined> | undefined = modelCatalogs.get(ctx.workspacePath)
101
+ if (!cached) {
102
+ cached = (async () => {
103
+ const client = await getAcpClient(await config.spawn(ctx))
104
+ const created = await client.rpc<AcpNewSessionResult>('session/new', {
105
+ cwd: ctx.workspacePath,
106
+ mcpServers: []
107
+ })
108
+ return created.models ?? undefined
109
+ })().catch(err => {
110
+ modelCatalogs.delete(ctx.workspacePath)
111
+ throw err
112
+ })
113
+ modelCatalogs.set(ctx.workspacePath, cached)
114
+ }
115
+ const mapModels =
116
+ config.mapModels ??
117
+ ((infos: AcpModelInfo[]): Model[] =>
118
+ infos.map(m => ({
119
+ value: m.modelId,
120
+ displayName: m.name ?? m.modelId,
121
+ ...(m.description ? { description: m.description } : {})
122
+ })))
123
+ try {
124
+ const state = await cached
125
+ return mapModels(state?.availableModels ?? [])
126
+ } catch (err) {
127
+ debug(`${config.id} model catalog failed: ${err instanceof Error ? err.message : String(err)}`)
128
+ return []
129
+ }
130
+ }
@@ -0,0 +1,68 @@
1
+ // Per-run durations for ACP sessions. ACP replays carry no timestamps, so a
2
+ // reloaded chat cannot compute how long each agent run took — but moi owns the
3
+ // prompt lifecycle live (`session/prompt`'s promise IS the run), so it records
4
+ // the durations itself and re-attaches them on replay. Without a recording the
5
+ // label falls back to a plain "Worked".
6
+ //
7
+ // Stored OUTSIDE the workspace in ONE global JSON file in moi's data dir
8
+ // (same choice, shape and locking as ./archived.ts), keyed by workspace path
9
+ // then session id, one entry per prompt run in prompt order:
10
+ // { "<workspacePath>": { "<sessionId>": [12100, 3400, …] } }
11
+ import { mkdir, rename } from 'node:fs/promises'
12
+ import { join } from 'node:path'
13
+
14
+ import { DATA_DIR } from '../../data-dir'
15
+
16
+ type Store = Record<string, Record<string, number[]>>
17
+
18
+ export const DEFAULT_RUN_DURATIONS_PATH = join(DATA_DIR, 'acp-run-durations.json')
19
+
20
+ let storePath = DEFAULT_RUN_DURATIONS_PATH
21
+
22
+ // Test seam: point the store at a scratch file (mirrors setArchivedSessionsPath).
23
+ export function setRunDurationsPath(path: string): void {
24
+ storePath = path
25
+ }
26
+
27
+ async function readStore(): Promise<Store> {
28
+ try {
29
+ const parsed = JSON.parse(await Bun.file(storePath).text())
30
+ return parsed && typeof parsed === 'object' ? (parsed as Store) : {}
31
+ } catch {
32
+ return {}
33
+ }
34
+ }
35
+
36
+ async function writeStore(store: Store): Promise<void> {
37
+ await mkdir(join(storePath, '..'), { recursive: true })
38
+ const tmp = `${storePath}.${process.pid}.tmp`
39
+ await Bun.write(tmp, JSON.stringify(store, null, 2))
40
+ await rename(tmp, storePath)
41
+ }
42
+
43
+ // Serialize read-modify-write so concurrent run completions can't clobber the
44
+ // single shared file.
45
+ let writeChain: Promise<unknown> = Promise.resolve()
46
+ function locked<T>(fn: () => Promise<T>): Promise<T> {
47
+ const run = writeChain.then(fn, fn)
48
+ writeChain = run.catch(() => {})
49
+ return run
50
+ }
51
+
52
+ export async function appendRunDuration(
53
+ workspacePath: string,
54
+ sessionId: string,
55
+ durationMs: number
56
+ ): Promise<void> {
57
+ if (!sessionId || !Number.isFinite(durationMs) || durationMs < 0) return
58
+ await locked(async () => {
59
+ const store = await readStore()
60
+ const sessions = (store[workspacePath] ??= {})
61
+ sessions[sessionId] = [...(sessions[sessionId] ?? []), Math.round(durationMs)]
62
+ await writeStore(store)
63
+ })
64
+ }
65
+
66
+ export async function runDurations(workspacePath: string, sessionId: string): Promise<number[]> {
67
+ return locked(async () => (await readStore())[workspacePath]?.[sessionId] ?? [])
68
+ }