moi-computer 0.5.2-next.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/client/AGENTS.md +9 -0
  2. package/client/api/app-ui-keys.ts +4 -0
  3. package/client/api/workspace-keys.ts +2 -2
  4. package/client/app/routes/WorkspaceRoute.tsx +8 -28
  5. package/client/app/shell/SidebarLayout.tsx +1 -1
  6. package/client/components/shared/Composer.tsx +15 -9
  7. package/client/components/shared/IconGhost.tsx +130 -0
  8. package/client/components/ui/dropdown-menu.tsx +2 -5
  9. package/client/components/ui/popover.tsx +11 -4
  10. package/client/components/ui/slider.tsx +70 -0
  11. package/client/components/ui/spinner.tsx +18 -0
  12. package/client/components/ui/toast.tsx +220 -0
  13. package/client/components/ui/tooltip.tsx +1 -1
  14. package/client/features/chat/ChatComposer.tsx +11 -14
  15. package/client/features/chat/ChatPanel.tsx +15 -14
  16. package/client/features/chat/ChatPopup.tsx +10 -4
  17. package/client/features/chat/ChatSelector.tsx +263 -48
  18. package/client/features/chat/ModelPicker.tsx +295 -121
  19. package/client/features/chat/TurnView.tsx +1 -1
  20. package/client/features/chat/api.ts +36 -9
  21. package/client/features/chat/chat-frames.ts +35 -6
  22. package/client/features/chat/chat-send.ts +40 -6
  23. package/client/features/chat/chat-store.ts +52 -40
  24. package/client/features/chat/model-order.ts +50 -28
  25. package/client/features/chat/useChat.ts +71 -60
  26. package/client/features/chat/useSelectedSession.ts +151 -0
  27. package/client/features/chat/useStickToBottom.ts +3 -3
  28. package/client/features/home/api.ts +0 -2
  29. package/client/features/scratchpad/ScratchpadControls.tsx +2 -2
  30. package/client/features/settings/IconPicker.tsx +2 -2
  31. package/client/features/settings/WorkspaceSettings.tsx +6 -6
  32. package/client/features/views/ViewBuilderTab.tsx +3 -4
  33. package/client/features/views/api.ts +1 -0
  34. package/client/features/views/useViewBuilderActions.ts +7 -3
  35. package/client/features/workspace/WorkspaceScreen.tsx +40 -19
  36. package/client/features/workspace/WorkspaceSkillUpdateBanner.tsx +2 -2
  37. package/client/features/workspace/WorkspaceTabs.tsx +10 -1
  38. package/client/index.css +5 -3
  39. package/client/main.tsx +2 -0
  40. package/client/runtime/useWorkspaceEvents.ts +1 -0
  41. package/client/store/ui.ts +13 -3
  42. package/dist/{chunk-m9qja0nx.js → chunk-0pcdwjkp.js} +1 -1
  43. package/dist/chunk-55sh4dty.js +2 -0
  44. package/dist/{chunk-h3evrtyp.js → chunk-9y2zbzqz.js} +1 -1
  45. package/dist/{chunk-7bzpmtxp.js → chunk-afgbg75t.js} +1 -1
  46. package/dist/chunk-agtetn7n.css +1 -0
  47. package/dist/chunk-bv6vrvqf.js +27 -0
  48. package/dist/chunk-dfs36zgc.js +1 -0
  49. package/dist/chunk-exj6hr30.js +9 -0
  50. package/dist/{chunk-v797g6ap.js → chunk-m11ckkxd.js} +1 -1
  51. package/dist/chunk-n6t40enm.js +1 -0
  52. package/dist/{chunk-jg6ezptn.js → chunk-rxvx4ta9.js} +3 -3
  53. package/dist/index.html +1 -1
  54. package/lib/attachment-note.ts +18 -0
  55. package/lib/chat-title.ts +6 -0
  56. package/lib/types.ts +33 -10
  57. package/package.json +1 -1
  58. package/server/api.ts +100 -10
  59. package/server/app-settings.ts +1 -1
  60. package/server/data-dir.ts +1 -1
  61. package/server/harness/README.md +6 -0
  62. package/server/harness/claude-code/adapter.ts +2 -2
  63. package/server/harness/claude-code/index.ts +7 -1
  64. package/server/harness/claude-code/models.ts +25 -2
  65. package/server/harness/claude-code/session-title.ts +106 -0
  66. package/server/harness/claude-code/session.ts +114 -17
  67. package/server/harness/claude-code/sessions.ts +35 -4
  68. package/server/harness/codex/adapter.ts +27 -2
  69. package/server/harness/codex/client.ts +56 -9
  70. package/server/harness/codex/index.ts +2 -0
  71. package/server/harness/codex/session-title.ts +149 -0
  72. package/server/harness/codex/session.ts +96 -14
  73. package/server/harness/openclaw/adapter.ts +4 -2
  74. package/server/harness/openclaw/discovery.ts +2 -0
  75. package/server/harness/openclaw/session.ts +15 -7
  76. package/server/harness/session-title.ts +96 -0
  77. package/server/harness/types.ts +5 -2
  78. package/server/selected-session.ts +132 -0
  79. package/server/session-config.ts +146 -0
  80. package/server/web.ts +15 -1
  81. package/workspace/.claude/skills/moi-workspace/DESIGN.md +54 -68
  82. package/workspace/.claude/skills/moi-workspace/SKILL.md +8 -2
  83. package/dist/chunk-5vaevt8z.js +0 -2
  84. package/dist/chunk-fhhv99bd.js +0 -1
  85. package/dist/chunk-h0hk61pm.js +0 -9
  86. package/dist/chunk-k5sjx9s5.js +0 -1
  87. package/dist/chunk-rs9nb0fr.js +0 -27
  88. package/dist/chunk-s7za1qsv.css +0 -1
  89. package/server/thread-config.ts +0 -124
