@myrialabs/clopen 0.4.15 → 0.4.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/backend/artifacts/matrix.ts +8 -0
  2. package/backend/artifacts/types.ts +2 -2
  3. package/backend/auth/permissions.ts +14 -0
  4. package/backend/chat/stream-manager.ts +5 -5
  5. package/backend/commands/detect.ts +1 -1
  6. package/backend/commands/sync.ts +1 -1
  7. package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
  8. package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
  9. package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
  10. package/backend/database/migrations/index.ts +21 -0
  11. package/backend/engine/README.md +36 -13
  12. package/backend/engine/adapters/cline/agent-tool.ts +64 -0
  13. package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
  14. package/backend/engine/adapters/cline/credential.ts +166 -0
  15. package/backend/engine/adapters/cline/error-handler.ts +49 -0
  16. package/backend/engine/adapters/cline/index.ts +1 -0
  17. package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
  18. package/backend/engine/adapters/cline/message-converter.ts +396 -0
  19. package/backend/engine/adapters/cline/models.ts +73 -0
  20. package/backend/engine/adapters/cline/presets.ts +128 -0
  21. package/backend/engine/adapters/cline/stream.ts +413 -0
  22. package/backend/engine/adapters/codex/credential.ts +1 -1
  23. package/backend/engine/adapters/codex/message-converter.ts +4 -4
  24. package/backend/engine/adapters/codex/session-fork.ts +1 -1
  25. package/backend/engine/adapters/codex/stream.ts +3 -3
  26. package/backend/engine/adapters/copilot/stream.ts +1 -1
  27. package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
  28. package/backend/engine/adapters/cursor/credential.ts +68 -0
  29. package/backend/engine/adapters/cursor/environment.ts +32 -0
  30. package/backend/engine/adapters/cursor/error-handler.ts +60 -0
  31. package/backend/engine/adapters/cursor/index.ts +1 -0
  32. package/backend/engine/adapters/cursor/message-converter.ts +615 -0
  33. package/backend/engine/adapters/cursor/models.ts +68 -0
  34. package/backend/engine/adapters/cursor/session-fork.ts +68 -0
  35. package/backend/engine/adapters/cursor/stream.ts +341 -0
  36. package/backend/engine/adapters/pi/agent-tool.ts +62 -0
  37. package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
  38. package/backend/engine/adapters/pi/credential.ts +137 -0
  39. package/backend/engine/adapters/pi/environment.ts +33 -0
  40. package/backend/engine/adapters/pi/error-handler.ts +46 -0
  41. package/backend/engine/adapters/pi/index.ts +1 -0
  42. package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
  43. package/backend/engine/adapters/pi/message-converter.ts +446 -0
  44. package/backend/engine/adapters/pi/models.ts +53 -0
  45. package/backend/engine/adapters/pi/presets.ts +133 -0
  46. package/backend/engine/adapters/pi/session-fork.ts +46 -0
  47. package/backend/engine/adapters/pi/stream.ts +427 -0
  48. package/backend/engine/adapters/qwen/message-converter.ts +5 -5
  49. package/backend/engine/adapters/qwen/stream.ts +2 -2
  50. package/backend/engine/docs/adapter-contract.md +7 -2
  51. package/backend/engine/docs/adding-an-engine.md +70 -12
  52. package/backend/engine/docs/artifacts.md +124 -0
  53. package/backend/engine/docs/database.md +4 -4
  54. package/backend/engine/docs/frontend-and-chat.md +22 -4
  55. package/backend/engine/docs/lessons-learned.md +219 -32
  56. package/backend/engine/docs/quick-reference.md +18 -7
  57. package/backend/engine/docs/websocket-routes.md +2 -2
  58. package/backend/engine/index.ts +9 -0
  59. package/backend/mcp/README.md +3 -3
  60. package/backend/mcp/external/config.ts +11 -0
  61. package/backend/mcp/index.ts +8 -0
  62. package/backend/mcp/internal/config.ts +33 -1
  63. package/backend/permissions/service.ts +5 -2
  64. package/backend/skills/sync.ts +1 -1
  65. package/backend/subagents/detect.ts +1 -1
  66. package/backend/subagents/sync.ts +1 -1
  67. package/backend/ws/chat/stream.ts +1 -1
  68. package/backend/ws/engine/cline/accounts.ts +317 -0
  69. package/backend/ws/engine/cline/index.ts +15 -0
  70. package/backend/ws/engine/cline/presets.ts +36 -0
  71. package/backend/ws/engine/cline/status.ts +49 -0
  72. package/backend/ws/engine/codex/accounts.ts +1 -1
  73. package/backend/ws/engine/cursor/accounts.ts +162 -0
  74. package/backend/ws/engine/cursor/index.ts +13 -0
  75. package/backend/ws/engine/cursor/status.ts +55 -0
  76. package/backend/ws/engine/index.ts +6 -0
  77. package/backend/ws/engine/pi/accounts.ts +319 -0
  78. package/backend/ws/engine/pi/index.ts +15 -0
  79. package/backend/ws/engine/pi/presets.ts +34 -0
  80. package/backend/ws/engine/pi/status.ts +50 -0
  81. package/backend/ws/sessions/crud.ts +2 -2
  82. package/backend/ws/settings/crud.ts +2 -2
  83. package/dist/assets/{index-EunAFLxP.js → index-BPvctwJ2.js} +1 -1
  84. package/dist/assets/{index-ChF_jIXj.js → index-vLKZpWQH.js} +1 -1
  85. package/dist/assets/{main-CTs4NXwP.js → main-BtBZvCwv.js} +359 -357
  86. package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
  87. package/dist/index.html +2 -2
  88. package/package.json +7 -1
  89. package/shared/constants/engine-tools.ts +16 -2
  90. package/shared/constants/engines.ts +27 -0
  91. package/shared/types/unified/common.ts +1 -1
  92. package/shared/types/unified/engine.ts +82 -1
  93. package/shared/types/unified/index.ts +6 -0
  94. package/shared/types/unified/message.ts +1 -1
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Pi credential storage.
3
+ *
4
+ * Pi is genuinely multi-provider and supports both API-key and OAuth
5
+ * (subscription) auth. Rather than let Pi write its own `auth.json`, Clopen owns
6
+ * the credential and serves it to `ModelRuntime` through a DB-backed
7
+ * `CredentialStore` (pi-ai's `read`/`modify`/`delete` seam).
8
+ *
9
+ * `engine_accounts.credential` for a Pi account stores a JSON wrapper:
10
+ *
11
+ * { "provider": "anthropic", "credential": { "type": "oauth", "access": …, "refresh": …, "expires": … } }
12
+ *
13
+ * The `credential` field is the raw pi-ai `Credential` (`ApiKeyCredential` or
14
+ * `OAuthCredential`). Because OAuth tokens auto-refresh, `modify()` writes the
15
+ * refreshed credential straight back into the account row — the refresh persists
16
+ * with NO dotfile swap and NO `process.env` mutation.
17
+ */
18
+
19
+ import type { Credential, CredentialInfo, CredentialStore } from '@earendil-works/pi-ai';
20
+ import { engineQueries, type EngineAccount } from '$backend/database/queries/engine-queries';
21
+ import { debug } from '$shared/utils/logger';
22
+
23
+ /** The single `engine_providers` row that owns every Pi account (Qwen-style). */
24
+ export function getPiProvider() {
25
+ return engineQueries.getProviderBySlug('pi', 'pi');
26
+ }
27
+
28
+ /** Every stored Pi account (each tagged with its own pi-ai provider). */
29
+ export function getPiAccounts(): EngineAccount[] {
30
+ const provider = getPiProvider();
31
+ return provider ? engineQueries.getAccountsByProvider(provider.id) : [];
32
+ }
33
+
34
+ /** The account backing a given pi-ai provider id, preferring the active one. */
35
+ export function getPiAccountForProvider(providerId: string): EngineAccount | null {
36
+ const accounts = getPiAccounts().filter(a => parsePiCredential(a.credential)?.provider === providerId);
37
+ if (accounts.length === 0) return null;
38
+ return accounts.find(a => a.is_active === 1) ?? accounts[accounts.length - 1];
39
+ }
40
+
41
+ export interface PiCredential {
42
+ /** pi-ai provider id (e.g. 'anthropic', 'openai', 'openai-codex'). */
43
+ provider: string;
44
+ /** The raw pi-ai credential blob (api_key or oauth). */
45
+ credential: Credential;
46
+ }
47
+
48
+ /** Parse a stored `engine_accounts.credential` blob. Returns null if unusable. */
49
+ export function parsePiCredential(stored: string | null | undefined): PiCredential | null {
50
+ if (!stored) return null;
51
+ const trimmed = stored.trim();
52
+ if (!trimmed.startsWith('{')) return null;
53
+ try {
54
+ const parsed = JSON.parse(trimmed) as Partial<PiCredential>;
55
+ if (!parsed || typeof parsed.provider !== 'string' || !parsed.provider) return null;
56
+ const cred = parsed.credential as Credential | undefined;
57
+ if (!cred || (cred.type !== 'api_key' && cred.type !== 'oauth')) return null;
58
+ return { provider: parsed.provider, credential: cred };
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ export function serializePiCredential(cred: PiCredential): string {
65
+ return JSON.stringify({ provider: cred.provider, credential: cred.credential });
66
+ }
67
+
68
+ /** Non-secret display metadata for one account (auth type + provider). */
69
+ export function describePiCredential(stored: string | null | undefined): { provider: string; type: 'api_key' | 'oauth' } | null {
70
+ const parsed = parsePiCredential(stored);
71
+ if (!parsed) return null;
72
+ return { provider: parsed.provider, type: parsed.credential.type };
73
+ }
74
+
75
+ /**
76
+ * A pi-ai `CredentialStore` backed by one or more `engine_accounts` rows.
77
+ *
78
+ * Keyed by pi-ai `providerId`. Each provider resolves to at most one account
79
+ * (the newest active one when several exist for the same provider). `modify()`
80
+ * persists refreshed OAuth tokens back to the account row so long-running
81
+ * streams survive token rotation.
82
+ */
83
+ export class DbCredentialStore implements CredentialStore {
84
+ /** providerId → engine_accounts.id */
85
+ private readonly providerToAccount = new Map<string, number>();
86
+
87
+ constructor(accounts: EngineAccount[]) {
88
+ for (const account of accounts) {
89
+ const parsed = parsePiCredential(account.credential);
90
+ if (!parsed) continue;
91
+ // Last write wins — callers pass the active account last, or a single account.
92
+ this.providerToAccount.set(parsed.provider, account.id);
93
+ }
94
+ }
95
+
96
+ async read(providerId: string): Promise<Credential | undefined> {
97
+ const accountId = this.providerToAccount.get(providerId);
98
+ if (accountId === undefined) return undefined;
99
+ const account = engineQueries.getAccount(accountId);
100
+ if (!account) return undefined;
101
+ const parsed = parsePiCredential(account.credential);
102
+ return parsed?.credential;
103
+ }
104
+
105
+ async list(): Promise<readonly CredentialInfo[]> {
106
+ const out: CredentialInfo[] = [];
107
+ for (const [providerId, accountId] of this.providerToAccount) {
108
+ const account = engineQueries.getAccount(accountId);
109
+ const parsed = account ? parsePiCredential(account.credential) : null;
110
+ if (parsed) out.push({ providerId, type: parsed.credential.type });
111
+ }
112
+ return out;
113
+ }
114
+
115
+ async modify(
116
+ providerId: string,
117
+ fn: (current: Credential | undefined) => Promise<Credential | undefined>,
118
+ ): Promise<Credential | undefined> {
119
+ const accountId = this.providerToAccount.get(providerId);
120
+ const current = accountId !== undefined
121
+ ? parsePiCredential(engineQueries.getAccount(accountId)?.credential)?.credential
122
+ : undefined;
123
+
124
+ const next = await fn(current);
125
+ if (next === undefined) return current;
126
+
127
+ if (accountId !== undefined) {
128
+ engineQueries.updateAccountCredential(accountId, serializePiCredential({ provider: providerId, credential: next }));
129
+ debug.log('engine', `Pi: persisted refreshed credential for provider "${providerId}" (account ${accountId})`);
130
+ }
131
+ return next;
132
+ }
133
+
134
+ async delete(providerId: string): Promise<void> {
135
+ this.providerToAccount.delete(providerId);
136
+ }
137
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Environment / directory isolation for the Pi engine.
3
+ *
4
+ * Pi is an IN-PROCESS SDK (`@earendil-works/pi-coding-agent`) — there is no CLI
5
+ * subprocess and no env var to redirect a home dir. Instead every `ModelRuntime`
6
+ * / `AgentSession` we build is pointed at an ISOLATED agent dir so Clopen never
7
+ * reads or writes the user's real `~/.pi/agent`. Credentials do NOT live in that
8
+ * dir's `auth.json`; they live in the `engine_accounts` table and are served to
9
+ * the runtime through a DB-backed `CredentialStore` (see ./credential.ts).
10
+ */
11
+
12
+ import { join } from 'node:path';
13
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
14
+
15
+ /** Isolated agent dir: `{clopenDir}/engine/pi/user/`. Mirrors §10.19 isolation. */
16
+ export function getPiAgentDir(): string {
17
+ return getEngineUserConfigDir('pi');
18
+ }
19
+
20
+ /** Isolated custom-models file (`models.json`) — optional, may not exist. */
21
+ export function getPiModelsPath(): string {
22
+ return join(getPiAgentDir(), 'models.json');
23
+ }
24
+
25
+ /** Isolated dynamic-catalog cache (`models-store.json`). */
26
+ export function getPiModelsStorePath(): string {
27
+ return join(getPiAgentDir(), 'models-store.json');
28
+ }
29
+
30
+ /** Isolated sessions dir — Pi persists session JSONL trees here. */
31
+ export function getPiSessionsDir(): string {
32
+ return join(getPiAgentDir(), 'sessions');
33
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Pi SDK error handler.
3
+ *
4
+ * Mirrors the Claude/Qwen pattern: swallow abort errors, normalise the common
5
+ * categories (missing auth, quota, bad model) and otherwise surface a sanitised
6
+ * message. Pi runs in-process, so there is no CLI stderr tail to fold in.
7
+ */
8
+
9
+ export function handleStreamError(error: unknown): void {
10
+ if (!(error instanceof Error)) {
11
+ throw error;
12
+ }
13
+
14
+ if (
15
+ error.name === 'AbortError'
16
+ || error.message.includes('aborted')
17
+ || error.message.includes('abort')
18
+ || error.message === 'Operation aborted'
19
+ ) {
20
+ return;
21
+ }
22
+
23
+ const lower = error.message.toLowerCase();
24
+
25
+ if (
26
+ lower.includes('no api key')
27
+ || lower.includes('not authenticated')
28
+ || lower.includes('unauthorized')
29
+ || lower.includes('401')
30
+ || lower.includes('no auth')
31
+ || lower.includes('invalid api key')
32
+ ) {
33
+ throw new Error('Pi is not authenticated for the selected provider. Add or re-authenticate the account in Settings → Engines → Pi.');
34
+ }
35
+
36
+ if (lower.includes('quota') || lower.includes('insufficient_quota') || lower.includes('429') || lower.includes('rate limit')) {
37
+ throw new Error('Pi provider quota/rate limit exceeded. Check your balance or switch account.');
38
+ }
39
+
40
+ if (lower.includes('model not found') || lower.includes('does not exist') || lower.includes('unsupported model') || lower.includes('no model')) {
41
+ throw new Error('Pi could not resolve the selected model for this account. Pick a model your provider supports.');
42
+ }
43
+
44
+ const message = error.message.replace(/^Error:\s*/, '') || error.name || 'Unknown error';
45
+ throw new Error(message);
46
+ }
@@ -0,0 +1 @@
1
+ export { PiEngine } from './stream';
@@ -0,0 +1,131 @@
1
+ /**
2
+ * MCP → Pi custom-tool bridge.
3
+ *
4
+ * Pi has NO native MCP support (by design — see the pi README). Because Pi runs
5
+ * IN-PROCESS, we don't need the `/mcp` HTTP bridge the other engines use: we
6
+ * expose each enabled Clopen MCP tool directly as a Pi custom tool
7
+ * (`ToolDefinition`) whose `execute` calls the tool handler in-process.
8
+ *
9
+ * - INTERNAL servers (`defineServer()` — e.g. browser-automation): the handler
10
+ * runs bound to the stream's project context (AsyncLocalStorage) with an
11
+ * abort short-circuit, exactly like Claude's in-process path.
12
+ * - EXTERNAL servers (user-installed, `mcp_servers` table): proxied to the
13
+ * upstream server via `callExternalServerTool`.
14
+ *
15
+ * Tool names use the canonical `mcp__<namespace>__<tool>` form so the unified UI
16
+ * + `toCanonicalToolName()` render them identically to the other engines.
17
+ *
18
+ * Note: MCP tool JSON schemas are surfaced to the model through the tool
19
+ * DESCRIPTION (Pi tool `parameters` stays a permissive object) — the handler
20
+ * validates the arguments, so this is lossless for execution.
21
+ */
22
+
23
+ import { Type } from 'typebox';
24
+ import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
25
+ import type { TextContent, ImageContent } from '@earendil-works/pi-ai';
26
+ import type { McpExecutionContext } from '../../types';
27
+ import {
28
+ getEnabledServerNames,
29
+ isToolEnabled,
30
+ getEnabledExternalServers,
31
+ listExternalServerTools,
32
+ callExternalServerTool,
33
+ projectContextService,
34
+ serverMetadata,
35
+ } from '../../../mcp';
36
+ import { debug } from '$shared/utils/logger';
37
+
38
+ type McpContentItem = { type: string; text?: string; data?: string; mimeType?: string };
39
+
40
+ /** Permissive object schema — arguments are validated by the tool handler. */
41
+ const OPEN_PARAMS = Type.Object({}, { additionalProperties: true });
42
+
43
+ /** Map an MCP content array into Pi's `(TextContent | ImageContent)[]`. */
44
+ function toPiContent(raw: unknown): (TextContent | ImageContent)[] {
45
+ const items = Array.isArray(raw) ? (raw as McpContentItem[]) : [];
46
+ const out: (TextContent | ImageContent)[] = [];
47
+ for (const item of items) {
48
+ if (item?.type === 'image' && typeof item.data === 'string') {
49
+ out.push({ type: 'image', data: item.data, mimeType: item.mimeType || 'image/png' });
50
+ } else if (typeof item?.text === 'string') {
51
+ out.push({ type: 'text', text: item.text });
52
+ } else if (item != null) {
53
+ out.push({ type: 'text', text: JSON.stringify(item) });
54
+ }
55
+ }
56
+ if (out.length === 0) out.push({ type: 'text', text: '' });
57
+ return out;
58
+ }
59
+
60
+ /**
61
+ * Build the set of Pi custom tools mirroring every enabled internal + external
62
+ * MCP tool. Scoped to the active Profile via `profileFilter` (server ids).
63
+ */
64
+ export async function buildPiMcpTools(
65
+ context: McpExecutionContext | undefined,
66
+ profileFilter: Set<string> | undefined,
67
+ ): Promise<ToolDefinition[]> {
68
+ const tools: ToolDefinition[] = [];
69
+
70
+ // ── Internal servers (in-process handlers) ──
71
+ for (const serverName of getEnabledServerNames()) {
72
+ if (profileFilter && !profileFilter.has(serverName)) continue;
73
+ const meta = (serverMetadata as Record<string, { tools: readonly string[]; toolDefs: Record<string, { description: string; schema: Record<string, unknown>; handler: (args: unknown) => Promise<{ content: McpContentItem[]; isError?: boolean }> }> }>)[serverName];
74
+ if (!meta) continue;
75
+
76
+ // meta.tools holds RAW tool names (the toolDefs keys). getEnabledToolsForServer()
77
+ // returns the `mcp__<server>__<tool>` form, which would never match toolDefs.
78
+ for (const toolName of meta.tools) {
79
+ if (!isToolEnabled(serverName, toolName)) continue;
80
+ const def = meta.toolDefs[toolName];
81
+ if (!def) continue;
82
+ const fullName = `mcp__${serverName}__${toolName}`;
83
+ const argKeys = Object.keys(def.schema ?? {});
84
+ tools.push({
85
+ name: fullName,
86
+ label: toolName,
87
+ description: `${def.description}${argKeys.length ? `\n\nArguments: ${argKeys.join(', ')}` : ''}`,
88
+ parameters: OPEN_PARAMS,
89
+ execute: async (_toolCallId: string, params: unknown) => {
90
+ const run = async () => {
91
+ const signal = projectContextService.getCurrentSignal();
92
+ if (signal?.aborted) {
93
+ return { content: [{ type: 'text' as const, text: `Tool ${fullName} was cancelled.` }], details: {} };
94
+ }
95
+ const result = await def.handler(params ?? {});
96
+ return { content: toPiContent(result?.content), details: {} };
97
+ };
98
+ return context ? projectContextService.runWithContextAsync(context, run) : run();
99
+ },
100
+ } as ToolDefinition);
101
+ }
102
+ }
103
+
104
+ // ── External servers (proxied upstream) ──
105
+ for (const server of getEnabledExternalServers(profileFilter)) {
106
+ let externalTools;
107
+ try {
108
+ externalTools = await listExternalServerTools(server.slug);
109
+ } catch (error) {
110
+ debug.warn('mcp', `Pi MCP bridge: could not list tools for "${server.slug}" (skipping):`, error);
111
+ continue;
112
+ }
113
+ for (const tool of externalTools) {
114
+ const fullName = `mcp__${server.namespace}__${tool.name}`;
115
+ const schemaText = tool.inputSchema ? `\n\nInput JSON schema:\n${JSON.stringify(tool.inputSchema)}` : '';
116
+ tools.push({
117
+ name: fullName,
118
+ label: tool.name,
119
+ description: `${tool.description ?? tool.name}${schemaText}`,
120
+ parameters: OPEN_PARAMS,
121
+ execute: async (_toolCallId: string, params: unknown) => {
122
+ const result = (await callExternalServerTool(server.slug, tool.name, params ?? {})) as { content?: unknown } | undefined;
123
+ return { content: toPiContent(result?.content), details: {} };
124
+ },
125
+ } as ToolDefinition);
126
+ }
127
+ }
128
+
129
+ debug.log('mcp', `Pi MCP bridge: ${tools.length} tool(s) exposed`);
130
+ return tools;
131
+ }