@myrialabs/clopen 0.4.44 → 0.4.46

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 (118) hide show
  1. package/backend/artifacts/project/bridge.ts +218 -0
  2. package/backend/artifacts/project/edit.ts +243 -0
  3. package/backend/artifacts/project/index.ts +38 -0
  4. package/backend/artifacts/project/project.test.ts +181 -0
  5. package/backend/artifacts/project/scan.ts +368 -0
  6. package/backend/artifacts/project/sources.ts +100 -0
  7. package/backend/artifacts/sync.ts +1 -1
  8. package/backend/auth/permissions.ts +15 -0
  9. package/backend/chat/stream-manager.ts +20 -3
  10. package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
  11. package/backend/database/migrations/index.ts +7 -0
  12. package/backend/database/queries/index.ts +2 -0
  13. package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
  14. package/backend/engine/adapters/claude/models.test.ts +49 -0
  15. package/backend/engine/adapters/claude/models.ts +81 -562
  16. package/backend/engine/adapters/claude/stream.ts +32 -5
  17. package/backend/engine/adapters/cline/credential.ts +42 -18
  18. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  19. package/backend/engine/adapters/cline/message-converter.ts +31 -1
  20. package/backend/engine/adapters/cline/models.test.ts +77 -0
  21. package/backend/engine/adapters/cline/models.ts +89 -3
  22. package/backend/engine/adapters/cline/presets.ts +5 -0
  23. package/backend/engine/adapters/cline/stream.ts +29 -8
  24. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  25. package/backend/engine/adapters/codex/models.ts +54 -31
  26. package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
  27. package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
  28. package/backend/engine/adapters/codex/session-fork.ts +5 -0
  29. package/backend/engine/adapters/codex/stream.ts +29 -11
  30. package/backend/engine/adapters/copilot/models.test.ts +40 -0
  31. package/backend/engine/adapters/copilot/models.ts +51 -24
  32. package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
  33. package/backend/engine/adapters/copilot/permissions.ts +72 -0
  34. package/backend/engine/adapters/copilot/stream.ts +83 -70
  35. package/backend/engine/adapters/cursor/stream.ts +27 -12
  36. package/backend/engine/adapters/opencode/server.ts +14 -4
  37. package/backend/engine/adapters/opencode/stream.ts +18 -3
  38. package/backend/engine/adapters/pi/credential.test.ts +83 -0
  39. package/backend/engine/adapters/pi/credential.ts +68 -12
  40. package/backend/engine/adapters/pi/environment.ts +9 -5
  41. package/backend/engine/adapters/pi/mcp.test.ts +194 -0
  42. package/backend/engine/adapters/pi/mcp.ts +88 -0
  43. package/backend/engine/adapters/pi/message-converter.ts +6 -4
  44. package/backend/engine/adapters/pi/presets.ts +10 -5
  45. package/backend/engine/adapters/pi/stream.ts +77 -41
  46. package/backend/engine/adapters/qwen/environment.ts +39 -2
  47. package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
  48. package/backend/engine/adapters/qwen/message-converter.ts +40 -23
  49. package/backend/engine/adapters/qwen/models.test.ts +25 -0
  50. package/backend/engine/adapters/qwen/models.ts +42 -5
  51. package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
  52. package/backend/engine/adapters/qwen/session-store.ts +66 -0
  53. package/backend/engine/adapters/qwen/stream.ts +118 -87
  54. package/backend/engine/artifact-sync.ts +12 -5
  55. package/backend/engine/docs/adapter-contract.md +7 -4
  56. package/backend/engine/docs/lessons-learned.md +405 -62
  57. package/backend/engine/docs/quick-reference.md +2 -2
  58. package/backend/engine/docs/stack.md +17 -4
  59. package/backend/engine/docs/websocket-routes.md +5 -5
  60. package/backend/engine/install-recipes.test.ts +105 -5
  61. package/backend/engine/install-recipes.ts +102 -42
  62. package/backend/engine/install-runner.ts +56 -2
  63. package/backend/engine/stack-project.ts +71 -1
  64. package/backend/files/file-watcher.test.ts +77 -0
  65. package/backend/files/file-watcher.ts +92 -60
  66. package/backend/files/watch-ignore.test.ts +182 -0
  67. package/backend/files/watch-ignore.ts +244 -0
  68. package/backend/git/git-executor.ts +14 -4
  69. package/backend/index.ts +16 -1
  70. package/backend/instructions/service.ts +5 -3
  71. package/backend/instructions/sync.ts +10 -27
  72. package/backend/mcp/README.md +2 -2
  73. package/backend/mcp/external/config.ts +83 -23
  74. package/backend/mcp/external/project.ts +124 -0
  75. package/backend/mcp/external/proxy.ts +65 -11
  76. package/backend/mcp/index.ts +22 -9
  77. package/backend/mcp/internal/config.ts +42 -3
  78. package/backend/mcp/internal/remote-server.ts +11 -1
  79. package/backend/memory/embedding/install.ts +29 -1
  80. package/backend/skills/marketplace.ts +1 -1
  81. package/backend/snapshot/blob-store.ts +9 -5
  82. package/backend/snapshot/git-attribution.test.ts +42 -0
  83. package/backend/snapshot/git-attribution.ts +306 -0
  84. package/backend/snapshot/gitignore.test.ts +62 -0
  85. package/backend/snapshot/gitignore.ts +158 -78
  86. package/backend/snapshot/snapshot-service.test.ts +270 -0
  87. package/backend/snapshot/snapshot-service.ts +412 -136
  88. package/backend/snapshot/turn-activity.test.ts +52 -0
  89. package/backend/snapshot/turn-activity.ts +83 -0
  90. package/backend/snapshot/turn-changes.test.ts +58 -1
  91. package/backend/snapshot/turn-changes.ts +66 -0
  92. package/backend/utils/keyed-lock.test.ts +33 -0
  93. package/backend/utils/keyed-lock.ts +17 -0
  94. package/backend/utils/port-utils.test.ts +29 -0
  95. package/backend/utils/port-utils.ts +19 -0
  96. package/backend/worktrees/tree.ts +1 -1
  97. package/backend/ws/chat/composer.ts +504 -0
  98. package/backend/ws/chat/index.ts +3 -1
  99. package/backend/ws/chat/stream.ts +252 -440
  100. package/backend/ws/engine/cline/accounts.ts +26 -6
  101. package/backend/ws/engine/codex/accounts.test.ts +49 -0
  102. package/backend/ws/engine/codex/accounts.ts +17 -13
  103. package/backend/ws/engine/pi/accounts.ts +61 -6
  104. package/backend/ws/index.ts +4 -0
  105. package/backend/ws/project-artifacts/index.ts +236 -0
  106. package/backend/ws/snapshot/changes.ts +66 -31
  107. package/dist/assets/{index-DX5OwLOc.js → index-BTcR1byF.js} +1 -1
  108. package/dist/assets/{index-BWyhqUi5.js → index-CwuKQelV.js} +1 -1
  109. package/dist/assets/main-BiDNMWb3.css +1 -0
  110. package/dist/assets/main-BlhKWz2B.js +1241 -0
  111. package/dist/index.html +2 -2
  112. package/package.json +19 -15
  113. package/shared/types/stores/settings.ts +5 -0
  114. package/shared/types/unified/message.ts +2 -0
  115. package/backend/engine/adapters/pi/mcp-tools.ts +0 -131
  116. package/backend/engine/adapters/qwen/session-fork.ts +0 -109
  117. package/dist/assets/main-DOkwqXRU.js +0 -1215
  118. package/dist/assets/main-DzCY0n-j.css +0 -1
