@myrialabs/clopen 0.4.14 → 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 (130) hide show
  1. package/backend/artifacts/matrix.ts +8 -0
  2. package/backend/artifacts/types.ts +2 -2
  3. package/backend/auth/permissions.ts +16 -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/056_support_mssql_driver.ts +137 -0
  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 +28 -0
  12. package/backend/database/queries/engine-queries.ts +13 -0
  13. package/backend/database/queries/message-queries.ts +43 -1
  14. package/backend/db-client/connection-manager.ts +8 -2
  15. package/backend/db-client/drivers/mssql.ts +829 -0
  16. package/backend/db-client/drivers/mysql.ts +33 -4
  17. package/backend/db-client/drivers/postgres.ts +55 -5
  18. package/backend/db-client/drivers/sql-builders.test.ts +70 -0
  19. package/backend/db-client/drivers/sql-builders.ts +9 -2
  20. package/backend/db-client/pool-config.ts +32 -0
  21. package/backend/db-client/query-executor.test.ts +42 -0
  22. package/backend/db-client/query-executor.ts +47 -3
  23. package/backend/engine/README.md +36 -13
  24. package/backend/engine/adapters/cline/agent-tool.ts +64 -0
  25. package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
  26. package/backend/engine/adapters/cline/credential.ts +166 -0
  27. package/backend/engine/adapters/cline/error-handler.ts +49 -0
  28. package/backend/engine/adapters/cline/index.ts +1 -0
  29. package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
  30. package/backend/engine/adapters/cline/message-converter.ts +396 -0
  31. package/backend/engine/adapters/cline/models.ts +73 -0
  32. package/backend/engine/adapters/cline/presets.ts +128 -0
  33. package/backend/engine/adapters/cline/stream.ts +413 -0
  34. package/backend/engine/adapters/codex/credential.ts +1 -1
  35. package/backend/engine/adapters/codex/message-converter.ts +4 -4
  36. package/backend/engine/adapters/codex/session-fork.ts +1 -1
  37. package/backend/engine/adapters/codex/stream.ts +3 -3
  38. package/backend/engine/adapters/copilot/stream.ts +1 -1
  39. package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
  40. package/backend/engine/adapters/cursor/credential.ts +68 -0
  41. package/backend/engine/adapters/cursor/environment.ts +32 -0
  42. package/backend/engine/adapters/cursor/error-handler.ts +60 -0
  43. package/backend/engine/adapters/cursor/index.ts +1 -0
  44. package/backend/engine/adapters/cursor/message-converter.ts +615 -0
  45. package/backend/engine/adapters/cursor/models.ts +68 -0
  46. package/backend/engine/adapters/cursor/session-fork.ts +68 -0
  47. package/backend/engine/adapters/cursor/stream.ts +341 -0
  48. package/backend/engine/adapters/opencode/config.ts +9 -0
  49. package/backend/engine/adapters/opencode/models.ts +10 -1
  50. package/backend/engine/adapters/opencode/server.ts +110 -2
  51. package/backend/engine/adapters/pi/agent-tool.ts +62 -0
  52. package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
  53. package/backend/engine/adapters/pi/credential.ts +137 -0
  54. package/backend/engine/adapters/pi/environment.ts +33 -0
  55. package/backend/engine/adapters/pi/error-handler.ts +46 -0
  56. package/backend/engine/adapters/pi/index.ts +1 -0
  57. package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
  58. package/backend/engine/adapters/pi/message-converter.ts +446 -0
  59. package/backend/engine/adapters/pi/models.ts +53 -0
  60. package/backend/engine/adapters/pi/presets.ts +133 -0
  61. package/backend/engine/adapters/pi/session-fork.ts +46 -0
  62. package/backend/engine/adapters/pi/stream.ts +427 -0
  63. package/backend/engine/adapters/qwen/message-converter.ts +5 -5
  64. package/backend/engine/adapters/qwen/stream.ts +2 -2
  65. package/backend/engine/docs/adapter-contract.md +7 -2
  66. package/backend/engine/docs/adding-an-engine.md +70 -12
  67. package/backend/engine/docs/artifacts.md +124 -0
  68. package/backend/engine/docs/database.md +4 -4
  69. package/backend/engine/docs/frontend-and-chat.md +22 -4
  70. package/backend/engine/docs/lessons-learned.md +219 -32
  71. package/backend/engine/docs/quick-reference.md +18 -7
  72. package/backend/engine/docs/websocket-routes.md +2 -2
  73. package/backend/engine/index.ts +9 -0
  74. package/backend/index.ts +6 -0
  75. package/backend/mcp/README.md +3 -3
  76. package/backend/mcp/external/config.ts +11 -0
  77. package/backend/mcp/index.ts +8 -0
  78. package/backend/mcp/internal/config.ts +33 -1
  79. package/backend/permissions/service.ts +5 -2
  80. package/backend/preview/browser/browser-preview-service.ts +15 -6
  81. package/backend/preview/browser/browser-video-capture.ts +232 -100
  82. package/backend/preview/browser/scripts/video-stream.ts +216 -56
  83. package/backend/preview/browser/types.ts +24 -12
  84. package/backend/skills/sync.ts +1 -1
  85. package/backend/subagents/detect.ts +1 -1
  86. package/backend/subagents/sync.ts +1 -1
  87. package/backend/ws/chat/stream.ts +13 -5
  88. package/backend/ws/db-client/connections.ts +2 -1
  89. package/backend/ws/db-client/query.ts +41 -4
  90. package/backend/ws/db-client/schema.ts +45 -1
  91. package/backend/ws/engine/claude/accounts.ts +37 -13
  92. package/backend/ws/engine/cline/accounts.ts +317 -0
  93. package/backend/ws/engine/cline/index.ts +15 -0
  94. package/backend/ws/engine/cline/presets.ts +36 -0
  95. package/backend/ws/engine/cline/status.ts +49 -0
  96. package/backend/ws/engine/codex/accounts.ts +37 -5
  97. package/backend/ws/engine/copilot/accounts.ts +12 -0
  98. package/backend/ws/engine/cursor/accounts.ts +162 -0
  99. package/backend/ws/engine/cursor/index.ts +13 -0
  100. package/backend/ws/engine/cursor/status.ts +55 -0
  101. package/backend/ws/engine/index.ts +6 -0
  102. package/backend/ws/engine/opencode/providers.ts +72 -1
  103. package/backend/ws/engine/pi/accounts.ts +319 -0
  104. package/backend/ws/engine/pi/index.ts +15 -0
  105. package/backend/ws/engine/pi/presets.ts +34 -0
  106. package/backend/ws/engine/pi/status.ts +50 -0
  107. package/backend/ws/engine/qwen/accounts.ts +22 -0
  108. package/backend/ws/messages/crud.ts +13 -0
  109. package/backend/ws/preview/browser/interact.ts +10 -8
  110. package/backend/ws/preview/browser/webcodecs.ts +26 -2
  111. package/backend/ws/sessions/crud.ts +2 -2
  112. package/backend/ws/settings/crud.ts +2 -2
  113. package/dist/assets/{index-CDZf6lfv.js → index-BPvctwJ2.js} +1 -1
  114. package/dist/assets/{index-BWf-DDJN.js → index-vLKZpWQH.js} +1 -1
  115. package/dist/assets/{main-C15mQTCW.js → main-BtBZvCwv.js} +428 -386
  116. package/dist/assets/main-D7ATW8pp.css +1 -0
  117. package/dist/index.html +2 -2
  118. package/package.json +11 -1
  119. package/shared/constants/engine-tools.ts +16 -2
  120. package/shared/constants/engines.ts +27 -0
  121. package/shared/types/db-client/connection.ts +1 -1
  122. package/shared/types/db-client/query.ts +4 -1
  123. package/shared/types/unified/common.ts +1 -1
  124. package/shared/types/unified/engine.ts +82 -1
  125. package/shared/types/unified/index.ts +6 -0
  126. package/shared/types/unified/message.ts +1 -1
  127. package/shared/utils/db-client/split-sql.test.ts +13 -0
  128. package/shared/utils/db-client/split-sql.ts +38 -1
  129. package/shared/utils/subagent-wire-trim.ts +87 -0
  130. package/dist/assets/main-Ba5ZGlY4.css +0 -1
