@myrialabs/clopen 0.4.15 → 0.4.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +8 -5
  2. package/backend/artifacts/matrix.ts +8 -0
  3. package/backend/artifacts/types.ts +2 -2
  4. package/backend/auth/permissions.ts +14 -0
  5. package/backend/chat/stream-manager.ts +5 -5
  6. package/backend/commands/detect.ts +1 -1
  7. package/backend/commands/sync.ts +1 -1
  8. package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
  9. package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
  10. package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
  11. package/backend/database/migrations/index.ts +21 -0
  12. package/backend/engine/README.md +36 -13
  13. package/backend/engine/adapters/cline/agent-tool.ts +64 -0
  14. package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
  15. package/backend/engine/adapters/cline/credential.ts +166 -0
  16. package/backend/engine/adapters/cline/error-handler.ts +49 -0
  17. package/backend/engine/adapters/cline/index.ts +1 -0
  18. package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
  19. package/backend/engine/adapters/cline/message-converter.ts +396 -0
  20. package/backend/engine/adapters/cline/models.ts +73 -0
  21. package/backend/engine/adapters/cline/presets.ts +128 -0
  22. package/backend/engine/adapters/cline/stream.ts +413 -0
  23. package/backend/engine/adapters/codex/credential.ts +1 -1
  24. package/backend/engine/adapters/codex/message-converter.ts +4 -4
  25. package/backend/engine/adapters/codex/session-fork.ts +1 -1
  26. package/backend/engine/adapters/codex/stream.ts +3 -3
  27. package/backend/engine/adapters/copilot/stream.ts +1 -1
  28. package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
  29. package/backend/engine/adapters/cursor/credential.ts +68 -0
  30. package/backend/engine/adapters/cursor/environment.ts +32 -0
  31. package/backend/engine/adapters/cursor/error-handler.ts +60 -0
  32. package/backend/engine/adapters/cursor/index.ts +1 -0
  33. package/backend/engine/adapters/cursor/message-converter.ts +615 -0
  34. package/backend/engine/adapters/cursor/models.ts +68 -0
  35. package/backend/engine/adapters/cursor/session-fork.ts +68 -0
  36. package/backend/engine/adapters/cursor/stream.ts +341 -0
  37. package/backend/engine/adapters/pi/agent-tool.ts +62 -0
  38. package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
  39. package/backend/engine/adapters/pi/credential.ts +137 -0
  40. package/backend/engine/adapters/pi/environment.ts +33 -0
  41. package/backend/engine/adapters/pi/error-handler.ts +46 -0
  42. package/backend/engine/adapters/pi/index.ts +1 -0
  43. package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
  44. package/backend/engine/adapters/pi/message-converter.ts +446 -0
  45. package/backend/engine/adapters/pi/models.ts +53 -0
  46. package/backend/engine/adapters/pi/presets.ts +133 -0
  47. package/backend/engine/adapters/pi/session-fork.ts +46 -0
  48. package/backend/engine/adapters/pi/stream.ts +427 -0
  49. package/backend/engine/adapters/qwen/message-converter.ts +5 -5
  50. package/backend/engine/adapters/qwen/stream.ts +2 -2
  51. package/backend/engine/docs/adapter-contract.md +7 -2
  52. package/backend/engine/docs/adding-an-engine.md +70 -12
  53. package/backend/engine/docs/artifacts.md +124 -0
  54. package/backend/engine/docs/database.md +4 -4
  55. package/backend/engine/docs/frontend-and-chat.md +22 -4
  56. package/backend/engine/docs/lessons-learned.md +219 -32
  57. package/backend/engine/docs/quick-reference.md +18 -7
  58. package/backend/engine/docs/websocket-routes.md +2 -2
  59. package/backend/engine/index.ts +9 -0
  60. package/backend/mcp/README.md +3 -3
  61. package/backend/mcp/external/config.ts +11 -0
  62. package/backend/mcp/index.ts +8 -0
  63. package/backend/mcp/internal/config.ts +33 -1
  64. package/backend/permissions/service.ts +5 -2
  65. package/backend/skills/sync.ts +1 -1
  66. package/backend/subagents/detect.ts +1 -1
  67. package/backend/subagents/sync.ts +1 -1
  68. package/backend/ws/chat/stream.ts +1 -1
  69. package/backend/ws/engine/cline/accounts.ts +317 -0
  70. package/backend/ws/engine/cline/index.ts +15 -0
  71. package/backend/ws/engine/cline/presets.ts +36 -0
  72. package/backend/ws/engine/cline/status.ts +49 -0
  73. package/backend/ws/engine/codex/accounts.ts +1 -1
  74. package/backend/ws/engine/cursor/accounts.ts +162 -0
  75. package/backend/ws/engine/cursor/index.ts +13 -0
  76. package/backend/ws/engine/cursor/status.ts +55 -0
  77. package/backend/ws/engine/index.ts +6 -0
  78. package/backend/ws/engine/pi/accounts.ts +319 -0
  79. package/backend/ws/engine/pi/index.ts +15 -0
  80. package/backend/ws/engine/pi/presets.ts +34 -0
  81. package/backend/ws/engine/pi/status.ts +50 -0
  82. package/backend/ws/sessions/crud.ts +2 -2
  83. package/backend/ws/settings/crud.ts +2 -2
  84. package/dist/assets/{index-EunAFLxP.js → index-Bu5loFQE.js} +1 -1
  85. package/dist/assets/{index-ChF_jIXj.js → index-kME3THy5.js} +1 -1
  86. package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
  87. package/dist/assets/{main-CTs4NXwP.js → main-HirJLquI.js} +361 -359
  88. package/dist/index.html +2 -2
  89. package/package.json +11 -2
  90. package/shared/constants/engine-tools.ts +16 -2
  91. package/shared/constants/engines.ts +27 -0
  92. package/shared/types/unified/common.ts +1 -1
  93. package/shared/types/unified/engine.ts +82 -1
  94. package/shared/types/unified/index.ts +6 -0
  95. package/shared/types/unified/message.ts +1 -1
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Cursor Account Management Handlers
3
+ *
4
+ * Auth model: API-key only. The user pastes a Cursor API key (user key from the
5
+ * dashboard, or a team service-account key); no PTY / device flow. The key is
6
+ * validated with `Cursor.me({ apiKey })` before it is stored as a JSON credential
7
+ * (`{ "apiKey": "…" }`) on engine_accounts under provider slug 'cursor'.
8
+ *
9
+ * Switching/deleting the active account disposes the project-scoped CursorEngine
10
+ * instances so the next stream picks up the new credential.
11
+ */
12
+
13
+ import { t } from 'elysia';
14
+ import { Cursor } from '@cursor/sdk';
15
+ import { createRouter } from '$shared/utils/ws-server';
16
+ import { engineQueries } from '../../../database/queries';
17
+ import { disposeAllProjectEnginesByType } from '../../../engine';
18
+ import { serializeCursorCredential } from '../../../engine/adapters/cursor/credential';
19
+ import { debug } from '$shared/utils/logger';
20
+
21
+ async function disposeCursorEngines(): Promise<void> {
22
+ try {
23
+ await disposeAllProjectEnginesByType('cursor');
24
+ } catch {
25
+ /* engine may not be initialised — ignore */
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Validate an API key by resolving the authenticated user. Only a genuine
31
+ * authentication failure (401 / `AuthenticationError`) means the key is bad —
32
+ * `Cursor.me()` also 403s with `plan_required` for free-tier keys (which are
33
+ * perfectly valid), and transient network errors shouldn't block saving a
34
+ * working key. So we reject ONLY on an auth error and accept everything else.
35
+ */
36
+ async function validateApiKey(apiKey: string): Promise<void> {
37
+ try {
38
+ await Cursor.me({ apiKey });
39
+ } catch (error) {
40
+ const status = (error as { status?: number })?.status;
41
+ const name = (error as Error)?.name;
42
+ if (name === 'AuthenticationError' || status === 401) {
43
+ throw new Error('Invalid Cursor API key. Check the key from cursor.com/dashboard and try again.');
44
+ }
45
+ debug.warn('engine', `Cursor key validation non-fatal (${name ?? 'error'} ${status ?? ''}) — accepting key`);
46
+ }
47
+ }
48
+
49
+ export const cursorAccountsHandler = createRouter()
50
+
51
+ .http('engine:cursor-accounts-list', {
52
+ data: t.Object({}),
53
+ response: t.Object({
54
+ accounts: t.Array(t.Object({
55
+ id: t.Number(),
56
+ name: t.String(),
57
+ isActive: t.Boolean(),
58
+ createdAt: t.String()
59
+ }))
60
+ })
61
+ }, async () => {
62
+ const provider = engineQueries.getProviderBySlug('cursor', 'cursor');
63
+ if (!provider) return { accounts: [] };
64
+ const accounts = engineQueries.getAccountsByProvider(provider.id);
65
+ return {
66
+ accounts: accounts.map(a => ({
67
+ id: a.id,
68
+ name: a.name,
69
+ isActive: a.is_active === 1,
70
+ createdAt: a.created_at
71
+ }))
72
+ };
73
+ })
74
+
75
+ .http('engine:cursor-accounts-add', {
76
+ data: t.Object({
77
+ name: t.String({ minLength: 1 }),
78
+ apiKey: t.String({ minLength: 1 })
79
+ }),
80
+ response: t.Object({
81
+ account: t.Object({
82
+ id: t.Number(),
83
+ name: t.String(),
84
+ isActive: t.Boolean(),
85
+ createdAt: t.String()
86
+ })
87
+ })
88
+ }, async ({ data }) => {
89
+ const provider = engineQueries.getProviderBySlug('cursor', 'cursor');
90
+ if (!provider) {
91
+ throw new Error('Cursor provider not found in database');
92
+ }
93
+
94
+ const apiKey = data.apiKey.trim();
95
+ await validateApiKey(apiKey);
96
+
97
+ const account = engineQueries.createAccount(provider.id, data.name.trim(), serializeCursorCredential({ apiKey }));
98
+
99
+ if (account.is_active === 1) {
100
+ await disposeCursorEngines();
101
+ }
102
+
103
+ return {
104
+ account: {
105
+ id: account.id,
106
+ name: account.name,
107
+ isActive: account.is_active === 1,
108
+ createdAt: account.created_at
109
+ }
110
+ };
111
+ })
112
+
113
+ .http('engine:cursor-accounts-switch', {
114
+ data: t.Object({ id: t.Number() }),
115
+ response: t.Object({ success: t.Boolean() })
116
+ }, async ({ data }) => {
117
+ engineQueries.switchAccount(data.id);
118
+ await disposeCursorEngines();
119
+ return { success: true };
120
+ })
121
+
122
+ .http('engine:cursor-accounts-delete', {
123
+ data: t.Object({ id: t.Number() }),
124
+ response: t.Object({ success: t.Boolean() })
125
+ }, async ({ data }) => {
126
+ const active = engineQueries.getActiveAccountForEngine('cursor');
127
+ engineQueries.deleteAccount(data.id);
128
+ if (active?.id === data.id) await disposeCursorEngines();
129
+ return { success: true };
130
+ })
131
+
132
+ .http('engine:cursor-accounts-rename', {
133
+ data: t.Object({ id: t.Number(), name: t.String({ minLength: 1 }) }),
134
+ response: t.Object({ success: t.Boolean() })
135
+ }, async ({ data }) => {
136
+ engineQueries.renameAccount(data.id, data.name.trim());
137
+ return { success: true };
138
+ })
139
+
140
+ // Replace the stored API key for an account. When the edited account is the
141
+ // active one, drop engine instances so the next stream picks up the key.
142
+ .http('engine:cursor-accounts-update-key', {
143
+ data: t.Object({ id: t.Number(), apiKey: t.String({ minLength: 1 }) }),
144
+ response: t.Object({ success: t.Boolean() })
145
+ }, async ({ data }) => {
146
+ const apiKey = data.apiKey.trim();
147
+ await validateApiKey(apiKey);
148
+ engineQueries.updateAccountCredential(data.id, serializeCursorCredential({ apiKey }));
149
+ const active = engineQueries.getActiveAccountForEngine('cursor');
150
+ if (active?.id === data.id) await disposeCursorEngines();
151
+ return { success: true };
152
+ })
153
+
154
+ // Restart all Cursor engine instances so subsequent models:list / chat calls
155
+ // re-initialise with fresh credentials.
156
+ .http('engine:cursor-restart', {
157
+ data: t.Object({}),
158
+ response: t.Object({ success: t.Boolean() })
159
+ }, async () => {
160
+ await disposeCursorEngines();
161
+ return { success: true };
162
+ });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Cursor Engine Router
3
+ *
4
+ * Combines status detection and account management handlers.
5
+ */
6
+
7
+ import { createRouter } from '$shared/utils/ws-server';
8
+ import { cursorStatusHandler } from './status';
9
+ import { cursorAccountsHandler } from './accounts';
10
+
11
+ export const cursorEngineRouter = createRouter()
12
+ .merge(cursorStatusHandler)
13
+ .merge(cursorAccountsHandler);
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Cursor Engine Status Handler
3
+ *
4
+ * Reports SDK availability and active account state. `@cursor/sdk` is bundled
5
+ * with Clopen and runs its local agent in-process, so there is nothing to
6
+ * install — `installed` is always true.
7
+ */
8
+
9
+ import { t } from 'elysia';
10
+ import { createRouter } from '$shared/utils/ws-server';
11
+ import { engineQueries } from '../../../database/queries';
12
+ import { debug } from '$shared/utils/logger';
13
+ import { getBackendOS } from '../../../utils/os';
14
+
15
+ function readSdkVersion(): string | null {
16
+ try {
17
+ const path = require.resolve('@cursor/sdk/package.json');
18
+ const pkg = require(path) as { version?: string };
19
+ return pkg.version ?? null;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ export const cursorStatusHandler = createRouter()
26
+ .http('engine:cursor-status', {
27
+ data: t.Object({}),
28
+ response: t.Object({
29
+ installed: t.Boolean(),
30
+ version: t.Union([t.String(), t.Null()]),
31
+ activeAccount: t.Union([
32
+ t.Object({
33
+ id: t.Number(),
34
+ name: t.String()
35
+ }),
36
+ t.Null()
37
+ ]),
38
+ accountsCount: t.Number(),
39
+ backendOS: t.Union([t.Literal('windows'), t.Literal('macos'), t.Literal('linux')])
40
+ })
41
+ }, async () => {
42
+ debug.log('engine', 'Checking Cursor status...');
43
+
44
+ const provider = engineQueries.getProviderBySlug('cursor', 'cursor');
45
+ const accounts = provider ? engineQueries.getAccountsByProvider(provider.id) : [];
46
+ const activeAccount = engineQueries.getActiveAccountForEngine('cursor');
47
+
48
+ return {
49
+ installed: true,
50
+ version: readSdkVersion(),
51
+ activeAccount: activeAccount ? { id: activeAccount.id, name: activeAccount.name } : null,
52
+ accountsCount: accounts.length,
53
+ backendOS: getBackendOS()
54
+ };
55
+ });
@@ -11,6 +11,9 @@ import { openCodeEngineRouter } from './opencode';
11
11
  import { copilotEngineRouter } from './copilot';
12
12
  import { codexEngineRouter } from './codex';
13
13
  import { qwenEngineRouter } from './qwen';
14
+ import { piEngineRouter } from './pi';
15
+ import { clineEngineRouter } from './cline';
16
+ import { cursorEngineRouter } from './cursor';
14
17
  import { engineRestartRouter } from './restart';
15
18
 
16
19
  export const engineRouter = createRouter()
@@ -19,4 +22,7 @@ export const engineRouter = createRouter()
19
22
  .merge(copilotEngineRouter)
20
23
  .merge(codexEngineRouter)
21
24
  .merge(qwenEngineRouter)
25
+ .merge(piEngineRouter)
26
+ .merge(clineEngineRouter)
27
+ .merge(cursorEngineRouter)
22
28
  .merge(engineRestartRouter);
@@ -0,0 +1,319 @@
1
+ /**
2
+ * Pi Account Management Handlers
3
+ *
4
+ * Pi is multi-provider (Anthropic, OpenAI, Google, …). BOTH API-key and OAuth
5
+ * auth go through the SAME event-driven flow, `ModelRuntime.login(provider,
6
+ * type, interaction)` — the provider owns its prompts, so it can ask for exactly
7
+ * what it needs (e.g. Cloudflare wants an account ID + key, not just a key). The
8
+ * interaction's `notify`/`prompt` callbacks are relayed to the client over WS;
9
+ * the client answers prompts via `engine:pi-account-login-submit`. Passing
10
+ * `reauthAccountId` re-authenticates an existing account in place.
11
+ *
12
+ * Every account's `engine_accounts.credential` stores a JSON wrapper
13
+ * `{ provider, credential }` (see `backend/engine/adapters/pi/credential.ts`).
14
+ */
15
+
16
+ import { t } from 'elysia';
17
+ import { createRouter } from '$shared/utils/ws-server';
18
+ import { ws } from '$backend/utils/ws';
19
+ import type { AuthEvent, AuthInteraction, AuthPrompt, AuthType, Credential } from '@earendil-works/pi-ai';
20
+ import { engineQueries } from '../../../database/queries';
21
+ import { disposeAllProjectEnginesByType } from '../../../engine';
22
+ import { createPiRuntime, getPiProviderFields } from '../../../engine/adapters/pi/presets';
23
+ import { DbCredentialStore, serializePiCredential, parsePiCredential, getPiProvider } from '../../../engine/adapters/pi/credential';
24
+ import { requireSetupSessionAccess } from '../access';
25
+ import { debug } from '$shared/utils/logger';
26
+
27
+ async function disposePiEngines(): Promise<void> {
28
+ try {
29
+ await disposeAllProjectEnginesByType('pi');
30
+ } catch {
31
+ /* engine may not be initialised — ignore */
32
+ }
33
+ }
34
+
35
+ // ── Interactive login sessions ──
36
+
37
+ interface PiLoginSession {
38
+ userId: string;
39
+ disposed: boolean;
40
+ controller: AbortController;
41
+ name: string;
42
+ provider: string;
43
+ /** When set, re-authenticate this existing account in place instead of creating one. */
44
+ reauthAccountId: number | null;
45
+ pendingPrompt: { resolve: (value: string) => void; reject: (error: Error) => void } | null;
46
+ timer: ReturnType<typeof setTimeout>;
47
+ }
48
+
49
+ const loginSessions = new Map<string, PiLoginSession>();
50
+ const LOGIN_TIMEOUT_MS = 15 * 60 * 1000;
51
+
52
+ function cleanupLogin(loginId: string): void {
53
+ const entry = loginSessions.get(loginId);
54
+ if (!entry || entry.disposed) return;
55
+ entry.disposed = true;
56
+ clearTimeout(entry.timer);
57
+ entry.pendingPrompt?.reject(new Error('Login session closed'));
58
+ entry.pendingPrompt = null;
59
+ if (!entry.controller.signal.aborted) entry.controller.abort();
60
+ loginSessions.delete(loginId);
61
+ }
62
+
63
+ export const piAccountsHandler = createRouter()
64
+
65
+ // ═══ CRUD ═══
66
+
67
+ .http('engine:pi-accounts-list', {
68
+ data: t.Object({}),
69
+ response: t.Object({
70
+ accounts: t.Array(t.Object({
71
+ id: t.Number(),
72
+ name: t.String(),
73
+ isActive: t.Boolean(),
74
+ createdAt: t.String(),
75
+ provider: t.String(),
76
+ authType: t.Union([t.Literal('api_key'), t.Literal('oauth')]),
77
+ /** Non-secret provider-scoped config (account id, base url, …) for edit prefill. */
78
+ env: t.Record(t.String(), t.String()),
79
+ })),
80
+ })
81
+ }, async () => {
82
+ const provider = getPiProvider();
83
+ if (!provider) return { accounts: [] };
84
+ const accounts = engineQueries.getAccountsByProvider(provider.id);
85
+ return {
86
+ accounts: accounts
87
+ .map(a => {
88
+ const parsed = parsePiCredential(a.credential);
89
+ if (!parsed) return null;
90
+ const env = parsed.credential.type === 'api_key' ? (parsed.credential.env ?? {}) : {};
91
+ return {
92
+ id: a.id,
93
+ name: a.name,
94
+ isActive: a.is_active === 1,
95
+ createdAt: a.created_at,
96
+ provider: parsed.provider,
97
+ authType: parsed.credential.type,
98
+ env,
99
+ };
100
+ })
101
+ .filter((x): x is NonNullable<typeof x> => x !== null),
102
+ };
103
+ })
104
+
105
+ // Add or edit an API-key account from an all-fields-at-once form. A blank
106
+ // secret field on edit keeps the stored value; blank env fields keep theirs.
107
+ .http('engine:pi-accounts-save', {
108
+ data: t.Object({
109
+ accountId: t.Optional(t.Number()),
110
+ name: t.String({ minLength: 1 }),
111
+ provider: t.String({ minLength: 1 }),
112
+ values: t.Record(t.String(), t.String()),
113
+ }),
114
+ response: t.Object({ success: t.Boolean(), accountId: t.Number() })
115
+ }, async ({ data }) => {
116
+ const providerRow = getPiProvider();
117
+ if (!providerRow) throw new Error('Pi provider not found in database');
118
+
119
+ const fields = getPiProviderFields(data.provider);
120
+ const keyField = fields.find(f => f.role === 'key');
121
+ const envFields = fields.filter(f => f.role === 'env');
122
+
123
+ const existing = data.accountId != null
124
+ ? parsePiCredential(engineQueries.getAccount(data.accountId)?.credential)
125
+ : null;
126
+ const existingApiKey = existing?.credential.type === 'api_key' ? existing.credential : null;
127
+
128
+ const providedKey = keyField ? (data.values[keyField.key] ?? '').trim() : '';
129
+ const key = providedKey || existingApiKey?.key || '';
130
+ if (!key) throw new Error('API key is required');
131
+
132
+ const env: Record<string, string> = { ...(existingApiKey?.env ?? {}) };
133
+ for (const field of envFields) {
134
+ const value = (data.values[field.key] ?? '').trim();
135
+ if (value) env[field.key] = value;
136
+ }
137
+
138
+ const credential: Credential = { type: 'api_key', key, ...(Object.keys(env).length ? { env } : {}) };
139
+ const serialized = serializePiCredential({ provider: data.provider, credential });
140
+
141
+ let accountId: number;
142
+ if (data.accountId != null && engineQueries.getAccount(data.accountId)) {
143
+ engineQueries.updateAccountCredential(data.accountId, serialized);
144
+ engineQueries.renameAccount(data.accountId, data.name.trim());
145
+ accountId = data.accountId;
146
+ } else {
147
+ accountId = engineQueries.createAccount(providerRow.id, data.name.trim(), serialized).id;
148
+ }
149
+ await disposePiEngines();
150
+ return { success: true, accountId };
151
+ })
152
+
153
+ .http('engine:pi-accounts-switch', {
154
+ data: t.Object({ id: t.Number() }),
155
+ response: t.Object({ success: t.Boolean() })
156
+ }, async ({ data }) => {
157
+ engineQueries.switchAccount(data.id);
158
+ await disposePiEngines();
159
+ return { success: true };
160
+ })
161
+
162
+ .http('engine:pi-accounts-delete', {
163
+ data: t.Object({ id: t.Number() }),
164
+ response: t.Object({ success: t.Boolean() })
165
+ }, async ({ data }) => {
166
+ const active = engineQueries.getActiveAccountForEngine('pi');
167
+ engineQueries.deleteAccount(data.id);
168
+ if (active?.id === data.id) await disposePiEngines();
169
+ return { success: true };
170
+ })
171
+
172
+ .http('engine:pi-accounts-rename', {
173
+ data: t.Object({ id: t.Number(), name: t.String({ minLength: 1 }) }),
174
+ response: t.Object({ success: t.Boolean() })
175
+ }, async ({ data }) => {
176
+ engineQueries.renameAccount(data.id, data.name.trim());
177
+ return { success: true };
178
+ })
179
+
180
+ // ═══ Interactive / OAuth login (event-driven) ═══
181
+
182
+ .on('engine:pi-account-login-start', {
183
+ data: t.Object({
184
+ name: t.String({ minLength: 1 }),
185
+ provider: t.String({ minLength: 1 }),
186
+ type: t.Union([t.Literal('api_key'), t.Literal('oauth')]),
187
+ reauthAccountId: t.Optional(t.Number()),
188
+ })
189
+ }, async ({ data, conn }) => {
190
+ const userId = ws.getUserId(conn);
191
+ const loginId = crypto.randomUUID();
192
+ const controller = new AbortController();
193
+
194
+ const entry: PiLoginSession = {
195
+ userId, disposed: false, controller,
196
+ name: data.name.trim(), provider: data.provider,
197
+ reauthAccountId: data.reauthAccountId ?? null,
198
+ pendingPrompt: null,
199
+ timer: setTimeout(() => {
200
+ ws.emit.user(userId, 'engine:pi-account-login-error', { loginId, message: 'Login timed out after 15 minutes' });
201
+ cleanupLogin(loginId);
202
+ }, LOGIN_TIMEOUT_MS),
203
+ };
204
+ loginSessions.set(loginId, entry);
205
+ ws.emit.user(userId, 'engine:pi-account-login-started', { loginId });
206
+
207
+ const interaction: AuthInteraction = {
208
+ signal: controller.signal,
209
+ notify: (event: AuthEvent) => {
210
+ ws.emit.user(userId, 'engine:pi-account-login-event', {
211
+ loginId,
212
+ kind: event.type,
213
+ message: 'message' in event ? event.message : undefined,
214
+ url: event.type === 'auth_url' ? event.url : undefined,
215
+ instructions: event.type === 'auth_url' ? event.instructions : undefined,
216
+ userCode: event.type === 'device_code' ? event.userCode : undefined,
217
+ verificationUri: event.type === 'device_code' ? event.verificationUri : undefined,
218
+ });
219
+ },
220
+ prompt: (prompt: AuthPrompt) => {
221
+ return new Promise<string>((resolve, reject) => {
222
+ entry.pendingPrompt = { resolve, reject };
223
+ ws.emit.user(userId, 'engine:pi-account-login-prompt', {
224
+ loginId,
225
+ kind: prompt.type,
226
+ message: prompt.message,
227
+ placeholder: 'placeholder' in prompt ? prompt.placeholder : undefined,
228
+ options: prompt.type === 'select'
229
+ ? prompt.options.map(o => ({ id: o.id, label: o.label, description: o.description }))
230
+ : undefined,
231
+ });
232
+ });
233
+ },
234
+ };
235
+
236
+ try {
237
+ const runtime = await createPiRuntime(new DbCredentialStore([]));
238
+ const credential = await runtime.login(data.provider, data.type as AuthType, interaction);
239
+ if (entry.disposed) return;
240
+
241
+ const serialized = serializePiCredential({ provider: data.provider, credential });
242
+ let accountId: number;
243
+ if (entry.reauthAccountId != null && engineQueries.getAccount(entry.reauthAccountId)) {
244
+ // Re-authenticate in place — update the credential (and name) of the
245
+ // existing account rather than creating a duplicate.
246
+ engineQueries.updateAccountCredential(entry.reauthAccountId, serialized);
247
+ engineQueries.renameAccount(entry.reauthAccountId, entry.name);
248
+ accountId = entry.reauthAccountId;
249
+ } else {
250
+ const providerRow = getPiProvider();
251
+ if (!providerRow) throw new Error('Pi provider not found in database');
252
+ accountId = engineQueries.createAccount(providerRow.id, entry.name, serialized).id;
253
+ }
254
+ await disposePiEngines();
255
+
256
+ ws.emit.user(userId, 'engine:pi-account-login-complete', { loginId, accountId });
257
+ cleanupLogin(loginId);
258
+ } catch (error) {
259
+ if (!entry.disposed) {
260
+ debug.warn('engine', `Pi login failed: ${error instanceof Error ? error.message : String(error)}`);
261
+ ws.emit.user(userId, 'engine:pi-account-login-error', {
262
+ loginId,
263
+ message: error instanceof Error ? error.message : 'Login failed',
264
+ });
265
+ }
266
+ cleanupLogin(loginId);
267
+ }
268
+ })
269
+
270
+ .on('engine:pi-account-login-submit', {
271
+ data: t.Object({ loginId: t.String(), value: t.String() })
272
+ }, async ({ data, conn }) => {
273
+ let entry: PiLoginSession;
274
+ try {
275
+ entry = requireSetupSessionAccess(conn, data.loginId, loginSessions);
276
+ } catch {
277
+ return;
278
+ }
279
+ const pending = entry.pendingPrompt;
280
+ entry.pendingPrompt = null;
281
+ pending?.resolve(data.value);
282
+ })
283
+
284
+ .on('engine:pi-account-login-cancel', {
285
+ data: t.Object({ loginId: t.String() })
286
+ }, async ({ data, conn }) => {
287
+ try {
288
+ requireSetupSessionAccess(conn, data.loginId, loginSessions);
289
+ } catch {
290
+ return;
291
+ }
292
+ cleanupLogin(data.loginId);
293
+ })
294
+
295
+ // ═══ Event declarations (Server → Client) ═══
296
+
297
+ .emit('engine:pi-account-login-started', t.Object({ loginId: t.String() }))
298
+ .emit('engine:pi-account-login-event', t.Object({
299
+ loginId: t.String(),
300
+ kind: t.String(),
301
+ message: t.Optional(t.String()),
302
+ url: t.Optional(t.String()),
303
+ instructions: t.Optional(t.String()),
304
+ userCode: t.Optional(t.String()),
305
+ verificationUri: t.Optional(t.String()),
306
+ }))
307
+ .emit('engine:pi-account-login-prompt', t.Object({
308
+ loginId: t.String(),
309
+ kind: t.String(),
310
+ message: t.String(),
311
+ placeholder: t.Optional(t.String()),
312
+ options: t.Optional(t.Array(t.Object({
313
+ id: t.String(),
314
+ label: t.String(),
315
+ description: t.Optional(t.String()),
316
+ }))),
317
+ }))
318
+ .emit('engine:pi-account-login-complete', t.Object({ loginId: t.String(), accountId: t.Number() }))
319
+ .emit('engine:pi-account-login-error', t.Object({ loginId: t.String(), message: t.String() }));
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Pi Engine Router
3
+ *
4
+ * Combines status detection, account/login management, and provider presets.
5
+ */
6
+
7
+ import { createRouter } from '$shared/utils/ws-server';
8
+ import { piStatusHandler } from './status';
9
+ import { piAccountsHandler } from './accounts';
10
+ import { piPresetsHandler } from './presets';
11
+
12
+ export const piEngineRouter = createRouter()
13
+ .merge(piStatusHandler)
14
+ .merge(piAccountsHandler)
15
+ .merge(piPresetsHandler);
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Pi Provider Presets Handler
3
+ *
4
+ * Exposes the Pi provider catalog (id, name, supported auth modes) to the
5
+ * frontend so the login picker can render the right flow per provider without
6
+ * importing backend modules directly. Built dynamically from `ModelRuntime`.
7
+ */
8
+
9
+ import { t } from 'elysia';
10
+ import { createRouter } from '$shared/utils/ws-server';
11
+ import { getPiProviderPresets } from '../../../engine/adapters/pi/presets';
12
+
13
+ export const piPresetsHandler = createRouter()
14
+ .http('engine:pi-presets-list', {
15
+ data: t.Object({}),
16
+ response: t.Object({
17
+ presets: t.Array(t.Object({
18
+ id: t.String(),
19
+ name: t.String(),
20
+ authModes: t.Array(t.Union([t.Literal('api_key'), t.Literal('oauth')])),
21
+ fields: t.Optional(t.Array(t.Object({
22
+ key: t.String(),
23
+ label: t.String(),
24
+ secret: t.Boolean(),
25
+ role: t.Union([t.Literal('key'), t.Literal('env')]),
26
+ placeholder: t.Optional(t.String()),
27
+ }))),
28
+ oauthLabel: t.Optional(t.String()),
29
+ apiKeyUrl: t.Optional(t.String()),
30
+ })),
31
+ })
32
+ }, async () => {
33
+ return { presets: await getPiProviderPresets() };
34
+ });
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Pi Engine Status Handler
3
+ *
4
+ * Pi is an in-process SDK (`@earendil-works/pi-coding-agent`) — there is no CLI
5
+ * to install, so `installed` is always true. Reports the SDK version and active
6
+ * account state.
7
+ */
8
+
9
+ import { t } from 'elysia';
10
+ import { createRouter } from '$shared/utils/ws-server';
11
+ import { engineQueries } from '../../../database/queries';
12
+ import { debug } from '$shared/utils/logger';
13
+ import { getBackendOS } from '../../../utils/os';
14
+
15
+ function readSdkVersion(): string | null {
16
+ try {
17
+ const path = require.resolve('@earendil-works/pi-coding-agent/package.json');
18
+ const pkg = require(path) as { version?: string };
19
+ return pkg.version ?? null;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ export const piStatusHandler = createRouter()
26
+ .http('engine:pi-status', {
27
+ data: t.Object({}),
28
+ response: t.Object({
29
+ installed: t.Boolean(),
30
+ version: t.Union([t.String(), t.Null()]),
31
+ activeAccount: t.Union([
32
+ t.Object({ id: t.Number(), name: t.String() }),
33
+ t.Null()
34
+ ]),
35
+ accountsCount: t.Number(),
36
+ backendOS: t.Union([t.Literal('windows'), t.Literal('macos'), t.Literal('linux')])
37
+ })
38
+ }, async () => {
39
+ debug.log('engine', 'Checking Pi status...');
40
+ const provider = engineQueries.getProviderBySlug('pi', 'pi');
41
+ const accounts = provider ? engineQueries.getAccountsByProvider(provider.id) : [];
42
+ const activeAccount = engineQueries.getActiveAccountForEngine('pi');
43
+ return {
44
+ installed: true,
45
+ version: readSdkVersion(),
46
+ activeAccount: activeAccount ? { id: activeAccount.id, name: activeAccount.name } : null,
47
+ accountsCount: accounts.length,
48
+ backendOS: getBackendOS()
49
+ };
50
+ });
@@ -32,7 +32,7 @@ const sessionSchema = t.Object({
32
32
  ended_at: t.Optional(t.String()),
33
33
  // Session preferences
34
34
  title: t.Optional(t.String()),
35
- engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode'), t.Literal('copilot'), t.Literal('codex'), t.Literal('qwen')])),
35
+ engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode'), t.Literal('copilot'), t.Literal('codex'), t.Literal('qwen'), t.Literal('pi'), t.Literal('cline'), t.Literal('cursor')])),
36
36
  model_id: t.Optional(t.String()),
37
37
  model_name: t.Optional(t.String()),
38
38
  account_id: t.Optional(t.Number()),
@@ -117,7 +117,7 @@ export const crudHandler = createRouter()
117
117
  .http('sessions:create', {
118
118
  data: t.Object({
119
119
  title: t.Optional(t.String()),
120
- engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode'), t.Literal('copilot'), t.Literal('codex'), t.Literal('qwen')]))
120
+ engine: t.Optional(t.Union([t.Literal('claude-code'), t.Literal('opencode'), t.Literal('copilot'), t.Literal('codex'), t.Literal('qwen'), t.Literal('pi'), t.Literal('cline'), t.Literal('cursor')]))
121
121
  }),
122
122
  response: sessionSchema
123
123
  }, async ({ data, conn }) => {