@@ -20,35 +20,50 @@
20
20
  * table but marked `visibility: "hide"` there, so they're deliberately left
21
21
  * out of this picker too.
22
22
  *
23
+ * Every entry also carries a `minimal_client_version`. The GPT-6 family needs
24
+ * 0.153 (`gpt-6-astra`, `gpt-6.1-sol`) or 0.155 (`gpt-6-sol`, `gpt-6-luna`), so
25
+ * this list must never run ahead of the pinned SDK: a model picked here that
26
+ * the bundled CLI is too old for fails at runtime, not at type-check.
27
+ *
23
28
  * Models tagged `requiresAuthMode` are filtered by the chat-input account
24
29
  * picker so the user can't pick a ChatGPT-only model while signed in with an
25
30
  * API key account (and vice versa).
26
31
  */
27
32
 
33
+ import type { ModelReasoningEffort } from '@openai/codex-sdk';
28
34
  import type { EngineModel, ReasoningControl } from '$shared/types/unified';
29
35
  import { toReasoningOptions } from '$shared/constants/engines';
30
36
 
31
37
  /**
32
- * Codex's reasoning knob is the `model_reasoning_effort` config value. The
33
- * levels are per-model now: the 5.6 family added `max` and `ultra` above
38
+ * Codex's reasoning knob is the SDK `modelReasoningEffort` thread option. The
39
+ * levels are per-model: the 5.6 and 6 families reach `max` or `ultra` above
34
40
  * `xhigh`, and `minimal` is no longer accepted by any current model.
35
41
  *
36
- * `max` and `ultra` sit past the SDK's `ModelReasoningEffort` union, which
37
- * still stops at `xhigh` in 0.147 — see `resolveCodexEffort` for why sending
38
- * them anyway is sound.
42
+ * Typed against the SDK union so a level the SDK doesn't know is a compile
43
+ * error here rather than a cast at the call site.
39
44
  */
40
- const EFFORTS_TO_ULTRA = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
41
- const EFFORTS_TO_MAX = ['low', 'medium', 'high', 'xhigh', 'max'];
42
- const EFFORTS_TO_XHIGH = ['low', 'medium', 'high', 'xhigh'];
45
+ const EFFORTS_TO_ULTRA: ModelReasoningEffort[] = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
46
+ const EFFORTS_TO_MAX: ModelReasoningEffort[] = ['low', 'medium', 'high', 'xhigh', 'max'];
47
+ const EFFORTS_TO_XHIGH: ModelReasoningEffort[] = ['low', 'medium', 'high', 'xhigh'];
43
48
 
