@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.
- package/backend/artifacts/project/bridge.ts +218 -0
- package/backend/artifacts/project/edit.ts +243 -0
- package/backend/artifacts/project/index.ts +38 -0
- package/backend/artifacts/project/project.test.ts +181 -0
- package/backend/artifacts/project/scan.ts +368 -0
- package/backend/artifacts/project/sources.ts +100 -0
- package/backend/artifacts/sync.ts +1 -1
- package/backend/auth/permissions.ts +15 -0
- package/backend/chat/stream-manager.ts +20 -3
- package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
- 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 +32 -5
- package/backend/engine/adapters/cline/credential.ts +42 -18
- package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
- 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 +29 -8
- 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 +29 -11
- 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 +83 -70
- package/backend/engine/adapters/cursor/stream.ts +27 -12
- package/backend/engine/adapters/opencode/server.ts +14 -4
- package/backend/engine/adapters/opencode/stream.ts +18 -3
- 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 +77 -41
- 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 +118 -87
- package/backend/engine/artifact-sync.ts +12 -5
- 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/files/file-watcher.test.ts +77 -0
- package/backend/files/file-watcher.ts +92 -60
- package/backend/files/watch-ignore.test.ts +182 -0
- package/backend/files/watch-ignore.ts +244 -0
- package/backend/git/git-executor.ts +14 -4
- package/backend/index.ts +16 -1
- package/backend/instructions/service.ts +5 -3
- package/backend/instructions/sync.ts +10 -27
- package/backend/mcp/README.md +2 -2
- package/backend/mcp/external/config.ts +83 -23
- package/backend/mcp/external/project.ts +124 -0
- package/backend/mcp/external/proxy.ts +65 -11
- package/backend/mcp/index.ts +22 -9
- package/backend/mcp/internal/config.ts +42 -3
- package/backend/mcp/internal/remote-server.ts +11 -1
- package/backend/memory/embedding/install.ts +29 -1
- package/backend/skills/marketplace.ts +1 -1
- package/backend/snapshot/blob-store.ts +9 -5
- package/backend/snapshot/git-attribution.test.ts +42 -0
- package/backend/snapshot/git-attribution.ts +306 -0
- package/backend/snapshot/gitignore.test.ts +62 -0
- package/backend/snapshot/gitignore.ts +158 -78
- package/backend/snapshot/snapshot-service.test.ts +270 -0
- package/backend/snapshot/snapshot-service.ts +412 -136
- package/backend/snapshot/turn-activity.test.ts +52 -0
- package/backend/snapshot/turn-activity.ts +83 -0
- package/backend/snapshot/turn-changes.test.ts +58 -1
- package/backend/snapshot/turn-changes.ts +66 -0
- 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/worktrees/tree.ts +1 -1
- package/backend/ws/chat/composer.ts +504 -0
- package/backend/ws/chat/index.ts +3 -1
- package/backend/ws/chat/stream.ts +252 -440
- 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/backend/ws/index.ts +4 -0
- package/backend/ws/project-artifacts/index.ts +236 -0
- package/backend/ws/snapshot/changes.ts +66 -31
- package/dist/assets/{index-DX5OwLOc.js → index-BTcR1byF.js} +1 -1
- package/dist/assets/{index-BWyhqUi5.js → index-CwuKQelV.js} +1 -1
- package/dist/assets/main-BiDNMWb3.css +1 -0
- package/dist/assets/main-BlhKWz2B.js +1241 -0
- package/dist/index.html +2 -2
- package/package.json +19 -15
- package/shared/types/stores/settings.ts +5 -0
- package/shared/types/unified/message.ts +2 -0
- package/backend/engine/adapters/pi/mcp-tools.ts +0 -131
- package/backend/engine/adapters/qwen/session-fork.ts +0 -109
- package/dist/assets/main-DOkwqXRU.js +0 -1215
- package/dist/assets/main-DzCY0n-j.css +0 -1
|
@@ -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
|
|
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
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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
|
-
|
|
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
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
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';
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi's native MCP wiring, end to end against the real SDK: a loopback MCP
|
|
3
|
+
* server stands in for Clopen's bridge and a scripted OpenAI-compatible
|
|
4
|
+
* endpoint plays the model, so the turn runs through Pi's own tool pipeline.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';
|
|
8
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { randomUUID } from 'node:crypto';
|
|
12
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
13
|
+
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
|
14
|
+
import { z } from 'zod';
|
|
15
|
+
import type { AgentSession, ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
16
|
+
import type { EngineOutput, MessageEngine } from '$shared/types/unified';
|
|
17
|
+
|
|
18
|
+
// The SDK lives in the managed stack dir at runtime; tests load the repo's copy.
|
|
19
|
+
// Keep the whole module surface — `mock.module` replaces it for the process.
|
|
20
|
+
const realLoader = { ...(await import('$backend/engine/sdk-loader')) };
|
|
21
|
+
mock.module('$backend/engine/sdk-loader', () => ({
|
|
22
|
+
...realLoader,
|
|
23
|
+
loadEngineSdk: async (_engine: string, packageName: string) => import(packageName),
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
const sdk = await import('@earendil-works/pi-coding-agent');
|
|
27
|
+
const { createPiMcpExtension, resolvePiToolName } = await import('./mcp');
|
|
28
|
+
const { createPiMessageConverter } = await import('./message-converter');
|
|
29
|
+
|
|
30
|
+
const TOKEN = 'test-service-token';
|
|
31
|
+
|
|
32
|
+
let dir: string;
|
|
33
|
+
let mcpServer: ReturnType<typeof Bun.serve>;
|
|
34
|
+
let llmServer: ReturnType<typeof Bun.serve>;
|
|
35
|
+
const mcpCalls: string[] = [];
|
|
36
|
+
let closedMcpSessions = 0;
|
|
37
|
+
const declaredTools: string[][] = [];
|
|
38
|
+
|
|
39
|
+
/** Stateful MCP server, so a client closing its session is observable (DELETE). */
|
|
40
|
+
function startMcpServer(): ReturnType<typeof Bun.serve> {
|
|
41
|
+
const transports = new Map<string, WebStandardStreamableHTTPServerTransport>();
|
|
42
|
+
return Bun.serve({
|
|
43
|
+
port: 0,
|
|
44
|
+
async fetch(request) {
|
|
45
|
+
if (request.headers.get('authorization') !== `Bearer ${TOKEN}`) return new Response('unauthorized', { status: 401 });
|
|
46
|
+
const sessionId = request.headers.get('mcp-session-id');
|
|
47
|
+
if (sessionId && transports.has(sessionId)) {
|
|
48
|
+
if (request.method === 'DELETE') closedMcpSessions++;
|
|
49
|
+
return transports.get(sessionId)!.handleRequest(request);
|
|
50
|
+
}
|
|
51
|
+
const server = new McpServer({ name: 'fixture', version: '1.0.0' });
|
|
52
|
+
server.registerTool('get-page', { description: 'Read a page', inputSchema: { id: z.string() } }, async ({ id }) => {
|
|
53
|
+
mcpCalls.push(`get-page:${id}`);
|
|
54
|
+
return { content: [{ type: 'text', text: `page ${id}` }] };
|
|
55
|
+
});
|
|
56
|
+
server.registerTool('delete-page', { description: 'Delete a page', inputSchema: {} }, async () => {
|
|
57
|
+
mcpCalls.push('delete-page');
|
|
58
|
+
return { content: [{ type: 'text', text: 'deleted' }] };
|
|
59
|
+
});
|
|
60
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
61
|
+
sessionIdGenerator: () => randomUUID(),
|
|
62
|
+
enableJsonResponse: true,
|
|
63
|
+
onsessioninitialized: (id) => { transports.set(id, transport); },
|
|
64
|
+
});
|
|
65
|
+
await server.connect(transport);
|
|
66
|
+
return transport.handleRequest(request);
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Chat-completions SSE: the first request calls both MCP tools, the next one answers. */
|
|
72
|
+
function startModelServer(): ReturnType<typeof Bun.serve> {
|
|
73
|
+
return Bun.serve({
|
|
74
|
+
port: 0,
|
|
75
|
+
async fetch(request) {
|
|
76
|
+
const body = await request.json() as { tools?: { function: { name: string } }[] };
|
|
77
|
+
declaredTools.push((body.tools ?? []).map((tool) => tool.function.name));
|
|
78
|
+
const base = { id: 'chunk', object: 'chat.completion.chunk', created: 0, model: 'scripted' };
|
|
79
|
+
const delta = declaredTools.length === 1
|
|
80
|
+
? { role: 'assistant', tool_calls: [
|
|
81
|
+
{ index: 0, id: 'call_read', type: 'function', function: { name: 'mcp__ext_server__get_page', arguments: '{"id":"42"}' } },
|
|
82
|
+
{ index: 1, id: 'call_delete', type: 'function', function: { name: 'mcp__ext_server__delete_page', arguments: '{}' } },
|
|
83
|
+
] }
|
|
84
|
+
: { role: 'assistant', content: 'done' };
|
|
85
|
+
const finish = declaredTools.length === 1 ? 'tool_calls' : 'stop';
|
|
86
|
+
const events = [
|
|
87
|
+
{ ...base, choices: [{ index: 0, delta, finish_reason: null }] },
|
|
88
|
+
{ ...base, choices: [{ index: 0, delta: {}, finish_reason: finish }] },
|
|
89
|
+
{ ...base, choices: [], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } },
|
|
90
|
+
];
|
|
91
|
+
const stream = events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('') + 'data: [DONE]\n\n';
|
|
92
|
+
return new Response(stream, { headers: { 'content-type': 'text/event-stream' } });
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
beforeAll(() => {
|
|
98
|
+
dir = mkdtempSync(join(tmpdir(), 'clopen-pi-mcp-'));
|
|
99
|
+
mcpServer = startMcpServer();
|
|
100
|
+
llmServer = startModelServer();
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
afterAll(() => {
|
|
104
|
+
mcpServer.stop(true);
|
|
105
|
+
llmServer.stop(true);
|
|
106
|
+
rmSync(dir, { recursive: true, force: true });
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
describe('resolvePiToolName', () => {
|
|
110
|
+
test('passes non-MCP names and a missing session through', () => {
|
|
111
|
+
expect(resolvePiToolName(null, 'mcp__a_b__c')).toBe('mcp__a_b__c');
|
|
112
|
+
const session = { getToolDefinition: () => undefined } as unknown as AgentSession;
|
|
113
|
+
expect(resolvePiToolName(session, 'read')).toBe('read');
|
|
114
|
+
expect(resolvePiToolName(session, 'mcp__unknown__tool')).toBe('mcp__unknown__tool');
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('recovers the namespace and tool name Pi sanitized, from the label', () => {
|
|
118
|
+
const session = { getToolDefinition: () => ({ label: 'my-server/get.page' }) } as unknown as AgentSession;
|
|
119
|
+
expect(resolvePiToolName(session, 'mcp__my_server__get_page')).toBe('mcp__my-server__get.page');
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe('Pi native MCP turn', () => {
|
|
124
|
+
test('declares, gates by canonical name, runs and closes MCP tools', async () => {
|
|
125
|
+
const agentDir = join(dir, 'agent');
|
|
126
|
+
const cwd = join(dir, 'project');
|
|
127
|
+
const modelsPath = join(dir, 'models.json');
|
|
128
|
+
writeFileSync(modelsPath, JSON.stringify({
|
|
129
|
+
providers: {
|
|
130
|
+
scripted: {
|
|
131
|
+
baseUrl: `http://localhost:${llmServer.port}/v1`,
|
|
132
|
+
api: 'openai-completions',
|
|
133
|
+
apiKey: 'unused',
|
|
134
|
+
models: [{ id: 'scripted', name: 'Scripted', reasoning: false, input: ['text'], contextWindow: 100_000, maxTokens: 1_000, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
}));
|
|
138
|
+
const runtime = await sdk.ModelRuntime.create({ modelsPath, modelsStorePath: join(dir, 'models-store.json') });
|
|
139
|
+
const model = runtime.getModels().find((m) => m.provider === 'scripted')!;
|
|
140
|
+
|
|
141
|
+
let session: AgentSession | null = null;
|
|
142
|
+
const blocked: string[] = [];
|
|
143
|
+
const permissionBlocker = (pi: ExtensionAPI) => {
|
|
144
|
+
pi.on('tool_call', async (event: { toolName: string }) => {
|
|
145
|
+
const toolName = resolvePiToolName(session, event.toolName);
|
|
146
|
+
if (toolName !== 'mcp__ext-server__delete-page') return undefined;
|
|
147
|
+
blocked.push(toolName);
|
|
148
|
+
return { block: true, reason: 'denied' };
|
|
149
|
+
});
|
|
150
|
+
};
|
|
151
|
+
const mcpExtension = await createPiMcpExtension({
|
|
152
|
+
'ext-server': {
|
|
153
|
+
type: 'http',
|
|
154
|
+
url: `http://localhost:${mcpServer.port}/mcp`,
|
|
155
|
+
headers: { Authorization: `Bearer ${TOKEN}` },
|
|
156
|
+
exposure: 'direct',
|
|
157
|
+
timeout: 60,
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
const resourceLoader = new sdk.DefaultResourceLoader({ cwd, agentDir, extensionFactories: [permissionBlocker, mcpExtension] });
|
|
161
|
+
await resourceLoader.reload();
|
|
162
|
+
({ session } = await sdk.createAgentSession({
|
|
163
|
+
cwd,
|
|
164
|
+
agentDir,
|
|
165
|
+
model,
|
|
166
|
+
modelRuntime: runtime,
|
|
167
|
+
resourceLoader,
|
|
168
|
+
excludeTools: ['write'],
|
|
169
|
+
sessionManager: sdk.SessionManager.inMemory(cwd),
|
|
170
|
+
settingsManager: sdk.SettingsManager.inMemory({ defaultTools: ['read', 'bash', 'write'] }),
|
|
171
|
+
}));
|
|
172
|
+
await session.bindExtensions({});
|
|
173
|
+
|
|
174
|
+
const converter = createPiMessageConverter({
|
|
175
|
+
engine: { type: 'pi' } as MessageEngine,
|
|
176
|
+
sessionId: session.sessionId,
|
|
177
|
+
resolveToolName: (name) => resolvePiToolName(session, name),
|
|
178
|
+
});
|
|
179
|
+
const outputs: EngineOutput[] = [];
|
|
180
|
+
session.subscribe((event) => { outputs.push(...converter.convert(event)); });
|
|
181
|
+
await session.prompt('go');
|
|
182
|
+
|
|
183
|
+
// MCP tools join the builtins instead of being filtered out by them.
|
|
184
|
+
expect(declaredTools[0]).toEqual(['read', 'bash', 'mcp__ext_server__get_page', 'mcp__ext_server__delete_page']);
|
|
185
|
+
const toolUses = outputs.flatMap((out) => out.type === 'assistant' ? out.content.filter((b) => b.type === 'tool_use').map((b) => b.name) : []);
|
|
186
|
+
expect(toolUses).toEqual(['mcp__ext-server__get-page', 'mcp__ext-server__delete-page']);
|
|
187
|
+
expect(blocked).toEqual(['mcp__ext-server__delete-page']);
|
|
188
|
+
expect(mcpCalls).toEqual(['get-page:42']);
|
|
189
|
+
|
|
190
|
+
await session.extensionRunner.emit({ type: 'session_shutdown', reason: 'quit' });
|
|
191
|
+
session.dispose();
|
|
192
|
+
expect(closedMcpSessions).toBe(1);
|
|
193
|
+
}, 30_000);
|
|
194
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi native MCP wiring.
|
|
3
|
+
*
|
|
4
|
+
* Pi ships its own MCP client (`createMcpExtension`, built on `@earendil-works/pi-mcp`).
|
|
5
|
+
* SDK sessions don't load it by default, so we add it to the resource loader
|
|
6
|
+
* with a Clopen-owned config: the internal `clopen-mcp` bridge plus one bridge
|
|
7
|
+
* per external / approved project server — the same `/mcp` endpoints the other
|
|
8
|
+
* engines use (see `getPiMcpConfig`). Clopen stays the single MCP authority:
|
|
9
|
+
*
|
|
10
|
+
* - `loadConfig` replaces Pi's own `mcp.json` discovery, which reads the REAL
|
|
11
|
+
* `~/.pi/agent` (Pi's `getAgentDir()`, not the isolated dir we pass the session).
|
|
12
|
+
* - Every entry carries the service-token `Authorization` header, so Pi never
|
|
13
|
+
* starts its OAuth flow; upstream OAuth stays in Clopen's proxy.
|
|
14
|
+
* - `logPath` / `openUrl` / `updateConfig` keep the extension from writing to
|
|
15
|
+
* `~/.pi/agent` or opening a browser.
|
|
16
|
+
*
|
|
17
|
+
* Pi names tools `mcp__<server>__<tool>` with every non-`[A-Za-z0-9_]` char
|
|
18
|
+
* turned into `_` (and a hash suffix on collision), so names like
|
|
19
|
+
* `mcp__clopen_mcp__actions` are lossy. The tool's `label` keeps the original
|
|
20
|
+
* `<server>/<tool>`, which {@link resolvePiToolName} maps back to Clopen's
|
|
21
|
+
* canonical `mcp__<namespace>__<tool>`.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { join } from 'node:path';
|
|
25
|
+
import type { AgentSession, ExtensionAPI, ExtensionContext, ExtensionFactory, McpServerConfig } from '@earendil-works/pi-coding-agent';
|
|
26
|
+
import { INTERNAL_BRIDGE_NAMESPACE, resolveOpenCodeToolName } from '../../../mcp';
|
|
27
|
+
import { loadEngineSdk } from '$backend/engine/sdk-loader';
|
|
28
|
+
import { getPiAgentDir } from './environment';
|
|
29
|
+
import { debug } from '$shared/utils/logger';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Pi's MCP extension, fed `servers` (from `getPiMcpConfig`) instead of any
|
|
33
|
+
* `mcp.json` on disk. Pi reports failed connections and config errors only
|
|
34
|
+
* through `ctx.ui.notify`, which is a no-op in an SDK session, so a server that
|
|
35
|
+
* never connected just left its tools missing. Those notices go to the debug
|
|
36
|
+
* log instead.
|
|
37
|
+
*/
|
|
38
|
+
export async function createPiMcpExtension(servers: Record<string, McpServerConfig>): Promise<ExtensionFactory> {
|
|
39
|
+
const { createMcpExtension } = await loadEngineSdk<typeof import('@earendil-works/pi-coding-agent')>('pi', '@earendil-works/pi-coding-agent');
|
|
40
|
+
const factory = createMcpExtension({
|
|
41
|
+
loadConfig: () => ({
|
|
42
|
+
servers: Object.entries(servers).map(([name, config]) => ({ name, config, source: 'clopen', scope: 'extension' })),
|
|
43
|
+
autoEnableCodemode: false,
|
|
44
|
+
errors: [],
|
|
45
|
+
}),
|
|
46
|
+
logPath: join(getPiAgentDir(), 'mcp.log'),
|
|
47
|
+
openUrl: (url) => debug.warn('mcp', `Pi MCP asked to open ${url}; ignored (Clopen owns MCP sign-in)`),
|
|
48
|
+
updateConfig: () => { /* servers come from Clopen's DB, not a file */ },
|
|
49
|
+
});
|
|
50
|
+
return (pi) => factory(withLoggedNotices(pi));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** `pi`, whose event handlers get a context with `ui.notify` routed to the debug log. */
|
|
54
|
+
function withLoggedNotices(pi: ExtensionAPI): ExtensionAPI {
|
|
55
|
+
const on = ((event: string, handler: (event: unknown, ctx: ExtensionContext) => unknown) =>
|
|
56
|
+
pi.on(event as never, ((payload: unknown, ctx: ExtensionContext) => handler(payload, withLoggedNotify(ctx))) as never)) as ExtensionAPI['on'];
|
|
57
|
+
return new Proxy(pi, { get: (target, key) => key === 'on' ? on : bound(target, key) });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function withLoggedNotify(ctx: ExtensionContext): ExtensionContext {
|
|
61
|
+
const notify = (message: string, type: 'info' | 'warning' | 'error' = 'info') => {
|
|
62
|
+
if (type === 'info') debug.log('mcp', `Pi MCP: ${message}`);
|
|
63
|
+
else debug.warn('mcp', `Pi MCP: ${message}`);
|
|
64
|
+
};
|
|
65
|
+
const ui = new Proxy(ctx.ui, { get: (target, key) => key === 'notify' ? notify : bound(target, key) });
|
|
66
|
+
return new Proxy(ctx, { get: (target, key) => key === 'ui' ? ui : bound(target, key) });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A property read off the real object, methods bound to it (they may use private fields). */
|
|
70
|
+
function bound(target: object, key: string | symbol): unknown {
|
|
71
|
+
const value: unknown = Reflect.get(target, key, target);
|
|
72
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Map a Pi tool name to Clopen's canonical form. MCP tools resolve through
|
|
77
|
+
* their `<server>/<tool>` label; everything else passes through unchanged.
|
|
78
|
+
*/
|
|
79
|
+
export function resolvePiToolName(session: AgentSession | null, name: string): string {
|
|
80
|
+
if (!name.startsWith('mcp__') || !session) return name;
|
|
81
|
+
const label = session.getToolDefinition(name)?.label;
|
|
82
|
+
const slash = label?.indexOf('/') ?? -1;
|
|
83
|
+
if (!label || slash <= 0) return name;
|
|
84
|
+
const server = label.slice(0, slash);
|
|
85
|
+
const tool = label.slice(slash + 1);
|
|
86
|
+
if (server === INTERNAL_BRIDGE_NAMESPACE) return resolveOpenCodeToolName(tool) ?? `mcp__${server}__${tool}`;
|
|
87
|
+
return `mcp__${server}__${tool}`;
|
|
88
|
+
}
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
*
|
|
15
15
|
* Pi built-in tool names are lowercase (`read`, `bash`, …); we canonicalise them
|
|
16
16
|
* to the unified PascalCase names + normalise input field names so the shared
|
|
17
|
-
* tool UI renders identically to Claude/Codex. MCP tools
|
|
18
|
-
*
|
|
17
|
+
* tool UI renders identically to Claude/Codex. MCP tools arrive under Pi's
|
|
18
|
+
* sanitized names and are mapped back through `resolveToolName` (see ./mcp.ts).
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
21
|
import type { AgentSessionEvent } from '@earendil-works/pi-coding-agent';
|
|
@@ -180,6 +180,8 @@ function mapUsage(raw: PiUsage | null | undefined): TokenUsage | null {
|
|
|
180
180
|
export interface PiConverterOptions {
|
|
181
181
|
engine: MessageEngine;
|
|
182
182
|
sessionId: string;
|
|
183
|
+
/** Maps a Pi tool name to Clopen's canonical one (MCP names are sanitized by Pi). */
|
|
184
|
+
resolveToolName?: (name: string) => string;
|
|
183
185
|
}
|
|
184
186
|
|
|
185
187
|
export interface PiMessageConverter {
|
|
@@ -191,7 +193,7 @@ export interface PiMessageConverter {
|
|
|
191
193
|
}
|
|
192
194
|
|
|
193
195
|
export function createPiMessageConverter(options: PiConverterOptions): PiMessageConverter {
|
|
194
|
-
const { engine, sessionId } = options;
|
|
196
|
+
const { engine, sessionId, resolveToolName = (name: string) => name } = options;
|
|
195
197
|
const totalUsage: TokenUsage = { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0 };
|
|
196
198
|
let totalCostUsd = 0;
|
|
197
199
|
let turns = 0;
|
|
@@ -214,7 +216,7 @@ export function createPiMessageConverter(options: PiConverterOptions): PiMessage
|
|
|
214
216
|
if (block.text.trim()) blocks.push({ type: 'text', text: block.text });
|
|
215
217
|
} else if (block.type === 'toolCall') {
|
|
216
218
|
const call = block as PiToolCall;
|
|
217
|
-
const canonical = canonicaliseToolName(call.name);
|
|
219
|
+
const canonical = canonicaliseToolName(resolveToolName(call.name));
|
|
218
220
|
const finalName = toCanonicalToolName(canonical);
|
|
219
221
|
const rawInput = (call.arguments && typeof call.arguments === 'object' ? call.arguments : {}) as Record<string, unknown>;
|
|
220
222
|
blocks.push({
|
|
@@ -43,7 +43,7 @@ const PROVIDER_FIELDS: Record<string, PiCredentialField[]> = {
|
|
|
43
43
|
{ key: 'CLOUDFLARE_ACCOUNT_ID', label: 'Account ID', secret: false, role: 'env' },
|
|
44
44
|
{ key: 'CLOUDFLARE_GATEWAY_ID', label: 'Gateway ID', secret: false, role: 'env' },
|
|
45
45
|
],
|
|
46
|
-
|
|
46
|
+
azure: [
|
|
47
47
|
{ key: 'apiKey', label: 'API key', secret: true, role: 'key' },
|
|
48
48
|
{ key: 'AZURE_OPENAI_BASE_URL', label: 'Base URL', secret: false, role: 'env', placeholder: 'https://your-resource.openai.azure.com' },
|
|
49
49
|
],
|
|
@@ -87,12 +87,15 @@ const API_KEY_URLS: Record<string, string> = {
|
|
|
87
87
|
nvidia: 'https://build.nvidia.com',
|
|
88
88
|
};
|
|
89
89
|
|
|
90
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* Labels for the OAuth (subscription) option where Pi ships no `loginLabel` of
|
|
92
|
+
* its own. Pi's label wins when present; anything else falls back to its OAuth
|
|
93
|
+
* display name.
|
|
94
|
+
*/
|
|
91
95
|
const OAUTH_LABELS: Record<string, string> = {
|
|
92
96
|
anthropic: 'Sign in with Claude Pro/Max',
|
|
93
|
-
'openai-codex': 'Sign in with ChatGPT (
|
|
97
|
+
'openai-codex': 'Sign in with ChatGPT (legacy)',
|
|
94
98
|
'github-copilot': 'Sign in with GitHub Copilot',
|
|
95
|
-
xai: 'Sign in with SuperGrok or X Premium',
|
|
96
99
|
radius: 'Sign in with Radius',
|
|
97
100
|
};
|
|
98
101
|
|
|
@@ -121,7 +124,9 @@ export async function getPiProviderPresets(): Promise<PiProviderPreset[]> {
|
|
|
121
124
|
name: provider.name,
|
|
122
125
|
authModes,
|
|
123
126
|
...(authModes.includes('api_key') ? { fields: getPiProviderFields(provider.id) } : {}),
|
|
124
|
-
...(
|
|
127
|
+
...(provider.auth.oauth ? {
|
|
128
|
+
oauthLabel: provider.auth.oauth.loginLabel ?? OAUTH_LABELS[provider.id] ?? `Sign in with ${provider.auth.oauth.name}`,
|
|
129
|
+
} : {}),
|
|
125
130
|
...(API_KEY_URLS[provider.id] ? { apiKeyUrl: API_KEY_URLS[provider.id] } : {}),
|
|
126
131
|
});
|
|
127
132
|
}
|