@@ -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
+ });
@@ -134,4 +134,26 @@ export const qwenAccountsHandler = createRouter()
134
134
  }, async ({ data }) => {
135
135
  engineQueries.renameAccount(data.id, data.name.trim());
136
136
  return { success: true };
137
+ })
138
+
139
+ // Update an account's API key and/or preset. Both are optional — an omitted
140
+ // (or blank) apiKey keeps the stored one, so the user can re-point the
141
+ // preset without re-entering the secret, and vice versa.
142
+ .http('engine:qwen-accounts-update', {
143
+ data: t.Object({
144
+ id: t.Number(),
145
+ apiKey: t.Optional(t.String()),
146
+ preset: t.Optional(PRESET_LITERALS),
147
+ }),
148
+ response: t.Object({ success: t.Boolean() })
149
+ }, async ({ data }) => {
150
+ const account = engineQueries.getAccount(data.id);
151
+ if (!account) throw new Error('Account not found');
152
+ const current = parseQwenCredential(account.credential);
153
+ const apiKey = data.apiKey?.trim() ? data.apiKey.trim() : current.apiKey;
154
+ const preset = data.preset ?? current.preset;
155
+ engineQueries.updateAccountCredential(data.id, serializeQwenCredential({ apiKey, preset }));
156
+ const active = engineQueries.getActiveAccountForEngine('qwen');
157
+ if (active?.id === data.id) await disposeQwenEngines();
158
+ return { success: true };
137
159
  });
