moi-computer 0.3.0-next.1 → 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 (206) hide show
  1. package/README.md +1 -1
  2. package/bunfig.toml +5 -1
  3. package/client/AGENTS.md +17 -2
  4. package/client/accept-hmr-dependencies.ts +22 -0
  5. package/client/api/http.ts +31 -0
  6. package/client/api/query-options.ts +6 -0
  7. package/client/api/workspace-keys.ts +18 -0
  8. package/client/app/AppRouter.tsx +44 -0
  9. package/client/app/routes/HomeRoute.tsx +13 -0
  10. package/client/app/routes/WorkspaceRoute.tsx +95 -0
  11. package/client/app/shell/SidebarLayout.tsx +196 -0
  12. package/client/assets/openai.svg +3 -0
  13. package/client/assets.d.ts +9 -0
  14. package/client/components/{BottomPanel.tsx → shared/BottomPanel.tsx} +2 -2
  15. package/client/components/shared/PanelHeader.tsx +9 -0
  16. package/client/components/shared/ReorderableList.tsx +199 -0
  17. package/client/components/ui/button.tsx +11 -7
  18. package/client/components/ui/collapsible.tsx +15 -0
  19. package/client/components/ui/dialog.tsx +2 -2
  20. package/client/components/ui/dropdown-menu.tsx +5 -5
  21. package/client/components/ui/hover-card.tsx +1 -1
  22. package/client/components/ui/input.tsx +1 -1
  23. package/client/components/ui/popover.tsx +1 -1
  24. package/client/components/ui/skeleton.tsx +13 -0
  25. package/client/components/ui/tooltip.tsx +1 -1
  26. package/client/externalize-react.ts +7 -1
  27. package/client/features/applets/AppletMount.tsx +44 -0
  28. package/client/{components → features/applets}/WidgetErrorBoundary.tsx +1 -1
  29. package/client/{components → features/applets}/WidgetShell.tsx +5 -2
  30. package/client/{lib → features/applets}/applet-cache.ts +8 -0
  31. package/client/features/applets/applet-styles.ts +61 -0
  32. package/client/{hooks → features/applets}/useApplet.ts +6 -7
  33. package/client/{components/ChatInput.tsx → features/chat/ChatComposer.tsx} +30 -24
  34. package/client/features/chat/ChatPanel.tsx +171 -0
  35. package/client/{components → features/chat}/ChatPopup.tsx +24 -13
  36. package/client/{components/ThreadSelector.tsx → features/chat/ChatSelector.tsx} +15 -13
  37. package/client/{components → features/chat}/MarkdownContent.tsx +1 -1
  38. package/client/{components → features/chat}/ModelPicker.tsx +68 -17
  39. package/client/{components → features/chat}/TurnView.tsx +17 -11
  40. package/client/features/chat/api.ts +78 -0
  41. package/client/features/chat/chat-connection.ts +107 -0
  42. package/client/features/chat/chat-frames.ts +131 -0
  43. package/client/features/chat/chat-send.ts +57 -0
  44. package/client/{lib → features/chat}/preview-turn.ts +1 -1
  45. package/client/{components → features/chat}/tool-group/ReadImagePreview.tsx +1 -1
  46. package/client/{components → features/chat}/tool-group/SubagentCard.tsx +12 -10
  47. package/client/{components → features/chat}/tool-group/TimelineRow.tsx +5 -5
  48. package/client/{components → features/chat}/tool-group/ToolCallGroup.tsx +14 -5
  49. package/client/{components → features/chat}/tool-group/ToolOutput.tsx +12 -18
  50. package/client/{components → features/chat}/tool-group/format.ts +117 -0
  51. package/client/{hooks → features/chat}/useChat.ts +16 -44
  52. package/client/features/connectors/ConnectorsPage.tsx +92 -0
  53. package/client/features/connectors/McpMenu.tsx +145 -0
  54. package/client/features/connectors/api.ts +28 -0
  55. package/client/features/dev/DevRoutes.tsx +18 -0
  56. package/client/features/dev/HarnessDebugPage.tsx +468 -0
  57. package/client/{components/playground → features/dev}/PixelPainter.tsx +10 -21
  58. package/client/{components/playground → features/dev}/PlaygroundPage.tsx +10 -12
  59. package/client/{components/playground → features/dev}/ToolCallsPage.tsx +9 -11
  60. package/client/features/home/CreateWorkspaceDialog.tsx +130 -0
  61. package/client/features/home/CreateWorkspaceDialogSteps.tsx +234 -0
  62. package/client/features/home/HomeLogo.tsx +344 -0
  63. package/client/features/home/HomePage.tsx +214 -0
  64. package/client/{components → features/home}/WorkspacePreview.tsx +4 -4
  65. package/client/features/home/api.ts +156 -0
  66. package/client/features/home/workspace-presentation.tsx +44 -0
  67. package/client/features/scratchpad/Scratchpad.tsx +312 -0
  68. package/client/features/scratchpad/ScratchpadControls.tsx +503 -0
  69. package/client/features/scratchpad/useScratchpadSnapshot.tsx +115 -0
  70. package/client/features/settings/EnvironmentSettings.tsx +149 -0
  71. package/client/features/settings/GeneralSettings.tsx +90 -0
  72. package/client/{components → features}/settings/IconPicker.tsx +76 -224
  73. package/client/features/settings/SettingsLayout.tsx +53 -0
  74. package/client/{components → features}/settings/WorkspaceSettings.tsx +12 -16
  75. package/client/features/settings/api.ts +88 -0
  76. package/client/features/settings/icon-picker-options.ts +30 -0
  77. package/client/{hooks → features/settings}/useEnvVars.ts +4 -4
  78. package/client/features/views/ViewBuilderTab.tsx +153 -0
  79. package/client/features/views/api.ts +124 -0
  80. package/client/features/views/useViewBuilderActions.ts +72 -0
  81. package/client/{components → features/widgets}/HiddenPanel.tsx +3 -3
  82. package/client/{components → features/widgets}/WidgetFrame.tsx +3 -8
  83. package/client/{components → features/widgets}/WidgetGrid.tsx +38 -29
  84. package/client/features/widgets/Widgets.tsx +265 -0
  85. package/client/{lib/grid-pack.ts → features/widgets/grid.ts} +7 -1
  86. package/client/{hooks → features/widgets}/useGridReconcile.ts +1 -1
  87. package/client/{components → features/workspace}/CustomizePanel.tsx +5 -6
  88. package/client/{lib → features/workspace}/WorkspaceLayoutContext.tsx +16 -15
  89. package/client/features/workspace/WorkspaceScreen.tsx +675 -0
  90. package/client/features/workspace/WorkspaceTabs.tsx +205 -0
  91. package/client/features/workspace/api.ts +56 -0
  92. package/client/features/workspace/useFitsSplitLayout.ts +37 -0
  93. package/client/global.d.ts +5 -0
  94. package/client/index.css +6 -45
  95. package/client/index.html +2 -2
  96. package/client/index.tsx +14 -31
  97. package/client/lib/app-icon-registry.ts +145 -0
  98. package/client/main.tsx +2 -2
  99. package/client/runtime/hmr-watchdog.ts +39 -0
  100. package/client/{hooks/useMeiEvents.ts → runtime/useWorkspaceEvents.ts} +12 -7
  101. package/client/store/ui.ts +5 -1
  102. package/client/theme.css +1 -3
  103. package/dist/chunk-11cab5dq.css +1 -0
  104. package/dist/chunk-4vf1t6v1.js +10 -0
  105. package/dist/chunk-6c24yndg.js +61 -0
  106. package/dist/chunk-6c8cwpzc.js +1 -0
  107. package/dist/chunk-b4b276wx.js +15 -0
  108. package/dist/chunk-cs8vbert.js +546 -0
  109. package/dist/chunk-cwqmay73.css +1 -0
  110. package/dist/chunk-kxmvv1ax.js +48 -0
  111. package/dist/chunk-pcnahct1.js +5 -0
  112. package/dist/chunk-rq0ar7vp.js +1 -0
  113. package/dist/chunk-tqd3pkg8.css +1 -0
  114. package/dist/chunk-vkvb3hjm.js +2 -0
  115. package/dist/chunk-zpxrb1ce.js +2 -0
  116. package/dist/index.html +3 -3
  117. package/dist/openai-h13pza4b.svg +3 -0
  118. package/lib/format.ts +2 -2
  119. package/lib/types.ts +56 -9
  120. package/lib/view-builder-meta.ts +35 -0
  121. package/lib/workspace-layout.ts +14 -0
  122. package/lib/workspace-name.ts +14 -0
  123. package/package.json +4 -2
  124. package/server/AGENTS.md +3 -3
  125. package/server/api.ts +279 -60
  126. package/server/applets.ts +1 -1
  127. package/server/bundle-queue.ts +19 -0
  128. package/server/bundler/applet-css.ts +50 -0
  129. package/server/{build-applet.ts → bundler/build-applet.ts} +36 -26
  130. package/server/cli.ts +90 -7
  131. package/server/control.ts +106 -8
  132. package/server/env-apply.ts +2 -2
  133. package/server/harness/README.md +228 -0
  134. package/server/harness/claude-code/NOTES.md +578 -0
  135. package/{lib/claude-adapter.ts → server/harness/claude-code/adapter.ts} +67 -5
  136. package/server/harness/claude-code/index.ts +124 -0
  137. package/server/{mcp.ts → harness/claude-code/mcp.ts} +73 -16
  138. package/server/{cc-session.ts → harness/claude-code/session.ts} +42 -14
  139. package/server/harness/claude-code/sessions.ts +42 -0
  140. package/server/harness/codex/NOTES.md +239 -0
  141. package/server/harness/codex/adapter.ts +414 -0
  142. package/server/harness/codex/client.ts +343 -0
  143. package/server/harness/codex/index.ts +68 -0
  144. package/server/harness/codex/probe.ts +186 -0
  145. package/server/harness/codex/session.ts +617 -0
  146. package/server/harness/debug.ts +57 -0
  147. package/server/harness/openclaw/NOTES.md +316 -0
  148. package/server/{openclaw-adapter.ts → harness/openclaw/adapter.ts} +2 -2
  149. package/server/harness/openclaw/index.ts +93 -0
  150. package/server/{openclaw-session.ts → harness/openclaw/session.ts} +44 -9
  151. package/server/{openclaw-strip.ts → harness/openclaw/strip.ts} +3 -1
  152. package/server/harness/registry.ts +36 -0
  153. package/server/harness/types.ts +87 -0
  154. package/server/layout.ts +36 -11
  155. package/server/moi-scaffold.ts +56 -11
  156. package/server/registry.ts +30 -52
  157. package/server/state.ts +5 -38
  158. package/server/status.ts +7 -46
  159. package/server/vendor.ts +1 -1
  160. package/server/view-builders.ts +428 -0
  161. package/server/views.ts +0 -0
  162. package/server/web.ts +19 -40
  163. package/server/workspace-init.ts +11 -25
  164. package/tsconfig.json +1 -1
  165. package/workspace/.claude/skills/moi-workspace/DESIGN.md +2 -1
  166. package/workspace/.claude/skills/moi-workspace/SKILL.md +28 -7
  167. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +1 -1
  168. package/client/api/workspaces.ts +0 -427
  169. package/client/assets/hermes-nous.png +0 -0
  170. package/client/components/App.tsx +0 -41
  171. package/client/components/ChatPanel.tsx +0 -275
  172. package/client/components/HomePage.tsx +0 -17
  173. package/client/components/McpMenu.tsx +0 -125
  174. package/client/components/Scratchpad.tsx +0 -935
  175. package/client/components/Widgets.tsx +0 -132
  176. package/client/components/WorkspacesPage.tsx +0 -245
  177. package/client/components/layout/SidebarLayout.tsx +0 -258
  178. package/client/components/routes/workspace/[id].tsx +0 -675
  179. package/client/components/routes/workspace/create.tsx +0 -155
  180. package/client/components/settings/SettingsPages.tsx +0 -255
  181. package/client/hooks/useFitsSidebar.ts +0 -34
  182. package/client/hooks/useScrollFade.ts +0 -38
  183. package/client/lib/connection.ts +0 -238
  184. package/dist/chunk-07qf2tv1.css +0 -1
  185. package/dist/chunk-w18801vn.js +0 -672
  186. package/dist/hermes-nous-pznd63x9.png +0 -0
  187. /package/client/components/{playground → shared}/LedLogo.tsx +0 -0
  188. /package/client/{components → features/chat}/ShimmerText.tsx +0 -0
  189. /package/client/{store/live.ts → features/chat/chat-store.ts} +0 -0
  190. /package/client/{lib → features/chat}/group-turns.ts +0 -0
  191. /package/client/{components → features/chat}/tool-group/CodeBlock.tsx +0 -0
  192. /package/client/{components → features/chat}/tool-group/Collapse.tsx +0 -0
  193. /package/client/{components → features/chat}/tool-group/detect.ts +0 -0
  194. /package/client/{components → features/chat}/tool-group/fixtures.ts +0 -0
  195. /package/client/{components → features/chat}/tool-group/index.ts +0 -0
  196. /package/client/{lib → features/chat}/uploads.ts +0 -0
  197. /package/client/{hooks → features/chat}/useStickToBottom.ts +0 -0
  198. /package/client/{components → features/connectors}/IconMcp.tsx +0 -0
  199. /package/client/{lib → features/connectors}/mcp-icons.ts +0 -0
  200. /package/client/{lib → features/scratchpad}/scratch-executor.ts +0 -0
  201. /package/client/{lib → features/settings}/render-icon.ts +0 -0
  202. /package/client/{lib → features/workspace}/WorkspaceContext.tsx +0 -0
  203. /package/client/{hooks → features/workspace}/useWorkspaceTheme.ts +0 -0
  204. /package/server/{agent.ts → harness/claude-code/models.ts} +0 -0
  205. /package/server/{openclaw.ts → harness/openclaw/discovery.ts} +0 -0
  206. /package/server/{openclaw-gateway.ts → harness/openclaw/gateway.ts} +0 -0