44
- function codexReasoning(levels: string[], fallback: string): ReasoningControl {
49
+ function codexReasoning(levels: ModelReasoningEffort[], fallback: ModelReasoningEffort): ReasoningControl {
45
50
  return { levels: toReasoningOptions(levels), default: fallback };
46
51
  }
47
52
 
53
+ /**
54
+ * The table carries two windows per model: `context_window` (272k, what the
55
+ * CLI uses by default) and `max_context_window` (872k for the 5.6 and 6
56
+ * families, 272k for `gpt-5.5`). Clopen runs every model at its max — see
57
+ * `CODEX_CONTEXT_WINDOW_REQUEST` — so the catalog reports the max.
58
+ */
59
+ const WINDOW_872K = 872_000;
60
+ const WINDOW_272K = 272_000;
61
+
48
62
  /** Shared shape for a Codex catalog entry; `reasoning: null` = no reasoning knob. */
49
63
  function codexModel(
50
64
  id: string,
51
65
  name: string,
66
+ contextWindow: number,
52
67
  reasoning: ReasoningControl | null,
53
68
  extra?: { image?: boolean; requiresAuthMode?: 'chatgpt' },
54
69
  ): EngineModel {
@@ -59,8 +74,7 @@ function codexModel(
59
74
  model: { id, name },
60
75
  account: { id: 0, name: '' },
61
76
  },
62
- // Every preset in the table reports a 272k context window.
63
- limit: { input: 272_000, output: 128_000 },
77
+ limit: { input: contextWindow, output: 128_000 },
64
78
  modalities: {
65
79
  input: { text: true, image: extra?.image ?? true, audio: false, video: false, pdf: false },
66
80
  output: { text: true, image: false, audio: false, video: false, pdf: false },
@@ -78,15 +92,29 @@ function codexModel(
78
92
 
79
93
  /** Ordered by the CLI's own `priority` field, so the picker matches Codex's. */
80
94
  export const CODEX_MODELS: EngineModel[] = [
81
- codexModel('gpt-6-astra', 'GPT-6-Astra', codexReasoning(EFFORTS_TO_ULTRA, 'low')),
82
- codexModel('gpt-6-sol', 'GPT-6-Sol', codexReasoning(EFFORTS_TO_ULTRA, 'medium')),
83
- codexModel('gpt-6-luna', 'GPT-6-Luna', codexReasoning(EFFORTS_TO_MAX, 'medium')),
84
- codexModel('gpt-5.6-sol', 'GPT-5.6-Sol', codexReasoning(EFFORTS_TO_ULTRA, 'low')),
85
- codexModel('gpt-5.6-terra', 'GPT-5.6-Terra', codexReasoning(EFFORTS_TO_ULTRA, 'medium')),
86
- codexModel('gpt-5.6-luna', 'GPT-5.6-Luna', codexReasoning(EFFORTS_TO_MAX, 'medium')),
87
- codexModel('gpt-5.5', 'GPT-5.5', codexReasoning(EFFORTS_TO_XHIGH, 'medium')),
95
+ codexModel('gpt-6.1-sol', 'GPT-6.1-Sol', WINDOW_872K, codexReasoning(EFFORTS_TO_ULTRA, 'low')),
96
+ codexModel('gpt-6-astra', 'GPT-6-Astra', WINDOW_872K, codexReasoning(EFFORTS_TO_ULTRA, 'low')),
97
+ codexModel('gpt-6-sol', 'GPT-6-Sol', WINDOW_872K, codexReasoning(EFFORTS_TO_ULTRA, 'medium')),
98
+ codexModel('gpt-6-luna', 'GPT-6-Luna', WINDOW_872K, codexReasoning(EFFORTS_TO_MAX, 'medium')),
99
+ codexModel('gpt-5.6-sol', 'GPT-5.6-Sol', WINDOW_872K, codexReasoning(EFFORTS_TO_ULTRA, 'low')),
100
+ codexModel('gpt-5.6-terra', 'GPT-5.6-Terra', WINDOW_872K, codexReasoning(EFFORTS_TO_ULTRA, 'medium')),
101
+ codexModel('gpt-5.6-luna', 'GPT-5.6-Luna', WINDOW_872K, codexReasoning(EFFORTS_TO_MAX, 'medium')),
102
+ codexModel('gpt-5.5', 'GPT-5.5', WINDOW_272K, codexReasoning(EFFORTS_TO_XHIGH, 'medium')),
88
103
  ];
89
104
 
105
+ /**
106
+ * The `model_context_window` sent to the CLI. Without it the CLI stays at each
107
+ * model's 272k `context_window` even where the model reaches 872k.
108
+ *
109
+ * The SDK bakes `config` into the client once, while the model changes per
110
+ * turn, so this is one value for every model: the largest window in the
111
+ * catalog. That is sound because the CLI clamps the request to the active
112
+ * model's `max_context_window` — verified against 0.159.3, where 872k on
113
+ * `gpt-5.5` reported a 272k window and 2M on `gpt-5.6-luna` reported 872k
114
+ * (each less the CLI's 5% reserve).
115
+ */
116
+ export const CODEX_CONTEXT_WINDOW_REQUEST = Math.max(...CODEX_MODELS.map(model => model.limit.input));
117
+
90
118
  /**
91
119
  * Resolve the `model_reasoning_effort` to send for a turn: the requested level
92
120
  * when that model accepts it, otherwise that model's own default, otherwise
@@ -95,19 +123,14 @@ export const CODEX_MODELS: EngineModel[] = [
95
123
  * This is the only gate on the value. The picker offers per-model levels, but a
96
124
  * stored preference outlives a catalog change, so a level that is no longer
97
125
  * valid (`minimal`, or `ultra` on a model that caps at `max`) must not reach
98
- * the CLI.
99
- *
100
- * The return type is deliberately `string`, not the SDK's
101
- * `ModelReasoningEffort`. That union still stops at `xhigh` in
102
- * @openai/codex-sdk 0.147 while the CLI it drives accepts
103
- * `none|minimal|low|medium|high|xhigh|max|ultra`, and the SDK does not validate
104
- * — it interpolates the value straight into
105
- * `--config model_reasoning_effort="…"` (`dist/index.js`). Narrowing to the
106
- * stale union would make `max` and `ultra`, the top levels of GPT-5.6 Sol and
107
- * Terra, unreachable from Clopen. The caller casts at the SDK boundary.
126
+ * the CLI — the SDK does not validate, it interpolates the value straight into
127
+ * `--config model_reasoning_effort="…"`.
108
128
  */
109
- export function resolveCodexEffort(modelId: string | undefined, requested: string | undefined): string {
129
+ export function resolveCodexEffort(modelId: string | undefined, requested: string | undefined): ModelReasoningEffort {
110
130
  const control = CODEX_MODELS.find(m => m.engine.model.id === modelId)?.capabilities.reasoningControl;
111
- if (requested && control?.levels.some(level => level.value === requested)) return requested;
112
- return control?.default ?? 'medium';
131
+ const accepts = (value: string | undefined): value is ModelReasoningEffort =>
132
+ value !== undefined && (control?.levels.some(level => level.value === value) ?? false);
133
+ if (accepts(requested)) return requested;
134
+ if (accepts(control?.default)) return control.default;
135
+ return 'medium';
113
136
  }
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, test } from 'bun:test';
2
2
  import type { FileChangeSet } from './patch-rollout';
3
- import { parseUnifiedDiff, findMatchingFileChangeSet } from './patch-rollout';
3
+ import { parseUnifiedDiff, findMatchingFileChangeSet, parseFileChangeSets } from './patch-rollout';
4
4
 
5
5
  describe('parseUnifiedDiff', () => {
6
6
  test('splits a single hunk into before/after text', () => {
@@ -86,3 +86,38 @@ describe('findMatchingFileChangeSet', () => {
86
86
  expect(findMatchingFileChangeSet([], ['/repo/a.ts'])).toBeNull();
87
87
  });
88
88
  });
89
+
90
+ describe('parseFileChangeSets', () => {
91
+ const changes = {
92
+ '/repo/style.css': { type: 'update', unified_diff: '@@ -1,2 +1,2 @@\n-color: red;\n+color: blue;\n', move_path: null },
93
+ '/repo/notes.md': { type: 'add', content: '# Notes\n' }
94
+ };
95
+ const expected: FileChangeSet = new Map([
96
+ ['/repo/style.css', { kind: 'update', oldString: 'color: red;\n', newString: 'color: blue;\n', content: '' }],
97
+ ['/repo/notes.md', { kind: 'add', oldString: '', newString: '', content: '# Notes\n' }]
98
+ ]);
99
+
100
+ test('reads the completed FileChange item the 0.159 CLI writes', () => {
101
+ const line = JSON.stringify({
102
+ type: 'event_msg',
103
+ payload: { type: 'item_completed', item: { type: 'FileChange', status: 'completed', changes } }
104
+ });
105
+ expect(parseFileChangeSets(line)).toEqual([expected]);
106
+ });
107
+
108
+ test('still reads the legacy patch_apply_end event', () => {
109
+ const line = JSON.stringify({ type: 'event_msg', payload: { type: 'patch_apply_end', success: true, changes } });
110
+ expect(parseFileChangeSets(line)).toEqual([expected]);
111
+ });
112
+
113
+ test('keeps file order and skips unrelated or malformed lines', () => {
114
+ const legacy = JSON.stringify({ type: 'event_msg', payload: { type: 'patch_apply_end', changes: { '/repo/a.ts': { type: 'delete' } } } });
115
+ const other = JSON.stringify({ type: 'event_msg', payload: { type: 'item_completed', item: { type: 'AgentMessage' } } });
116
+ const current = JSON.stringify({ type: 'event_msg', payload: { type: 'item_completed', item: { type: 'FileChange', changes } } });
117
+ const sets = parseFileChangeSets([legacy, other, '{"FileChange": broken', '', current].join('\n'));
118
+
119
+ expect(sets).toHaveLength(2);
120
+ expect(sets[0]?.get('/repo/a.ts')?.kind).toBe('delete');
121
+ expect(sets[1]).toEqual(expected);
122
+ });
123
+ });
@@ -8,18 +8,27 @@
8
8
  * `oldString` / `newString` / `content` fields would always be empty.
9
9
  *
10
10
  * The Codex CLI does write the real contents to the rollout JSONL at
11
- * `<codex-home>/sessions/YYYY/MM/DD/rollout-*-<thread_id>.jsonl` as a
12
- * `patch_apply_end` event, emitted just before the SDK's `file_change` item:
11
+ * `<codex-home>/sessions/YYYY/MM/DD/rollout-*-<thread_id>.jsonl`, just before
12
+ * the SDK's `file_change` item. The event carrying them changed between CLI
13
+ * 0.147 and 0.159:
13
14
  *
15
+ * 0.159 — a completed `FileChange` item:
16
+ * {"type":"event_msg","payload":{"type":"item_completed",
17
+ * "item":{"type":"FileChange","status":"completed","changes":{…}}}}
18
+ *
19
+ * 0.147 — a dedicated patch event (still read for older rollouts, which a
20
+ * resumed thread carries forward):
14
21
  * {"type":"event_msg","payload":{"type":"patch_apply_end","success":true,
15
- * "changes":{
16
- * "/abs/path.css": {"type":"update","unified_diff":"@@ -1,3 +1,3 @@\n …"},
17
- * "/abs/new.md": {"type":"add","content":"# New file\n…"}
18
- * }}}
22
+ * "changes":{…}}}
23
+ *
24
+ * Both share the same `changes` shape:
25
+ *
26
+ * {"/abs/path.css": {"type":"update","unified_diff":"@@ -1,3 +1,3 @@\n …"},
27
+ * "/abs/new.md": {"type":"add","content":"# New file\n…"}}
19
28
  *
20
- * We read the rollout, collect every `patch_apply_end`, and look up the
21
- * latest one whose change-paths match the live `FileChangeItem` so the Edit
22
- * and Write blocks can be filled with the real content.
29
+ * We read the rollout, collect every change set, and look up the latest one
30
+ * whose change-paths match the live `FileChangeItem` so the Edit and Write
31
+ * blocks can be filled with the real content.
23
32
  *
24
33
  * TODO(codex-sdk): once `@openai/codex-sdk` exposes per-change content on
25
34
  * `FileUpdateChange` natively (e.g. `unifiedDiff`/`content`), delete this
@@ -44,11 +53,11 @@ export interface FileChangeContent {
44
53
  content: string;
45
54
  }
46
55
 
47
- /** One `patch_apply_end` event: absolute file path → recovered content. */
56
+ /** One applied patch: absolute file path → recovered content. */
48
57
  export type FileChangeSet = Map<string, FileChangeContent>;
49
58
 
50
59
  /**
51
- * Shape of `payload.changes[path]` in a `patch_apply_end` rollout event.
60
+ * Shape of one `changes[path]` entry in a rollout patch event.
52
61
  * Undocumented CLI-internal format — every field is treated as optional.
53
62
  */
54
63
  interface RolloutFileChange {
@@ -117,8 +126,45 @@ function toFileChangeContent(change: RolloutFileChange): FileChangeContent | nul
117
126
  }
118
127
 
119
128
  /**
120
- * Read every `patch_apply_end` event from the rollout file in chronological
129
+ * The `changes` map of one rollout line, when that line records an applied
130
+ * patch in either the current (`item_completed` + `FileChange`) or the legacy
131
+ * (`patch_apply_end`) format. Anything else returns null.
132
+ */
133
+ function changesOfRolloutLine(line: string): Record<string, RolloutFileChange> | null {
134
+ if (!line.includes('"FileChange"') && !line.includes('"patch_apply_end"')) return null;
135
+ try {
136
+ const payload = JSON.parse(line)?.payload;
137
+ if (payload?.type === 'item_completed' && payload.item?.type === 'FileChange') {
138
+ return payload.item.changes ?? null;
139
+ }
140
+ if (payload?.type === 'patch_apply_end') {
141
+ return payload.changes ?? null;
142
+ }
143
+ } catch { /* malformed line — skip */ }
144
+ return null;
145
+ }
146
+
147
+ /**
148
+ * Collect every applied patch from rollout JSONL content in chronological
121
149
  * (file) order. Each entry maps an absolute path → recovered content.
150
+ */
151
+ export function parseFileChangeSets(rolloutContent: string): FileChangeSet[] {
152
+ const changeSets: FileChangeSet[] = [];
153
+ for (const line of rolloutContent.split('\n')) {
154
+ const changes = changesOfRolloutLine(line);
155
+ if (!changes) continue;
156
+ const changeSet: FileChangeSet = new Map();
157
+ for (const [path, raw] of Object.entries(changes)) {
158
+ const recovered = toFileChangeContent(raw ?? {});
159
+ if (recovered) changeSet.set(path, recovered);
160
+ }
161
+ if (changeSet.size > 0) changeSets.push(changeSet);
162
+ }
163
+ return changeSets;
164
+ }
165
+
166
+ /**
167
+ * Read every applied patch from the thread's rollout file.
122
168
  *
123
169
  * Returns an empty array if the rollout file isn't found or the read fails —
124
170
  * callers should fall back to leaving the content fields empty.
@@ -127,33 +173,18 @@ export function readFileChangeSetsFromRollout(threadId: string): FileChangeSet[]
127
173
  const file = findRolloutFile(threadId);
128
174
  if (!file) return [];
129
175
 
130
- const changeSets: FileChangeSet[] = [];
131
176
  try {
132
- const content = fs.readFileSync(file, 'utf-8');
133
- for (const line of content.split('\n')) {
134
- if (!line || !line.includes('"patch_apply_end"')) continue;
135
- try {
136
- const payload = JSON.parse(line)?.payload;
137
- if (payload?.type !== 'patch_apply_end' || !payload.changes) continue;
138
- const changeSet: FileChangeSet = new Map();
139
- for (const [path, raw] of Object.entries(payload.changes as Record<string, RolloutFileChange>)) {
140
- const recovered = toFileChangeContent(raw ?? {});
141
- if (recovered) changeSet.set(path, recovered);
142
- }
143
- if (changeSet.size > 0) changeSets.push(changeSet);
144
- } catch { /* malformed line — skip */ }
145
- }
177
+ return parseFileChangeSets(fs.readFileSync(file, 'utf-8'));
146
178
  } catch (err) {
147
179
  debug.warn('engine', `Codex patch-rollout: failed to read ${file}:`, err);
148
180
  return [];
149
181
  }
150
- return changeSets;
151
182
  }
