@myrialabs/clopen 0.4.17 → 0.4.18

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 (89) hide show
  1. package/README.md +3 -3
  2. package/backend/auth/auth-service.ts +265 -13
  3. package/backend/auth/permissions.ts +3 -0
  4. package/backend/auth/rate-limiter.ts +1 -0
  5. package/backend/auth/session-cleanup.ts +5 -0
  6. package/backend/auth/tokens.ts +8 -1
  7. package/backend/chat/stream-manager.ts +8 -0
  8. package/backend/database/migrations/060_create_device_codes_table.ts +38 -0
  9. package/backend/database/migrations/061_add_session_device_metadata.ts +42 -0
  10. package/backend/database/migrations/062_add_session_source.ts +43 -0
  11. package/backend/database/migrations/063_add_invite_project_ids.ts +42 -0
  12. package/backend/database/migrations/064_create_messages_fts.ts +71 -0
  13. package/backend/database/migrations/index.ts +35 -0
  14. package/backend/database/queries/auth-queries.ts +100 -6
  15. package/backend/database/queries/message-queries.ts +44 -0
  16. package/backend/database/queries/session-queries.ts +117 -12
  17. package/backend/engine/README.md +21 -4
  18. package/backend/engine/adapters/claude/stream.ts +4 -2
  19. package/backend/engine/adapters/cline/agent-tool.ts +3 -2
  20. package/backend/engine/adapters/cline/ask-question-tool.ts +3 -2
  21. package/backend/engine/adapters/cline/credential.ts +2 -1
  22. package/backend/engine/adapters/cline/mcp-tools.ts +2 -1
  23. package/backend/engine/adapters/cline/models.ts +3 -1
  24. package/backend/engine/adapters/cline/presets.ts +5 -3
  25. package/backend/engine/adapters/cline/stream.ts +10 -7
  26. package/backend/engine/adapters/codex/stream.ts +3 -1
  27. package/backend/engine/adapters/copilot/stream.ts +8 -1
  28. package/backend/engine/adapters/cursor/environment.ts +4 -2
  29. package/backend/engine/adapters/cursor/models.ts +2 -1
  30. package/backend/engine/adapters/cursor/stream.ts +5 -3
  31. package/backend/engine/adapters/pi/presets.ts +3 -1
  32. package/backend/engine/adapters/pi/session-fork.ts +3 -1
  33. package/backend/engine/adapters/pi/stream.ts +11 -8
  34. package/backend/engine/bootstrap-default-engine.ts +69 -0
  35. package/backend/engine/docs/adding-an-engine.md +29 -6
  36. package/backend/engine/docs/frontend-and-chat.md +21 -5
  37. package/backend/engine/docs/lessons-learned.md +41 -0
  38. package/backend/engine/docs/quick-reference.md +3 -2
  39. package/backend/engine/docs/system-tools.md +65 -9
  40. package/backend/engine/docs/websocket-routes.md +4 -3
  41. package/backend/engine/engine-setup.ts +72 -0
  42. package/backend/engine/install-recipes.ts +82 -77
  43. package/backend/engine/install-runner.ts +27 -2
  44. package/backend/engine/sdk-loader.ts +180 -0
  45. package/backend/engine/version-check.ts +6 -6
  46. package/backend/http/files-upload.test.ts +4 -1
  47. package/backend/index.ts +32 -2
  48. package/backend/mcp/README.md +26 -8
  49. package/backend/mcp/index.ts +2 -2
  50. package/backend/mcp/internal/config.ts +54 -63
  51. package/backend/mcp/internal/remote-server.test.ts +4 -1
  52. package/backend/mcp/internal/servers/helper.ts +4 -34
  53. package/backend/mcp/internal/servers/index.ts +4 -13
  54. package/backend/tunnel/public-origin.ts +118 -0
  55. package/backend/utils/ws.ts +126 -1
  56. package/backend/ws/auth/device.ts +239 -0
  57. package/backend/ws/auth/index.ts +8 -0
  58. package/backend/ws/auth/invites.ts +16 -6
  59. package/backend/ws/auth/login.test.ts +2 -2
  60. package/backend/ws/auth/login.ts +12 -6
  61. package/backend/ws/engine/claude/status.ts +4 -4
  62. package/backend/ws/engine/cline/accounts.ts +3 -2
  63. package/backend/ws/engine/cline/status.ts +4 -12
  64. package/backend/ws/engine/codex/status.ts +4 -12
  65. package/backend/ws/engine/copilot/status.ts +5 -12
  66. package/backend/ws/engine/cursor/accounts.ts +2 -1
  67. package/backend/ws/engine/cursor/status.ts +5 -12
  68. package/backend/ws/engine/opencode/status.ts +4 -4
  69. package/backend/ws/engine/pi/status.ts +4 -12
  70. package/backend/ws/engine/qwen/status.ts +5 -12
  71. package/backend/ws/sessions/crud.ts +29 -4
  72. package/backend/ws/settings/crud.ts +10 -1
  73. package/backend/ws/system/operations.ts +34 -18
  74. package/backend/ws/system-tools/install.ts +3 -0
  75. package/backend/ws/system-tools/status.ts +7 -2
  76. package/backend/ws/tunnel/index.ts +3 -1
  77. package/backend/ws/tunnel/share.ts +27 -0
  78. package/bin/clopen.ts +1 -1
  79. package/dist/assets/{index-kME3THy5.js → index-Cz8HVhsm.js} +1 -1
  80. package/dist/assets/{index-Bu5loFQE.js → index-SI4Gcd0p.js} +1 -1
  81. package/dist/assets/main-Cry3pLcl.css +1 -0
  82. package/dist/assets/{main-HirJLquI.js → main-Dlba-fXF.js} +337 -330
  83. package/dist/index.html +2 -2
  84. package/package.json +15 -14
  85. package/shared/constants/engines.ts +39 -40
  86. package/shared/constants/tool-icons.ts +49 -0
  87. package/shared/types/stores/settings.ts +9 -0
  88. package/shared/utils/logger.ts +1 -0
  89. package/dist/assets/main-D7ATW8pp.css +0 -1