@@ -18,8 +18,10 @@ import {
18
18
  query
19
19
  } from '@anthropic-ai/claude-agent-sdk'
20
20
 
21
- import { ATTACHMENT_ONLY_PLACEHOLDER, appendAttachmentNote } from '@/lib/attachment-note'
21
+ import { appendAttachmentNote, attachmentOnlyPlaceholder } from '@/lib/attachment-note'
22
+ import { buildSessionTitleSource } from '../session-title'
22
23
  import { ClaudeAdapter } from './adapter'
24
+ import { generateClaudeSessionTitle, renameClaudeSessionIfUnchanged } from './session-title'
23
25
  import type { Part } from '@/lib/format'
24
26
  import type { SessionActivity } from '@/lib/types'
25
27
  import { type MoiContext, moiContextSystemReminder, renderMoiContext } from '@/lib/moi-context'
@@ -27,7 +29,8 @@ import { type MoiContext, moiContextSystemReminder, renderMoiContext } from '@/l
27
29
  import { debug } from '../../debug'
28
30
  import { tapWire } from '../debug'
29
31
  import { broadcast } from '../../state'
30
- import { hasThreadConfig, renameThreadConfig, saveThreadConfig } from '../../thread-config'
32
+ import { renameSelectedSession } from '../../selected-session'
33
+ import { hasSessionConfig, renameSessionConfig, saveSessionConfig } from '../../session-config'
31
34
  import { type StoredUpload, resolveUploads, uploadToDisplayPart } from '../../uploads'
