@myrialabs/clopen 0.4.27 → 0.4.29

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 (47) hide show
  1. package/backend/auth/auth-service.ts +45 -25
  2. package/backend/auth/onboarding.test.ts +106 -0
  3. package/backend/auth/permissions.ts +1 -1
  4. package/backend/database/utils/connection.ts +7 -31
  5. package/backend/engine/README.md +8 -3
  6. package/backend/engine/adapters/claude/message-converter.ts +55 -23
  7. package/backend/engine/adapters/codex/message-converter.ts +8 -2
  8. package/backend/engine/adapters/codex/models.ts +85 -98
  9. package/backend/engine/adapters/codex/stream.ts +5 -7
  10. package/backend/engine/adapters/codex/usage-rollout.ts +7 -0
  11. package/backend/engine/adapters/copilot/stream.ts +24 -0
  12. package/backend/engine/docs/lessons-learned.md +78 -1
  13. package/backend/engine/docs/stack.md +8 -0
  14. package/backend/engine/install-recipes.ts +19 -2
  15. package/backend/files/file-size-limit.ts +5 -14
  16. package/backend/files/file-watcher.test.ts +160 -0
  17. package/backend/files/file-watcher.ts +276 -58
  18. package/backend/git/git-executor.ts +8 -0
  19. package/backend/git/git-service.test.ts +136 -0
  20. package/backend/git/git-service.ts +113 -17
  21. package/backend/index.ts +11 -4
  22. package/backend/mcp/internal/remote-server.test.ts +8 -3
  23. package/backend/mcp/internal/remote-server.ts +1 -1
  24. package/backend/settings/system-settings.ts +97 -0
  25. package/backend/tunnel/public-origin.ts +5 -13
  26. package/backend/utils/env.ts +29 -0
  27. package/backend/utils/paths.ts +9 -3
  28. package/backend/ws/auth/login.test.ts +8 -1
  29. package/backend/ws/auth/login.ts +22 -15
  30. package/backend/ws/auth/status.ts +24 -1
  31. package/backend/ws/chat/stream.ts +1 -0
  32. package/backend/ws/engine/claude/accounts.ts +4 -12
  33. package/backend/ws/engine/codex/accounts.ts +4 -13
  34. package/backend/ws/engine/pty-output.test.ts +37 -0
  35. package/backend/ws/engine/pty-output.ts +43 -0
  36. package/backend/ws/files/watch.ts +9 -0
  37. package/backend/ws/settings/crud.ts +14 -22
  38. package/dist/assets/{index-BTGcf_Vy.js → index-C7e5TWG3.js} +1 -1
  39. package/dist/assets/{index-BCv5HlPk.js → index-Derlqeyy.js} +1 -1
  40. package/dist/assets/{main-BrqMMMRX.css → main-CqzaPnux.css} +1 -1
  41. package/dist/assets/main-OGhsRKU1.js +1037 -0
  42. package/dist/index.html +2 -2
  43. package/package.json +14 -14
  44. package/shared/constants/engines.ts +1 -0
  45. package/shared/types/stores/settings.ts +11 -1
  46. package/shared/types/unified/stream.ts +10 -4
  47. package/dist/assets/main-CgmAFpU3.js +0 -1036
@@ -4,7 +4,8 @@
4
4
  * Core authentication logic: user creation, session management, invite handling.
5
5
  */
6
6
 
7
- import { authQueries, projectQueries, settingsQueries } from '$backend/database/queries';
7
+ import { authQueries, projectQueries } from '$backend/database/queries';
8
+ import { readSystemSettings, writeSystemSettings } from '$backend/settings/system-settings';
8
9
  import type { Project } from '$shared/types/database/schema';
9
10
  import { generateSessionToken, generatePAT, generateInviteToken, generateDeviceCode, hashToken, getTokenType } from './tokens';
10
11
  import { generateColorFromString, getInitials } from '$backend/utils/user-helpers';
@@ -85,38 +86,57 @@ export function needsSetup(): boolean {
85
86
  }
86
87
 
87
88
  /**
88
- * Get parsed system settings from DB (cached per call).
89
+ * Onboarding (setup wizard) state.
90
+ *
91
+ * `pending` is only ever reported when we positively know the wizard is
92
+ * unfinished — a fresh install, or a run that recorded the marker and has not
93
+ * completed yet. Everything else resolves to `complete`, because sending a
94
+ * working instance back through the wizard is destructive: it re-asks for the
95
+ * auth mode and lets the user overwrite live settings.
96
+ *
97
+ * `getOnboardingState()` deliberately does NOT catch read failures. A database
98
+ * error must surface to the caller instead of being reported as "never
99
+ * onboarded" — that silent downgrade is what used to drop users into the wizard
100
+ * at random.
89
101
  */