@@ -14,9 +14,9 @@
14
14
  * tool result carries the formatted answers.
15
15
  */
16
16
 
17
- import { createTool } from '@cline/sdk';
18
17
  import type { AgentTool, AgentToolContext } from '@cline/sdk';
19
18
  import type { AskUserQuestion } from '$shared/types/unified';
19
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
20
20
 
21
21
  export interface PendingAsk {
22
22
  questions: AskUserQuestion[];
@@ -72,7 +72,8 @@ const ASK_INPUT_SCHEMA = {
72
72
  required: ['questions'],
73
73
  } as const;
74
74
 
75
- export function createAskUserQuestionTool(bindings: AskToolBindings): AgentTool {
75
+ export async function createAskUserQuestionTool(bindings: AskToolBindings): Promise<AgentTool> {
76
+ const { createTool } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
76
77
  return createTool({
77
78
  name: 'AskUserQuestion',
78
79
  description:
@@ -19,10 +19,10 @@
19
19
  * mutation (mirrors Pi's DB-backed credential contract).
20
20
  */
21
21
 
22
- import { getProviderAuthHandler, formatProviderOAuthApiKey } from '@cline/sdk';
23
22
  import type { OAuthCredentials, ProviderSettings } from '@cline/sdk';
24
23
  import { engineQueries, type EngineAccount } from '$backend/database/queries/engine-queries';
25
24
  import { debug } from '$shared/utils/logger';
25
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
26
26
 
27
27
  export type ClineAuthMethod = 'api_key' | 'oauth';
28
28
 
@@ -125,6 +125,7 @@ export async function resolveClineAuth(account: EngineAccount): Promise<Resolved
125
125
  }
126
126
 
127
127
  // OAuth: refresh if near-expiry, then format the access token as an api key.
128
+ const { getProviderAuthHandler, formatProviderOAuthApiKey } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
128
129
  let creds = parsed.oauth as OAuthCredentials;
129
130
  const handler = getProviderAuthHandler(parsed.provider);
130
131
  const nearExpiry = typeof creds.expires === 'number' && creds.expires <= Date.now() + OAUTH_REFRESH_BUFFER_MS;
@@ -16,9 +16,9 @@
16
16
  * + `toCanonicalToolName()` render them identically to the other engines.
17
17
  */
18
18
 
19
- import { createTool } from '@cline/sdk';
20
19
  import type { AgentTool, AgentToolContext } from '@cline/sdk';
21
20
  import type { McpExecutionContext } from '../../types';
21
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
22
22
  import {
23
23
  getEnabledServerNames,
24
24
  isToolEnabled,
@@ -59,6 +59,7 @@ export async function buildClineMcpTools(
59
59
  context: McpExecutionContext | undefined,
60
60
  profileFilter: Set<string> | undefined,
61
61
  ): Promise<AgentTool[]> {
62
+ const { createTool } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
62
63
  const tools: AgentTool[] = [];
63
64
 
64
65
  // ── Internal servers (in-process handlers) ──
@@ -11,15 +11,17 @@
11
11
  * the picker renders empty rather than a stale list).
12
12
  */
13
13
 
14
- import { Llms } from '@cline/sdk';
14
+ import type { Llms } from '@cline/sdk';
15
15
  import type { EngineModel } from '$shared/types/unified';
16
16
  import { debug } from '$shared/utils/logger';
17
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
17
18
  import { getClineAccounts, parseClineCredential } from './credential';
18
19
 
19
20
  type CatalogModel = Awaited<ReturnType<typeof Llms.getModelsForProvider>>[string];
20
21
 
21
22
  export async function fetchClineModels(): Promise<EngineModel[]> {
22
23
  try {
24
+ const { Llms } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
23
25
  // Distinct providers that have at least one stored account.
24
26
  const providers = new Set<string>();
25
27
  for (const account of getClineAccounts()) {
@@ -12,9 +12,9 @@
12
12
  * importing `$backend`.
13
13
  */
14
14
 
15
- import { Llms, getProviderConfigFields, isOAuthProvider } from '@cline/sdk';
16
15
  import type { ClineAuthMode, ClineCredentialField, ClineProviderPreset } from '$shared/types/unified';
17
16
  import { debug } from '$shared/utils/logger';
17
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
18
18
 
19
19
  export type { ClineAuthMode, ClineCredentialField, ClineProviderPreset };
20
20
 
@@ -64,7 +64,8 @@ const SECRET_FIELDS = new Set(['apiKey', 'sapClientSecret']);
64
64
  * Map a provider's `getProviderConfigFields` shape into the wire
65
65
  * `ClineCredentialField[]` the account form renders.
66
66
  */
67
- export function getClineProviderFields(providerId: string): ClineCredentialField[] {
67
+ export async function getClineProviderFields(providerId: string): Promise<ClineCredentialField[]> {
68
+ const { getProviderConfigFields } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
68
69
  const config = getProviderConfigFields(providerId);
69
70
  const out: ClineCredentialField[] = [];
70
71
  for (const [key, req] of Object.entries(config.fields ?? {})) {
@@ -97,11 +98,12 @@ let presetsCache: ClineProviderPreset[] | null = null;
97
98
  export async function getClineProviderPresets(): Promise<ClineProviderPreset[]> {
98
99
  if (presetsCache) return presetsCache;
99
100
  try {
101
+ const { Llms, getProviderConfigFields, isOAuthProvider } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
100
102
  const presets: ClineProviderPreset[] = [];
101
103
  for (const provider of await Llms.getAllProviders()) {
102
104
  const config = getProviderConfigFields(provider.id);
103
105
  const oauth = isOAuthProvider(provider.id) || config.authMethod === 'oauth';
104
- const fields = getClineProviderFields(provider.id);
106
+ const fields = await getClineProviderFields(provider.id);
105
107
  const hasApiKey = config.authMethod === 'api-key' || config.authMethod === 'local' || fields.some(f => f.role === 'apiKey');
106
108
 
107
109
  const authModes: ClineAuthMode[] = [];
@@ -21,11 +21,11 @@
21
21
  * the running server via `restore()` of the prior transcript.
22
22
  */
23
23
 
24
- import { Agent, createBuiltinTools, getClineDefaultSystemPrompt } from '@cline/sdk';
25
- import type { AgentTool, ToolPolicy } from '@cline/sdk';
24
+ import type { Agent, AgentTool, ToolPolicy } from '@cline/sdk';
26
25
  import type { AgentMessage, AgentMessagePart, AgentRunResult } from '@cline/agents';
27
26
  import type { EngineOutput, EngineModel, MessageEngine } from '$shared/types/unified';
28
27
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
28
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
29
29
  import { resolveOsPath } from '$backend/utils/paths';
30
30
  import { debug } from '$shared/utils/logger';
31
31
  import { engineQueries } from '$backend/database/queries/engine-queries';
@@ -50,7 +50,7 @@ const CLINE_BUILTIN_TOOLS = ['read_files', 'search_codebase', 'run_commands', 'f
50
50
  /** Max per-turn transcripts kept in memory before FIFO eviction (branch history). */
51
51
  const MAX_TRACKED_SESSIONS = 500;
52
52
 
53
- type ClineAgent = InstanceType<typeof Agent>;
53
+ type ClineAgent = Agent;
54
54
 
55
55
  /** Strip YAML frontmatter from a subagent markdown doc, leaving the instructions. */
56
56
  function stripFrontmatter(md: string): string {
@@ -120,7 +120,8 @@ export class ClineEngine implements AIEngine {
120
120
  return fetchClineModels();
121
121
  }
122
122
 
123
- private buildSystemPrompt(cwd: string, providerId: string, profileId?: number): string {
123
+ private async buildSystemPrompt(cwd: string, providerId: string, profileId?: number): Promise<string> {
124
+ const { getClineDefaultSystemPrompt } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
124
125
  let base: string;
125
126
  try {
126
127
  base = getClineDefaultSystemPrompt({ cwd, workspaceRoot: cwd, providerId, platform: process.platform });
@@ -161,12 +162,13 @@ export class ClineEngine implements AIEngine {
161
162
  const queueHolder: { queue: EventQueue<EngineOutput> | null } = { queue: null };
162
163
 
163
164
  // ── Tools: builtins + AskUserQuestion + MCP bridge ──
165
+ const { Agent, createBuiltinTools, getClineDefaultSystemPrompt } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
164
166
  const builtinTools = createBuiltinTools({
165
167
  cwd: resolvedProjectPath,
166
168
  enableAskQuestion: false,
167
169
  enableSubmitAndExit: false,
168
170
  });
169
- const askTool = createAskUserQuestionTool({
171
+ const askTool = await createAskUserQuestionTool({
170
172
  register: (id, entry) => this.pendingAsks.set(id, entry),
171
173
  unregister: (id) => this.pendingAsks.delete(id),
172
174
  });
@@ -186,7 +188,7 @@ export class ClineEngine implements AIEngine {
186
188
  // system prompt and returns its final text. ──
187
189
  const subagents: SubagentInfo[] = subagentQueries.getEnabled().map(s => ({ slug: s.slug, name: s.name, description: s.description }));
188
190
  if (subagents.length > 0) {
189
- const agentTool = createAgentDispatchTool({
191
+ const agentTool = await createAgentDispatchTool({
190
192
  subagents,
191
193
  run: async (subagent, subPrompt, toolCallId, signal) => {
192
194
  const md = (await readSubagentMd(subagent.slug)) ?? '';
@@ -264,7 +266,7 @@ export class ClineEngine implements AIEngine {
264
266
  const priorMessages = resume ? this.sessions.get(resume) : undefined;
265
267
  const sessionId = crypto.randomUUID();
266
268
 
267
- const systemPrompt = this.buildSystemPrompt(resolvedProjectPath, provider, profileId);
269
+ const systemPrompt = await this.buildSystemPrompt(resolvedProjectPath, provider, profileId);
268
270
  const agent = new Agent({
269
271
  providerId: provider,
270
272
  modelId,
@@ -396,6 +398,7 @@ export class ClineEngine implements AIEngine {
396
398
  const provider = parseClineCredential(account.credential)?.provider ?? providerSlug;
397
399
  const auth = await resolveClineAuth(account);
398
400
 
401
+ const { Agent } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
399
402
  const agent = new Agent({
400
403
  providerId: provider,
401
404
  modelId,
@@ -19,7 +19,8 @@
19
19
  * `backend/ws/chat/stream.ts` to it — same pattern as Claude/OpenCode.
20
20
  */
21
21
 
22
- import { Codex, type Thread, type ThreadOptions, type Input as CodexInput } from '@openai/codex-sdk';
22
+ import type { Codex, Thread, ThreadOptions, Input as CodexInput } from '@openai/codex-sdk';
23
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
23
24
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
24
25
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
25
26
  import { extractJson } from '../../structured-helpers';
@@ -119,6 +120,7 @@ export class CodexEngine implements AIEngine {
119
120
  // The SDK does NOT inherit process.env when `env` is provided, so we
120
121
  // pass the full clean spawn env and layer CODEX_HOME on top to redirect
121
122
  // the subprocess's auth.json + sessions into Clopen's isolated dir.
123
+ const { Codex } = await loadEngineSdk<typeof import('@openai/codex-sdk')>('codex', '@openai/codex-sdk');
122
124
  this.codex = new Codex({
123
125
  apiKey: credential.kind === 'api_key' ? credential.apiKey : undefined,
124
126
  ...(codexBinary ? { codexPathOverride: codexBinary } : {}),
@@ -6,8 +6,8 @@
6
6
  * isolated by the per-project engine registry in backend/engine/index.ts.
7
7
  */
8
8
 
9
- import { CopilotClient, approveAll } from '@github/copilot-sdk';
10
9
  import type {
10
+ CopilotClient,
11
11
  CopilotSession,
12
12
  SessionConfig,
13
13
  ResumeSessionConfig,
@@ -16,6 +16,7 @@ import type {
16
16
  PermissionRequest,
17
17
  PermissionRequestResult,
18
18
  } from '@github/copilot-sdk';
19
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
19
20
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
20
21
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
21
22
  import { buildJsonPrompt, extractJson } from '../../structured-helpers';
@@ -153,6 +154,8 @@ export class CopilotEngine implements AIEngine {
153
154
  throw new Error('Copilot is not configured. Add a Personal Access Token in Settings → Engines → Copilot.');
154
155
  }
155
156
 
157
+ const { CopilotClient } = await loadEngineSdk<typeof import('@github/copilot-sdk')>('copilot', '@github/copilot-sdk');
158
+
156
159
  this.client = new CopilotClient({
157
160
  gitHubToken: account.credential,
158
161
  useLoggedInUser: false,
@@ -298,6 +301,8 @@ export class CopilotEngine implements AIEngine {
298
301
  };
299
302
  this.activeController.signal.addEventListener('abort', onAbort, { once: true });
300
303
 
304
+ const { approveAll } = await loadEngineSdk<typeof import('@github/copilot-sdk')>('copilot', '@github/copilot-sdk');
305
+
301
306
  try {
302
307
  const mcpConfig = getCopilotMcpConfig(mcpProfileFilter);
303
308
 
@@ -622,6 +627,8 @@ export class CopilotEngine implements AIEngine {
622
627
  throw new Error('Copilot client unavailable.');
623
628
  }
624
629
 
630
+ const { approveAll } = await loadEngineSdk<typeof import('@github/copilot-sdk')>('copilot', '@github/copilot-sdk');
631
+
625
632
  const controller = abortController || new AbortController();
626
633
  const resolvedProjectPath = resolveOsPath(projectPath);
627
634
  const jsonPrompt = buildJsonPrompt(prompt, schema);
@@ -13,8 +13,9 @@
13
13
  */
14
14
 
15
15
  import { join } from 'node:path';
16
- import { JsonlLocalAgentStore } from '@cursor/sdk';
16
+ import type { JsonlLocalAgentStore } from '@cursor/sdk';
17
17
  import { getEngineUserConfigDir } from '$backend/utils/paths';
18
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
18
19
 
19
20
  /** Root dir holding every project's isolated Cursor agent store. */
20
21
  export function getCursorStoreRoot(): string {
@@ -27,6 +28,7 @@ function getCursorStoreDir(projectPath: string): string {
27
28
  }
28
29
 
29
30
  /** A per-project `JsonlLocalAgentStore` for a stream (create + resume + fork). */
30
- export function getCursorStore(projectPath: string): JsonlLocalAgentStore {
31
+ export async function getCursorStore(projectPath: string): Promise<JsonlLocalAgentStore> {
32
+ const { JsonlLocalAgentStore } = await loadEngineSdk<typeof import('@cursor/sdk')>('cursor', '@cursor/sdk');
31
33
  return new JsonlLocalAgentStore(getCursorStoreDir(projectPath));
32
34
  }
@@ -16,9 +16,9 @@
16
16
  * unavailable (empty or errored). Only a missing account/key returns `[]`.
17
17
  */
18
18
 
19
- import { Cursor } from '@cursor/sdk';
20
19
  import type { EngineModel } from '$shared/types/unified';
21
20
  import { debug } from '$shared/utils/logger';
21
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
22
22
  import { getActiveCursorAccount, parseCursorCredential } from './credential';
23
23
 
24
24
  /** Known Cursor model ids used when `Cursor.models.list()` is unavailable. */
@@ -31,6 +31,7 @@ export async function fetchCursorModels(): Promise<EngineModel[]> {
31
31
  if (!apiKey) return [];
32
32
 
33
33
  try {
34
+ const { Cursor } = await loadEngineSdk<typeof import('@cursor/sdk')>('cursor', '@cursor/sdk');
34
35
  const models = await Cursor.models.list({ apiKey });
35
36
  if (models.length) {
36
37
  debug.log('engine', `Cursor getAvailableModels: ${models.length} models`);
@@ -21,11 +21,11 @@
21
21
  * to Cursor's native `agents` config.
22
22
  */
23
23
 
24
- import { Agent, Cursor } from '@cursor/sdk';
25
24
  import type { SDKAgent, Run, SDKUserMessage, SDKImage, AgentDefinition, SDKCustomTool } from '@cursor/sdk';
26
25
  import type { EngineOutput, EngineModel, MessageEngine } from '$shared/types/unified';
27
26
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
28
27
  import { resolveOsPath } from '$backend/utils/paths';
28
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
29
29
  import { debug } from '$shared/utils/logger';
30
30
  import { engineQueries } from '$backend/database/queries/engine-queries';
31
31
  import { syncSkills } from '$backend/skills';
@@ -160,7 +160,8 @@ export class CursorEngine implements AIEngine {
160
160
  const mcpServers = getCursorMcpConfig(mcpProfileFilter);
161
161
  const agents = await this.buildAgents();
162
162
 
163
- const store = getCursorStore(projectPath);
163
+ const { Agent } = await loadEngineSdk<typeof import('@cursor/sdk')>('cursor', '@cursor/sdk');
164
+ const store = await getCursorStore(projectPath);
164
165
  const engineMeta: MessageEngine = {
165
166
  type: 'cursor',
166
167
  provider: 'cursor',
@@ -324,10 +325,11 @@ export class CursorEngine implements AIEngine {
324
325
  if (!account) throw new Error('Cursor is not configured.');
325
326
  const apiKey = resolveCursorApiKey(account);
326
327
 
328
+ const { Agent } = await loadEngineSdk<typeof import('@cursor/sdk')>('cursor', '@cursor/sdk');
327
329
  const agent = await Agent.create({
328
330
  apiKey,
329
331
  model: { id: modelId },
330
- local: { cwd: resolveOsPath(projectPath), store: getCursorStore(projectPath) },
332
+ local: { cwd: resolveOsPath(projectPath), store: await getCursorStore(projectPath) },
331
333
  });
332
334
  try {
333
335
  const run = await agent.send(buildJsonPrompt(prompt, schema));
@@ -13,8 +13,9 @@
13
13
  * `$backend`.
14
14
  */
15
15
 
16
- import { ModelRuntime } from '@earendil-works/pi-coding-agent';
16
+ import type { ModelRuntime } from '@earendil-works/pi-coding-agent';
17
17
  import type { CredentialStore } from '@earendil-works/pi-ai';
18
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
18
19
  import type { PiAuthMode, PiCredentialField, PiProviderPreset } from '$shared/types/unified';
19
20
  import { getPiModelsPath, getPiModelsStorePath } from './environment';
20
21
  import { debug } from '$shared/utils/logger';
@@ -62,6 +63,7 @@ export function getPiProviderFields(providerId: string): PiCredentialField[] {
62
63
  * `~/.pi/agent/auth.json` — the DB store is the sole credential source.
63
64
  */
64
65
  export async function createPiRuntime(credentials?: CredentialStore): Promise<ModelRuntime> {
66
+ const { ModelRuntime } = await loadEngineSdk<typeof import('@earendil-works/pi-coding-agent')>('pi', '@earendil-works/pi-coding-agent');
65
67
  return ModelRuntime.create({
66
68
  ...(credentials ? { credentials } : {}),
67
69
  modelsPath: getPiModelsPath(),
@@ -13,7 +13,8 @@
13
13
  */
14
14
 
15
15
  import { join } from 'node:path';
16
- import { SessionManager } from '@earendil-works/pi-coding-agent';
16
+ import type { SessionManager } from '@earendil-works/pi-coding-agent';
17
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
17
18
  import { getPiSessionsDir } from './environment';
18
19
  import { debug } from '$shared/utils/logger';
19
20
 
@@ -27,6 +28,7 @@ export function getPiSessionDir(projectPath: string): string {
27
28
  * session, fork from it (new id, source untouched); otherwise start fresh.
28
29
  */
29
30
  export async function resolvePiSessionManager(projectPath: string, resume?: string): Promise<SessionManager> {
31
+ const { SessionManager } = await loadEngineSdk<typeof import('@earendil-works/pi-coding-agent')>('pi', '@earendil-works/pi-coding-agent');
30
32
  const sessionDir = getPiSessionDir(projectPath);
31
33
  if (resume) {
32
34
  try {
@@ -19,15 +19,12 @@
19
19
  * answer path.
20
20
  */
21
21
 
22
- import {
23
- createAgentSession,
24
- DefaultResourceLoader,
25
- SessionManager,
26
- SettingsManager,
27
- type AgentSession,
28
- type ExtensionAPI,
29
- type ToolDefinition,
22
+ import type {
23
+ AgentSession,
24
+ ExtensionAPI,
25
+ ToolDefinition,
30
26
  } from '@earendil-works/pi-coding-agent';
27
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
31
28
  import type { AgentToolResult } from '@earendil-works/pi-agent-core';
32
29
  import type { ImageContent } from '@earendil-works/pi-ai';
33
30
  import type { EngineOutput, EngineModel, MessageEngine } from '$shared/types/unified';
@@ -121,6 +118,9 @@ export class PiEngine implements AIEngine {
121
118
  const { projectPath, prompt, resume, providerSlug, modelId, abortController, accountId } = options;
122
119
  debug.log('chat', 'Pi - Stream Query', { providerSlug, modelId, resume });
123
120
 
121
+ const { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager } =
122
+ await loadEngineSdk<typeof import('@earendil-works/pi-coding-agent')>('pi', '@earendil-works/pi-coding-agent');
123
+
124
124
  // ── Resolve account + credential + runtime + model ──
125
125
  // Pi is multi-provider: prefer the account matching the model's provider,
126
126
  // falling back to an explicit accountId override. (The chat picker selects
@@ -386,6 +386,9 @@ export class PiEngine implements AIEngine {
386
386
  async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
387
387
  const { prompt, providerSlug, modelId, schema, projectPath, accountId } = options;
388
388
 
389
+ const { createAgentSession, SessionManager, SettingsManager } =
390
+ await loadEngineSdk<typeof import('@earendil-works/pi-coding-agent')>('pi', '@earendil-works/pi-coding-agent');
391
+
389
392
  const account = getPiAccountForProvider(providerSlug)
390
393
  ?? (accountId != null ? engineQueries.getAccount(accountId) : null);
391
394
  if (!account) throw new Error(`Pi has no account for provider "${providerSlug}".`);
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Fresh-install default engine bootstrap.
3
+ *
4
+ * On a machine where NO engine SDK is installed yet, auto-install OpenCode —
5
+ * the one free, no-account engine — into the managed stack dir so first-time
6
+ * users have a working default without any manual setup (wizard or otherwise).
7
+ * Runs in the background at startup; failures are non-fatal (engines remain
8
+ * installable from Settings → Stack). Skipped as soon as ANY engine is present,
9
+ * so it never fights a user who intentionally removed OpenCode.
10
+ */
11
+
12
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+ import { debug } from '$shared/utils/logger';
15
+ import { getCleanSpawnEnv } from '$backend/utils/env';
16
+ import { isEngineSdkInstalled } from './sdk-loader';
17
+ import { resolveRecipe } from './install-recipes';
18
+
19
+ const ENGINE_SDK_PACKAGES = [
20
+ '@anthropic-ai/claude-agent-sdk',
21
+ '@github/copilot-sdk',
22
+ '@openai/codex-sdk',
23
+ '@qwen-code/sdk',
24
+ '@opencode-ai/sdk',
25
+ '@earendil-works/pi-coding-agent',
26
+ '@cline/sdk',
27
+ '@cursor/sdk',
28
+ ];
29
+
30
+ let bootstrapStarted = false;
31
+
32
+ /**
33
+ * Install OpenCode on a fresh machine (no engine SDK present). Idempotent and
34
+ * safe to call at every startup; it no-ops once any engine exists.
35
+ */
36
+ export async function ensureDefaultEngineInstalled(): Promise<void> {
37
+ if (bootstrapStarted) return;
38
+ bootstrapStarted = true;
39
+
40
+ if (ENGINE_SDK_PACKAGES.some(isEngineSdkInstalled)) return;
41
+
42
+ const recipe = await resolveRecipe('opencode');
43
+ if (!recipe.command || !recipe.cwd) return;
44
+
45
+ // Ensure the managed dir is a minimal bun project before `bun add` runs.
46
+ mkdirSync(recipe.cwd, { recursive: true });
47
+ const pkgJsonPath = join(recipe.cwd, 'package.json');
48
+ if (!existsSync(pkgJsonPath)) {
49
+ writeFileSync(
50
+ pkgJsonPath,
51
+ JSON.stringify({ name: 'clopen-stack-engines', private: true, version: '0.0.0' }, null, 2) + '\n'
52
+ );
53
+ }
54
+
55
+ debug.log('engine', `Auto-installing default engine (OpenCode): ${recipe.displayCommand}`);
56
+ try {
57
+ const proc = Bun.spawn(recipe.command, {
58
+ cwd: recipe.cwd,
59
+ env: getCleanSpawnEnv(),
60
+ stdout: 'ignore',
61
+ stderr: 'ignore',
62
+ stdin: 'ignore',
63
+ });
64
+ const code = await proc.exited;
65
+ debug.log('engine', `Default engine (OpenCode) auto-install exited with code ${code}`);
66
+ } catch (error) {
67
+ debug.warn('engine', 'Default engine auto-install failed (non-fatal)', error);
68
+ }
69
+ }
@@ -43,6 +43,18 @@ blueprint for the next engine you add.
43
43
  Refer to §2.6 for the full file taxonomy. Every adapter ships these five
44
44
  mandatory files; optional files use the canonical names from §2.6.
45
45
 
46
+ > **Lazy-load the SDK — never bundle it.** The engine's SDK package is NOT a
47
+ > runtime dependency; it lives in `package.json` `devDependencies` (pinned
48
+ > exact) and is installed on demand into `~/.clopen/stack/engines`. In the
49
+ > adapter, reference the SDK's types only via `import type` (erased at runtime)
50
+ > and resolve the real module at point of use with
51
+ > `loadEngineSdk<typeof import('<pkg>')>('newengine', '<pkg>')` from
52
+ > `backend/engine/sdk-loader.ts`. The loader throws `EngineNotReadyError`
53
+ > (`not-installed` / `needs-update`) when the SDK is absent or version-mismatched,
54
+ > and the stream-manager surfaces that message in the chat error surface —
55
+ > nudging the user to install/update the engine in Settings → Stack. Mirror
56
+ > `copilot/stream.ts` / `codex/stream.ts` for the pattern.
57
+
46
58
  - [ ] Create `backend/engine/adapters/newengine/`
47
59
  - [ ] `index.ts` (mandatory) → `export { NewEngineEngine } from './stream';`
48
60
  (+ `disposeXxxClient` if there is a subprocess).
@@ -160,17 +172,27 @@ mandatory files; optional files use the canonical names from §2.6.
160
172
  account edit form (in-place re-auth), gated on `newengineReauthAccountId`
161
173
  — mirror `ClaudeCodePanel`/`CodexPanel`/`PiPanel`.
162
174
 
163
- ### Stage 7 — Settings → System Tools
175
+ ### Stage 7 — Settings → Stack
176
+
177
+ Engine SDKs are installed **on demand** into the clopen-managed stack dir
178
+ (`~/.clopen/stack/engines`), not onto the machine's PATH — so you don't write a
179
+ per-platform recipe. You only declare the pinned package(s); `resolveEngineRecipe()`
180
+ handles the install. (The panel is displayed as "Stack"; its WS route/id stays
181
+ `system-tools`.)
164
182
 
183
+ - [ ] `package.json`: add the engine's SDK package(s) to `devDependencies` at an
184
+ **exact** pinned version — this is the single source of truth for the
185
+ version clopen installs on demand.
165
186
  - [ ] `backend/engine/install-recipes.ts`:
166
187
  - Add `'newengine'` to `ToolId`.
167
- - Write `resolveNewEngineRecipe()` (winget/brew/curl pipe — whatever the
168
- SDK needs to install its CLI).
169
- - Add a case in `resolveRecipe()`.
188
+ - Add its package(s) to `ENGINE_PACKAGES` (first entry = the SDK clopen
189
+ imports and detects install-state from; any extras pin a transitive CLI the
190
+ SDK would otherwise float, e.g. Copilot's `@github/copilot`).
191
+ - No resolver needed — `resolveEngineRecipe()` picks it up.
170
192
  - [ ] `backend/ws/system-tools/status.ts` & `install.ts`: add
171
193
  `'newengine'` to `TOOL_UNION`.
172
194
  - [ ] `frontend/components/settings/system-tools/SystemToolsSettings.svelte`:
173
- `<ToolInstallCard tool="newengine" title="NewEngine CLI" description="..." />`.
195
+ `<ToolInstallCard tool="newengine" title="NewEngine" description="..." />`.
174
196
 
175
197
  ### Stage 8 — Chat input
176
198
 
@@ -202,7 +224,8 @@ bun run check && bun run lint
202
224
 
203
225
  Then the minimum UI scenarios that must pass:
204
226
 
205
- - [ ] Settings → System Tools → Install NewEngine CLI → exit 0.
227
+ - [ ] Settings → Stack → Install NewEngine → exit 0 (SDK lands in
228
+ `~/.clopen/stack/engines`, status shows the pinned version).
206
229
  - [ ] Settings → Engines → NewEngine → Add Account → status `Installed,
207
230
  Active account: <name>`.
208
231
  - [ ] Chat input → pick NewEngine + model → send a message → assistant
@@ -63,17 +63,22 @@ modelStore // models[], fetchModels(engine), refreshModels(engin
63
63
  // getByEngine(engine), getById(modelId)
64
64
  ```
65
65
 
66
- ### 5.2 Settings → System Tools
66
+ ### 5.2 Settings → Stack
67
+
68
+ The panel is displayed as **Stack** (its internal section id / WS route stays
69
+ `system-tools`).
67
70
 
68
71
  Files:
69
72
  - `frontend/components/settings/system-tools/SystemToolsSettings.svelte`
70
73
  - `frontend/components/settings/system-tools/ToolInstallCard.svelte`
71
74
 
72
- `SystemToolsSettings` renders one `ToolInstallCard` per tool (`git`,
73
- `claude`, `opencode`, `chrome`, `cloudflared`). `ToolInstallCard`:
75
+ `SystemToolsSettings` renders one `ToolInstallCard` per tool — host tools
76
+ (`git`, `chrome`, `cloudflared`) plus every engine SDK (`claude`, `opencode`,
77
+ `copilot`, `codex`, `qwen`, `pi`, `cline`, `cursor`). `ToolInstallCard`:
74
78
 
75
79
  1. Calls `system-tools:status` on mount.
76
- 2. Renders: status (installed/version/source), an "Install" button if
80
+ 2. Renders: status (installed/version/source; engines also carry
81
+ `requiredVersion` + `needsUpdate`), an "Install" button if
77
82
  `recipe.autoInstallable`, otherwise a "Manual install" dialog.
78
83
  3. While installing: `system-tools:install-start` → subscribe to
79
84
  `system-tools:install-stream` (per-line) → render in xterm + show
@@ -81,7 +86,15 @@ Files:
81
86
  4. The session survives navigation: if `activeSession` exists on refresh,
82
87
  re-attach to the same session id.
83
88
 
84
- To add a new tool (e.g. `goose`):
89
+ Engine cards differ from host-tool cards:
90
+ - The SDK installs on demand into `~/.clopen/stack/engines` (managed dir), not
91
+ the machine's PATH; there is no manual command to run.
92
+ - The **"Check for Updates"** button is hidden — engine versions are pinned in
93
+ `package.json` and move in lockstep with clopen, so there is no upstream to
94
+ check. When the installed version ≠ the pinned version, the card shows
95
+ **"Update required"** and an `Update → <version>` button instead.
96
+
97
+ To add a new **host** tool (e.g. `goose`):
85
98
  1. Add the literal to `ToolId` (`backend/engine/install-recipes.ts`).
86
99
  2. Add `resolveGooseRecipe()` + a case in `resolveRecipe()`.
87
100
  3. Add the literal to `TOOL_UNION` (`backend/ws/system-tools/status.ts`
@@ -91,6 +104,9 @@ To add a new tool (e.g. `goose`):
91
104
  5. (Optional) expose detection in the `engine:<name>-status` handler so
92
105
  Settings → Engines can show an "Installed" badge.
93
106
 
107
+ For a new **engine SDK**, you declare the pinned package instead of a resolver —
108
+ see [system-tools](./system-tools.md) §7.7.
109
+
94
110
  ---
95
111
 
96
112
  ## 6. Chat integration — model picker & stream
@@ -1065,3 +1065,44 @@ and socket errors to clear user messages in `error-handler.ts`.
1065
1065
  > `ContextIndicator.svelte` handles an unknown max context. When an engine's data
1066
1066
  > exposes a UI bug, fix it in the shared component, not the adapter.
1067
1067
 
1068
+ ---
1069
+
1070
+ ### 10.21 The SDK is not bundled — lazy-load it and never top-level-import it
1071
+
1072
+ Engine SDKs are **not** runtime dependencies. They live in `package.json`
1073
+ `devDependencies` (pinned exact — the single source of truth) and are installed
1074
+ **on demand** into the clopen-managed dir `~/.clopen/stack/engines`
1075
+ (`getStackEnginesDir()`), never the user's global bun store or their project.
1076
+ This is what fixed `bun add -g @myrialabs/clopen` aborting on Windows: bundling
1077
+ the SDKs dragged 200–300 MB of native CLI binaries into the global install, and
1078
+ one failed tarball extraction killed the whole thing.
1079
+
1080
+ Consequences for an adapter:
1081
+
1082
+ - **Reference SDK types only via `import type`.** A plain `import { Foo } from
1083
+ '<pkg>'` forces Bun to resolve the package at module-load time — which throws
1084
+ for every user who hasn't installed that engine yet, crashing the backend on
1085
+ boot. `import type` is erased at runtime, so it's safe. Resolve the real module
1086
+ at point of use with
1087
+ `loadEngineSdk<typeof import('<pkg>')>('newengine', '<pkg>')` from
1088
+ `backend/engine/sdk-loader.ts` (which does `Bun.resolveSync(pkg, stackDir)` +
1089
+ dynamic import, cached).
1090
+
1091
+ - **Loading is version-guarded.** `loadEngineSdk` refuses an SDK whose installed
1092
+ version ≠ the pinned version, throwing `EngineNotReadyError`
1093
+ (`reason: 'not-installed' | 'needs-update'`). The stream-manager surfaces that
1094
+ message in the chat error surface, telling the user to install/update the
1095
+ engine in Settings → Stack. Don't catch-and-swallow it — the readable message
1096
+ is the UX.
1097
+
1098
+ - **Detection reads the stack dir, not PATH.** `readEngineSdkVersion(pkg)` (used
1099
+ by both `getToolStatus` in the Stack panel and every engine picker
1100
+ `status.ts`) checks the SDK's version inside `~/.clopen/stack/engines` — there
1101
+ is no CLI-on-PATH probe for engines anymore. `ToolStatus` also carries
1102
+ `requiredVersion` + `needsUpdate` so the UI can show "Update required".
1103
+
1104
+ The same lazy-load applies to the one non-adapter consumer of the Claude SDK:
1105
+ `backend/mcp/index.ts::getEnabledMcpServers()` is `async` and lazy-loads
1106
+ `@anthropic-ai/claude-agent-sdk` only on the Claude path (see
1107
+ `backend/mcp/README.md`).
1108
+