@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
@@ -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
+ }
@@ -13,8 +13,7 @@ import type {
13
13
  ResumeSessionConfig,
14
14
  SessionEvent,
15
15
  ModelInfo,
16
- PermissionRequest,
17
- PermissionRequestResult,
16
+ MessageOptions,
18
17
  } from '@github/copilot-sdk';
19
18
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
20
19
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
@@ -28,9 +27,11 @@ import { EngineRuns } from '../run-registry';
28
27
  import { artifactFilter } from '$backend/profiles';
29
28
  import { syncSkills } from '$backend/skills';
30
29
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
31
- import { resolvePermissionsFromDb, isToolAllowed, type ResolvedPermissions } from '$backend/permissions';
30
+ import { resolveProjectBridge } from '$backend/artifacts/project';
31
+ import { resolvePermissionsFromDb } from '$backend/permissions';
32
32
  import { handleStreamError, buildSessionError } from './error-handler';
33
33
  import { fetchCopilotModels } from './models';
34
+ import { buildCopilotManagedSettings, enforceCopilotPermission } from './permissions';
34
35
 
35
36
  // `UserInputResponse` isn't part of the SDK's public type exports
36
37
  // (see `node_modules/@github/copilot-sdk/dist/index.d.ts`), but
@@ -38,38 +39,17 @@ import { fetchCopilotModels } from './models';
38
39
  // it from the SessionConfig field so we don't drift from the SDK.
39
40
  type UserInputResponse = Awaited<ReturnType<NonNullable<SessionConfig['onUserInputRequest']>>>;
40
41
 
41
- // `MessageOptions` is likewise not re-exported from the SDK root, so derive the
42
- // attachment element type from `session.send`'s options overload.
43
- type MessageAttachment = NonNullable<Parameters<CopilotSession['send']>[0] extends string
44
- ? never
45
- : NonNullable<Extract<Parameters<CopilotSession['send']>[0], { prompt: string }>['attachments']>>[number];
42
+ type MessageAttachment = NonNullable<MessageOptions['attachments']>[number];
43
+ type CopilotReasoningEffort = NonNullable<ResumeSessionConfig['reasoningEffort']>;
46
44
 
47
45
  /**
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.
46
+ * Every level the SDK's `reasoningEffort` accepts. Typed against the SDK union
47
+ * so a level it drops is a compile error here. The picker only offers what the
48
+ * model reports in `supportedReasoningEfforts`; this guards against a stale
49
+ * per-model default from another engine reaching the SDK.
52
50
  */