32
35
  import {
33
36
  markViewBuilderBuildingBySession,
@@ -80,11 +83,11 @@ export function buildUserMessage(
80
83
 
81
84
  const files = uploads.filter(u => u.kind === 'file' && u.path)
82
85
  const agentText = appendAttachmentNote(
83
- text,
86
+ text || attachmentOnlyPlaceholder(uploads.map(upload => upload.filename)),
84
87
  files.map(f => ({ filename: f.filename, path: f.path! }))
85
88
  )
86
89
  // Always end with a text block so an image-only message still has a prompt.
87
- blocks.push({ type: 'text', text: agentText || ATTACHMENT_ONLY_PLACEHOLDER })
90
+ blocks.push({ type: 'text', text: agentText })
88
91
  return { content: blocks, parts }
89
92
  }
90
93
 
@@ -121,6 +124,7 @@ type InputQueue = {
121
124
  type LiveSession = {
122
125
  workspaceId: string
123
126
  workspacePath: string
127
+ workspaceEnv: Record<string, string>
124
128
  sessionId: string // current real id (rekeyed on rename)
125
129
  q: Query
126
130
  adapter: ClaudeAdapter
@@ -140,6 +144,9 @@ type LiveSession = {
140
144
  // idle TTL — tearing down the subprocess would kill its background children.
141
145
  bgTasks: Set<string>
142
146
  model: string | undefined
147
+ // Fast mode is a live flag setting. Undefined clears moi's override and
148
+ // inherits the provider configuration.
149
+ fastMode: boolean | undefined
143
150
  // Reasoning effort the query was created with. The SDK has no live setter for
144
151
  // it (unlike setModel), so a change tears the session down and resumes.
145
152
  effort: string | undefined
@@ -163,6 +170,9 @@ type LiveSession = {
163
170
  createdAt: number
164
171
  lastActivityAt: number
165
172
  lastUserText: string | undefined
173
+ refreshSessionsOnResult: boolean
174
+ sessionTitleSource: string | undefined
175
+ sessionTitleAbort: AbortController | null
166
176
  }
167
177
 
168
178
  const sessions = new Map<string, LiveSession>()
@@ -208,6 +218,7 @@ export type CCDebugSession = {
208
218
  workspaceId: string
209
219
  sessionId: string
210
220
  model: string | undefined
221
+ fastMode: boolean | undefined
211
222
  effort: string | undefined
212
223
  desiredEffort: string | undefined
213
224
  stream: boolean
@@ -229,6 +240,7 @@ export function getCCDebugSnapshot(): { sessions: CCDebugSession[]; aliases: num
229
240
  workspaceId: s.workspaceId,
230
241
  sessionId: s.sessionId,
231
242
  model: s.model,
243
+ fastMode: s.fastMode,
232
244
  effort: s.effort,
233
245
  desiredEffort: s.desiredEffort,
234
246
  stream: s.stream,
@@ -328,6 +340,8 @@ function teardown(s: LiveSession) {
328
340
  setActivity(s, 'idle')
329
341
  s.closed = true
330
342
  clearIdle(s)
343
+ s.sessionTitleAbort?.abort()
344
+ s.sessionTitleAbort = null
331
345
  s.input.close()
332
346
  try {
333
347
  s.q.close?.()
@@ -340,17 +354,59 @@ function teardown(s: LiveSession) {
340
354
  }
341
355
  }
342
356
 
357
+ function isCurrentLiveSession(s: LiveSession, abort: AbortController): boolean {
358
+ return (
359
+ !s.closed && !abort.signal.aborted && sessions.get(recKey(s.workspaceId, s.sessionId)) === s
360
+ )
361
+ }
362
+
363
+ function startClaudeSessionTitleJob(s: LiveSession) {
364
+ if (!s.sessionTitleSource || s.closed) return
365
+ const source = s.sessionTitleSource
366
+ s.sessionTitleSource = undefined
367
+ const abort = new AbortController()
368
+ s.sessionTitleAbort = abort
369
+
370
+ void (async () => {
371
+ try {
372
+ const title = await generateClaudeSessionTitle({
373
+ source,
374
+ abortController: abort
375
+ })
376
+ if (!title || !isCurrentLiveSession(s, abort)) return
377
+
378
+ const renamed = await renameClaudeSessionIfUnchanged({
379
+ sessionId: s.sessionId,
380
+ workspacePath: s.workspacePath,
381
+ title,
382
+ isCurrent: () => isCurrentLiveSession(s, abort)
383
+ })
384
+ if (!renamed || !isCurrentLiveSession(s, abort)) return
385
+ broadcast(s.workspaceId, { type: 'sessions_changed', sessionId: s.sessionId })
386
+ debug(
387
+ `cc session title ws=${s.workspaceId} session=${s.sessionId} title=${JSON.stringify(title)}`
388
+ )
389
+ } catch (err) {
390
+ debug(
391
+ `cc session title failed ws=${s.workspaceId} session=${s.sessionId}: ${err instanceof Error ? err.message : String(err)}`
392
+ )
393
+ } finally {
394
+ if (s.sessionTitleAbort === abort) s.sessionTitleAbort = null
395
+ }
396
+ })()
397
+ }
398
+
343
399
  // On `system/init` the SDK reports the real session id. For a brand-new session
344
400
  // that differs from the client's temporary id, so we rekey the registry and
345
401
  // tell the client to move its optimistic state. Subsequent inits report the
346
402
  // same id and no-op.
347
- function renameSession(s: LiveSession, realId: string) {
403
+ function renameSession(s: LiveSession, realId: string): string {
348
404
  const from = s.sessionId
349
405
  sessions.delete(recKey(s.workspaceId, from))
350
406
  s.sessionId = realId
351
407
  sessions.set(recKey(s.workspaceId, realId), s)
352
408
  aliases.set(recKey(s.workspaceId, from), realId)
353
- broadcast(s.workspaceId, { type: 'session_renamed', from, to: realId })
409
+ return from
354
410
  }
355
411
 
356
412
  // The session just went idle (state event, or `result` on a CLI without state
@@ -375,20 +431,30 @@ async function consume(s: LiveSession) {
375
431
  if (msg.type === 'system' && msg.subtype === 'init') {
376
432
  const realId = msg.session_id
377
433
  if (realId && realId !== s.sessionId) {
378
- const from = s.sessionId
379
- renameSession(s, realId)
434
+ const from = renameSession(s, realId)
380
435
  // Carry any config the picker wrote under the temp id to the real id.
381
- await renameThreadConfig(s.workspacePath, from, s.sessionId)
436
+ await renameSessionConfig(s.workspacePath, from, s.sessionId)
437
+ await renameSelectedSession(s.workspacePath, from, s.sessionId)
382
438
  await renameViewBuilderSession(s.workspaceId, s.workspacePath, from, s.sessionId)
439
+ broadcast(s.workspaceId, {
440
+ type: 'session_renamed',
441
+ from,
442
+ to: s.sessionId
443
+ })
383
444
  }
384
- // Seed the thread's config from what it actually ran with — but only if
445
+ startClaudeSessionTitleJob(s)
446
+ // Seed the session's config from what it actually ran with — but only if
385
447
  // it has none yet, so an explicit user PUT (or a migrated temp-id edit)
386
- // always wins. A default run (no model/effort) leaves no file and falls
387
- // back to the workspace defaults.
388
- if ((s.model || s.effort) && !(await hasThreadConfig(s.workspacePath, s.sessionId))) {
389
- await saveThreadConfig(s.workspacePath, s.sessionId, {
448
+ // always wins. A default run leaves no file and falls back to the
449
+ // workspace defaults.
450
+ if (
451
+ (s.model || s.effort || s.fastMode !== undefined) &&
452
+ !(await hasSessionConfig(s.workspacePath, s.sessionId))
453
+ ) {
454
+ await saveSessionConfig(s.workspacePath, s.sessionId, {
390
455
  model: s.model,
391
- effort: s.effort
456
+ effort: s.effort,
457
+ fastMode: s.fastMode
392
458
  })
393
459
  }
394
460
  }
@@ -466,6 +532,10 @@ async function consume(s: LiveSession) {
466
532
  ? undefined
467
533
  : msg.errors.join('\n') || msg.subtype.replaceAll('_', ' ')
468
534
  debug(`cc result ws=${s.workspaceId} session=${s.sessionId} subtype=${msg.subtype}`)
535
+ if (s.refreshSessionsOnResult) {
536
+ s.refreshSessionsOnResult = false
537
+ broadcast(s.workspaceId, { type: 'sessions_changed', sessionId: s.sessionId })
538
+ }
469
539
  // Fallback for CLIs that never emit `session_state_changed`: treat
470
540
  // every result as turn-over. With state events, `idle` follows the
471
541
  // result and drives the same path.
@@ -514,12 +584,14 @@ function createLiveSession(input: {
514
584
  isNew: boolean
515
585
  model: string | undefined
516
586
  effort: string | undefined
587
+ fastMode: boolean | undefined
517
588
  // Live token streaming (`includePartialMessages`). Only enabled when the
518
589
  // client opts in; off leaves the query byte-for-byte as before.
519
590
  stream: boolean
520
591
  // Resolved workspace env (.env + UI custom overrides), injected so the agent's
521
592
  // Bash tool can use workspace secrets. Frozen at spawn — see restartWorkspaceSessions.
522
593
  workspaceEnv: Record<string, string>
594
+ sessionTitleSource: string | undefined
523
595
  }): LiveSession {
524
596
  evictIfNeeded()
525
597
 
@@ -544,6 +616,7 @@ function createLiveSession(input: {
544
616
  // is valid for the model; the SDK silently downgrades otherwise. Cast because
545
617
  // the SDK under-types the union (no 'xhigh') vs our pass-through string.
546
618
  ...(input.effort ? { effort: input.effort as Options['effort'] } : {}),
619
+ ...(input.fastMode !== undefined ? { settings: { fastMode: input.fastMode } } : {}),
547
620
  // Emit `stream_event` partial-message frames so the adapter can surface a
548
621
  // live token-by-token preview. Off = unchanged behavior (whole blocks only).
549
622
  includePartialMessages: input.stream,
@@ -559,6 +632,7 @@ function createLiveSession(input: {
559
632
  const session: LiveSession = {
560
633
  workspaceId: input.workspaceId,
561
634
  workspacePath: input.workspacePath,
635
+ workspaceEnv: input.workspaceEnv,
562
636
  sessionId: input.sessionId,
563
637
  q: query({ prompt: queue.iterator, options }),
564
638
  adapter: new ClaudeAdapter(),
@@ -568,6 +642,7 @@ function createLiveSession(input: {
568
642
  sawStateEvents: false,
569
643
  bgTasks: new Set(),
570
644
  model: input.model,
645
+ fastMode: input.fastMode,
571
646
  effort: input.effort,
572
647
  desiredEffort: input.effort,
573
648
  stream: input.stream,
@@ -577,11 +652,14 @@ function createLiveSession(input: {
577
652
  lastBuilderError: undefined,
578
653
  createdAt: Date.now(),
579
654
  lastActivityAt: Date.now(),
580
- lastUserText: undefined
655
+ lastUserText: undefined,
656
+ refreshSessionsOnResult: input.isNew,
657
+ sessionTitleSource: input.sessionTitleSource,
658
+ sessionTitleAbort: null
581
659
  }
582
660
  sessions.set(recKey(session.workspaceId, session.sessionId), session)
583
661
  debug(
584
- `cc create ${input.isNew ? 'new' : 'resume'} ws=${input.workspaceId} session=${input.sessionId} model=${input.model ?? 'default'} effort=${input.effort ?? 'default'} live=${sessions.size}`
662
+ `cc create ${input.isNew ? 'new' : 'resume'} ws=${input.workspaceId} session=${input.sessionId} model=${input.model ?? 'default'} effort=${input.effort ?? 'default'} fast=${input.fastMode ?? 'default'} live=${sessions.size}`
585
663
  )
586
664
  void consume(session)
587
665
  return session
@@ -600,6 +678,7 @@ export async function sendCCMessage(input: {
600
678
  optimisticId?: string
601
679
  model?: string
602
680
  effort?: string
681
+ fastMode?: boolean
603
682
  stream?: boolean
604
683
  // Structured moi context (lib/moi-context.ts), rendered here and injected
605
684
  // as a leading system-reminder text block; the display parts never see it.
@@ -612,6 +691,12 @@ export async function sendCCMessage(input: {
612
691
  ? resolveUploads(input.workspaceId, input.attachments)
613
692
  : []
614
693
  if (!input.content && uploads.length === 0) return
694
+ const sessionTitleSource = input.isNew
695
+ ? buildSessionTitleSource(
696
+ input.content,
697
+ uploads.map(upload => upload.filename)
698
+ )
699
+ : undefined
615
700
  const { content: userContent, parts } = buildUserMessage(input.content, uploads)
616
701
  // The envelope goes in as its OWN leading text block, never merged into the
617
702
  // user's string: the SDK's first-prompt extraction (session titles,
@@ -654,6 +739,15 @@ export async function sendCCMessage(input: {
654
739
  // silently lose the message and hang the spinner).
655
740
  if (s.closed) s = undefined
656
741
  }
742
+ if (s && input.fastMode !== s.fastMode) {
743
+ try {
744
+ await s.q.applyFlagSettings({ fastMode: input.fastMode ?? null })
745
+ s.fastMode = input.fastMode
746
+ } catch (err) {
747
+ console.error('[cc-session] applyFlagSettings failed', err)
748
+ }
749
+ if (s.closed) s = undefined
750
+ }
657
751
  if (s) {
658
752
  // Effort/streaming can't change on a running query; record the request so
659
753
  // the session rebuilds once its turns drain (see the `result` handler).
@@ -671,7 +765,9 @@ export async function sendCCMessage(input: {
671
765
  isNew: input.isNew,
672
766
  model: input.model,
673
767
  effort: input.effort,
768
+ fastMode: input.fastMode,
674
769
  stream: wantStream,
770
+ sessionTitleSource,
675
771
  // The agent only sees secrets scoped to the 'agent' sink (plus .env).
676
772
  workspaceEnv: await resolveWorkspaceEnv(input.workspacePath)
677
773
  })
@@ -748,6 +844,7 @@ export async function interruptCCSession(workspaceId: string, sessionId: string)
748
844
  }
749
845
  } catch (err) {
750
846
  console.error('[cc-session] interrupt failed', err)
847
+ teardown(s)
751
848
  } finally {
752
849
  clearTimeout(timer)
753
850
  }
@@ -1,11 +1,19 @@
1
1
  // Session discovery + history replay for Claude Code workspaces, backed by
2
2
  // the Agent SDK's persisted `.jsonl` session files.
3
- import { getSessionMessages, listSessions } from '@anthropic-ai/claude-agent-sdk'
3
+ import { getSessionMessages, listSessions, tagSession } from '@anthropic-ai/claude-agent-sdk'
4
+ import type { SDKSessionInfo } from '@anthropic-ai/claude-agent-sdk'
4
5
 
6
+ import {
7
+ attachmentOnlyFilenames,
8
+ isAttachmentOnlyPlaceholder,
9
+ splitAttachmentNote
10
+ } from '@/lib/attachment-note'
5
11
  import type { SessionInfo, StreamEvent } from '@/lib/types'
6
12
 
7
13
  import { ClaudeAdapter } from './adapter'
8
14
 
15
+ export const MOI_ARCHIVED_SESSION_TAG = 'moi:archived'
16
+
9
17
  export type SessionFirstPromptCandidate = {
10
18
  sessionId: string
11
19
  firstPrompt?: string
@@ -18,11 +26,27 @@ export type SessionWorkspacePreview = {
18
26
  updatedAt?: number
19
27
  }
20
28
 
29
+ export function claudeSessionSummary(
30
+ session: Pick<SDKSessionInfo, 'customTitle' | 'firstPrompt' | 'summary'>
31
+ ): string {
32
+ if (session.customTitle || !session.firstPrompt || session.summary !== session.firstPrompt) {
33
+ return session.summary
34
+ }
35
+ const split = splitAttachmentNote(session.firstPrompt)
36
+ return isAttachmentOnlyPlaceholder(split.text)
37
+ ? attachmentOnlyFilenames(split.text).join(', ')
38
+ : session.summary
39
+ }
40
+
41
+ export function visibleClaudeSessions<T extends Pick<SDKSessionInfo, 'tag'>>(sessions: T[]): T[] {
42
+ return sessions.filter(session => session.tag !== MOI_ARCHIVED_SESSION_TAG)
43
+ }
44
+
21
45
  export async function getSessions(workspacePath: string): Promise<SessionInfo[]> {
22
- const sessions = await listSessions({ dir: workspacePath })
46
+ const sessions = visibleClaudeSessions(await listSessions({ dir: workspacePath }))
23
47
  return sessions.map(s => ({
24
48
  sessionId: s.sessionId,
25
- summary: s.summary,
49
+ summary: claudeSessionSummary(s),
26
50
  lastModified: s.lastModified,
27
51
  cwd: s.cwd
28
52
  }))
@@ -55,7 +79,7 @@ export async function getSessionWorkspacePreview(
55
79
  workspacePath: string,
56
80
  includeFirstUserMessage: boolean
57
81
  ): Promise<SessionWorkspacePreview> {
58
- const sessions = await listSessions({ dir: workspacePath })
82
+ const sessions = visibleClaudeSessions(await listSessions({ dir: workspacePath }))
59
83
  const updatedAt = selectLatestSessionUpdatedAt(sessions)
60
84
  const firstUserMessage = includeFirstUserMessage
61
85
  ? selectOldestSessionFirstUserMessage(sessions)
@@ -67,6 +91,13 @@ export async function getSessionWorkspacePreview(
67
91
  }
68
92
  }
69
93
 
94
+ export async function archiveClaudeSession(
95
+ sessionId: string,
96
+ workspacePath: string
97
+ ): Promise<void> {
98
+ await tagSession(sessionId, MOI_ARCHIVED_SESSION_TAG, { dir: workspacePath })
99
+ }
100
+
70
101
  /**
71
102
  * Replay a session's persisted raw messages through a fresh adapter and
72
103
  * return the resulting StreamEvents. Events are carefully NOT deduplicated —
@@ -112,10 +112,23 @@ export type CodexModel = {
112
112
  supportedReasoningEfforts?: { reasoningEffort: string; description?: string }[]
113
113
  defaultReasoningEffort?: string
114
114
  isDefault?: boolean
115
+ serviceTiers?: { id: string; name: string; description: string }[]
116
+ defaultServiceTier?: string | null
117
+ // Older app-server versions advertised Fast mode through this field.
118
+ additionalSpeedTiers?: string[]
115
119
  }
116
120
 
117
121
  // ---- discovery mappings ------------------------------------------------------
118
122
 
123
+ const CODEX_FAST_SERVICE_TIER = 'priority'
124
+
125
+ export function codexServiceTierForFastMode(
126
+ fastMode: boolean | undefined
127
+ ): typeof CODEX_FAST_SERVICE_TIER | null | undefined {
128
+ if (fastMode === undefined) return undefined
129
+ return fastMode ? CODEX_FAST_SERVICE_TIER : null
130
+ }
131
+
119
132
  // `thread/list.preview` snippets come from the raw first user message — on
120
133
  // the pre-0.135 fallback path that text carries the appended context envelope,
121
134
  // so previews strip it like transcript turns do. Loose variant: previews are
@@ -164,9 +177,15 @@ export function selectCodexWorkspacePreview(
164
177
  }
165
178
  }
166
179
 
167
- export function codexModelToModel(m: CodexModel): Model {
180
+ export function codexModelToModel(m: CodexModel, configuredServiceTier?: string | null): Model {
168
181
  const efforts = (m.supportedReasoningEfforts ?? []).map(e => e.reasoningEffort)
169
182
  const displayName = m.displayName.replace(/^GPT-/, '').replaceAll('-', ' ')
183
+ const supportsFastMode =
184
+ (m.serviceTiers ?? []).some(tier => tier.id === CODEX_FAST_SERVICE_TIER) ||
185
+ (m.additionalSpeedTiers ?? []).includes('fast')
186
+ // The effective user/project config governs omitted wire values. A null
187
+ // config value leaves the model catalog's default in charge.
188
+ const defaultServiceTier = configuredServiceTier ?? m.defaultServiceTier
170
189
  return {
171
190
  value: m.id,
172
191
  resolvedModel: m.model,
@@ -178,7 +197,13 @@ export function codexModelToModel(m: CodexModel): Model {
178
197
  ? { description: `${displayName} · ${m.description}` }
179
198
  : { description: displayName }),
180
199
  supportsEffort: efforts.length > 0,
181
- ...(efforts.length > 0 ? { supportedEffortLevels: efforts } : {})
200
+ ...(efforts.length > 0 ? { supportedEffortLevels: efforts } : {}),
201
+ ...(supportsFastMode
202
+ ? {
203
+ supportsFastMode: true,
204
+ defaultFastMode: defaultServiceTier === CODEX_FAST_SERVICE_TIER
205
+ }
206
+ : {})
182
207
  }
183
208
  }
184
209
 
@@ -320,6 +320,25 @@ export async function getCodexSessions(workspacePath: string): Promise<SessionIn
320
320
  }
321
321
  }
322
322
 
323
+ export async function archiveCodexThread(
324
+ client: Pick<CodexClient, 'rpc'>,
325
+ threadId: string
326
+ ): Promise<void> {
327
+ await client.rpc('thread/archive', { threadId })
328
+ }
329
+
330
+ export async function interruptCodexTurn(
331
+ client: Pick<CodexClient, 'rpc'>,
332
+ threadId: string,
333
+ turnId: string
334
+ ): Promise<void> {
335
+ await client.rpc('turn/interrupt', { threadId, turnId })
336
+ }
337
+
338
+ export async function archiveCodexSession(workspacePath: string, threadId: string): Promise<void> {
339
+ await archiveCodexThread(await getCodexClient(workspacePath), threadId)
340
+ }
341
+
323
342
  // Home-page card preview. Peek-only: with no live app-server the card simply
324
343
  // omits the activity fields until the workspace is opened once.
325
344
  export async function getCodexWorkspacePreview(
@@ -340,21 +359,49 @@ export async function getCodexWorkspacePreview(
340
359
  }
341
360
 
342
361
  // Account-wide model catalog (identical for every workspace); cached like the
343
- // Claude list in agent.ts, cleared on failure so a later call can retry.
344
- let codexModelsPromise: Promise<Model[]> | null = null
345
-
346
- export function getCodexModels(workspacePath: string): Promise<Model[]> {
347
- if (!codexModelsPromise) {
348
- codexModelsPromise = (async () => {
362
+ // Claude list in agent.ts, cleared on failure so a later call can retry. Keep
363
+ // the raw rows so internal helpers can read isDefault and effort ordering.
364
+ // The effective service tier is cwd-scoped and applied after reading the cache.
365
+ let codexModelCatalogPromise: Promise<CodexModel[]> | null = null
366
+
367
+ export function getCodexModelCatalog(workspacePath: string): Promise<CodexModel[]> {
368
+ if (!codexModelCatalogPromise) {
369
+ codexModelCatalogPromise = (async () => {
349
370
  const client = await getCodexClient(workspacePath)
350
371
  const res = await client.rpc<{ data?: CodexModel[] }>('model/list', {})
351
- return (res.data ?? []).filter(m => !m.hidden).map(codexModelToModel)
372
+ return (res.data ?? []).filter(model => !model.hidden)
352
373
  })().catch(err => {
353
- codexModelsPromise = null
374
+ codexModelCatalogPromise = null
354
375
  throw err
355
376
  })
356
377
  }
357
- return codexModelsPromise
378
+ return codexModelCatalogPromise
379
+ }
380
+
381
+ async function getCodexConfiguredServiceTier(
382
+ workspacePath: string
383
+ ): Promise<string | null | undefined> {
384
+ try {
385
+ const client = await getCodexClient(workspacePath)
386
+ const res = await client.rpc<{ config?: { service_tier?: string | null } }>('config/read', {
387
+ cwd: workspacePath,
388
+ includeLayers: false
389
+ })
390
+ return res.config?.service_tier
391
+ } catch (err) {
392
+ debug(
393
+ `codex config/read failed cwd=${workspacePath}: ${err instanceof Error ? err.message : String(err)}`
394
+ )
395
+ return undefined
396
+ }
397
+ }
398
+
399
+ export async function getCodexModels(workspacePath: string): Promise<Model[]> {
400
+ const [models, configuredServiceTier] = await Promise.all([
401
+ getCodexModelCatalog(workspacePath),
402
+ getCodexConfiguredServiceTier(workspacePath)
403
+ ])
404
+ return models.map(model => codexModelToModel(model, configuredServiceTier))
358
405
  }
359
406
 
360
407
  // MCP servers as Codex sees them (from ~/.codex/config.toml), for the
@@ -3,6 +3,7 @@
3
3
  import type { Harness } from '../types'
4
4
  import { findHarnessExecutable, pathHarnessAvailability } from '../executable'
5
5
  import {
6
+ archiveCodexSession,
6
7
  getCodexMcpStatus,
7
8
  getCodexModels,
8
9
  getCodexProcessInfo,
@@ -33,6 +34,7 @@ export const codexHarness: Harness = {
33
34
 
34
35
  sendMessage: input => sendCodexMessage(input),
35
36
  interrupt: (workspaceId, sessionId) => interruptCodexRun({ workspaceId, sessionId }),
37
+ archiveSession: (ws, sessionId) => archiveCodexSession(ws.path, sessionId),
36
38
  activeSessions: () => getCodexActiveSessions(),
37
39
 
38
40
  listSessions: ws => getCodexSessions(ws.path),
@@ -0,0 +1,149 @@
1
+ import { join } from 'node:path'
2
+
3
+ import type { CodexThread } from './adapter'
4
+ import type { CodexClient } from './client'
5
+
6
+ import {
7
+ SESSION_TITLE_SCHEMA,
8
+ SESSION_TITLE_SYSTEM_PROMPT,
9
+ SESSION_TITLE_TIMEOUT_MS,
10
+ createSessionTitleTempDir,
11
+ parseGeneratedSessionTitleJson,
12
+ removeSessionTitleTempDir,
13
+ runSessionTitleCommand
14
+ } from '../session-title'
15
+ import { requireHarnessExecutable } from '../executable'
16
+
17
+ const CODEX_SESSION_TITLE_MODEL = 'gpt-5.6-luna'
18
+
19
+ function codexSessionTitleEnv(): Record<string, string | undefined> {
20
+ return Object.fromEntries(
21
+ Object.entries(process.env).filter(
22
+ ([key]) => !key.startsWith('CODEX_') || key === 'CODEX_HOME' || key === 'CODEX_API_KEY'
23
+ )
24
+ )
25
+ }
26
+
27
+ export function parseCodexFeatureNames(value: string): string[] {
28
+ return value
29
+ .split('\n')
30
+ .map(line => line.trim().split(/\s+/u)[0])
31
+ .filter((name): name is string => Boolean(name?.match(/^[a-z][a-z0-9_]*$/u)))
32
+ }
33
+
34
+ export function codexSessionTitleCommand(input: {
35
+ executable: string
36
+ cwd: string
37
+ schemaPath: string
38
+ outputPath: string
39
+ features: readonly string[]
40
+ }): string[] {
41
+ const disabledFeatures = input.features.flatMap(feature => ['--disable', feature])
42
+ const config = [
43
+ `developer_instructions=${JSON.stringify(SESSION_TITLE_SYSTEM_PROMPT)}`,
44
+ 'model_reasoning_effort="low"',
45
+ 'model_reasoning_summary="none"',
46
+ 'web_search="disabled"',
47
+ 'tools.experimental_request_user_input.enabled=false',
48
+ 'include_permissions_instructions=false',
49
+ 'include_apps_instructions=false',
50
+ 'include_collaboration_mode_instructions=false',
51
+ 'include_environment_context=false',
52
+ 'project_doc_max_bytes=0',
53
+ 'project_doc_fallback_filenames=[]',
54
+ 'skills.include_instructions=false',
55
+ 'skills.bundled.enabled=false',
56
+ 'orchestrator.skills.enabled=false',
57
+ 'orchestrator.mcp.enabled=false',
58
+ 'notify=[]'
59
+ ].flatMap(value => ['-c', value])
60
+
61
+ return [
62
+ input.executable,
63
+ 'exec',
64
+ '--model',
65
+ CODEX_SESSION_TITLE_MODEL,
66
+ '--ephemeral',
67
+ '--ignore-user-config',
68
+ '--ignore-rules',
69
+ '--strict-config',
70
+ '--skip-git-repo-check',
71
+ '--sandbox',
72
+ 'read-only',
73
+ '--cd',
74
+ input.cwd,
75
+ '--output-schema',
76
+ input.schemaPath,
77
+ '--output-last-message',
78
+ input.outputPath,
79
+ '--color',
80
+ 'never',
81
+ ...disabledFeatures,
82
+ ...config,
83
+ '-'
84
+ ]
85
+ }
86
+
87
+ export async function generateCodexSessionTitle(input: {
88
+ source: string
89
+ abortController: AbortController
90
+ timeoutMs?: number
91
+ }): Promise<string | null> {
92
+ if (!input.source || input.abortController.signal.aborted) return null
93
+ const timer = setTimeout(
94
+ () => input.abortController.abort(),
95
+ input.timeoutMs ?? SESSION_TITLE_TIMEOUT_MS
96
+ )
97
+ let tempDir: string | undefined
98
+ try {
99
+ tempDir = await createSessionTitleTempDir()
100
+ const executable = requireHarnessExecutable('codex')
101
+ const env = codexSessionTitleEnv()
102
+ const featureOutput = await runSessionTitleCommand({
103
+ command: [executable, 'features', 'list'],
104
+ cwd: tempDir,
105
+ signal: input.abortController.signal,
106
+ env
107
+ })
108
+ const features = featureOutput ? parseCodexFeatureNames(featureOutput) : []
109
+ if (features.length === 0) return null
110
+
111
+ const schemaPath = join(tempDir, 'schema.json')
112
+ const outputPath = join(tempDir, 'result.json')
113
+ await Bun.write(schemaPath, JSON.stringify(SESSION_TITLE_SCHEMA))
114
+ const output = await runSessionTitleCommand({
115
+ command: codexSessionTitleCommand({
116
+ executable,
117
+ cwd: tempDir,
118
+ schemaPath,
119
+ outputPath,
120
+ features
121
+ }),
122
+ cwd: tempDir,
123
+ stdin: JSON.stringify({ sessionTitleSource: input.source }),
124
+ signal: input.abortController.signal,
125
+ env
126
+ })
127
+ if (output === null) return null
128
+ return parseGeneratedSessionTitleJson(await Bun.file(outputPath).text())
129
+ } finally {
130
+ clearTimeout(timer)
131
+ if (tempDir) await removeSessionTitleTempDir(tempDir).catch(() => {})
132
+ }
133
+ }
134
+
135
+ export async function renameCodexSessionIfUnchanged(input: {
136
+ client: Pick<CodexClient, 'rpc'>
137
+ threadId: string
138
+ title: string
139
+ isCurrent: () => boolean
140
+ }): Promise<boolean> {
141
+ if (!input.isCurrent()) return false
142
+ const response = await input.client.rpc<{ thread?: CodexThread }>('thread/read', {
143
+ threadId: input.threadId,
144
+ includeTurns: false
145
+ })
146
+ if (!response.thread || response.thread.name?.trim() || !input.isCurrent()) return false
147
+ await input.client.rpc('thread/name/set', { threadId: input.threadId, name: input.title })
148
+ return true
149
+ }