@myrialabs/clopen 0.4.45 → 0.4.47

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 (73) hide show
  1. package/backend/artifacts/project/sources.ts +2 -2
  2. package/backend/engine/adapters/claude/models.test.ts +49 -0
  3. package/backend/engine/adapters/claude/models.ts +81 -562
  4. package/backend/engine/adapters/claude/stream.ts +5 -4
  5. package/backend/engine/adapters/cline/credential.ts +42 -18
  6. package/backend/engine/adapters/cline/message-converter.ts +31 -1
  7. package/backend/engine/adapters/cline/models.test.ts +77 -0
  8. package/backend/engine/adapters/cline/models.ts +89 -3
  9. package/backend/engine/adapters/cline/presets.ts +5 -0
  10. package/backend/engine/adapters/cline/stream.ts +9 -2
  11. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  12. package/backend/engine/adapters/codex/models.ts +54 -31
  13. package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
  14. package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
  15. package/backend/engine/adapters/codex/session-fork.ts +5 -0
  16. package/backend/engine/adapters/codex/stream.ts +8 -7
  17. package/backend/engine/adapters/copilot/models.test.ts +40 -0
  18. package/backend/engine/adapters/copilot/models.ts +51 -24
  19. package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
  20. package/backend/engine/adapters/copilot/permissions.ts +72 -0
  21. package/backend/engine/adapters/copilot/stream.ts +77 -67
  22. package/backend/engine/adapters/cursor/stream.ts +8 -4
  23. package/backend/engine/adapters/opencode/presets.ts +27 -2
  24. package/backend/engine/adapters/opencode/server.ts +6 -4
  25. package/backend/engine/adapters/pi/credential.test.ts +83 -0
  26. package/backend/engine/adapters/pi/credential.ts +68 -12
  27. package/backend/engine/adapters/pi/environment.ts +9 -5
  28. package/backend/engine/adapters/pi/mcp.test.ts +194 -0
  29. package/backend/engine/adapters/pi/mcp.ts +88 -0
  30. package/backend/engine/adapters/pi/message-converter.ts +6 -4
  31. package/backend/engine/adapters/pi/presets.ts +10 -5
  32. package/backend/engine/adapters/pi/stream.ts +42 -38
  33. package/backend/engine/adapters/qwen/environment.ts +39 -2
  34. package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
  35. package/backend/engine/adapters/qwen/message-converter.ts +40 -23
  36. package/backend/engine/adapters/qwen/models.test.ts +25 -0
  37. package/backend/engine/adapters/qwen/models.ts +42 -5
  38. package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
  39. package/backend/engine/adapters/qwen/session-store.ts +66 -0
  40. package/backend/engine/adapters/qwen/stream.ts +110 -87
  41. package/backend/engine/docs/adapter-contract.md +7 -4
  42. package/backend/engine/docs/lessons-learned.md +405 -62
  43. package/backend/engine/docs/quick-reference.md +2 -2
  44. package/backend/engine/docs/stack.md +17 -4
  45. package/backend/engine/docs/websocket-routes.md +5 -5
  46. package/backend/engine/install-recipes.test.ts +105 -5
  47. package/backend/engine/install-recipes.ts +102 -42
  48. package/backend/engine/install-runner.ts +56 -2
  49. package/backend/engine/stack-project.ts +71 -1
  50. package/backend/index.ts +5 -0
  51. package/backend/mcp/README.md +2 -2
  52. package/backend/mcp/external/config.ts +18 -0
  53. package/backend/mcp/external/proxy.ts +2 -2
  54. package/backend/mcp/index.ts +8 -0
  55. package/backend/mcp/internal/config.ts +42 -3
  56. package/backend/memory/embedding/install.ts +29 -1
  57. package/backend/utils/keyed-lock.test.ts +33 -0
  58. package/backend/utils/keyed-lock.ts +17 -0
  59. package/backend/utils/port-utils.test.ts +29 -0
  60. package/backend/utils/port-utils.ts +19 -0
  61. package/backend/ws/engine/cline/accounts.ts +26 -6
  62. package/backend/ws/engine/codex/accounts.test.ts +49 -0
  63. package/backend/ws/engine/codex/accounts.ts +17 -13
  64. package/backend/ws/engine/opencode/providers.ts +2 -1
  65. package/backend/ws/engine/pi/accounts.ts +61 -6
  66. package/dist/assets/{index-D-Ad1N96.js → index-BTcR1byF.js} +1 -1
  67. package/dist/assets/{index-Am-rJRxA.js → index-CwuKQelV.js} +1 -1
  68. package/dist/assets/{main--PLCDxSy.css → main-BiDNMWb3.css} +1 -1
  69. package/dist/assets/{main-DelPm2Xt.js → main-BlhKWz2B.js} +595 -593
  70. package/dist/index.html +2 -2
  71. package/package.json +19 -15
  72. package/backend/engine/adapters/pi/mcp-tools.ts +0 -153
  73. package/backend/engine/adapters/qwen/session-fork.ts +0 -109
@@ -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';
@@ -34,7 +34,7 @@ import { artifactFilter } from '$backend/profiles';
34
34
  import { syncSkills } from '$backend/skills';
35
35
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
36
36
  import { resolveProjectBridge } from '$backend/artifacts/project';
37
- import { CODEX_MODELS, resolveCodexEffort } from './models';
37
+ import { CODEX_CONTEXT_WINDOW_REQUEST, CODEX_MODELS, resolveCodexEffort } from './models';
38
38
  import { debug } from '$shared/utils/logger';
39
39
  import { handleStreamError, buildTurnError } from './error-handler';
