@myrialabs/clopen 0.4.45 → 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.
- package/backend/artifacts/project/sources.ts +2 -2
- package/backend/engine/adapters/claude/models.test.ts +49 -0
- package/backend/engine/adapters/claude/models.ts +81 -562
- package/backend/engine/adapters/claude/stream.ts +5 -4
- package/backend/engine/adapters/cline/credential.ts +42 -18
- package/backend/engine/adapters/cline/message-converter.ts +31 -1
- package/backend/engine/adapters/cline/models.test.ts +77 -0
- package/backend/engine/adapters/cline/models.ts +89 -3
- package/backend/engine/adapters/cline/presets.ts +5 -0
- package/backend/engine/adapters/cline/stream.ts +9 -2
- package/backend/engine/adapters/codex/message-converter.ts +1 -1
- package/backend/engine/adapters/codex/models.ts +54 -31
- package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
- package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
- package/backend/engine/adapters/codex/session-fork.ts +5 -0
- package/backend/engine/adapters/codex/stream.ts +8 -7
- package/backend/engine/adapters/copilot/models.test.ts +40 -0
- package/backend/engine/adapters/copilot/models.ts +51 -24
- package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
- package/backend/engine/adapters/copilot/permissions.ts +72 -0
- package/backend/engine/adapters/copilot/stream.ts +77 -67
- package/backend/engine/adapters/cursor/stream.ts +8 -4
- package/backend/engine/adapters/pi/credential.test.ts +83 -0
- package/backend/engine/adapters/pi/credential.ts +68 -12
- package/backend/engine/adapters/pi/environment.ts +9 -5
- package/backend/engine/adapters/pi/mcp.test.ts +194 -0
- package/backend/engine/adapters/pi/mcp.ts +88 -0
- package/backend/engine/adapters/pi/message-converter.ts +6 -4
- package/backend/engine/adapters/pi/presets.ts +10 -5
- package/backend/engine/adapters/pi/stream.ts +42 -38
- package/backend/engine/adapters/qwen/environment.ts +39 -2
- package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
- package/backend/engine/adapters/qwen/message-converter.ts +40 -23
- package/backend/engine/adapters/qwen/models.test.ts +25 -0
- package/backend/engine/adapters/qwen/models.ts +42 -5
- package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
- package/backend/engine/adapters/qwen/session-store.ts +66 -0
- package/backend/engine/adapters/qwen/stream.ts +110 -87
- package/backend/engine/docs/adapter-contract.md +7 -4
- package/backend/engine/docs/lessons-learned.md +405 -62
- package/backend/engine/docs/quick-reference.md +2 -2
- package/backend/engine/docs/stack.md +17 -4
- package/backend/engine/docs/websocket-routes.md +5 -5
- package/backend/engine/install-recipes.test.ts +105 -5
- package/backend/engine/install-recipes.ts +102 -42
- package/backend/engine/install-runner.ts +56 -2
- package/backend/engine/stack-project.ts +71 -1
- package/backend/index.ts +5 -0
- package/backend/mcp/README.md +2 -2
- package/backend/mcp/external/config.ts +18 -0
- package/backend/mcp/external/proxy.ts +2 -2
- package/backend/mcp/index.ts +8 -0
- package/backend/mcp/internal/config.ts +42 -3
- package/backend/memory/embedding/install.ts +29 -1
- package/backend/utils/keyed-lock.test.ts +33 -0
- package/backend/utils/keyed-lock.ts +17 -0
- package/backend/utils/port-utils.test.ts +29 -0
- package/backend/utils/port-utils.ts +19 -0
- package/backend/ws/engine/cline/accounts.ts +26 -6
- package/backend/ws/engine/codex/accounts.test.ts +49 -0
- package/backend/ws/engine/codex/accounts.ts +17 -13
- package/backend/ws/engine/pi/accounts.ts +61 -6
- package/dist/assets/{index-D-Ad1N96.js → index-BTcR1byF.js} +1 -1
- package/dist/assets/{index-Am-rJRxA.js → index-CwuKQelV.js} +1 -1
- package/dist/assets/{main--PLCDxSy.css → main-BiDNMWb3.css} +1 -1
- package/dist/assets/{main-DelPm2Xt.js → main-BlhKWz2B.js} +595 -593
- package/dist/index.html +2 -2
- package/package.json +19 -15
- package/backend/engine/adapters/pi/mcp-tools.ts +0 -153
- package/backend/engine/adapters/qwen/session-fork.ts +0 -109
package/backend/mcp/index.ts
CHANGED
|
@@ -149,6 +149,14 @@ export function getCursorMcpConfig(profileFilter?: Set<string>, context?: McpExe
|
|
|
149
149
|
};
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
+
/** Pi MCP config: internal `clopen-mcp` remote bridge + external servers. */
|
|
153
|
+
export function getPiMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
|
|
154
|
+
return {
|
|
155
|
+
...internal.getPiMcpConfig(profileFilter, context),
|
|
156
|
+
...external.getPiExternalMcpConfig(profileFilter, context?.projectId)
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
152
160
|
/** Qwen Code MCP config. */
|
|
153
161
|
export function getQwenMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
|
|
154
162
|
return {
|
|
@@ -10,6 +10,7 @@ import type { McpRemoteConfig } from '@opencode-ai/sdk';
|
|
|
10
10
|
import type { MCPHTTPServerConfig } from '@github/copilot-sdk';
|
|
11
11
|
import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
|
|
12
12
|
import type { McpServerConfig as CursorMcpServerConfig } from '@cursor/sdk';
|
|
13
|
+
import type { McpServerConfig as PiMcpServerConfig } from '@earendil-works/pi-coding-agent';
|
|
13
14
|
import type { ServerConfig, ParsedMcpToolName, ServerName } from './types';
|
|
14
15
|
import type { McpExecutionContext } from '../../engine/types';
|
|
15
16
|
import type { EngineType } from '$shared/types/unified';
|
|
@@ -442,7 +443,7 @@ export function resolveOpenCodeToolName(toolName: string): string | null {
|
|
|
442
443
|
/**
|
|
443
444
|
* Loopback URL of the internal `clopen-mcp` bridge, addressed to the caller.
|
|
444
445
|
*
|
|
445
|
-
* The in-process engines (Claude,
|
|
446
|
+
* The in-process engines (Claude, Cline) bind `McpExecutionContext` around
|
|
446
447
|
* every tool handler, so a tool call always knows which project asked. The
|
|
447
448
|
* engines that reach the bridge over HTTP had no such thing: the request
|
|
448
449
|
* carries no identity, so the handler fell back to "the most recently started
|
|
@@ -453,8 +454,8 @@ export function resolveOpenCodeToolName(toolName: string): string | null {
|
|
|
453
454
|
* The query string closes that. Each config says as much as its own lifetime
|
|
454
455
|
* allows, and the bridge binds whatever it is told:
|
|
455
456
|
*
|
|
456
|
-
* - `project` + `session` — the caller named outright. Copilot, Cursor and
|
|
457
|
-
* build their config per stream, so both are true for the whole MCP session.
|
|
457
|
+
* - `project` + `session` — the caller named outright. Copilot, Cursor, Pi and
|
|
458
|
+
* Qwen build their config per stream, so both are true for the whole MCP session.
|
|
458
459
|
* - `project` alone — Codex, whose client (and therefore this URL) is built
|
|
459
460
|
* once per project and reused by every chat session in it.
|
|
460
461
|
* - `engine` alone — Open Code, whose URL is baked into a server the pool shares
|
|
@@ -664,6 +665,44 @@ export function getCursorMcpConfig(
|
|
|
664
665
|
};
|
|
665
666
|
}
|
|
666
667
|
|
|
668
|
+
// ============================================================================
|
|
669
|
+
// Pi MCP Configuration
|
|
670
|
+
// ============================================================================
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* Get MCP configuration for the Pi engine.
|
|
674
|
+
*
|
|
675
|
+
* Pi runs in-process but connects MCP servers with its own client (the SDK's
|
|
676
|
+
* `createMcpExtension`), so it reaches the SAME `/mcp` bridge as the other
|
|
677
|
+
* engines instead of calling handlers directly. `exposure: 'direct'` declares
|
|
678
|
+
* the tools to the model like any other tool — Pi's default (`codemode`) would
|
|
679
|
+
* hide them behind a scripting tool. The bearer header also keeps Pi's own
|
|
680
|
+
* OAuth flow (and its `mcp-auth.json`) out of the loop; `timeout` is seconds.
|
|
681
|
+
*/
|
|
682
|
+
export function getPiMcpConfig(
|
|
683
|
+
profileFilter?: Set<string>,
|
|
684
|
+
context?: McpExecutionContext
|
|
685
|
+
): Record<string, PiMcpServerConfig> {
|
|
686
|
+
const enabledServers = activeInternalServerNames(profileFilter);
|
|
687
|
+
if (enabledServers.length === 0) {
|
|
688
|
+
return {};
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
const url = internalBridgeUrl('pi', context);
|
|
692
|
+
|
|
693
|
+
debug.log('mcp', `📦 Pi MCP: remote server at ${url}`);
|
|
694
|
+
|
|
695
|
+
return {
|
|
696
|
+
'clopen-mcp': {
|
|
697
|
+
type: 'http',
|
|
698
|
+
url,
|
|
699
|
+
exposure: 'direct',
|
|
700
|
+
timeout: MCP_TOOL_CALL_TIMEOUT_MS / 1000,
|
|
701
|
+
headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
|
|
702
|
+
},
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
|
|
667
706
|
// ============================================================================
|
|
668
707
|
// Qwen Code MCP Configuration
|
|
669
708
|
// ============================================================================
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* neighbours forever, which is far harder to notice than a failed download.
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
|
-
import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
23
|
+
import { mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
24
24
|
import { join } from 'node:path';
|
|
25
25
|
import { debug } from '$shared/utils/logger';
|
|
26
26
|
import { embedder } from './embedder';
|
|
@@ -160,6 +160,7 @@ async function run(): Promise<boolean> {
|
|
|
160
160
|
if (isEmbeddingArtifactInstalled()) {
|
|
161
161
|
const loaded = await embedder.load();
|
|
162
162
|
if (loaded) {
|
|
163
|
+
void pruneStaleVersions();
|
|
163
164
|
clearRetry();
|
|
164
165
|
setStatus({
|
|
165
166
|
phase: 'installed',
|
|
@@ -233,6 +234,7 @@ async function run(): Promise<boolean> {
|
|
|
233
234
|
embedder.unload();
|
|
234
235
|
const loaded = await embedder.load();
|
|
235
236
|
if (loaded) {
|
|
237
|
+
void pruneStaleVersions();
|
|
236
238
|
clearRetry();
|
|
237
239
|
setStatus({
|
|
238
240
|
phase: 'installed',
|
|
@@ -250,5 +252,31 @@ async function run(): Promise<boolean> {
|
|
|
250
252
|
return loaded;
|
|
251
253
|
}
|
|
252
254
|
|
|
255
|
+
/**
|
|
256
|
+
* Remove every other version's directory — and any leftover `.partial` staging
|
|
257
|
+
* dir — once the current version has loaded. A version bump downloads into a
|
|
258
|
+
* fresh directory and nothing ever read the old one again, so it sat there for
|
|
259
|
+
* good. Gated on a successful load so an upgrade that fails keeps the previous
|
|
260
|
+
* artifact on disk.
|
|
261
|
+
*/
|
|
262
|
+
async function pruneStaleVersions(): Promise<void> {
|
|
263
|
+
const root = getStackEmbeddingDir();
|
|
264
|
+
let entries: string[];
|
|
265
|
+
try {
|
|
266
|
+
entries = await readdir(root);
|
|
267
|
+
} catch {
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
for (const entry of entries) {
|
|
271
|
+
if (entry === EMBEDDING_VERSION) continue;
|
|
272
|
+
try {
|
|
273
|
+
await rm(join(root, entry), { recursive: true, force: true });
|
|
274
|
+
debug.log('memory', `Removed superseded embedding artifact: ${entry}`);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
debug.warn('memory', `Could not remove superseded embedding artifact ${entry}`, error);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
253
281
|
/** Marker so the catch can tell a bad payload from a bad connection. */
|
|
254
282
|
class CorruptAssetError extends Error {}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { createKeyedLock } from './keyed-lock';
|
|
3
|
+
|
|
4
|
+
const tick = () => new Promise((resolve) => setTimeout(resolve, 5));
|
|
5
|
+
|
|
6
|
+
describe('createKeyedLock', () => {
|
|
7
|
+
test('runs tasks for one key one at a time, in order', async () => {
|
|
8
|
+
const lock = createKeyedLock<number>();
|
|
9
|
+
const order: string[] = [];
|
|
10
|
+
await Promise.all([1, 2, 3].map((n) => lock(7, async () => {
|
|
11
|
+
order.push(`start ${n}`);
|
|
12
|
+
await tick();
|
|
13
|
+
order.push(`end ${n}`);
|
|
14
|
+
})));
|
|
15
|
+
expect(order).toEqual(['start 1', 'end 1', 'start 2', 'end 2', 'start 3', 'end 3']);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('a failed task does not block the next one', async () => {
|
|
19
|
+
const lock = createKeyedLock<string>();
|
|
20
|
+
const failed = lock('a', async () => { throw new Error('boom'); });
|
|
21
|
+
await expect(failed).rejects.toThrow('boom');
|
|
22
|
+
expect(await lock('a', async () => 'next')).toBe('next');
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test('different keys do not wait on each other', async () => {
|
|
26
|
+
const lock = createKeyedLock<string>();
|
|
27
|
+
let release!: () => void;
|
|
28
|
+
const blocked = lock('a', () => new Promise<void>((resolve) => { release = resolve; }));
|
|
29
|
+
expect(await lock('b', async () => 'free')).toBe('free');
|
|
30
|
+
release();
|
|
31
|
+
await blocked;
|
|
32
|
+
});
|
|
33
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serialize async work per key within this process. Tasks for the same key run
|
|
3
|
+
* one after another (a failed task does not block the next); different keys
|
|
4
|
+
* never wait on each other.
|
|
5
|
+
*/
|
|
6
|
+
export function createKeyedLock<K>(): <T>(key: K, task: () => Promise<T>) => Promise<T> {
|
|
7
|
+
const tails = new Map<K, Promise<unknown>>();
|
|
8
|
+
return <T>(key: K, task: () => Promise<T>): Promise<T> => {
|
|
9
|
+
const run = (tails.get(key) ?? Promise.resolve()).then(task, task);
|
|
10
|
+
const settled = run.then(() => undefined, () => undefined);
|
|
11
|
+
tails.set(key, settled);
|
|
12
|
+
void settled.then(() => {
|
|
13
|
+
if (tails.get(key) === settled) tails.delete(key);
|
|
14
|
+
});
|
|
15
|
+
return run;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { hasLoopbackCallbackListener } from './port-utils';
|
|
3
|
+
|
|
4
|
+
const authUrl = (redirect: string) =>
|
|
5
|
+
`https://auth.example.com/authorize?${new URLSearchParams({ client_id: 'x', redirect_uri: redirect })}`;
|
|
6
|
+
|
|
7
|
+
describe('hasLoopbackCallbackListener', () => {
|
|
8
|
+
test('true while something listens on the loopback redirect port', async () => {
|
|
9
|
+
const server = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: () => new Response('ok') });
|
|
10
|
+
try {
|
|
11
|
+
expect(await hasLoopbackCallbackListener(authUrl(`http://127.0.0.1:${server.port}/auth/callback`))).toBe(true);
|
|
12
|
+
} finally {
|
|
13
|
+
server.stop(true);
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('false when nothing listens there', async () => {
|
|
18
|
+
const server = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: () => new Response('ok') });
|
|
19
|
+
const port = server.port;
|
|
20
|
+
server.stop(true);
|
|
21
|
+
expect(await hasLoopbackCallbackListener(authUrl(`http://127.0.0.1:${port}/auth/callback`))).toBe(false);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test('false for a hosted redirect or a URL without one', async () => {
|
|
25
|
+
expect(await hasLoopbackCallbackListener(authUrl('https://console.anthropic.com/oauth/code/callback'))).toBe(false);
|
|
26
|
+
expect(await hasLoopbackCallbackListener('https://auth.example.com/authorize')).toBe(false);
|
|
27
|
+
expect(await hasLoopbackCallbackListener('not a url')).toBe(false);
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -46,3 +46,22 @@ export async function findAvailablePort(startPort: number, maxAttempts = 8): Pro
|
|
|
46
46
|
}
|
|
47
47
|
throw new Error(`No available port found starting from ${startPort} (tried ${maxAttempts} ports)`);
|
|
48
48
|
}
|
|
49
|
+
|
|
50
|
+
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Whether an OAuth flow's loopback callback is actually listening, read off the
|
|
54
|
+
* `redirect_uri` of its authorization URL. Engine logins race that callback
|
|
55
|
+
* against a pasted redirect URL; the paste is only required when nothing is
|
|
56
|
+
* listening (the port was taken) or the redirect goes to a hosted page instead.
|
|
57
|
+
*/
|
|
58
|
+
export async function hasLoopbackCallbackListener(authUrl: string): Promise<boolean> {
|
|
59
|
+
try {
|
|
60
|
+
const redirect = new URL(new URL(authUrl).searchParams.get('redirect_uri') ?? '');
|
|
61
|
+
if (!LOOPBACK_HOSTS.has(redirect.hostname)) return false;
|
|
62
|
+
const port = Number(redirect.port || (redirect.protocol === 'https:' ? 443 : 80));
|
|
63
|
+
return await isPortInUse(port);
|
|
64
|
+
} catch {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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. **
|
|
11
|
-
* CLI thinks it's interactive and emits its banner +
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
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() }));
|