152
183
 
153
184
  /**
154
185
  * Pick the change set that best matches the paths in the current
155
186
  * `FileChangeItem`. Walks from the end of the list (most recent first) so the
156
- * newest matching `patch_apply_end` wins — that's the one whose SDK
187
+ * newest matching patch wins — that's the one whose SDK
157
188
  * `file_change` event we just received.
158
189
  *
159
190
  * Reading the rollout fresh on every `file_change` keeps this correct when a
@@ -28,6 +28,11 @@
28
28
  * one line — the same pattern Claude (`forkSession: true`) and OpenCode
29
29
  * (`client.session.fork()`) already use.
30
30
  *
31
+ * The CLI grew `codex exec fork <id>` in 0.148, but the SDK (0.159) still
32
+ * only spawns `exec` and `exec resume`, so it is not reachable from here.
33
+ * Copy-and-resume was re-verified on 0.159.3: the forked id resumes with the
34
+ * source's history intact.
35
+ *
31
36
  * Cross-account note: `~/.codex/sessions/` is shared across ChatGPT
32
37
  * accounts. A session forked under account A is readable by account B if
33
38
  * accounts swap. That matches running the Codex CLI manually with two
@@ -19,7 +19,7 @@
19
19
  * `backend/ws/chat/stream.ts` to it — same pattern as Claude/OpenCode.
20
20
  */
