@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
package/README.md CHANGED
@@ -26,7 +26,7 @@
26
26
  <img src="https://clopen.myrialabs.dev/images/workspace.webp" alt="Clopen workspace overview" />
27
27
  </p>
28
28
 
29
- All-in-one workspace for AI coding agents — Claude Code, OpenCode, Codex, Copilot, and Qwen Code. Chat, terminal, git, browser preview, database client, and real-time collaboration — plus Skills, Subagents, Commands, and MCP connectors to extend every engine.
29
+ All-in-one workspace for AI coding agents — Claude Code, OpenCode, Codex, Copilot, Qwen Code, Pi, Cline, and Cursor. Chat, terminal, git, browser preview, database client, and real-time collaboration — plus Skills, Subagents, Commands, and MCP connectors to extend every engine.
30
30
 
31
31
  ---
32
32
 
@@ -56,7 +56,7 @@ All-in-one workspace for AI coding agents — Claude Code, OpenCode, Codex, Copi
56
56
 
57
57
  A complete development environment designed around AI-assisted workflows, built to disappear into the background and just work.
58
58
 
59
- - **Multi-Engine Support** — Switch between Claude Code, OpenCode, Codex, GitHub Copilot, and Qwen Code as your AI engine, per session
59
+ - **Multi-Engine Support** — Switch between Claude Code, OpenCode, Codex, GitHub Copilot, Qwen Code, Pi, Cline, and Cursor as your AI engine, per session
60
60
  - **Multi-Account Per Engine** — Manage multiple accounts per engine (personal, work, or team) and switch between them instantly per chat session
61
61
  - **Integrated Terminal** — Multi-tab xterm.js terminal with full keyboard control and complete ANSI/VT support, right inside your workspace
62
62
  - **Full Git Management** — Stage, commit, branch, push, pull, stash, log, and resolve conflicts, all from a clean UI
@@ -80,7 +80,7 @@ A complete development environment designed around AI-assisted workflows, built
80
80
  ### Prerequisites
81
81
 
