@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
|
@@ -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
|
}
|
|
@@ -13,8 +13,9 @@
|
|
|
13
13
|
* `ModelRuntime` whose `CredentialStore` is served from `engine_accounts`
|
|
14
14
|
* (see ./credential.ts). OAuth refresh persists straight back to the DB — no
|
|
15
15
|
* dotfile swap, no `process.env` mutation.
|
|
16
|
-
* 3. **
|
|
17
|
-
*
|
|
16
|
+
* 3. **Pi's own MCP client, Clopen's servers.** Pi's MCP extension connects to
|
|
17
|
+
* the same `/mcp` bridges the other engines use, fed a Clopen-built config
|
|
18
|
+
* (./mcp.ts). AskUserQuestion is a custom blocking tool
|
|
18
19
|
* (./ask-question-tool.ts) since Pi's native `ask_question` has no headless
|
|
19
20
|
* answer path.
|
|
20
21
|
*/
|
|
@@ -43,12 +44,13 @@ import { artifactFilter } from '$backend/profiles';
|
|
|
43
44
|
import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
|
|
44
45
|
import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
|
|
45
46
|
import { EngineRuns } from '../run-registry';
|
|
46
|
-
import { DbCredentialStore, getPiAccountForProvider, parsePiCredential } from './credential';
|
|
47
|
+
import { DbCredentialStore, canonicalPiProviderId, getPiAccountForProvider, parsePiCredential } from './credential';
|
|
47
48
|
import { createPiRuntime } from './presets';
|
|
48
49
|
import { getPiAgentDir } from './environment';
|
|
49
50
|
import { fetchPiModels } from './models';
|
|
50
51
|
import { resolvePiSessionManager } from './session-fork';
|
|
51
|
-
import {
|
|
52
|
+
import { getPiMcpConfig } from '../../../mcp';
|
|
53
|
+
import { createPiMcpExtension, resolvePiToolName } from './mcp';
|
|
52
54
|
import { createAskUserQuestionTool, formatAnswers, type PendingAsk } from './ask-question-tool';
|
|
53
55
|
import { createAgentDispatchTool, type SubagentInfo } from './agent-tool';
|
|
54
56
|
import { createPiMessageConverter } from './message-converter';
|
|
@@ -149,7 +151,7 @@ export class PiEngine implements AIEngine {
|
|
|
149
151
|
if (!account) {
|
|
150
152
|
throw new Error(`Pi has no account for provider "${providerSlug}". Add one in Settings → Engines → Pi.`);
|
|
151
153
|
}
|
|
152
|
-
const provider = parsePiCredential(account.credential)?.provider ?? providerSlug;
|
|
154
|
+
const provider = parsePiCredential(account.credential)?.provider ?? canonicalPiProviderId(providerSlug);
|
|
153
155
|
const runtime = await createPiRuntime(new DbCredentialStore([account]));
|
|
154
156
|
const model = runtime.getModel(provider, modelId);
|
|
155
157
|
if (!model) {
|
|
@@ -177,11 +179,13 @@ export class PiEngine implements AIEngine {
|
|
|
177
179
|
|
|
178
180
|
// ── Permissions (enforced at the `tool_call` extension hook) ──
|
|
179
181
|
const permissions = resolvePermissionsFromDb('pi', options.mcpContext?.projectId, profileId);
|
|
182
|
+
// MCP rules name tools canonically; Pi's own MCP names are sanitized.
|
|
180
183
|
const permissionBlocker = (pi: ExtensionAPI) => {
|
|
181
184
|
pi.on('tool_call', async (event: { toolName: string }) => {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
+
const toolName = resolvePiToolName(run.session, event.toolName);
|
|
186
|
+
if (!isToolAllowed(permissions, toolName)) {
|
|
187
|
+
debug.log('permissions', `⛔ Pi blocked tool "${toolName}" (Clopen permission policy)`);
|
|
188
|
+
return { block: true, reason: `Blocked by Clopen permission policy: ${toolName}` };
|
|
185
189
|
}
|
|
186
190
|
return undefined;
|
|
187
191
|
});
|
|
@@ -191,15 +195,19 @@ export class PiEngine implements AIEngine {
|
|
|
191
195
|
// (built before the queue exists) can push sub-activity messages into it.
|
|
192
196
|
const queueHolder: { queue: EventQueue<EngineOutput> | null } = { queue: null };
|
|
193
197
|
|
|
194
|
-
// ── Tools: builtins (permission-filtered) + AskUserQuestion + MCP
|
|
198
|
+
// ── Tools: builtins (permission-filtered) + AskUserQuestion + subagents; MCP via Pi's extension ──
|
|
199
|
+
// The builtins go in as the `defaultTools` setting, not a `tools` allowlist:
|
|
200
|
+
// an allowlist also filters every tool registered later, which would drop
|
|
201
|
+
// the MCP tools Pi registers once its servers connect.
|
|
195
202
|
const allowedBuiltins = PI_BUILTIN_TOOLS.filter((name) => isToolAllowed(permissions, name));
|
|
203
|
+
const deniedBuiltins = PI_BUILTIN_TOOLS.filter((name) => !allowedBuiltins.includes(name));
|
|
196
204
|
const askTool = createAskUserQuestionTool({
|
|
197
205
|
register: (id, entry) => this.pendingAsks.set(id, { ...entry, owner: run }),
|
|
198
206
|
unregister: (id) => this.pendingAsks.delete(id),
|
|
199
207
|
});
|
|
200
|
-
const
|
|
201
|
-
const
|
|
202
|
-
const
|
|
208
|
+
const customTools: ToolDefinition[] = [askTool];
|
|
209
|
+
const mcpServers = getPiMcpConfig(mcpProfileFilter, options.mcpContext);
|
|
210
|
+
const mcpExtension = await createPiMcpExtension(mcpServers);
|
|
203
211
|
|
|
204
212
|
// Subagent dispatch — Pi has no native Agent tool, so materialising the
|
|
205
213
|
// "Available Subagents" preamble isn't enough; expose a tool that actually
|
|
@@ -281,7 +289,6 @@ export class PiEngine implements AIEngine {
|
|
|
281
289
|
},
|
|
282
290
|
});
|
|
283
291
|
customTools.push(agentTool);
|
|
284
|
-
toolAllowlist.push('Agent');
|
|
285
292
|
}
|
|
286
293
|
|
|
287
294
|
// ── Resource loader (discovers synced skills/prompts/AGENTS.md) ──
|
|
@@ -293,7 +300,7 @@ export class PiEngine implements AIEngine {
|
|
|
293
300
|
const resourceLoader = new DefaultResourceLoader({
|
|
294
301
|
cwd: resolvedProjectPath,
|
|
295
302
|
agentDir,
|
|
296
|
-
extensionFactories: [permissionBlocker],
|
|
303
|
+
extensionFactories: [permissionBlocker, mcpExtension],
|
|
297
304
|
...(projectBridge.skills.length > 0 && { additionalSkillPaths: projectBridge.skills.map((s) => s.skillMd) }),
|
|
298
305
|
...(projectInstructions && { appendSystemPrompt: [projectInstructions] }),
|
|
299
306
|
skillsOverride: (base) => ({
|
|
@@ -314,13 +321,15 @@ export class PiEngine implements AIEngine {
|
|
|
314
321
|
? clampThinkingLevel(model, reasoningEffort as ModelThinkingLevel)
|
|
315
322
|
: (model.reasoning ? 'medium' : 'off'),
|
|
316
323
|
resourceLoader,
|
|
317
|
-
tools: toolAllowlist,
|
|
318
324
|
customTools,
|
|
319
|
-
excludeTools: ['ask_question'],
|
|
325
|
+
excludeTools: ['ask_question', ...deniedBuiltins],
|
|
320
326
|
sessionManager,
|
|
321
|
-
settingsManager: SettingsManager.inMemory({ retry: PI_RETRY }),
|
|
327
|
+
settingsManager: SettingsManager.inMemory({ retry: PI_RETRY, defaultTools: allowedBuiltins }),
|
|
322
328
|
});
|
|
323
329
|
run.session = session;
|
|
330
|
+
// Fires `session_start`, which connects the MCP servers; the first prompt
|
|
331
|
+
// waits (bounded) for their tools to be declared.
|
|
332
|
+
await session.bindExtensions({});
|
|
324
333
|
|
|
325
334
|
const engineMeta: MessageEngine = {
|
|
326
335
|
type: 'pi',
|
|
@@ -328,7 +337,11 @@ export class PiEngine implements AIEngine {
|
|
|
328
337
|
model: { id: modelId, name: model.name || modelId },
|
|
329
338
|
account: { id: account.id, name: account.name },
|
|
330
339
|
};
|
|
331
|
-
const converter = createPiMessageConverter({
|
|
340
|
+
const converter = createPiMessageConverter({
|
|
341
|
+
engine: engineMeta,
|
|
342
|
+
sessionId: session.sessionId,
|
|
343
|
+
resolveToolName: (name) => resolvePiToolName(session, name),
|
|
344
|
+
});
|
|
332
345
|
const queue = new EventQueue<EngineOutput>();
|
|
333
346
|
queueHolder.queue = queue;
|
|
334
347
|
const unsubscribe = session.subscribe((event) => {
|
|
@@ -351,34 +364,21 @@ export class PiEngine implements AIEngine {
|
|
|
351
364
|
.filter((b): b is Extract<typeof b, { type: 'image' }> => b.type === 'image')
|
|
352
365
|
.map((b) => ({ type: 'image', data: b.data, mimeType: b.mediaType }));
|
|
353
366
|
|
|
354
|
-
// system_init first — model +
|
|
367
|
+
// system_init first — model + tools active so far (MCP tools join as their servers connect).
|
|
355
368
|
yield {
|
|
356
369
|
type: 'system_init',
|
|
357
370
|
sessionId: session.sessionId,
|
|
358
371
|
model: modelId,
|
|
359
372
|
engine: 'pi',
|
|
360
|
-
tools:
|
|
373
|
+
tools: session.getActiveToolNames().map((name) => resolvePiToolName(session, name)),
|
|
361
374
|
mcpServers: [],
|
|
362
375
|
};
|
|
363
376
|
|
|
364
377
|
// Close the queue when prompt() settles even if no `agent_end` ever fires
|
|
365
|
-
// (e.g.
|
|
366
|
-
//
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
preflightResult: (success: boolean) => {
|
|
370
|
-
if (!success) {
|
|
371
|
-
queue.push({
|
|
372
|
-
type: 'notification',
|
|
373
|
-
sessionId: session.sessionId,
|
|
374
|
-
level: 'warning',
|
|
375
|
-
title: 'Prompt not accepted',
|
|
376
|
-
message: 'Pi did not accept this input (unknown command or empty prompt).',
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
|
-
},
|
|
380
|
-
};
|
|
381
|
-
const promptPromise = session.prompt(promptText, promptOptions)
|
|
378
|
+
// (e.g. an input an extension handled, or an empty expansion) — otherwise
|
|
379
|
+
// the drain loop would block forever and the stream would hang. A prompt
|
|
380
|
+
// Pi rejects throws, which reaches the caller through `queue.fail`.
|
|
381
|
+
const promptPromise = session.prompt(promptText, images.length ? { images } : undefined)
|
|
382
382
|
.then(() => queue.close())
|
|
383
383
|
.catch((error) => queue.fail(error));
|
|
384
384
|
|
|
@@ -390,6 +390,10 @@ export class PiEngine implements AIEngine {
|
|
|
390
390
|
} finally {
|
|
391
391
|
controller.signal.removeEventListener('abort', onAbort);
|
|
392
392
|
unsubscribe();
|
|
393
|
+
// `dispose()` alone never emits `session_shutdown`, which is what closes
|
|
394
|
+
// the MCP connections — without it every turn leaks one per server.
|
|
395
|
+
await session.extensionRunner.emit({ type: 'session_shutdown', reason: 'quit' })
|
|
396
|
+
.catch((error) => debug.warn('engine', 'Pi session shutdown hook failed:', error));
|
|
393
397
|
try { session.dispose(); } catch { /* already disposed */ }
|
|
394
398
|
// Retire THIS run only — another chat session of the same project may
|
|
395
399
|
// still be streaming on this instance.
|
|
@@ -467,7 +471,7 @@ export class PiEngine implements AIEngine {
|
|
|
467
471
|
const account = getPiAccountForProvider(providerSlug)
|
|
468
472
|
?? (accountId != null ? engineQueries.getAccount(accountId) : null);
|
|
469
473
|
if (!account) throw new Error(`Pi has no account for provider "${providerSlug}".`);
|
|
470
|
-
const provider = parsePiCredential(account.credential)?.provider ?? providerSlug;
|
|
474
|
+
const provider = parsePiCredential(account.credential)?.provider ?? canonicalPiProviderId(providerSlug);
|
|
471
475
|
const runtime = await createPiRuntime(new DbCredentialStore([account]));
|
|
472
476
|
const model = runtime.getModel(provider, modelId);
|
|
473
477
|
if (!model) throw new Error(`Pi could not resolve model "${modelId}" for provider "${provider}".`);
|
|
@@ -16,12 +16,46 @@
|
|
|
16
16
|
* deprecated the free-tier OAuth in April 2026.
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
19
21
|
import { engineQueries } from '$backend/database/queries/engine-queries';
|
|
20
22
|
import type { EngineAccount } from '$backend/database/queries/engine-queries';
|
|
21
23
|
import { getCleanSpawnEnv } from '$backend/utils/index.js';
|
|
22
24
|
import { debug } from '$shared/utils/logger';
|
|
23
25
|
import { parseQwenCredential, resolveQwenBaseUrl } from './credential';
|
|
24
|
-
import { getQwenRuntimeDir } from './session-
|
|
26
|
+
import { getQwenRuntimeDir } from './session-store';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Settings Clopen forces on every Qwen CLI run, via the CLI's system-settings
|
|
30
|
+
* tier (highest precedence, so neither ~/.qwen nor a repo's .qwen/ can turn
|
|
31
|
+
* them back on).
|
|
32
|
+
*
|
|
33
|
+
* Managed auto-memory (on by default since the 0.1.17 CLI) runs an extraction
|
|
34
|
+
* agent after every turn and holds the `result` back until it finishes — a
|
|
35
|
+
* minute or more of extra model calls on the user's key, with the chat stuck
|
|
36
|
+
* on "working" the whole time. It also writes memories into the CLI's own
|
|
37
|
+
* store, which no other engine reads; Clopen owns memory for every engine.
|
|
38
|
+
*/
|
|
39
|
+
const QWEN_SYSTEM_SETTINGS = {
|
|
40
|
+
memory: {
|
|
41
|
+
enableManagedAutoMemory: false,
|
|
42
|
+
enableManagedAutoDream: false,
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Write the forced settings file (only when it changed) and return its path. */
|
|
47
|
+
function ensureQwenSystemSettings(): string {
|
|
48
|
+
const file = path.join(getQwenRuntimeDir(), 'clopen-system-settings.json');
|
|
49
|
+
const content = `${JSON.stringify(QWEN_SYSTEM_SETTINGS, null, 2)}\n`;
|
|
50
|
+
try {
|
|
51
|
+
if (fs.readFileSync(file, 'utf-8') === content) return file;
|
|
52
|
+
} catch {
|
|
53
|
+
/* missing — written below */
|
|
54
|
+
}
|
|
55
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
56
|
+
fs.writeFileSync(file, content);
|
|
57
|
+
return file;
|
|
58
|
+
}
|
|
25
59
|
|
|
26
60
|
export interface QwenEnvResolution {
|
|
27
61
|
env: Record<string, string>;
|
|
@@ -71,10 +105,13 @@ export function getEngineEnv(accountId?: number): QwenEnvResolution | null {
|
|
|
71
105
|
env['OPENAI_BASE_URL'] = baseUrl;
|
|
72
106
|
// Isolate Qwen's runtime output (chats/sessions, history, logs, tmp) to
|
|
73
107
|
// {clopenDir}/engine/qwen/user/ instead of the shared ~/.qwen. Mirrors the path
|
|
74
|
-
// the
|
|
108
|
+
// the session store reads from (see ./session-store.ts). The CLI's global
|
|
75
109
|
// settings.json stays in ~/.qwen — there is no env override for it — but
|
|
76
110
|
// Clopen uses paste-token auth so that file is irrelevant here.
|
|
77
111
|
env['QWEN_RUNTIME_DIR'] = getQwenRuntimeDir();
|
|
112
|
+
// Replaces the machine-wide system settings file for these runs only
|
|
113
|
+
// (`/Library/Application Support/QwenCode/settings.json` and friends).
|
|
114
|
+
env['QWEN_CODE_SYSTEM_SETTINGS_PATH'] = ensureQwenSystemSettings();
|
|
78
115
|
// Strip any inherited Qwen OAuth hints — if the host shell exports them
|
|
79
116
|
// the bundled CLI prefers the OAuth path even when API-key env vars are
|
|
80
117
|
// present, surfacing the "OAuth free tier discontinued" error.
|