@myrialabs/clopen 0.4.15 → 0.4.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/backend/artifacts/matrix.ts +8 -0
  2. package/backend/artifacts/types.ts +2 -2
  3. package/backend/auth/permissions.ts +14 -0
  4. package/backend/chat/stream-manager.ts +5 -5
  5. package/backend/commands/detect.ts +1 -1
  6. package/backend/commands/sync.ts +1 -1
  7. package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
  8. package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
  9. package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
  10. package/backend/database/migrations/index.ts +21 -0
  11. package/backend/engine/README.md +36 -13
  12. package/backend/engine/adapters/cline/agent-tool.ts +64 -0
  13. package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
  14. package/backend/engine/adapters/cline/credential.ts +166 -0
  15. package/backend/engine/adapters/cline/error-handler.ts +49 -0
  16. package/backend/engine/adapters/cline/index.ts +1 -0
  17. package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
  18. package/backend/engine/adapters/cline/message-converter.ts +396 -0
  19. package/backend/engine/adapters/cline/models.ts +73 -0
  20. package/backend/engine/adapters/cline/presets.ts +128 -0
  21. package/backend/engine/adapters/cline/stream.ts +413 -0
  22. package/backend/engine/adapters/codex/credential.ts +1 -1
  23. package/backend/engine/adapters/codex/message-converter.ts +4 -4
  24. package/backend/engine/adapters/codex/session-fork.ts +1 -1
  25. package/backend/engine/adapters/codex/stream.ts +3 -3
  26. package/backend/engine/adapters/copilot/stream.ts +1 -1
  27. package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
  28. package/backend/engine/adapters/cursor/credential.ts +68 -0
  29. package/backend/engine/adapters/cursor/environment.ts +32 -0
  30. package/backend/engine/adapters/cursor/error-handler.ts +60 -0
  31. package/backend/engine/adapters/cursor/index.ts +1 -0
  32. package/backend/engine/adapters/cursor/message-converter.ts +615 -0
  33. package/backend/engine/adapters/cursor/models.ts +68 -0
  34. package/backend/engine/adapters/cursor/session-fork.ts +68 -0
  35. package/backend/engine/adapters/cursor/stream.ts +341 -0
  36. package/backend/engine/adapters/pi/agent-tool.ts +62 -0
  37. package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
  38. package/backend/engine/adapters/pi/credential.ts +137 -0
  39. package/backend/engine/adapters/pi/environment.ts +33 -0
  40. package/backend/engine/adapters/pi/error-handler.ts +46 -0
  41. package/backend/engine/adapters/pi/index.ts +1 -0
  42. package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
  43. package/backend/engine/adapters/pi/message-converter.ts +446 -0
  44. package/backend/engine/adapters/pi/models.ts +53 -0
  45. package/backend/engine/adapters/pi/presets.ts +133 -0
  46. package/backend/engine/adapters/pi/session-fork.ts +46 -0
  47. package/backend/engine/adapters/pi/stream.ts +427 -0
  48. package/backend/engine/adapters/qwen/message-converter.ts +5 -5
  49. package/backend/engine/adapters/qwen/stream.ts +2 -2
  50. package/backend/engine/docs/adapter-contract.md +7 -2
  51. package/backend/engine/docs/adding-an-engine.md +70 -12
  52. package/backend/engine/docs/artifacts.md +124 -0
  53. package/backend/engine/docs/database.md +4 -4
  54. package/backend/engine/docs/frontend-and-chat.md +22 -4
  55. package/backend/engine/docs/lessons-learned.md +219 -32
  56. package/backend/engine/docs/quick-reference.md +18 -7
  57. package/backend/engine/docs/websocket-routes.md +2 -2
  58. package/backend/engine/index.ts +9 -0
  59. package/backend/mcp/README.md +3 -3
  60. package/backend/mcp/external/config.ts +11 -0
  61. package/backend/mcp/index.ts +8 -0
  62. package/backend/mcp/internal/config.ts +33 -1
  63. package/backend/permissions/service.ts +5 -2
  64. package/backend/skills/sync.ts +1 -1
  65. package/backend/subagents/detect.ts +1 -1
  66. package/backend/subagents/sync.ts +1 -1
  67. package/backend/ws/chat/stream.ts +1 -1
  68. package/backend/ws/engine/cline/accounts.ts +317 -0
  69. package/backend/ws/engine/cline/index.ts +15 -0
  70. package/backend/ws/engine/cline/presets.ts +36 -0
  71. package/backend/ws/engine/cline/status.ts +49 -0
  72. package/backend/ws/engine/codex/accounts.ts +1 -1
  73. package/backend/ws/engine/cursor/accounts.ts +162 -0
  74. package/backend/ws/engine/cursor/index.ts +13 -0
  75. package/backend/ws/engine/cursor/status.ts +55 -0
  76. package/backend/ws/engine/index.ts +6 -0
  77. package/backend/ws/engine/pi/accounts.ts +319 -0
  78. package/backend/ws/engine/pi/index.ts +15 -0
  79. package/backend/ws/engine/pi/presets.ts +34 -0
  80. package/backend/ws/engine/pi/status.ts +50 -0
  81. package/backend/ws/sessions/crud.ts +2 -2
  82. package/backend/ws/settings/crud.ts +2 -2
  83. package/dist/assets/{index-EunAFLxP.js → index-BPvctwJ2.js} +1 -1
  84. package/dist/assets/{index-ChF_jIXj.js → index-vLKZpWQH.js} +1 -1
  85. package/dist/assets/{main-CTs4NXwP.js → main-BtBZvCwv.js} +359 -357
  86. package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
  87. package/dist/index.html +2 -2
  88. package/package.json +7 -1
  89. package/shared/constants/engine-tools.ts +16 -2
  90. package/shared/constants/engines.ts +27 -0
  91. package/shared/types/unified/common.ts +1 -1
  92. package/shared/types/unified/engine.ts +82 -1
  93. package/shared/types/unified/index.ts +6 -0
  94. package/shared/types/unified/message.ts +1 -1
