@myrialabs/clopen 0.4.28 → 0.4.30

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 (62) 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/migrations/067_add_memory_graph_layout.ts +91 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/graph-queries.ts +417 -32
  7. package/backend/database/utils/connection.ts +7 -31
  8. package/backend/db-client/drivers/mssql.ts +57 -22
  9. package/backend/db-client/drivers/mysql.ts +69 -48
  10. package/backend/db-client/drivers/postgres.ts +65 -53
  11. package/backend/engine/README.md +8 -3
  12. package/backend/engine/adapters/claude/message-converter.ts +51 -0
  13. package/backend/engine/adapters/claude/stream.ts +81 -15
  14. package/backend/engine/adapters/codex/message-converter.ts +8 -2
  15. package/backend/engine/adapters/codex/models.ts +85 -98
  16. package/backend/engine/adapters/codex/stream.ts +5 -7
  17. package/backend/engine/adapters/codex/usage-rollout.ts +7 -0
  18. package/backend/engine/adapters/copilot/stream.ts +24 -0
  19. package/backend/engine/docs/artifacts.md +1 -1
  20. package/backend/engine/docs/lessons-learned.md +78 -1
  21. package/backend/engine/docs/quick-reference.md +1 -1
  22. package/backend/engine/docs/stack.md +8 -0
  23. package/backend/engine/install-recipes.ts +19 -2
  24. package/backend/files/file-size-limit.ts +5 -14
  25. package/backend/files/file-watcher.test.ts +160 -0
  26. package/backend/files/file-watcher.ts +276 -58
  27. package/backend/git/git-executor.ts +8 -0
  28. package/backend/git/git-service.test.ts +136 -0
  29. package/backend/git/git-service.ts +113 -17
  30. package/backend/index.ts +16 -4
  31. package/backend/mcp/internal/remote-server.test.ts +8 -3
  32. package/backend/mcp/internal/remote-server.ts +1 -1
  33. package/backend/memory/bootstrap.ts +9 -0
  34. package/backend/memory/layout.ts +985 -0
  35. package/backend/memory/notify.ts +33 -7
  36. package/backend/memory/view.ts +375 -69
  37. package/backend/permissions/index.ts +4 -2
  38. package/backend/permissions/resolve.ts +7 -5
  39. package/backend/settings/system-settings.ts +97 -0
  40. package/backend/tunnel/public-origin.ts +5 -13
  41. package/backend/utils/env.ts +29 -0
  42. package/backend/utils/paths.ts +9 -3
  43. package/backend/utils/process-warnings.ts +41 -0
  44. package/backend/ws/auth/login.test.ts +8 -1
  45. package/backend/ws/auth/login.ts +22 -15
  46. package/backend/ws/auth/status.ts +24 -1
  47. package/backend/ws/chat/stream.ts +1 -0
  48. package/backend/ws/files/watch.ts +9 -0
  49. package/backend/ws/memory/crud.ts +50 -2
  50. package/backend/ws/settings/crud.ts +14 -22
  51. package/dist/assets/{index-BujQYGBm.js → index-DUc5T21e.js} +1 -1
  52. package/dist/assets/{index-DRMOgS9y.js → index-DYwQ5bP8.js} +1 -1
  53. package/dist/assets/main-VgdjTBLR.css +1 -0
  54. package/dist/assets/main-r0iv2PDz.js +1044 -0
  55. package/dist/index.html +2 -2
  56. package/package.json +14 -14
  57. package/shared/constants/engines.ts +1 -0
  58. package/shared/types/memory.ts +70 -0
  59. package/shared/types/stores/settings.ts +11 -1
  60. package/shared/types/unified/stream.ts +10 -4
  61. package/dist/assets/main-BrYtWn-4.js +0 -1036
  62. package/dist/assets/main-BrqMMMRX.css +0 -1
@@ -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
+ }
@@ -32,7 +32,7 @@ import { getCodexMcpConfig } from '../../../mcp';
32
32
  import { artifactFilter } from '$backend/profiles';
