moi-computer 0.3.0 → 0.3.1-next.1

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 (121) hide show
  1. package/client/api/workspace-keys.ts +2 -2
  2. package/client/app/AppRouter.tsx +0 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +3 -1
  4. package/client/app/shell/SidebarLayout.tsx +3 -16
  5. package/client/assets/openai.svg +1 -3
  6. package/client/components/shared/Composer.tsx +112 -0
  7. package/client/components/ui/button.tsx +1 -1
  8. package/client/components/ui/dropdown-menu.tsx +3 -3
  9. package/client/components/ui/tooltip.tsx +12 -15
  10. package/client/features/applets/WidgetErrorBoundary.tsx +19 -3
  11. package/client/features/applets/WidgetShell.tsx +8 -1
  12. package/client/features/applets/applet-log.ts +100 -0
  13. package/client/features/applets/useApplet.ts +21 -7
  14. package/client/features/chat/ChatComposer.tsx +33 -30
  15. package/client/features/chat/ChatPanel.tsx +5 -2
  16. package/client/features/chat/MarkdownContent.tsx +20 -2
  17. package/client/features/chat/ModelPicker.tsx +29 -41
  18. package/client/features/chat/TurnView.tsx +2 -2
  19. package/client/features/chat/chat-frames.ts +14 -6
  20. package/client/features/chat/chat-send.ts +1 -1
  21. package/client/features/chat/chat-store.ts +22 -17
  22. package/client/features/chat/model-order.ts +47 -0
  23. package/client/features/chat/tool-group/ToolOutput.tsx +4 -12
  24. package/client/features/chat/tool-group/format.ts +0 -6
  25. package/client/features/chat/useChat.ts +15 -2
  26. package/client/features/connectors/McpServerCards.tsx +95 -0
  27. package/client/features/connectors/api.ts +0 -11
  28. package/client/features/home/HomePage.tsx +45 -42
  29. package/client/features/home/WorkspacePreview.tsx +179 -38
  30. package/client/features/home/api.ts +24 -12
  31. package/client/features/home/workspace-presentation.tsx +17 -15
  32. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +243 -0
  33. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +95 -0
  34. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +230 -0
  35. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +35 -0
  36. package/client/features/home/workspace-setup/useWorkspaceImport.ts +61 -0
  37. package/client/features/settings/ConnectorsSettings.tsx +89 -0
  38. package/client/features/settings/GeneralSettings.tsx +12 -0
  39. package/client/features/settings/SettingsLayout.tsx +2 -2
  40. package/client/features/settings/WorkspaceSettings.tsx +8 -4
  41. package/client/features/views/ViewBuilderTab.tsx +28 -29
  42. package/client/features/views/useViewBuilderActions.ts +1 -1
  43. package/client/features/widgets/WidgetFrame.tsx +3 -0
  44. package/client/features/widgets/WidgetGrid.tsx +1 -0
  45. package/client/features/widgets/Widgets.tsx +12 -3
  46. package/client/features/widgets/api.ts +47 -0
  47. package/client/features/widgets/useWidgetThumbnails.ts +107 -0
  48. package/client/features/widgets/widget-snapshot.ts +71 -0
  49. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -4
  50. package/client/features/workspace/WorkspaceScreen.tsx +19 -4
  51. package/client/features/workspace/api.ts +25 -3
  52. package/client/features/workspace/moi-context.ts +85 -0
  53. package/client/index.css +0 -5
  54. package/client/main.tsx +13 -4
  55. package/dist/{chunk-cs8vbert.js → chunk-1dfbr7n2.js} +2 -2
  56. package/dist/chunk-339jds4x.js +15 -0
  57. package/dist/chunk-3xsvsnhr.css +1 -0
  58. package/dist/{chunk-zpxrb1ce.js → chunk-anqmsbjt.js} +2 -2
  59. package/dist/chunk-hbvfb6sk.js +63 -0
  60. package/dist/chunk-jen6xcm1.js +14 -0
  61. package/dist/{chunk-kxmvv1ax.js → chunk-qwm5f6qk.js} +1 -1
  62. package/dist/{chunk-fjksw6xf.js → chunk-sxbfh73c.js} +1 -1
  63. package/dist/chunk-yp4srgqt.js +10 -0
  64. package/dist/index.html +1 -1
  65. package/dist/openai-ep9ht2pq.svg +1 -0
  66. package/lib/ids.ts +15 -0
  67. package/lib/moi-context.ts +170 -0
  68. package/lib/types.ts +95 -13
  69. package/lib/view-builder-directives.ts +16 -0
  70. package/lib/workspace-types.ts +12 -0
  71. package/package.json +4 -2
  72. package/server/api.ts +180 -34
  73. package/server/applet-log.ts +149 -0
  74. package/server/cli.ts +161 -7
  75. package/server/control.ts +81 -1
  76. package/server/functions.ts +44 -14
  77. package/server/harness/README.md +26 -9
  78. package/server/harness/claude-code/NOTES.md +20 -6
  79. package/server/harness/claude-code/adapter.ts +2 -2
  80. package/server/harness/claude-code/git-worktree.ts +32 -0
  81. package/server/harness/claude-code/index.ts +35 -13
  82. package/server/harness/claude-code/mcp.ts +16 -65
  83. package/server/harness/claude-code/models.ts +3 -0
  84. package/server/harness/claude-code/session.ts +196 -61
  85. package/server/harness/claude-code/sessions.ts +51 -0
  86. package/server/harness/codex/NOTES.md +41 -11
  87. package/server/harness/codex/adapter.ts +52 -6
  88. package/server/harness/codex/client.ts +69 -18
  89. package/server/harness/codex/discovery.ts +114 -0
  90. package/server/harness/codex/index.ts +12 -5
  91. package/server/harness/codex/probe.ts +4 -2
  92. package/server/harness/codex/session.ts +57 -5
  93. package/server/harness/executable.ts +82 -0
  94. package/server/harness/openclaw/adapter.ts +8 -1
  95. package/server/harness/openclaw/discovery.ts +139 -6
  96. package/server/harness/openclaw/gateway.ts +40 -18
  97. package/server/harness/openclaw/index.ts +12 -15
  98. package/server/harness/openclaw/session.ts +50 -10
  99. package/server/harness/openclaw/strip.ts +2 -2
  100. package/server/harness/shell-path.ts +79 -0
  101. package/server/harness/types.ts +37 -5
  102. package/server/layout.ts +81 -51
  103. package/server/registry.ts +57 -12
  104. package/server/scratchpad-assets.ts +41 -6
  105. package/server/scratchpad.ts +30 -0
  106. package/server/view-builders.ts +3 -2
  107. package/server/views.ts +5 -0
  108. package/server/web.ts +30 -8
  109. package/server/widgets.ts +23 -2
  110. package/server/workspace-import.ts +45 -0
  111. package/workspace/.claude/skills/moi-workspace/SKILL.md +27 -3
  112. package/client/features/connectors/ConnectorsPage.tsx +0 -92
  113. package/client/features/connectors/McpMenu.tsx +0 -145
  114. package/client/features/home/CreateWorkspaceDialog.tsx +0 -130
  115. package/client/features/home/CreateWorkspaceDialogSteps.tsx +0 -234
  116. package/dist/chunk-4vf1t6v1.js +0 -10
  117. package/dist/chunk-4z52b2av.css +0 -1
  118. package/dist/chunk-b4b276wx.js +0 -15
  119. package/dist/chunk-y82s1jxm.js +0 -61
  120. package/dist/openai-h13pza4b.svg +0 -3
  121. package/lib/view-builder-meta.ts +0 -35
