@myrialabs/clopen 0.4.15 → 0.4.17

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 (95) hide show
  1. package/README.md +8 -5
  2. package/backend/artifacts/matrix.ts +8 -0
  3. package/backend/artifacts/types.ts +2 -2
  4. package/backend/auth/permissions.ts +14 -0
  5. package/backend/chat/stream-manager.ts +5 -5
  6. package/backend/commands/detect.ts +1 -1
  7. package/backend/commands/sync.ts +1 -1
  8. package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
  9. package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
  10. package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
  11. package/backend/database/migrations/index.ts +21 -0
  12. package/backend/engine/README.md +36 -13
  13. package/backend/engine/adapters/cline/agent-tool.ts +64 -0
  14. package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
  15. package/backend/engine/adapters/cline/credential.ts +166 -0
  16. package/backend/engine/adapters/cline/error-handler.ts +49 -0
  17. package/backend/engine/adapters/cline/index.ts +1 -0
  18. package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
  19. package/backend/engine/adapters/cline/message-converter.ts +396 -0
  20. package/backend/engine/adapters/cline/models.ts +73 -0
  21. package/backend/engine/adapters/cline/presets.ts +128 -0
  22. package/backend/engine/adapters/cline/stream.ts +413 -0
  23. package/backend/engine/adapters/codex/credential.ts +1 -1
  24. package/backend/engine/adapters/codex/message-converter.ts +4 -4
  25. package/backend/engine/adapters/codex/session-fork.ts +1 -1
  26. package/backend/engine/adapters/codex/stream.ts +3 -3
  27. package/backend/engine/adapters/copilot/stream.ts +1 -1
  28. package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
  29. package/backend/engine/adapters/cursor/credential.ts +68 -0
  30. package/backend/engine/adapters/cursor/environment.ts +32 -0
  31. package/backend/engine/adapters/cursor/error-handler.ts +60 -0
  32. package/backend/engine/adapters/cursor/index.ts +1 -0
  33. package/backend/engine/adapters/cursor/message-converter.ts +615 -0
  34. package/backend/engine/adapters/cursor/models.ts +68 -0
  35. package/backend/engine/adapters/cursor/session-fork.ts +68 -0
  36. package/backend/engine/adapters/cursor/stream.ts +341 -0
  37. package/backend/engine/adapters/pi/agent-tool.ts +62 -0
  38. package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
  39. package/backend/engine/adapters/pi/credential.ts +137 -0
  40. package/backend/engine/adapters/pi/environment.ts +33 -0
  41. package/backend/engine/adapters/pi/error-handler.ts +46 -0
  42. package/backend/engine/adapters/pi/index.ts +1 -0
  43. package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
  44. package/backend/engine/adapters/pi/message-converter.ts +446 -0
  45. package/backend/engine/adapters/pi/models.ts +53 -0
  46. package/backend/engine/adapters/pi/presets.ts +133 -0
  47. package/backend/engine/adapters/pi/session-fork.ts +46 -0
  48. package/backend/engine/adapters/pi/stream.ts +427 -0
  49. package/backend/engine/adapters/qwen/message-converter.ts +5 -5
  50. package/backend/engine/adapters/qwen/stream.ts +2 -2
  51. package/backend/engine/docs/adapter-contract.md +7 -2
  52. package/backend/engine/docs/adding-an-engine.md +70 -12
  53. package/backend/engine/docs/artifacts.md +124 -0
  54. package/backend/engine/docs/database.md +4 -4
  55. package/backend/engine/docs/frontend-and-chat.md +22 -4
  56. package/backend/engine/docs/lessons-learned.md +219 -32
  57. package/backend/engine/docs/quick-reference.md +18 -7
  58. package/backend/engine/docs/websocket-routes.md +2 -2
  59. package/backend/engine/index.ts +9 -0
  60. package/backend/mcp/README.md +3 -3
  61. package/backend/mcp/external/config.ts +11 -0
  62. package/backend/mcp/index.ts +8 -0
  63. package/backend/mcp/internal/config.ts +33 -1
  64. package/backend/permissions/service.ts +5 -2
  65. package/backend/skills/sync.ts +1 -1
  66. package/backend/subagents/detect.ts +1 -1
  67. package/backend/subagents/sync.ts +1 -1
  68. package/backend/ws/chat/stream.ts +1 -1
  69. package/backend/ws/engine/cline/accounts.ts +317 -0
  70. package/backend/ws/engine/cline/index.ts +15 -0
  71. package/backend/ws/engine/cline/presets.ts +36 -0
  72. package/backend/ws/engine/cline/status.ts +49 -0
  73. package/backend/ws/engine/codex/accounts.ts +1 -1
  74. package/backend/ws/engine/cursor/accounts.ts +162 -0
  75. package/backend/ws/engine/cursor/index.ts +13 -0
  76. package/backend/ws/engine/cursor/status.ts +55 -0
  77. package/backend/ws/engine/index.ts +6 -0
  78. package/backend/ws/engine/pi/accounts.ts +319 -0
  79. package/backend/ws/engine/pi/index.ts +15 -0
  80. package/backend/ws/engine/pi/presets.ts +34 -0
  81. package/backend/ws/engine/pi/status.ts +50 -0
  82. package/backend/ws/sessions/crud.ts +2 -2
  83. package/backend/ws/settings/crud.ts +2 -2
  84. package/dist/assets/{index-EunAFLxP.js → index-Bu5loFQE.js} +1 -1
  85. package/dist/assets/{index-ChF_jIXj.js → index-kME3THy5.js} +1 -1
  86. package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
  87. package/dist/assets/{main-CTs4NXwP.js → main-HirJLquI.js} +361 -359
  88. package/dist/index.html +2 -2
  89. package/package.json +11 -2
  90. package/shared/constants/engine-tools.ts +16 -2
  91. package/shared/constants/engines.ts +27 -0
  92. package/shared/types/unified/common.ts +1 -1
  93. package/shared/types/unified/engine.ts +82 -1
  94. package/shared/types/unified/index.ts +6 -0
  95. package/shared/types/unified/message.ts +1 -1
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Pi Engine Adapter
3
+ *
4
+ * Wraps `@earendil-works/pi-coding-agent` (in-process SDK) into the AIEngine
5
+ * interface. Three things make Pi structurally different from the other
6
+ * adapters:
7
+ *
8
+ * 1. **Subscribe, not async-generator.** Pi drives output through
9
+ * `session.subscribe(listener)` + `await session.prompt()`. `streamQuery`
10
+ * bridges that push stream into the required `AsyncGenerator<EngineOutput>`
11
+ * via a small pushable queue.
12
+ * 2. **Multi-provider, DB-backed credentials.** Each stream builds a
13
+ * `ModelRuntime` whose `CredentialStore` is served from `engine_accounts`
14
+ * (see ./credential.ts). OAuth refresh persists straight back to the DB — no
15
+ * dotfile swap, no `process.env` mutation.
16
+ * 3. **No native MCP.** Clopen's MCP tools are bridged in-process as Pi custom
17
+ * tools (./mcp-tools.ts). AskUserQuestion is a custom blocking tool
18
+ * (./ask-question-tool.ts) since Pi's native `ask_question` has no headless
19
+ * answer path.
20
+ */
21
+
22
+ import {
23
+ createAgentSession,
24
+ DefaultResourceLoader,
25
+ SessionManager,
26
+ SettingsManager,
27
+ type AgentSession,
28
+ type ExtensionAPI,
29
+ type ToolDefinition,
30
+ } from '@earendil-works/pi-coding-agent';
31
+ import type { AgentToolResult } from '@earendil-works/pi-agent-core';
32
+ import type { ImageContent } from '@earendil-works/pi-ai';
33
+ import type { EngineOutput, EngineModel, MessageEngine } from '$shared/types/unified';
34
+ import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
35
+ import { resolveOsPath } from '$backend/utils/paths';
36
+ import { debug } from '$shared/utils/logger';
37
+ import { engineQueries } from '$backend/database/queries/engine-queries';
38
+ import { subagentQueries } from '$backend/database/queries';
39
+ import { readSubagentMd } from '$backend/subagents/store';
40
+ import { syncSkills } from '$backend/skills';
41
+ import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
42
+ import { artifactFilter } from '$backend/profiles';
43
+ import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
44
+ import { buildJsonPrompt, extractJson } from '../../structured-helpers';
45
+ import { DbCredentialStore, getPiAccountForProvider, parsePiCredential } from './credential';
46
+ import { createPiRuntime } from './presets';
47
+ import { getPiAgentDir } from './environment';
48
+ import { fetchPiModels } from './models';
49
+ import { resolvePiSessionManager } from './session-fork';
50
+ import { buildPiMcpTools } from './mcp-tools';
51
+ import { createAskUserQuestionTool, formatAnswers, type PendingAsk } from './ask-question-tool';
52
+ import { createAgentDispatchTool, type SubagentInfo } from './agent-tool';
53
+ import { createPiMessageConverter } from './message-converter';
54
+ import { handleStreamError } from './error-handler';
55
+
56
+ const PI_BUILTIN_TOOLS = ['read', 'bash', 'edit', 'write', 'grep', 'find', 'ls'];
57
+
58
+ /** Auto-retry transient provider failures (socket close, 5xx, overload). */
59
+ const PI_RETRY = { enabled: true, maxRetries: 3, baseDelayMs: 1000 } as const;
60
+
61
+ /** Strip YAML frontmatter from a subagent markdown doc, leaving the instructions. */
62
+ function stripFrontmatter(md: string): string {
63
+ const match = md.match(/^---\n[\s\S]*?\n---\n?/);
64
+ return (match ? md.slice(match[0].length) : md).trim();
65
+ }
66
+
67
+ /** Minimal pushable queue bridging Pi's subscribe stream → an async generator. */
68
+ class EventQueue<T> {
69
+ private buffer: T[] = [];
70
+ private wake: (() => void) | null = null;
71
+ private done = false;
72
+ private error: unknown = null;
73
+
74
+ push(value: T): void { this.buffer.push(value); this.signal(); }
75
+ close(): void { this.done = true; this.signal(); }
76
+ fail(error: unknown): void { this.error = error; this.done = true; this.signal(); }
77
+
78
+ private signal(): void {
79
+ const wake = this.wake;
80
+ this.wake = null;
81
+ wake?.();
82
+ }
83
+
84
+ async *drain(): AsyncGenerator<T, void, unknown> {
85
+ while (true) {
86
+ while (this.buffer.length) yield this.buffer.shift() as T;
87
+ if (this.error) throw this.error;
88
+ if (this.done) return;
89
+ await new Promise<void>((resolve) => { this.wake = resolve; });
90
+ }
91
+ }
92
+ }
93
+
94
+ export class PiEngine implements AIEngine {
95
+ readonly name = 'pi' as const;
96
+ private _isInitialized = false;
97
+ private activeController: AbortController | null = null;
98
+ private activeSession: AgentSession | null = null;
99
+ private pendingAsks = new Map<string, PendingAsk>();
100
+
101
+ get isInitialized(): boolean { return this._isInitialized; }
102
+ get isActive(): boolean { return this.activeController !== null; }
103
+
104
+ async initialize(): Promise<void> {
105
+ if (this._isInitialized) return;
106
+ this._isInitialized = true;
107
+ debug.log('engine', '✅ Pi engine initialized');
108
+ }
109
+
110
+ async dispose(): Promise<void> {
111
+ await this.cancel();
112
+ this.pendingAsks.clear();
113
+ this._isInitialized = false;
114
+ }
115
+
116
+ async getAvailableModels(): Promise<EngineModel[]> {
117
+ return fetchPiModels();
118
+ }
119
+
120
+ async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
121
+ const { projectPath, prompt, resume, providerSlug, modelId, abortController, accountId } = options;
122
+ debug.log('chat', 'Pi - Stream Query', { providerSlug, modelId, resume });
123
+
124
+ // ── Resolve account + credential + runtime + model ──
125
+ // Pi is multi-provider: prefer the account matching the model's provider,
126
+ // falling back to an explicit accountId override. (The chat picker selects
127
+ // one "active" account, but the model determines which provider streams.)
128
+ const account = getPiAccountForProvider(providerSlug)
129
+ ?? (accountId != null ? engineQueries.getAccount(accountId) : null);
130
+ if (!account) {
131
+ throw new Error(`Pi has no account for provider "${providerSlug}". Add one in Settings → Engines → Pi.`);
132
+ }
133
+ const provider = parsePiCredential(account.credential)?.provider ?? providerSlug;
134
+ const runtime = await createPiRuntime(new DbCredentialStore([account]));
135
+ const model = runtime.getModel(provider, modelId);
136
+ if (!model) {
137
+ throw new Error(`Pi could not resolve model "${modelId}" for provider "${provider}".`);
138
+ }
139
+
140
+ this.activeController = abortController || new AbortController();
141
+ const resolvedProjectPath = resolveOsPath(projectPath);
142
+ const agentDir = getPiAgentDir();
143
+
144
+ // ── Active Profile scoping + artifact materialization ──
145
+ const profileId = options.mcpContext?.profileId;
146
+ const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
147
+ await syncSkills('pi', profileId);
148
+ await syncEngineArtifacts('pi', profileId);
149
+
150
+ // ── Permissions (enforced at the `tool_call` extension hook) ──
151
+ const permissions = resolvePermissionsFromDb('pi', options.mcpContext?.projectId, profileId);
152
+ const permissionBlocker = (pi: ExtensionAPI) => {
153
+ pi.on('tool_call', async (event: { toolName: string }) => {
154
+ if (!isToolAllowed(permissions, event.toolName)) {
155
+ debug.log('permissions', `⛔ Pi blocked tool "${event.toolName}" (Clopen permission policy)`);
156
+ return { block: true, reason: `Blocked by Clopen permission policy: ${event.toolName}` };
157
+ }
158
+ return undefined;
159
+ });
160
+ };
161
+
162
+ // Late-bound handle to the stream's event queue so the subagent runner
163
+ // (built before the queue exists) can push sub-activity messages into it.
164
+ const queueHolder: { queue: EventQueue<EngineOutput> | null } = { queue: null };
165
+
166
+ // ── Tools: builtins (permission-filtered) + AskUserQuestion + MCP bridge + subagents ──
167
+ const allowedBuiltins = PI_BUILTIN_TOOLS.filter((name) => isToolAllowed(permissions, name));
168
+ const askTool = createAskUserQuestionTool({
169
+ register: (id, entry) => this.pendingAsks.set(id, entry),
170
+ unregister: (id) => this.pendingAsks.delete(id),
171
+ });
172
+ const mcpTools = await buildPiMcpTools(options.mcpContext, mcpProfileFilter);
173
+ const customTools: ToolDefinition[] = [askTool, ...mcpTools];
174
+ const toolAllowlist = [...allowedBuiltins, 'AskUserQuestion', ...mcpTools.map((t) => t.name)];
175
+
176
+ // Subagent dispatch — Pi has no native Agent tool, so materialising the
177
+ // "Available Subagents" preamble isn't enough; expose a tool that actually
178
+ // spawns a sub-session with the chosen subagent's system prompt.
179
+ const subagents: SubagentInfo[] = subagentQueries.getEnabled().map((s) => ({ slug: s.slug, name: s.name, description: s.description }));
180
+ if (subagents.length > 0) {
181
+ const agentTool = createAgentDispatchTool({
182
+ subagents,
183
+ run: async (subagent, subPrompt, toolCallId, signal) => {
184
+ const md = (await readSubagentMd(subagent.slug)) ?? '';
185
+ const instructions = stripFrontmatter(md) || `You are the ${subagent.name} subagent. ${subagent.description}`;
186
+ // APPEND the subagent instructions to Pi's base coding prompt —
187
+ // replacing it wholesale strips the tool-use scaffolding and the
188
+ // sub-agent then produces nothing. Keep the sub-session bounded:
189
+ // no nested skills/prompts/context-files/subagents.
190
+ const subLoader = new DefaultResourceLoader({
191
+ cwd: resolvedProjectPath,
192
+ agentDir,
193
+ appendSystemPromptOverride: (base) => [...base, `# Subagent: ${subagent.name}\n\n${instructions}`],
194
+ agentsFilesOverride: () => ({ agentsFiles: [] }),
195
+ skillsOverride: () => ({ skills: [], diagnostics: [] }),
196
+ promptsOverride: () => ({ prompts: [], diagnostics: [] }),
197
+ });
198
+ await subLoader.reload();
199
+ const { session: sub } = await createAgentSession({
200
+ cwd: resolvedProjectPath,
201
+ agentDir,
202
+ model,
203
+ modelRuntime: runtime,
204
+ thinkingLevel: 'off',
205
+ resourceLoader: subLoader,
206
+ tools: allowedBuiltins,
207
+ sessionManager: SessionManager.inMemory(resolvedProjectPath),
208
+ settingsManager: SettingsManager.inMemory({ retry: PI_RETRY, compaction: { enabled: false } }),
209
+ });
210
+ // Convert the sub-agent's events and route its messages into the
211
+ // parent Agent block as sub-activities (parent.toolUseId = the
212
+ // Agent tool_use id). Drop transient events so the sub-agent's
213
+ // live typing / result never leaks into the main turn.
214
+ const subConverter = createPiMessageConverter({
215
+ engine: { type: 'pi', provider, model: { id: modelId, name: model.name || modelId }, account: { id: account.id, name: account.name } },
216
+ sessionId: sub.sessionId,
217
+ });
218
+ let text = '';
219
+ const unsub = sub.subscribe((ev) => {
220
+ for (const out of subConverter.convert(ev)) {
221
+ if (out.type === 'stream_event' || out.type === 'result' || out.type === 'system_init' || out.type === 'notification') continue;
222
+ if (out.type === 'assistant' || out.type === 'user' || out.type === 'reasoning') {
223
+ out.parent = { messageId: null, sessionId: null, toolUseId: toolCallId };
224
+ }
225
+ if (out.type === 'assistant') {
226
+ const t = out.content.filter((b) => b.type === 'text').map((b) => (b.type === 'text' ? b.text : '')).join('');
227
+ if (t.trim()) text = t;
228
+ }
229
+ queueHolder.queue?.push(out);
230
+ }
231
+ });
232
+ const onSubAbort = () => { void sub.abort(); };
233
+ signal?.addEventListener('abort', onSubAbort, { once: true });
234
+ try {
235
+ await sub.prompt(subPrompt);
236
+ } finally {
237
+ signal?.removeEventListener('abort', onSubAbort);
238
+ unsub();
239
+ try { sub.dispose(); } catch { /* already disposed */ }
240
+ }
241
+ return text;
242
+ },
243
+ });
244
+ customTools.push(agentTool);
245
+ toolAllowlist.push('Agent');
246
+ }
247
+
248
+ // ── Resource loader (discovers synced skills/prompts/AGENTS.md) ──
249
+ const resourceLoader = new DefaultResourceLoader({
250
+ cwd: resolvedProjectPath,
251
+ agentDir,
252
+ extensionFactories: [permissionBlocker],
253
+ });
254
+ await resourceLoader.reload();
255
+
256
+ const sessionManager = await resolvePiSessionManager(resolvedProjectPath, resume);
257
+
258
+ const { session } = await createAgentSession({
259
+ cwd: resolvedProjectPath,
260
+ agentDir,
261
+ model,
262
+ modelRuntime: runtime,
263
+ thinkingLevel: model.reasoning ? 'medium' : 'off',
264
+ resourceLoader,
265
+ tools: toolAllowlist,
266
+ customTools,
267
+ excludeTools: ['ask_question'],
268
+ sessionManager,
269
+ settingsManager: SettingsManager.inMemory({ retry: PI_RETRY }),
270
+ });
271
+ this.activeSession = session;
272
+
273
+ const engineMeta: MessageEngine = {
274
+ type: 'pi',
275
+ provider,
276
+ model: { id: modelId, name: model.name || modelId },
277
+ account: { id: account.id, name: account.name },
278
+ };
279
+ const converter = createPiMessageConverter({ engine: engineMeta, sessionId: session.sessionId });
280
+ const queue = new EventQueue<EngineOutput>();
281
+ queueHolder.queue = queue;
282
+ const unsubscribe = session.subscribe((event) => {
283
+ try {
284
+ for (const out of converter.convert(event)) queue.push(out);
285
+ } catch (error) {
286
+ queue.fail(error);
287
+ return;
288
+ }
289
+ if (event.type === 'agent_end') queue.close();
290
+ });
291
+
292
+ // Abort wiring: cancelling the stream aborts the Pi session.
293
+ const onAbort = () => { void session.abort(); };
294
+ this.activeController.signal.addEventListener('abort', onAbort, { once: true });
295
+
296
+ // Prompt text + image attachments.
297
+ const promptText = prompt.content.filter((b) => b.type === 'text').map((b) => b.text).join('\n');
298
+ const images: ImageContent[] = prompt.content
299
+ .filter((b): b is Extract<typeof b, { type: 'image' }> => b.type === 'image')
300
+ .map((b) => ({ type: 'image', data: b.data, mimeType: b.mediaType }));
301
+
302
+ // system_init first — model + enabled tools (Pi bridges MCP as custom tools).
303
+ yield {
304
+ type: 'system_init',
305
+ sessionId: session.sessionId,
306
+ model: modelId,
307
+ engine: 'pi',
308
+ tools: toolAllowlist,
309
+ mcpServers: [],
310
+ };
311
+
312
+ // Close the queue when prompt() settles even if no `agent_end` ever fires
313
+ // (e.g. a slash command Pi rejects at preflight, or an empty expansion) —
314
+ // otherwise the drain loop would block forever and the stream would hang.
315
+ const promptOptions = {
316
+ ...(images.length ? { images } : {}),
317
+ preflightResult: (success: boolean) => {
318
+ if (!success) {
319
+ queue.push({
320
+ type: 'notification',
321
+ sessionId: session.sessionId,
322
+ level: 'warning',
323
+ title: 'Prompt not accepted',
324
+ message: 'Pi did not accept this input (unknown command or empty prompt).',
325
+ });
326
+ }
327
+ },
328
+ };
329
+ const promptPromise = session.prompt(promptText, promptOptions)
330
+ .then(() => queue.close())
331
+ .catch((error) => queue.fail(error));
332
+
333
+ try {
334
+ for await (const out of queue.drain()) yield out;
335
+ await promptPromise;
336
+ } catch (error) {
337
+ handleStreamError(error);
338
+ } finally {
339
+ this.activeController?.signal.removeEventListener('abort', onAbort);
340
+ unsubscribe();
341
+ try { session.dispose(); } catch { /* already disposed */ }
342
+ this.activeSession = null;
343
+ this.activeController = null;
344
+ this.pendingAsks.clear();
345
+ }
346
+ }
347
+
348
+ async cancel(): Promise<void> {
349
+ if (this.activeController && !this.activeController.signal.aborted) {
350
+ this.activeController.abort();
351
+ }
352
+ if (this.activeSession) {
353
+ try { await this.activeSession.abort(); } catch { /* may already be idle */ }
354
+ }
355
+ this.pendingAsks.clear();
356
+ this.activeSession = null;
357
+ this.activeController = null;
358
+ }
359
+
360
+ async interrupt(): Promise<void> {
361
+ if (this.activeSession) {
362
+ try { await this.activeSession.abort(); } catch { /* ignore */ }
363
+ }
364
+ }
365
+
366
+ resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
367
+ const pending = this.pendingAsks.get(toolUseId);
368
+ if (!pending) {
369
+ debug.warn('engine', `Pi resolveUserAnswer: no pending question for ${toolUseId}`);
370
+ return false;
371
+ }
372
+ const result: AgentToolResult<unknown> = {
373
+ content: [{ type: 'text', text: formatAnswers(pending.questions, answers) }],
374
+ details: {},
375
+ };
376
+ pending.resolve(result);
377
+ this.pendingAsks.delete(toolUseId);
378
+ return true;
379
+ }
380
+
381
+ /**
382
+ * One-shot structured JSON generation via prompt engineering (Pi has no native
383
+ * JSON-schema output mode). Runs a tool-less in-memory session and parses the
384
+ * final assistant text.
385
+ */
386
+ async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
387
+ const { prompt, providerSlug, modelId, schema, projectPath, accountId } = options;
388
+
389
+ const account = getPiAccountForProvider(providerSlug)
390
+ ?? (accountId != null ? engineQueries.getAccount(accountId) : null);
391
+ if (!account) throw new Error(`Pi has no account for provider "${providerSlug}".`);
392
+ const provider = parsePiCredential(account.credential)?.provider ?? providerSlug;
393
+ const runtime = await createPiRuntime(new DbCredentialStore([account]));
394
+ const model = runtime.getModel(provider, modelId);
395
+ if (!model) throw new Error(`Pi could not resolve model "${modelId}" for provider "${provider}".`);
396
+
397
+ const resolvedProjectPath = resolveOsPath(projectPath);
398
+ const { session } = await createAgentSession({
399
+ cwd: resolvedProjectPath,
400
+ agentDir: getPiAgentDir(),
401
+ model,
402
+ modelRuntime: runtime,
403
+ thinkingLevel: 'off',
404
+ noTools: 'all',
405
+ sessionManager: SessionManager.inMemory(resolvedProjectPath),
406
+ settingsManager: SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: false } }),
407
+ });
408
+
409
+ let resultText = '';
410
+ const unsubscribe = session.subscribe((event) => {
411
+ if (event.type === 'message_end' && (event.message as { role?: string })?.role === 'assistant') {
412
+ const content = (event.message as { content?: Array<{ type: string; text?: string }> }).content ?? [];
413
+ resultText = content.filter((b) => b.type === 'text').map((b) => b.text ?? '').join('');
414
+ }
415
+ });
416
+
417
+ try {
418
+ await session.prompt(buildJsonPrompt(prompt, schema));
419
+ } finally {
420
+ unsubscribe();
421
+ try { session.dispose(); } catch { /* ignore */ }
422
+ }
423
+
424
+ if (!resultText.trim()) throw new Error('Pi returned no structured output');
425
+ return extractJson<T>(resultText);
426
+ }
427
+ }
@@ -216,7 +216,7 @@ const QWEN_TOOL_NAME_MAP: Record<string, string> = {
216
216
  function canonicaliseToolName(rawName: string): string {
217
217
  // MCP tools come through as `clopen-mcp_<tool>` or `clopen-mcp-<tool>` —
218
218
  // route through the shared resolver so they collapse to the canonical
219
- // `mcp__<server>__<tool>` form (README §9.12).
219
+ // `mcp__<server>__<tool>` form (README §10.12).
220
220
  const resolved = resolveOpenCodeToolName(rawName);
221
221
  if (resolved) return resolved;
222
222
 
@@ -632,7 +632,7 @@ export function convertAssistantMessage(msg: SDKAssistantMessage, state: QwenCon
632
632
  };
633
633
  outputs.push(assistant);
634
634
  } else {
635
- // One tool_use per AssistantMessage (README §9.3).
635
+ // One tool_use per AssistantMessage (README §10.3).
636
636
  blocks.forEach((block, idx) => {
637
637
  const assistant: AssistantMessage = {
638
638
  type: 'assistant',
@@ -708,7 +708,7 @@ export function convertUserMessage(msg: SDKUserMessage, state: QwenConverterStat
708
708
  messageId: msg.uuid || crypto.randomUUID(),
709
709
  sessionId: msg.session_id,
710
710
  // Top-level tool_result UserMessage MUST keep parent.toolUseId = null
711
- // (README §9.5). Sub-agent messages are an explicit exception.
711
+ // (README §10.5). Sub-agent messages are an explicit exception.
712
712
  parent: { messageId: null, sessionId: null, toolUseId: msg.parent_tool_use_id || null },
713
713
  engine: buildEngine(state.modelId),
714
714
  sender: { id: '', name: '' },
@@ -751,7 +751,7 @@ export function convertStreamEvent(msg: SDKPartialAssistantMessage, state: QwenC
751
751
  // message scoped to the sub-agent (which carries `parent_tool_use_id` and
752
752
  // is routed into the parent Agent block's subActivities by the frontend
753
753
  // grouper). Without this drop, the deltas leak into the main turn's text
754
- // bubble. See README §9.15 fix #3.
754
+ // bubble. See README §10.15 fix #3.
755
755
  if (msg.parent_tool_use_id) return outputs;
756
756
 
757
757
  switch (event.type) {
@@ -905,7 +905,7 @@ function convertTaskNotification(msg: SDKSystemMessage, state: QwenConverterStat
905
905
  /**
906
906
  * Finalize any AskUserQuestion / Agent calls that are still open when the
907
907
  * SDK ends the query. Without this, the UI would leave Agent blocks spinning
908
- * forever (Qwen forks have no completion notification — README §9.15) and
908
+ * forever (Qwen forks have no completion notification — README §10.15) and
909
909
  * AUQ blocks would stay pending if the user closed the dialog without
910
910
  * answering.
911
911
  */
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * MCP: reuses the existing remote MCP HTTP server at `/mcp` via
16
16
  * `getQwenMcpConfig()`. Tool handlers run in-process in the Clopen backend
17
- * (README §9.12).
17
+ * (README §10.12).
18
18
  *
19
19
  * AskUserQuestion: Qwen's `canUseTool` callback signature does NOT include
20
20
  * the tool_use_id (see `node_modules/@qwen-code/sdk/dist/index.d.ts:406-409`),
@@ -155,7 +155,7 @@ export class QwenEngine implements AIEngine {
155
155
 
156
156
  // Fork-by-copy on EVERY resume — same semantics as Claude
157
157
  // (`forkSession: true`), OpenCode (`client.session.fork()`),
158
- // Copilot, and Codex (README §9.10): each turn must produce a
158
+ // Copilot, and Codex (README §10.10): each turn must produce a
159
159
  // brand-new session id so the original branch's history is never
160
160
  // mutated and the multi-branch checkpoint tree stays consistent.
161
161
  // Falls through to a plain resume only when the source chat can't
@@ -129,7 +129,7 @@ calling `getEnabledMcpServers(options.mcpContext)`.
129
129
  - ❌ **Create per-account isolated home directories** to multiplex two
130
130
  accounts into the same CLI's shared dotfile. Snapshot the CLI's auth
131
131
  file into `engine_accounts.credential` on login; write the chosen
132
- account's snapshot back into the shared location on switch. See §9.13.
132
+ account's snapshot back into the shared location on switch. See §10.13.
133
133
 
134
134
  ### 2.6 Standard files in each adapter
135
135
 
@@ -157,7 +157,7 @@ Naming rules — strict, even when an SDK's local jargon differs:
157
157
 
158
158
  | File | Owns |
159
159
  |-------------------|-----------------------------------------------------------------------|
160
- | `credential.ts` | Parse `engine_accounts.credential` (JSON wrapper or raw key); for shared-CLI engines, materialise the auth-blob into the dotfile and snapshot it back. **Never** name this `auth.ts` — credentials are the unified concept (see §9.13). |
160
+ | `credential.ts` | Parse `engine_accounts.credential` (JSON wrapper or raw key); for shared-CLI engines, materialise the auth-blob into the dotfile and snapshot it back. **Never** name this `auth.ts` — credentials are the unified concept (see §10.13). |
161
161
  | `error-handler.ts`| Export `handleStreamError(error: unknown, ...): void` that swallows abort errors and re-throws everything else as a sanitised `Error`. Required even when the body is short — `OpenCodeEngine` previously inlined ~50 lines into the catch block; that pattern is no longer accepted. |
162
162
  | `presets.ts` | Multi-provider/region picker catalog (Qwen's DashScope/OpenRouter/Fireworks; OpenCode's models.dev cache). Multi-provider engines that lacked a `presets.ts` (OpenCode used to call this `config.ts`) have been migrated. |
163
163
  | `config.ts` | Runtime config builder ONLY — turning DB providers + accounts into env vars / spawn options. Catalog data goes in `presets.ts`. |
@@ -178,6 +178,11 @@ Important conventions:
178
178
  use `[]` as the failure sentinel (network, auth, parse error). Do **not**
179
179
  return `null` — both `fetchOpenCodeModels` and `fetchQwenModels` return
180
180
  `[]` on failure so the picker renders empty rather than a stale catalog.
181
+ - `stream.ts` materialises the user's artifacts at stream start: call
182
+ `syncSkills(...)` then `syncEngineArtifacts(...)` (and, for prompt-scoped
183
+ engines, prepend `buildArtifactsPromptContext(...)` to the prompt) from
184
+ `backend/engine/artifact-sync.ts`. These are shared helpers, **not** files in
185
+ the per-adapter taxonomy — the adapter only calls them. See §8.3.
181
186
 
182
187
  ---
183
188
 
@@ -1,6 +1,6 @@
1
1
  [← Engine adapter guide](../README.md)
2
2
 
3
- ## 8. End-to-end checklist for adding a new engine
3
+ ## 9. End-to-end checklist for adding a new engine
4
4
 
5
5
  The steps below are the same pattern used when the **`copilot`**
6
6
  (`@github/copilot-sdk`) adapter was added to the repo. Use it as a
@@ -13,6 +13,19 @@ blueprint for the next engine you add.
13
13
  - [ ] `shared/types/unified/message.ts`: add `'newengine'` to `MessageEngine.type`.
14
14
  - [ ] `shared/constants/engines.ts`: add an entry in `ENGINES[]`
15
15
  (`type, name, description, icon.light, icon.dark`).
16
+ - [ ] **Exhaustive `Record<EngineType, …>` maps & unions — forgetting any is a
17
+ compile error, so `bun run check` after this step catches them all:**
18
+ - `shared/constants/engine-tools.ts`: add `'newengine'` to
19
+ `ENGINE_BUILTIN_TOOLS` (its built-in tool names) **and**
20
+ `ENGINE_TOOLS_BEST_EFFORT` (`true` unless the SDK has a real per-tool
21
+ permission hook).
22
+ - `backend/artifacts/types.ts`: add the engine's config-dir slug to
23
+ `ArtifactEngine` **and** `ARTIFACT_ENGINES` (usually the same as the
24
+ `EngineType`; `claude-code`→`claude` is the one exception).
25
+ - `backend/permissions/service.ts`: add the entry to `ENGINE_TYPE_TO_ARTIFACT`
26
+ (+ `ArtifactEngineKey`).
27
+ - `backend/ws/sessions/crud.ts`: add the `'newengine'` literal to the two
28
+ session-engine typebox unions (in addition to the Stage-4 chat/crud ones).
16
29
  - [ ] `backend/engine/adapters/newengine/models.ts`: own the catalog. Static
17
30
  engines export a `NEWENGINE_MODELS: EngineModel[]` array; dynamic
18
31
  engines export a fetcher (`fetchNewengineModels(...)`) consumed by
@@ -36,30 +49,63 @@ mandatory files; optional files use the canonical names from §2.6.
36
49
  - [ ] `stream.ts` (mandatory) → class `NewEngineEngine implements AIEngine`.
37
50
  Pick a template: `claude/stream.ts` (in-process SDK),
38
51
  `opencode/stream.ts` (subprocess), `copilot/stream.ts` (in-process
39
- with construction-time credential), or `qwen/stream.ts` (CLI subprocess
40
- via SDK with auth-blob swap).
52
+ with construction-time credential), `qwen/stream.ts` (CLI subprocess
53
+ via SDK with auth-blob swap), `pi/stream.ts` (in-process SDK with an
54
+ on-disk session store), or `cline/stream.ts` (in-process, **session-less**
55
+ stateless `Agent`).
56
+ - [ ] **Fork / checkpoints (mandatory, easy to miss).** Every resume MUST
57
+ fork so branches don't cross-contaminate — see §10.10. Native-fork SDKs
58
+ pass a flag; on-disk SDKs copy the session file; a **session-less** SDK
59
+ (`cline`) mints a fresh session id per turn and copies the parent
60
+ transcript forward in memory (never reuse the `resume` id as the store
61
+ key). Symptom of getting it wrong: every persisted assistant message
62
+ shares one session id, and an undo+continue answers with the sibling
63
+ branch's history.
64
+ - [ ] **Sub-agents (if the engine has no native `Task`/`Agent` tool).** A
65
+ session-less/bare-loop SDK must **synthesize** the `Agent` tool
66
+ (`cline/agent-tool.ts`), register it + `toolPolicies.Agent`, route the
67
+ sub-agent's messages into the stream tagged with `parent.toolUseId`, and
68
+ push **tool_use only** as sub-activities — see §10.15.
41
69
  - [ ] `models.ts` (mandatory) → static `NEWENGINE_MODELS: EngineModel[]`
42
70
  OR `fetchNewengineModels(...): Promise<EngineModel[]>` (dynamic;
43
71
  return `[]` on failure — see §4.5).
44
72
  - [ ] `message-converter.ts` (mandatory) → pure functions SDK → `EngineOutput`.
45
- Use `toCanonicalToolName()` for tool names.
73
+ Use `toCanonicalToolName()` for tool names. **Before writing it, capture the
74
+ SDK's REAL runtime shapes** — a throwaway script that runs one agent and
75
+ `JSON.stringify`s each stream event, tool arg, and tool result (using the
76
+ model the user will run). `.d.ts` types routinely mislead on: whether the
77
+ stream is per-chunk deltas vs snapshots, the actual tool-arg field names,
78
+ whether a payload lives in the args or the result, tool-name wrapping
79
+ (`mcp`-style), and result envelopes (`{status,value}` / images). See
80
+ **§10.20** for the full catalogue of these traps.
81
+ - [ ] **Usage that arrives once per turn:** if the SDK emits a single `usage`
82
+ event after all messages (Codex, Cursor), assistant rows persist
83
+ `usage:null` — add the engine to `stream-manager.ts::backfillUsageForStream`'s
84
+ gate so the turn aggregate is written to every assistant row (see §10.20-I).
85
+ - [ ] **Context window:** set `EngineModel.limit.input` to the model's real max
86
+ when the catalog provides it; leave `0` when it doesn't — do NOT hard-code a
87
+ value. The UI renders `0` as "?" via `getContextUsage(...).unknown` (§10.20-J).
46
88
  - [ ] `error-handler.ts` (mandatory) → exports `handleStreamError(error,
47
89
  ...): void` (and any helper formatters specific to the SDK's error
48
90
  payload — see `opencode/error-handler.ts::formatSessionError` for the
49
91
  pattern).
50
92
  - [ ] `credential.ts` / `environment.ts` / `server.ts` / `config.ts` /
51
93
  `presets.ts` / `session-fork.ts` (optional; canonical names only).
94
+ - [ ] Artifacts: in `streamQuery`, call `syncSkills(...)` +
95
+ `syncEngineArtifacts(...)` at stream start, and — for a prompt-scoped
96
+ engine — prepend `buildArtifactsPromptContext(...)` to the prompt (from
97
+ `backend/engine/artifact-sync.ts`). Mirror `claude/stream.ts`. See §8.
52
98
  - [ ] `backend/engine/index.ts`: import + add a case in
53
99
  `createEngine(type)`. If there is a shared subprocess, call
54
100
  `disposeXxxClient()` from `disposeAllProjectEngines()`.
55
101
  - [ ] MCP config (if the SDK accepts a streamable-HTTP MCP URL):
56
102
  - [ ] Internal bridge — add `getXxxMcpConfig()` in
57
- `backend/mcp/internal/config.ts` (reuse `clopen-mcp`; see §9.12).
103
+ `backend/mcp/internal/config.ts` (reuse `clopen-mcp`; see §10.12).
58
104
  - [ ] External servers — add `getXxxExternalMcpConfig()` in
59
105
  `backend/mcp/external/config.ts` and **forward `headers`** so the
60
106
  centralized OAuth bearer reaches the engine. Use the SDK's real
61
107
  header field — **Codex uses `http_headers`, not `bearer_token`**.
62
- See §9.18 and `backend/mcp/README.md`.
108
+ See §10.18 and `backend/mcp/README.md`.
63
109
 
64
110
  ### Stage 3 — Database (if a default provider needs to be seeded)
65
111
 
@@ -94,13 +140,25 @@ mandatory files; optional files use the canonical names from §2.6.
94
140
 
95
141
  ### Stage 6 — Settings → Engines
96
142
 
97
- - [ ] Add a panel to `AIEnginesSettings.svelte`: the card appears
98
- automatically since `ENGINES` already has the new entry. Implement
99
- the setup flow:
100
- - Load status via `ws.http('engine:newengine-status', {})`.
101
- - Subscribe to server-emit events for login progress.
102
- - After save: `newengineStore.refresh()` +
143
+ - [ ] Add `frontend/components/settings/engines/panels/NewEnginePanel.svelte`
144
+ and wire it into `AIEnginesSettings.svelte`: its selector tile appears
145
+ automatically (`ENGINES` has the new entry), and the shell renders the
146
+ panel in the `{#if activeEngine === 'newengine'}` branch. Add the
147
+ engine's status shape to `panels/panel-types.ts` and a
148
+ `refreshNewEngineStatus()` in the shell (fetched on mount for the grid,
149
+ passed to the panel as `onRefreshStatus`). Implement the setup flow in
150
+ the panel:
151
+ - Receive `status` + `isLoading` (+ `onRefreshStatus` if it mutates
152
+ accounts) as props; read the account list from its own store.
153
+ - Load status via `ws.http('engine:newengine-status', {})` (in the shell).
154
+ - Subscribe to server-emit events for login progress (in the panel's
155
+ `onMount`, cleaned up in `onDestroy`).
156
+ - After save: `newengineStore.refresh()` + `onRefreshStatus()` +
103
157
  `modelStore.refreshModels('newengine')`.
158
+ - If the engine has a browser/device auth flow, factor the auth markup into
159
+ a `{#snippet}` and render it both in the "Add Account" area and in the
160
+ account edit form (in-place re-auth), gated on `newengineReauthAccountId`
161
+ — mirror `ClaudeCodePanel`/`CodexPanel`/`PiPanel`.
104
162
 
105
163
  ### Stage 7 — Settings → System Tools
106
164