21
21
 
22
- import type { Codex, Thread, ThreadOptions, Input as CodexInput, ModelReasoningEffort } from '@openai/codex-sdk';
22
+ import type { Codex, Thread, ThreadOptions, Input as CodexInput } from '@openai/codex-sdk';
23
23
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
24
24
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
25
25
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
@@ -28,12 +28,13 @@ import { engineQueries } from '$backend/database/queries/engine-queries';
28
28
  import { resolveOsPath } from '$backend/utils/paths';
29
29
  import { resolveEngineCli } from '$backend/engine/engine-cli';
30
30
  import { getCleanSpawnEnv } from '$backend/utils/index.js';
31
- import { getCodexMcpConfig } from '../../../mcp';
31
+ import { getCodexMcpConfig, getTrustedProjectServers } from '../../../mcp';
32
32
  import { EngineRuns } from '../run-registry';
33
33
  import { artifactFilter } from '$backend/profiles';
34
34
  import { syncSkills } from '$backend/skills';
35
35
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
36
- import { CODEX_MODELS, resolveCodexEffort } from './models';
36
+ import { resolveProjectBridge } from '$backend/artifacts/project';
37
+ import { CODEX_CONTEXT_WINDOW_REQUEST, CODEX_MODELS, resolveCodexEffort } from './models';
37
38
  import { debug } from '$shared/utils/logger';
