moi-computer 0.3.0-next.2 → 0.3.0-next.3

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 (125) hide show
  1. package/README.md +1 -1
  2. package/client/AGENTS.md +2 -2
  3. package/client/api/http.ts +1 -1
  4. package/client/api/workspace-keys.ts +1 -0
  5. package/client/app/AppRouter.tsx +14 -5
  6. package/client/app/routes/HomeRoute.tsx +1 -1
  7. package/client/app/routes/WorkspaceRoute.tsx +8 -2
  8. package/client/app/shell/SidebarLayout.tsx +10 -5
  9. package/client/assets/openai.svg +3 -0
  10. package/client/components/shared/BottomPanel.tsx +2 -2
  11. package/client/components/ui/button.tsx +3 -2
  12. package/client/components/ui/input.tsx +1 -1
  13. package/client/features/applets/AppletMount.tsx +44 -0
  14. package/client/features/applets/WidgetShell.tsx +4 -1
  15. package/client/features/applets/applet-cache.ts +8 -0
  16. package/client/features/applets/applet-styles.ts +61 -0
  17. package/client/features/chat/ChatComposer.tsx +2 -2
  18. package/client/features/chat/ChatPanel.tsx +8 -25
  19. package/client/features/chat/ChatPopup.tsx +3 -3
  20. package/client/features/chat/{ThreadSelector.tsx → ChatSelector.tsx} +4 -4
  21. package/client/features/chat/TurnView.tsx +8 -9
  22. package/client/features/chat/api.ts +1 -1
  23. package/client/features/chat/chat-send.ts +57 -0
  24. package/client/features/chat/tool-group/ToolCallGroup.tsx +2 -1
  25. package/client/features/chat/tool-group/format.ts +117 -0
  26. package/client/features/chat/useChat.ts +10 -34
  27. package/client/features/connectors/McpMenu.tsx +4 -21
  28. package/client/features/dev/DevRoutes.tsx +18 -0
  29. package/client/features/dev/HarnessDebugPage.tsx +468 -0
  30. package/client/{components/playground → features/dev}/PlaygroundPage.tsx +1 -1
  31. package/client/features/home/CreateWorkspaceDialog.tsx +64 -158
  32. package/client/features/home/CreateWorkspaceDialogSteps.tsx +234 -0
  33. package/client/features/home/HomeLogo.tsx +344 -0
  34. package/client/features/home/HomePage.tsx +15 -21
  35. package/client/features/home/WorkspacePreview.tsx +2 -2
  36. package/client/features/home/api.ts +11 -3
  37. package/client/features/home/workspace-presentation.tsx +4 -4
  38. package/client/features/settings/GeneralSettings.tsx +3 -3
  39. package/client/features/settings/IconPicker.tsx +4 -3
  40. package/client/features/settings/icon-picker-options.ts +0 -131
  41. package/client/features/views/ViewBuilderTab.tsx +153 -0
  42. package/client/features/views/api.ts +124 -0
  43. package/client/features/views/useViewBuilderActions.ts +72 -0
  44. package/client/features/widgets/WidgetGrid.tsx +36 -20
  45. package/client/features/widgets/Widgets.tsx +140 -90
  46. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -9
  47. package/client/features/workspace/WorkspaceScreen.tsx +179 -40
  48. package/client/features/workspace/WorkspaceTabs.tsx +4 -4
  49. package/client/index.css +0 -35
  50. package/client/index.html +1 -1
  51. package/client/lib/app-icon-registry.ts +145 -0
  52. package/client/runtime/useWorkspaceEvents.ts +3 -1
  53. package/client/theme.css +1 -1
  54. package/dist/chunk-4vf1t6v1.js +10 -0
  55. package/dist/chunk-6c24yndg.js +61 -0
  56. package/dist/chunk-6c8cwpzc.js +1 -0
  57. package/dist/chunk-b4b276wx.js +15 -0
  58. package/dist/{chunk-c4j722at.js → chunk-cs8vbert.js} +2 -2
  59. package/dist/chunk-cwqmay73.css +1 -0
  60. package/dist/chunk-kxmvv1ax.js +48 -0
  61. package/dist/chunk-rq0ar7vp.js +1 -0
  62. package/dist/{chunk-p68fnz3q.js → chunk-vkvb3hjm.js} +1 -1
  63. package/dist/chunk-zpxrb1ce.js +2 -0
  64. package/dist/index.html +2 -2
  65. package/dist/openai-h13pza4b.svg +3 -0
  66. package/lib/format.ts +2 -2
  67. package/lib/types.ts +38 -2
  68. package/lib/view-builder-meta.ts +35 -0
  69. package/lib/workspace-layout.ts +14 -0
  70. package/package.json +2 -1
  71. package/server/AGENTS.md +3 -3
  72. package/server/api.ts +165 -51
  73. package/server/applets.ts +1 -1
  74. package/server/bundle-queue.ts +19 -0
  75. package/server/bundler/applet-css.ts +50 -0
  76. package/server/{build-applet.ts → bundler/build-applet.ts} +36 -26
  77. package/server/cli.ts +79 -2
  78. package/server/control.ts +106 -8
  79. package/server/env-apply.ts +2 -2
  80. package/server/harness/README.md +228 -0
  81. package/server/harness/claude-code/NOTES.md +578 -0
  82. package/{lib/claude-adapter.ts → server/harness/claude-code/adapter.ts} +67 -5
  83. package/server/harness/claude-code/index.ts +124 -0
  84. package/server/{mcp.ts → harness/claude-code/mcp.ts} +1 -1
  85. package/server/{cc-session.ts → harness/claude-code/session.ts} +42 -14
  86. package/server/harness/claude-code/sessions.ts +42 -0
  87. package/server/harness/codex/NOTES.md +239 -0
  88. package/server/harness/codex/adapter.ts +414 -0
  89. package/server/harness/codex/client.ts +343 -0
  90. package/server/harness/codex/index.ts +68 -0
  91. package/server/harness/codex/probe.ts +186 -0
  92. package/server/harness/codex/session.ts +617 -0
  93. package/server/harness/debug.ts +57 -0
  94. package/server/harness/openclaw/NOTES.md +316 -0
  95. package/server/{openclaw-adapter.ts → harness/openclaw/adapter.ts} +2 -2
  96. package/server/harness/openclaw/index.ts +93 -0
  97. package/server/{openclaw-session.ts → harness/openclaw/session.ts} +44 -9
  98. package/server/{openclaw-strip.ts → harness/openclaw/strip.ts} +3 -1
  99. package/server/harness/registry.ts +36 -0
  100. package/server/harness/types.ts +87 -0
  101. package/server/layout.ts +6 -12
  102. package/server/moi-scaffold.ts +1 -1
  103. package/server/registry.ts +14 -52
  104. package/server/state.ts +5 -38
  105. package/server/status.ts +7 -46
  106. package/server/vendor.ts +1 -1
  107. package/server/view-builders.ts +428 -0
  108. package/server/views.ts +0 -0
  109. package/server/web.ts +18 -40
  110. package/server/workspace-init.ts +6 -6
  111. package/workspace/.claude/skills/moi-workspace/DESIGN.md +1 -0
  112. package/workspace/.claude/skills/moi-workspace/SKILL.md +28 -7
  113. package/client/assets/hermes-nous.png +0 -0
  114. package/client/hooks/useScrollFade.ts +0 -38
  115. package/dist/chunk-23cgr1tz.css +0 -1
  116. package/dist/chunk-3hy3qy6d.js +0 -10
  117. package/dist/chunk-dyfaffyz.js +0 -119
  118. package/dist/chunk-kpe40hm8.js +0 -1
  119. package/dist/chunk-ty6dvda0.js +0 -1
  120. package/dist/hermes-nous-pznd63x9.png +0 -0
  121. /package/client/{components/playground → features/dev}/PixelPainter.tsx +0 -0
  122. /package/client/{components/playground → features/dev}/ToolCallsPage.tsx +0 -0
  123. /package/server/{agent.ts → harness/claude-code/models.ts} +0 -0
  124. /package/server/{openclaw.ts → harness/openclaw/discovery.ts} +0 -0
  125. /package/server/{openclaw-gateway.ts → harness/openclaw/gateway.ts} +0 -0