@@ -9,8 +9,11 @@
9
9
  // Type shapes are hand-written against `codex app-server generate-ts`
10
10
  // (CLI 0.144.5) and read defensively — see ./NOTES.md.
11
11
  import type { Part, StreamEvent, SystemNotice, ToolCall, ToolState, Turn } from '@/lib/format'
12
+ import { stripMoiContext, stripMoiContextLoose } from '@/lib/moi-context'
12
13
  import type { Model, SessionInfo } from '@/lib/types'
13
14
 
15
+ import type { WorkspaceActivityPreview } from '../types'
16
+
14
17
  // ---- protocol shapes (subset we consume) ------------------------------------
15
18
 
16
19
  export type CodexUserInput =
@@ -103,28 +106,67 @@ export type CodexModel = {
103
106
 
104
107
  // ---- discovery mappings ------------------------------------------------------
105
108
 
109
+ // `thread/list.preview` snippets come from the raw first user message — on
110
+ // the pre-0.135 fallback path that text carries the appended context envelope,
111
+ // so previews strip it like transcript turns do. Loose variant: previews are
112
+ // truncated snippets, so a mid-envelope cut must still strip.
113
+ function cleanPreview(preview: string | undefined): string {
114
+ return preview ? stripMoiContextLoose(preview).trim() : ''
115
+ }
116
+
106
117
  export function codexThreadToSessionInfo(t: CodexThread): SessionInfo {
107
118
  return {
108
119
  sessionId: t.id,
109
- summary: t.name?.trim() || t.preview?.trim() || '',
120
+ summary: t.name?.trim() || cleanPreview(t.preview),
110
121
  // Codex timestamps are unix seconds; SessionInfo wants millis.
111
122
  lastModified: (t.updatedAt ?? t.createdAt ?? 0) * 1000,
112
123
  cwd: t.cwd
113
124
  }
114
125
  }
115
126
 
127
+ // Home-page card preview from thread/list alone: `preview` already carries the
128
+ // thread's first-message snippet, so no thread/read is needed. The oldest
129
+ // thread by creation supplies the message; the newest activity supplies the
130
+ // timestamp.
131
+ export function selectCodexWorkspacePreview(
132
+ threads: CodexThread[],
133
+ includeFirstUserMessage: boolean
134
+ ): WorkspaceActivityPreview {
135
+ const latest = threads.reduce<number | undefined>((acc, t) => {
136
+ const ts = t.updatedAt ?? t.createdAt
137
+ return ts !== undefined && (acc === undefined || ts > acc) ? ts : acc
138
+ }, undefined)
139
+ const updatedAt = latest !== undefined ? latest * 1000 : undefined
140
+
141
+ let firstUserMessage: string | undefined
142
+ if (includeFirstUserMessage) {
143
+ const oldest = [...threads].sort(
144
+ (a, b) =>
145
+ (a.createdAt ?? a.updatedAt ?? 0) - (b.createdAt ?? b.updatedAt ?? 0) ||
146
+ a.id.localeCompare(b.id)
147
+ )[0]
148
+ firstUserMessage = cleanPreview(oldest?.preview) || undefined
149
+ }
150
+
151
+ return {
152
+ ...(firstUserMessage ? { firstUserMessage } : {}),
153
+ ...(updatedAt !== undefined ? { updatedAt } : {})
154
+ }
155
+ }
156
+
116
157
  export function codexModelToModel(m: CodexModel): Model {
117
158
  const efforts = (m.supportedReasoningEfforts ?? []).map(e => e.reasoningEffort)
159
+ const displayName = m.displayName.replace(/^GPT-/, '').replaceAll('-', ' ')
118
160
  return {
119
161
  value: m.id,
120
162
  resolvedModel: m.model,
121
- displayName: m.displayName,
163
+ displayName,
122
164
  // Our Model.description is a " · "-joined "<headline> · <tagline>" blurb
123
165
  // (the picker renders the first segment as the row label), so lead with
124
166
  // the display name and let Codex's one-liner be the tagline.
125
167
  ...(m.description
126
- ? { description: `${m.displayName} · ${m.description}` }
127
- : { description: m.displayName }),
168
+ ? { description: `${displayName} · ${m.description}` }
169
+ : { description: displayName }),
128
170
  supportsEffort: efforts.length > 0,
129
171
  ...(efforts.length > 0 ? { supportedEffortLevels: efforts } : {})
130
172
  }
@@ -150,8 +192,12 @@ function statusToToolState(status: string | undefined): ToolState {
150
192
  function userInputToParts(content: CodexUserInput[] | undefined): Part[] {
151
193
  const parts: Part[] = []
152
194
  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)
195
+ // The send path appends the `<moi-context>` envelope to the agent text;
196
+ // the native echo and thread replays carry it back, so peel it here.
197
+ if (c.type === 'text' && c.text) {
198
+ const text = stripMoiContext(c.text)
199
+ if (text) parts.push({ type: 'text', text })
200
+ } else if (c.type === 'image' && c.url)
155
201
  parts.push({ type: 'file', mediaType: 'image/*', url: c.url })
156
202
  else if (c.type === 'localImage' && c.path)
157
203
  parts.push({ type: 'text', text: `[image: ${c.path}]` })
@@ -17,8 +17,11 @@ import {
17
17
  type CodexThread,
18
18
  codexModelToModel,
19
19
  codexThreadToEvents,
20
- codexThreadToSessionInfo
20
+ codexThreadToSessionInfo,
21
+ selectCodexWorkspacePreview
21
22
  } from './adapter'
23
+ import type { WorkspaceActivityPreview } from '../types'
24
+ import { findHarnessExecutable, requireHarnessExecutable } from '../executable'
22
25
  import { debug } from '../../debug'
23
26
  import { tapWire } from '../debug'
24
27
  import { resolveWorkspaceEnv } from '../../workspace-env'
@@ -40,7 +43,7 @@ export type CodexProcessInfo = {
40
43
 
41
44
  export function getCodexProcessInfo(workspacePath: string): Promise<CodexProcessInfo> {
42
45
  const rec = clients.get(workspacePath)
43
- const binary = findCodexBinary()
46
+ const binary = findHarnessExecutable('codex')
44
47
  if (!rec) return Promise.resolve({ running: false, binary })
45
48
  return rec
46
49
  .then(r => ({ running: r.client.isAlive(), pid: r.proc.pid, binary }))
@@ -52,14 +55,27 @@ export type CodexClient = {
52
55
  onNotification: (l: NotificationListener) => () => void
53
56
  isAlive: () => boolean
54
57
  workspacePath: string
58
+ // Whether this app-server accepts `turn/start.additionalContext` (the native
59
+ // per-turn context channel). Resolved from the initialize handshake.
60
+ supportsAdditionalContext: boolean
55
61
  }
56
62
 
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
+ // `additionalContext` shipped in codex 0.135.0 (openai/codex#24154, May 2026).
64
+ // Older servers have no `deny_unknown_fields` on TurnStartParams, so they
65
+ // silently DROP the field instead of erroring — probing is useless. The only
66
+ // reliable signal is the version embedded in the initialize response's
67
+ // userAgent (e.g. `codex_cli_rs/0.144.5 (…)`); an unparsable userAgent gates
68
+ // to false and the session path falls back to appending context to the text.
69
+ const ADDITIONAL_CONTEXT_MIN_VERSION = [0, 135, 0] as const
70
+
71
+ export function codexSupportsAdditionalContext(userAgent: string | undefined): boolean {
72
+ const m = userAgent?.match(/\/(\d+)\.(\d+)\.(\d+)/)
73
+ if (!m) return false
74
+ const v = [Number(m[1]), Number(m[2]), Number(m[3])]
75
+ for (let i = 0; i < 3; i++) {
76
+ if (v[i] !== ADDITIONAL_CONTEXT_MIN_VERSION[i]) return v[i] > ADDITIONAL_CONTEXT_MIN_VERSION[i]
77
+ }
78
+ return true
63
79
  }
64
80
 
65
81
  type ClientRecord = {
@@ -70,12 +86,7 @@ type ClientRecord = {
70
86
  const clients = new Map<string, Promise<ClientRecord>>() // key: workspacePath
71
87
 
72
88
  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
- }
89
+ const bin = requireHarnessExecutable('codex')
79
90
 
80
91
  const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
81
92
  const proc = Bun.spawn([bin, 'app-server'], {
@@ -216,7 +227,8 @@ async function startClient(workspacePath: string): Promise<ClientRecord> {
216
227
  return () => listeners.delete(l)
217
228
  },
218
229
  isAlive: () => alive,
219
- workspacePath
230
+ workspacePath,
231
+ supportsAdditionalContext: false
220
232
  }
221
233
  const record: ClientRecord = { client, proc }
222
234
  const recordPromise = Promise.resolve(record)
@@ -224,12 +236,18 @@ async function startClient(workspacePath: string): Promise<ClientRecord> {
224
236
  void readLoop()
225
237
  void drainStderr()
226
238
 
227
- await rpc('initialize', {
239
+ // experimentalApi opts this connection into experimental fields — required
240
+ // for `turn/start.additionalContext`; servers new enough to gate it reject
241
+ // the field otherwise. The response's userAgent carries the CLI version.
242
+ const init = await rpc<{ userAgent?: string }>('initialize', {
228
243
  clientInfo: { name: 'moi', title: 'moi', version: '0.1' },
229
- capabilities: { experimentalApi: false, requestAttestation: false }
244
+ capabilities: { experimentalApi: true, requestAttestation: false }
230
245
  })
246
+ client.supportsAdditionalContext = codexSupportsAdditionalContext(init?.userAgent)
231
247
  send({ jsonrpc: '2.0', method: 'initialized', params: {} })
232
- debug(`codex app-server started ws=${workspacePath} bin=${bin}`)
248
+ debug(
249
+ `codex app-server started ws=${workspacePath} bin=${bin} ua=${init?.userAgent ?? 'unknown'} additionalContext=${client.supportsAdditionalContext}`
250
+ )
233
251
  return record
234
252
  }
235
253
 
@@ -250,6 +268,20 @@ export async function getCodexClient(workspacePath: string): Promise<CodexClient
250
268
  }
251
269
  }
252
270
 
271
+ // Preview reads must not spawn an app-server — home-page cards render for
272
+ // every workspace, and starting a codex process per card is disproportionate.
273
+ // Returns the workspace's client only if one is already running.
274
+ async function peekCodexClient(workspacePath: string): Promise<CodexClient | null> {
275
+ const existing = clients.get(workspacePath)
276
+ if (!existing) return null
277
+ try {
278
+ const rec = await existing
279
+ return rec.client.isAlive() ? rec.client : null
280
+ } catch {
281
+ return null
282
+ }
283
+ }
284
+
253
285
  // Kill a workspace's app-server so the next message respawns it with fresh
254
286
  // env (env is process-level and frozen at spawn). Mirrors the semantics of
255
287
  // cc-session's restartWorkspaceSessions; in-flight turns are lost.
@@ -285,6 +317,25 @@ export async function getCodexSessions(workspacePath: string): Promise<SessionIn
285
317
  }
286
318
  }
287
319
 
320
+ // Home-page card preview. Peek-only: with no live app-server the card simply
321
+ // omits the activity fields until the workspace is opened once.
322
+ export async function getCodexWorkspacePreview(
323
+ workspacePath: string,
324
+ includeFirstUserMessage: boolean
325
+ ): Promise<WorkspaceActivityPreview> {
326
+ const client = await peekCodexClient(workspacePath)
327
+ if (!client) return {}
328
+ try {
329
+ const res = await client.rpc<{ data?: CodexThread[] }>('thread/list', {
330
+ cwd: workspacePath,
331
+ limit: 50
332
+ })
333
+ return selectCodexWorkspacePreview(res.data ?? [], includeFirstUserMessage)
334
+ } catch {
335
+ return {}
336
+ }
337
+ }
338
+
288
339
  // Account-wide model catalog (identical for every workspace); cached like the
289
340
  // Claude list in agent.ts, cleared on failure so a later call can retry.
290
341
  let codexModelsPromise: Promise<Model[]> | null = null
@@ -0,0 +1,114 @@
1
+ // Discover directories the Codex CLI has run in, for the home page's
2
+ // "Import from this computer" list.
3
+ //
4
+ // Codex persists every thread as a rollout file under
5
+ // `~/.codex/sessions/YYYY/MM/DD/rollout-<timestamp>-<uuid>.jsonl`, whose FIRST
6
+ // line is a `session_meta` record carrying the thread's `cwd`. Reading those
7
+ // heads directly (no app-server spawn, no codex binary needed) mirrors how the
8
+ // Claude Code harness scans its own session history — discovery still works
9
+ // when the CLI has since been uninstalled.
10
+ import { readdir, stat } from 'node:fs/promises'
11
+ import { homedir } from 'node:os'
12
+ import { isAbsolute, join } from 'node:path'
13
+
14
+ import type { DiscoveredWorkspaceCandidate } from '../types'
15
+
16
+ export const CODEX_SESSIONS_ROOT = join(homedir(), '.codex', 'sessions')
17
+
18
+ // Newest files scanned per discovery pass. Session dirs grow unboundedly; the
19
+ // most recent rollouts cover every workspace anyone still cares about.
20
+ const SCAN_LIMIT = 400
21
+ // The session_meta line is small (id/cwd/timestamps), but read a generous head
22
+ // in case a Codex version inlines instructions into it.
23
+ const HEAD_BYTES = 64 * 1024
24
+
25
+ type SessionMeta = { cwd: string; timestamp?: string }
26
+
27
+ // Parse the first line of a rollout file. Formats differ across CLI versions
28
+ // ({type:'session_meta', payload:{cwd}} vs a flat meta object), so accept both
29
+ // and fall back to a regex when the head truncates mid-JSON.
30
+ async function readSessionMeta(file: string): Promise<SessionMeta | null> {
31
+ let head: string
32
+ try {
33
+ head = await Bun.file(file).slice(0, HEAD_BYTES).text()
34
+ } catch {
35
+ return null
36
+ }
37
+ const nl = head.indexOf('\n')
38
+ const line = nl >= 0 ? head.slice(0, nl) : head
39
+ try {
40
+ const parsed = JSON.parse(line) as {
41
+ timestamp?: string
42
+ cwd?: string
43
+ payload?: { cwd?: string; timestamp?: string }
44
+ }
45
+ const cwd = parsed.payload?.cwd ?? parsed.cwd
46
+ // isAbsolute (not a '/' check) so Windows drive-letter cwds survive.
47
+ if (typeof cwd === 'string' && isAbsolute(cwd)) {
48
+ const timestamp = parsed.payload?.timestamp ?? parsed.timestamp
49
+ return { cwd, ...(typeof timestamp === 'string' ? { timestamp } : {}) }
50
+ }
51
+ } catch {
52
+ // Truncated head: pull the quoted cwd value out and JSON-parse just the
53
+ // string so escapes (Windows "C:\\...") decode correctly.
54
+ const m = line.match(/"cwd"\s*:\s*("(?:[^"\\]|\\.)*")/)
55
+ if (m) {
56
+ try {
57
+ const cwd = JSON.parse(m[1]) as string
58
+ if (isAbsolute(cwd)) return { cwd }
59
+ } catch {}
60
+ }
61
+ }
62
+ return null
63
+ }
64
+
65
+ // Up to `limit` rollout files under the date-partitioned tree, newest first.
66
+ // Directory names are zero-padded dates and filenames embed ISO timestamps,
67
+ // so descending name order at every level IS reverse-chronological order —
68
+ // which lets the walk stop at the cap instead of traversing (and sorting)
69
+ // the entire unbounded history first.
70
+ async function listRolloutFiles(root: string, limit: number): Promise<string[]> {
71
+ const out: string[] = []
72
+ async function walk(dir: string) {
73
+ let entries
74
+ try {
75
+ entries = await readdir(dir, { withFileTypes: true })
76
+ } catch {
77
+ return
78
+ }
79
+ entries.sort((a, b) => (a.name < b.name ? 1 : -1))
80
+ for (const e of entries) {
81
+ if (out.length >= limit) return
82
+ const p = join(dir, e.name)
83
+ if (e.isDirectory()) await walk(p)
84
+ else if (e.isFile() && e.name.endsWith('.jsonl')) out.push(p)
85
+ }
86
+ }
87
+ await walk(root)
88
+ return out
89
+ }
90
+
91
+ export async function discoverCodexWorkspaces(
92
+ registeredPaths: Set<string>,
93
+ sessionsRoot: string = CODEX_SESSIONS_ROOT
94
+ ): Promise<DiscoveredWorkspaceCandidate[]> {
95
+ const files = await listRolloutFiles(sessionsRoot, SCAN_LIMIT)
96
+ // Newest-first scan: only the first rollout seen per cwd is needed.
97
+ const byCwd = new Map<string, string | undefined>()
98
+ for (const file of files) {
99
+ const meta = await readSessionMeta(file)
100
+ if (!meta || byCwd.has(meta.cwd)) continue
101
+ byCwd.set(meta.cwd, meta.timestamp)
102
+ }
103
+ const out: DiscoveredWorkspaceCandidate[] = []
104
+ for (const cwd of byCwd.keys()) {
105
+ if (registeredPaths.has(cwd)) continue
106
+ try {
107
+ if (!(await stat(cwd)).isDirectory()) continue
108
+ } catch {
109
+ continue // directory deleted since the session ran
110
+ }
111
+ out.push({ path: cwd, type: 'codex' })
112
+ }
113
+ return out
114
+ }
@@ -1,18 +1,21 @@
1
1
  // Codex as a Harness. Thin wiring over this folder's modules — see
2
2
  // ../types.ts for the contract and ../README.md for the architecture.
3
3
  import type { Harness } from '../types'
4
+ import { pathHarnessAvailability } from '../executable'
4
5
  import {
5
6
  getCodexMcpStatus,
6
7
  getCodexModels,
7
8
  getCodexProcessInfo,
8
9
  getCodexSessions,
9
10
  getCodexThreadEvents,
11
+ getCodexWorkspacePreview,
10
12
  killAllCodexClients,
11
13
  killCodexWorkspace
12
14
  } from './client'
15
+ import { discoverCodexWorkspaces } from './discovery'
13
16
  import {
14
17
  ensureCodexSessionLive,
15
- getCodexRunningSessions,
18
+ getCodexActiveSessions,
16
19
  getLiveCodexEvents,
17
20
  interruptCodexRun,
18
21
  sendCodexMessage
@@ -30,9 +33,11 @@ export const codexHarness: Harness = {
30
33
 
31
34
  sendMessage: input => sendCodexMessage(input),
32
35
  interrupt: (workspaceId, sessionId) => interruptCodexRun({ workspaceId, sessionId }),
33
- runningSessions: () => getCodexRunningSessions(),
36
+ activeSessions: () => getCodexActiveSessions(),
34
37
 
35
38
  listSessions: ws => getCodexSessions(ws.path),
39
+ workspacePreview: (ws, includeFirstUserMessage) =>
40
+ getCodexWorkspacePreview(ws.path, includeFirstUserMessage),
36
41
  // Prefer the live view when one exists; otherwise resume the thread so WS
37
42
  // frames upsert into the same view, and fall back to a static thread/read
38
43
  // if the resume fails.
@@ -51,6 +56,8 @@ export const codexHarness: Harness = {
51
56
  },
52
57
  listModels: ws => getCodexModels(ws.path),
53
58
  mcpStatus: ws => getCodexMcpStatus(ws.path),
59
+ discoverWorkspaces: registeredPaths => discoverCodexWorkspaces(registeredPaths),
60
+ availability: async () => pathHarnessAvailability('codex'),
54
61
 
55
62
  onEnvChanged: workspacePath => killCodexWorkspace(workspacePath),
56
63
  shutdown: () => killAllCodexClients(),
@@ -59,10 +66,10 @@ export const codexHarness: Harness = {
59
66
  wireScope: ws => ws.path,
60
67
 
61
68
  statusLines: () => {
62
- const running = getCodexRunningSessions()
69
+ const active = getCodexActiveSessions()
63
70
  return [
64
- `live Codex runs ${running.length}`,
65
- ...running.map(r => ` ▶ busy ws=${r.workspaceId} session=${r.sessionId}`)
71
+ `live Codex runs ${active.length}`,
72
+ ...active.map(r => ` ▶ busy ws=${r.workspaceId} session=${r.sessionId}`)
66
73
  ]
67
74
  }
68
75
  }
@@ -32,9 +32,11 @@ const [cmd = 'chat', ...rest] = positional
32
32
  const asJson = flags.get('json') === 'true'
33
33
  const timeoutSec = Number(flags.get('timeout') ?? 120)
34
34
 
35
- const bin = process.env.CODEX_CLI_PATH ?? Bun.which('codex')
35
+ const bin = Bun.which('codex')
36
36
  if (!bin) {
37
- console.error('codex binary not found (install @openai/codex or set CODEX_CLI_PATH)')
37
+ console.error(
38
+ 'Run curl -fsSL https://chatgpt.com/codex/install.sh | sh in your terminal to install Codex'
39
+ )
38
40
  process.exit(1)
39
41
  }
40
42
 
@@ -16,8 +16,14 @@
16
16
  // `clientUserMessageId` as `clientId`, so the optimistic-id rendezvous is
17
17
  // first-class (no text matching like OpenClaw needs).
18
18
  import { appendAttachmentNote } from '@/lib/attachment-note'
19
+ import {
20
+ type MoiContext,
21
+ appendMoiContext,
22
+ renderMoiContext,
23
+ renderMoiContextBody
24
+ } from '@/lib/moi-context'
19
25
  import { type Part, type SubagentRecord, type Turn, applyEvent, emptyViewState } from '@/lib/format'
20
- import type { StreamEvent, ViewState } from '@/lib/types'
26
+ import type { SessionActivity, StreamEvent, ViewState } from '@/lib/types'
21
27
 
22
28
  import {
23
29
  type CodexThread,
@@ -91,10 +97,20 @@ function liveKey(workspaceId: string, sessionId: string): string {
91
97
  return real ? recKey(workspaceId, real) : direct
92
98
  }
93
99
 
94
- export function getCodexRunningSessions(): { workspaceId: string; sessionId: string }[] {
95
- const out: { workspaceId: string; sessionId: string }[] = []
100
+ export function getCodexActiveSessions(): {
101
+ workspaceId: string
102
+ sessionId: string
103
+ activity: SessionActivity
104
+ }[] {
105
+ const out: { workspaceId: string; sessionId: string; activity: SessionActivity }[] = []
96
106
  for (const s of sessions.values()) {
97
- if (s.processing) out.push({ workspaceId: s.workspaceId, sessionId: s.sessionId })
107
+ // Codex never surfaces `requires-action`: approvals are designed out
108
+ // (APPROVAL_POLICY 'never' + transport auto-accept in client.ts). If that
109
+ // policy is ever relaxed, `*requestApproval` / `elicitation` server
110
+ // requests are the signals to map to it.
111
+ if (s.processing) {
112
+ out.push({ workspaceId: s.workspaceId, sessionId: s.sessionId, activity: 'running' })
113
+ }
98
114
  }
99
115
  return out
100
116
  }
@@ -103,7 +119,11 @@ function setProcessing(rec: SessionRecord, processing: boolean, turnId: string |
103
119
  rec.activeTurnId = turnId
104
120
  if (rec.processing === processing) return
105
121
  rec.processing = processing
106
- broadcast(rec.workspaceId, { type: 'status', sessionId: rec.sessionId, processing })
122
+ broadcast(rec.workspaceId, {
123
+ type: 'status',
124
+ sessionId: rec.sessionId,
125
+ activity: processing ? 'running' : 'idle'
126
+ })
107
127
  }
108
128
 
109
129
  function emitTurnEvent(rec: SessionRecord, ev: StreamEvent) {
@@ -290,6 +310,11 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
290
310
  content: turn.error.message
291
311
  })
292
312
  }
313
+ // An externally-interrupted turn otherwise ends silently, identical to a
314
+ // clean completion — surface the stop so the client can render it.
315
+ if (turn?.status === 'interrupted') {
316
+ broadcast(rec.workspaceId, { kind: 'stopped', sessionId: rec.sessionId })
317
+ }
293
318
  return
294
319
  }
295
320
  case 'error': {
@@ -298,6 +323,9 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
298
323
  if (message) {
299
324
  broadcast(rec.workspaceId, { kind: 'error', sessionId: rec.sessionId, content: message })
300
325
  }
326
+ // A top-level error without a following turn/completed would otherwise
327
+ // leave the session busy forever — the error is terminal for the turn.
328
+ setProcessing(rec, false, null)
301
329
  return
302
330
  }
303
331
  // Codex hooks (~/.codex/hooks.json) — surface as hook notices, parity
@@ -452,6 +480,11 @@ export async function sendCodexMessage(input: {
452
480
  model?: string
453
481
  effort?: string
454
482
  stream?: boolean
483
+ // Structured moi context (lib/moi-context.ts), rendered here. Servers
484
+ // >= 0.135 take it via `additionalContext` (never enters userMessage
485
+ // items); older ones get it appended to the text item, stripped from
486
+ // echoes by the adapter.
487
+ context?: MoiContext
455
488
  }): Promise<void> {
456
489
  const uploads = input.attachments?.length
457
490
  ? resolveUploads(input.workspaceId, input.attachments)
@@ -496,6 +529,9 @@ export async function sendCodexMessage(input: {
496
529
  rec = await resumeSession(input)
497
530
  }
498
531
  } catch (err) {
532
+ // No session record exists to run setProcessing through — clear the
533
+ // client's optimistic spinner explicitly or it sticks until reconnect.
534
+ broadcast(input.workspaceId, { type: 'status', sessionId: input.sessionId, activity: 'idle' })
499
535
  broadcast(input.workspaceId, {
500
536
  kind: 'error',
501
537
  sessionId: input.sessionId,
@@ -524,10 +560,25 @@ export async function sendCodexMessage(input: {
524
560
  setProcessing(rec, true, rec.activeTurnId)
525
561
  try {
526
562
  const client = await getCodexClient(input.workspacePath)
563
+ // Native context channel: diffed per key server-side (unchanged values
564
+ // inject nothing) and never echoed back in userMessage items. The entry
565
+ // key becomes the tag, so ship the unwrapped body. Older servers silently
566
+ // drop the field, so append to the text item there instead.
567
+ const additionalContext =
568
+ input.context && client.supportsAdditionalContext
569
+ ? { 'moi-context': { value: renderMoiContextBody(input.context), kind: 'application' } }
570
+ : undefined
571
+ if (input.context && !additionalContext) {
572
+ const envelope = renderMoiContext(input.context)
573
+ const last = userInput[userInput.length - 1]
574
+ if (last?.type === 'text') last.text = appendMoiContext(last.text, envelope)
575
+ else userInput.push({ type: 'text', text: envelope })
576
+ }
527
577
  const turnParams = {
528
578
  threadId: rec.sessionId,
529
579
  clientUserMessageId: turnId,
530
580
  input: userInput,
581
+ ...(additionalContext ? { additionalContext } : {}),
531
582
  // Without an explicit summary mode Codex still reasons but emits the
532
583
  // reasoning item with EMPTY summary/content (verified on the wire —
533
584
  // scripts/codex-probe.ts), so no thinking ever reaches the UI. 'auto'
@@ -545,6 +596,7 @@ export async function sendCodexMessage(input: {
545
596
  threadId: rec.sessionId,
546
597
  clientUserMessageId: turnId,
547
598
  input: userInput,
599
+ ...(additionalContext ? { additionalContext } : {}),
548
600
  expectedTurnId: rec.activeTurnId
549
601
  })
550
602
  } catch {
@@ -0,0 +1,82 @@
1
+ import { accessSync, constants, statSync } from 'node:fs'
2
+
3
+ import type { HarnessAvailability, WorkspaceType } from '@/lib/types'
4
+
5
+ import { cachedLoginShellPath, loginShellPath, mergeSearchPaths } from './shell-path'
6
+
7
+ type PathWorkspaceType = Extract<WorkspaceType, 'claude-code' | 'codex'>
8
+
9
+ type ExecutableConfig = {
10
+ command: string
11
+ unavailableReason: string
12
+ // Absolute locations probed when the PATH lookup misses. PATH wins, so a
13
+ // deliberately installed CLI is never shadowed by an app-bundled copy.
14
+ fallbackPaths?: readonly string[]
15
+ }
16
+
17
+ const executableConfig: Record<PathWorkspaceType, ExecutableConfig> = {
18
+ 'claude-code': {
19
+ command: 'claude',
20
+ unavailableReason:
21
+ 'Run curl -fsSL https://claude.ai/install.sh | sh in your terminal to install Claude'
22
+ },
23
+ codex: {
24
+ command: 'codex',
25
+ // Codex Desktop manages an app-internal binary and does not put `codex`
26
+ // on PATH: probe the known macOS bundle locations (ChatGPT.app is the
27
+ // current home, Codex.app the legacy standalone install).
28
+ fallbackPaths: [
29
+ '/Applications/ChatGPT.app/Contents/Resources/codex',
30
+ '/Applications/Codex.app/Contents/Resources/codex'
31
+ ],
32
+ unavailableReason:
33
+ 'Run curl -fsSL https://chatgpt.com/codex/install.sh | sh in your terminal to install Codex'
34
+ }
35
+ }
36
+
37
+ // Resolve the login-shell PATH eagerly so sync lookups on the spawn path see
38
+ // it settled long before the first session starts.
39
+ void loginShellPath()
40
+
41
+ function isExecutableFile(path: string): boolean {
42
+ try {
43
+ accessSync(path, constants.X_OK)
44
+ return statSync(path).isFile()
45
+ } catch {
46
+ return false
47
+ }
48
+ }
49
+
50
+ export function firstExecutable(paths: readonly string[]): string | null {
51
+ return paths.find(isExecutableFile) ?? null
52
+ }
53
+
54
+ // `path` is a test seam: when given, only that PATH is searched — no
55
+ // login-shell merge, no bundle fallbacks.
56
+ export function findHarnessExecutable(type: PathWorkspaceType, path?: string): string | null {
57
+ const config = executableConfig[type]
58
+ if (path !== undefined) return Bun.which(config.command, { PATH: path })
59
+ return (
60
+ Bun.which(config.command, {
61
+ PATH: mergeSearchPaths(cachedLoginShellPath(), process.env.PATH)
62
+ }) ?? firstExecutable(config.fallbackPaths ?? [])
63
+ )
64
+ }
65
+
66
+ export function requireHarnessExecutable(type: PathWorkspaceType, path?: string): string {
67
+ const executable = findHarnessExecutable(type, path)
68
+ if (!executable) throw new Error(executableConfig[type].unavailableReason)
69
+ return executable
70
+ }
71
+
72
+ export async function pathHarnessAvailability(
73
+ type: PathWorkspaceType,
74
+ path?: string
75
+ ): Promise<HarnessAvailability> {
76
+ // Availability is asked per request (and long after startup), but await the
77
+ // probe anyway so the very first request can't report a false negative.
78
+ if (path === undefined) await loginShellPath()
79
+ return findHarnessExecutable(type, path)
80
+ ? { available: true }
81
+ : { available: false, reason: executableConfig[type].unavailableReason }
82
+ }
@@ -25,11 +25,18 @@ import type {
25
25
  OpenClawSessionDetail,
26
26
  OpenClawSessionRow
27
27
  } from './discovery'
28
+ import { stripMoiContextLoose } from '@/lib/moi-context'
28
29
  import { stripUserMessageMetadata } from './strip'
29
30
 
30
31
  export function toSessionInfo(row: OpenClawSessionRow, cwd: string): SessionInfo {
32
+ // Gateway previews carry the raw stored message — for a user send that
33
+ // includes the appended context envelope, and truncation can cut it open,
34
+ // so clean with the loose strip like the Codex previews do.
31
35
  const summary =
32
- row.lastMessagePreview?.trim() || row.displayName?.trim() || row.label?.trim() || ''
36
+ stripMoiContextLoose(row.lastMessagePreview ?? '').trim() ||
37
+ row.displayName?.trim() ||
38
+ row.label?.trim() ||
39
+ ''
33
40
  return {
34
41
  sessionId: row.sessionId,
35
42
  summary,