38
39
  import { handleStreamError, buildTurnError } from './error-handler';
39
40
  import {
@@ -135,8 +136,20 @@ export class CodexEngine implements AIEngine {
135
136
  return this.runs.isActive;
136
137
  }
137
138
 
139
+ /**
140
+ * Identity of the MCP set baked into the client: the Profile's connector
141
+ * filter plus the project's approved `.agents/mcp.json` servers. Approving,
142
+ * revoking or editing that file changes the key, so the next turn rebuilds
143
+ * the client instead of serving a stale server list.
144
+ */
145
+ private mcpKeyFor(mcpProfileFilter: Set<string> | undefined, projectId: string | null): string {
146
+ const filterKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
147
+ const projectKey = getTrustedProjectServers(projectId).map(s => s.namespace).sort().join(',');
148
+ return `${filterKey}|${projectKey}`;
149
+ }
150
+
138
151
  async initialize(accountId?: number, mcpProfileFilter?: Set<string>): Promise<void> {
139
- const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
152
+ const mcpKey = this.mcpKeyFor(mcpProfileFilter, this.pendingProjectId);
140
153
  if (this._isInitialized && (accountId == null || accountId === this.currentAccountId) && mcpKey === this.currentMcpFilterKey) {
141
154
  return;
142
155
  }
@@ -167,8 +180,9 @@ export class CodexEngine implements AIEngine {
167
180
  const mcpConfig = getCodexMcpConfig(mcpProfileFilter, projectId ? { projectId } : undefined);
168
181
 
169
182
  // Codex SDK takes config at construction. We pass `show_raw_agent_reasoning`
170
- // (so the SDK forwards reasoning text events) and forward the Clopen MCP
171
- // HTTP endpoint to the spawned subprocess. Sandbox is disabled at the
183
+ // (so the SDK forwards reasoning text events), lift the context window to
184
+ // each model's max (`CODEX_CONTEXT_WINDOW_REQUEST`), and forward the Clopen
185
+ // MCP HTTP endpoint to the spawned subprocess. Sandbox is disabled at the
172
186
  // thread level (`sandboxMode: 'danger-full-access'`) to match the trust
173
187
  // model of every other engine in this repo — Claude bypasses permissions,
174
188
  // OpenCode auto-approves every permission event, Copilot uses `approveAll`,
@@ -186,6 +200,7 @@ export class CodexEngine implements AIEngine {
186
200
  env: { ...getCleanSpawnEnv(), CODEX_HOME: getCodexHomeDir(), ...this.pendingGitIdentityEnv },
187
201
  config: {
188
202
  show_raw_agent_reasoning: true,
203
+ model_context_window: CODEX_CONTEXT_WINDOW_REQUEST,
189
204
  ...(Object.keys(mcpConfig).length > 0 ? { mcp_servers: mcpConfig } : {}),
190
205
  },
191
206
  });
@@ -217,9 +232,8 @@ export class CodexEngine implements AIEngine {
217
232
  const { projectPath, prompt, resume, modelId, reasoningEffort, abortController, accountId } = options;
218
233
 
219
234
  // Per-model reasoning levels live in the catalog, which is derived from the
220
- // CLI's own preset table — see `resolveCodexEffort` for the validity rules
221
- // and for why the SDK's narrower `ModelReasoningEffort` union is cast past.
222
- const modelReasoningEffort = resolveCodexEffort(modelId, reasoningEffort) as ModelReasoningEffort;
235
+ // CLI's own preset table — see `resolveCodexEffort` for the validity rules.
236
+ const modelReasoningEffort = resolveCodexEffort(modelId, reasoningEffort);
223
237
 
224
238
  // Active Profile for this stream — scopes the materialized artifact set AND
225
239
  // (below) the MCP connector set baked into the Codex client.
@@ -234,7 +248,7 @@ export class CodexEngine implements AIEngine {
234
248
  // Qwen/Copilot do per stream); `undefined` = unfiltered → no change for the
235
249
  // common no-profile path.
236
250
  const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
237
- const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
251
+ const mcpKey = this.mcpKeyFor(mcpProfileFilter, options.mcpContext?.projectId ?? null);
238
252
  const accountChanged = this._isInitialized && accountId != null && accountId !== this.currentAccountId;
239
253
  const mcpChanged = this._isInitialized && mcpKey !== this.currentMcpFilterKey;
240
254
  // A client built without a project (the bare `initialize()` the engine
@@ -319,7 +333,11 @@ export class CodexEngine implements AIEngine {
319
333
  // Prompt-scoped engine: advertise the profile-scoped Skills/Commands/
320
334
  // Subagents PER-SESSION via the prompt (not the shared global AGENTS.md /
321
335
  // persistent client) so the active Profile scopes them correctly.
322
- const artifactsContext = buildArtifactsPromptContext('codex', profileId);
336
+ // Codex reads AGENTS.md and `.agents/skills` itself; anything else the
337
+ // repo carries (e.g. `.claude/skills`, the Clopen-only project block)
338
+ // rides the same per-turn prompt context.
339
+ const projectBridge = await resolveProjectBridge('codex', resolvedProjectPath, options.mcpContext?.projectId);
340
+ const artifactsContext = buildArtifactsPromptContext('codex', profileId, projectBridge);
323
341
  const input = await buildCodexInput(prompt, artifactsContext || undefined);
324
342
  const { events } = await thread.runStreamed(input, {
325
343
  signal: controller.signal,
@@ -0,0 +1,40 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { CopilotClient, ModelInfo } from '@github/copilot-sdk';
3
+ import { fetchCopilotModels } from './models';
4
+
5
+ function clientReturning(result: ModelInfo[] | Error): CopilotClient {
6
+ return {
7
+ listModels: async () => {
8
+ if (result instanceof Error) throw result;
9
+ return result;
10
+ }
11
+ } as unknown as CopilotClient;
12
+ }
13
+
14
+ const ids = (models: { engine: { model: { id: string } } }[]) => models.map(m => m.engine.model.id);
15
+
16
+ describe('fetchCopilotModels', () => {
17
+ test('a Copilot Free account with no picker-enabled models still gets Auto', async () => {
18
+ const { models } = await fetchCopilotModels(clientReturning([]), null);
19
+ expect(ids(models)).toEqual(['auto']);
20
+ });
21
+
22
+ test('Auto leads the catalog and is never duplicated', async () => {
23
+ const gpt = { id: 'gpt-6-luna', name: 'GPT-6 Luna', capabilities: {} } as ModelInfo;
24
+ expect(ids((await fetchCopilotModels(clientReturning([gpt]), null)).models)).toEqual(['auto', 'gpt-6-luna']);
25
+
26
+ const auto = { id: 'auto', name: 'Auto', capabilities: {} } as ModelInfo;
27
+ expect(ids((await fetchCopilotModels(clientReturning([auto, gpt]), null)).models)).toEqual(['auto', 'gpt-6-luna']);
28
+ });
29
+
30
+ test('a rejected token surfaces as an actionable error instead of an empty list', async () => {
31
+ const failure = new Error('Request models.list failed with message: Not authenticated. Please authenticate first.');
32
+ expect(fetchCopilotModels(clientReturning(failure), null)).rejects.toThrow('Settings → Engines → Copilot');
33
+ });
34
+
35
+ test('a fine-grained PAT the models endpoint refuses falls back to Auto', async () => {
36
+ const failure = new Error('Personal Access Tokens are not supported for this endpoint');
37
+ const { models } = await fetchCopilotModels(clientReturning(failure), null);
38
+ expect(ids(models)).toEqual(['auto']);
39
+ });
40
+ });
@@ -2,10 +2,13 @@
2
2
  * Copilot dynamic model discovery.
3
3
  *
4
4
  * Wraps `CopilotClient.listModels()` and translates `ModelInfo[]` into
5
- * `EngineModel[]`. Returns `[]` on any failure with a friendly error
6
- * message logged via `summariseModelsError` — common 4xx responses (PAT
7
- * missing the "Copilot Requests" scope, fine-grained PAT not accepted)
8
- * are mapped to actionable hints for the server log.
5
+ * `EngineModel[]`, always led by an `Auto` entry (see `AUTO_MODEL`).
6
+ *
7
+ * Failures are thrown, not returned as `[]`: an empty catalog renders as "No
8
+ * models available for this engine", which hid the real cause — most often a
9
+ * token GitHub no longer accepts — behind a message nobody could act on. The
10
+ * thrown text reaches the model picker, which offers to open Copilot's
11
+ * account settings.
9
12
  */
10
13
 
11
14
  import type { CopilotClient, ModelInfo } from '@github/copilot-sdk';
@@ -13,41 +16,65 @@ import type { EngineModel, ReasoningControl } from '$shared/types/unified';
13
16
  import { toReasoningOptions } from '$shared/constants/engines';
14
17
  import { debug } from '$shared/utils/logger';
15
18
 
19
+ /**
20
+ * Copilot's own router. `models.list` only returns models whose CAPI entry is
21
+ * `model_picker_enabled`, and on Copilot Free none are — every model there is
22
+ * reached through Auto, which the runtime still accepts as a session model
23
+ * (runtime 1.0.90 routes it to an entitled model, e.g. `gpt-6-luna`). The 1.0.79
24
+ * runtime injected this entry itself; 1.0.90 no longer does, so without it a
25
+ * Free account has nothing to pick at all.
26
+ */
27
+ const AUTO_MODEL: ModelInfo = {
28
+ id: 'auto',
29
+ name: 'Auto',
30
+ capabilities: { supports: {}, limits: { max_context_window_tokens: 0 } },
31
+ } as ModelInfo;
32
+
16
33
  export async function fetchCopilotModels(
17
34
  client: CopilotClient,
18
35
  cache: ModelInfo[] | null,
19
36
  ): Promise<{ models: EngineModel[]; cache: ModelInfo[] | null }> {
20
- try {
21
- const infos = cache ?? await client.listModels();
22
- return {
23
- models: infos.map(info => mapModelInfoToEngineModel(info)),
24
- cache: infos,
25
- };
26
- } catch (error) {
27
- debug.warn('engine', `Copilot models unavailable: ${summariseModelsError(error)}`);
28
- return { models: [], cache };
37
+ let infos = cache;
38
+ if (!infos) {
39
+ try {
40
+ infos = withAuto(await client.listModels());
41
+ } catch (error) {
42
+ const raw = error instanceof Error ? error.message : String(error);
43
+ // The models endpoint refuses fine-grained PATs that chat accepts, so
44
+ // Auto is still a working choice — offer it instead of failing.
45
+ if (raw.includes('Personal Access Tokens are not supported')) {
46
+ debug.warn('engine', 'Copilot models.list rejects fine-grained PATs; offering Auto only');
47
+ infos = [AUTO_MODEL];
48
+ } else {
49
+ throw new Error(summariseModelsError(raw));
50
+ }
51
+ }
29
52
  }
53
+ return { models: infos.map(info => mapModelInfoToEngineModel(info)), cache: infos };
54
+ }
55
+
56
+ function withAuto(infos: ModelInfo[]): ModelInfo[] {
57
+ return infos.some(info => info.id === AUTO_MODEL.id) ? infos : [AUTO_MODEL, ...infos];
30
58
  }
31
59
 
32
60
  /**
33
- * Build a one-line, human-readable summary of a models.list failure for the
34
- * server log. Strips the JSON-RPC stack frame noise and maps known GitHub
35
- * Copilot 4xx responses to actionable hints.
61
+ * Turn a models.list failure into one actionable sentence for the picker.
62
+ * Strips the JSON-RPC stack noise and maps known GitHub Copilot responses.
36
63
  */
37
- function summariseModelsError(error: unknown): string {
38
- const raw = error instanceof Error ? error.message : String(error);
39
- const firstLine = raw.split('\n')[0]?.trim() || raw;
64
+ function summariseModelsError(raw: string): string {
65
+ const firstLine = raw.split('\n')[0]?.replace(/^Request models\.list failed with message:\s*/, '').trim() || raw;
66
+ const fix = 'Update the token in Settings → Engines → Copilot.';
40
67
 
41
- if (raw.includes('Personal Access Tokens are not supported')) {
42
- return 'the models.list endpoint does not accept fine-grained PATs (chat will still work if the PAT has Copilot Requests).';
68
+ if (raw.includes('Not authenticated')) {
69
+ return `GitHub rejected the Copilot account's token — it is invalid, expired or revoked. ${fix}`;
43
70
  }
44
71
  if (raw.includes('Copilot Requests')) {
45
- return 'PAT is missing the "Copilot Requests" permission.';
72
+ return `The Copilot token is missing the "Copilot Requests" permission. ${fix}`;
46
73
  }
47
74
  if (raw.includes('401') || raw.toLowerCase().includes('unauthorized')) {
48
- return 'unauthorized — check that the GitHub PAT is valid and has Copilot access.';
75
+ return `GitHub refused the Copilot token. Check that it is valid and has Copilot access. ${fix}`;
49
76
  }
50
- return firstLine;
77
+ return `Could not load Copilot models: ${firstLine}`;
51
78
  }
52
79
 
53
80
  /**
@@ -0,0 +1,47 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { PermissionRequest } from '@github/copilot-sdk';
3
+ import { buildCopilotManagedSettings, enforceCopilotPermission } from './permissions';
4
+
5
+ describe('buildCopilotManagedSettings', () => {
6
+ test('returns undefined when the policy restricts nothing', () => {
7
+ expect(buildCopilotManagedSettings({ allow: [], deny: [] })).toBeUndefined();
8
+ });
9
+
10
+ test('denies the families the deny list names', () => {
11
+ expect(buildCopilotManagedSettings({ allow: [], deny: ['shell', 'write'] })).toEqual({
12
+ permissions: { deny: ['Shell', 'Write'] }
13
+ });
14
+ });
15
+
16
+ test('denies the families an allowlist leaves out', () => {
17
+ expect(buildCopilotManagedSettings({ allow: ['read', 'url'], deny: [] })).toEqual({
18
+ permissions: { deny: ['Shell', 'Write'] }
19
+ });
20
+ });
21
+
22
+ test('never emits a family the runtime rejects', () => {
23
+ // url / memory / MCP rules fail session creation on the runtime, so a
24
+ // policy that only touches them must leave the managed layer empty.
25
+ expect(buildCopilotManagedSettings({ allow: [], deny: ['url', 'memory', 'mcp__clopen__*'] })).toBeUndefined();
26
+ });
27
+
28
+ test('honours wildcard patterns', () => {
29
+ expect(buildCopilotManagedSettings({ allow: [], deny: ['*'] })).toEqual({
30
+ permissions: { deny: ['Shell', 'Write', 'Read'] }
31
+ });
32
+ });
33
+ });
34
+
35
+ describe('enforceCopilotPermission', () => {
36
+ const request = (data: Record<string, unknown>) => data as unknown as PermissionRequest;
37
+
38
+ test('rejects a denied kind', () => {
39
+ expect(enforceCopilotPermission({ allow: [], deny: ['url'] }, request({ kind: 'url' }))?.kind).toBe('reject');
40
+ });
41
+
42
+ test('matches MCP tools by tool name rather than kind', () => {
43
+ const policy = { allow: [], deny: ['mcp__github__*'] };
44
+ expect(enforceCopilotPermission(policy, request({ kind: 'mcp', toolName: 'mcp__github__get_me' }))?.kind).toBe('reject');
45
+ expect(enforceCopilotPermission(policy, request({ kind: 'mcp', toolName: 'mcp__clopen__x' }))).toBeNull();
46
+ });
47
+ });