@myrialabs/clopen 0.4.20 → 0.4.21

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 (38) hide show
  1. package/backend/bootstrap.ts +39 -0
  2. package/backend/chat/stream-manager.ts +15 -0
  3. package/backend/database/migrations/065_add_session_reasoning_effort.ts +28 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/session-queries.ts +10 -0
  6. package/backend/engine/adapters/claude/models.ts +46 -23
  7. package/backend/engine/adapters/claude/stream.ts +18 -4
  8. package/backend/engine/adapters/codex/models.ts +19 -2
  9. package/backend/engine/adapters/codex/stream.ts +10 -3
  10. package/backend/engine/adapters/copilot/models.ts +20 -1
  11. package/backend/engine/adapters/copilot/stream.ts +11 -1
  12. package/backend/engine/adapters/cursor/models.ts +27 -3
  13. package/backend/engine/adapters/cursor/stream.ts +23 -3
  14. package/backend/engine/adapters/pi/models.ts +20 -2
  15. package/backend/engine/adapters/pi/stream.ts +6 -3
  16. package/backend/engine/bootstrap-default-engine.ts +18 -5
  17. package/backend/engine/types.ts +6 -0
  18. package/backend/index.ts +6 -9
  19. package/backend/ws/chat/stream.ts +38 -2
  20. package/backend/ws/system/device-info.ts +290 -0
  21. package/backend/ws/system/index.ts +2 -0
  22. package/backend/ws/system/operations.ts +7 -0
  23. package/backend/ws/user/crud.ts +6 -3
  24. package/dist/assets/{index-DdrcY5TE.js → index-B8YRz8wG.js} +1 -1
  25. package/dist/assets/{index-BqBxKeAv.js → index-CEGW8vEt.js} +1 -1
  26. package/dist/assets/main-D-2ByODy.js +590 -0
  27. package/dist/assets/main-D8I0MfRQ.css +1 -0
  28. package/dist/index.html +2 -2
  29. package/package.json +2 -1
  30. package/shared/constants/engines.ts +23 -0
  31. package/shared/types/database/schema.ts +1 -0
  32. package/shared/types/stores/settings.ts +6 -0
  33. package/shared/types/unified/engine.ts +33 -0
  34. package/shared/types/unified/index.ts +2 -0
  35. package/shared/types/unified/message.ts +6 -0
  36. package/shared/types/unified/stream.ts +6 -0
  37. package/dist/assets/main-BBxAj17T.js +0 -582
  38. package/dist/assets/main-Cry3pLcl.css +0 -1
@@ -26,7 +26,8 @@ import type {
26
26
  } from '@earendil-works/pi-coding-agent';
27
27
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
28
28
  import type { AgentToolResult } from '@earendil-works/pi-agent-core';
29
- import type { ImageContent } from '@earendil-works/pi-ai';
29
+ import type { ImageContent, ModelThinkingLevel } from '@earendil-works/pi-ai';
30
+ import { clampThinkingLevel } from '@earendil-works/pi-ai';
30
31
  import type { EngineOutput, EngineModel, MessageEngine } from '$shared/types/unified';
31
32
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
32
33
  import { resolveOsPath } from '$backend/utils/paths';
@@ -115,7 +116,7 @@ export class PiEngine implements AIEngine {
115
116
  }
116
117
 
117
118
  async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
118
- const { projectPath, prompt, resume, providerSlug, modelId, abortController, accountId } = options;
119
+ const { projectPath, prompt, resume, providerSlug, modelId, reasoningEffort, abortController, accountId } = options;
119
120
  debug.log('chat', 'Pi - Stream Query', { providerSlug, modelId, resume });
120
121
 
121
122
  const { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager } =
@@ -260,7 +261,9 @@ export class PiEngine implements AIEngine {
260
261
  agentDir,
261
262
  model,
262
263
  modelRuntime: runtime,
263
- thinkingLevel: model.reasoning ? 'medium' : 'off',
264
+ thinkingLevel: reasoningEffort
265
+ ? clampThinkingLevel(model, reasoningEffort as ModelThinkingLevel)
266
+ : (model.reasoning ? 'medium' : 'off'),
264
267
  resourceLoader,
265
268
  tools: toolAllowlist,
266
269
  customTools,
@@ -27,16 +27,29 @@ const ENGINE_SDK_PACKAGES = [
27
27
  '@cursor/sdk',
28
28
  ];
29
29
 
30
- let bootstrapStarted = false;
30
+ /**
31
+ * Tracks an in-flight install so concurrent callers share one run — but only
32
+ * while it's running. A permanent "already started" latch would wrongly skip a
33
+ * legitimate reinstall after "Clear All Data" wipes ~/.clopen/stack/engines on
34
+ * the live process; gating on the in-flight promise instead lets a later call
35
+ * re-evaluate `isEngineSdkInstalled` once the previous run has settled.
36
+ */
37
+ let inFlight: Promise<void> | null = null;
31
38
 
32
39
  /**
33
40
  * Install OpenCode on a fresh machine (no engine SDK present). Idempotent and
34
- * safe to call at every startup; it no-ops once any engine exists.
41
+ * safe to call at every startup and after a data wipe; it no-ops once any engine
42
+ * exists, and de-dupes concurrent calls via the in-flight promise.
35
43
  */
36
- export async function ensureDefaultEngineInstalled(): Promise<void> {
37
- if (bootstrapStarted) return;
38
- bootstrapStarted = true;
44
+ export function ensureDefaultEngineInstalled(): Promise<void> {
45
+ if (inFlight) return inFlight;
46
+ inFlight = runDefaultEngineInstall().finally(() => {
47
+ inFlight = null;
48
+ });
49
+ return inFlight;
50
+ }
39
51
 
52
+ async function runDefaultEngineInstall(): Promise<void> {
40
53
  if (ENGINE_SDK_PACKAGES.some(isEngineSdkInstalled)) return;
41
54
 
42
55
  const recipe = await resolveRecipe('opencode');
@@ -35,6 +35,12 @@ export interface EngineQueryOptions {
35
35
  providerSlug: string;
36
36
  /** Model ID (e.g. 'claude-opus-4-6', 'gpt-5'). */
37
37
  modelId: string;
38
+ /**
39
+ * Reasoning/thinking level token chosen for this turn (native per engine —
40
+ * see `EngineModel.capabilities.reasoningControl`). Undefined → the engine's
41
+ * own default applies. Each adapter clamps/maps it to its SDK's knob.
42
+ */
43
+ reasoningEffort?: string;
38
44
  includePartialMessages?: boolean;
39
45
  abortController?: AbortController;
40
46
  accountId?: number;
package/backend/index.ts CHANGED
@@ -23,8 +23,7 @@ import { loggerMiddleware } from './middleware/logger';
23
23
 
24
24
  // Database initialization
25
25
  import { initializeDatabase, closeDatabase } from './database';
26
- import { ensureDefaultEngineInstalled } from './engine/bootstrap-default-engine';
27
- import { syncInternalServers } from './mcp';
26
+ import { bootstrapAfterDbInit } from './bootstrap';
28
27
  import { disposeAllEngines } from './engine';
29
28
  import { connectionManager } from './db-client/connection-manager';
30
29
  import { refreshProcessPath } from './utils/path-enrich';
@@ -235,16 +234,14 @@ async function startServer() {
235
234
  try {
236
235
  await initializeDatabase();
237
236
  debug.log('database', '✅ Database initialized successfully');
238
- // Mirror code-defined internal MCP servers into the DB so Settings → MCP
239
- // can list and toggle them. Idempotent; preserves the user's toggles.
240
- syncInternalServers();
237
+ // Re-establish code-defined built-ins that live outside migrations/seeders
238
+ // (internal MCP servers like Browser Automation + the default engine).
239
+ // Shared with the clear-data handler so a DB wipe on the live process
240
+ // restores them without a restart.
241
+ bootstrapAfterDbInit();
241
242
  // Start expired session cleanup now that the database is ready
242
243
  sessionCleanupScheduler.start();
243
244
  uploadTempCleanup.start();
244
- // Fresh installs: auto-install OpenCode (free, no account) in the
245
- // background so first-time users have a working engine without any manual
246
- // setup. Non-blocking; no-ops once any engine is already installed.
247
- void ensureDefaultEngineInstalled();
248
245
  } catch (error) {
249
246
  debug.warn('database', '⚠️ Database initialization failed:', error);
250
247
  }
@@ -219,7 +219,10 @@ export const streamHandler = createRouter()
219
219
  }),
220
220
  // Active Profile for this session (null = explicit none; absent = use
221
221
  // the project default). Persisted like engine/model.
222
- profileId: t.Optional(t.Union([t.Number(), t.Null()]))
222
+ profileId: t.Optional(t.Union([t.Number(), t.Null()])),
223
+ // Reasoning/thinking level for this session (native per engine; null/
224
+ // absent = engine default). Persisted like engine/model.
225
+ reasoningEffort: t.Optional(t.Union([t.String(), t.Null()]))
223
226
  })
224
227
  }, async ({ data, conn }) => {
225
228
  requireSessionAccess(conn, data.chatSessionId);
@@ -239,7 +242,8 @@ export const streamHandler = createRouter()
239
242
  chatSessionId: data.chatSessionId,
240
243
  engine: data.engine,
241
244
  sender: data.sender,
242
- profileId: data.profileId
245
+ profileId: data.profileId,
246
+ reasoningEffort: data.reasoningEffort
243
247
  });