33
33
  import { syncSkills } from '$backend/skills';
34
34
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
35
- import { CODEX_MODELS } from './models';
35
+ import { CODEX_MODELS, resolveCodexEffort } from './models';
36
36
  import { debug } from '$shared/utils/logger';
37
37
  import { handleStreamError, buildTurnError } from './error-handler';
38
38
  import {
@@ -153,12 +153,10 @@ export class CodexEngine implements AIEngine {
153
153
  async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
154
154
  const { projectPath, prompt, resume, modelId, reasoningEffort, abortController, accountId } = options;
155
155
 
156
- // Codex's reasoning knob (`minimal | low | medium | high | xhigh`); default
157
- // medium when unset or an unsupported token slips through.
158
- const codexEfforts = new Set<string>(['minimal', 'low', 'medium', 'high', 'xhigh']);
159
- const modelReasoningEffort: ModelReasoningEffort = reasoningEffort && codexEfforts.has(reasoningEffort)
160
- ? reasoningEffort as ModelReasoningEffort
161
- : 'medium';
156
+ // Per-model reasoning levels live in the catalog, which is derived from the
157
+ // CLI's own preset table — see `resolveCodexEffort` for the validity rules
158
+ // and for why the SDK's narrower `ModelReasoningEffort` union is cast past.
159
+ const modelReasoningEffort = resolveCodexEffort(modelId, reasoningEffort) as ModelReasoningEffort;
162
160
 
163
161
  // Active Profile for this stream — scopes the materialized artifact set AND
164
162
  // (below) the MCP connector set baked into the Codex client.
@@ -91,6 +91,12 @@ interface RolloutTokenInfo {
91
91
  last_token_usage?: {
92
92
  input_tokens?: number;
93
93
  cached_input_tokens?: number;
94
+ /**
95
+ * Added by the CLI that ships with @openai/codex-sdk 0.147. Rollout files
96
+ * written by an older CLI (a thread started before the update) omit it, so
97
+ * it stays optional here and defaults to 0.
98
+ */
99
+ cache_write_input_tokens?: number;
94
100
  output_tokens?: number;
95
101
  reasoning_output_tokens?: number;
96
102
  };
@@ -139,6 +145,7 @@ export function readLastTokenUsageFromRollout(threadId: string): Usage | null {
139
145
  return {
140
146
  input_tokens: last.input_tokens ?? 0,
141
147
  cached_input_tokens: last.cached_input_tokens ?? 0,
148
+ cache_write_input_tokens: last.cache_write_input_tokens ?? 0,
142
149
  output_tokens: last.output_tokens ?? 0,
143
150
  reasoning_output_tokens: last.reasoning_output_tokens ?? 0,
144
151
  };
@@ -543,6 +543,30 @@ export class CopilotEngine implements AIEngine {
543
543
  finished = true;
544
544
  break;
545
545
 
546
+ case 'session_limits_exhausted.requested': {
547
+ // Added in @github/copilot-sdk 1.0.9. The model request is
548
+ // BLOCKED until a client answers this over `rpc.ui` — an
549
+ // unhandled one hangs the turn with no output at all.
550
+ //
551
+ // The available actions are `add` / `set` / `unset` / `cancel`,
552
+ // i.e. three of them raise (or remove) the user's AI-credit
553
+ // ceiling. Clopen never spends on someone's behalf, so it
554
+ // cancels the blocked request and reports the numbers; raising
555
+ // the limit stays a deliberate act in GitHub's own settings.
556
+ const { requestId, usedAiCredits, maxAiCredits } = event.data;
557
+ void session.rpc.ui
558
+ .handlePendingSessionLimitsExhausted({ requestId, response: { action: 'cancel' } })
559
+ .catch((error: unknown) => debug.warn('engine', 'Copilot session-limit cancel failed:', error));
560
+ yield {
561
+ type: 'notification',
562
+ sessionId: state.sessionId,
563
+ level: 'error',
564
+ title: 'Copilot AI credit limit reached',
565
+ message: `This session used ${usedAiCredits} of ${maxAiCredits} AI credits, so the request was cancelled. Raise the limit in your GitHub Copilot settings to continue.`,
566
+ };
567
+ break;
568
+ }
569
+
546
570
  case 'session.error':
547
571
  throw buildSessionError(event.data);
548
572
 
@@ -98,7 +98,7 @@ reliably re-read per turn — the prompt is the one genuinely per-session channe
98
98
  | **Commands** (`backend/commands/`) | custom slash commands | global, project | one `.md` per command into the engine command dir, or synthetic preamble. Profile-bundled |
99
99
  | **Subagents** (`backend/subagents/`) | specialized delegated agents | global, project | one `.md` per subagent, or synthetic preamble. Profile-bundled |
100
100
  | **Instructions** (`backend/instructions/`) | a shared instruction block | global, project | marker region inside the engine memory file (`CLAUDE.md` / `QWEN.md` / `AGENTS.md`). Global set always synced in full; never profile-bundled |
101
- | **Permissions** (`backend/permissions/`) | per-engine tool allow/deny | global, project | **enforcement is a runtime hook** (`resolvePermissionsFromDb` + `isToolAllowed`) each adapter consults at its auto-approve point. The matrix only describes the optional on-disk "honesty" file, which today only Claude reads (a managed `permissions` key merged into its isolated `settings.json`) |
101
+ | **Permissions** (`backend/permissions/`) | per-engine tool allow/deny | global, project | **enforcement is a runtime check** (`resolvePermissionsFromDb` + `isToolAllowed`) each adapter runs at whichever surface fires for every tool call — for Claude a `PreToolUse` hook, since `bypassPermissions` auto-approves before `canUseTool` is consulted. The matrix only describes the optional on-disk file, which today only Claude reads (a managed `permissions` key merged into its isolated `settings.json`); its `deny` rules do bite even under `bypassPermissions`, an allowlist has no on-disk equivalent |
102
102
  | **Profiles** (`backend/profiles/`) | a named bundle of slugs | per session | not materialized. Narrows which instance-global artifacts are active: effective profile = `chat_sessions.profile_id ?? projects.default_profile_id`, resolved once at stream start and threaded down as `profileId`. Only constrains the types it references (`artifactFilter` → `null` = unconstrained), so a Commands-only profile never disables every Skill |
103
103
 
104
104
  ### 8.5 Connectors (MCP)
@@ -248,7 +248,7 @@ resume.
248
248
  |-----------|----------------------------------------------------------------------------------------------|
249
249
  | Claude | Pass `forkSession: true` in the SDK options on every call — native. |
250
250
  | OpenCode | Call `client.session.fork({ path: { id: resume } })` on every resume — native. |
251
- | Copilot | Call `client.rpc.sessions.fork({ sessionId: resume })` on every resume — native (`@experimental`, added in `@github/copilot-sdk` 1.0.0-beta.4). |
251
+ | Copilot | Call `client.rpc.sessions.fork({ sessionId: resume })` on every resume — native (added in `@github/copilot-sdk` 1.0.0-beta.4; still marked `@experimental` in 1.0.9, so keep the fallback-to-plain-resume path). |
252
252
  | Codex | **No native API yet** — fork by copying the rollout JSONL FILE on every resume. |
253
253
  | Qwen Code | **No native API yet** — fork by copying the chat JSONL FILE on every resume. |
254
254
  | Pi | `SessionManager.forkFrom()` on the on-disk JSONL tree (in Clopen's isolated sessions dir) — native, on every resume. |
@@ -1431,3 +1431,80 @@ reachable, so smuggling the import into some other boot-path file is caught
1431
1431
  too. It also asserts each key loads *its own* adapter: mapping `cursor` to
1432
1432
  `ClineEngine` type-checks with zero errors and would route a user's chat
1433
1433
  through the wrong SDK, and nothing but that check catches it.
1434
+
1435
+ ---
1436
+
1437
+ ### 10.25 Upgrading engine SDKs — the type-checker only sees half of it
1438
+
1439
+ The August 2026 pass moved all eleven engine packages to current (Claude
1440
+ 0.3.158 → 0.3.229, Copilot beta.9 → 1.0.9 + CLI 1.0.55 → 1.0.79, Codex 0.135 →
1441
+ 0.147, OpenCode 1.15.12 → 1.18.18, Pi 0.80.10 → 0.84.1, Cline 0.0.65 → 0.0.74,
1442
+ Cursor 1.0.24 → 1.0.27, Qwen 0.1.7 → 0.1.8). `bun run check` reported exactly
1443
+ two errors — and neither of them was one of the three real problems. What the
1444
+ type-checker cannot see is where the work is:
1445
+
1446
+ - **A new *blocking* event is a hang, not a type error.** Copilot 1.0.9 added
1447
+ `session_limits_exhausted.requested`: the model request stops until a client
1448
+ answers it over `session.rpc.ui.handlePendingSessionLimitsExhausted`. An
1449
+ unhandled `case` compiles perfectly and the turn simply never produces
1450
+ output. Before shipping an upgrade, diff the event union for anything named
1451
+ `*.requested` / `*.asked` / `*_request` and check whether it has a paired
1452
+ `.completed` — that pairing is the tell for "someone must answer this".
1453
+ Clopen answers `cancel` and surfaces a notification: three of the four
1454
+ actions raise the user's AI-credit ceiling, and no auto-approval policy
1455
+ covers spending someone's money.
1456
+
1457
+ - **A new *informational* message type is silent data loss.** Claude's
1458
+ `SDKMessage` grew eight members; two of them (`model_refusal_fallback`,
1459
+ `model_refusal_no_fallback`) are precisely the cases a user notices — the
1460
+ answer came from a model they did not pick, or no answer came at all — and
1461
+ the converter's `default` arm swallowed both. Adapters end their dispatch
1462
+ with a catch-all by design, so every SDK bump must diff the union rather than
1463
+ trust a clean compile.
1464
+
1465
+ - **A static model catalog goes stale on the same clock, and the CLI knows the
1466
+ answer.** The Codex bump moved the whole lineup: `gpt-5.6-sol/terra/luna`
1467
+ appeared, `gpt-5.3-codex` and the `gpt-5.4` pair left, `gpt-5.5` stopped being
1468
+ ChatGPT-only, the context window went 200k → 272k, `minimal` stopped being a
1469
+ valid effort and `max`/`ultra` became one. None of that surfaces as a type
1470
+ error — a wrong slug fails at runtime, inside the CLI, as somebody's chat.
1471
+ Do not transcribe the docs: the shipped binary embeds its own preset table
1472
+ (`strings <codex-binary>`, search `"models": [`) with slug, `display_name`,
1473
+ `context_window`, `default_reasoning_level`, `supported_reasoning_levels`,
1474
+ `visibility` and `priority`. That is what the client actually accepts, and
1475
+ `backend/engine/adapters/codex/models.ts` mirrors it field for field. Treat
1476
+ the public docs as the second source, not the first — and remember the CLI
1477
+ also fetches account-entitled models from the server, so absence from the
1478
+ embedded table is not proof of removal (that is why `gpt-5.3-codex-spark`
1479
+ stayed).
1480
+
1481
+ - **Peer dependencies float even when the SDK is pinned.**
1482
+ `@anthropic-ai/claude-agent-sdk` ships no dependencies: `@anthropic-ai/sdk`,
1483
+ `@modelcontextprotocol/sdk` and `zod` are peers. `ENGINE_PACKAGES` listed
1484
+ only the SDK, so `bun add` resolved all three at `@latest` inside
1485
+ `~/.clopen/stack/engines` — a real install carried `@anthropic-ai/sdk`
1486
+ 0.115.0 while clopen type-checked against its pinned 0.100.1. Same class as
1487
+ the typebox float (#362). The peers are pinned explicitly now. When adding an
1488
+ engine, read its `peerDependencies`, not just its `dependencies`.
1489
+
1490
+ **Known gap, deliberately not closed:** `SDKModelRefusalFallbackMessage`
1491
+ carries `retracted_message_uuids` — messages the CLI has *withdrawn* after
1492
+ delivering them. Clopen's `messageId` for Claude is the SDK uuid, so honouring
1493
+ it is feasible, but it needs a retraction event threaded through
1494
+ adapter → stream-manager → WS → frontend removal. Until then the refused
1495
+ partial stays in the transcript above the fallback answer, and the toast is
1496
+ what explains it.
1497
+
1498
+ A second gap worth naming: the SDK's own types can lag the CLI it drives.
1499
+ `ModelReasoningEffort` still stops at `xhigh` in codex-sdk 0.147 while the CLI
1500
+ enum runs to `max` and `ultra`, and the SDK never validates — it interpolates
1501
+ the string into `--config model_reasoning_effort="…"`. Reading the transport,
1502
+ not just the type, is what made GPT-5.6's top levels reachable. Cast at the SDK
1503
+ boundary and gate the value in one place (`resolveCodexEffort`), never by a
1504
+ second copy of the allow-list next to the call site — that copy is exactly what
1505
+ had gone stale.
1506
+
1507
+ The mechanical part of an upgrade is cheap; budget the time for the union
1508
+ diffs. `/tmp`-installing the old and new versions side by side and diffing the
1509
+ `type: "…"` literals in each SDK's event declarations found every item above in
1510
+ minutes.
@@ -29,7 +29,7 @@
29
29
  | Materialize an artifact per engine (matrix) | `backend/artifacts/matrix.ts::resolveArtifact`, generic writer `backend/artifacts/sync.ts`, scanner `backend/artifacts/detect.ts` (see §8.2) |
30
30
  | Per-stream artifact sync (Commands/Subagents/Instructions) | `backend/engine/artifact-sync.ts::syncEngineArtifacts` + `buildArtifactsPromptContext` — called from each `stream.ts` after `syncSkills` (see §8.3) |
31
31
  | Profile scoping (narrow active artifacts) | `backend/profiles/service.ts::resolveActiveProfileId` + `artifactFilter` (see §8.4) |
32
- | Permission enforcement (runtime hook) | `backend/permissions/service.ts::resolvePermissionsFromDb` + `isToolAllowed` (see §8.4) |
32
+ | Permission enforcement (runtime check) | `backend/permissions/service.ts::resolvePermissionsFromDb` + `isToolAllowed` (see §8.4); Claude wires it into a `PreToolUse` hook in `claude/stream.ts` |
33
33
  | Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §10.13 |
34
34
  | Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `engines/panels/OpenCodePanel.svelte::handleRestartServer`/`forceRestartServer` |
35
35
  | `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`); `opencode` / `copilot` / `qwen` / `pi` / `cline` / `cursor` are prompt-engineered via `backend/engine/structured-helpers.ts` (`buildJsonPrompt` + `extractJson`). See §10.16 for the strict-schema + part-fallback gotchas. |
@@ -125,6 +125,14 @@ Engine SDKs don't need a hand-written resolver. When you add an engine
125
125
  clopen imports and detects install-state from; extras pin a transitive CLI
126
126
  the SDK would otherwise float). Add the same packages to `package.json`
127
127
  `devDependencies` at an exact version — that is the single source of truth.
128
+ **Read the SDK's `peerDependencies` too.** A peer the SDK ships no copy of
129
+ resolves at `@latest` inside the stack dir unless it is listed here, leaving
130
+ clopen type-checked against one version and running another —
131
+ `@anthropic-ai/claude-agent-sdk` has `@anthropic-ai/sdk`,
132
+ `@modelcontextprotocol/sdk` and `zod` listed for exactly that reason (see
133
+ [lessons-learned](./lessons-learned.md) §10.25). A package the SDK depends
134
+ on *directly* needs no entry: its own range governs, and bun nests a copy
135
+ when two engines disagree.
128
136
  3. `resolveEngineRecipe(tool)` handles the rest automatically (installs into the
129
137
  stack dir at the pinned version).
130
138
  4. Add the literal to `TOOL_UNION` (`status.ts`, `install.ts`).
@@ -84,7 +84,19 @@ export interface ToolStatus {
84
84
  /**
85
85
  * Engine → the npm package(s) clopen must install to run that engine on demand.
86
86
  * The FIRST entry is the SDK clopen imports (used for install-state detection);
87
- * any extras pin a transitive CLI the SDK would otherwise float (e.g. copilot).
87
+ * any extras pin something the SDK would otherwise float — a transitive CLI
88
+ * (copilot), a sibling package (pi, cline), or an unmet PEER dependency.
89
+ *
90
+ * Peers are the subtle case. `@anthropic-ai/claude-agent-sdk` declares
91
+ * `@anthropic-ai/sdk`, `@modelcontextprotocol/sdk` and `zod` as peers and ships
92
+ * no copy of its own, so installing the SDK alone lets bun resolve all three at
93
+ * `@latest` inside the stack dir — clopen would then type-check against the
94
+ * versions in its own package.json while the adapter loads different ones at
95
+ * runtime (observed: pinned `@anthropic-ai/sdk` 0.100.1 vs 0.115.0 installed).
96
+ * Listing them here holds them to the same pin. Engines whose SDK depends on
97
+ * these packages directly (copilot, cursor, qwen) need no entry: their own
98
+ * range governs, and bun nests a separate copy when it disagrees.
99
+ *
88
100
  * Versions are read from package.json (the single source of truth), so an
89
101
  * on-demand install always matches the exact version clopen was tested against.
90
102
  * Every package listed here must therefore be declared in package.json —
@@ -92,7 +104,12 @@ export interface ToolStatus {
92
104
  * silently install as `@latest`.
93
105
  */
94
106
  export const ENGINE_PACKAGES: Partial<Record<ToolId, string[]>> = {
95
- claude: ['@anthropic-ai/claude-agent-sdk'],
107
+ claude: [
108
+ '@anthropic-ai/claude-agent-sdk',
109
+ '@anthropic-ai/sdk',
110
+ '@modelcontextprotocol/sdk',
111
+ 'zod'
112
+ ],
96
113
  opencode: ['@opencode-ai/sdk'],
97
114
  copilot: ['@github/copilot-sdk', '@github/copilot'],
98
115
  codex: ['@openai/codex-sdk'],
@@ -7,7 +7,7 @@
7
7
  * defaults to 500MB when the setting is missing or invalid.
8
8
  */
9
9
 
10
- import { settingsQueries } from '../database/queries';
10
+ import { readSystemSetting } from '../settings/system-settings';
11
11
 
12
12
  /** Default maximum file size in megabytes when no admin setting is present. */
13
13
  export const DEFAULT_MAX_FILE_SIZE_MB = 500;
@@ -19,19 +19,10 @@ export const DEFAULT_MAX_FILE_SIZE_MB = 500;
19
19
  * (e.g. on first boot before the admin writes any system setting).
20
20
  */
21
21
  export function getMaxFileSize(): number {
22
- let limitMB = DEFAULT_MAX_FILE_SIZE_MB;
23
- try {
24
- const row = settingsQueries.get('system:settings');
25
- if (row?.value) {
26
- const parsed = typeof row.value === 'string' ? JSON.parse(row.value) : row.value;
27
- const candidate = Number(parsed?.maxFileSizeMB);
28
- if (Number.isFinite(candidate) && candidate > 0) {
29
- limitMB = candidate;
30
- }
31
- }
32
- } catch {
33
- // Fall back to default on any read/parse failure.
34
- }
22
+ const limitMB = readSystemSetting((settings) => {
23
+ const candidate = Number(settings.maxFileSizeMB);
24
+ return Number.isFinite(candidate) && candidate > 0 ? candidate : undefined;
25
+ }, DEFAULT_MAX_FILE_SIZE_MB);
35
26
  return Math.floor(limitMB * 1024 * 1024);
36
27
  }
37
28
 
@@ -0,0 +1,160 @@
1
+ /**
2
+ * File watcher tests.
3
+ *
4
+ * These exercise the real watcher against a real temp directory, because the
5
+ * bugs this code exists to prevent are all about what the OS actually reports:
6
+ * ignored directories still generating events, a rebuilt watcher announcing
7
+ * itself as a file change, and nested directories created after start-up going
8
+ * unwatched (which is only a risk on the platforms where recursion is emulated).
9
+ */
10
+
11
+ import { describe, expect, mock, test, beforeAll, afterEach } from 'bun:test';
12
+ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
13
+ import { tmpdir } from 'node:os';
14
+ import { join } from 'node:path';
15
+
16
+ interface Emitted {
17
+ projectId: string;
18
+ event: string;
19
+ payload: Record<string, unknown>;
20
+ }
21
+
22
+ const emitted: Emitted[] = [];
23
+
24
+ mock.module('$backend/utils/ws', () => ({
25
+ ws: {
26
+ emit: {
27
+ project: (projectId: string, event: string, payload: Record<string, unknown>) => {
28
+ emitted.push({ projectId, event, payload });
29
+ },
30
+ user: () => {},
31
+ global: () => {}
32
+ }
33
+ }
34
+ }));
35
+
36
+ // Imported after the mock so the watcher binds to the stub.
37
+ let fileWatcher: typeof import('./file-watcher').fileWatcher;
38
+
39
+ beforeAll(async () => {
40
+ ({ fileWatcher } = await import('./file-watcher'));
41
+ });
42
+
43
+ const tempRoots: string[] = [];
44
+
45
+ async function makeProject(): Promise<string> {
46
+ const dir = await mkdtemp(join(tmpdir(), 'clopen-watch-'));
47
+ tempRoots.push(dir);
48
+ return dir;
49
+ }
50
+
51
+ /** Wait until `predicate` holds, or fail after `timeout` ms. */
52
+ async function waitFor(predicate: () => boolean, timeout = 4000): Promise<void> {
53
+ const deadline = Date.now() + timeout;
54
+ while (Date.now() < deadline) {
55
+ if (predicate()) return;
56
+ await new Promise((r) => setTimeout(r, 25));
57
+ }
58
+ throw new Error('Timed out waiting for watcher event');
59
+ }
60
+
61
+ function changesFor(projectId: string): string[] {
62
+ return emitted
63
+ .filter((e) => e.projectId === projectId && e.event === 'files:changed')
64
+ .flatMap((e) => (e.payload.changes as { path: string }[]).map((c) => c.path));
65
+ }
66
+
67
+ afterEach(async () => {
68
+ for (const projectId of fileWatcher.getWatchedProjects()) {
69
+ fileWatcher.releaseProject(projectId);
70
+ }
71
+ emitted.length = 0;
72
+ await Promise.all(tempRoots.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
73
+ });
74
+
75
+ describe('FileWatcherManager', () => {
76
+ test('reports changes to files in the project root', async () => {
77
+ const root = await makeProject();
78
+ expect(await fileWatcher.startWatching('p1', root)).toBe(true);
79
+
80
+ await writeFile(join(root, 'index.ts'), 'export {}');
81
+
82
+ await waitFor(() => changesFor('p1').some((p) => p.endsWith('index.ts')));
83
+ });
84
+
85
+ test('reports changes in nested directories created after the watch started', async () => {
86
+ const root = await makeProject();
87
+ expect(await fileWatcher.startWatching('p2', root)).toBe(true);
88
+
89
+ // A directory that did not exist at start-up: on Linux this only works if
90
+ // the watcher attaches to newly created directories as it sees them.
91
+ const nested = join(root, 'src', 'deep');
92
+ await mkdir(nested, { recursive: true });
93
+ await waitFor(() => changesFor('p2').some((p) => p.endsWith('src')));
94
+
95
+ emitted.length = 0;
96
+ await writeFile(join(nested, 'mod.ts'), 'export {}');
97
+
98
+ await waitFor(() => changesFor('p2').some((p) => p.endsWith('mod.ts')));
99
+ });
100
+
101
+ test('never reports changes inside ignored directories', async () => {
102
+ const root = await makeProject();
103
+ await mkdir(join(root, 'node_modules', 'pkg'), { recursive: true });
104
+ await mkdir(join(root, '.git'), { recursive: true });
105
+ expect(await fileWatcher.startWatching('p3', root)).toBe(true);
106
+
107
+ await writeFile(join(root, 'node_modules', 'pkg', 'index.js'), '// noise');
108
+ await writeFile(join(root, '.git', 'COMMIT_EDITMSG'), 'wip');
109
+
110
+ // Space the writes out: the platform watchers coalesce bursts and can drop
111
+ // events that land in the same instant, which would make this pass for the
112
+ // wrong reason (or fail on the sentinel write below).
113
+ await new Promise((r) => setTimeout(r, 400));
114
+
115
+ // Write a watched file last; once it lands, the ignored writes have had at
116
+ // least as long to arrive, so their absence is meaningful rather than a race.
117
+ await writeFile(join(root, 'app.ts'), 'export {}');
118
+ await waitFor(() => changesFor('p3').some((p) => p.endsWith('app.ts')));
119
+
120
+ const paths = changesFor('p3');
121
+ expect(paths.some((p) => p.includes('node_modules'))).toBe(false);
122
+ expect(paths.some((p) => p.includes('.git'))).toBe(false);
123
+ });
124
+
125
+ test('does not emit an empty change list', async () => {
126
+ const root = await makeProject();
127
+ expect(await fileWatcher.startWatching('p4', root)).toBe(true);
128
+
129
+ await writeFile(join(root, 'a.ts'), 'export {}');
130
+ await waitFor(() => changesFor('p4').length > 0);
131
+
132
+ const empties = emitted.filter(
133
+ (e) => e.event === 'files:changed' && (e.payload.changes as unknown[]).length === 0
134
+ );
135
+ expect(empties).toHaveLength(0);
136
+ });
137
+
138
+ test('tracks dirty files for the snapshot system', async () => {
139
+ const root = await makeProject();
140
+ expect(await fileWatcher.startWatching('p5', root)).toBe(true);
141
+
142
+ await writeFile(join(root, 'tracked.ts'), 'export {}');
143
+ await waitFor(() => fileWatcher.getDirtyFiles('p5').has('tracked.ts'));
144
+
145
+ fileWatcher.clearDirtyFiles('p5');
146
+ expect(fileWatcher.getDirtyFiles('p5').size).toBe(0);
147
+ });
148
+
149
+ test('stops watching once the last viewer leaves', async () => {
150
+ const root = await makeProject();
151
+ expect(await fileWatcher.addViewer('conn-a', 'p6', root)).toBe(true);
152
+ expect(await fileWatcher.addViewer('conn-b', 'p6', root)).toBe(true);
153
+
154
+ fileWatcher.removeViewer('conn-a', 'p6');
155
+ expect(fileWatcher.isWatching('p6')).toBe(true);
156
+
157
+ fileWatcher.removeViewer('conn-b', 'p6');
158
+ expect(fileWatcher.isWatching('p6')).toBe(false);
159
+ });
160
+ });