@@ -12,12 +12,13 @@ import type {
12
12
  Turn,
13
13
  TurnMeta,
14
14
  TurnOrigin
15
- } from './format'
15
+ } from '@/lib/format'
16
16
 
17
- import { ATTACHMENT_ONLY_PLACEHOLDER, splitAttachmentNote } from './attachment-note'
17
+ import { ATTACHMENT_ONLY_PLACEHOLDER, splitAttachmentNote } from '@/lib/attachment-note'
18
+ import { stripViewBuilderMeta } from '@/lib/view-builder-meta'
18
19
 
19
20
  // Loose SDK message shape — we don't pull in the full SDK type tree; the
20
- // adapter tolerates missing fields. Reference: dev/sdk-message-spec.md.
21
+ // adapter tolerates missing fields. Reference: ./NOTES.md.
21
22
  type ContentBlock = {
22
23
  type: string
23
24
  text?: string
@@ -83,7 +84,15 @@ type SdkMessage = {
83
84
  task_id?: string
84
85
  description?: string
85
86
  status?: string
86
- usage?: { total_tokens?: number; tool_uses?: number; duration_ms?: number }
87
+ // task_* events report total_tokens/tool_uses; `result` reports the API
88
+ // usage breakdown (input/output tokens).
89
+ usage?: {
90
+ total_tokens?: number
91
+ tool_uses?: number
92
+ duration_ms?: number
93
+ input_tokens?: number
94
+ output_tokens?: number
95
+ }
87
96
  hook_id?: string
88
97
  hook_name?: string
89
98
  hook_event?: string
@@ -105,6 +114,18 @@ type SdkMessage = {
105
114
  duration_ms?: number
106
115
  num_turns?: number
107
116
  total_cost_usd?: number
117
+ // Per-model usage on `result` — the reliable token source (top-level
118
+ // `usage` has been observed all-zero).
119
+ modelUsage?: Record<
120
+ string,
121
+ {
122
+ inputTokens?: number
123
+ outputTokens?: number
124
+ cacheReadInputTokens?: number
125
+ cacheCreationInputTokens?: number
126
+ costUSD?: number
127
+ } | null
128
+ >
108
129
  state?: string
109
130
  }
110
131
 
@@ -274,6 +295,47 @@ export class ClaudeAdapter {
274
295
  durationMs: msg.duration_ms
275
296
  }
276
297
  })