@@ -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
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Cline credential storage.
3
+ *
4
+ * Cline (`@cline/sdk`) is genuinely multi-provider and supports both API-key and
5
+ * OAuth (the Cline account signs in through WorkOS OAuth). Rather than let the
6
+ * SDK write its own `~/.cline` provider settings, Clopen OWNS the credential and
7
+ * feeds it to the stateless `Agent` per stream: an API key (or the OAuth access
8
+ * token, formatted via `formatProviderOAuthApiKey`) is passed as
9
+ * `AgentRuntimeConfigWithProvider.apiKey`.
10
+ *
11
+ * `engine_accounts.credential` for a Cline account stores a JSON wrapper:
12
+ *
13
+ * { "provider": "anthropic", "authMethod": "api_key", "apiKey": "sk-…", "baseUrl": "…", "fields": { … } }
14
+ * { "provider": "cline", "authMethod": "oauth", "oauth": { "access": …, "refresh": …, "expires": … } }
15
+ *
16
+ * Because OAuth access tokens rotate, `resolveClineAuth()` refreshes an expired
17
+ * token via the SDK's provider auth handler and persists the refreshed blob
18
+ * straight back into the account row — no dotfile swap, no `process.env`
19
+ * mutation (mirrors Pi's DB-backed credential contract).
20
+ */
21
+
22
+ import { getProviderAuthHandler, formatProviderOAuthApiKey } from '@cline/sdk';
23
+ import type { OAuthCredentials, ProviderSettings } from '@cline/sdk';
24
+ import { engineQueries, type EngineAccount } from '$backend/database/queries/engine-queries';
25
+ import { debug } from '$shared/utils/logger';
26
+
27
+ export type ClineAuthMethod = 'api_key' | 'oauth';
28
+
29
+ export interface ClineCredential {
30
+ /** Cline SDK provider id (e.g. 'anthropic', 'openai', 'cline'). */
31
+ provider: string;
32
+ authMethod: ClineAuthMethod;
33
+ /** API key (api_key mode). */
34
+ apiKey?: string;
35
+ /** Custom base URL (OpenAI-compatible / self-hosted). */
36
+ baseUrl?: string;
37
+ /** Extra provider-scoped fields (awsRegion, gcpProjectId, …). */
38
+ fields?: Record<string, string>;
39
+ /** OAuth token blob (oauth mode). */
40
+ oauth?: OAuthCredentials;
41
+ }
42
+
43
+ /** The single `engine_providers` row that owns every Cline account (Pi/Qwen-style). */
44
+ export function getClineProvider() {
45
+ return engineQueries.getProviderBySlug('cline', 'cline');
46
+ }
47
+
48
+ /** Every stored Cline account (each tagged with its own Cline provider id). */
49
+ export function getClineAccounts(): EngineAccount[] {
50
+ const provider = getClineProvider();
51
+ return provider ? engineQueries.getAccountsByProvider(provider.id) : [];
52
+ }
53
+
54
+ /** The account backing a given Cline provider id, preferring the active one. */
55
+ export function getClineAccountForProvider(providerId: string): EngineAccount | null {
56
+ const accounts = getClineAccounts().filter(a => parseClineCredential(a.credential)?.provider === providerId);
57
+ if (accounts.length === 0) return null;
58
+ return accounts.find(a => a.is_active === 1) ?? accounts[accounts.length - 1];
59
+ }
60
+
61
+ /** Parse a stored `engine_accounts.credential` blob. Returns null if unusable. */
62
+ export function parseClineCredential(stored: string | null | undefined): ClineCredential | null {
63
+ if (!stored) return null;
64
+ const trimmed = stored.trim();
65
+ if (!trimmed.startsWith('{')) return null;
66
+ try {
67
+ const parsed = JSON.parse(trimmed) as Partial<ClineCredential>;
68
+ if (!parsed || typeof parsed.provider !== 'string' || !parsed.provider) return null;
69
+ const authMethod = parsed.authMethod === 'oauth' ? 'oauth' : 'api_key';
70
+ if (authMethod === 'api_key' && !parsed.apiKey) return null;
71
+ if (authMethod === 'oauth' && !parsed.oauth?.access) return null;
72
+ return {
73
+ provider: parsed.provider,
74
+ authMethod,
75
+ ...(parsed.apiKey ? { apiKey: parsed.apiKey } : {}),
76
+ ...(parsed.baseUrl ? { baseUrl: parsed.baseUrl } : {}),
77
+ ...(parsed.fields && typeof parsed.fields === 'object' ? { fields: parsed.fields } : {}),
78
+ ...(parsed.oauth ? { oauth: parsed.oauth } : {}),
79
+ };
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ export function serializeClineCredential(cred: ClineCredential): string {
86
+ return JSON.stringify(cred);
87
+ }
88
+
89
+ /** Non-secret display metadata for one account (auth method + provider). */
90
+ export function describeClineCredential(
91
+ stored: string | null | undefined,
92
+ ): { provider: string; authMethod: ClineAuthMethod } | null {
93
+ const parsed = parseClineCredential(stored);
94
+ if (!parsed) return null;
95
+ return { provider: parsed.provider, authMethod: parsed.authMethod };
96
+ }
97
+
98
+ export interface ResolvedClineAuth {
99
+ provider: string;
100
+ apiKey?: string;
101
+ baseUrl?: string;
102
+ /** Gateway options for provider-scoped fields (awsRegion, gcpProjectId, …). */
103
+ options?: Record<string, unknown>;
104
+ }
105
+
106
+ /** Refresh window: refresh an OAuth token that expires within the next minute. */
107
+ const OAUTH_REFRESH_BUFFER_MS = 60_000;
108
+
109
+ /**
110
+ * Resolve the auth an `Agent` needs for one account. For OAuth accounts this
111
+ * refreshes a near-expired access token (persisting the rotated blob back to the
112
+ * DB) and formats it into the api-key the provider handler expects.
113
+ */
114
+ export async function resolveClineAuth(account: EngineAccount): Promise<ResolvedClineAuth> {
115
+ const parsed = parseClineCredential(account.credential);
116
+ if (!parsed) throw new Error('Cline account has no usable credential.');
117
+
118
+ if (parsed.authMethod === 'api_key') {
119
+ return {
120
+ provider: parsed.provider,
121
+ ...(parsed.apiKey ? { apiKey: parsed.apiKey } : {}),
122
+ ...(parsed.baseUrl ? { baseUrl: parsed.baseUrl } : {}),
123
+ ...(parsed.fields && Object.keys(parsed.fields).length ? { options: { ...parsed.fields } } : {}),
124
+ };
125
+ }
126
+
127
+ // OAuth: refresh if near-expiry, then format the access token as an api key.
128
+ let creds = parsed.oauth as OAuthCredentials;
129
+ const handler = getProviderAuthHandler(parsed.provider);
130
+ const nearExpiry = typeof creds.expires === 'number' && creds.expires <= Date.now() + OAUTH_REFRESH_BUFFER_MS;
131
+ if (handler && creds.refresh && nearExpiry) {
132
+ try {
133
+ const settings = {
134
+ auth: {
135
+ accessToken: creds.access,
136
+ refreshToken: creds.refresh,
137
+ expiresAt: creds.expires,
138
+ ...(creds.accountId ? { accountId: creds.accountId } : {}),
139
+ },
140
+ } as ProviderSettings;
141
+ const refreshed = await handler.refresh({ settings, credentials: creds });
142
+ if (refreshed?.access) {
143
+ creds = refreshed;
144
+ engineQueries.updateAccountCredential(
145
+ account.id,
146
+ serializeClineCredential({ ...parsed, oauth: refreshed }),
147
+ );
148
+ debug.log('engine', `Cline: refreshed OAuth token for provider "${parsed.provider}" (account ${account.id})`);
149
+ }
150
+ } catch (error) {
151
+ debug.warn('engine', `Cline OAuth refresh failed for "${parsed.provider}" (using stored token): ${error instanceof Error ? error.message : String(error)}`);
152
+ }
153
+ }
154
+
155
+ let apiKey: string;
156
+ try {
157
+ apiKey = formatProviderOAuthApiKey(parsed.provider, { access: creds.access });
158
+ } catch {
159
+ apiKey = creds.access;
160
+ }
161
+ return {
162
+ provider: parsed.provider,
163
+ apiKey,
164
+ ...(parsed.baseUrl ? { baseUrl: parsed.baseUrl } : {}),
165
+ };
166
+ }