moi-computer 0.5.2-next.1 → 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 (75) 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/components/shared/Composer.tsx +3 -6
  6. package/client/components/shared/IconGhost.tsx +130 -0
  7. package/client/components/ui/dropdown-menu.tsx +1 -1
  8. package/client/components/ui/spinner.tsx +18 -0
  9. package/client/components/ui/toast.tsx +220 -0
  10. package/client/features/chat/ChatComposer.tsx +3 -2
  11. package/client/features/chat/ChatPanel.tsx +7 -6
  12. package/client/features/chat/ChatPopup.tsx +10 -4
  13. package/client/features/chat/ChatSelector.tsx +263 -48
  14. package/client/features/chat/ModelPicker.tsx +13 -18
  15. package/client/features/chat/api.ts +36 -9
  16. package/client/features/chat/chat-frames.ts +35 -6
  17. package/client/features/chat/chat-send.ts +25 -1
  18. package/client/features/chat/chat-store.ts +43 -18
  19. package/client/features/chat/useChat.ts +54 -52
  20. package/client/features/chat/useSelectedSession.ts +151 -0
  21. package/client/features/chat/useStickToBottom.ts +3 -3
  22. package/client/features/home/api.ts +0 -2
  23. package/client/features/scratchpad/ScratchpadControls.tsx +2 -2
  24. package/client/features/settings/WorkspaceSettings.tsx +6 -6
  25. package/client/features/views/ViewBuilderTab.tsx +3 -4
  26. package/client/features/views/useViewBuilderActions.ts +3 -1
  27. package/client/features/workspace/WorkspaceScreen.tsx +38 -18
  28. package/client/features/workspace/WorkspaceTabs.tsx +10 -1
  29. package/client/main.tsx +2 -0
  30. package/client/runtime/useWorkspaceEvents.ts +1 -0
  31. package/client/store/ui.ts +2 -2
  32. package/dist/{chunk-zs4mte79.js → chunk-0pcdwjkp.js} +1 -1
  33. package/dist/chunk-55sh4dty.js +2 -0
  34. package/dist/{chunk-tzz101ea.js → chunk-9y2zbzqz.js} +1 -1
  35. package/dist/{chunk-jvhvme3z.js → chunk-afgbg75t.js} +1 -1
  36. package/dist/chunk-agtetn7n.css +1 -0
  37. package/dist/chunk-bv6vrvqf.js +27 -0
  38. package/dist/chunk-dfs36zgc.js +1 -0
  39. package/dist/chunk-exj6hr30.js +9 -0
  40. package/dist/{chunk-bcrkdhwe.js → chunk-m11ckkxd.js} +1 -1
  41. package/dist/{chunk-xwhya7kb.js → chunk-n6t40enm.js} +1 -1
  42. package/dist/{chunk-kfw1qwqe.js → chunk-rxvx4ta9.js} +3 -3
  43. package/dist/index.html +1 -1
  44. package/lib/attachment-note.ts +18 -0
  45. package/lib/chat-title.ts +6 -0
  46. package/lib/types.ts +24 -10
  47. package/package.json +1 -1
  48. package/server/api.ts +90 -9
  49. package/server/app-settings.ts +1 -1
  50. package/server/data-dir.ts +1 -1
  51. package/server/harness/README.md +6 -0
  52. package/server/harness/claude-code/adapter.ts +2 -2
  53. package/server/harness/claude-code/index.ts +7 -1
  54. package/server/harness/claude-code/session-title.ts +106 -0
  55. package/server/harness/claude-code/session.ts +87 -13
  56. package/server/harness/claude-code/sessions.ts +35 -4
  57. package/server/harness/codex/client.ts +30 -12
  58. package/server/harness/codex/index.ts +2 -0
  59. package/server/harness/codex/session-title.ts +149 -0
  60. package/server/harness/codex/session.ts +84 -11
  61. package/server/harness/openclaw/adapter.ts +4 -2
  62. package/server/harness/openclaw/discovery.ts +2 -0
  63. package/server/harness/openclaw/session.ts +15 -7
  64. package/server/harness/session-title.ts +96 -0
  65. package/server/harness/types.ts +2 -0
  66. package/server/selected-session.ts +132 -0
  67. package/server/{thread-config.ts → session-config.ts} +57 -39
  68. package/server/web.ts +12 -1
  69. package/workspace/.claude/skills/moi-workspace/DESIGN.md +16 -26
  70. package/workspace/.claude/skills/moi-workspace/SKILL.md +8 -2
  71. package/dist/chunk-94m3q9ce.js +0 -1
  72. package/dist/chunk-k9dcnd73.js +0 -27
  73. package/dist/chunk-pk11vfzs.js +0 -9
  74. package/dist/chunk-r2bqaege.js +0 -2
  75. package/dist/chunk-y4g8j7mv.css +0 -1