298
+ // Fold the turn's token usage into the newest top-level assistant turn
299
+ // so the meta strip can show it (parity with the codex/openclaw
300
+ // adapters — previously these counts were dropped entirely). The
301
+ // result's top-level `usage` is unreliable (observed all-zero); the
302
+ // per-model `modelUsage` map carries the real numbers, so sum those
303
+ // and count cache reads/creation as input (the context the turn
304
+ // actually processed), falling back to `usage` if absent.
305
+ let inputTokens = 0
306
+ let outputTokens = 0
307
+ let sawUsage = false
308
+ for (const mu of Object.values(msg.modelUsage ?? {})) {
309
+ if (!mu || typeof mu !== 'object') continue
310
+ sawUsage = true
311
+ inputTokens +=
312
+ (mu.inputTokens ?? 0) +
313
+ (mu.cacheReadInputTokens ?? 0) +
314
+ (mu.cacheCreationInputTokens ?? 0)
315
+ outputTokens += mu.outputTokens ?? 0
316
+ }
317
+ if (!sawUsage && msg.usage) {
318
+ inputTokens = msg.usage.input_tokens ?? 0
319
+ outputTokens = msg.usage.output_tokens ?? 0
320
+ sawUsage = typeof msg.usage.input_tokens === 'number'
321
+ }
322
+ if (sawUsage) {
323
+ for (let i = this.turns.length - 1; i >= 0; i--) {
324
+ const t = this.turns[i]
325
+ if (t.role !== 'assistant' || t.parentTaskId) continue
326
+ t.meta = {
327
+ ...t.meta,
328
+ usage: {
329
+ inputTokens,
330
+ outputTokens,
331
+ totalTokens: inputTokens + outputTokens,
332
+ ...(typeof msg.total_cost_usd === 'number' ? { costUsd: msg.total_cost_usd } : {})
333
+ }
334
+ }
335
+ events.push({ kind: 'turn', turn: t })
336
+ break
337
+ }
338
+ }
277
339
  return events
278
340
  }
279
341
 
