@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
@@ -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';
@@ -29,9 +28,10 @@ import { artifactFilter } from '$backend/profiles';
29
28
  import { syncSkills } from '$backend/skills';
30
29
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
31
30
  import { resolveProjectBridge } from '$backend/artifacts/project';
32
- import { resolvePermissionsFromDb, isToolAllowed, type ResolvedPermissions } from '$backend/permissions';
31
+ import { resolvePermissionsFromDb } from '$backend/permissions';
33
32
  import { handleStreamError, buildSessionError } from './error-handler';
34
33
  import { fetchCopilotModels } from './models';
34
+ import { buildCopilotManagedSettings, enforceCopilotPermission } from './permissions';
35
35
 
36
36
  // `UserInputResponse` isn't part of the SDK's public type exports
37
37
  // (see `node_modules/@github/copilot-sdk/dist/index.d.ts`), but
@@ -39,38 +39,17 @@ import { fetchCopilotModels } from './models';
39
39
  // it from the SessionConfig field so we don't drift from the SDK.
40
40
  type UserInputResponse = Awaited<ReturnType<NonNullable<SessionConfig['onUserInputRequest']>>>;
41
41
 
42
- // `MessageOptions` is likewise not re-exported from the SDK root, so derive the
43
- // attachment element type from `session.send`'s options overload.
44
- type MessageAttachment = NonNullable<Parameters<CopilotSession['send']>[0] extends string
45
- ? never
46
- : NonNullable<Extract<Parameters<CopilotSession['send']>[0], { prompt: string }>['attachments']>>[number];
42
+ type MessageAttachment = NonNullable<MessageOptions['attachments']>[number];
43
+ type CopilotReasoningEffort = NonNullable<ResumeSessionConfig['reasoningEffort']>;
47
44
 
48
45
  /**
49
- * Map a Copilot permission request to the token the permission policy matches on.
50
- * MCP / custom tools carry a `toolName`; everything else is matched by its
51
- * operation `kind` (`shell` / `write` / `read` / `url` / `memory` / …), which is
52
- * 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.
53
50
  */
54
- function copilotPermissionToken(request: PermissionRequest): string {
55
- const named = (request as { toolName?: string }).toolName;
56
- return named && named.trim() ? named : request.kind;
57
- }
51
+ const COPILOT_EFFORTS: ReadonlySet<string> = new Set<CopilotReasoningEffort>(['low', 'medium', 'high', 'xhigh', 'max']);
58
52
 