244
248
 
245
249
  debug.log('chat', 'Stream started with ID:', streamId);
@@ -867,6 +871,33 @@ export const streamHandler = createRouter()
867
871
  });
868
872
  })
869
873
 
874
+ // Collaborative reasoning-effort sync — broadcast + persist the per-session
875
+ // reasoning/thinking level, mirroring chat:model-sync. Choosing a level is a
876
+ // per-run choice like the model/account.
877
+ .on('chat:reasoning-sync', {
878
+ data: t.Object({
879
+ senderId: t.String(),
880
+ chatSessionId: t.String(),
881
+ reasoningEffort: t.Union([t.String(), t.Null()])
882
+ })
883
+ }, ({ data, conn }) => {
884
+ requireSessionAccess(conn, data.chatSessionId);
885
+ const chatSessionId = data.chatSessionId;
886
+
887
+ // Persist to the session record so refreshes and late joiners get it.
888
+ try {
889
+ sessionQueries.updateReasoning(chatSessionId, data.reasoningEffort);
890
+ } catch (err) {
891
+ debug.error('chat', 'Failed to persist reasoning sync to DB:', err);
892
+ }
893
+
894
+ // Broadcast to all users in the same chat session
895
+ ws.emit.chatSession(chatSessionId, 'chat:reasoning-sync', {
896
+ senderId: data.senderId,
897
+ reasoningEffort: data.reasoningEffort
898
+ });
899
+ })
900
+
870
901
  // Collaborative profile sync — broadcast + persist the per-session active
871
902
  // profile, mirroring chat:model-sync. Non-admin: choosing a profile is a run
872
903
  // choice like the model, not an admin mutation of the profile itself.
@@ -929,6 +960,11 @@ export const streamHandler = createRouter()
929
960
  profileId: t.Union([t.Number(), t.Null()])
930
961
  }))
931
962
 