@@ -459,7 +521,7 @@ export class ClaudeAdapter {
459
521
  // file chips here — a reloaded bubble matches the live one
460
522
  // instead of leaking temp paths into it.
461
523
  const split = splitAttachmentNote(text)
462
- text = split.text
524
+ text = stripViewBuilderMeta(split.text)
463
525
  for (const f of split.files) {
464
526
  parts.push({
465
527
  type: 'file',
@@ -0,0 +1,124 @@
1
+ // Claude Code as a Harness. Thin wiring over this folder's modules — see
2
+ // ../types.ts for the contract and ../README.md for the architecture.
3
+ import { join } from 'node:path'
4
+
5
+ import type { DiscoveredWorkspace, McpServer } from '@/lib/types'
6
+
7
+ import type { Harness } from '../types'
8
+ import { getMcpStatus } from './mcp'
9
+ import { getClaudeModels } from './models'
10
+ import {
11
+ SESSION_LIMITS,
12
+ getCCDebugSnapshot,
13
+ getCCRunningSessions,
14
+ interruptCCSession,
15
+ killAllCCSessions,
16
+ restartWorkspaceSessions,
17
+ sendCCMessage
18
+ } from './session'
19
+ import { getSessionEvents, getSessions } from './sessions'
20
+
21
+ function fmtDuration(ms: number): string {
22
+ const s = Math.floor(ms / 1000)
23
+ const h = Math.floor(s / 3600)
24
+ const m = Math.floor((s % 3600) / 60)
25
+ const sec = s % 60
26
+ if (h > 0) return `${h}h ${m}m ${sec}s`
27
+ if (m > 0) return `${m}m ${sec}s`
28
+ return `${sec}s`
29
+ }
30
+
31
+ function fmtAgo(ts: number, now: number): string {
32
+ const s = Math.round((now - ts) / 1000)
33
+ if (s < 1) return 'now'
34
+ if (s < 60) return `${s}s ago`
35
+ const m = Math.floor(s / 60)
36
+ if (m < 60) return `${m}m ${s % 60}s ago`
37
+ return `${Math.floor(m / 60)}h ${m % 60}m ago`
38
+ }
39
+
40
+ // Discover directories with CC session history that aren't registered yet.
41
+ async function discoverWorkspaces(registeredPaths: Set<string>): Promise<DiscoveredWorkspace[]> {
42
+ try {
43
+ const { listSessions } = await import('@anthropic-ai/claude-agent-sdk')
44
+ const sessions = await listSessions({})
45
+ const { stat } = await import('node:fs/promises')
46
+ const paths = new Set<string>()
47
+ for (const s of sessions) {
48
+ if (!s.cwd || registeredPaths.has(s.cwd)) continue
49
+ try {
50
+ const info = await stat(s.cwd)
51
+ if (info.isDirectory()) paths.add(s.cwd)
52
+ } catch {}
53
+ }
54
+ return [...paths].map(path => ({ path, type: 'claude-code' as const }))
55
+ } catch {
56
+ return []
57
+ }
58
+ }
59
+
60
+ export const claudeCodeHarness: Harness = {
61
+ id: 'claude-code',
62
+ capabilities: {
63
+ supportsStreaming: true,
64
+ imagesInline: 'base64',
65
+ liveModelSwitch: true,
66
+ liveEffortSwitch: false, // construct-time; session.ts drains + rebuilds
67
+ nativeUserEcho: false // streaming-input never echoes; the server synthesizes the turn
68
+ },
69
+
70
+ sendMessage: input => sendCCMessage(input),
71
+ interrupt: (workspaceId, sessionId) => interruptCCSession(workspaceId, sessionId),
72
+ runningSessions: () => getCCRunningSessions(),
73
+
74
+ listSessions: ws => getSessions(ws.path),
75
+ sessionEvents: (ws, sessionId) => getSessionEvents(sessionId, ws.path),
76
+ listModels: ws => getClaudeModels(ws.path),
77
+ // The SDK's McpServerStatus is a superset of the UI's McpServer (extra
78
+ // fields are ignored by the client) — pass it through unchanged.
79
+ mcpStatus: async ws => (await getMcpStatus(ws.path, 'project')) as unknown as McpServer[],
80
+ discoverWorkspaces,
81
+
82
+ onEnvChanged: workspacePath => restartWorkspaceSessions(workspacePath),
83
+ shutdown: () => killAllCCSessions(),
84
+ skillsDir: workspaceRoot => join(workspaceRoot, '.claude', 'skills'),
85
+
86
+ statusLines: now => {
87
+ const cc = getCCDebugSnapshot()
88
+ const busy = cc.sessions.filter(s => s.busy).length
89
+ const lines = [
90
+ `live CC sessions ${cc.sessions.length}/${SESSION_LIMITS.maxLive} ` +
91
+ `(${busy} busy, ${cc.sessions.length - busy} idle, ${cc.aliases} alias${cc.aliases === 1 ? '' : 'es'}, ` +
92
+ `idle TTL ${fmtDuration(SESSION_LIMITS.idleTtlMs)})`
93
+ ]
94
+ if (cc.sessions.length === 0) {
95
+ lines.push(' (none held in memory — next message will resume from disk)')
96
+ return lines
97
+ }
98
+ // Busiest / most-recently-active first.
99
+ const sorted = [...cc.sessions].sort(
100
+ (a, b) => Number(b.busy) - Number(a.busy) || b.lastActivityAt - a.lastActivityAt
101
+ )
102
+ for (const s of sorted) {
103
+ const mark = s.busy ? '▶ busy' : s.closed ? '✗ closed' : '○ idle'
104
+ const bits = [
105
+ mark.padEnd(8),
106
+ `ws=${s.workspaceId}`,
107
+ `session=${s.sessionId}`,
108
+ `model=${s.model ?? 'default'}`,
109
+ `effort=${s.effort ?? 'default'}`,
110
+ `stream=${s.stream ? 'on' : 'off'}`,
111
+ `pending=${s.pendingTurns}`,
112
+ `age=${fmtDuration(now - s.createdAt)}`,
113
+ `lastActivity=${fmtAgo(s.lastActivityAt, now)}`
114
+ ]
115
+ if (s.desiredEffort !== s.effort) bits.push(`desiredEffort=${s.desiredEffort ?? 'default'}`)
116
+ if (s.desiredStream !== s.stream) bits.push(`desiredStream=${s.desiredStream ? 'on' : 'off'}`)
117
+ if (!s.busy && !s.hasIdleTimer) bits.push('(no idle timer)')
118
+ let line = ' ' + bits.join(' ')
119
+ if (s.lastUserText) line += `\n last: ${JSON.stringify(s.lastUserText)}`
120
+ lines.push(line)
121
+ }
122
+ return lines
123
+ }
124
+ }
@@ -6,7 +6,7 @@ import type {
6
6
  } from '@anthropic-ai/claude-agent-sdk'
7
7
  import { join } from 'path'
8
8
 
9
- import { debugEnabled } from './debug'
9
+ import { debugEnabled } from '../../debug'
10
10
 
11
11
  export type McpScope = 'user' | 'project'
12
12
 
@@ -19,14 +19,21 @@ import {
19
19
  } from '@anthropic-ai/claude-agent-sdk'
20
20
 
21
21
  import { ATTACHMENT_ONLY_PLACEHOLDER, appendAttachmentNote } from '@/lib/attachment-note'
22
- import { ClaudeAdapter } from '@/lib/claude-adapter'
22
+ import { ClaudeAdapter } from './adapter'
23
23
  import type { Part } from '@/lib/format'
24
+ import { stripViewBuilderMeta } from '@/lib/view-builder-meta'
24
25
 
25
- import { debug } from './debug'
26
- import { broadcast } from './state'
27
- import { hasThreadConfig, renameThreadConfig, saveThreadConfig } from './thread-config'
28
- import { type StoredUpload, resolveUploads, uploadToDisplayPart } from './uploads'
29
- import { resolveWorkspaceEnv } from './workspace-env'
26
+ import { debug } from '../../debug'
27
+ import { tapWire } from '../debug'
28
+ import { broadcast } from '../../state'
29
+ import { hasThreadConfig, renameThreadConfig, saveThreadConfig } from '../../thread-config'
30
+ import { type StoredUpload, resolveUploads, uploadToDisplayPart } from '../../uploads'
31
+ import {
32
+ markViewBuilderBuildingBySession,
33
+ markViewBuilderWaitingBySession,
34
+ renameViewBuilderSession
35
+ } from '../../view-builders'
36
+ import { resolveWorkspaceEnv } from '../../workspace-env'
30
37
 
31
38
  // Media types Claude vision accepts; uploads.ts guarantees every image upload is
32
39
  // normalized to one of these, so the cast on `media_type` below is sound.
@@ -43,14 +50,15 @@ type MessageContent = SDKUserMessage['message']['content']
43
50
  // Exported for unit tests.
44
51
  export function buildUserMessage(
45
52
  text: string,
46
- uploads: StoredUpload[]
53
+ uploads: StoredUpload[],
54
+ displayText = text
47
55
  ): { content: MessageContent; parts: Part[] } {
48
56
  const parts: Part[] = []
49
57
  for (const u of uploads) {
50
58
  const part = uploadToDisplayPart(u)
51
59
  if (part) parts.push(part)
52
60
  }
53
- if (text) parts.push({ type: 'text', text })
61
+ if (displayText) parts.push({ type: 'text', text: displayText })
54
62
 
55
63
  if (uploads.length === 0) return { content: text, parts }
56
64
 
@@ -305,6 +313,8 @@ function renameSession(s: LiveSession, realId: string) {
305
313
  async function consume(s: LiveSession) {
306
314
  try {
307
315
  for await (const msg of s.q) {
316
+ // Raw SDK message into the debug wire ring (/playground/harness).
317
+ tapWire(s.workspaceId, 'recv', msg)
308
318
  if (msg.type === 'system' && msg.subtype === 'init') {
309
319
  const realId = msg.session_id
310
320
  if (realId && realId !== s.sessionId) {
@@ -312,6 +322,7 @@ async function consume(s: LiveSession) {
312
322
  renameSession(s, realId)
313
323
  // Carry any config the picker wrote under the temp id to the real id.
314
324
  await renameThreadConfig(s.workspacePath, from, s.sessionId)
325
+ await renameViewBuilderSession(s.workspaceId, s.workspacePath, from, s.sessionId)
315
326
  }
316
327
  // Seed the thread's config from what it actually ran with — but only if
317
328
  // it has none yet, so an explicit user PUT (or a migrated temp-id edit)
@@ -348,6 +359,16 @@ async function consume(s: LiveSession) {
348
359
  debug(`cc result ws=${s.workspaceId} session=${s.sessionId} pendingTurns=${s.pendingTurns}`)
349
360
  if (s.pendingTurns === 0) {
350
361
  broadcastProcessing(s, false)
362
+ const builderError =
363
+ msg.subtype === 'success'
364
+ ? undefined
365
+ : msg.errors.join('\n') || msg.subtype.replaceAll('_', ' ')
366
+ await markViewBuilderWaitingBySession(
367
+ s.workspaceId,
368
+ s.workspacePath,
369
+ s.sessionId,
370
+ builderError
371
+ )
351
372
  // A mid-turn effort/streaming change couldn't be applied live; now
352
373
  // that the queue has drained, tear down so the next message resumes
353
374
  // with it.
@@ -361,11 +382,13 @@ async function consume(s: LiveSession) {
361
382
  `cc consume error ws=${s.workspaceId} session=${s.sessionId}: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`
362
383
  )
363
384
  if (!(err instanceof Error && err.name === 'AbortError')) {
385
+ const message = err instanceof Error ? err.message : 'Unknown error'
364
386
  broadcast(s.workspaceId, {
365
387
  kind: 'error',
366
388
  sessionId: s.sessionId,
367
- content: err instanceof Error ? err.message : 'Unknown error'
389
+ content: message
368
390
  })
391
+ await markViewBuilderWaitingBySession(s.workspaceId, s.workspacePath, s.sessionId, message)
369
392
  }
370
393
  } finally {
371
394
  if (s.pendingTurns > 0) {
@@ -486,7 +509,8 @@ export async function sendCCMessage(input: {
486
509
  ? resolveUploads(input.workspaceId, input.attachments)
487
510
  : []
488
511
  if (!input.content && uploads.length === 0) return
489
- const { content, parts } = buildUserMessage(input.content, uploads)
512
+ const displayContent = stripViewBuilderMeta(input.content)
513
+ const { content, parts } = buildUserMessage(input.content, uploads, displayContent)
490
514
 
491
515
  const wantStream = input.stream === true
492
516
  let s = sessions.get(liveKey(input.workspaceId, input.sessionId))
@@ -537,7 +561,6 @@ export async function sendCCMessage(input: {
537
561
  workspaceEnv: await resolveWorkspaceEnv(input.workspacePath)
538
562
  })
539
563
  }
540
-
541
564
  // Streaming-input mode does NOT echo the pushed user message back in the
542
565
  // output stream (string-prompt mode did — that's what expectUserEcho was
543
566
  // for), so the adapter never emits a user turn. Synthesize and broadcast it
@@ -559,18 +582,22 @@ export async function sendCCMessage(input: {
559
582
  // Safety net: if a future SDK does echo the user message, the adapter re-ids
560
583
  // that echo to the same optimisticId so it collapses onto the turn above
561
584
  // instead of duplicating.
562
- if (input.optimisticId) s.adapter.expectUserEcho(input.optimisticId, input.content)
585
+ if (input.optimisticId) s.adapter.expectUserEcho(input.optimisticId, displayContent)
563
586
 
564
587
  s.lastActivityAt = Date.now()
565
588
  // For an attachment-only message, fall back to the filenames so the thread
566
589
  // list / status view don't show a blank label.
567
- const label = input.content || uploads.map(u => u.filename).join(', ')
590
+ const label = displayContent || uploads.map(u => u.filename).join(', ')
568
591
  s.lastUserText = label.replace(/\s+/g, ' ').slice(0, 120)
569
592
 
570
593
  const wasIdle = s.pendingTurns === 0
571
594
  s.pendingTurns++
572
- if (wasIdle) broadcastProcessing(s, true)
595
+ if (wasIdle) {
596
+ await markViewBuilderBuildingBySession(s.workspaceId, s.workspacePath, s.sessionId)
597
+ broadcastProcessing(s, true)
598
+ }
573
599
  s.input.push(content)
600
+ tapWire(s.workspaceId, 'send', { type: 'user', content })
574
601
  debug(
575
602
  `cc enqueue ws=${s.workspaceId} session=${s.sessionId} pendingTurns=${s.pendingTurns} text=${JSON.stringify(s.lastUserText)}`
576
603
  )
@@ -591,6 +618,7 @@ export async function interruptCCSession(workspaceId: string, sessionId: string)
591
618
  s.pendingTurns = 0
592
619
  broadcast(s.workspaceId, { kind: 'stopped', sessionId: s.sessionId })
593
620
  broadcastProcessing(s, false)
621
+ await markViewBuilderWaitingBySession(s.workspaceId, s.workspacePath, s.sessionId)
594
622
  armIdle(s)
595
623
  }
596
624
 
@@ -0,0 +1,42 @@
1
+ // Session discovery + history replay for Claude Code workspaces, backed by
2
+ // the Agent SDK's persisted `.jsonl` session files.
3
+ import { getSessionMessages, listSessions } from '@anthropic-ai/claude-agent-sdk'
4
+
5
+ import type { SessionInfo, StreamEvent } from '@/lib/types'
6
+
7
+ import { ClaudeAdapter } from './adapter'
8
+
9
+ export async function getSessions(workspacePath: string): Promise<SessionInfo[]> {
10
+ const sessions = await listSessions({ dir: workspacePath })
11
+ return sessions.map(s => ({
12
+ sessionId: s.sessionId,
13
+ summary: s.summary,
14
+ lastModified: s.lastModified,
15
+ cwd: s.cwd
16
+ }))
17
+ }
18
+
19
+ /**
20
+ * Replay a session's persisted raw messages through a fresh adapter and
21
+ * return the resulting StreamEvents. Events are carefully NOT deduplicated —
22
+ * the client reducer is idempotent under upsert-by-id.
23
+ */
24
+ export async function getSessionEvents(
25
+ sessionId: string,
26
+ workspacePath: string
27
+ ): Promise<StreamEvent[]> {
28
+ const adapter = new ClaudeAdapter()
29
+ const events: StreamEvent[] = []
30
+ try {
31
+ const raw = await getSessionMessages(sessionId, { dir: workspacePath })
32
+ for (const msg of raw) {
33
+ // Disk replay carries no `stream_event` messages, so the adapter never
34
+ // produces previews here — filter defensively to keep this the pure,
35
+ // persisted StreamEvent path that reconnect-healing trusts.
36
+ for (const ev of adapter.ingest(msg)) if (ev.kind !== 'preview') events.push(ev)
37
+ }
38
+ } catch {
39
+ // session file missing or unreadable — return whatever we have (often [])
40
+ }
41
+ return events
42
+ }
@@ -0,0 +1,239 @@
1
+ # Codex — integration research
2
+
3
+ Research notes on driving OpenAI Codex as a moi harness (July 2026). The
4
+ adapter shipped on the app-server path recommended below — see §5 for what
5
+ implementation against CLI 0.144.5 confirmed/corrected. Codex exposes **two**
6
+ programmable surfaces, and they differ enough that the choice shapes the
7
+ whole adapter:
8
+
9
+ 1. **`@openai/codex-sdk`** (npm, TypeScript) — a thin wrapper that spawns
10
+ `codex exec` as a fresh subprocess per turn.
11
+ 2. **`codex app-server`** — a long-lived JSON-RPC 2.0 server bundled with the
12
+ CLI; the protocol behind the official VS Code extension.
13
+
14
+ **Recommendation: target the app-server.** The exec SDK is missing too much
15
+ (no interrupt method, no model list, no token deltas, no steering); the
16
+ app-server covers essentially the whole adapter checklist in
17
+ [../README.md](../README.md) and even exceeds the Claude Agent SDK in places.
18
+
19
+ Sources: [SDK TypeScript source](https://github.com/openai/codex/tree/main/sdk/typescript/src),
20
+ [app-server README](https://github.com/openai/codex/blob/main/codex-rs/app-server/README.md),
21
+ [Codex SDK docs](https://developers.openai.com/codex/sdk).
22
+
23
+ ## 1. The exec SDK (`@openai/codex-sdk`)
24
+
25
+ ```ts
26
+ const codex = new Codex({ env, config }) // env REPLACES process.env, not merged
27
+ const thread = codex.startThread({
28
+ model,
29
+ sandboxMode,
30
+ workingDirectory,
31
+ modelReasoningEffort,
32
+ approvalPolicy
33
+ })
34
+ const { events } = await thread.runStreamed(input, { outputSchema, signal })
35
+ ```
36
+
37
+ - Every `run()`/`runStreamed()` spawns `codex exec` (`resume <threadId>` after
38
+ the first turn) and exits when the turn ends. Thread state persists in
39
+ `~/.codex/sessions`; the in-memory `Thread` is just an id + options.
40
+ - Because each turn is a new process, _every_ setting is effectively per-turn
41
+ (`resumeThread(id, newOptions)`) — but there's also no live process to
42
+ interrupt (`AbortSignal` kills it) or steer.
43
+ - Events are **item-level**, not token-level: `thread.started`, `turn.started`,
44
+ `item.started/updated/completed`, `turn.completed { usage }`, `turn.failed`.
45
+ Item union: `agent_message`, `reasoning`, `command_execution` (aggregated
46
+ output + exit code), `file_change` (patch summary), `mcp_tool_call`,
47
+ `web_search`, `todo_list`, `error`.
48
+ - Input: plain string or `{type:"text"}` / `{type:"local_image", path}` — no
49
+ base64 image blocks; uploads must be materialized to disk (we already do
50
+ this for OpenClaw).
51
+ - No model list, no session list API, no MCP status probe, no approval
52
+ callbacks. Structured output via `outputSchema` (JSON Schema/Zod) is the one
53
+ feature CC lacks.
54
+
55
+ Fine for CI-style one-shot runs; too thin for a moi chat harness.
56
+
57
+ ## 2. The app-server (`codex app-server`)
58
+
59
+ JSON-RPC 2.0 over **stdio** (newline-delimited JSON, `"jsonrpc"` header
60
+ omitted — same transport style as a stdio MCP server). Other transports
61
+ (unix socket, websocket) exist but stdio is the only production-supported one.
62
+
63
+ ### Topology
64
+
65
+ - **One process serves N threads in N different cwds.** `cwd` is per-thread
66
+ (`thread/start`) and overridable per-turn. `thread/loaded/list` shows what's
67
+ in memory; a thread with no subscribers and no activity for 30 min is
68
+ unloaded (`thread/closed`). This replaces most of `claude-code/session.ts`'s
69
+ eviction/idle-TTL machinery.
70
+ - **Env vars are process-level.** There is no per-thread env injection, so
71
+ moi's per-workspace `workspaceEnv` doesn't map onto a single shared process.
72
+ Options: one app-server per workspace (env frozen at spawn, restart on env
73
+ change — same semantics as `restartWorkspaceSessions`), or accept
74
+ process-level env.
75
+ - Handshake: one `initialize` request per connection (with `clientInfo`), then
76
+ an `initialized` notification. Everything before that is rejected.
77
+ - The wire carries three shapes the client must route: responses (matched by
78
+ `id`), notifications, and **server-initiated requests** the client must
79
+ answer (approvals, dynamic tool calls).
80
+ - Backpressure: overload → error `-32001`, retry with backoff.
81
+ - Crash recovery: respawn + `thread/resume` (threads persist in
82
+ `~/.codex/sessions`).
83
+
84
+ ### Core flow
85
+
86
+ ```
87
+ thread/start | thread/resume | thread/fork → thread id, auto-subscribes
88
+ turn/start { threadId, input, model?, effort?, outputSchema?, ... }
89
+ ← turn/started
90
+ ← item/started / item/*/delta / item/completed (per item)
91
+ ← turn/completed { status: completed|interrupted|failed }
92
+ turn/steer { expectedTurnId, input } — append input to the RUNNING turn
93
+ turn/interrupt { threadId, turnId }
94
+ ```
95
+
96
+ Per-turn overrides (`model`, `effort`, `summary`, sandbox/approval policy)
97
+ become the thread's defaults for later turns — no drain-then-rebuild dance at
98
+ all. `thread/settings/update` queues setting changes without starting a turn.
99
+
100
+ ### Feature map vs the adapter checklist
101
+
102
+ - **Models**: `model/list` — models with ordered `supportedReasoningEfforts`,
103
+ exactly what the picker needs.
104
+ - **Streaming**: `item/agentMessage/delta`, `item/reasoning/summaryTextDelta`
105
+ (+ raw `textDelta`), `item/commandExecution/outputDelta` (live command
106
+ output — CC has no equivalent). Per-connection opt-out via
107
+ `initialize.capabilities.optOutNotificationMethods`, so non-streaming mode
108
+ is a handshake flag, not a session rebuild.
109
+ - **Items**: `userMessage` (echoes our `clientUserMessageId` as `clientId` —
110
+ native optimistic-id rendezvous), `agentMessage`, `reasoning`
111
+ (summary vs raw content), `commandExecution` (cwd, exit code, duration),
112
+ `fileChange` (structured per-file diffs), `mcpToolCall`, `collabToolCall`
113
+ (subagents: spawn/send/wait/close), `webSearch`, `todoList`/`plan`
114
+ (`turn/plan/updated`), `imageView`, `contextCompaction`, review items.
115
+ Plus `turn/diff/updated` — an aggregated unified diff for the whole turn.
116
+ - **Approvals**: interactive server→client JSON-RPC requests
117
+ (`item/commandExecution/requestApproval`, `item/fileChange/requestApproval`,
118
+ `item/permissions/requestApproval`) answered with
119
+ `accept | acceptForSession | decline | cancel`. Or delegate with
120
+ `approvalsReviewer: "auto_review"`. Sandbox modes / named permission
121
+ profiles (`:read-only`, `:workspace`).
122
+ - **Input**: `{type:"text"}`, `{type:"image", url:"data:..."}` (inline data
123
+ URL — our base64 upload path works), `{type:"localImage", path}`, plus
124
+ skill invocation items (`{type:"skill", name, path}`).
125
+ - **History**: `thread/list` (cursor pagination, cwd filter, search),
126
+ `thread/read` (without resuming), `thread/turns/list`, archive/unarchive/
127
+ delete, `thread/name/set`. Replaces jsonl-scraping entirely.
128
+ - **MCP**: `mcpServerStatus/list` (tools + auth status — our whole `mcp.ts`
129
+ probe becomes one call), `mcpServer/oauth/login`, `config/mcpServer/reload`.
130
+ - **Usage**: `thread/tokenUsage/updated` streamed live (restored on resume);
131
+ `account/rateLimits/read` + `/updated`, `account/usage/read`.
132
+ - **Errors**: typed `codexErrorInfo` enum (`ContextWindowExceeded`,
133
+ `UsageLimitExceeded`, `HttpConnectionFailed{status}`, …).
134
+ - **Auth**: `account/read`, `account/login/start` (API key / ChatGPT OAuth /
135
+ device code), `account/updated` notifications.
136
+ - **Extras with no CC equivalent**: `review/start` (built-in reviewer),
137
+ `thread/shellCommand` (user `!` commands injected into the turn),
138
+ `command/exec` / `process/spawn` (sandboxed/unsandboxed exec with PTY),
139
+ `fs/*` + `fs/watch`, **dynamic client-provided tools** (`item/tool/call` —
140
+ the agent calls back into moi), `thread/compact/start`, structured
141
+ `outputSchema` per turn.
142
+
143
+ ### Caveats
144
+
145
+ - Much of the surface is gated behind `capabilities.experimentalApi` or marked
146
+ under development (plugins, environments, realtime). The core
147
+ thread/turn/item/approval/model surface is stable — it's what the VS Code
148
+ extension runs on.
149
+ - Typed bindings are generated, version-matched to the installed binary:
150
+ `codex app-server generate-ts --out DIR` (or `generate-json-schema`).
151
+
152
+ ### Binary availability (Codex Desktop caveat)
153
+
154
+ Don't assume Codex Desktop puts `codex` on PATH. The desktop app is a CLI
155
+ _consumer_: it resolves an external codex binary (honoring `CODEX_CLI_PATH`,
156
+ then PATH) and on first launch can install/update `@openai/codex` with a Node
157
+ runtime bundled inside the app — app-managed, not necessarily a shell-visible
158
+ `codex` command. Officially the CLI is a separate install (`npm i -g
159
+ @openai/codex`, brew, or the standalone installer). The adapter should detect
160
+ the binary: explicit config → `CODEX_CLI_PATH` → `codex` on PATH → error with
161
+ install instructions.
162
+
163
+ ## 3. Client libraries
164
+
165
+ - **TypeScript: nothing official.** `@openai/codex-sdk` wraps exec only.
166
+ - **Python: official** — `openai-codex` on PyPI (`sdk/python` in openai/codex)
167
+ is a real app-server client: subprocess + stdio JSON-RPC, message router,
168
+ generated pydantic models, approval handler callbacks. Good design
169
+ reference.
170
+ - Community TS/JS bridges exist (see the
171
+ [`codex-app-server` GitHub topic](https://github.com/topics/codex-app-server))
172
+ but are small/young.
173
+ - **Plan for moi**: write the thin client ourselves (~200 lines in Bun — spawn,
174
+ line-split stdio, id→promise map, notification + server-request routing;
175
+ same pattern as `../openclaw/gateway.ts`) and use `generate-ts` for
176
+ types.
177
+
178
+ ## 4. Adapter shape
179
+
180
+ A Codex harness would look much closer to `openclaw/session.ts` than
181
+ `claude-code/session.ts`: one long-lived connection to a server that owns session
182
+ lifecycle, subscribe per thread, map `item/*` notifications onto
183
+ `StreamEvent`s. Capability flags: `liveSettingsPerTurn`, `steering`,
184
+ `interactiveApprovals`, `nativeThreadList`, `imagesInline: 'data-url'`.
185
+
186
+ ## 5. Implementation notes (shipped, CLI 0.144.5)
187
+
188
+ The adapter landed as `client.ts` (process + stdio JSON-RPC client, one
189
+ app-server per workspace for env injection), `adapter.ts` (item →
190
+ `Turn` mapping, hand-written types), and `session.ts` (per-thread
191
+ state, steer/interrupt, previews, usage). Empirical findings beyond §2:
192
+
193
+ - **Always pass absolute `cwd`.** A relative `thread/start.cwd` is resolved
194
+ against the app-server process cwd, silently nesting paths.
195
+ - **Deltas stream by default** — no opt-in needed; moi's `stream` flag only
196
+ gates forwarding them as preview frames.
197
+ - **Reasoning summaries need `summary: "auto"` on `turn/start`.** Without it
198
+ the model still reasons (nonzero `reasoningOutputTokens`) but the
199
+ `reasoning` item arrives with EMPTY `summary`/`content` — thinking is
200
+ invisible. With it, summaries stream via `item/reasoning/summaryTextDelta`
201
+ and land populated. Also note reasoning is adaptive: trivial prompts at low
202
+ effort legitimately produce no reasoning item at all.
203
+ - **Subagents (collab tools) work unflagged**: the parent emits
204
+ `collabAgentToolCall` (spawn/send/wait/close) and `subAgentActivity` items;
205
+ the child agent runs as its own thread whose full item stream arrives on
206
+ the same connection under `agentThreadId`.
207
+ - **`clientUserMessageId` echo confirmed**: the `userMessage` item carries it
208
+ as `clientId`, on live frames only. `thread/read` replay _renumbers_ item
209
+ ids (`item-1`, `item-2`, …) and drops `clientId`, so replayed turn ids never
210
+ match live ones — harmless under upsert-by-id, but don't key anything
211
+ durable on them.
212
+ - **`turn/completed` carries no items** (`itemsView: "notLoaded"`); items
213
+ arrive only via `item/started`/`item/completed`.
214
+ - **The npm `codex` bin is a Node shim** that spawns the platform binary;
215
+ killing the shim tears down the server via stdin EOF, so no orphans — but
216
+ binary detection must tolerate shim paths (`CODEX_CLI_PATH` → PATH).
217
+ - **User-level config bleeds in**: threads start MCP servers and hooks from
218
+ `~/.codex/config.toml` / `hooks.json` per thread; their failures arrive as
219
+ notifications (`mcpServer/startupStatus/updated`, `hook/completed`) we
220
+ currently ignore.
221
+ - `thread/start` responses label threads `source: "vscode"` — app-server
222
+ clients are indistinguishable from the VS Code extension in `thread/list`.
223
+
224
+ ## 6. Type maintenance (`generate-ts`)
225
+
226
+ The wire types in `adapter.ts`/`client.ts` are a hand-written defensive
227
+ subset of the protocol, produced against the bindings from:
228
+
229
+ ```
230
+ codex app-server generate-ts --out /tmp/codex-types # CLI 0.144.5
231
+ ```
232
+
233
+ They are deliberately NOT generated at build time: users run arbitrary codex
234
+ CLI versions, so the runtime reads frames defensively regardless, and
235
+ vendoring ~600 generated files (or generating in CI) would couple typecheck
236
+ to an installed codex binary. When bumping the supported CLI version, re-run
237
+ `generate-ts` into a scratch dir and diff the relevant definitions
238
+ (`v2/ThreadItem`, `v2/TurnStartParams`, `ServerNotification`, `ServerRequest`)
239
+ against the subset here.