82
82
  - [Bun.js](https://bun.sh/) v1.2.12+
83
- - At least one supported AI engine — [Claude Code](https://github.com/anthropics/claude-code), [OpenCode](https://opencode.ai), [Codex](https://github.com/openai/codex), [GitHub Copilot CLI](https://github.com/github/copilot-cli), or [Qwen Code](https://github.com/QwenLM/qwen-code). All are installable from **Settings → System Tools** after first launch
83
+ - At least one supported AI engine — [Claude Code](https://github.com/anthropics/claude-code), [OpenCode](https://opencode.ai), [Codex](https://github.com/openai/codex), [GitHub Copilot CLI](https://github.com/github/copilot-cli), or [Qwen Code](https://github.com/QwenLM/qwen-code). All are installable from **Settings → System Tools** after first launch. [Pi](https://github.com/earendil-works/pi), [Cline](https://github.com/cline/cline), and [Cursor](https://cursor.com) are bundled as in-process SDKs and need no separate CLI install — just sign in from **Settings → Engines**
84
84
 
85
85
  ### Installation
86
86
 
@@ -117,7 +117,7 @@ On first launch, a setup wizard guides you through:
117
117
  1. **Authentication mode** — Choose between **No Login** (no authentication required, ideal for personal/local use) or **With Login** (login with Personal Access Token, supports team collaboration)
118
118
  2. **Admin account** — If With Login mode is selected, create your admin account and save the generated PAT
119
119
  3. **System Tools** — Install Git, Chrome, Cloudflared, and any AI engine you don't have yet — straight from the wizard, no terminal needed
120
- 4. **AI Engines** — Check installation status for Claude Code, OpenCode, Codex, Copilot, and Qwen Code, and sign in to the engines you'll use
120
+ 4. **AI Engines** — Check installation status for Claude Code, OpenCode, Codex, Copilot, and Qwen Code, and sign in to the engines you'll use. Pi, Cline, and Cursor need no install and are ready to sign in to directly
121
121
  5. **Preferences** — Set dark mode, font size, sound notifications, and message layout (Classic cards or Compact lines)
122
122
 
123
123
  You can change the authentication mode anytime in **Settings → Security → Authentication**.
@@ -164,7 +164,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines and [DECISIONS.md](DECISIO
164
164
  | Styling | Tailwind CSS v4 |
165
165
  | Database | SQLite with migrations |
166
166
  | Terminal | bun-pty |
167
- | AI Engines | Claude Code, OpenCode, Codex, Copilot, Qwen Code |
167
+ | AI Engines | Claude Code, OpenCode, Codex, Copilot, Qwen Code, Pi, Cline, Cursor |
168
168
  | DB Client | Postgres, MySQL, SQLite, MongoDB, Redis (+ SSH tunnel) |
169
169
 
170
170
  ---
@@ -202,6 +202,9 @@ MIT License - see [LICENSE](LICENSE) for details.
202
202
  - [Codex](https://github.com/openai/codex) by OpenAI
203
203
  - [GitHub Copilot CLI](https://github.com/github/copilot-cli) by GitHub
204
204
  - [Qwen Code](https://github.com/QwenLM/qwen-code) by Alibaba Qwen
205
+ - [Pi](https://github.com/earendil-works/pi) by Earendil Works
206
+ - [Cline](https://github.com/cline/cline) by Cline Bot Inc.
207
+ - [Cursor](https://cursor.com) by Anysphere
205
208
  - [Bun](https://bun.sh/) runtime
206
209
  - [Svelte](https://svelte.dev/) framework
207
210
 
@@ -74,6 +74,9 @@ function nativeDir(type: ArtifactType, ctx: ArtifactContext): string | null {
74
74
  case 'claude': return scope === 'global' ? join(base, 'skills') : proj ? join(proj, '.claude', 'skills') : null;
75
75
  case 'qwen': return scope === 'global' ? join(homedir(), '.qwen', 'skills') : null;
76
76
  case 'copilot': return scope === 'global' ? join(homedir(), '.copilot', 'skills') : null;
77
+ // Pi discovers skills from `<agentDir>/skills` (global) and `.pi/skills`
78
+ // (project) via DefaultResourceLoader — https://pi.dev/docs/latest/skills.
79
+ case 'pi': return scope === 'global' ? join(base, 'skills') : proj ? join(proj, '.pi', 'skills') : null;
77
80
  default: return null;
78
81
  }
79
82
  }
@@ -82,6 +85,9 @@ function nativeDir(type: ArtifactType, ctx: ArtifactContext): string | null {
82
85
  case 'claude': return scope === 'global' ? join(base, 'commands') : proj ? join(proj, '.claude', 'commands') : null;
83
86
  case 'opencode': return scope === 'global' ? join(base, 'opencode', 'command') : proj ? join(proj, '.opencode', 'command') : null;
84
87
  case 'codex': return scope === 'global' ? join(base, 'prompts') : null;
88
+ // Pi's file-based prompt templates live in `<agentDir>/prompts` (global)
89
+ // and `.pi/prompts` (project) — https://pi.dev/docs/latest/prompt-templates.
90
+ case 'pi': return scope === 'global' ? join(base, 'prompts') : proj ? join(proj, '.pi', 'prompts') : null;
85
91
  default: return null;
86
92
  }
87
93
  }
@@ -102,11 +108,13 @@ function realGlobalLocations(type: ArtifactType, engine: ArtifactEngine): string
102
108
  if (engine === 'claude') return [join(home, '.claude', 'skills')];
103
109
  if (engine === 'qwen') return [join(home, '.qwen', 'skills')];
104
110
  if (engine === 'copilot') return [join(home, '.copilot', 'skills')];
111
+ if (engine === 'pi') return [join(home, '.pi', 'agent', 'skills')];
105
112
  }
106
113
  if (type === 'command') {
107
114
  if (engine === 'claude') return [join(home, '.claude', 'commands')];
108
115
  if (engine === 'opencode') return [join(home, '.config', 'opencode', 'command')];
109
116
  if (engine === 'codex') return [join(home, '.codex', 'prompts')];
117
+ if (engine === 'pi') return [join(home, '.pi', 'agent', 'prompts')];
110
118
  }
111
119
  if (type === 'subagent') {
112
120
  if (engine === 'claude') return [join(home, '.claude', 'agents')];
@@ -33,9 +33,9 @@
33
33
  * `'claude'`, not the `EngineType` `'claude-code'`) so they line up with
34
34
  * {@link getEngineUserConfigDir} and the original Skills sync.
35
35
  */
36
- export type ArtifactEngine = 'claude' | 'codex' | 'copilot' | 'qwen' | 'opencode';
36
+ export type ArtifactEngine = 'claude' | 'codex' | 'copilot' | 'qwen' | 'opencode' | 'pi' | 'cline' | 'cursor';
37
37
 
38
- export const ARTIFACT_ENGINES: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode'];
38
+ export const ARTIFACT_ENGINES: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode', 'pi', 'cline', 'cursor'];
39
39
 
40
40
  /**
41
41
  * Kinds of artifact the framework can materialize. `'mcp'` is reserved (see file
@@ -71,6 +71,20 @@ export const ADMIN_ONLY_ROUTES = new Set([
71
71
  'engine:qwen-accounts-switch',
72
72
  'engine:qwen-accounts-delete',
73
73
  'engine:qwen-accounts-rename',
74
+ 'engine:pi-accounts-save',
75
+ 'engine:pi-accounts-switch',
76
+ 'engine:pi-accounts-delete',
77
+ 'engine:pi-accounts-rename',
78
+ 'engine:pi-account-login-start',
79
+ 'engine:pi-account-login-submit',
80
+ 'engine:pi-account-login-cancel',
81
+ 'engine:cline-accounts-save',
82
+ 'engine:cline-accounts-switch',
83
+ 'engine:cline-accounts-delete',
84
+ 'engine:cline-accounts-rename',
85
+ 'engine:cline-account-login-start',
86
+ 'engine:cline-account-login-submit',
87
+ 'engine:cline-account-login-cancel',
74
88
  'engine:opencode-provider-add',
75
89
  'engine:opencode-provider-remove',
76
90
  'engine:opencode-provider-toggle',
@@ -811,11 +811,11 @@ class StreamManager extends EventEmitter {
811
811
  });
812
812
  }
813
813
  }
814
- // Codex emits usage only once per turn (after all items
815
- // streamed live), so saved assistant rows have usage:null.
816
- // Backfill the turn's aggregate to every saved assistant
817
- // without usage so it survives a refresh.
818
- if (successResult.usage && streamState.engine === 'codex') {
814
+ // Codex and Cursor emit usage only once per turn (after all
815
+ // items streamed live), so saved assistant rows have
816
+ // usage:null. Backfill the turn's aggregate to every saved
817
+ // assistant without usage so it survives a refresh.
818
+ if (successResult.usage && (streamState.engine === 'codex' || streamState.engine === 'cursor')) {
819
819
  this.backfillUsageForStream(streamState, successResult.usage, requestSender);
820
820
  }
821
821
  } else {
@@ -13,7 +13,7 @@ export interface DetectedCommandGroup {
13
13
 
14
14
  /** Detect commands across all engines for the given scope. */
15
15
  export async function detectCommands(projectPath?: string): Promise<DetectedCommandGroup[]> {
16
- const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode'];
16
+ const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode', 'pi'];
17
17
  const scope = projectPath ? 'project' : 'global';
18
18
  const groups = await Promise.all(
19
19
  engines.map(async engine => ({
@@ -89,6 +89,6 @@ export async function syncCommands(engine: ArtifactEngine, profileId?: number):
89
89
  }
90
90
 
91
91
  export async function syncCommandsAllEngines(): Promise<void> {
92
- const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode'];
92
+ const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode', 'pi'];
93
93
  await Promise.all(engines.map(syncCommands));
94
94
  }
@@ -0,0 +1,25 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Seed the Pi engine provider (multi-provider via pi-coding-agent)';
5
+
6
+ /**
7
+ * Pi is Qwen-style: a single `engine_providers` row owns every Pi account. Each
8
+ * account's `credential` blob carries the pi-ai provider id + credential (see
9
+ * `backend/engine/adapters/pi/credential.ts`), so one row backs Anthropic,
10
+ * OpenAI, Google, … accounts side by side.
11
+ */
12
+ export const up = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Seeding Pi provider...');
14
+ db.exec(`
15
+ INSERT OR IGNORE INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled)
16
+ VALUES ('pi', 'pi', 'Pi', '@earendil-works/pi-coding-agent', NULL, '{}', 1)
17
+ `);
18
+ debug.log('migration', 'Pi provider seeded');
19
+ };
20
+
21
+ export const down = (db: DatabaseConnection): void => {
22
+ debug.log('migration', 'Removing Pi provider...');
23
+ db.exec(`DELETE FROM engine_providers WHERE engine_type = 'pi' AND slug = 'pi'`);
24
+ debug.log('migration', 'Pi provider removed');
25
+ };
@@ -0,0 +1,25 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Seed the Cline engine provider (multi-provider via @cline/sdk)';
5
+
6
+ /**
7
+ * Cline is Pi/Qwen-style: a single `engine_providers` row owns every Cline
8
+ * account. Each account's `credential` blob carries the Cline provider id + auth
9
+ * method + secret (see `backend/engine/adapters/cline/credential.ts`), so one row
10
+ * backs Anthropic, OpenAI, Google, the Cline account, … side by side.
11
+ */
12
+ export const up = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Seeding Cline provider...');
14
+ db.exec(`
15
+ INSERT OR IGNORE INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled)
16
+ VALUES ('cline', 'cline', 'Cline', '@cline/sdk', NULL, '{}', 1)
17
+ `);
18
+ debug.log('migration', 'Cline provider seeded');
19
+ };
20
+
21
+ export const down = (db: DatabaseConnection): void => {
22
+ debug.log('migration', 'Removing Cline provider...');
23
+ db.exec(`DELETE FROM engine_providers WHERE engine_type = 'cline' AND slug = 'cline'`);
24
+ debug.log('migration', 'Cline provider removed');
25
+ };
@@ -0,0 +1,25 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Seed the Cursor engine provider (@cursor/sdk, single API-key account)';
5
+
6
+ /**
7
+ * Cursor is single-provider: one `engine_providers` row owns every Cursor
8
+ * account. Each account's `credential` blob carries just the Cursor API key
9
+ * (see `backend/engine/adapters/cursor/credential.ts`) — there is no per-provider
10
+ * fan-out like Cline/Qwen.
11
+ */
12
+ export const up = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Seeding Cursor provider...');
14
+ db.exec(`
15
+ INSERT OR IGNORE INTO engine_providers (engine_type, slug, name, npm, api_url, options, is_enabled)
16
+ VALUES ('cursor', 'cursor', 'Cursor', '@cursor/sdk', NULL, '{}', 1)
17
+ `);
18
+ debug.log('migration', 'Cursor provider seeded');
19
+ };
20
+
21
+ export const down = (db: DatabaseConnection): void => {
22
+ debug.log('migration', 'Removing Cursor provider...');
23
+ db.exec(`DELETE FROM engine_providers WHERE engine_type = 'cursor' AND slug = 'cursor'`);
24
+ debug.log('migration', 'Cursor provider removed');
25
+ };
@@ -55,6 +55,9 @@ import * as migration053 from './053_add_profile_to_permission_sets';
55
55
  import * as migration054 from './054_drop_subagent_agent_type';
56
56
  import * as migration055 from './055_artifact_model_tools_per_engine';
57
57
  import * as migration056 from './056_support_mssql_driver';
58
+ import * as migration057 from './057_seed_pi_provider';
59
+ import * as migration058 from './058_seed_cline_provider';
60
+ import * as migration059 from './059_seed_cursor_provider';
58
61
 
59
62
  // Export all migrations in order
60
63
  export const migrations = [
@@ -393,6 +396,24 @@ export const migrations = [
393
396
  description: migration056.description,
394
397
  up: migration056.up,
395
398
  down: migration056.down
399
+ },
400
+ {
401
+ id: '057',
402
+ description: migration057.description,
403
+ up: migration057.up,
404
+ down: migration057.down
405
+ },
406
+ {
407
+ id: '058',
408
+ description: migration058.description,
409
+ up: migration058.up,
410
+ down: migration058.down
411
+ },
412
+ {
413
+ id: '059',
414
+ description: migration059.description,
415
+ up: migration059.up,
416
+ down: migration059.down
396
417
  }
397
418
  ];
398
419
 
@@ -1,12 +1,34 @@
1
1
  # `backend/engine/` — End-to-End Adapter Guide
2
2
 
3
3
  This folder is the **boundary** between Clopen and the AI SDKs that drive
4
- streaming chat. Today there are three adapters: **`claude`**
5
- (`@anthropic-ai/claude-agent-sdk`), **`opencode`** (`@opencode-ai/sdk`), and
6
- **`copilot`** (`@github/copilot-sdk`). Every adapter follows the same shape so
7
- that the rest of the system outside this folder — `stream-manager`, MCP, DB,
8
- WebSocket, frontend chat, settings UI — stays **agnostic** to the underlying
9
- SDK.
4
+ streaming chat. The adapters today: **`claude`**
5
+ (`@anthropic-ai/claude-agent-sdk`), **`opencode`** (`@opencode-ai/sdk`),
6
+ **`copilot`** (`@github/copilot-sdk`), **`codex`** (`@openai/codex-sdk`),
7
+ **`qwen`** (`@qwen-code/qwen-code`), **`pi`**
8
+ (`@earendil-works/pi-coding-agent`), **`cline`** (`@cline/sdk`), and
9
+ **`cursor`** (`@cursor/sdk`). Every
10
+ adapter follows the same shape so that the rest of the system outside this
11
+ folder — `stream-manager`, MCP, DB, WebSocket, frontend chat, settings UI —
12
+ stays **agnostic** to the underlying SDK.
13
+
14
+ > **In-process, session-less SDKs are their own category.** Most adapters
15
+ > wrap a CLI subprocess or an SDK that owns a session store (on disk or via a
16
+ > server). `cline` is different: `@cline/sdk`'s stateless `Agent` holds **no**
17
+ > session store at all, so the adapter reconstructs branch history in memory
18
+ > and synthesizes the sub-agent (`Agent`) tool itself. Both were bug sources
19
+ > during bring-up — read **§10.10** (checkpoint forks) and **§10.15**
20
+ > (sub-agents) in [lessons-learned](./docs/lessons-learned.md) before adding a
21
+ > similar engine.
22
+
23
+ > **Delta-stream SDKs are another category.** `cursor` (`@cursor/sdk`) is
24
+ > in-process with an on-disk store like `pi`, but its `run.stream()` emits each
25
+ > text/thinking CHUNK as its own message (deltas, not snapshots), routes MCP +
26
+ > custom tools through a single wrapper tool, streams sub-agents only via
27
+ > `onDelta`, and reports no context-window metadata. If a new SDK is delta-based,
28
+ > tool-wrapping, or metadata-poor, read **§10.20** in
29
+ > [lessons-learned](./docs/lessons-learned.md) before writing the converter — and
30
+ > capture the SDK's real runtime shapes with a throwaway script rather than
31
+ > trusting its `.d.ts`.
10
32
 
11
33
  This guide is split into focused documents — start here for the architecture
12
34
  map, then jump to the area you need.
@@ -19,9 +41,10 @@ map, then jump to the area you need.
19
41
  4. [WebSocket routes](./docs/websocket-routes.md) — `engine:*`, `system-tools:*`, `models:list`, `chat:stream`, and the Restart-Server pattern.
20
42
  5. [Frontend & chat integration](./docs/frontend-and-chat.md) — Settings → Engines / System Tools, the model picker, the send path, reasoning/attachments/AskUserQuestion.
21
43
  6. [System Tools](./docs/system-tools.md) — registering a binary in `install-recipes.ts` + the install runner.
22
- 7. [Adding a new engine](./docs/adding-an-engine.md) — the end-to-end, stage-by-stage checklist.
23
- 8. [Lessons learned](./docs/lessons-learned.md) — §9 pitfalls (tool name/input canonicalisation, fork session, MCP reuse, auth-blob swap, sub-agent routing, OpenCode v1/v2, structured output, …).
24
- 9. [Quick reference](./docs/quick-reference.md) — "I need X → look in file Y" table.
44
+ 7. [Artifacts & Access](./docs/artifacts.md) — the extension layer (Skills, Commands, Subagents, Instructions, Permissions, Profiles, MCP), the capability matrix, and the `artifact-sync.ts` seam adapters call at stream start.
45
+ 8. [Adding a new engine](./docs/adding-an-engine.md) — the end-to-end, stage-by-stage checklist.
46
+ 9. [Lessons learned](./docs/lessons-learned.md) — §10 pitfalls (tool name/input canonicalisation, fork session, MCP reuse, auth-blob swap, sub-agent routing, OpenCode v1/v2, structured output, …).
47
+ 10. [Quick reference](./docs/quick-reference.md) — "I need X → look in file Y" table.
25
48
 
26
49
  ---
27
50
 
@@ -32,7 +55,7 @@ map, then jump to the area you need.
32
55
  │ │
33
56
  │ Settings → Engines Settings → System Tools Chat Input │
34
57
  │ ───────────────────── ────────────────────── ────────────── │
35
- │ AIEnginesSettings.svelte SystemToolsSettings… EngineModel… │
58
+ │ AIEnginesSettings+panels/ SystemToolsSettings… EngineModel… │
36
59
  │ │ │ │ │
37
60
  │ ├─ claudeAccountsStore └─ ws.http( ├─ model │
38
61
  │ ├─ copilotAccountsStore 'system-tools:…') │ Store │
@@ -104,19 +127,19 @@ Three key rules that **every** layer upholds:
104
127
  > `streamable-http` MCP URL (Codex, future engines) reuses **the same
105
128
  > URL** by adding a sibling `getXxxMcpConfig()` helper in
106
129
  > `backend/mcp/internal/config.ts`. Do **NOT** propose a "new MCP bridge",
107
- > "per-engine MCP server", or "per-stream MCP path". See §9.12.
130
+ > "per-engine MCP server", or "per-stream MCP path". See §10.12.
108
131
  > 2. **Engine home dirs are isolated per-engine (Clopen vs. global), but
109
132
  > multi-account stays DB-swap.** Two different axes — don't conflate them:
110
133
  > - **Clopen vs. the user's global CLI usage:** every engine's home/config
111
134
  > is redirected to `{clopenDir}/engine/{engine}/user/` via that engine's env
112
135
  > var (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME` via
113
136
  > `baseDirectory`, `QWEN_RUNTIME_DIR`, `XDG_*` for OpenCode) so Clopen
114
- > never touches `~/.codex`, `~/.copilot`, … See §9.19.
137
+ > never touches `~/.codex`, `~/.copilot`, … See §10.19.
115
138
  > - **Multiple accounts *within* Clopen:** still the auth-blob swap — one
116
139
  > shared dotfile inside that isolated home, snapshotted to/from the DB on
117
140
  > login/switch. Do **NOT** propose **per-account** home dirs
118
141
  > (`CODEX_HOME=/foo/account-1/`); that splits session-state, breaks
119
- > fork-by-copy, and loses token-refresh persistence. See §9.13.
142
+ > fork-by-copy, and loses token-refresh persistence. See §10.13.
120
143
 
121
144
  ---
122
145
 
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Subagent dispatch tool for Cline.
3
+ *
4
+ * Cline's stateless `Agent` has no native Agent/Task primitive, so the synthetic
5
+ * "Available Subagents" preamble (injected into the system prompt) is
6
+ * informational only — the model can describe subagents but can't invoke them.
7
+ * This custom `Agent` tool closes that gap: calling it spawns a fresh sub-`Agent`
8
+ * with the subagent's system prompt, runs the delegated prompt to completion, and
9
+ * returns the final text as the tool result. Sub-activity does not stream to the
10
+ * main UI (it runs inside the tool), but the delegation actually happens.
11
+ */
12
+
13
+ import { createTool } from '@cline/sdk';
14
+ import type { AgentTool, AgentToolContext } from '@cline/sdk';
15
+
16
+ export interface SubagentInfo {
17
+ slug: string;
18
+ name: string;
19
+ description: string;
20
+ }
21
+
22
+ export interface AgentDispatchBindings {
23
+ /** Enabled subagents advertised to the model. */
24
+ subagents: SubagentInfo[];
25
+ /**
26
+ * Run one subagent against a prompt; resolve with its final text output.
27
+ * `toolCallId` is the parent Agent tool_use id — the runner tags the
28
+ * subagent's messages with it so they render as sub-activities.
29
+ */
30
+ run: (subagent: SubagentInfo, prompt: string, toolCallId: string, signal?: AbortSignal) => Promise<string>;
31
+ }
32
+
33
+ const AGENT_INPUT_SCHEMA = {
34
+ type: 'object',
35
+ properties: {
36
+ subagentType: { type: 'string', description: 'The slug of the subagent to delegate to.' },
37
+ prompt: { type: 'string', description: 'The self-contained task for the subagent.' },
38
+ description: { type: 'string', description: 'A short (3-5 word) description of the delegated task.' },
39
+ },
40
+ required: ['subagentType', 'prompt', 'description'],
41
+ } as const;
42
+
43
+ export function createAgentDispatchTool(bindings: AgentDispatchBindings): AgentTool {
44
+ const catalog = bindings.subagents.map(s => `- ${s.slug}: ${s.name} — ${s.description}`).join('\n');
45
+ return createTool({
46
+ name: 'Agent',
47
+ description:
48
+ 'Delegate a self-contained subtask to a specialized subagent. Pass the subagent slug as `subagentType` and the task as `prompt`. Available subagents:\n' + catalog,
49
+ inputSchema: AGENT_INPUT_SCHEMA,
50
+ async execute(input: { subagentType?: string; prompt?: string }, context: AgentToolContext) {
51
+ const match = bindings.subagents.find(s => s.slug === input.subagentType || s.name === input.subagentType);
52
+ if (!match) {
53
+ const names = bindings.subagents.map(s => s.slug).join(', ') || '(none configured)';
54
+ return `No subagent named "${input.subagentType}". Available: ${names}`;
55
+ }
56
+ try {
57
+ const text = await bindings.run(match, input.prompt ?? '', context.toolCallId ?? '', context.signal);
58
+ return text.trim() || '(subagent produced no output)';
59
+ } catch (error) {
60
+ return `Subagent "${match.slug}" failed: ${error instanceof Error ? error.message : String(error)}`;
61
+ }
62
+ },
63
+ }) as AgentTool;
64
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * AskUserQuestion custom tool for Cline.
3
+ *
4
+ * Cline's built-in `ask_question` drives its own UI and has no headless answer
5
+ * path, so we disable it (`enableAskQuestion: false`) and register our own
6
+ * canonical `AskUserQuestion` tool that BLOCKS until the user answers through the
7
+ * chat UI — the same contract Claude's `canUseTool` provides, modelled as a
8
+ * blocking tool because the stateless `Agent` loop resolves a tool call by its
9
+ * returned promise.
10
+ *
11
+ * The tool's `execute` returns a promise the engine resolves via
12
+ * `resolveUserAnswer(toolCallId, answers)`. The converter renders the tool_use
13
+ * block (name `AskUserQuestion`) so the frontend shows the dialog; the resolved
14
+ * tool result carries the formatted answers.
15
+ */
16
+
17
+ import { createTool } from '@cline/sdk';
18
+ import type { AgentTool, AgentToolContext } from '@cline/sdk';
19
+ import type { AskUserQuestion } from '$shared/types/unified';
20
+
21
+ export interface PendingAsk {
22
+ questions: AskUserQuestion[];
23
+ resolve: (text: string) => void;
24
+ }
25
+
26
+ export interface AskToolBindings {
27
+ register: (toolCallId: string, entry: PendingAsk) => void;
28
+ unregister: (toolCallId: string) => void;
29
+ }
30
+
31
+ /** Format the user's answers in the shared OpenCode/Qwen/Pi wording. */
32
+ export function formatAnswers(questions: AskUserQuestion[], answers: Record<string, string>): string {
33
+ const pairs: string[] = [];
34
+ for (const [key, value] of Object.entries(answers)) {
35
+ const idx = Number.parseInt(key, 10);
36
+ const q = Number.isFinite(idx) ? questions[idx] : undefined;
37
+ const label = q?.question ?? q?.header ?? key;
38
+ pairs.push(`"${label}"="${value}"`);
39
+ }
40
+ if (pairs.length === 0) return 'User did not provide any answers.';
41
+ return `User has answered your questions: ${pairs.join(', ')}. You can now continue with the user's answers in mind.`;
42
+ }
43
+
44
+ const ASK_INPUT_SCHEMA = {
45
+ type: 'object',
46
+ properties: {
47
+ questions: {
48
+ type: 'array',
49
+ description: 'One or more multiple-choice questions to ask the user.',
50
+ items: {
51
+ type: 'object',
52
+ properties: {
53
+ question: { type: 'string', description: 'The full question text.' },
54
+ header: { type: 'string', description: 'A short (max 12 char) label for the question.' },
55
+ multiSelect: { type: 'boolean', description: 'Whether multiple options may be selected.' },
56
+ options: {
57
+ type: 'array',
58
+ items: {
59
+ type: 'object',
60
+ properties: {
61
+ label: { type: 'string' },
62
+ description: { type: 'string' },
63
+ },
64
+ required: ['label', 'description'],
65
+ },
66
+ },
67
+ },
68
+ required: ['question', 'header', 'options'],
69
+ },
70
+ },
71
+ },
72
+ required: ['questions'],
73
+ } as const;
74
+
75
+ export function createAskUserQuestionTool(bindings: AskToolBindings): AgentTool {
76
+ return createTool({
77
+ name: 'AskUserQuestion',
78
+ description:
79
+ 'Ask the user one or more multiple-choice questions when you need a decision only they can make. Blocks until the user answers in the UI.',
80
+ inputSchema: ASK_INPUT_SCHEMA,
81
+ async execute(input: { questions?: AskUserQuestion[] }, context: AgentToolContext) {
82
+ const questions = (input?.questions ?? []) as AskUserQuestion[];
83
+ const toolCallId = context.toolCallId ?? '';
84
+ const signal = context.signal;
85
+ return new Promise<string>((resolve) => {
86
+ if (!toolCallId || signal?.aborted) {
87
+ resolve('User did not answer the question.');
88
+ return;
89
+ }
90
+ const onAbort = () => {
91
+ bindings.unregister(toolCallId);
92
+ resolve('User did not answer the question.');
93
+ };
94
+ signal?.addEventListener('abort', onAbort, { once: true });
95
+ bindings.register(toolCallId, {
96
+ questions,
97
+ resolve: (text) => {
98
+ signal?.removeEventListener('abort', onAbort);
99
+ resolve(text);
100
+ },
101
+ });
102
+ });
103
+ },
104
+ }) as AgentTool;
105
+ }