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,343 @@
1
+ // Long-lived `codex app-server` client, one process per workspace.
2
+ //
3
+ // The app-server is a JSON-RPC 2.0 server over stdio (newline-delimited JSON)
4
+ // bundled with the Codex CLI — the same protocol the official VS Code
5
+ // extension drives. One process serves every thread of one workspace: threads
6
+ // carry their own cwd, but env is process-level, so per-workspace env
7
+ // injection (moi's `workspaceEnv`) forces one process per workspace — same
8
+ // frozen-at-spawn semantics as the Claude Code subprocess (`cc-session.ts`).
9
+ //
10
+ // Protocol shapes here are hand-written against the bindings generated by
11
+ // `codex app-server generate-ts` at CLI 0.144.5, and read defensively — see
12
+ // ./NOTES.md.
13
+ import type { McpServer, Model, SessionInfo, StreamEvent } from '@/lib/types'
14
+
15
+ import {
16
+ type CodexModel,
17
+ type CodexThread,
18
+ codexModelToModel,
19
+ codexThreadToEvents,
20
+ codexThreadToSessionInfo
21
+ } from './adapter'
22
+ import { debug } from '../../debug'
23
+ import { tapWire } from '../debug'
24
+ import { resolveWorkspaceEnv } from '../../workspace-env'
25
+
26
+ const REQUEST_TIMEOUT_MS = 30_000
27
+
28
+ type Json = Record<string, unknown>
29
+ type NotificationListener = (method: string, params: Json) => void
30
+
31
+ // Every JSON-RPC frame in either direction lands in the shared wire ring
32
+ // (server/harness-debug.ts, scoped by workspacePath), kept OUTSIDE the client
33
+ // record so it survives process death. Read via /api/.../harness/debug.
34
+
35
+ export type CodexProcessInfo = {
36
+ running: boolean
37
+ pid?: number
38
+ binary: string | null
39
+ }
40
+
41
+ export function getCodexProcessInfo(workspacePath: string): Promise<CodexProcessInfo> {
42
+ const rec = clients.get(workspacePath)
43
+ const binary = findCodexBinary()
44
+ if (!rec) return Promise.resolve({ running: false, binary })
45
+ return rec
46
+ .then(r => ({ running: r.client.isAlive(), pid: r.proc.pid, binary }))
47
+ .catch(() => ({ running: false, binary }))
48
+ }
49
+
50
+ export type CodexClient = {
51
+ rpc: <T>(method: string, params?: Json) => Promise<T>
52
+ onNotification: (l: NotificationListener) => () => void
53
+ isAlive: () => boolean
54
+ workspacePath: string
55
+ }
56
+
57
+ // Locate the codex binary. Codex Desktop does NOT guarantee a `codex` on PATH
58
+ // (it manages an app-internal install), so honor an explicit override first.
59
+ export function findCodexBinary(): string | null {
60
+ const explicit = process.env.CODEX_CLI_PATH
61
+ if (explicit) return explicit
62
+ return Bun.which('codex')
63
+ }
64
+
65
+ type ClientRecord = {
66
+ client: CodexClient
67
+ proc: ReturnType<typeof Bun.spawn>
68
+ }
69
+
70
+ const clients = new Map<string, Promise<ClientRecord>>() // key: workspacePath
71
+
72
+ async function startClient(workspacePath: string): Promise<ClientRecord> {
73
+ const bin = findCodexBinary()
74
+ if (!bin) {
75
+ throw new Error(
76
+ 'codex CLI not found — install it (`npm i -g @openai/codex`) or set CODEX_CLI_PATH'
77
+ )
78
+ }
79
+
80
+ const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
81
+ const proc = Bun.spawn([bin, 'app-server'], {
82
+ cwd: workspacePath,
83
+ stdin: 'pipe',
84
+ stdout: 'pipe',
85
+ stderr: 'pipe',
86
+ env: { ...process.env, ...workspaceEnv }
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 }
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('codex app-server not running'))
105
+ const id = nextId++
106
+ send({ jsonrpc: '2.0', id, method, params })
107
+ return new Promise<T>((resolve, reject) => {
108
+ const timer = setTimeout(() => {
109
+ pending.delete(id)
110
+ reject(new Error(`codex rpc timeout: ${method}`))
111
+ }, REQUEST_TIMEOUT_MS)
112
+ pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer })
113
+ })
114
+ }
115
+
116
+ function fanout(method: string, params: Json) {
117
+ for (const l of listeners) {
118
+ try {
119
+ l(method, params)
120
+ } catch (err) {
121
+ console.error('[codex] notification listener threw', err)
122
+ }
123
+ }
124
+ }
125
+
126
+ // Server→client requests MUST be answered or the turn hangs. We run threads
127
+ // with `approvalPolicy: 'never'`, so approval requests should not occur —
128
+ // accept defensively if one does; reject anything else as unsupported.
129
+ function answerServerRequest(msg: Json) {
130
+ const method = msg.method as string
131
+ if (method.endsWith('requestApproval') || method === 'applyPatchApproval') {
132
+ send({ jsonrpc: '2.0', id: msg.id, result: { decision: 'accept' } })
133
+ } else if (method === 'execCommandApproval') {
134
+ send({ jsonrpc: '2.0', id: msg.id, result: { decision: 'approved' } })
135
+ } else {
136
+ send({
137
+ jsonrpc: '2.0',
138
+ id: msg.id,
139
+ error: { code: -32601, message: `moi does not handle ${method}` }
140
+ })
141
+ }
142
+ }
143
+
144
+ function handleLine(line: string) {
145
+ if (!line.trim()) return
146
+ let msg: Json
147
+ try {
148
+ msg = JSON.parse(line) as Json
149
+ } catch {
150
+ return
151
+ }
152
+ tapWire(workspacePath, 'recv', msg)
153
+ if ('id' in msg && 'method' in msg) {
154
+ answerServerRequest(msg)
155
+ } else if ('id' in msg) {
156
+ const p = pending.get(msg.id as number)
157
+ if (!p) return
158
+ pending.delete(msg.id as number)
159
+ clearTimeout(p.timer)
160
+ if ('error' in msg) {
161
+ const e = msg.error as { message?: string } | undefined
162
+ p.reject(new Error(e?.message ?? JSON.stringify(msg.error)))
163
+ } else {
164
+ p.resolve(msg.result)
165
+ }
166
+ } else if (typeof msg.method === 'string') {
167
+ fanout(msg.method, (msg.params ?? {}) as Json)
168
+ }
169
+ }
170
+
171
+ async function readLoop() {
172
+ const reader = (proc.stdout as ReadableStream<Uint8Array>).getReader()
173
+ const decoder = new TextDecoder()
174
+ let buf = ''
175
+ try {
176
+ while (true) {
177
+ const { done, value } = await reader.read()
178
+ if (done) break
179
+ buf += decoder.decode(value, { stream: true })
180
+ let nl: number
181
+ while ((nl = buf.indexOf('\n')) >= 0) {
182
+ handleLine(buf.slice(0, nl))
183
+ buf = buf.slice(nl + 1)
184
+ }
185
+ }
186
+ } finally {
187
+ alive = false
188
+ if (clients.get(workspacePath) === recordPromise) clients.delete(workspacePath)
189
+ for (const [, p] of pending) {
190
+ clearTimeout(p.timer)
191
+ p.reject(new Error('codex app-server exited'))
192
+ }
193
+ pending.clear()
194
+ fanout('__exit', {})
195
+ debug(`codex app-server exited ws=${workspacePath}`)
196
+ }
197
+ }
198
+
199
+ async function drainStderr() {
200
+ const reader = (proc.stderr as ReadableStream<Uint8Array>).getReader()
201
+ const decoder = new TextDecoder()
202
+ while (true) {
203
+ const { done, value } = await reader.read()
204
+ if (done) break
205
+ const text = decoder.decode(value).trim()
206
+ if (text) console.error('[codex stderr]', text)
207
+ }
208
+ }
209
+
210
+ // recordPromise is referenced by readLoop's cleanup to make sure we only
211
+ // delete our own registry entry (not a replacement spawned after a crash).
212
+ const client: CodexClient = {
213
+ rpc,
214
+ onNotification(l) {
215
+ listeners.add(l)
216
+ return () => listeners.delete(l)
217
+ },
218
+ isAlive: () => alive,
219
+ workspacePath
220
+ }
221
+ const record: ClientRecord = { client, proc }
222
+ const recordPromise = Promise.resolve(record)
223
+
224
+ void readLoop()
225
+ void drainStderr()
226
+
227
+ await rpc('initialize', {
228
+ clientInfo: { name: 'moi', title: 'moi', version: '0.1' },
229
+ capabilities: { experimentalApi: false, requestAttestation: false }
230
+ })
231
+ send({ jsonrpc: '2.0', method: 'initialized', params: {} })
232
+ debug(`codex app-server started ws=${workspacePath} bin=${bin}`)
233
+ return record
234
+ }
235
+
236
+ export async function getCodexClient(workspacePath: string): Promise<CodexClient> {
237
+ const existing = clients.get(workspacePath)
238
+ if (existing) {
239
+ const rec = await existing
240
+ if (rec.client.isAlive()) return rec.client
241
+ clients.delete(workspacePath)
242
+ }
243
+ const started = startClient(workspacePath)
244
+ clients.set(workspacePath, started)
245
+ try {
246
+ return (await started).client
247
+ } catch (err) {
248
+ clients.delete(workspacePath)
249
+ throw err
250
+ }
251
+ }
252
+
253
+ // Kill a workspace's app-server so the next message respawns it with fresh
254
+ // env (env is process-level and frozen at spawn). Mirrors the semantics of
255
+ // cc-session's restartWorkspaceSessions; in-flight turns are lost.
256
+ export function killCodexWorkspace(workspacePath: string): void {
257
+ const rec = clients.get(workspacePath)
258
+ if (!rec) return
259
+ clients.delete(workspacePath)
260
+ void rec.then(r => r.proc.kill()).catch(() => {})
261
+ }
262
+
263
+ // Server shutdown: kill every app-server so no codex process is orphaned.
264
+ export function killAllCodexClients(): void {
265
+ for (const [path, rec] of clients) {
266
+ clients.delete(path)
267
+ void rec.then(r => r.proc.kill()).catch(() => {})
268
+ }
269
+ }
270
+
271
+ // ---- discovery (sessions list / models / cold history) -----------------------
272
+
273
+ // Threads whose recorded cwd is exactly the workspace path, newest first.
274
+ export async function getCodexSessions(workspacePath: string): Promise<SessionInfo[]> {
275
+ try {
276
+ const client = await getCodexClient(workspacePath)
277
+ const res = await client.rpc<{ data?: CodexThread[] }>('thread/list', {
278
+ cwd: workspacePath,
279
+ limit: 50
280
+ })
281
+ return (res.data ?? []).map(codexThreadToSessionInfo)
282
+ } catch (err) {
283
+ console.error('[codex] thread/list failed', err)
284
+ return []
285
+ }
286
+ }
287
+
288
+ // Account-wide model catalog (identical for every workspace); cached like the
289
+ // Claude list in agent.ts, cleared on failure so a later call can retry.
290
+ let codexModelsPromise: Promise<Model[]> | null = null
291
+
292
+ export function getCodexModels(workspacePath: string): Promise<Model[]> {
293
+ if (!codexModelsPromise) {
294
+ codexModelsPromise = (async () => {
295
+ const client = await getCodexClient(workspacePath)
296
+ const res = await client.rpc<{ data?: CodexModel[] }>('model/list', {})
297
+ return (res.data ?? []).filter(m => !m.hidden).map(codexModelToModel)
298
+ })().catch(err => {
299
+ codexModelsPromise = null
300
+ throw err
301
+ })
302
+ }
303
+ return codexModelsPromise
304
+ }
305
+
306
+ // MCP servers as Codex sees them (from ~/.codex/config.toml), for the
307
+ // connectors UI. `authStatus` "notLoggedIn" means an OAuth server awaiting
308
+ // login; anything else that returned at all is reachable.
309
+ export async function getCodexMcpStatus(workspacePath: string): Promise<McpServer[]> {
310
+ try {
311
+ const client = await getCodexClient(workspacePath)
312
+ const res = await client.rpc<{ data?: { name?: string; authStatus?: string }[] }>(
313
+ 'mcpServerStatus/list',
314
+ {}
315
+ )
316
+ return (res.data ?? [])
317
+ .filter((s): s is { name: string; authStatus?: string } => typeof s.name === 'string')
318
+ .map(s => ({
319
+ name: s.name,
320
+ status: s.authStatus === 'notLoggedIn' ? ('needs-auth' as const) : ('connected' as const)
321
+ }))
322
+ } catch (err) {
323
+ console.error('[codex] mcpServerStatus/list failed', err)
324
+ return []
325
+ }
326
+ }
327
+
328
+ // Static history replay for the REST events endpoint (no live subscription).
329
+ export async function getCodexThreadEvents(
330
+ workspacePath: string,
331
+ threadId: string
332
+ ): Promise<StreamEvent[]> {
333
+ try {
334
+ const client = await getCodexClient(workspacePath)
335
+ const res = await client.rpc<{ thread?: CodexThread }>('thread/read', {
336
+ threadId,
337
+ includeTurns: true
338
+ })
339
+ return res.thread ? codexThreadToEvents(res.thread) : []
340
+ } catch {
341
+ return []
342
+ }
343
+ }
@@ -0,0 +1,68 @@
1
+ // Codex 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 type { Harness } from '../types'
4
+ import {
5
+ getCodexMcpStatus,
6
+ getCodexModels,
7
+ getCodexProcessInfo,
8
+ getCodexSessions,
9
+ getCodexThreadEvents,
10
+ killAllCodexClients,
11
+ killCodexWorkspace
12
+ } from './client'
13
+ import {
14
+ ensureCodexSessionLive,
15
+ getCodexRunningSessions,
16
+ getLiveCodexEvents,
17
+ interruptCodexRun,
18
+ sendCodexMessage
19
+ } from './session'
20
+
21
+ export const codexHarness: Harness = {
22
+ id: 'codex',
23
+ capabilities: {
24
+ supportsStreaming: true, // app-server always streams deltas; moi gates forwarding
25
+ imagesInline: 'data-url',
26
+ liveModelSwitch: true, // per-turn override becomes the thread default
27
+ liveEffortSwitch: true,
28
+ nativeUserEcho: true // clientUserMessageId echoes back as clientId
29
+ },
30
+
31
+ sendMessage: input => sendCodexMessage(input),
32
+ interrupt: (workspaceId, sessionId) => interruptCodexRun({ workspaceId, sessionId }),
33
+ runningSessions: () => getCodexRunningSessions(),
34
+
35
+ listSessions: ws => getCodexSessions(ws.path),
36
+ // Prefer the live view when one exists; otherwise resume the thread so WS
37
+ // frames upsert into the same view, and fall back to a static thread/read
38
+ // if the resume fails.
39
+ sessionEvents: async (ws, sessionId) => {
40
+ const live = getLiveCodexEvents(ws.id, sessionId)
41
+ if (live) return live
42
+ try {
43
+ return await ensureCodexSessionLive({
44
+ workspaceId: ws.id,
45
+ workspacePath: ws.path,
46
+ sessionId
47
+ })
48
+ } catch {
49
+ return getCodexThreadEvents(ws.path, sessionId)
50
+ }
51
+ },
52
+ listModels: ws => getCodexModels(ws.path),
53
+ mcpStatus: ws => getCodexMcpStatus(ws.path),
54
+
55
+ onEnvChanged: workspacePath => killCodexWorkspace(workspacePath),
56
+ shutdown: () => killAllCodexClients(),
57
+ skillsDir: workspaceRoot => `${workspaceRoot}/.agents/skills`,
58
+ debugInfo: ws => getCodexProcessInfo(ws.path),
59
+ wireScope: ws => ws.path,
60
+
61
+ statusLines: () => {
62
+ const running = getCodexRunningSessions()
63
+ return [
64
+ `live Codex runs ${running.length}`,
65
+ ...running.map(r => ` ▶ busy ws=${r.workspaceId} session=${r.sessionId}`)
66
+ ]
67
+ }
68
+ }
@@ -0,0 +1,186 @@
1
+ // Standalone probe for the `codex app-server` JSON-RPC protocol — talk to the
2
+ // raw harness without moi in the loop. Complements /playground/codex (which
3
+ // debugs the full server → client pipeline); use this when you need to poke
4
+ // the protocol itself: try params, watch notifications, verify a claim in
5
+ // ./NOTES.md.
6
+ //
7
+ // Usage:
8
+ // bun scripts/codex-probe.ts chat [cwd] "prompt" — thread/start + one turn
9
+ // bun scripts/codex-probe.ts rpc [cwd] <method> ['params-json']
10
+ // bun scripts/codex-probe.ts models — model/list
11
+ // bun scripts/codex-probe.ts threads [cwd] — thread/list for cwd
12
+ // bun scripts/codex-probe.ts read [cwd] <threadId> — thread/read w/ turns
13
+ //
14
+ // Flags: --model=<id> --effort=<level> --summary=<auto|concise|detailed|none>
15
+ // --timeout=<sec, default 120> --json (newline JSON, no pretty labels)
16
+ //
17
+ // Every frame in both directions is printed. Server→client requests
18
+ // (approvals) are auto-accepted and logged.
19
+
20
+ export {} // top-level await needs module context under tsc
21
+
22
+ type Json = Record<string, unknown>
23
+
24
+ const flags = new Map<string, string>()
25
+ const positional: string[] = []
26
+ for (const a of process.argv.slice(2)) {
27
+ const m = a.match(/^--([^=]+)(?:=(.*))?$/)
28
+ if (m) flags.set(m[1], m[2] ?? 'true')
29
+ else positional.push(a)
30
+ }
31
+ const [cmd = 'chat', ...rest] = positional
32
+ const asJson = flags.get('json') === 'true'
33
+ const timeoutSec = Number(flags.get('timeout') ?? 120)
34
+
35
+ const bin = process.env.CODEX_CLI_PATH ?? Bun.which('codex')
36
+ if (!bin) {
37
+ console.error('codex binary not found (install @openai/codex or set CODEX_CLI_PATH)')
38
+ process.exit(1)
39
+ }
40
+
41
+ const cwd = rest[0] && !rest[0].startsWith('{') ? rest[0] : process.cwd()
42
+
43
+ const proc = Bun.spawn([bin, 'app-server'], {
44
+ cwd,
45
+ stdin: 'pipe',
46
+ stdout: 'pipe',
47
+ stderr: 'pipe'
48
+ })
49
+
50
+ let nextId = 1
51
+ const pending = new Map<number, (v: { result?: unknown; error?: unknown }) => void>()
52
+
53
+ function log(dir: '>>' | '<<', frame: unknown) {
54
+ if (asJson) console.log(JSON.stringify({ dir, frame }))
55
+ else {
56
+ const f = frame as Json
57
+ const head =
58
+ typeof f.method === 'string'
59
+ ? `${f.method}${'id' in f ? ` #${f.id}` : ''}`
60
+ : `response #${f.id}`
61
+ console.log(`${dir} ${head}`)
62
+ const body = JSON.stringify(f.params ?? f.result ?? f.error ?? {}, null, 2)
63
+ if (body !== '{}') console.log(body.replace(/^/gm, ' '))
64
+ }
65
+ }
66
+
67
+ function send(frame: Json) {
68
+ log('>>', frame)
69
+ proc.stdin.write(JSON.stringify(frame) + '\n')
70
+ proc.stdin.flush()
71
+ }
72
+
73
+ function rpc<T>(method: string, params: Json = {}): Promise<T> {
74
+ const id = nextId++
75
+ send({ jsonrpc: '2.0', id, method, params })
76
+ return new Promise((resolve, reject) => {
77
+ pending.set(id, msg => {
78
+ if (msg.error !== undefined) reject(new Error(JSON.stringify(msg.error)))
79
+ else resolve(msg.result as T)
80
+ })
81
+ })
82
+ }
83
+
84
+ let turnDone: (() => void) | null = null
85
+
86
+ async function readLoop() {
87
+ const reader = (proc.stdout as ReadableStream<Uint8Array>).getReader()
88
+ const decoder = new TextDecoder()
89
+ let buf = ''
90
+ while (true) {
91
+ const { done, value } = await reader.read()
92
+ if (done) break
93
+ buf += decoder.decode(value, { stream: true })
94
+ let nl: number
95
+ while ((nl = buf.indexOf('\n')) >= 0) {
96
+ const line = buf.slice(0, nl)
97
+ buf = buf.slice(nl + 1)
98
+ if (!line.trim()) continue
99
+ let msg: Json
100
+ try {
101
+ msg = JSON.parse(line) as Json
102
+ } catch {
103
+ continue
104
+ }
105
+ log('<<', msg)
106
+ if ('id' in msg && 'method' in msg) {
107
+ // Server→client request: accept approvals, reject the rest.
108
+ const method = msg.method as string
109
+ const accepts = method.endsWith('requestApproval') || method === 'applyPatchApproval'
110
+ send(
111
+ accepts
112
+ ? { jsonrpc: '2.0', id: msg.id, result: { decision: 'accept' } }
113
+ : { jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'probe: unhandled' } }
114
+ )
115
+ } else if ('id' in msg) {
116
+ const cb = pending.get(msg.id as number)
117
+ pending.delete(msg.id as number)
118
+ cb?.(msg as { result?: unknown; error?: unknown })
119
+ } else if (msg.method === 'turn/completed') {
120
+ turnDone?.()
121
+ }
122
+ }
123
+ }
124
+ }
125
+
126
+ async function drainStderr() {
127
+ const reader = (proc.stderr as ReadableStream<Uint8Array>).getReader()
128
+ const decoder = new TextDecoder()
129
+ while (true) {
130
+ const { done, value } = await reader.read()
131
+ if (done) break
132
+ const text = decoder.decode(value).trim()
133
+ if (text) console.error('[stderr]', text)
134
+ }
135
+ }
136
+
137
+ void readLoop()
138
+ void drainStderr()
139
+
140
+ setTimeout(() => {
141
+ console.error(`probe timeout after ${timeoutSec}s`)
142
+ proc.kill()
143
+ process.exit(1)
144
+ }, timeoutSec * 1000)
145
+
146
+ await rpc('initialize', {
147
+ clientInfo: { name: 'moi-codex-probe', title: 'moi codex probe', version: '0.1' },
148
+ capabilities: { experimentalApi: false, requestAttestation: false }
149
+ })
150
+ send({ jsonrpc: '2.0', method: 'initialized', params: {} })
151
+
152
+ if (cmd === 'models') {
153
+ await rpc('model/list', {})
154
+ } else if (cmd === 'threads') {
155
+ await rpc('thread/list', { cwd, limit: 20 })
156
+ } else if (cmd === 'read') {
157
+ await rpc('thread/read', { threadId: rest[1], includeTurns: true })
158
+ } else if (cmd === 'rpc') {
159
+ const method = rest[0]?.startsWith('{') ? cmd : (rest[1] ?? rest[0])
160
+ const paramsRaw = rest.find(a => a.startsWith('{'))
161
+ await rpc(method, paramsRaw ? (JSON.parse(paramsRaw) as Json) : {})
162
+ } else if (cmd === 'chat') {
163
+ const prompt = rest[rest.length - 1] ?? 'Reply with exactly: pong'
164
+ const started = await rpc<{ thread: { id: string } }>('thread/start', {
165
+ cwd,
166
+ sandbox: 'danger-full-access',
167
+ approvalPolicy: 'never',
168
+ ...(flags.has('model') ? { model: flags.get('model') } : {})
169
+ })
170
+ const waitTurn = new Promise<void>(res => {
171
+ turnDone = res
172
+ })
173
+ await rpc('turn/start', {
174
+ threadId: started.thread.id,
175
+ input: [{ type: 'text', text: prompt }],
176
+ ...(flags.has('model') ? { model: flags.get('model') } : {}),
177
+ ...(flags.has('effort') ? { effort: flags.get('effort') } : {}),
178
+ ...(flags.has('summary') ? { summary: flags.get('summary') } : {})
179
+ })
180
+ await waitTurn
181
+ } else {
182
+ console.error(`unknown command: ${cmd}`)
183
+ }
184
+
185
+ proc.kill()
186
+ process.exit(0)