@@ -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
@@ -166,6 +170,9 @@ type LiveSession = {
166
170
  createdAt: number
167
171
  lastActivityAt: number
168
172
  lastUserText: string | undefined
173
+ refreshSessionsOnResult: boolean
174
+ sessionTitleSource: string | undefined
175
+ sessionTitleAbort: AbortController | null
169
176
  }
170
177
 
171
178
  const sessions = new Map<string, LiveSession>()
@@ -333,6 +340,8 @@ function teardown(s: LiveSession) {
333
340
  setActivity(s, 'idle')
334
341
  s.closed = true
335
342
  clearIdle(s)
343
+ s.sessionTitleAbort?.abort()
344
+ s.sessionTitleAbort = null
336
345
  s.input.close()
337
346
  try {
338
347
  s.q.close?.()
@@ -345,17 +354,59 @@ function teardown(s: LiveSession) {
345
354
  }
346
355
  }
347
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
+
348
399
  // On `system/init` the SDK reports the real session id. For a brand-new session
349
400
  // that differs from the client's temporary id, so we rekey the registry and
350
401
  // tell the client to move its optimistic state. Subsequent inits report the
351
402
  // same id and no-op.
352
- function renameSession(s: LiveSession, realId: string) {
403
+ function renameSession(s: LiveSession, realId: string): string {
353
404
  const from = s.sessionId
354
405
  sessions.delete(recKey(s.workspaceId, from))
355
406
  s.sessionId = realId
356
407
  sessions.set(recKey(s.workspaceId, realId), s)
357
408
  aliases.set(recKey(s.workspaceId, from), realId)
358
- broadcast(s.workspaceId, { type: 'session_renamed', from, to: realId })
409
+ return from
359
410
  }
360
411
 
361
412
  // The session just went idle (state event, or `result` on a CLI without state
@@ -380,21 +431,27 @@ async function consume(s: LiveSession) {
380
431
  if (msg.type === 'system' && msg.subtype === 'init') {
381
432
  const realId = msg.session_id
382
433
  if (realId && realId !== s.sessionId) {
383
- const from = s.sessionId
384
- renameSession(s, realId)
434
+ const from = renameSession(s, realId)
385
435
  // Carry any config the picker wrote under the temp id to the real id.
386
- await renameThreadConfig(s.workspacePath, from, s.sessionId)
436
+ await renameSessionConfig(s.workspacePath, from, s.sessionId)
437
+ await renameSelectedSession(s.workspacePath, from, s.sessionId)
387
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
+ })
388
444
  }
389
- // 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
390
447
  // it has none yet, so an explicit user PUT (or a migrated temp-id edit)
391
448
  // always wins. A default run leaves no file and falls back to the
392
449
  // workspace defaults.
393
450
  if (
394
451
  (s.model || s.effort || s.fastMode !== undefined) &&
395
- !(await hasThreadConfig(s.workspacePath, s.sessionId))
452
+ !(await hasSessionConfig(s.workspacePath, s.sessionId))
396
453
  ) {
397
- await saveThreadConfig(s.workspacePath, s.sessionId, {
454
+ await saveSessionConfig(s.workspacePath, s.sessionId, {
398
455
  model: s.model,
399
456
  effort: s.effort,
400
457
  fastMode: s.fastMode
@@ -475,6 +532,10 @@ async function consume(s: LiveSession) {
475
532
  ? undefined
476
533
  : msg.errors.join('\n') || msg.subtype.replaceAll('_', ' ')
477
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
+ }
478
539
  // Fallback for CLIs that never emit `session_state_changed`: treat
479
540
  // every result as turn-over. With state events, `idle` follows the
480
541
  // result and drives the same path.
@@ -530,6 +591,7 @@ function createLiveSession(input: {
530
591
  // Resolved workspace env (.env + UI custom overrides), injected so the agent's
531
592
  // Bash tool can use workspace secrets. Frozen at spawn — see restartWorkspaceSessions.
532
593
  workspaceEnv: Record<string, string>
594
+ sessionTitleSource: string | undefined
533
595
  }): LiveSession {
534
596
  evictIfNeeded()
535
597
 
@@ -570,6 +632,7 @@ function createLiveSession(input: {
570
632
  const session: LiveSession = {
571
633
  workspaceId: input.workspaceId,
572
634
  workspacePath: input.workspacePath,
635
+ workspaceEnv: input.workspaceEnv,
573
636
  sessionId: input.sessionId,
574
637
  q: query({ prompt: queue.iterator, options }),
575
638
  adapter: new ClaudeAdapter(),
@@ -589,7 +652,10 @@ function createLiveSession(input: {
589
652
  lastBuilderError: undefined,
590
653
  createdAt: Date.now(),
591
654
  lastActivityAt: Date.now(),
592
- lastUserText: undefined
655
+ lastUserText: undefined,
656
+ refreshSessionsOnResult: input.isNew,
657
+ sessionTitleSource: input.sessionTitleSource,
658
+ sessionTitleAbort: null
593
659
  }
594
660
  sessions.set(recKey(session.workspaceId, session.sessionId), session)
595
661
  debug(
@@ -625,6 +691,12 @@ export async function sendCCMessage(input: {
625
691
  ? resolveUploads(input.workspaceId, input.attachments)
626
692
  : []
627
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
628
700
  const { content: userContent, parts } = buildUserMessage(input.content, uploads)
629
701
  // The envelope goes in as its OWN leading text block, never merged into the
630
702
  // user's string: the SDK's first-prompt extraction (session titles,
@@ -695,6 +767,7 @@ export async function sendCCMessage(input: {
695
767
  effort: input.effort,
696
768
  fastMode: input.fastMode,
697
769
  stream: wantStream,
770
+ sessionTitleSource,
698
771
  // The agent only sees secrets scoped to the 'agent' sink (plus .env).
699
772
  workspaceEnv: await resolveWorkspaceEnv(input.workspacePath)
700
773
  })
@@ -771,6 +844,7 @@ export async function interruptCCSession(workspaceId: string, sessionId: string)
771
844
  }
772
845
  } catch (err) {
773
846
  console.error('[cc-session] interrupt failed', err)
847
+ teardown(s)
774
848
  } finally {
775
849
  clearTimeout(timer)
776
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 —
@@ -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(
@@ -341,21 +360,22 @@ export async function getCodexWorkspacePreview(
341
360
 
342
361
  // Account-wide model catalog (identical for every workspace); cached like the
343
362
  // Claude list in agent.ts, cleared on failure so a later call can retry. Keep
344
- // the raw catalog cached because the effective service tier is cwd-scoped.
345
- let codexModelsPromise: Promise<CodexModel[]> | null = null
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
346
366
 
347
- function getCachedCodexModels(workspacePath: string): Promise<CodexModel[]> {
348
- if (!codexModelsPromise) {
349
- codexModelsPromise = (async () => {
367
+ export function getCodexModelCatalog(workspacePath: string): Promise<CodexModel[]> {
368
+ if (!codexModelCatalogPromise) {
369
+ codexModelCatalogPromise = (async () => {
350
370
  const client = await getCodexClient(workspacePath)
351
371
  const res = await client.rpc<{ data?: CodexModel[] }>('model/list', {})
352
- return res.data ?? []
372
+ return (res.data ?? []).filter(model => !model.hidden)
353
373
  })().catch(err => {
354
- codexModelsPromise = null
374
+ codexModelCatalogPromise = null
355
375
  throw err
356
376
  })
357
377
  }
358
- return codexModelsPromise
378
+ return codexModelCatalogPromise
359
379
  }
360
380
 
361
381
  async function getCodexConfiguredServiceTier(
@@ -378,12 +398,10 @@ async function getCodexConfiguredServiceTier(
378
398
 
379
399
  export async function getCodexModels(workspacePath: string): Promise<Model[]> {
380
400
  const [models, configuredServiceTier] = await Promise.all([
381
- getCachedCodexModels(workspacePath),
401
+ getCodexModelCatalog(workspacePath),
382
402
  getCodexConfiguredServiceTier(workspacePath)
383
403
  ])
384
- return models
385
- .filter(model => !model.hidden)
386
- .map(model => codexModelToModel(model, configuredServiceTier))
404
+ return models.map(model => codexModelToModel(model, configuredServiceTier))
387
405
  }
388
406
 
389
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
+ }