@@ -44,6 +44,19 @@ export const crudHandler = createRouter()
44
44
  return loadMessage(message);
45
45
  })
46
46
 
47
+ // Get full (untrimmed) sub-agent messages nested under a message.
48
+ // Used by the Debug modal to show complete data despite the wire trimming
49
+ // sub-agent noise from the normal chat payload.
50
+ .http('messages:get-subagents', {
51
+ data: t.Object({
52
+ messageId: t.String({ minLength: 1 })
53
+ }),
54
+ response: t.Array(t.Any())
55
+ }, async ({ data, conn }) => {
56
+ requireMessageAccess(conn, data.messageId);
57
+ return messageQueries.getSubAgentMessages(data.messageId);
58
+ })
59
+
47
60
  // Delete message
48
61
  .http('messages:delete', {
49
62
  data: t.Object({
@@ -445,16 +445,18 @@ export const interactPreviewHandler = createRouter()
445
445
  break;
446
446
 
447
447
  case 'scale-update':
448
- // Handle scale update from frontend (hot-swap, no reconnection)
448
+ // Display fit-scale changed on the frontend (CSS-only concern).
449
+ // Capture stays at native viewport resolution — restart the
450
+ // screencast as a refresh so a stuck stream recovers (the
451
+ // frontend also uses this action as its refresh path).
449
452
  if (action.scale && action.scale > 0 && action.scale <= 1) {
450
453
  session.scale = action.scale;
451
- debug.log('preview', `📐 Scale updated for tab ${tabId}: ${action.scale}`);
454
+ debug.log('preview', `📐 Scale updated for tab ${tabId}: ${action.scale} (display-only), refreshing screencast`);
452
455
 
453
- // Hot-swap resolution without reconnection
454
- const updated = await previewService.updateWebCodecsScale(session.id, action.scale);
456
+ const updated = await previewService.refreshWebCodecsScreencast(session.id);
455
457
  if (!updated) {
456
- debug.warn('preview', `⚠️ Hot-swap failed, falling back to restart`);
457
- // Fallback: restart if hot-swap fails
458
+ debug.warn('preview', `⚠️ Screencast refresh failed, falling back to restart`);
459
+ // Fallback: restart if refresh fails
458
460
  await previewService.stopWebCodecsStreaming(session.id);
459
461
  await previewService.startWebCodecsStreaming(session.id);
460
462
  }
@@ -468,10 +470,10 @@ export const interactPreviewHandler = createRouter()
468
470
  if (action.deviceSize) session.deviceSize = action.deviceSize as any;
469
471
  if (action.rotation) session.rotation = action.rotation as any;
470
472
 
471
- debug.log('preview', `📱 Viewport updated for tab ${tabId}: ${action.width}x${action.height} (scale: ${action.scale})`);
473
+ debug.log('preview', `📱 Viewport updated for tab ${tabId}: ${action.width}x${action.height}`);
472
474
 
473
475
  // Hot-swap viewport without reconnection
474
- const updated = await previewService.updateWebCodecsViewport(session.id, action.width, action.height, action.scale);
476
+ const updated = await previewService.updateWebCodecsViewport(session.id, action.width, action.height);
475
477
  if (!updated) {
476
478
  debug.warn('preview', `⚠️ Viewport hot-swap failed`);
477
479
  }
@@ -17,7 +17,10 @@ export const streamPreviewHandler = createRouter()
17
17
  'preview:browser-stream-start',
18
18
  {
19
19
  data: t.Object({
20
- tabId: t.Optional(t.String())
20
+ tabId: t.Optional(t.String()),
21
+ // Client VP9 decode capability — encoder prefers VP9 quantizer
22
+ // mode but must fall back to VP8 if the viewer can't decode it
23
+ vp9: t.Optional(t.Boolean())
21
24
  }),
22
25
  response: t.Object({
23
26
  success: t.Boolean(),
@@ -41,7 +44,7 @@ export const streamPreviewHandler = createRouter()
41
44
  }
42
45
 
43
46
  // Start WebCodecs streaming
44
- const started = await previewService.startWebCodecsStreaming(sessionId);
47
+ const started = await previewService.startWebCodecsStreaming(sessionId, data.vp9 !== false);
45
48
 
46
49
  if (!started) {
47
50
  throw new Error('Failed to start WebCodecs streaming');
@@ -148,6 +151,27 @@ export const streamPreviewHandler = createRouter()
148
151
  }
149
152
  )
150
153
 
154
+ // Client-driven keyframe request (PLI equivalent) — sent when the client
155
+ // decoder errors or joins mid-stream and needs a sync point
156
+ .http(
157
+ 'preview:browser-stream-keyframe',
158
+ {
159
+ data: t.Object({
160
+ tabId: t.Optional(t.String())
161
+ }),
162
+ response: t.Object({
163
+ success: t.Boolean()
164
+ })
165
+ },
166
+ async ({ data, conn }) => {
167
+ const { previewService, tab } = requireBrowserTabAccess(conn, data.tabId);
168
+
169
+ const success = await previewService.requestWebCodecsKeyframe(tab.id);
170
+
171
+ return { success };
172
+ }
173
+ )
174
+
151
175
  // Stop streaming
152
176
  .http(
153
177
  'preview:browser-stream-stop',
@@ -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 }) => {
@@ -110,11 +110,11 @@ export const crudHandler = createRouter()
110
110
  // List available models for an engine
111
111
  .http('models:list', {
112
112
  data: t.Object({
113
- engine: t.Union([t.Literal('claude-code'), t.Literal('opencode'), t.Literal('copilot'), t.Literal('codex'), t.Literal('qwen')])
113
+ engine: 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')])
114
114
  }),
115
115
  response: t.Array(t.Object({
116
116
  engine: t.Object({
117
- type: t.Union([t.Literal('claude-code'), t.Literal('opencode'), t.Literal('copilot'), t.Literal('codex'), t.Literal('qwen')]),
117
+ type: 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')]),
118
118
  provider: t.String(),
119
119
  model: t.Object({ id: t.String(), name: t.String() }),
120
120
  account: t.Object({ id: t.Number(), name: t.String() }),
@@ -1 +1 @@
1
- import{s as _,_ as d,r as s,a as u}from"./main-C15mQTCW.js";import{C as T,P as y,W as E,d as L,b as g,c as v,h as P,l as b,m as k,e as D,n as O,f as R,g as S,t as V}from"./main-C15mQTCW.js";async function h(o,e={}){const i=e.loading===!1?void 0:_(o,e.loadingText??"Loading…"),[{Terminal:l},{FitAddon:c}]=await Promise.all([d(()=>import("./xterm-B-qIQCd3.js"),[]),d(()=>import("./addon-fit-DX4qG4td.js"),[])]).catch(r=>{throw i?.(),r}),a=new l({scrollback:e.scrollback??5e3,fontSize:e.fontSize??13,fontFamily:e.fontFamily??"ui-monospace, SFMono-Regular, Menlo, monospace",lineHeight:e.lineHeight??1,cursorBlink:e.cursorBlink??!1,cursorStyle:e.cursorStyle??"block",disableStdin:e.stdin!==!0,allowProposedApi:!0,convertEol:!0,theme:s(e.theme),...e.cols?{cols:e.cols}:{},...e.rows?{rows:e.rows}:{},...e.terminalOptions??{}}),t=e.fit===!1?void 0:new c;if(t&&a.loadAddon(t),e.clipboard)try{const{ClipboardAddon:r}=await d(()=>import("./addon-clipboard-wHJhZAA4.js"),[]);a.loadAddon(new r)}catch{}if(e.webLinks)try{const{WebLinksAddon:r}=await d(()=>import("./addon-web-links-DIbG5aQx.js"),[]);a.loadAddon(new r)}catch{}if(e.unicode11)try{const{Unicode11Addon:r}=await d(()=>import("./addon-unicode11-Bt8F3D7-.js"),[]);a.loadAddon(new r),a.unicode.activeVersion="11"}catch{}for(const r of e.addons??[])a.loadAddon(r);if(a.open(o),e.ligatures)try{const{LigaturesAddon:r}=await d(()=>import("./addon-ligatures-DpDY8N_X.js"),[]);a.loadAddon(new r)}catch{}const m=t?u({resize:async()=>{}},a,t,{debounceMs:e.fitDebounceMs??100}):void 0;e.onReady?.(a),i?.();let n=!1;return{terminal:a,fitAddon:t,write:r=>a.write(r),clear:()=>{a.clear(),a.reset()},fit:()=>t?.fit(),setTheme:r=>{a.options.theme=s(r)},dispose(){n||(n=!0,m?.(),a.dispose())}}}export{T as ClientSession,y as PtyKitClient,E as WsCore,u as attachFit,L as darkTheme,g as defaultPersistence,v as draculaTheme,P as hostSocket,b as lightTheme,k as matrixTheme,D as mountTerminal,h as mountViewer,O as nordTheme,s as resolveTheme,_ as showLoadingOverlay,R as solarizedDarkTheme,S as solarizedLightTheme,V as themes};
1
+ import{s as _,_ as d,r as s,a as u}from"./main-BtBZvCwv.js";import{C as T,P as y,W as E,d as L,b as g,c as v,h as P,l as b,m as k,e as D,n as O,f as R,g as S,t as V}from"./main-BtBZvCwv.js";async function h(o,e={}){const i=e.loading===!1?void 0:_(o,e.loadingText??"Loading…"),[{Terminal:l},{FitAddon:c}]=await Promise.all([d(()=>import("./xterm-B-qIQCd3.js"),[]),d(()=>import("./addon-fit-DX4qG4td.js"),[])]).catch(r=>{throw i?.(),r}),a=new l({scrollback:e.scrollback??5e3,fontSize:e.fontSize??13,fontFamily:e.fontFamily??"ui-monospace, SFMono-Regular, Menlo, monospace",lineHeight:e.lineHeight??1,cursorBlink:e.cursorBlink??!1,cursorStyle:e.cursorStyle??"block",disableStdin:e.stdin!==!0,allowProposedApi:!0,convertEol:!0,theme:s(e.theme),...e.cols?{cols:e.cols}:{},...e.rows?{rows:e.rows}:{},...e.terminalOptions??{}}),t=e.fit===!1?void 0:new c;if(t&&a.loadAddon(t),e.clipboard)try{const{ClipboardAddon:r}=await d(()=>import("./addon-clipboard-wHJhZAA4.js"),[]);a.loadAddon(new r)}catch{}if(e.webLinks)try{const{WebLinksAddon:r}=await d(()=>import("./addon-web-links-DIbG5aQx.js"),[]);a.loadAddon(new r)}catch{}if(e.unicode11)try{const{Unicode11Addon:r}=await d(()=>import("./addon-unicode11-Bt8F3D7-.js"),[]);a.loadAddon(new r),a.unicode.activeVersion="11"}catch{}for(const r of e.addons??[])a.loadAddon(r);if(a.open(o),e.ligatures)try{const{LigaturesAddon:r}=await d(()=>import("./addon-ligatures-DpDY8N_X.js"),[]);a.loadAddon(new r)}catch{}const m=t?u({resize:async()=>{}},a,t,{debounceMs:e.fitDebounceMs??100}):void 0;e.onReady?.(a),i?.();let n=!1;return{terminal:a,fitAddon:t,write:r=>a.write(r),clear:()=>{a.clear(),a.reset()},fit:()=>t?.fit(),setTheme:r=>{a.options.theme=s(r)},dispose(){n||(n=!0,m?.(),a.dispose())}}}export{T as ClientSession,y as PtyKitClient,E as WsCore,u as attachFit,L as darkTheme,g as defaultPersistence,v as draculaTheme,P as hostSocket,b as lightTheme,k as matrixTheme,D as mountTerminal,h as mountViewer,O as nordTheme,s as resolveTheme,_ as showLoadingOverlay,R as solarizedDarkTheme,S as solarizedLightTheme,V as themes};