59
- /**
60
- * Enforce the resolved permission policy for one Copilot request. Returns a
61
- * reject decision for blocked tools, or null to fall through to auto-approve.
62
- */
63
- function enforceCopilotPermission(
64
- permissions: ResolvedPermissions,
65
- request: PermissionRequest
66
- ): PermissionRequestResult | null {
67
- const token = copilotPermissionToken(request);
68
- if (!isToolAllowed(permissions, token)) {
69
- debug.log('permissions', `⛔ Blocked tool "${token}" (Clopen permission policy)`);
70
- return { kind: 'reject', feedback: `Blocked by Clopen permission policy: ${token}` };
71
- }
72
- return null;
73
- }
74
53
  import {
75
54
  createStreamConverterState,
76
55
  convertSessionStart,
@@ -134,12 +113,6 @@ export class CopilotEngine implements AIEngine {
134
113
  */
135
114
  private runs = new EngineRuns<CopilotRun>();
136
115
  private modelsCache: ModelInfo[] | null = null;
137
- /**
138
- * Account ID currently baked into `this.client`. The Copilot SDK takes the
139
- * GitHub token as a constructor argument, so per-stream account overrides
140
- * require disposing and re-creating the client (see streamQuery below).
141
- */
142
- private currentAccountId: number | null = null;
143
116
 
144
117
  /**
145
118
  * AskUserQuestion bookkeeping. The Copilot SDK splits the `ask_user`
@@ -167,18 +140,17 @@ export class CopilotEngine implements AIEngine {
167
140
  return this.runs.isActive;
168
141
  }
169
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
+ */
170
150
  async initialize(accountId?: number): Promise<void> {
171
- if (this._isInitialized && (accountId == null || accountId === this.currentAccountId)) {
172
- return;
173
- }
174
-
175
- const account = accountId != null
176
- ? engineQueries.getAccount(accountId)
177
- : engineQueries.getActiveAccountForEngine('copilot');
178
- if (!account) {
179
- throw new Error('Copilot is not configured. Add a Personal Access Token in Settings → Engines → Copilot.');
180
- }
151
+ if (this._isInitialized) return;
181
152
 
153
+ const account = resolveCopilotAccount(accountId);
182
154
  const { CopilotClient } = await loadEngineSdk<typeof import('@github/copilot-sdk')>('copilot', '@github/copilot-sdk');
183
155
 
184
156
  this.client = new CopilotClient({
@@ -188,10 +160,10 @@ export class CopilotEngine implements AIEngine {
188
160
  // {clopenDir}/engine/copilot/user/ instead of the shared ~/.copilot. The SDK
189
161
  // forwards this as COPILOT_HOME to the spawned runtime.
190
162
  baseDirectory: getEngineUserConfigDir('copilot'),
163
+ clientInfo: { applicationName: 'clopen' },
191
164
  });
192
165
 
193
166
  await this.client.start();
194
- this.currentAccountId = account.id;
195
167
  this._isInitialized = true;
196
168
  debug.log('engine', `Copilot engine initialized (account ${account.id})`);
197
169
  }
@@ -217,7 +189,6 @@ export class CopilotEngine implements AIEngine {
217
189
 
218
190
  this.client = null;
219
191
  this.modelsCache = null;
220
- this.currentAccountId = null;
221
192
  this._isInitialized = false;
222
193
  debug.log('engine', 'Copilot engine disposed');
223
194
  }
@@ -238,22 +209,13 @@ export class CopilotEngine implements AIEngine {
238
209
  async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
239
210
  const { projectPath, prompt, resume, modelId, reasoningEffort, abortController, accountId } = options;
240
211
 
241
- // Copilot's `reasoningEffort` accepts low | medium | high | xhigh; only
242
- // applied for models that support it (unsupported tokens are dropped so
243
- // the SDK falls back to the model default).
244
- const copilotEfforts = new Set<string>(['low', 'medium', 'high', 'xhigh']);
212
+ // Unknown tokens are dropped so the SDK falls back to the model default.
245
213
  const reasoningOption: Pick<ResumeSessionConfig, 'reasoningEffort'> | Record<string, never> =
246
- reasoningEffort && copilotEfforts.has(reasoningEffort)
247
- ? { reasoningEffort: reasoningEffort as ResumeSessionConfig['reasoningEffort'] }
214
+ reasoningEffort && COPILOT_EFFORTS.has(reasoningEffort)
215
+ ? { reasoningEffort: reasoningEffort as CopilotReasoningEffort }
248
216
  : {};
249
217
 
250
- // Per-stream account override: the Copilot SDK takes the GitHub token at
251
- // construction time, so an account switch requires recreating the client.
252
- if (this._isInitialized && accountId != null && accountId !== this.currentAccountId) {
253
- debug.log('engine', `Copilot account switch ${this.currentAccountId} → ${accountId}; re-initializing client`);
254
- await this.dispose();
255
- }
256
-
218
+ const auth = sessionAuth(accountId);
257
219
  if (!this._isInitialized || !this.client) {
258
220
  await this.initialize(accountId);
259
221
  }
@@ -344,7 +306,13 @@ export class CopilotEngine implements AIEngine {
344
306
  try {
345
307
  const mcpConfig = getCopilotMcpConfig(mcpProfileFilter, options.mcpContext);
346
308
 
309
+ const managedSettings = buildCopilotManagedSettings(permissions);
310
+
347
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 }),
348
316
  onPermissionRequest: (request, invocation) =>
349
317
  enforceCopilotPermission(permissions, request) ?? approveAll(request, invocation),
350
318
  // Enables the agent's `ask_user` tool. Without this callback the
@@ -429,12 +397,13 @@ export class CopilotEngine implements AIEngine {
429
397
  try {
430
398
  session = await this.client.resumeSession(resumeId, baseConfig);
431
399
  debug.log('engine', `Copilot resumed session: ${resumeId}${resumeId === resume ? '' : ` (forked from ${resume})`}`);
400
+ await reloadInstructions(session);
432
401
  } catch (error) {
433
402
  debug.warn('engine', `Failed to resume Copilot session ${resumeId}, creating fresh:`, error);
434
- session = await this.client.createSession({ ...baseConfig } as SessionConfig);
403
+ session = await this.client.createSession(freshSessionConfig(baseConfig));
435
404
  }
436
405
  } else {
437
- session = await this.client.createSession({ ...baseConfig } as SessionConfig);
406
+ session = await this.client.createSession(freshSessionConfig(baseConfig));
438
407
  }
439
408
 
440
409
  run.session = session;
@@ -708,9 +677,7 @@ export class CopilotEngine implements AIEngine {
708
677
  accountId,
709
678
  } = options;
710
679
 
711
- if (this._isInitialized && accountId != null && accountId !== this.currentAccountId) {
712
- await this.dispose();
713
- }
680
+ const auth = sessionAuth(accountId);
714
681
  if (!this._isInitialized || !this.client) {
715
682
  await this.initialize(accountId);
716
683
  }
@@ -725,6 +692,7 @@ export class CopilotEngine implements AIEngine {
725
692
  const jsonPrompt = buildJsonPrompt(prompt, schema);
726
693
 
727
694
  const session = await this.client.createSession({
695
+ ...auth,
728
696
  model: modelId,
729
697
  workingDirectory: resolvedProjectPath,
730
698
  onPermissionRequest: approveAll,
@@ -778,6 +746,48 @@ export class CopilotEngine implements AIEngine {
778
746
  // Helpers
779
747
  // ============================================================================
780
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
+
781
791
  function extractPromptText(prompt: EngineQueryOptions['prompt']): string {
782
792
  const parts: string[] = [];
783
793
  for (const block of prompt.content) {
@@ -275,10 +275,12 @@ export class CursorEngine implements AIEngine {
275
275
 
276
276
  // Build the user turn (text + image attachments).
277
277
  //
278
- // The artifact context rides the user message because `@cursor/sdk` has no
279
- // system-prompt option — `AgentOptions` exposes model/tools/mcpServers/agents
280
- // and nothing else. It is rebuilt per turn on purpose: the active Profile can
281
- // 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.
282
284
  const promptText = prompt.content.filter(b => b.type === 'text').map(b => (b.type === 'text' ? b.text : '')).join('\n');
283
285
  const artifacts = buildArtifactsPromptContext('cursor', profileId, projectBridge);
284
286
  const text = artifacts ? `${artifacts}\n\n${promptText}` : promptText;
@@ -309,6 +311,8 @@ export class CursorEngine implements AIEngine {
309
311
  },
310
312
  });
311
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.
312
316
 
313
317
  // Abort wiring: cancelling the stream cancels the Cursor run.
314
318
  onAbort = () => { run.cancel().catch(() => { /* already terminal */ }); };
@@ -26,6 +26,31 @@ export interface ModelsDevProvider {
26
26
  api: string | null;
27
27
  }
28
28
 
29
+ /**
30
+ * OpenAI-compatible providers that models.dev doesn't list. They ride the same
31
+ * path as catalog providers with an `api` URL: stored with `api_url`, the
32
+ * account key becomes the bearer, and models are discovered from `/models`.
33
+ * A models.dev entry with the same id wins, so these retire themselves once
34
+ * upstream adds them.
35
+ */
36
+ const CURATED_PROVIDERS: ModelsDevProvider[] = [
37
+ {
38
+ id: 'vikey',
39
+ name: 'Vikey',
40
+ npm: '@ai-sdk/openai-compatible',
41
+ env: ['VIKEY_API_KEY'],
42
+ api: 'https://api.vikey.ai/v1',
43
+ },
44
+ ];
45
+
46
+ /** Merge curated providers into a models.dev catalog, keeping it name-sorted. */
47
+ export function withCuratedProviders(catalog: ModelsDevProvider[]): ModelsDevProvider[] {
48
+ const ids = new Set(catalog.map(c => c.id));
49
+ const extras = CURATED_PROVIDERS.filter(c => !ids.has(c.id));
50
+ if (extras.length === 0) return catalog;
51
+ return [...catalog, ...extras].sort((a, b) => a.name.localeCompare(b.name));
52
+ }
53
+
29
54
  /**
30
55
  * Fetch models.dev/api.json and cache a minimal provider catalog in the DB.
31
56
  * Returns the parsed catalog.
@@ -68,7 +93,7 @@ export async function fetchAndCacheModelsDevCatalog(): Promise<ModelsDevProvider
68
93
  settingsQueries.set(CACHE_TS_KEY, new Date().toISOString());
69
94
 
70
95
  debug.log('engine', `Cached ${catalog.length} providers from models.dev`);
71
- return catalog;
96
+ return withCuratedProviders(catalog);
72
97
  }
73
98
 
74
99
  /**
@@ -82,7 +107,7 @@ export function getCachedModelsDevCatalog(): { catalog: ModelsDevProvider[]; cac
82
107
 
83
108
  try {
84
109
  return {
85
- catalog: JSON.parse(cached.value) as ModelsDevProvider[],
110
+ catalog: withCuratedProviders(JSON.parse(cached.value) as ModelsDevProvider[]),
86
111
  cachedAt: cachedAt.value,
87
112
  };
88
113
  } catch {
@@ -551,9 +551,11 @@ async function buildProviderSection(): Promise<Record<string, unknown>> {
551
551
  // malformed options — proceed to auto-discover
552
552
  }
553
553
 
554
- const addModel = (id: string) => {
554
+ // `advertisedContext` comes from discovery: many OpenAI-compatible
555
+ // gateways report `context_window`/`context_length` on /models.
556
+ const addModel = (id: string, advertisedContext?: number) => {
555
557
  const lim = modelLimits[id];
556
- models[id] = { name: modelNames[id] || id, limit: { context: lim?.context || defaultContext, output: lim?.output || defaultOutput } };
558
+ models[id] = { name: modelNames[id] || id, limit: { context: lim?.context || advertisedContext || defaultContext, output: lim?.output || defaultOutput } };
557
559
  };
558
560
 
559
561
  for (const id of storedModels) {
@@ -569,9 +571,9 @@ async function buildProviderSection(): Promise<Record<string, unknown>> {
569
571
  signal: AbortSignal.timeout(3000),
570
572
  });
571
573
  if (res.ok) {
572
- const body = await res.json() as { data?: { id: string }[] };
574
+ const body = await res.json() as { data?: { id: string; context_window?: number; context_length?: number }[] };
573
575
  for (const m of body.data ?? []) {
574
- addModel(m.id);
576
+ addModel(m.id, m.context_window || m.context_length);
575
577
  }
576
578
  }
577
579
  } catch {
@@ -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
+ });
@@ -18,6 +18,8 @@
18
18
 
19
19
  import type { Credential, CredentialInfo, CredentialStore } from '@earendil-works/pi-ai';
20
20
  import { engineQueries, type EngineAccount } from '$backend/database/queries/engine-queries';
21
+ import { settingsQueries } from '$backend/database/queries/settings-queries';
22
+ import { createKeyedLock } from '$backend/utils/keyed-lock';
21
23
  import { debug } from '$shared/utils/logger';
22
24
 
23
25
  /** The single `engine_providers` row that owns every Pi account (Qwen-style). */
@@ -31,13 +33,46 @@ export function getPiAccounts(): EngineAccount[] {
31
33
  return provider ? engineQueries.getAccountsByProvider(provider.id) : [];
32
34
  }
33
35
 
36
+ /**
37
+ * Provider ids pi-ai has renamed, old → new. Accounts, chat sessions and saved
38
+ * model choices keep whatever id they were created with, so every id coming in
39
+ * is read through this; a stored credential is rewritten under the new id the
40
+ * next time it is saved.
41
+ */
42
+ const RENAMED_PROVIDERS: Record<string, string> = {
43
+ // pi 1.0.3: the provider now also serves Foundry Chat Completions.
44
+ 'azure-openai-responses': 'azure',
45
+ };
46
+
47
+ /** The current pi-ai id for a provider id that may predate a rename. */
48
+ export function canonicalPiProviderId(providerId: string): string {
49
+ return RENAMED_PROVIDERS[providerId] ?? providerId;
50
+ }
51
+
34
52
  /** The account backing a given pi-ai provider id, preferring the active one. */
35
53
  export function getPiAccountForProvider(providerId: string): EngineAccount | null {
36
- const accounts = getPiAccounts().filter(a => parsePiCredential(a.credential)?.provider === providerId);
54
+ const wanted = canonicalPiProviderId(providerId);
55
+ const accounts = getPiAccounts().filter(a => parsePiCredential(a.credential)?.provider === wanted);
37
56
  if (accounts.length === 0) return null;
38
57
  return accounts.find(a => a.is_active === 1) ?? accounts[accounts.length - 1];
39
58
  }
40
59
 
60
+ const DEVICE_ID_KEY = 'pi_device_id';
61
+
62
+ /**
63
+ * Stable id of this Clopen installation, created on first use. Pi's login flows
64
+ * ask for it through `LoginOptions.getDeviceId` — Sign in with ChatGPT sends it
65
+ * to OpenAI as the agent host id and refuses to start without one. The Pi CLI
66
+ * keeps it in its global settings; Clopen keeps it in the `settings` table.
67
+ */
68
+ export function getPiDeviceId(): string {
69
+ const stored = settingsQueries.get(DEVICE_ID_KEY)?.value;
70
+ if (stored) return stored;
71
+ const id = crypto.randomUUID();
72
+ settingsQueries.set(DEVICE_ID_KEY, id);
73
+ return id;
74
+ }
75
+
41
76
  export interface PiCredential {
42
77
  /** pi-ai provider id (e.g. 'anthropic', 'openai', 'openai-codex'). */
43
78
  provider: string;
@@ -55,7 +90,7 @@ export function parsePiCredential(stored: string | null | undefined): PiCredenti
55
90
  if (!parsed || typeof parsed.provider !== 'string' || !parsed.provider) return null;
56
91
  const cred = parsed.credential as Credential | undefined;
57
92
  if (!cred || (cred.type !== 'api_key' && cred.type !== 'oauth')) return null;
58
- return { provider: parsed.provider, credential: cred };
93
+ return { provider: canonicalPiProviderId(parsed.provider), credential: cred };
59
94
  } catch {
60
95
  return null;
61
96
  }
@@ -72,6 +107,27 @@ export function describePiCredential(stored: string | null | undefined): { provi
72
107
  return { provider: parsed.provider, type: parsed.credential.type };
73
108
  }
74
109
 
110
+ /**
111
+ * Per-account write chain shared by EVERY store instance in the process. Each
112
+ * stream and each model-list refresh builds its own `DbCredentialStore`, but
113
+ * they all write the same row — and providers that rotate refresh tokens
114
+ * (OpenAI, Anthropic) revoke the grant when one token is spent twice. Pi's
115
+ * refresh re-checks expiry inside `modify`, so serializing here turns the
116
+ * second caller into a no-op instead of a second refresh.
117
+ */
118
+ const withAccountLock = createKeyedLock<number>();
119
+
120
+ /**
121
+ * Replace an account's stored credential (re-login, edited key) in line with
122
+ * any refresh in flight, so the refresh can't land afterwards and put the old
123
+ * grant back.
124
+ */
125
+ export function writePiAccountCredential(accountId: number, serialized: string): Promise<void> {
126
+ return withAccountLock(accountId, async () => {
127
+ engineQueries.updateAccountCredential(accountId, serialized);
128
+ });
129
+ }
130
+
75
131
  /**
76
132
  * A pi-ai `CredentialStore` backed by one or more `engine_accounts` rows.
77
133
  *
@@ -117,18 +173,18 @@ export class DbCredentialStore implements CredentialStore {
117
173
  fn: (current: Credential | undefined) => Promise<Credential | undefined>,
118
174
  ): Promise<Credential | undefined> {
119
175
  const accountId = this.providerToAccount.get(providerId);
120
- const current = accountId !== undefined
121
- ? parsePiCredential(engineQueries.getAccount(accountId)?.credential)?.credential
122
- : undefined;
123
-
124
- const next = await fn(current);
125
- if (next === undefined) return current;
126
-
127
- if (accountId !== undefined) {
176
+ // No row behind it (a login into an empty store): nothing to race over.
177
+ if (accountId === undefined) return (await fn(undefined)) ?? undefined;
178
+
179
+ return withAccountLock(accountId, async () => {
180
+ // Read inside the lock — a refresh that just finished must be seen.
181
+ const current = parsePiCredential(engineQueries.getAccount(accountId)?.credential)?.credential;
182
+ const next = await fn(current);
183
+ if (next === undefined) return current;
128
184
  engineQueries.updateAccountCredential(accountId, serializePiCredential({ provider: providerId, credential: next }));
129
185
  debug.log('engine', `Pi: persisted refreshed credential for provider "${providerId}" (account ${accountId})`);
130
- }
131
- return next;
186
+ return next;
187
+ });
132
188
  }
133
189
 
134
190
  async delete(providerId: string): Promise<void> {
@@ -2,11 +2,15 @@
2
2
  * Environment / directory isolation for the Pi engine.
3
3
  *
4
4
  * Pi is an IN-PROCESS SDK (`@earendil-works/pi-coding-agent`) — there is no CLI
5
- * subprocess and no env var to redirect a home dir. Instead every `ModelRuntime`
6
- * / `AgentSession` we build is pointed at an ISOLATED agent dir so Clopen never
7
- * reads or writes the user's real `~/.pi/agent`. Credentials do NOT live in that
8
- * dir's `auth.json`; they live in the `engine_accounts` table and are served to
9
- * the runtime through a DB-backed `CredentialStore` (see ./credential.ts).
5
+ * subprocess to hand an env to. `PI_CODING_AGENT_DIR` exists, but setting it on
6
+ * Clopen's own process would also redirect a `pi` the user runs in a terminal.
7
+ * Instead every `ModelRuntime` / `AgentSession` we build is pointed at an
8
+ * ISOLATED agent dir, and anything that falls back to Pi's `getAgentDir()` (the
9
+ * MCP extension's config and log) is overridden explicitly (see ./mcp.ts), so
10
+ * Clopen never reads or writes the user's real `~/.pi/agent`. Credentials do
11
+ * NOT live in that dir's `auth.json`; they live in the `engine_accounts` table
12
+ * and are served to the runtime through a DB-backed `CredentialStore` (see
13
+ * ./credential.ts).
10
14
  */
11
15
 
12
16
  import { join } from 'node:path';