@@ -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.
@@ -0,0 +1,414 @@
1
+ // Map Codex app-server shapes into our agent-agnostic display format.
2
+ //
3
+ // Codex emits semantic ThreadItems (a command, a patch, an MCP call) with
4
+ // their own lifecycle (`item/started` → `item/completed`), not raw
5
+ // tool_use/tool_result pairs. Each item becomes one Turn: `userMessage` a
6
+ // user turn, everything else an assistant turn; tool-shaped items carry a
7
+ // single `tool-call` part whose state tracks the item's `status`.
8
+ //
9
+ // Type shapes are hand-written against `codex app-server generate-ts`
10
+ // (CLI 0.144.5) and read defensively — see ./NOTES.md.
11
+ import type { Part, StreamEvent, SystemNotice, ToolCall, ToolState, Turn } from '@/lib/format'
12
+ import type { Model, SessionInfo } from '@/lib/types'
13
+
14
+ // ---- protocol shapes (subset we consume) ------------------------------------
15
+
16
+ export type CodexUserInput =
17
+ | { type: 'text'; text: string }
18
+ | { type: 'image'; url: string }
19
+ | { type: 'localImage'; path: string }
20
+
21
+ export type CodexThreadItem = {
22
+ type: string
23
+ id: string
24
+ // userMessage
25
+ clientId?: string | null
26
+ content?: CodexUserInput[]
27
+ // agentMessage / plan
28
+ text?: string
29
+ phase?: string | null
30
+ // reasoning
31
+ summary?: string[]
32
+ // commandExecution
33
+ command?: string
34
+ cwd?: string
35
+ status?: string
36
+ aggregatedOutput?: string | null
37
+ exitCode?: number | null
38
+ durationMs?: number | null
39
+ // Codex's own parse of what the command does (read/listFiles/search/
40
+ // unknown) — one entry per piped command. Drives CC-style semantic labels.
41
+ commandActions?: {
42
+ type?: string
43
+ command?: string
44
+ name?: string
45
+ path?: string
46
+ query?: string | null
47
+ }[]
48
+ // fileChange
49
+ changes?: { path: string; kind?: { type?: string }; diff?: string }[]
50
+ // mcpToolCall
51
+ server?: string
52
+ tool?: string
53
+ arguments?: unknown
54
+ result?: { content?: unknown[]; structuredContent?: unknown } | null
55
+ error?: { message?: string } | null
56
+ // webSearch
57
+ query?: string
58
+ action?: { query?: string | null; queries?: (string | null)[] | null } | null
59
+ // imageGeneration
60
+ revisedPrompt?: string | null
61
+ // collabAgentToolCall (tool reused from mcpToolCall above)
62
+ prompt?: string | null
63
+ senderThreadId?: string
64
+ receiverThreadIds?: string[]
65
+ // subAgentActivity
66
+ kind?: string
67
+ agentThreadId?: string
68
+ agentPath?: string
69
+ }
70
+
71
+ export type CodexTurn = {
72
+ id: string
73
+ items: CodexThreadItem[]
74
+ status: string
75
+ error?: { message?: string; codexErrorInfo?: unknown } | null
76
+ }
77
+
78
+ export type CodexThread = {
79
+ id: string
80
+ preview?: string
81
+ cwd?: string
82
+ createdAt?: number
83
+ updatedAt?: number
84
+ name?: string | null
85
+ turns?: CodexTurn[]
86
+ }
87
+
88
+ export type CodexTokenUsage = {
89
+ total?: { totalTokens?: number; inputTokens?: number; outputTokens?: number }
90
+ last?: { totalTokens?: number; inputTokens?: number; outputTokens?: number }
91
+ }
92
+
93
+ export type CodexModel = {
94
+ id: string
95
+ model: string
96
+ displayName: string
97
+ description?: string
98
+ hidden?: boolean
99
+ supportedReasoningEfforts?: { reasoningEffort: string; description?: string }[]
100
+ defaultReasoningEffort?: string
101
+ isDefault?: boolean
102
+ }
103
+
104
+ // ---- discovery mappings ------------------------------------------------------
105
+
106
+ export function codexThreadToSessionInfo(t: CodexThread): SessionInfo {
107
+ return {
108
+ sessionId: t.id,
109
+ summary: t.name?.trim() || t.preview?.trim() || '',
110
+ // Codex timestamps are unix seconds; SessionInfo wants millis.
111
+ lastModified: (t.updatedAt ?? t.createdAt ?? 0) * 1000,
112
+ cwd: t.cwd
113
+ }
114
+ }
115
+
116
+ export function codexModelToModel(m: CodexModel): Model {
117
+ const efforts = (m.supportedReasoningEfforts ?? []).map(e => e.reasoningEffort)
118
+ return {
119
+ value: m.id,
120
+ resolvedModel: m.model,
121
+ displayName: m.displayName,
122
+ // Our Model.description is a " · "-joined "<headline> · <tagline>" blurb
123
+ // (the picker renders the first segment as the row label), so lead with
124
+ // the display name and let Codex's one-liner be the tagline.
125
+ ...(m.description
126
+ ? { description: `${m.displayName} · ${m.description}` }
127
+ : { description: m.displayName }),
128
+ supportsEffort: efforts.length > 0,
129
+ ...(efforts.length > 0 ? { supportedEffortLevels: efforts } : {})
130
+ }
131
+ }
132
+
133
+ // ---- item → turn -------------------------------------------------------------
134
+
135
+ function statusToToolState(status: string | undefined): ToolState {
136
+ switch (status) {
137
+ case 'inProgress':
138
+ return 'running'
139
+ case 'completed':
140
+ return 'success'
141
+ case 'failed':
142
+ return 'error'
143
+ case 'declined':
144
+ return 'approval-denied'
145
+ default:
146
+ return 'pending'
147
+ }
148
+ }
149
+
150
+ function userInputToParts(content: CodexUserInput[] | undefined): Part[] {
151
+ const parts: Part[] = []
152
+ for (const c of content ?? []) {
153
+ if (c.type === 'text' && c.text) parts.push({ type: 'text', text: c.text })
154
+ else if (c.type === 'image' && c.url)
155
+ parts.push({ type: 'file', mediaType: 'image/*', url: c.url })
156
+ else if (c.type === 'localImage' && c.path)
157
+ parts.push({ type: 'text', text: `[image: ${c.path}]` })
158
+ }
159
+ return parts
160
+ }
161
+
162
+ // Flatten an MCP result's content blocks into a readable string (same
163
+ // approach as the OpenClaw adapter — text blocks joined, others tagged).
164
+ function flattenMcpResult(result: CodexThreadItem['result']): string {
165
+ if (!result) return ''
166
+ if (result.structuredContent !== undefined && result.structuredContent !== null) {
167
+ return JSON.stringify(result.structuredContent, null, 2)
168
+ }
169
+ const blocks = Array.isArray(result.content) ? result.content : []
170
+ return blocks
171
+ .map(b => {
172
+ if (b && typeof b === 'object' && (b as { type?: string }).type === 'text') {
173
+ const t = (b as { text?: unknown }).text
174
+ return typeof t === 'string' ? t : ''
175
+ }
176
+ return b && typeof b === 'object' ? `[${(b as { type?: string }).type ?? 'block'}]` : ''
177
+ })
178
+ .filter(Boolean)
179
+ .join('\n')
180
+ }
181
+
182
+ function itemToToolCall(item: CodexThreadItem): ToolCall | null {
183
+ switch (item.type) {
184
+ case 'commandExecution': {
185
+ const call: ToolCall = {
186
+ toolCallId: item.id,
187
+ name: 'exec',
188
+ caller: 'model',
189
+ provider: 'codex',
190
+ state: statusToToolState(item.status),
191
+ input: {
192
+ command: item.command,
193
+ cwd: item.cwd,
194
+ ...(item.commandActions?.length ? { commandActions: item.commandActions } : {})
195
+ }
196
+ }
197
+ if (item.aggregatedOutput) {
198
+ if (call.state === 'error') call.errorText = item.aggregatedOutput
199
+ else call.output = item.aggregatedOutput
200
+ }
201
+ if (typeof item.exitCode === 'number' || typeof item.durationMs === 'number') {
202
+ call.sidecar = { exitCode: item.exitCode, durationMs: item.durationMs }
203
+ }
204
+ return call
205
+ }
206
+ case 'fileChange': {
207
+ return {
208
+ toolCallId: item.id,
209
+ name: 'apply_patch',
210
+ caller: 'model',
211
+ provider: 'codex',
212
+ state: statusToToolState(item.status),
213
+ input: {
214
+ changes: (item.changes ?? []).map(c => ({
215
+ path: c.path,
216
+ kind: c.kind?.type,
217
+ diff: c.diff
218
+ }))
219
+ }
220
+ }
221
+ }
222
+ case 'mcpToolCall': {
223
+ const call: ToolCall = {
224
+ toolCallId: item.id,
225
+ name: item.tool ?? 'mcp',
226
+ caller: 'model',
227
+ provider: 'codex',
228
+ mcpServer: item.server,
229
+ state: statusToToolState(item.status),
230
+ input: item.arguments
231
+ }
232
+ const output = flattenMcpResult(item.result)
233
+ if (item.error?.message) {
234
+ call.state = 'error'
235
+ call.errorText = item.error.message
236
+ } else if (output) {
237
+ call.output = output
238
+ }
239
+ return call
240
+ }
241
+ case 'webSearch': {
242
+ // A single item can fan out into several queries (`action.queries`).
243
+ const queries = (item.action?.queries ?? []).filter(
244
+ (q): q is string => typeof q === 'string' && q.length > 0
245
+ )
246
+ return {
247
+ toolCallId: item.id,
248
+ name: 'web_search',
249
+ caller: 'model',
250
+ provider: 'codex',
251
+ // webSearch items have no lifecycle status; they appear when done.
252
+ state: 'success',
253
+ input: { query: item.query, ...(queries.length ? { queries } : {}) }
254
+ }
255
+ }
256
+ case 'plan': {
257
+ return {
258
+ toolCallId: item.id,
259
+ name: 'update_plan',
260
+ caller: 'model',
261
+ provider: 'codex',
262
+ state: 'success',
263
+ input: { plan: item.text }
264
+ }
265
+ }
266
+ // Codex multi-agent: the parent's collab tool invocations (spawn / send /
267
+ // wait / close). The child agent runs as its OWN thread whose items
268
+ // stream on the same connection under `agentThreadId` — nesting that
269
+ // transcript into a SubagentRecord is future work; for now the card makes
270
+ // the spawn/wait visible instead of silently dropping it.
271
+ case 'collabAgentToolCall': {
272
+ return {
273
+ toolCallId: item.id,
274
+ name: 'subagent',
275
+ caller: 'subagent',
276
+ provider: 'codex',
277
+ state: statusToToolState(item.status),
278
+ input: {
279
+ action: item.tool,
280
+ ...(item.prompt ? { prompt: item.prompt } : {}),
281
+ ...(item.receiverThreadIds?.length ? { agents: item.receiverThreadIds } : {})
282
+ }
283
+ }
284
+ }
285
+ case 'subAgentActivity': {
286
+ // The card that carries the child agent's nested transcript: the
287
+ // session layer correlates the child thread (`agentThreadId`) and
288
+ // attaches a SubagentRecord to this call (see session.ts).
289
+ return {
290
+ toolCallId: item.id,
291
+ name: 'subagent_activity',
292
+ caller: 'subagent',
293
+ provider: 'codex',
294
+ state: 'success',
295
+ input: { kind: item.kind, agentThreadId: item.agentThreadId, agentPath: item.agentPath }
296
+ }
297
+ }
298
+ case 'enteredReviewMode':
299
+ case 'exitedReviewMode': {
300
+ return {
301
+ toolCallId: item.id,
302
+ name: 'review',
303
+ caller: 'model',
304
+ provider: 'codex',
305
+ state: 'success',
306
+ input: {
307
+ phase: item.type === 'enteredReviewMode' ? 'entered' : 'exited',
308
+ review: item.text ?? (item as { review?: string }).review
309
+ }
310
+ }
311
+ }
312
+ case 'imageView': {
313
+ return {
314
+ toolCallId: item.id,
315
+ name: 'view_image',
316
+ caller: 'model',
317
+ provider: 'codex',
318
+ state: 'success',
319
+ input: { path: (item as { path?: string }).path }
320
+ }
321
+ }
322
+ case 'imageGeneration': {
323
+ // `revisedPrompt` is the model's final prompt; the item also carries
324
+ // `result` — the ENTIRE generated image as base64 (megabytes). Never
325
+ // fold that into the turn: it would ride every broadcast/replay.
326
+ return {
327
+ toolCallId: item.id,
328
+ name: 'generate_image',
329
+ caller: 'model',
330
+ provider: 'codex',
331
+ state: statusToToolState(item.status),
332
+ input: { ...(item.revisedPrompt ? { prompt: item.revisedPrompt } : {}) }
333
+ }
334
+ }
335
+ default:
336
+ return null
337
+ }
338
+ }
339
+
340
+ // Build a Turn from one Codex ThreadItem, or null for item kinds we don't
341
+ // render (contextCompaction becomes a notice — see itemToNotice).
342
+ export function codexItemToTurn(item: CodexThreadItem, threadId: string): Turn | null {
343
+ const turnId = `codex:${threadId}:${item.id}`
344
+ if (item.type === 'userMessage') {
345
+ const parts = userInputToParts(item.content)
346
+ if (parts.length === 0) return null
347
+ return {
348
+ // The echo carries our optimistic id back as `clientId` — reusing it
349
+ // upserts the sender's optimistic bubble in place of a duplicate.
350
+ id: item.clientId || turnId,
351
+ role: 'user',
352
+ origin: { kind: 'user-input' },
353
+ parts
354
+ }
355
+ }
356
+ if (item.type === 'agentMessage') {
357
+ if (!item.text) return null
358
+ return {
359
+ id: turnId,
360
+ role: 'assistant',
361
+ origin: { kind: 'user-input' },
362
+ parts: [{ type: 'text', text: item.text }],
363
+ // The item id keys the live token preview; reporting it as the
364
+ // apiMessageId lets the client clear that preview when the turn lands.
365
+ meta: { apiMessageId: item.id }
366
+ }
367
+ }
368
+ if (item.type === 'reasoning') {
369
+ const text = (item.summary ?? []).filter(Boolean).join('\n\n')
370
+ if (!text) return null
371
+ return {
372
+ id: turnId,
373
+ role: 'assistant',
374
+ origin: { kind: 'user-input' },
375
+ parts: [{ type: 'reasoning', text }],
376
+ meta: { apiMessageId: item.id }
377
+ }
378
+ }
379
+ const call = itemToToolCall(item)
380
+ if (!call) return null
381
+ return {
382
+ id: turnId,
383
+ role: 'assistant',
384
+ origin: { kind: 'user-input' },
385
+ parts: [{ type: 'tool-call', call }]
386
+ }
387
+ }
388
+
389
+ export function codexItemToNotice(item: CodexThreadItem, threadId: string): SystemNotice | null {
390
+ if (item.type !== 'contextCompaction') return null
391
+ return {
392
+ id: `codex:${threadId}:${item.id}`,
393
+ kind: 'compact',
394
+ at: new Date().toISOString()
395
+ }
396
+ }
397
+
398
+ // Static replay path: map a `thread/read`/`thread/resume` payload (turns
399
+ // included) onto StreamEvents for the REST events endpoint.
400
+ export function codexThreadToEvents(thread: CodexThread): StreamEvent[] {
401
+ const events: StreamEvent[] = []
402
+ for (const turn of thread.turns ?? []) {
403
+ for (const item of turn.items ?? []) {
404
+ const t = codexItemToTurn(item, thread.id)
405
+ if (t) {
406
+ events.push({ kind: 'turn', turn: t })
407
+ continue
408
+ }
409
+ const n = codexItemToNotice(item, thread.id)
410
+ if (n) events.push({ kind: 'notice', notice: n })
411
+ }
412
+ }
413
+ return events
414
+ }