963
+ .emit('chat:reasoning-sync', t.Object({
964
+ senderId: t.String(),
965
+ reasoningEffort: t.Union([t.String(), t.Null()])
966
+ }))
967
+
932
968
  .emit('chat:connection', t.Object({
933
969
  processId: t.String(),
934
970
  timestamp: t.String(),
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Device Info
3
+ *
4
+ * HTTP endpoint reporting general information about the machine running clopen
5
+ * (the server), designed to work both on a local desktop/laptop and on a
6
+ * headless VPS.
7
+ *
8
+ * Cross-platform notes:
9
+ * - Battery is absent on desktops/VPS — `battery.hasBattery` is false there.
10
+ * - GPU utilization is best-effort: macOS and most headless Linux servers do
11
+ * not expose it (only NVIDIA via nvidia-smi typically does), so util fields
12
+ * are `null` when unavailable rather than a misleading `0`.
13
+ *
14
+ * Static facts (OS, CPU model, core count, GPU model, virtualization) are
15
+ * captured once per process; dynamic metrics (load, memory, battery, disk,
16
+ * GPU utilization) are recomputed on every request so the panel can poll live.
17
+ */
18
+
19
+ import { t } from 'elysia';
20
+ import os from 'node:os';
21
+ import si from 'systeminformation';
22
+ import type { Systeminformation } from 'systeminformation';
23
+ import { createRouter } from '$shared/utils/ws-server';
24
+
25
+ interface StaticInfo {
26
+ hostname: string;
27
+ platform: string;
28
+ distro: string;
29
+ release: string;
30
+ kernel: string;
31
+ arch: string;
32
+ isVirtual: boolean;
33
+ cpuBrand: string;
34
+ cpuManufacturer: string;
35
+ physicalCores: number;
36
+ logicalCores: number;
37
+ cpuSpeedGhz: number | null;
38
+ gpus: Array<{ model: string; vendor: string; vramMb: number | null }>;
39
+ }
40
+
41
+ /** Static facts don't change while the process runs — resolve them once. */
42
+ let staticInfoPromise: Promise<StaticInfo> | null = null;
43
+
44
+ async function getStaticInfo(): Promise<StaticInfo> {
45
+ if (!staticInfoPromise) {
46
+ staticInfoPromise = (async () => {
47
+ const [osInfo, cpu, system, graphics] = await Promise.all([
48
+ si.osInfo(),
49
+ si.cpu(),
50
+ si.system(),
51
+ si.graphics()
52
+ ]);
53
+ return {
54
+ hostname: osInfo.hostname || os.hostname(),
55
+ platform: osInfo.platform,
56
+ distro: osInfo.distro,
57
+ release: osInfo.release,
58
+ kernel: osInfo.kernel,
59
+ arch: osInfo.arch || os.arch(),
60
+ isVirtual: Boolean(system.virtual),
61
+ cpuBrand: cpu.brand,
62
+ cpuManufacturer: cpu.manufacturer,
63
+ physicalCores: cpu.physicalCores || cpu.cores,
64
+ logicalCores: cpu.cores,
65
+ cpuSpeedGhz: typeof cpu.speed === 'number' && cpu.speed > 0 ? cpu.speed : null,
66
+ gpus: graphics.controllers.map((c) => ({
67
+ model: c.model || 'Unknown GPU',
68
+ vendor: c.vendor || 'Unknown',
69
+ vramMb: typeof c.vram === 'number' && c.vram > 0 ? c.vram : null
70
+ }))
71
+ };
72
+ })().catch((err) => {
73
+ // Don't cache a failed probe — allow the next request to retry.
74
+ staticInfoPromise = null;
75
+ throw err;
76
+ });
77
+ }
78
+ return staticInfoPromise;
79
+ }
80
+
81
+ const GpuSchema = t.Object({
82
+ model: t.String(),
83
+ vendor: t.String(),
84
+ vramMb: t.Union([t.Number(), t.Null()]),
85
+ utilizationGpu: t.Union([t.Number(), t.Null()]),
86
+ memoryUsedMb: t.Union([t.Number(), t.Null()]),
87
+ memoryTotalMb: t.Union([t.Number(), t.Null()])
88
+ });
89
+
90
+ const DiskSchema = t.Object({
91
+ mount: t.String(),
92
+ type: t.String(),
93
+ sizeBytes: t.Number(),
94
+ usedBytes: t.Number(),
95
+ usePercent: t.Number()
96
+ });
97
+
98
+ const BatterySchema = t.Object({
99
+ hasBattery: t.Boolean(),
100
+ percent: t.Union([t.Number(), t.Null()]),
101
+ isCharging: t.Boolean(),
102
+ acConnected: t.Boolean(),
103
+ timeRemainingMinutes: t.Union([t.Number(), t.Null()])
104
+ });
105
+
106
+ /** Filesystem pseudo/virtual types that never represent a real disk. */
107
+ const PSEUDO_FS_TYPES = new Set([
108
+ 'tmpfs', 'devtmpfs', 'devfs', 'overlay', 'squashfs', 'autofs',
109
+ 'none', 'nullfs', 'fuse', 'fuseblk', 'tracefs', 'proc', 'sysfs'
110
+ ]);
111
+
112
+ /** Mount-point prefixes that are OS internals, not user-facing storage. */
113
+ const INTERNAL_MOUNT_PREFIXES = ['/private', '/dev', '/nix', '/Library/Developer', '/System/Library'];
114
+
115
+ interface DiskInfo {
116
+ mount: string;
117
+ type: string;
118
+ sizeBytes: number;
119
+ usedBytes: number;
120
+ usePercent: number;
121
+ }
122
+
123
+ /**
124
+ * Reduce the raw filesystem list to just the primary disk(s).
125
+ *
126
+ * The raw list is noisy — especially on macOS, where APFS exposes a dozen
127
+ * synthetic volumes (Preboot, VM, Update, xarts, Data, …) that all share one
128
+ * physical container, plus tiny 500 MB system volumes. We drop pseudo
129
+ * filesystems and OS-internal mounts, then on macOS collapse each physical
130
+ * container (grouped by identical total size) down to the volume that actually
131
+ * holds the data (highest usage) so the user sees one meaningful entry.
132
+ */
133
+ function selectPrimaryDisks(raw: Systeminformation.FsSizeData[], platform: string): DiskInfo[] {
134
+ const isMac = platform === 'darwin';
135
+
136
+ const candidates = raw.filter((d) => {
137
+ if (!d.size || d.size <= 0) return false;
138
+ if (PSEUDO_FS_TYPES.has((d.type || '').toLowerCase())) return false;
139
+ if (d.mount === '/') return true; // root is always primary
140
+ if (INTERNAL_MOUNT_PREFIXES.some((p) => d.mount.startsWith(p))) return false;
141
+ // macOS: keep only the real Data volume among the /System/Volumes/* set.
142
+ if (d.mount.startsWith('/System/Volumes/') && d.mount !== '/System/Volumes/Data') return false;
143
+ // Drop sub-1 GB helper volumes (boot/EFI/recovery) — not "main" storage.
144
+ return d.size >= 1024 ** 3;
145
+ });
146
+
147
+ // macOS: many volumes map to one physical container (identical total size).
148
+ // Keep the fullest representative per container so we show one entry per disk.
149
+ const chosen = isMac
150
+ ? [
151
+ ...candidates
152
+ .reduce((byContainer, d) => {
153
+ const cur = byContainer.get(d.size);
154
+ if (!cur || d.used > cur.used) byContainer.set(d.size, d);
155
+ return byContainer;
156
+ }, new Map<number, Systeminformation.FsSizeData>())
157
+ .values()
158
+ ]
159
+ : candidates;
160
+
161
+ return chosen
162
+ .map((d) => ({
163
+ // Relabel the collapsed macOS container as the root drive instead of an
164
+ // internal path like /System/Volumes/Data.
165
+ mount: isMac && d.mount.startsWith('/System/Volumes/') ? '/' : d.mount,
166
+ type: d.type,
167
+ sizeBytes: d.size,
168
+ usedBytes: d.used,
169
+ usePercent: typeof d.use === 'number' ? d.use : d.used / d.size * 100
170
+ }))
171
+ // Root first, then largest disks.
172
+ .sort((a, b) => (a.mount === '/' ? -1 : b.mount === '/' ? 1 : b.sizeBytes - a.sizeBytes));
173
+ }
174
+
175
+ export const deviceInfoHandler = createRouter()
176
+ .http('system:device-info', {
177
+ data: t.Object({}),
178
+ response: t.Object({
179
+ hostname: t.String(),
180
+ platform: t.String(),
181
+ distro: t.String(),
182
+ release: t.String(),
183
+ kernel: t.String(),
184
+ arch: t.String(),
185
+ isVirtual: t.Boolean(),
186
+ uptimeSec: t.Number(),
187
+ cpu: t.Object({
188
+ brand: t.String(),
189
+ manufacturer: t.String(),
190
+ physicalCores: t.Number(),
191
+ logicalCores: t.Number(),
192
+ speedGhz: t.Union([t.Number(), t.Null()]),
193
+ loadPercent: t.Number(),
194
+ loadAvg1: t.Union([t.Number(), t.Null()])
195
+ }),
196
+ memory: t.Object({
197
+ totalBytes: t.Number(),
198
+ usedBytes: t.Number(),
199
+ freeBytes: t.Number(),
200
+ swapTotalBytes: t.Number(),
201
+ swapUsedBytes: t.Number()
202
+ }),
203
+ network: t.Object({
204
+ iface: t.String(),
205
+ ip4: t.String(),
206
+ mac: t.String()
207
+ }),
208
+ battery: BatterySchema,
209
+ gpus: t.Array(GpuSchema),
210
+ disks: t.Array(DiskSchema)
211
+ })
212
+ }, async () => {
213
+ const staticInfo = await getStaticInfo();
214
+
215
+ const [load, mem, battery, graphics, fsSize, netDefault] = await Promise.all([
216
+ si.currentLoad(),
217
+ si.mem(),
218
+ si.battery(),
219
+ si.graphics(),
220
+ si.fsSize(),
221
+ si.networkInterfaces('default')
222
+ ]);
223
+
224
+ // networkInterfaces('default') returns the single default interface, but
225
+ // normalize defensively in case a build returns an array.
226
+ const net = Array.isArray(netDefault) ? netDefault[0] : netDefault;
227
+
228
+ // avgLoad is 0/undefined on platforms without load average (e.g. Windows).
229
+ const loadAvg1 = typeof load.avgLoad === 'number' && load.avgLoad > 0 ? load.avgLoad : null;
230
+
231
+ // Pair live GPU utilization with the cached controller identity by index.
232
+ const gpus = staticInfo.gpus.map((g, i) => {
233
+ const live = graphics.controllers[i];
234
+ return {
235
+ model: g.model,
236
+ vendor: g.vendor,
237
+ vramMb: g.vramMb,
238
+ utilizationGpu: live && typeof live.utilizationGpu === 'number' ? live.utilizationGpu : null,
239
+ memoryUsedMb: live && typeof live.memoryUsed === 'number' ? live.memoryUsed : null,
240
+ memoryTotalMb: live && typeof live.memoryTotal === 'number' ? live.memoryTotal : null
241
+ };
242
+ });
243
+
244
+ // Show only the primary disk(s); collapses macOS APFS synthetic volumes.
245
+ const disks = selectPrimaryDisks(fsSize, staticInfo.platform);
246
+
247
+ return {
248
+ hostname: staticInfo.hostname,
249
+ platform: staticInfo.platform,
250
+ distro: staticInfo.distro,
251
+ release: staticInfo.release,
252
+ kernel: staticInfo.kernel,
253
+ arch: staticInfo.arch,
254
+ isVirtual: staticInfo.isVirtual,
255
+ uptimeSec: os.uptime(),
256
+ cpu: {
257
+ brand: staticInfo.cpuBrand,
258
+ manufacturer: staticInfo.cpuManufacturer,
259
+ physicalCores: staticInfo.physicalCores,
260
+ logicalCores: staticInfo.logicalCores,
261
+ speedGhz: staticInfo.cpuSpeedGhz,
262
+ loadPercent: typeof load.currentLoad === 'number' ? load.currentLoad : 0,
263
+ loadAvg1
264
+ },
265
+ memory: {
266
+ totalBytes: mem.total,
267
+ usedBytes: mem.active,
268
+ freeBytes: mem.available,
269
+ swapTotalBytes: mem.swaptotal,
270
+ swapUsedBytes: mem.swapused
271
+ },
272
+ network: {
273
+ iface: net?.iface || '',
274
+ ip4: net?.ip4 || '',
275
+ mac: net?.mac || ''
276
+ },
277
+ battery: {
278
+ hasBattery: Boolean(battery.hasBattery),
279
+ percent: typeof battery.percent === 'number' && battery.hasBattery ? battery.percent : null,
280
+ isCharging: Boolean(battery.isCharging),
281
+ acConnected: Boolean(battery.acConnected),
282
+ timeRemainingMinutes:
283
+ typeof battery.timeRemaining === 'number' && battery.timeRemaining > 0
284
+ ? battery.timeRemaining
285
+ : null
286
+ },
287
+ gpus,
288
+ disks
289
+ };
290
+ });
@@ -10,9 +10,11 @@
10
10
  import { createRouter } from '$shared/utils/ws-server';
11
11
  import { t } from 'elysia';
12
12
  import { operationsHandler } from './operations';
13
+ import { deviceInfoHandler } from './device-info';
13
14
 
14
15
  export const systemRouter = createRouter()
15
16
  .merge(operationsHandler)
17
+ .merge(deviceInfoHandler)
16
18
  // Declare system:update-completed event (broadcast after successful package update)
17
19
  .emit('system:update-completed', t.Object({
18
20
  fromVersion: t.String(),
@@ -17,6 +17,7 @@ import { debug } from '$shared/utils/logger';
17
17
  import { ws } from '$backend/utils/ws';
18
18
  import { getClopenDir } from '$backend/utils/index';
19
19
  import { resetEnvironment } from '$backend/engine/adapters/claude/environment';
20
+ import { bootstrapAfterDbInit } from '$backend/bootstrap';
20
21
 
21
22
  /** In-memory flag: set after successful update, cleared on server restart */
22
23
  let pendingUpdate: { fromVersion: string; toVersion: string } | null = null;
@@ -198,6 +199,12 @@ export const operationsHandler = createRouter()
198
199
  // Reinitialize database from scratch (creates dir, db, migrations, seeders)
199
200
  await initializeDatabase();
200
201
 
202
+ // Re-establish code-defined built-ins that migrations/seeders don't cover
203
+ // (internal MCP servers like Browser Automation + the default engine).
204
+ // The process stays alive across clear-data, so without this they'd vanish
205
+ // until the next restart.
206
+ bootstrapAfterDbInit();
207
+
201
208
  debug.log('server', 'All data cleared successfully');
202
209
 
203
210
  return {
@@ -111,7 +111,8 @@ export const crudHandler = createRouter()
111
111
  settings: t.Union([t.Any(), t.Null()]),
112
112
  unreadSessions: t.Union([t.Any(), t.Null()]),
113
113
  todoPanelState: t.Union([t.Any(), t.Null()]),
114
- projectOrder: t.Union([t.Array(t.String()), t.Null()])
114
+ projectOrder: t.Union([t.Array(t.String()), t.Null()]),
115
+ commandUsage: t.Union([t.Any(), t.Null()])
115
116
  })
116
117
  }, async ({ conn }) => {
117
118
  const userId = ws.getUserId(conn);
@@ -122,6 +123,7 @@ export const crudHandler = createRouter()
122
123
  const unreadSessions = getUserState(userId, 'unreadSessions');
123
124
  const todoPanelState = getUserState(userId, 'todoPanelState');
124
125
  const projectOrder = getUserState(userId, 'projectOrder');
126
+ const commandUsage = getUserState(userId, 'commandUsage');
125
127
 
126
128
  debug.log('user', `Restored state for ${userId}:`, {
127
129
  currentProjectId,
@@ -137,7 +139,8 @@ export const crudHandler = createRouter()
137
139
  settings: userSettings ?? null,
138
140
  unreadSessions: unreadSessions ?? null,
139
141
  todoPanelState: todoPanelState ?? null,
140
- projectOrder: Array.isArray(projectOrder) ? projectOrder : null
142
+ projectOrder: Array.isArray(projectOrder) ? projectOrder : null,
143
+ commandUsage: commandUsage ?? null
141
144
  };
142
145
  })
143
146
 
@@ -154,7 +157,7 @@ export const crudHandler = createRouter()
154
157
  const userId = ws.getUserId(conn);
155
158
 
156
159
  // Validate allowed keys to prevent arbitrary data storage
157
- const allowedKeys = ['currentProjectId', 'lastView', 'settings', 'unreadSessions', 'todoPanelState', 'projectOrder'];
160
+ const allowedKeys = ['currentProjectId', 'lastView', 'settings', 'unreadSessions', 'todoPanelState', 'projectOrder', 'commandUsage'];
158
161
  if (!allowedKeys.includes(data.key)) {
159
162
  throw new Error(`Invalid state key: ${data.key}. Allowed: ${allowedKeys.join(', ')}`);
160
163
  }
@@ -1 +1 @@
1
- import{s as _,_ as d,r as s,a as u}from"./main-BBxAj17T.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-BBxAj17T.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-D-2ByODy.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-D-2ByODy.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};