@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
@@ -28,10 +28,12 @@ import {
28
28
  getClineProvider,
29
29
  parseClineCredential,
30
30
  serializeClineCredential,
31
+ writeClineAccountCredential,
31
32
  type ClineCredential,
32
33
  } from '../../../engine/adapters/cline/credential';
33
34
  import { requireSetupSessionAccess } from '../access';
34
35
  import { debug } from '$shared/utils/logger';
36
+ import { hasLoopbackCallbackListener } from '$backend/utils/port-utils';
35
37
 
36
38
  async function disposeClineEngines(): Promise<void> {
37
39
  try {
@@ -51,6 +53,8 @@ interface ClineLoginSession {
51
53
  /** When set, re-authenticate this existing account in place instead of creating one. */
52
54
  reauthAccountId: number | null;
53
55
  pendingPrompt: { resolve: (value: string) => void; reject: (error: Error) => void } | null;
56
+ /** The flow's latest authorization URL, to tell an optional redirect paste from a required one. */
57
+ authUrl: string | null;
54
58
  timer: ReturnType<typeof setTimeout>;
55
59
  }
56
60
 
@@ -157,7 +161,7 @@ export const clineAccountsHandler = createRouter()
157
161
 
158
162
  let accountId: number;
159
163
  if (data.accountId != null && engineQueries.getAccount(data.accountId)) {
160
- engineQueries.updateAccountCredential(data.accountId, serialized);
164
+ await writeClineAccountCredential(data.accountId, serialized);
161
165
  engineQueries.renameAccount(data.accountId, data.name.trim());
162
166
  accountId = data.accountId;
163
167
  } else {
@@ -218,6 +222,7 @@ export const clineAccountsHandler = createRouter()
218
222
  name: data.name.trim(), provider: data.provider,
219
223
  reauthAccountId: data.reauthAccountId ?? null,
220
224
  pendingPrompt: null,
225
+ authUrl: null,
221
226
  timer: setTimeout(() => {
222
227
  ws.emit.user(userId, 'engine:cline-account-login-error', { loginId, message: 'Login timed out after 15 minutes' });
223
228
  cleanupLogin(loginId);
@@ -226,23 +231,35 @@ export const clineAccountsHandler = createRouter()
226
231
  loginSessions.set(loginId, entry);
227
232
  ws.emit.user(userId, 'engine:cline-account-login-started', { loginId });
228
233
 
229
- const awaitPrompt = (message: string): Promise<string> =>
234
+ // `onManualCodeInput` is raced against the loopback callback, so it is
235
+ // optional while that callback is listening; `onPrompt` only follows a
236
+ // callback that came back empty, so it is always required.
237
+ const awaitPrompt = (message: string, kind: 'text' | 'manual_code'): Promise<string> =>
230
238
  new Promise<string>((resolve, reject) => {
231
239
  entry.pendingPrompt = { resolve, reject };
232
- ws.emit.user(userId, 'engine:cline-account-login-prompt', { loginId, message });
240
+ const emitPrompt = (optional: boolean) =>
241
+ ws.emit.user(userId, 'engine:cline-account-login-prompt', { loginId, message, kind, optional });
242
+ if (kind === 'manual_code' && entry.authUrl) {
243
+ void hasLoopbackCallbackListener(entry.authUrl).then((listening) => {
244
+ if (entry.pendingPrompt?.resolve === resolve) emitPrompt(listening);
245
+ });
246
+ } else {
247
+ emitPrompt(false);
248
+ }
233
249
  });
234
250
 
235
251
  const callbacks: OAuthLoginCallbacks = {
236
252
  onAuth: (info: { url: string; instructions?: string }) => {
253
+ entry.authUrl = info.url;
237
254
  ws.emit.user(userId, 'engine:cline-account-login-event', {
238
255
  loginId, kind: 'auth_url', message: info.instructions, url: info.url,
239
256
  });
240
257
  },
241
- onPrompt: (prompt: OAuthPrompt) => awaitPrompt(prompt.message),
258
+ onPrompt: (prompt: OAuthPrompt) => awaitPrompt(prompt.message, 'text'),
242
259
  onProgress: (message: string) => {
243
260
  ws.emit.user(userId, 'engine:cline-account-login-event', { loginId, kind: 'progress', message });
244
261
  },
245
- onManualCodeInput: () => awaitPrompt('Paste the authorization code from your browser:'),
262
+ onManualCodeInput: () => awaitPrompt('Paste the authorization code from your browser:', 'manual_code'),
246
263
  };
247
264
 
248
265
  try {
@@ -252,7 +269,7 @@ export const clineAccountsHandler = createRouter()
252
269
  const serialized = serializeClineCredential({ provider: data.provider, authMethod: 'oauth', oauth: credential });
253
270
  let accountId: number;
254
271
  if (entry.reauthAccountId != null && engineQueries.getAccount(entry.reauthAccountId)) {
255
- engineQueries.updateAccountCredential(entry.reauthAccountId, serialized);
272
+ await writeClineAccountCredential(entry.reauthAccountId, serialized);
256
273
  engineQueries.renameAccount(entry.reauthAccountId, entry.name);
257
274
  accountId = entry.reauthAccountId;
258
275
  } else {
@@ -313,6 +330,9 @@ export const clineAccountsHandler = createRouter()
313
330
  .emit('engine:cline-account-login-prompt', t.Object({
314
331
  loginId: t.String(),
315
332
  message: t.String(),
333
+ kind: t.Union([t.Literal('text'), t.Literal('manual_code')]),
334
+ /** A manual fallback the flow can complete without (its loopback callback is listening). */
335
+ optional: t.Boolean(),
316
336
  }))
317
337
  .emit('engine:cline-account-login-complete', t.Object({ loginId: t.String(), accountId: t.Number() }))
318
338
  .emit('engine:cline-account-login-error', t.Object({ loginId: t.String(), message: t.String() }));
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `codex login` output is scraped from a PTY, so these pin the parsers to what
3
+ * the pinned CLI (0.159.3) actually prints for each sign-in method.
4
+ */
5
+
6
+ import { describe, expect, test } from 'bun:test';
7
+ import { extractAuthUrl, extractDeviceCode, isLoginSuccess } from './accounts';
8
+
9
+ const BROWSER_OUTPUT = `Starting local login server on http://localhost:1455.
10
+ If your browser did not open, navigate to this URL to authenticate:
11
+
12
+ https://auth.openai.com/oauth/authorize?response_type=code&client_id=app_EMoamEEZ73f0CkXaXp7hrann&redirect_uri=http%3A%2F%2F127.0.0.1%3A1455%2Fauth%2Fcallback&code_challenge=bL5H6vSHRqMufZdc1_eRnO1yvz7jym6dQFKGe11OmPg&code_challenge_method=S256&state=U83pc_Y3JBV1i6yqxiTawcFkdW1raWCRtt8zzI7l2zg&scope=openid+profile+email+offline_access&originator=codex_cli_rs
13
+
14
+ On a remote or headless machine? Use \`codex login --device-auth\` instead.
15
+ `;
16
+
17
+ const DEVICE_OUTPUT = `Welcome to Codex [v0.159.3]
18
+ OpenAI's command-line coding agent
19
+
20
+ Follow these steps to sign in with ChatGPT using device code authorization:
21
+
22
+ 1. Open this link in your browser and sign in to your account
23
+ https://auth.openai.com/codex/device
24
+
25
+ 2. Enter this one-time code (expires in 15 minutes)
26
+ 6XUJ-L2VE1
27
+
28
+ Continue only if you started this login in Codex. If a website or another person gave you this code, cancel.
29
+ `;
30
+
31
+ describe('codex login output', () => {
32
+ test('browser login: the authorize URL, whole, without the trailing hint', () => {
33
+ const url = extractAuthUrl(BROWSER_OUTPUT);
34
+ expect(url).toStartWith('https://auth.openai.com/oauth/authorize?response_type=code');
35
+ expect(url).toEndWith('originator=codex_cli_rs');
36
+ expect(new URL(url!).searchParams.get('redirect_uri')).toBe('http://127.0.0.1:1455/auth/callback');
37
+ expect(extractDeviceCode(BROWSER_OUTPUT)).toBeNull();
38
+ });
39
+
40
+ test('device login: the verification URL and one-time code', () => {
41
+ expect(extractDeviceCode(DEVICE_OUTPUT)).toEqual({ code: '6XUJ-L2VE1', verificationUrl: 'https://auth.openai.com/codex/device' });
42
+ expect(extractAuthUrl(DEVICE_OUTPUT)).toBeNull();
43
+ });
44
+
45
+ test('success line, shared by both methods', () => {
46
+ expect(isLoginSuccess('Successfully logged in.')).toBe(true);
47
+ expect(isLoginSuccess(BROWSER_OUTPUT)).toBe(false);
48
+ });
49
+ });
@@ -7,15 +7,19 @@
7
7
  * is wrapped as `{kind:"api_key", apiKey}` and stored in
8
8
  * `engine_accounts.credential`. No filesystem mutation.
9
9
  *
10
- * 2. **ChatGPT browser OAuth** — spawn `codex login` inside a PTY (so the
11
- * CLI thinks it's interactive and emits its banner + URL prompt),
12
- * scrape stdout for the `https://auth.openai.com/...` URL, surface it
13
- * to the UI. The CLI writes `~/.codex/auth.json` after the user
14
- * finishes OAuth in the browser. We snapshot the file content into
15
- * `engine_accounts.credential` as `{kind:"chatgpt", authJson:<file>}`.
16
- *
17
- * Headless fallback: `codex login --device-auth` produces a device code
18
- * printed to stdout that the user enters at openai.com/auth/device.
10
+ * 2. **Sign in with ChatGPT** — spawn `codex login` inside a PTY (so the
11
+ * CLI thinks it's interactive and emits its banner + prompt) and scrape
12
+ * stdout. The user picks the method:
13
+ * - browser (`codex login`): the CLI prints an
14
+ * `https://auth.openai.com/oauth/authorize…` URL and finishes on its
15
+ * own through a loopback callback on the server (127.0.0.1:1455, or
16
+ * the next free port), so it only completes when the browser runs on
17
+ * the same machine;
18
+ * - device code (`codex login --device-auth`): a one-time code the user
19
+ * enters at auth.openai.com/codex/device — works from anywhere.
20
+ * The CLI writes `auth.json` into Clopen's isolated CODEX_HOME; we
21
+ * snapshot it into `engine_accounts.credential` as
22
+ * `{kind:"chatgpt", authJson:<file>}`.
19
23
  *
20
24
  * Switching between accounts:
21
25
  * - chatgpt → write the stored `authJson` blob back to `~/.codex/auth.json`
@@ -118,13 +122,13 @@ function cleanupSetup(setupId: string): void {
118
122
  setupProcesses.delete(setupId);
119
123
  }
120
124
 
121
- function extractAuthUrl(buffer: string): string | null {
125
+ export function extractAuthUrl(buffer: string): string | null {
122
126
  // Browser-OAuth flow URL printed by `codex login` (no --device-auth).
123
127
  const match = buffer.match(/https:\/\/auth\.openai\.com\/oauth\/authorize\?[^\s]+/);
124
128
  return match ? match[0] : null;
125
129
  }
126
130
 
127
- function extractDeviceCode(buffer: string): { code: string; verificationUrl: string } | null {
131
+ export function extractDeviceCode(buffer: string): { code: string; verificationUrl: string } | null {
128
132
  // `codex login --device-auth` (v0.120+) prints a multi-line block:
129
133
  // 1. Open this link in your browser and sign in to your account
130
134
  // https://auth.openai.com/codex/device
@@ -146,7 +150,7 @@ function extractDeviceCode(buffer: string): { code: string; verificationUrl: str
146
150
  return { code: codeMatch[1], verificationUrl: urlMatch[0] };
147
151
  }
148
152
 
149
- function isLoginSuccess(buffer: string): boolean {
153
+ export function isLoginSuccess(buffer: string): boolean {
150
154
  return /Successfully logged in/i.test(buffer);
151
155
  }
152
156
 
@@ -306,7 +310,7 @@ export const codexAccountsHandler = createRouter()
306
310
  return { success: true };
307
311
  })
308
312
 
309
- // ─── ChatGPT browser OAuth flow ───
313
+ // ─── Sign in with ChatGPT (browser or device code) ───
310
314
  //
311
315
  // Spawn `codex login` in a PTY (the CLI silently no-ops when stdout
312
316
  // isn't a TTY), scan stdout for the URL/device-code prompt, surface it
@@ -20,8 +20,9 @@ import type { AuthEvent, AuthInteraction, AuthPrompt, AuthType, Credential } fro
20
20
  import { engineQueries } from '../../../database/queries';
21
21
  import { disposeAllProjectEnginesByType } from '../../../engine';
22
22
  import { createPiRuntime, getPiProviderFields } from '../../../engine/adapters/pi/presets';
23
- import { DbCredentialStore, serializePiCredential, parsePiCredential, getPiProvider } from '../../../engine/adapters/pi/credential';
23
+ import { DbCredentialStore, serializePiCredential, parsePiCredential, getPiProvider, getPiDeviceId, writePiAccountCredential } from '../../../engine/adapters/pi/credential';
24
24
  import { requireSetupSessionAccess } from '../access';
25
+ import { hasLoopbackCallbackListener } from '$backend/utils/port-utils';
25
26
  import { debug } from '$shared/utils/logger';
26
27
 
27
28
  async function disposePiEngines(): Promise<void> {
@@ -43,6 +44,8 @@ interface PiLoginSession {
43
44
  /** When set, re-authenticate this existing account in place instead of creating one. */
44
45
  reauthAccountId: number | null;
45
46
  pendingPrompt: { resolve: (value: string) => void; reject: (error: Error) => void } | null;
47
+ /** The flow's latest authorization URL, to tell an optional redirect paste from a required one. */
48
+ authUrl: string | null;
46
49
  timer: ReturnType<typeof setTimeout>;
47
50
  }
48
51
 
@@ -60,6 +63,32 @@ function cleanupLogin(loginId: string): void {
60
63
  loginSessions.delete(loginId);
61
64
  }
62
65
 
66
+ /**
67
+ * Turn a login failure into something the user can act on.
68
+ *
69
+ * - Sign in with ChatGPT holds 127.0.0.1:1455 for its callback and, since pi
70
+ * 1.0.1, fails outright when the port is taken instead of continuing into a
71
+ * state mismatch. Codex's browser login listens there first and moves on when
72
+ * it can't, so in Clopen the usual holder is a Codex or ChatGPT sign-in still
73
+ * waiting in another panel — pi's own wording ("another pi session") doesn't
74
+ * say that.
75
+ * - `invalid_grant` on the code exchange right after the browser reported
76
+ * success was earendil-works/pi#10258 (closed upstream 2026-10-02); should it
77
+ * recur, a fresh browser session is what cleared it.
78
+ */
79
+ function explainLoginError(provider: string, type: string, error: unknown): string {
80
+ const message = error instanceof Error ? error.message : 'Login failed';
81
+ const port = message.match(/Port (\d+) is in use/)?.[1];
82
+ if (port) {
83
+ return `Another sign-in is still waiting on port ${port} — a Codex or ChatGPT login in Clopen, or the Codex CLI. Finish or cancel it, then try again.`;
84
+ }
85
+ if (provider === 'openai' && type === 'oauth' && message.includes('invalid_grant')) {
86
+ return 'OpenAI rejected the sign-in (invalid_grant). Sign out of chatgpt.com or use a private window, then try again. '
87
+ + 'If it keeps failing, sign in through the "OpenAI Codex (legacy)" provider instead.';
88
+ }
89
+ return message;
90
+ }
91
+
63
92
  export const piAccountsHandler = createRouter()
64
93
 
65
94
  // ═══ CRUD ═══
@@ -140,7 +169,7 @@ export const piAccountsHandler = createRouter()
140
169
 
141
170
  let accountId: number;
142
171
  if (data.accountId != null && engineQueries.getAccount(data.accountId)) {
143
- engineQueries.updateAccountCredential(data.accountId, serialized);
172
+ await writePiAccountCredential(data.accountId, serialized);
144
173
  engineQueries.renameAccount(data.accountId, data.name.trim());
145
174
  accountId = data.accountId;
146
175
  } else {
@@ -196,6 +225,7 @@ export const piAccountsHandler = createRouter()
196
225
  name: data.name.trim(), provider: data.provider,
197
226
  reauthAccountId: data.reauthAccountId ?? null,
198
227
  pendingPrompt: null,
228
+ authUrl: null,
199
229
  timer: setTimeout(() => {
200
230
  ws.emit.user(userId, 'engine:pi-account-login-error', { loginId, message: 'Login timed out after 15 minutes' });
201
231
  cleanupLogin(loginId);
@@ -207,6 +237,7 @@ export const piAccountsHandler = createRouter()
207
237
  const interaction: AuthInteraction = {
208
238
  signal: controller.signal,
209
239
  notify: (event: AuthEvent) => {
240
+ if (event.type === 'auth_url') entry.authUrl = event.url;
210
241
  ws.emit.user(userId, 'engine:pi-account-login-event', {
211
242
  loginId,
212
243
  kind: event.type,
@@ -215,12 +246,22 @@ export const piAccountsHandler = createRouter()
215
246
  instructions: event.type === 'auth_url' ? event.instructions : undefined,
216
247
  userCode: event.type === 'device_code' ? event.userCode : undefined,
217
248
  verificationUri: event.type === 'device_code' ? event.verificationUri : undefined,
249
+ links: event.type === 'info' && event.links?.length ? [...event.links] : undefined,
218
250
  });
219
251
  },
220
252
  prompt: (prompt: AuthPrompt) => {
221
253
  return new Promise<string>((resolve, reject) => {
222
254
  entry.pendingPrompt = { resolve, reject };
223
- ws.emit.user(userId, 'engine:pi-account-login-prompt', {
255
+ // A manual fallback (paste the redirect URL) is raced against the
256
+ // browser callback; Pi aborts it once the callback wins, so take it
257
+ // off the screen instead of leaving a field nobody needs.
258
+ prompt.signal?.addEventListener('abort', () => {
259
+ if (entry.pendingPrompt?.resolve !== resolve) return;
260
+ entry.pendingPrompt = null;
261
+ reject(new Error('Prompt closed'));
262
+ ws.emit.user(userId, 'engine:pi-account-login-prompt-closed', { loginId });
263
+ }, { once: true });
264
+ const emitPrompt = (optional: boolean) => ws.emit.user(userId, 'engine:pi-account-login-prompt', {
224
265
  loginId,
225
266
  kind: prompt.type,
226
267
  message: prompt.message,
@@ -228,14 +269,24 @@ export const piAccountsHandler = createRouter()
228
269
  options: prompt.type === 'select'
229
270
  ? prompt.options.map(o => ({ id: o.id, label: o.label, description: o.description }))
230
271
  : undefined,
272
+ optional,
231
273
  });
274
+ // A pasted redirect is optional only while the flow's loopback
275
+ // callback can still complete the login by itself.
276
+ if (prompt.type === 'manual_code' && prompt.signal && entry.authUrl) {
277
+ void hasLoopbackCallbackListener(entry.authUrl).then((listening) => {
278
+ if (entry.pendingPrompt?.resolve === resolve) emitPrompt(listening);
279
+ });
280
+ } else {
281
+ emitPrompt(false);
282
+ }
232
283
  });
233
284
  },
234
285
  };
235
286
 
236
287
  try {
237
288
  const runtime = await createPiRuntime(new DbCredentialStore([]));
238
- const credential = await runtime.login(data.provider, data.type as AuthType, interaction);
289
+ const credential = await runtime.login(data.provider, data.type as AuthType, interaction, { getDeviceId: getPiDeviceId });
239
290
  if (entry.disposed) return;
240
291
 
241
292
  const serialized = serializePiCredential({ provider: data.provider, credential });
@@ -243,7 +294,7 @@ export const piAccountsHandler = createRouter()
243
294
  if (entry.reauthAccountId != null && engineQueries.getAccount(entry.reauthAccountId)) {
244
295
  // Re-authenticate in place — update the credential (and name) of the
245
296
  // existing account rather than creating a duplicate.
246
- engineQueries.updateAccountCredential(entry.reauthAccountId, serialized);
297
+ await writePiAccountCredential(entry.reauthAccountId, serialized);
247
298
  engineQueries.renameAccount(entry.reauthAccountId, entry.name);
248
299
  accountId = entry.reauthAccountId;
249
300
  } else {
@@ -260,7 +311,7 @@ export const piAccountsHandler = createRouter()
260
311
  debug.warn('engine', `Pi login failed: ${error instanceof Error ? error.message : String(error)}`);
261
312
  ws.emit.user(userId, 'engine:pi-account-login-error', {
262
313
  loginId,
263
- message: error instanceof Error ? error.message : 'Login failed',
314
+ message: explainLoginError(data.provider, data.type, error),
264
315
  });
265
316
  }
266
317
  cleanupLogin(loginId);
@@ -303,6 +354,7 @@ export const piAccountsHandler = createRouter()
303
354
  instructions: t.Optional(t.String()),
304
355
  userCode: t.Optional(t.String()),
305
356
  verificationUri: t.Optional(t.String()),
357
+ links: t.Optional(t.Array(t.Object({ url: t.String(), label: t.Optional(t.String()) }))),
306
358
  }))
307
359
  .emit('engine:pi-account-login-prompt', t.Object({
308
360
  loginId: t.String(),
@@ -314,6 +366,9 @@ export const piAccountsHandler = createRouter()
314
366
  label: t.String(),
315
367
  description: t.Optional(t.String()),
316
368
  }))),
369
+ /** A manual fallback the flow can complete without (its loopback callback is listening). */
370
+ optional: t.Boolean(),
317
371
  }))
372
+ .emit('engine:pi-account-login-prompt-closed', t.Object({ loginId: t.String() }))
318
373
  .emit('engine:pi-account-login-complete', t.Object({ loginId: t.String(), accountId: t.Number() }))
319
374
  .emit('engine:pi-account-login-error', t.Object({ loginId: t.String(), message: t.String() }));
@@ -39,6 +39,7 @@ import { integrationsRouter } from './integrations';
39
39
  import { skillsRouter } from './skills';
40
40
  import { subagentsRouter } from './subagents';
41
41
  import { instructionsRouter } from './instructions';
42
+ import { projectArtifactsRouter } from './project-artifacts';
42
43
  import { permissionsRouter } from './permissions';
43
44
  import { profilesRouter } from './profiles';
44
45
  import { artifactsRouter } from './artifacts';
@@ -112,6 +113,9 @@ export const wsRouter = createRouter()
112
113
  .merge(instructionsRouter)
113
114
  .merge(permissionsRouter)
114
115
 
116
+ // The active project's own artifacts (`.agents/`, `.claude/`, AGENTS.md, …)
117
+ .merge(projectArtifactsRouter)
118
+
115
119
  // Profiles (reusable artifact bundles activated per-session)
116
120
  .merge(profilesRouter)
117
121
  .merge(artifactsRouter)
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Project Artifacts Router — the "This project" side of Settings → Artifacts &
3
+ * Access: what the repository carries (`.agents/`, `.claude/`, `AGENTS.md`, …),
4
+ * which engines read each item, and in-place edits.
5
+ *
6
+ * Every route resolves the repository from `projectId` server-side (never from
7
+ * a client path) and reads the MAIN project checkout — worktrees follow it once
8
+ * the change is committed and merged. Writes go only to `.agents/` and the
9
+ * managed block of `AGENTS.md` (see `backend/artifacts/project/edit.ts`).
10
+ * Admin-only: see ADMIN_ONLY_ROUTES.
11
+ */
12
+
13
+ import { t } from 'elysia';
14
+ import { createRouter } from '$shared/utils/ws-server';
15
+ import type { WSConnection } from '$shared/utils/ws-server';
16
+ import { debug } from '$shared/utils/logger';
17
+ import { ws } from '$backend/utils/ws';
18
+ import { requireProjectAccess } from '../access';
19
+ import { projectMcpTrustQueries } from '$backend/database/queries';
20
+ import {
21
+ scanProject,
22
+ readProjectFile,
23
+ saveProjectSkill,
24
+ deleteProjectSkill,
25
+ saveProjectSubagent,
26
+ deleteProjectSubagent,
27
+ copyToAgents,
28
+ readAgentsMd,
29
+ saveAgentsMd,
30
+ saveProjectMcp,
31
+ hashContent,
32
+ PROJECT_WRITE_PATHS
33
+ } from '$backend/artifacts/project';
34
+ import { readProjectMcpFile } from '$backend/mcp';
35
+
36
+ const COVERAGE = t.Record(t.String(), t.String());
37
+
38
+ const ITEM = t.Object({
39
+ kind: t.String(),
40
+ slug: t.String(),
41
+ name: t.String(),
42
+ description: t.String(),
43
+ sourceId: t.String(),
44
+ sourcePath: t.String(),
45
+ path: t.String(),
46
+ editable: t.Boolean(),
47
+ shadowedBy: t.Union([t.String(), t.Null()]),
48
+ coverage: COVERAGE
49
+ });
50
+
51
+ const SCAN = t.Object({
52
+ root: t.String(),
53
+ skills: t.Array(ITEM),
54
+ subagents: t.Array(ITEM),
55
+ instructions: t.Array(t.Object({
56
+ sourceId: t.String(),
57
+ path: t.String(),
58
+ fileCount: t.Union([t.Number(), t.Null()]),
59
+ size: t.Number(),
60
+ editable: t.Boolean(),
61
+ note: t.Union([t.String(), t.Null()]),
62
+ coverage: COVERAGE
63
+ })),
64
+ mcp: t.Array(t.Object({
65
+ sourceId: t.String(),
66
+ path: t.String(),
67
+ editable: t.Boolean(),
68
+ servers: t.Array(t.Object({
69
+ name: t.String(),
70
+ transport: t.String(),
71
+ command: t.Union([t.String(), t.Null()]),
72
+ args: t.Array(t.String()),
73
+ env: t.Record(t.String(), t.String()),
74
+ url: t.Union([t.String(), t.Null()]),
75
+ headers: t.Record(t.String(), t.String())
76
+ })),
77
+ error: t.Union([t.String(), t.Null()]),
78
+ hash: t.String(),
79
+ coverage: COVERAGE
80
+ })),
81
+ claudePermissions: t.Array(t.Object({ path: t.String(), allow: t.Array(t.String()), deny: t.Array(t.String()) })),
82
+ mcpTrust: t.Union([t.Object({ hash: t.String(), approvedBy: t.Union([t.String(), t.Null()]), approvedAt: t.String() }), t.Null()])
83
+ });
84
+
85
+ const SAVED = t.Object({ slug: t.String(), path: t.String() });
86
+
87
+ const AGENTS_MD = t.Object({ exists: t.Boolean(), content: t.String() });
88
+
89
+ /** Project row + repository root for a request, with the caller's access checked. */
90
+ function projectRoot(conn: WSConnection, projectId: string): { root: string; projectId: string } {
91
+ const project = requireProjectAccess(conn, projectId);
92
+ if (!project.path) throw new Error('Project has no path on disk');
93
+ return { root: project.path, projectId };
94
+ }
95
+
96
+ async function scanFor(conn: WSConnection, projectId: string) {
97
+ const { root } = projectRoot(conn, projectId);
98
+ const scan = await scanProject(root, hash => projectMcpTrustQueries.isTrusted(projectId, hash));
99
+ const trust = projectMcpTrustQueries.get(projectId);
100
+ return {
101
+ ...scan,
102
+ mcpTrust: trust ? { hash: trust.file_hash, approvedBy: trust.approved_by, approvedAt: trust.approved_at } : null
103
+ };
104
+ }
105
+
106
+ export const projectArtifactsRouter = createRouter()
107
+ .http('project-artifacts:scan', {
108
+ data: t.Object({ projectId: t.String() }),
109
+ response: SCAN
110
+ }, async ({ data, conn }) => {
111
+ debug.log('path', `project-artifacts:scan ${data.projectId}`);
112
+ return scanFor(conn, data.projectId);
113
+ })
114
+
115
+ .http('project-artifacts:read', {
116
+ data: t.Object({ projectId: t.String(), path: t.String() }),
117
+ response: t.Object({ content: t.String() })
118
+ }, async ({ data, conn }) => {
119
+ const { root } = projectRoot(conn, data.projectId);
120
+ return { content: await readProjectFile(root, data.path) };
121
+ })
122
+
123
+ // ── Skills: .agents/skills/<slug>/SKILL.md ─────────────────────────────────
124
+ .http('project-artifacts:save-skill', {
125
+ data: t.Object({
126
+ projectId: t.String(),
127
+ originalSlug: t.Optional(t.String()),
128
+ name: t.String(),
129
+ description: t.String(),
130
+ body: t.String()
131
+ }),
132
+ response: SAVED
133
+ }, async ({ data, conn }) => {
134
+ debug.log('path', `project-artifacts:save-skill ${data.projectId} ${data.name}`);
135
+ const { root } = projectRoot(conn, data.projectId);
136
+ return saveProjectSkill(root, data);
137
+ })
138
+ .http('project-artifacts:delete-skill', {
139
+ data: t.Object({ projectId: t.String(), slug: t.String() }),
140
+ response: t.Object({ success: t.Boolean() })
141
+ }, async ({ data, conn }) => {
142
+ debug.log('path', `project-artifacts:delete-skill ${data.projectId} ${data.slug}`);
143
+ const { root } = projectRoot(conn, data.projectId);
144
+ await deleteProjectSkill(root, data.slug);
145
+ return { success: true };
146
+ })
147
+
148
+ // ── Subagents: .agents/agents/<slug>.md ────────────────────────────────────
149
+ .http('project-artifacts:save-subagent', {
150
+ data: t.Object({
151
+ projectId: t.String(),
152
+ originalSlug: t.Optional(t.String()),
153
+ name: t.String(),
154
+ description: t.String(),
155
+ tools: t.Optional(t.String()),
156
+ model: t.Optional(t.String()),
157
+ body: t.String()
158
+ }),
159
+ response: SAVED
160
+ }, async ({ data, conn }) => {
161
+ debug.log('path', `project-artifacts:save-subagent ${data.projectId} ${data.name}`);
162
+ const { root } = projectRoot(conn, data.projectId);
163
+ return saveProjectSubagent(root, data);
164
+ })
165
+ .http('project-artifacts:delete-subagent', {
166
+ data: t.Object({ projectId: t.String(), slug: t.String() }),
167
+ response: t.Object({ success: t.Boolean() })
168
+ }, async ({ data, conn }) => {
169
+ debug.log('path', `project-artifacts:delete-subagent ${data.projectId} ${data.slug}`);
170
+ const { root } = projectRoot(conn, data.projectId);
171
+ await deleteProjectSubagent(root, data.slug);
172
+ return { success: true };
173
+ })
174
+
175
+ .http('project-artifacts:copy-to-agents', {
176
+ data: t.Object({ projectId: t.String(), kind: t.Union([t.Literal('skill'), t.Literal('subagent')]), path: t.String() }),
177
+ response: SAVED
178
+ }, async ({ data, conn }) => {
179
+ debug.log('path', `project-artifacts:copy-to-agents ${data.projectId} ${data.path}`);
180
+ const { root } = projectRoot(conn, data.projectId);
181
+ return copyToAgents(root, data.kind, data.path);
182
+ })
183
+
184
+ // ── Instructions: AGENTS.md ───────────────────────────────
185
+ .http('project-artifacts:get-agents-md', {
186
+ data: t.Object({ projectId: t.String() }),
187
+ response: AGENTS_MD
188
+ }, async ({ data, conn }) => {
189
+ const { root } = projectRoot(conn, data.projectId);
190
+ return readAgentsMd(root);
191
+ })
192
+ .http('project-artifacts:save-agents-md', {
193
+ data: t.Object({ projectId: t.String(), content: t.String() }),
194
+ response: AGENTS_MD
195
+ }, async ({ data, conn }) => {
196
+ debug.log('path', `project-artifacts:save-agents-md ${data.projectId}`);
197
+ const { root } = projectRoot(conn, data.projectId);
198
+ return saveAgentsMd(root, data.content);
199
+ })
200
+
201
+ // ── MCP: .agents/mcp.json + trust gate ─────────────────────────────────────
202
+ .http('project-artifacts:get-mcp', {
203
+ data: t.Object({ projectId: t.String() }),
204
+ response: t.Object({ path: t.String(), content: t.String() })
205
+ }, async ({ data, conn }) => {
206
+ const { root } = projectRoot(conn, data.projectId);
207
+ return { path: PROJECT_WRITE_PATHS.mcp, content: readProjectMcpFile(root) ?? '' };
208
+ })
209
+ .http('project-artifacts:save-mcp', {
210
+ data: t.Object({ projectId: t.String(), content: t.String() }),
211
+ response: t.Object({ hash: t.String() })
212
+ }, async ({ data, conn }) => {
213
+ debug.log('path', `project-artifacts:save-mcp ${data.projectId}`);
214
+ const { root, projectId } = projectRoot(conn, data.projectId);
215
+ const hash = await saveProjectMcp(root, data.content);
216
+ // An admin writing the file from Settings IS the approval: they authored
217
+ // exactly this content. Edits from anywhere else still need approving.
218
+ if (hash) projectMcpTrustQueries.approve(projectId, hash, ws.getUserId(conn));
219
+ else projectMcpTrustQueries.revoke(projectId);
220
+ return { hash };
221
+ })
222
+ .http('project-artifacts:approve-mcp', {
223
+ data: t.Object({ projectId: t.String(), hash: t.String() }),
224
+ response: t.Object({ success: t.Boolean() })
225
+ }, async ({ data, conn }) => {
226
+ debug.log('path', `project-artifacts:approve-mcp ${data.projectId}`);
227
+ const { root, projectId } = projectRoot(conn, data.projectId);
228
+ const raw = readProjectMcpFile(root);
229
+ // Approve only what the admin actually reviewed: the hash they saw must
230
+ // still be the file on disk.
231
+ if (raw == null || hashContent(raw) !== data.hash) {
232
+ throw new Error('.agents/mcp.json changed since it was shown — review it again before approving');
233
+ }
234
+ projectMcpTrustQueries.approve(projectId, data.hash, ws.getUserId(conn));
235
+ return { success: true };
236
+ });