40
40
  import {
@@ -180,8 +180,9 @@ export class CodexEngine implements AIEngine {
180
180
  const mcpConfig = getCodexMcpConfig(mcpProfileFilter, projectId ? { projectId } : undefined);
181
181
 
182
182
  // Codex SDK takes config at construction. We pass `show_raw_agent_reasoning`
183
- // (so the SDK forwards reasoning text events) and forward the Clopen MCP
184
- // 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
185
186
  // thread level (`sandboxMode: 'danger-full-access'`) to match the trust
186
187
  // model of every other engine in this repo — Claude bypasses permissions,
187
188
  // OpenCode auto-approves every permission event, Copilot uses `approveAll`,
@@ -199,6 +200,7 @@ export class CodexEngine implements AIEngine {
199
200
  env: { ...getCleanSpawnEnv(), CODEX_HOME: getCodexHomeDir(), ...this.pendingGitIdentityEnv },
200
201
  config: {
201
202
  show_raw_agent_reasoning: true,
203
+ model_context_window: CODEX_CONTEXT_WINDOW_REQUEST,
202
204
  ...(Object.keys(mcpConfig).length > 0 ? { mcp_servers: mcpConfig } : {}),
203
205
  },
204
206
  });
@@ -230,9 +232,8 @@ export class CodexEngine implements AIEngine {
230
232
  const { projectPath, prompt, resume, modelId, reasoningEffort, abortController, accountId } = options;
231
233
 
232
234
  // Per-model reasoning levels live in the catalog, which is derived from the
233
- // CLI's own preset table — see `resolveCodexEffort` for the validity rules
234
- // and for why the SDK's narrower `ModelReasoningEffort` union is cast past.
235
- 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);
236
237
 
237
238
  // Active Profile for this stream — scopes the materialized artifact set AND
238
239
  // (below) the MCP connector set baked into the Codex client.
@@ -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
+ });
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Clopen permission policy → Copilot permission decisions.
3
+ *
4
+ * Two layers enforce the same policy:
5
+ *
6
+ * 1. `managedSettings.permissions.deny` — the runtime refuses a denied tool
7
+ * before `onPermissionRequest` is ever consulted, so it holds even for tools
8
+ * that never surface a permission request. Only the `Shell`, `Write` and
9
+ * `Read` rule families exist: runtime 1.0.90 rejects session creation for any
10
+ * other family (`url`, `memory`, MCP server names were all tried), so a rule
11
+ * outside these three would break every turn rather than restrict it.
12
+ *
13
+ * 2. `onPermissionRequest` — covers what the managed layer cannot express:
14
+ * `url`, `memory` and MCP tools.
15
+ *
16
+ * Only deny rules are injected. A managed `allow` list must admit every
17
+ * operation, including the families Clopen's policy never mentions, so
18
+ * translating an allowlist would block tools the user allowed. Computing the
19
+ * denied families through `isToolAllowed` gives the same result for an
20
+ * allowlist without that risk.
21
+ */
22
+
23
+ import type { ManagedSettings, PermissionRequest, PermissionRequestResult } from '@github/copilot-sdk';
24
+ import { hasAnyRestriction, isToolAllowed, type ResolvedPermissions } from '$backend/permissions';
25
+ import { debug } from '$shared/utils/logger';
26
+
27
+ /** Copilot permission kind → the managed rule family the runtime accepts for it. */
28
+ const MANAGED_RULE_FAMILIES: ReadonlyArray<readonly [kind: string, family: string]> = [
29
+ ['shell', 'Shell'],
30
+ ['write', 'Write'],
31
+ ['read', 'Read']
32
+ ];
33
+
34
+ /**
35
+ * Managed settings that deny every rule family the policy blocks, or undefined
36
+ * when none is blocked. Must be passed on resume too: the runtime does not
37
+ * persist injected settings, and omitting them clears the layer.
38
+ */
39
+ export function buildCopilotManagedSettings(permissions: ResolvedPermissions): ManagedSettings | undefined {
40
+ if (!hasAnyRestriction(permissions)) return undefined;
41
+ const deny = MANAGED_RULE_FAMILIES
42
+ .filter(([kind]) => !isToolAllowed(permissions, kind))
43
+ .map(([, family]) => family);
44
+ return deny.length > 0 ? { permissions: { deny } } : undefined;
45
+ }
46
+
47
+ /**
48
+ * Map a Copilot permission request to the token the permission policy matches on.
49
+ * MCP / custom tools carry a `toolName`; everything else is matched by its
50
+ * operation `kind` (`shell` / `write` / `read` / `url` / `memory` / …), which is
51
+ * why the Copilot builtin catalog lists kinds rather than tool names.
52
+ */
53
+ function copilotPermissionToken(request: PermissionRequest): string {
54
+ const named = (request as { toolName?: string }).toolName;
55
+ return named && named.trim() ? named : request.kind;
56
+ }
57
+
58
+ /**
59
+ * Enforce the resolved permission policy for one Copilot request. Returns a
60
+ * reject decision for blocked tools, or null to fall through to auto-approve.
61
+ */
62
+ export function enforceCopilotPermission(
63
+ permissions: ResolvedPermissions,
64
+ request: PermissionRequest
65
+ ): PermissionRequestResult | null {
66
+ const token = copilotPermissionToken(request);
67
+ if (!isToolAllowed(permissions, token)) {
68
+ debug.log('permissions', `⛔ Blocked tool "${token}" (Clopen permission policy)`);
69
+ return { kind: 'reject', feedback: `Blocked by Clopen permission policy: ${token}` };
70
+ }
71
+ return null;
72
+ }