90
- function getSystemSettingsParsed(): Record<string, unknown> {
91
- try {
92
- const setting = settingsQueries.get('system:settings');
93
- if (setting?.value) {
94
- return typeof setting.value === 'string' ? JSON.parse(setting.value) : setting.value;
95
- }
96
- } catch {
97
- // Settings may not exist yet
102
+ export type OnboardingState = 'pending' | 'complete';
103
+
104
+ export function getOnboardingState(): OnboardingState {
105
+ const stored = readSystemSettings();
106
+
107
+ // `onboarding` is the current marker; `onboardingComplete` is the legacy
108
+ // boolean, still read (and written) so a downgrade keeps working.
109
+ if (stored.onboarding === 'complete' || stored.onboardingComplete === true) return 'complete';
110
+ if (stored.onboarding === 'pending') return 'pending';
111
+
112
+ // No marker at all. An install that already has users has, by definition,
113
+ // been through setup — the wizard is what created them. Record that so a
114
+ // single missing key can never flap the whole instance back to setup.
115
+ if (!needsSetup()) {
116
+ markOnboardingComplete();
117
+ debug.log('auth', 'Onboarding marker missing but users exist — recorded as complete');
118
+ return 'complete';
98
119
  }
99
- return {};
120
+
121
+ return 'pending';
100
122
  }
101
123
 
102
- /**
103
- * Get the current auth mode from system settings.
104
- * Returns 'required' by default (before setup is complete).
105
- */
106
- export function getAuthMode(): 'none' | 'required' {
107
- const parsed = getSystemSettingsParsed();
108
- if (parsed.authMode === 'none' || parsed.authMode === 'required') {
109
- return parsed.authMode as 'none' | 'required';
110
- }
111
- return 'required';
124
+ /** True when the setup wizard has been completed. */
125
+ export function isOnboardingComplete(): boolean {
126
+ return getOnboardingState() === 'complete';
112
127
  }
113
128
 
114
129
  /**
115
- * Check if the initial onboarding wizard has been completed.
130
+ * Record that a fresh install has entered the wizard, so a refresh mid-setup
131
+ * resumes it instead of being mistaken for a completed install.
116
132
  */
117
- export function isOnboardingComplete(): boolean {
118
- const parsed = getSystemSettingsParsed();
119
- return parsed.onboardingComplete === true;
133
+ export function markOnboardingPending(): void {
134
+ writeSystemSettings({ onboarding: 'pending', onboardingComplete: false });
135
+ }
136
+
137
+ /** Record that the wizard finished. Writes both the current and legacy markers. */
138
+ export function markOnboardingComplete(): void {
139
+ writeSystemSettings({ onboarding: 'complete', onboardingComplete: true });
120
140
  }
121
141
 
122
142
  /**
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Regression tests for the setup-wizard gate.
3
+ *
4
+ * These lock in the two properties that stopped a working install from being
5
+ * sent back through onboarding (and having its settings reset by the wizard):
6
+ * the data directory is isolated while testing, and a missing onboarding marker
7
+ * on an install that already has users resolves to "complete" instead of
8
+ * "never onboarded".
9
+ */
10
+
11
+ import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
12
+ import { randomUUID } from 'node:crypto';
13
+
14
+ import { getOnboardingState, markOnboardingComplete } from './auth-service';
15
+ import { readSystemSettings, writeSystemSettings, SYSTEM_SETTINGS_KEY } from '../settings/system-settings';
16
+ import { getClopenDir } from '../utils/paths';
17
+ import { authQueries, settingsQueries } from '../database/queries';
18
+ import { initializeDatabase, closeDatabase } from '../database';
19
+
20
+ let testUserId: string;
21
+ let originalSettings: string | null = null;
22
+
23
+ beforeAll(async () => {
24
+ await initializeDatabase();
25
+ originalSettings = settingsQueries.get(SYSTEM_SETTINGS_KEY)?.value ?? null;
26
+
27
+ // The self-heal path is only correct for an install that has users, so make
28
+ // sure one exists regardless of what else ran before this file.
29
+ testUserId = `user-${randomUUID()}`;
30
+ authQueries.createUser({
31
+ id: testUserId,
32
+ name: 'Onboarding Test User',
33
+ color: '#000000',
34
+ avatar: 'OT',
35
+ role: 'admin',
36
+ personal_access_token_hash: `hash-${randomUUID()}`,
37
+ created_at: new Date().toISOString()
38
+ });
39
+ });
40
+
41
+ afterAll(() => {
42
+ authQueries.deleteUser(testUserId);
43
+ if (originalSettings === null) {
44
+ settingsQueries.delete(SYSTEM_SETTINGS_KEY);
45
+ } else {
46
+ settingsQueries.set(SYSTEM_SETTINGS_KEY, originalSettings);
47
+ }
48
+ closeDatabase();
49
+ });
50
+
51
+ describe('data directory isolation', () => {
52
+ test('tests never resolve to the production data directory', () => {
53
+ // The whole class of bug this file guards against started here: the test
54
+ // runner sets NODE_ENV=test, which used to fall through to ~/.clopen and
55
+ // let the suite rewrite live rows in the developer's own install.
56
+ const dir = getClopenDir();
57
+ expect(dir).toContain('.clopen-test');
58
+ expect(dir.endsWith('/.clopen')).toBe(false);
59
+ });
60
+ });
61
+
62
+ describe('system settings writes', () => {
63
+ test('merge into the stored blob instead of replacing it', () => {
64
+ writeSystemSettings({ onboarding: 'complete', maxFileSizeMB: 123 });
65
+ writeSystemSettings({ authMode: 'required' });
66
+
67
+ const stored = readSystemSettings();
68
+ expect(stored.authMode).toBe('required');
69
+ expect(stored.maxFileSizeMB).toBe(123);
70
+ // The sibling that used to disappear.
71
+ expect(stored.onboarding).toBe('complete');
72
+ });
73
+ });
74
+
75
+ describe('onboarding state', () => {
76
+ test('is complete once the marker is recorded', () => {
77
+ markOnboardingComplete();
78
+ expect(getOnboardingState()).toBe('complete');
79
+ });
80
+
81
+ test('respects an explicitly pending wizard so a refresh resumes setup', () => {
82
+ writeSystemSettings({ onboarding: 'pending', onboardingComplete: false });
83
+ expect(getOnboardingState()).toBe('pending');
84
+ });
85
+
86
+ test('still honours the legacy onboardingComplete boolean', () => {
87
+ settingsQueries.set(SYSTEM_SETTINGS_KEY, JSON.stringify({ onboardingComplete: true }));
88
+ expect(getOnboardingState()).toBe('complete');
89
+ });
90
+
91
+ test('self-heals when the marker is missing but users exist', () => {
92
+ // Exactly the state a stray full-blob write leaves behind.
93
+ settingsQueries.set(SYSTEM_SETTINGS_KEY, JSON.stringify({ authMode: 'required' }));
94
+
95
+ expect(getOnboardingState()).toBe('complete');
96
+ // And it is persisted, so the next read cannot flap back to the wizard.
97
+ expect(readSystemSettings().onboarding).toBe('complete');
98
+ });
99
+
100
+ test('self-heals when the whole settings row is gone', () => {
101
+ settingsQueries.delete(SYSTEM_SETTINGS_KEY);
102
+
103
+ expect(getOnboardingState()).toBe('complete');
104
+ expect(readSystemSettings().onboarding).toBe('complete');
105
+ });
106
+ });
@@ -5,7 +5,7 @@
5
5
  * Used by the auth gate in WSRouter.handleMessage().
6
6
  */
7
7
 
8
- import { getAuthMode } from './auth-service';
8
+ import { getAuthMode } from '$backend/settings/system-settings';
9
9
 
10
10
  /** Routes that can be accessed WITHOUT authentication */
11
11
  export const PUBLIC_ROUTES = new Set([
@@ -1,4 +1,5 @@
1
1
  import { join } from 'path';
2
+ import { mkdirSync } from 'fs';
2
3
  import { Database } from 'bun:sqlite';
3
4
  import type { DatabaseConnection } from '$shared/types/database/connection';
4
5
 
@@ -29,37 +30,12 @@ export class DatabaseManager {
29
30
  debug.log('database', '🔗 Connecting to database...');
30
31
 
31
32
  try {
32
- // Create clopen directory if it doesn't exist
33
- const clopenDir = getClopenDir();
34
- const dirFile = Bun.file(clopenDir);
35
-
36
- // Check if directory exists, if not create it
37
- try {
38
- await dirFile.stat();
39
- } catch {
40
- // Directory doesn't exist, create using Bun.write workaround
41
- const tempFile = join(clopenDir, '.init');
42
- await Bun.write(tempFile, '');
43
- // Remove the temp file
44
- try {
45
- const tempFileHandle = Bun.file(tempFile);
46
- if (await tempFileHandle.exists()) {
47
- if (process.platform === 'win32') {
48
- await Bun.spawn(['cmd', '/c', 'del', '/f', '/q', tempFile.replace(/\//g, '\\')], {
49
- stdout: 'ignore',
50
- stderr: 'ignore'
51
- }).exited;
52
- } else {
53
- await Bun.spawn(['rm', '-f', tempFile], {
54
- stdout: 'ignore',
55
- stderr: 'ignore'
56
- }).exited;
57
- }
58
- }
59
- } catch {
60
- // Ignore cleanup errors
61
- }
62
- }
33
+ // Ensure the data directory exists before SQLite touches the path.
34
+ // This has to be reliable: on a first run the directory is missing, and
35
+ // opening a database inside a missing directory fails in ways that
36
+ // surface much later as "no such table". `mkdirSync` is atomic, creates
37
+ // parents, and no-ops when the directory is already there.
38
+ mkdirSync(getClopenDir(), { recursive: true });
63
39
 
64
40
  // Use Bun's native SQLite exclusively
65
41
  this.db = new Database(this.dbPath);
@@ -23,8 +23,13 @@ stays **agnostic** to the underlying SDK.
23
23
  > `EngineNotReadyError` (`reason: 'not-installed' | 'needs-update'`) — the
24
24
  > engine must first be installed/updated in **Settings → Stack**. This is
25
25
  > what fixed `bun add -g @myrialabs/clopen` aborting mid-install (it used to
26
- > drag 200–300 MB of native CLI binaries). Future Stack work (runtimes,
27
- > services, per-project versioning) is specced in
26
+ > drag 200–300 MB of native CLI binaries). The pin covers an SDK's unbundled
27
+ > **peer** dependencies too (`ENGINE_PACKAGES` in
28
+ > [`install-recipes.ts`](./install-recipes.ts)) — without that they resolve at
29
+ > `@latest` in the stack dir and clopen runs a version it never type-checked
30
+ > against; read **§10.25** in [lessons-learned](./docs/lessons-learned.md)
31
+ > before bumping any SDK. Future Stack work (runtimes, services, per-project
32
+ > versioning) is specced in
28
33
  > [`docs/stack-roadmap.md`](../../docs/stack-roadmap.md).
29
34
 
30
35
  > **Adapters load on first use, and that rule is now mechanical.** The registry
@@ -85,7 +90,7 @@ map, then jump to the area you need.
85
90
  6. [Stack](./docs/stack.md) — registering a host tool or on-demand engine SDK in `install-recipes.ts` + the install runner.
86
91
  7. [Artifacts & Access](./docs/artifacts.md) — the extension layer (Skills, Commands, Subagents, Instructions, Permissions, Profiles, MCP), the capability matrix, and the `artifact-sync.ts` seam adapters call at stream start.
87
92
  8. [Adding a new engine](./docs/adding-an-engine.md) — the end-to-end, stage-by-stage checklist.
88
- 9. [Lessons learned](./docs/lessons-learned.md) — §10 pitfalls (tool name/input canonicalisation, fork session, MCP reuse, auth-blob swap, sub-agent routing, OpenCode v1/v2, structured output, cross-engine handoff, …).
93
+ 9. [Lessons learned](./docs/lessons-learned.md) — §10 pitfalls (tool name/input canonicalisation, fork session, MCP reuse, auth-blob swap, sub-agent routing, OpenCode v1/v2, structured output, cross-engine handoff, SDK upgrades, …).
89
94
  10. [Quick reference](./docs/quick-reference.md) — "I need X → look in file Y" table.
90
95
 
91
96
  ---
@@ -18,6 +18,8 @@ import type {
18
18
  SDKSystemMessage,
19
19
  SDKCompactBoundaryMessage,
20
20
  SDKRateLimitEvent,
21
+ SDKModelRefusalFallbackMessage,
22
+ SDKModelRefusalNoFallbackMessage,
21
23
  } from '@anthropic-ai/claude-agent-sdk';
22
24
  // Infer block/usage types from the agent SDK so we stay in sync with whichever
23
25
  // @anthropic-ai/sdk version claude-agent-sdk bundles internally.
@@ -395,27 +397,6 @@ export function convertSystemInit(msg: SDKSystemMessage): SystemInitEvent {
395
397
  };
396
398
  }
397
399
 
398
- /**
399
- * Convert SDKTaskNotificationMessage (terminal background-task event) →
400
- * NotificationEvent. Fires when a backgrounded Agent/teammate finishes
401
- * abnormally (failed | stopped). Successful completion is intentionally
402
- * not surfaced — the result already lands in the conversation, and a
403
- * success toast is just noise. The non-terminal task_started /
404
- * task_progress / task_updated messages are also not surfaced.
405
- */
406
- function convertTaskNotification(
407
- msg: { session_id: string; status: string; summary?: string; task_id: string },
408
- ): NotificationEvent | null {
409
- if (msg.status === 'completed') return null;
410
- return {
411
- type: 'notification',
412
- sessionId: msg.session_id,
413
- level: 'warning',
414
- title: `Background task ${msg.status}`,
415
- message: msg.summary || `Task ${msg.task_id} ${msg.status}`,
416
- };
417
- }
418
-
419
400
  function workflowActivityMessage(
420
401
  msg: { session_id: string; uuid?: string },
421
402
  parentToolUseId: string,
@@ -448,6 +429,50 @@ export function convertCompactBoundary(msg: SDKCompactBoundaryMessage): CompactB
448
429
  };
449
430
  }
450
431
 
432
+ /**
433
+ * Convert a model-refusal banner → NotificationEvent.
434
+ *
435
+ * Both subtypes arrived in @anthropic-ai/claude-agent-sdk 0.3.229 and were
436
+ * previously dropped by the `default` arm, which is the worst outcome for the
437
+ * two cases users actually notice: a turn answered by a *different* model than
438
+ * the one they picked, and a turn that produced nothing at all. Neither is an
439
+ * error the stream should abort on, so they surface as toasts.
440
+ *
441
+ * NOT handled: `retracted_message_uuids`, the fallback's list of already-
442
+ * delivered messages the CLI has retracted. Honouring it means deleting
443
+ * persisted messages by id across adapter → stream-manager → WS → UI, so the
444
+ * refused partial currently stays in the transcript above the fallback answer.
445
+ * See docs/lessons-learned.md §10.25.
446
+ */
447
+ function convertModelRefusalFallback(msg: SDKModelRefusalFallbackMessage): NotificationEvent {
448
+ // 'local' means only this response came from the fallback (a subagent or a
449
+ // side question); 'session' means the session's model itself was swapped.
450
+ const scope = msg.scope ?? 'session';
451
+ const swapped = scope === 'session'
452
+ ? `The session model is now ${msg.fallback_model}.`
453
+ : `Only this response came from ${msg.fallback_model}; the session model is unchanged.`;
454
+ return {
455
+ type: 'notification',
456
+ sessionId: msg.session_id,
457
+ level: 'warning',
458
+ title: 'Model refused — answered by a fallback',
459
+ message: `${msg.original_model} declined this request${msg.api_refusal_category ? ` (${msg.api_refusal_category})` : ''}. ${swapped}`,
460
+ };
461
+ }
462
+
463
+ /** Convert SDKModelRefusalNoFallbackMessage → NotificationEvent (no retry ran). */
464
+ function convertModelRefusalNoFallback(msg: SDKModelRefusalNoFallbackMessage): NotificationEvent {
465
+ return {
466
+ type: 'notification',
467
+ sessionId: msg.session_id,
468
+ level: 'error',
469
+ title: 'Model refused this request',
470
+ // `content` is the CLI's own human-readable banner; explanation is
471
+ // unstable prose meant for display only.
472
+ message: msg.api_refusal_explanation || msg.content,
473
+ };
474
+ }
475
+
451
476
  /** Convert SDKRateLimitEvent → RateLimitEvent (returns null for non-actionable 'allowed' status) */
452
477
  export function convertRateLimit(msg: SDKRateLimitEvent): RateLimitEvent | null {
453
478
  const info = msg.rate_limit_info;
@@ -530,6 +555,10 @@ function* dispatchSdkMessage(msg: SDKMessage, state: StreamConverterState): Gene
530
555
  yield convertSystemInit(msg as SDKSystemMessage);
531
556
  } else if (subtype === 'compact_boundary') {
532
557
  yield convertCompactBoundary(msg as SDKCompactBoundaryMessage);
558
+ } else if (subtype === 'model_refusal_fallback') {
559
+ yield convertModelRefusalFallback(msg as SDKModelRefusalFallbackMessage);
560
+ } else if (subtype === 'model_refusal_no_fallback') {
561
+ yield convertModelRefusalNoFallback(msg as SDKModelRefusalNoFallbackMessage);
533
562
  } else if (subtype === 'task_started') {
534
563
  const task = msg as unknown as { session_id: string; uuid?: string; task_id: string; tool_use_id?: string; task_type?: string; workflow_name?: string; description?: string };
535
564
  if (task.task_type === 'local_workflow' && task.tool_use_id) {
@@ -538,14 +567,17 @@ function* dispatchSdkMessage(msg: SDKMessage, state: StreamConverterState): Gene
538
567
  yield workflowActivityMessage(task, task.tool_use_id, detail);
539
568
  }
540
569
  } else if (subtype === 'task_notification') {
570
+ // Only workflow tasks surface anything, and only inline in the
571
+ // conversation. Backgrounded Agent/Bash tasks stay silent: their
572
+ // outcome already lands in the transcript, so a terminal toast
573
+ // ("Background task failed") is pure noise — a backgrounded
574
+ // `grep` with no match is a non-zero exit, not a problem.
541
575
  const task = msg as unknown as { session_id: string; uuid?: string; task_id: string; tool_use_id?: string; status: string; summary?: string };
542
576
  const parent = task.tool_use_id || state.workflowParents.get(task.task_id);
543
577
  if (parent && state.workflowParents.has(task.task_id)) {
544
578
  yield workflowActivityMessage(task, parent, `Workflow ${task.status}.`);
545
579
  state.workflowParents.delete(task.task_id);
546
580
  }
547
- const note = convertTaskNotification(task);
548
- if (note) yield note;
549
581
  }
550
582
  // task_progress is a repeated heartbeat; real child activity is replayed
551
583
  // from Workflow-owned transcripts. task_updated has no tool_use_id.
@@ -627,6 +627,11 @@ function buildErrorUserMessage(item: ErrorItem, state: CodexStreamState): UserMe
627
627
  * `cacheReadInputTokens`. Subtract here, otherwise the frontend's context
628
628
  * window indicator (which sums input + cacheCreate + cacheRead) would
629
629
  * double-count the cached prefix and appear to fill up far too quickly.
630
+ *
631
+ * `cache_write_input_tokens` (added in SDK 0.147) is the slice of that same
632
+ * prompt written INTO the cache this turn, so it is subtracted for the same
633
+ * reason and reported as `cacheCreationInputTokens`. The three parts still sum
634
+ * back to `input_tokens`, which is what the indicator expects.
630
635
  */
631
636
  function mapUsage(raw: Usage | null): TokenUsage {
632
637
  if (!raw) {
@@ -634,10 +639,11 @@ function mapUsage(raw: Usage | null): TokenUsage {
634
639
  }
635
640
  const totalInput = raw.input_tokens ?? 0;
636
641
  const cached = raw.cached_input_tokens ?? 0;
642
+ const cacheWrite = raw.cache_write_input_tokens ?? 0;
637
643
  return {
638
- inputTokens: Math.max(0, totalInput - cached),
644
+ inputTokens: Math.max(0, totalInput - cached - cacheWrite),
639
645
  outputTokens: (raw.output_tokens ?? 0) + (raw.reasoning_output_tokens ?? 0),
640
- cacheCreationInputTokens: 0,
646
+ cacheCreationInputTokens: cacheWrite,
641
647
  cacheReadInputTokens: cached,
642
648
  };
643
649
  }
@@ -1,122 +1,109 @@
1
1
  /**
2
2
  * Codex Engine model catalog.
3
3
  *
4
- * Static catalog — sourced from https://developers.openai.com/codex/models.md
5
- * and pruned to the IDs the Codex CLI actually accepts via `--model`. Models
6
- * tagged with `requiresAuthMode` are filtered by the chat-input account
4
+ * Static catalog — it mirrors the model preset table the Codex CLI ships with
5
+ * (`@openai/codex`, read out of the shipped binary), cross-checked against
6
+ * https://learn.chatgpt.com/docs/models.md. That table is the CLI's own source
7
+ * of truth for slug, display name, context window and reasoning levels, so
8
+ * re-read it on every SDK bump rather than transcribing docs by hand.
9
+ *
10
+ * Presence in that table decides membership here: `gpt-5.3-codex`, `gpt-5.4`
11
+ * and `gpt-5.4-mini` left it in the 0.147 bump and are dropped (the 5.4 pair
12
+ * retires 2026-08-31). `gpt-5.3-codex-spark` is the deliberate exception — the
13
+ * CLI also fetches account-entitled models from the server, so its absence from
14
+ * the shipped table is not evidence of removal, and the docs still list it for
15
+ * ChatGPT Pro.
16
+ *
17
+ * Models tagged `requiresAuthMode` are filtered by the chat-input account
7
18
  * picker so the user can't pick a ChatGPT-only model while signed in with an
8
- * API key account (and vice versa). Update when OpenAI ships a new
9
- * generation.
19
+ * API key account (and vice versa).
10
20
  */
11
21
 
12
22
  import type { EngineModel, ReasoningControl } from '$shared/types/unified';
13
23
  import { toReasoningOptions } from '$shared/constants/engines';
14
24
 
15
25
  /**
16
- * Codex's reasoning knob is the SDK `modelReasoningEffort` thread option
17
- * (`minimal | low | medium | high | xhigh`). `medium` is the historical
18
- * default. Attached only to reasoning-capable models below.
26
+ * Codex's reasoning knob is the `model_reasoning_effort` config value. The
27
+ * levels are per-model now: the 5.6 family added `max` and `ultra` above
28
+ * `xhigh`, and `minimal` is no longer accepted by any current model.
29
+ *
30
+ * `max` and `ultra` sit past the SDK's `ModelReasoningEffort` union, which
31
+ * still stops at `xhigh` in 0.147 — see `resolveCodexEffort` for why sending
32
+ * them anyway is sound.
19
33
  */
20
- const CODEX_REASONING_CONTROL: ReasoningControl = {
21
- levels: toReasoningOptions(['minimal', 'low', 'medium', 'high', 'xhigh']),
22
- default: 'medium',
23
- };
34
+ const EFFORTS_TO_ULTRA = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
35
+ const EFFORTS_TO_MAX = ['low', 'medium', 'high', 'xhigh', 'max'];
36
+ const EFFORTS_TO_XHIGH = ['low', 'medium', 'high', 'xhigh'];
24
37
 
25
- const CODEX_MODELS_BASE: EngineModel[] = [
26
- {
27
- engine: {
28
- type: 'codex',
29
- provider: 'openai',
30
- model: { id: 'gpt-5.4', name: 'GPT-5.4' },
31
- account: { id: 0, name: '' },
32
- },
33
- limit: { input: 200_000, output: 128_000 },
34
- modalities: {
35
- input: { text: true, image: true, audio: false, video: false, pdf: false },
36
- output: { text: true, image: false, audio: false, video: false, pdf: false },
37
- },
38
- capabilities: { reasoning: true, tools: true, structuredOutput: true },
39
- cost: { input: 0, output: 0 },
40
- },
41
- {
42
- engine: {
43
- type: 'codex',
44
- provider: 'openai',
45
- model: { id: 'gpt-5.4-mini', name: 'GPT-5.4 mini' },
46
- account: { id: 0, name: '' },
47
- },
48
- limit: { input: 200_000, output: 128_000 },
49
- modalities: {
50
- input: { text: true, image: true, audio: false, video: false, pdf: false },
51
- output: { text: true, image: false, audio: false, video: false, pdf: false },
52
- },
53
- capabilities: { reasoning: true, tools: true, structuredOutput: true },
54
- cost: { input: 0, output: 0 },
55
- },
56
- {
57
- engine: {
58
- type: 'codex',
59
- provider: 'openai',
60
- model: { id: 'gpt-5.3-codex', name: 'GPT-5.3 Codex' },
61
- account: { id: 0, name: '' },
62
- },
63
- limit: { input: 200_000, output: 128_000 },
64
- modalities: {
65
- input: { text: true, image: true, audio: false, video: false, pdf: false },
66
- output: { text: true, image: false, audio: false, video: false, pdf: false },
67
- },
68
- capabilities: { reasoning: true, tools: true, structuredOutput: true },
69
- cost: { input: 0, output: 0 },
70
- },
71
- {
72
- engine: {
73
- type: 'codex',
74
- provider: 'openai',
75
- model: { id: 'gpt-5.2', name: 'GPT-5.2' },
76
- account: { id: 0, name: '' },
77
- },
78
- limit: { input: 200_000, output: 128_000 },
79
- modalities: {
80
- input: { text: true, image: true, audio: false, video: false, pdf: false },
81
- output: { text: true, image: false, audio: false, video: false, pdf: false },
82
- },
83
- capabilities: { reasoning: true, tools: true, structuredOutput: true },
84
- cost: { input: 0, output: 0 },
85
- },
86
- {
38
+ function codexReasoning(levels: string[], fallback: string): ReasoningControl {
39
+ return { levels: toReasoningOptions(levels), default: fallback };
40
+ }
41
+
42
+ /** Shared shape for a Codex catalog entry; `reasoning: null` = no reasoning knob. */
43
+ function codexModel(
44
+ id: string,
45
+ name: string,
46
+ reasoning: ReasoningControl | null,
47
+ extra?: { image?: boolean; requiresAuthMode?: 'chatgpt' },
48
+ ): EngineModel {
49
+ return {
87
50
  engine: {
88
51
  type: 'codex',
89
52
  provider: 'openai',
90
- model: { id: 'gpt-5.5', name: 'GPT-5.5 (ChatGPT only)' },
53
+ model: { id, name },
91
54
  account: { id: 0, name: '' },
92
55
  },
93
- limit: { input: 200_000, output: 128_000 },
56
+ // Every preset in the table reports a 272k context window.
57
+ limit: { input: 272_000, output: 128_000 },
94
58
  modalities: {
95
- input: { text: true, image: true, audio: false, video: false, pdf: false },
59
+ input: { text: true, image: extra?.image ?? true, audio: false, video: false, pdf: false },
96
60
  output: { text: true, image: false, audio: false, video: false, pdf: false },
97
61
  },
98
- capabilities: { reasoning: true, tools: true, structuredOutput: true, requiresAuthMode: 'chatgpt' },
99
- cost: { input: 0, output: 0 },
100
- },
101
- {
102
- engine: {
103
- type: 'codex',
104
- provider: 'openai',
105
- model: { id: 'gpt-5.3-codex-spark', name: 'GPT-5.3 Codex Spark (ChatGPT Pro)' },
106
- account: { id: 0, name: '' },
62
+ capabilities: {
63
+ reasoning: reasoning !== null,
64
+ tools: true,
65
+ structuredOutput: reasoning !== null,
66
+ ...(reasoning ? { reasoningControl: reasoning } : {}),
67
+ ...(extra?.requiresAuthMode ? { requiresAuthMode: extra.requiresAuthMode } : {}),
107
68
  },
108
- limit: { input: 200_000, output: 128_000 },
109
- modalities: {
110
- input: { text: true, image: false, audio: false, video: false, pdf: false },
111
- output: { text: true, image: false, audio: false, video: false, pdf: false },
112
- },
113
- capabilities: { reasoning: false, tools: true, structuredOutput: false, requiresAuthMode: 'chatgpt' },
114
69
  cost: { input: 0, output: 0 },
115
- },
70
+ };
71
+ }
72
+
73
+ /** Ordered by the CLI's own `priority` field, so the picker matches Codex's. */
74
+ export const CODEX_MODELS: EngineModel[] = [
75
+ codexModel('gpt-5.6-sol', 'GPT-5.6-Sol', codexReasoning(EFFORTS_TO_ULTRA, 'low')),
76
+ codexModel('gpt-5.6-terra', 'GPT-5.6-Terra', codexReasoning(EFFORTS_TO_ULTRA, 'medium')),
77
+ codexModel('gpt-5.6-luna', 'GPT-5.6-Luna', codexReasoning(EFFORTS_TO_MAX, 'medium')),
78
+ codexModel('gpt-5.5', 'GPT-5.5', codexReasoning(EFFORTS_TO_XHIGH, 'medium')),
79
+ codexModel('gpt-5.2', 'GPT-5.2', codexReasoning(EFFORTS_TO_XHIGH, 'medium')),
80
+ codexModel('gpt-5.3-codex-spark', 'GPT-5.3 Codex Spark (ChatGPT Pro)', null, {
81
+ image: false,
82
+ requiresAuthMode: 'chatgpt',
83
+ }),
116
84
  ];
117
85
 
118
- export const CODEX_MODELS: EngineModel[] = CODEX_MODELS_BASE.map((model) =>
119
- model.capabilities.reasoning
120
- ? { ...model, capabilities: { ...model.capabilities, reasoningControl: CODEX_REASONING_CONTROL } }
121
- : model,
122
- );
86
+ /**
87
+ * Resolve the `model_reasoning_effort` to send for a turn: the requested level
88
+ * when that model accepts it, otherwise that model's own default, otherwise
89
+ * `medium`.
90
+ *
91
+ * This is the only gate on the value. The picker offers per-model levels, but a
92
+ * stored preference outlives a catalog change, so a level that is no longer
93
+ * valid (`minimal`, or `ultra` on a model that caps at `max`) must not reach
94
+ * the CLI.
95
+ *
96
+ * The return type is deliberately `string`, not the SDK's
97
+ * `ModelReasoningEffort`. That union still stops at `xhigh` in
98
+ * @openai/codex-sdk 0.147 while the CLI it drives accepts
99
+ * `none|minimal|low|medium|high|xhigh|max|ultra`, and the SDK does not validate
100
+ * — it interpolates the value straight into
101
+ * `--config model_reasoning_effort="…"` (`dist/index.js`). Narrowing to the
102
+ * stale union would make `max` and `ultra`, the top levels of GPT-5.6 Sol and
103
+ * Terra, unreachable from Clopen. The caller casts at the SDK boundary.
104
+ */
105
+ export function resolveCodexEffort(modelId: string | undefined, requested: string | undefined): string {
106
+ const control = CODEX_MODELS.find(m => m.engine.model.id === modelId)?.capabilities.reasoningControl;
107
+ if (requested && control?.levels.some(level => level.value === requested)) return requested;
108
+ return control?.default ?? 'medium';
109
+ }