53
- function copilotPermissionToken(request: PermissionRequest): string {
54
- const named = (request as { toolName?: string }).toolName;
55
- return named && named.trim() ? named : request.kind;
56
- }
51
+ const COPILOT_EFFORTS: ReadonlySet<string> = new Set<CopilotReasoningEffort>(['low', 'medium', 'high', 'xhigh', 'max']);
57
52
 
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
- 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
- }
73
53
  import {
74
54
  createStreamConverterState,
75
55
  convertSessionStart,
@@ -133,12 +113,6 @@ export class CopilotEngine implements AIEngine {
133
113
  */
134
114
  private runs = new EngineRuns<CopilotRun>();
135
115
  private modelsCache: ModelInfo[] | null = null;
136
- /**
137
- * Account ID currently baked into `this.client`. The Copilot SDK takes the
138
- * GitHub token as a constructor argument, so per-stream account overrides
139
- * require disposing and re-creating the client (see streamQuery below).
140
- */
141
- private currentAccountId: number | null = null;
142
116
 
143
117
  /**
144
118
  * AskUserQuestion bookkeeping. The Copilot SDK splits the `ask_user`
@@ -166,18 +140,17 @@ export class CopilotEngine implements AIEngine {
166
140
  return this.runs.isActive;
167
141
  }
168
142
 
143
+ /**
144
+ * Start the runtime once per instance. The client-level token only
145
+ * authenticates the runtime process and the model listing; every session
146
+ * carries its own account's token (see `sessionAuth`), so a stream on another
147
+ * account no longer tears the client down — which used to abort every other
148
+ * chat streaming on this instance.
149
+ */
169
150
  async initialize(accountId?: number): Promise<void> {
170
- if (this._isInitialized && (accountId == null || accountId === this.currentAccountId)) {
171
- return;
172
- }
173
-
174
- const account = accountId != null
175
- ? engineQueries.getAccount(accountId)
176
- : engineQueries.getActiveAccountForEngine('copilot');
177
- if (!account) {
178
- throw new Error('Copilot is not configured. Add a Personal Access Token in Settings → Engines → Copilot.');
179
- }
151
+ if (this._isInitialized) return;
180
152
 
153
+ const account = resolveCopilotAccount(accountId);
181
154
  const { CopilotClient } = await loadEngineSdk<typeof import('@github/copilot-sdk')>('copilot', '@github/copilot-sdk');
182
155
 
183
156
  this.client = new CopilotClient({
@@ -187,10 +160,10 @@ export class CopilotEngine implements AIEngine {
187
160
  // {clopenDir}/engine/copilot/user/ instead of the shared ~/.copilot. The SDK
188
161
  // forwards this as COPILOT_HOME to the spawned runtime.
189
162
  baseDirectory: getEngineUserConfigDir('copilot'),
163
+ clientInfo: { applicationName: 'clopen' },
190
164
  });
191
165
 
192
166
  await this.client.start();
193
- this.currentAccountId = account.id;
194
167
  this._isInitialized = true;
195
168
  debug.log('engine', `Copilot engine initialized (account ${account.id})`);
196
169
  }
@@ -216,7 +189,6 @@ export class CopilotEngine implements AIEngine {
216
189
 
217
190
  this.client = null;
218
191
  this.modelsCache = null;
219
- this.currentAccountId = null;
220
192
  this._isInitialized = false;
221
193
  debug.log('engine', 'Copilot engine disposed');
222
194
  }
@@ -237,22 +209,13 @@ export class CopilotEngine implements AIEngine {
237
209
  async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
238
210
  const { projectPath, prompt, resume, modelId, reasoningEffort, abortController, accountId } = options;
239
211
 
240
- // Copilot's `reasoningEffort` accepts low | medium | high | xhigh; only
241
- // applied for models that support it (unsupported tokens are dropped so
242
- // the SDK falls back to the model default).
243
- const copilotEfforts = new Set<string>(['low', 'medium', 'high', 'xhigh']);
212
+ // Unknown tokens are dropped so the SDK falls back to the model default.
244
213
  const reasoningOption: Pick<ResumeSessionConfig, 'reasoningEffort'> | Record<string, never> =
245
- reasoningEffort && copilotEfforts.has(reasoningEffort)
246
- ? { reasoningEffort: reasoningEffort as ResumeSessionConfig['reasoningEffort'] }
214
+ reasoningEffort && COPILOT_EFFORTS.has(reasoningEffort)
215
+ ? { reasoningEffort: reasoningEffort as CopilotReasoningEffort }
247
216
  : {};
248
217
 
249
- // Per-stream account override: the Copilot SDK takes the GitHub token at
250
- // construction time, so an account switch requires recreating the client.
251
- if (this._isInitialized && accountId != null && accountId !== this.currentAccountId) {
252
- debug.log('engine', `Copilot account switch ${this.currentAccountId} → ${accountId}; re-initializing client`);
253
- await this.dispose();
254
- }
255
-
218
+ const auth = sessionAuth(accountId);
256
219
  if (!this._isInitialized || !this.client) {
257
220
  await this.initialize(accountId);
258
221
  }
@@ -279,13 +242,15 @@ export class CopilotEngine implements AIEngine {
279
242
  // the authoritative per-session signal (synthetic commands/subagents are
280
243
  // stripped from the global file; the native skill mirror still loads the
281
244
  // filtered folders).
282
- const artifactsContext = buildArtifactsPromptContext('copilot', profileId);
245
+ const resolvedProjectPath = resolveOsPath(projectPath);
246
+ // Copilot reads `.github/*`, `.agents/skills`, `.claude/skills` and
247
+ // AGENTS.md itself; the rest of the repo's artifacts join the preamble.
248
+ const projectBridge = await resolveProjectBridge('copilot', resolvedProjectPath, options.mcpContext?.projectId);
249
+ const artifactsContext = buildArtifactsPromptContext('copilot', profileId, projectBridge);
283
250
 
284
251
  // Resolve the permission policy once per stream; onPermissionRequest below
285
252
  // enforces it (Copilot otherwise approves every tool via approveAll).
286
253
  const permissions = resolvePermissionsFromDb('copilot', options.mcpContext?.projectId, profileId);
287
-
288
- const resolvedProjectPath = resolveOsPath(projectPath);
289
254
  const state = createStreamConverterState('', modelId);
290
255
 
291
256
  // Buffered queue between async event handler and the for-await consumer.
@@ -341,7 +306,13 @@ export class CopilotEngine implements AIEngine {
341
306
  try {
342
307
  const mcpConfig = getCopilotMcpConfig(mcpProfileFilter, options.mcpContext);
343
308
 
309
+ const managedSettings = buildCopilotManagedSettings(permissions);
310
+
344
311
  const baseConfig: ResumeSessionConfig = {
312
+ ...auth,
313
+ // Re-supplied on every resume: the runtime does not persist injected
314
+ // settings, and omitting them clears the layer.
315
+ ...(managedSettings && { managedSettings }),
345
316
  onPermissionRequest: (request, invocation) =>
346
317
  enforceCopilotPermission(permissions, request) ?? approveAll(request, invocation),
347
318
  // Enables the agent's `ask_user` tool. Without this callback the
@@ -426,12 +397,13 @@ export class CopilotEngine implements AIEngine {
426
397
  try {
427
398
  session = await this.client.resumeSession(resumeId, baseConfig);
428
399
  debug.log('engine', `Copilot resumed session: ${resumeId}${resumeId === resume ? '' : ` (forked from ${resume})`}`);
400
+ await reloadInstructions(session);
429
401
  } catch (error) {
430
402
  debug.warn('engine', `Failed to resume Copilot session ${resumeId}, creating fresh:`, error);
431
- session = await this.client.createSession({ ...baseConfig } as SessionConfig);
403
+ session = await this.client.createSession(freshSessionConfig(baseConfig));
432
404
  }
433
405
  } else {
434
- session = await this.client.createSession({ ...baseConfig } as SessionConfig);
406
+ session = await this.client.createSession(freshSessionConfig(baseConfig));
435
407
  }
436
408
 
437
409
  run.session = session;
@@ -705,9 +677,7 @@ export class CopilotEngine implements AIEngine {
705
677
  accountId,
706
678
  } = options;
707
679
 
708
- if (this._isInitialized && accountId != null && accountId !== this.currentAccountId) {
709
- await this.dispose();
710
- }
680
+ const auth = sessionAuth(accountId);
711
681
  if (!this._isInitialized || !this.client) {
712
682
  await this.initialize(accountId);
713
683
  }
@@ -722,6 +692,7 @@ export class CopilotEngine implements AIEngine {
722
692
  const jsonPrompt = buildJsonPrompt(prompt, schema);
723
693
 
724
694
  const session = await this.client.createSession({
695
+ ...auth,
725
696
  model: modelId,
726
697
  workingDirectory: resolvedProjectPath,
727
698
  onPermissionRequest: approveAll,
@@ -775,6 +746,48 @@ export class CopilotEngine implements AIEngine {
775
746
  // Helpers
776
747
  // ============================================================================
777
748
 
749
+ function resolveCopilotAccount(accountId?: number) {
750
+ const account = accountId != null
751
+ ? engineQueries.getAccount(accountId)
752
+ : engineQueries.getActiveAccountForEngine('copilot');
753
+ if (!account) {
754
+ throw new Error('Copilot is not configured. Add a Personal Access Token in Settings → Engines → Copilot.');
755
+ }
756
+ return account;
757
+ }
758
+
759
+ /**
760
+ * Per-session GitHub identity. The runtime resolves this token into the
761
+ * session's login, plan, endpoints and quota, independently of the client's
762
+ * own token — so concurrent chats on different accounts share one runtime.
763
+ */
764
+ function sessionAuth(accountId?: number): Pick<SessionConfig, 'gitHubToken'> {
765
+ return { gitHubToken: resolveCopilotAccount(accountId).credential };
766
+ }
767
+
768
+ /**
769
+ * Create-time config. Instruction discovery is cached process-wide by the
770
+ * runtime, and the client lives across turns while AGENTS.md, Copilot
771
+ * instruction files and Clopen's artifact sync rewrite them — so every new
772
+ * session re-reads them from disk instead of inheriting a stale cache.
773
+ */
774
+ function freshSessionConfig(base: ResumeSessionConfig): SessionConfig {
775
+ return { ...base, refreshCustomInstructions: true } as SessionConfig;
776
+ }
777
+
778
+ /**
779
+ * Resume-time counterpart of `refreshCustomInstructions`, which only exists on
780
+ * create. Experimental RPC, so a failure is logged and the turn carries on with
781
+ * the instructions the runtime already has.
782
+ */
783
+ async function reloadInstructions(session: CopilotSession): Promise<void> {
784
+ try {
785
+ await session.rpc.instructions.reload();
786
+ } catch (error) {
787
+ debug.warn('engine', 'Copilot instructions.reload failed (non-fatal):', error);
788
+ }
789
+ }
790
+
778
791
  function extractPromptText(prompt: EngineQueryOptions['prompt']): string {
779
792
  const parts: string[] = [];
780
793
  for (const block of prompt.content) {
@@ -30,6 +30,7 @@ import { debug } from '$shared/utils/logger';
30
30
  import { engineQueries } from '$backend/database/queries/engine-queries';
31
31
  import { syncSkills } from '$backend/skills';
32
32
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
33
+ import { resolveProjectBridge, type ProjectBridge } from '$backend/artifacts/project';
33
34
  import { artifactFilter } from '$backend/profiles';
34
35
  import { resolvePermissionsFromDb, excludedBuiltinTools } from '$backend/permissions';
35
36
  import { getCursorMcpConfig } from '../../../mcp';
@@ -138,17 +139,24 @@ export class CursorEngine implements AIEngine {
138
139
  return fetchCursorModels();
139
140
  }
140
141
 
141
- /** Build the `agents` config from Clopen's enabled subagents (Cursor-native). */
142
- private async buildAgents(): Promise<Record<string, AgentDefinition> | undefined> {
143
- const subagents = subagentQueries.getEnabled();
144
- if (subagents.length === 0) return undefined;
142
+ /**
143
+ * Build the `agents` config from Clopen's enabled subagents plus the
144
+ * repository's own (Cursor-native). Clopen runs Cursor with its project
145
+ * setting source off, so repo subagents only arrive this way; an installed
146
+ * subagent wins a slug clash.
147
+ */
148
+ private async buildAgents(project: ProjectBridge): Promise<Record<string, AgentDefinition> | undefined> {
145
149
  const agents: Record<string, AgentDefinition> = {};
146
- for (const s of subagents) {
150
+ for (const s of subagentQueries.getEnabled()) {
147
151
  const md = (await readSubagentMd(s.slug)) ?? '';
148
152
  const prompt = stripFrontmatter(md) || `You are the ${s.name} subagent. ${s.description}`;
149
153
  agents[s.slug] = { description: s.description || s.name, prompt, model: 'inherit' };
150
154
  }
151
- return agents;
155
+ for (const s of project.subagents) {
156
+ if (agents[s.slug]) continue;
157
+ agents[s.slug] = { description: s.description || s.name, prompt: s.prompt, model: 'inherit' };
158
+ }
159
+ return Object.keys(agents).length > 0 ? agents : undefined;
152
160
  }
153
161
 
154
162
  async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
@@ -177,6 +185,9 @@ export class CursorEngine implements AIEngine {
177
185
  const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
178
186
  await syncSkills('cursor', profileId);
179
187
  await syncEngineArtifacts('cursor', profileId);
188
+ // Cursor's own repo scan is gated on `settingSources`, which Clopen leaves
189
+ // off — so every project artifact reaches it through Clopen.
190
+ const projectBridge = await resolveProjectBridge('cursor', resolvedProjectPath, options.mcpContext?.projectId);
180
191
 
181
192
  // ── Permissions → disallowedTools ──
182
193
  // Cursor exposes no per-call permission hook, but `AgentOptions` takes a
@@ -208,7 +219,7 @@ export class CursorEngine implements AIEngine {
208
219
  });
209
220
  const customTools: Record<string, SDKCustomTool> = { AskUserQuestion: askTool };
210
221
  const mcpServers = getCursorMcpConfig(mcpProfileFilter, options.mcpContext);
211
- const agents = await this.buildAgents();
222
+ const agents = await this.buildAgents(projectBridge);
212
223
 
213
224
  const { Agent } = await loadEngineSdk<typeof import('@cursor/sdk')>('cursor', '@cursor/sdk');
214
225
  const store = await getCursorStore(projectPath);
@@ -264,12 +275,14 @@ export class CursorEngine implements AIEngine {
264
275
 
265
276
  // Build the user turn (text + image attachments).
266
277
  //
267
- // The artifact context rides the user message because `@cursor/sdk` has no
268
- // system-prompt option — `AgentOptions` exposes model/tools/mcpServers/agents
269
- // and nothing else. It is rebuilt per turn on purpose: the active Profile can
270
- // change mid-session, and a stale advertisement is worse than a repeated one.
278
+ // The artifact context rides the user message, as on every prompt-scoped
279
+ // engine. `systemPrompt` (1.0.37+) is not used: it replaces Cursor's whole
280
+ // harness prompt, is server-gated (`InvalidArgument` without access) and
281
+ // must be re-passed on every resume — revisit if it becomes additive and
282
+ // generally available. It is rebuilt per turn on purpose: the active Profile
283
+ // can change mid-session, and a stale advertisement is worse than a repeated one.
271
284
  const promptText = prompt.content.filter(b => b.type === 'text').map(b => (b.type === 'text' ? b.text : '')).join('\n');
272
- const artifacts = buildArtifactsPromptContext('cursor', profileId);
285
+ const artifacts = buildArtifactsPromptContext('cursor', profileId, projectBridge);
273
286
  const text = artifacts ? `${artifacts}\n\n${promptText}` : promptText;
274
287
  const images: SDKImage[] = [];
275
288
  for (const b of prompt.content) {
@@ -298,6 +311,8 @@ export class CursorEngine implements AIEngine {
298
311
  },
299
312
  });
300
313
  runState.run = run;
314
+ // `run.steer(text)` (1.0.37+, local only) can inject a message into this
315
+ // turn; unused until Clopen has a mid-turn steering flow across engines.
301
316
 
302
317
  // Abort wiring: cancelling the stream cancels the Cursor run.
303
318
  onAbort = () => { run.cancel().catch(() => { /* already terminal */ }); };
@@ -70,7 +70,7 @@ import { readdir, readFile, rename, stat } from 'fs/promises';
70
70
  import { createServer } from 'node:net';
71
71
  import type { OpencodeClient } from '@opencode-ai/sdk';
72
72
  import type { Subprocess } from 'bun';
73
- import { getOpenCodeMcpConfig, getEnabledServerNames, getEnabledToolsForServer } from '../../../mcp';
73
+ import { getOpenCodeMcpConfig, getOpenCodeProjectMcpConfig, getEnabledServerNames, getEnabledToolsForServer } from '../../../mcp';
74
74
  import { engineQueries, settingsQueries } from '../../../database/queries';
75
75
  import { generateOpenCodeProviderConfig, parseCredentialMap } from './config';
76
76
  import type { OpenCodeInlineAgent } from '$backend/subagents';
@@ -155,6 +155,13 @@ export interface ServerConfigSpec {
155
155
  * every turn and the signature does not move, so no extra server is spawned.
156
156
  */
157
157
  gitIdentityEnv?: Record<string, string>;
158
+ /**
159
+ * Project whose approved `.agents/mcp.json` servers join the MCP set. Folded
160
+ * in at assembly time (not in the per-scope cache), so it changes the process
161
+ * signature but not the data dir — a project without such a file resolves to
162
+ * the same server as before.
163
+ */
164
+ projectId?: string | null;
158
165
  }
159
166
 
160
167
  /** Everything needed to spawn a server, plus the key derived from it. */
@@ -643,10 +650,13 @@ async function resolveConfig(spec: ServerConfigSpec, scopeKey: string): Promise<
643
650
  function assembleConfigContent(
644
651
  cached: CachedConfig,
645
652
  enabledProviders: string[],
646
- inlineAgents?: Record<string, OpenCodeInlineAgent>
653
+ inlineAgents?: Record<string, OpenCodeInlineAgent>,
654
+ projectMcp: Record<string, unknown> = {}
647
655
  ): string {
648
656
  const mergedConfig: Record<string, unknown> = {};
649
- if (Object.keys(cached.mcpConfig).length > 0) mergedConfig.mcp = cached.mcpConfig;
657
+ // Project servers never shadow an installed server of the same namespace.
658
+ const mcp = { ...projectMcp, ...cached.mcpConfig };
659
+ if (Object.keys(mcp).length > 0) mergedConfig.mcp = mcp;
650
660
  if (enabledProviders.length > 0) mergedConfig.enabled_providers = enabledProviders;
651
661
  if (inlineAgents && Object.keys(inlineAgents).length > 0) mergedConfig.agent = inlineAgents;
652
662
  if (Object.keys(cached.providerSection).length > 0) mergedConfig.provider = cached.providerSection;
@@ -666,7 +676,7 @@ async function resolvePlan(spec: ServerConfigSpec): Promise<SpawnPlan> {
666
676
  // Cheap and DB-derived, so it is resolved per call rather than cached — the
667
677
  // models.dev catalog it reads lives in `settings`, which bumps no revision.
668
678
  const providerConfig = generateOpenCodeProviderConfig();
669
- const configContent = assembleConfigContent(config, providerConfig.enabledProviders, spec.inlineAgents);
679
+ const configContent = assembleConfigContent(config, providerConfig.enabledProviders, spec.inlineAgents, getOpenCodeProjectMcpConfig(spec.projectId));
670
680
  // Sorted so the key order the builder happens to emit is not mistaken for a
671
681
  // different identity.
672
682
  const gitIdentityEnv = spec.gitIdentityEnv ?? {};
@@ -45,6 +45,8 @@ import {
45
45
  import { ensureClient, acquireServer, releaseServer, getDefaultServer, type ServerInstance } from './server';
46
46
  import { syncSkills } from '$backend/skills';
47
47
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
48
+ import { resolveProjectBridge } from '$backend/artifacts/project';
49
+ import { resolveOsPath } from '$backend/utils/paths';
48
50
  import { artifactFilter } from '$backend/profiles';
49
51
  import { buildOpenCodeInlineAgents } from '$backend/subagents';
50
52
  import { getOpenCodeProfileDisabledToolIds } from '$backend/mcp';
@@ -221,7 +223,20 @@ export class OpenCodeEngine implements AIEngine {
221
223
  // server, different Profiles get isolated servers, concurrently.
222
224
  const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
223
225
  const subagentFilter = artifactFilter(profileId, 'subagent') ?? undefined;
224
- const inlineAgents = await buildOpenCodeInlineAgents(profileId);
226
+ // Repository artifacts Open Code doesn't read natively (it reads
227
+ // `.opencode/*`, `.agents/skills`, `.claude/skills` and AGENTS.md itself).
228
+ // Project subagents join the inline agents (an installed one wins a slug
229
+ // clash); the approved `.agents/mcp.json` joins MCP via `projectId`.
230
+ const projectBridge = await resolveProjectBridge('opencode', resolveOsPath(projectPath), options.mcpContext?.projectId);
231
+ const inlineAgents = {
232
+ ...Object.fromEntries(projectBridge.subagents.map(sub => [sub.slug, {
233
+ description: sub.description || sub.name,
234
+ mode: 'subagent' as const,
235
+ prompt: sub.prompt,
236
+ ...(sub.model ? { model: sub.model } : {})
237
+ }])),
238
+ ...(await buildOpenCodeInlineAgents(profileId))
239
+ };
225
240
  // The pool derives the key from the config it is about to spawn with, so a
226
241
  // changed connector set, provider, credential or subagent prompt routes this
227
242
  // stream to a server built from it — while any server still serving another
@@ -229,7 +244,7 @@ export class OpenCodeEngine implements AIEngine {
229
244
  // stream id is what makes that safe: a held server is never reaped.
230
245
  const holderId = options.mcpContext?.streamId;
231
246
  const server = await acquireServer(
232
- { mcpProfileFilter, subagentFilter, inlineAgents, gitIdentityEnv: options.gitIdentityEnv },
247
+ { mcpProfileFilter, subagentFilter, inlineAgents, gitIdentityEnv: options.gitIdentityEnv, projectId: options.mcpContext?.projectId ?? null },
233
248
  holderId
234
249
  );
235
250
  run.server = server;
@@ -253,7 +268,7 @@ export class OpenCodeEngine implements AIEngine {
253
268
  // so advertise the profile-scoped set PER-SESSION by prepending it as a
254
269
  // leading context part each turn (authoritative for synthetic skills;
255
270
  // advisory on top of the native command/agent dirs).
256
- const artifactsContext = buildArtifactsPromptContext('opencode', profileId);
271
+ const artifactsContext = buildArtifactsPromptContext('opencode', profileId, projectBridge);
257
272
  if (artifactsContext) {
258
273
  promptParts.unshift({ type: 'text', text: artifactsContext });
259
274
  }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Pi credential storage: the installation's device id, refreshes that must
3
+ * never spend one rotating refresh token twice, and accounts saved under a
4
+ * provider id pi-ai has since renamed.
5
+ */
6
+
7
+ import { beforeAll, describe, expect, test } from 'bun:test';
8
+ import { initializeDatabase } from '$backend/database';
9
+ import { settingsQueries } from '$backend/database/queries/settings-queries';
10
+ import { engineQueries } from '$backend/database/queries/engine-queries';
11
+ import type { Credential } from '@earendil-works/pi-ai';
12
+ import { DbCredentialStore, getPiAccountForProvider, getPiDeviceId, getPiProvider, parsePiCredential, serializePiCredential } from './credential';
13
+
14
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15
+
16
+ beforeAll(async () => {
17
+ await initializeDatabase();
18
+ });
19
+
20
+ describe('getPiDeviceId', () => {
21
+ test('creates a UUID once and returns it on every later call', () => {
22
+ settingsQueries.delete('pi_device_id');
23
+ const first = getPiDeviceId();
24
+ expect(first).toMatch(UUID);
25
+ expect(getPiDeviceId()).toBe(first);
26
+ expect(settingsQueries.get('pi_device_id')?.value).toBe(first);
27
+ });
28
+ });
29
+
30
+ describe('DbCredentialStore.modify', () => {
31
+ test('serializes refreshes across store instances so a rotating token is spent once', async () => {
32
+ const provider = getPiProvider();
33
+ expect(provider).not.toBeNull();
34
+ const expired: Credential = { type: 'oauth', access: 'a0', refresh: 'r0', expires: Date.now() - 1000 };
35
+ const account = engineQueries.createAccount(provider!.id, `refresh-race-${crypto.randomUUID()}`, serializePiCredential({ provider: 'openai', credential: expired }));
36
+
37
+ let refreshes = 0;
38
+ // What pi-ai's Models does: refresh only if the credential it is handed is still expired.
39
+ const refreshIfExpired = async (current: Credential | undefined): Promise<Credential | undefined> => {
40
+ if (current?.type !== 'oauth' || Date.now() < current.expires) return undefined;
41
+ refreshes++;
42
+ await new Promise((resolve) => setTimeout(resolve, 20));
43
+ return { ...current, access: `a${refreshes}`, refresh: `r${refreshes}`, expires: Date.now() + 3_600_000 };
44
+ };
45
+
46
+ // Two streams, two stores, one account row.
47
+ const [a, b] = await Promise.all([
48
+ new DbCredentialStore([account]).modify('openai', refreshIfExpired),
49
+ new DbCredentialStore([account]).modify('openai', refreshIfExpired),
50
+ ]);
51
+
52
+ expect(refreshes).toBe(1);
53
+ expect(a).toEqual(b);
54
+ const stored = parsePiCredential(engineQueries.getAccount(account.id)?.credential)?.credential;
55
+ expect(stored?.type === 'oauth' && stored.refresh).toBe('r1');
56
+ engineQueries.deleteAccount(account.id);
57
+ });
58
+ });
59
+
60
+ describe('renamed providers', () => {
61
+ test('an account saved under azure-openai-responses resolves as azure, under either id', () => {
62
+ const provider = getPiProvider();
63
+ expect(provider).not.toBeNull();
64
+ const credential: Credential = { type: 'api_key', key: 'k', env: { AZURE_OPENAI_BASE_URL: 'https://example.openai.azure.com' } };
65
+ const account = engineQueries.createAccount(provider!.id, `azure-rename-${crypto.randomUUID()}`, serializePiCredential({ provider: 'azure-openai-responses', credential }));
66
+
67
+ expect(parsePiCredential(account.credential)?.provider).toBe('azure');
68
+ expect(getPiAccountForProvider('azure')?.id).toBe(account.id);
69
+ expect(getPiAccountForProvider('azure-openai-responses')?.id).toBe(account.id);
70
+ engineQueries.deleteAccount(account.id);
71
+ });
72
+
73
+ test('the store serves the credential to pi-ai under the new id', async () => {
74
+ const provider = getPiProvider();
75
+ const credential: Credential = { type: 'api_key', key: 'k2' };
76
+ const account = engineQueries.createAccount(provider!.id, `azure-store-${crypto.randomUUID()}`, serializePiCredential({ provider: 'azure-openai-responses', credential }));
77
+
78
+ const store = new DbCredentialStore([account]);
79
+ expect(await store.read('azure')).toEqual(credential);
80
+ expect(await store.read('azure-openai-responses')).toBeUndefined();
81
+ engineQueries.deleteAccount(account.id);
82
+ });
83
+ });