@myrialabs/clopen 0.4.20 → 0.4.22

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 (116) hide show
  1. package/README.md +2 -1
  2. package/backend/artifacts/generate.ts +11 -5
  3. package/backend/auth/permissions.ts +8 -8
  4. package/backend/bootstrap.ts +39 -0
  5. package/backend/chat/stream-manager.ts +15 -0
  6. package/backend/database/migrations/065_add_session_reasoning_effort.ts +28 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/session-queries.ts +10 -0
  9. package/backend/engine/README.md +11 -8
  10. package/backend/engine/adapters/claude/models.ts +46 -23
  11. package/backend/engine/adapters/claude/stream.ts +18 -4
  12. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  13. package/backend/engine/adapters/codex/models.ts +19 -2
  14. package/backend/engine/adapters/codex/stream.ts +10 -3
  15. package/backend/engine/adapters/copilot/models.ts +20 -1
  16. package/backend/engine/adapters/copilot/stream.ts +11 -1
  17. package/backend/engine/adapters/cursor/models.ts +27 -3
  18. package/backend/engine/adapters/cursor/stream.ts +23 -3
  19. package/backend/engine/adapters/pi/models.ts +20 -2
  20. package/backend/engine/adapters/pi/stream.ts +6 -3
  21. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  22. package/backend/engine/bootstrap-default-engine.ts +18 -5
  23. package/backend/engine/docs/adapter-contract.md +66 -2
  24. package/backend/engine/docs/adding-an-engine.md +46 -7
  25. package/backend/engine/docs/frontend-and-chat.md +80 -17
  26. package/backend/engine/docs/lessons-learned.md +126 -7
  27. package/backend/engine/docs/quick-reference.md +12 -3
  28. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  29. package/backend/engine/docs/websocket-routes.md +54 -15
  30. package/backend/engine/install-runner.ts +4 -4
  31. package/backend/engine/resolve-model.ts +87 -0
  32. package/backend/engine/structured-helpers.test.ts +64 -0
  33. package/backend/engine/structured-helpers.ts +105 -13
  34. package/backend/engine/types.ts +6 -0
  35. package/backend/index.ts +6 -9
  36. package/backend/mcp/README.md +32 -11
  37. package/backend/mcp/internal/config.ts +3 -20
  38. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  39. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  40. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  41. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  42. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  43. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  44. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  45. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +146 -0
  46. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +63 -0
  47. package/backend/mcp/internal/servers/browser-automation/context.ts +82 -0
  48. package/backend/mcp/internal/servers/browser-automation/description.ts +59 -0
  49. package/backend/mcp/internal/servers/browser-automation/format.ts +56 -0
  50. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  51. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  52. package/backend/mcp/internal/servers/browser-automation/runner.ts +260 -0
  53. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  54. package/backend/preview/browser/browser-console-manager.ts +310 -156
  55. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  56. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  57. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  58. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  59. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  60. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  61. package/backend/preview/browser/browser-pool.ts +83 -9
  62. package/backend/preview/browser/browser-preview-service.ts +432 -53
  63. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  64. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  65. package/backend/preview/browser/capture-profile.ts +213 -0
  66. package/backend/preview/browser/element-locator.ts +357 -0
  67. package/backend/preview/browser/frame-targeting.ts +92 -0
  68. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  69. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  70. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  71. package/backend/preview/browser/types.ts +397 -37
  72. package/backend/utils/cli.ts +1 -1
  73. package/backend/utils/path-enrich.ts +2 -2
  74. package/backend/ws/README.md +1 -1
  75. package/backend/ws/artifacts/generate.ts +2 -1
  76. package/backend/ws/chat/stream.ts +38 -2
  77. package/backend/ws/engine/codex/accounts.ts +1 -1
  78. package/backend/ws/engine/codex/status.ts +1 -1
  79. package/backend/ws/git/branch-name.ts +11 -5
  80. package/backend/ws/git/commit-message.ts +11 -5
  81. package/backend/ws/index.ts +3 -3
  82. package/backend/ws/preview/browser/host.ts +95 -0
  83. package/backend/ws/preview/browser/interact.ts +204 -10
  84. package/backend/ws/preview/browser/native-ui.ts +31 -1
  85. package/backend/ws/preview/browser/tab-info.ts +10 -1
  86. package/backend/ws/preview/browser/tab.ts +43 -0
  87. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  88. package/backend/ws/preview/index.ts +58 -1
  89. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  90. package/backend/ws/stack/index.ts +16 -0
  91. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  92. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  93. package/backend/ws/system/device-info.ts +290 -0
  94. package/backend/ws/system/index.ts +2 -0
  95. package/backend/ws/system/operations.ts +7 -0
  96. package/backend/ws/user/crud.ts +6 -3
  97. package/dist/assets/{index-BqBxKeAv.js → index-DH_GO0Lf.js} +1 -1
  98. package/dist/assets/{index-DdrcY5TE.js → index-igSQ3JaM.js} +1 -1
  99. package/dist/assets/main-BD3-qPfT.css +1 -0
  100. package/dist/assets/main-D-d8SFfW.js +616 -0
  101. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +2 -1
  104. package/shared/constants/engines.ts +23 -0
  105. package/shared/types/database/schema.ts +1 -0
  106. package/shared/types/stores/settings.ts +12 -0
  107. package/shared/types/unified/engine.ts +33 -0
  108. package/shared/types/unified/index.ts +2 -0
  109. package/shared/types/unified/message.ts +6 -0
  110. package/shared/types/unified/stream.ts +6 -0
  111. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  112. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  113. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  114. package/backend/ws/system-tools/index.ts +0 -16
  115. package/dist/assets/main-BBxAj17T.js +0 -582
  116. package/dist/assets/main-Cry3pLcl.css +0 -1
@@ -211,7 +211,16 @@ export class CopilotEngine implements AIEngine {
211
211
  }
212
212
 
213
213
  async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
214
- const { projectPath, prompt, resume, modelId, abortController, accountId } = options;
214
+ const { projectPath, prompt, resume, modelId, reasoningEffort, abortController, accountId } = options;
215
+
216
+ // Copilot's `reasoningEffort` accepts low | medium | high | xhigh; only
217
+ // applied for models that support it (unsupported tokens are dropped so
218
+ // the SDK falls back to the model default).
219
+ const copilotEfforts = new Set<string>(['low', 'medium', 'high', 'xhigh']);
220
+ const reasoningOption: Pick<ResumeSessionConfig, 'reasoningEffort'> | Record<string, never> =
221
+ reasoningEffort && copilotEfforts.has(reasoningEffort)
222
+ ? { reasoningEffort: reasoningEffort as ResumeSessionConfig['reasoningEffort'] }
223
+ : {};
215
224
 
216
225
  // Per-stream account override: the Copilot SDK takes the GitHub token at
217
226
  // construction time, so an account switch requires recreating the client.
@@ -346,6 +355,7 @@ export class CopilotEngine implements AIEngine {
346
355
  });
347
356
  },
348
357
  model: modelId,
358
+ ...reasoningOption,
349
359
  workingDirectory: resolvedProjectPath,
350
360
  onEvent: handler,
351
361
  // Emit assistant.message_delta / assistant.reasoning_delta events
@@ -16,7 +16,9 @@
16
16
  * unavailable (empty or errored). Only a missing account/key returns `[]`.
17
17
  */
18
18
 
19
- import type { EngineModel } from '$shared/types/unified';
19
+ import type { ModelListItem, ModelParameterDefinition } from '@cursor/sdk';
20
+ import type { EngineModel, ReasoningControl } from '$shared/types/unified';
21
+ import { reasoningLevelLabel } from '$shared/constants/engines';
20
22
  import { debug } from '$shared/utils/logger';
21
23
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
22
24
  import { getActiveCursorAccount, parseCursorCredential } from './credential';
@@ -35,7 +37,7 @@ export async function fetchCursorModels(): Promise<EngineModel[]> {
35
37
  const models = await Cursor.models.list({ apiKey });
36
38
  if (models.length) {
37
39
  debug.log('engine', `Cursor getAvailableModels: ${models.length} models`);
38
- return models.map(m => makeModel(m.id, m.displayName || m.id));
40
+ return models.map(m => makeModel(m.id, m.displayName || m.id, m));
39
41
  }
40
42
  debug.warn('engine', 'Cursor models.list returned empty — using fallback catalog');
41
43
  } catch (error) {
@@ -44,7 +46,28 @@ export async function fetchCursorModels(): Promise<EngineModel[]> {
44
46
  return CURSOR_FALLBACK_MODEL_IDS.map(id => makeModel(id, id));
45
47
  }
46
48
 
47
- function makeModel(id: string, name: string): EngineModel {
49
+ /**
50
+ * Cursor exposes reasoning as a per-model `ModelParameterDefinition` (a
51
+ * dropdown of values) selected via `ModelSelection.params`. We surface it as a
52
+ * reasoning control when a model advertises a parameter whose id looks like a
53
+ * reasoning/thinking/effort toggle. The option `value` encodes the parameter id
54
+ * as `"<paramId>::<value>"` so the stream adapter can rebuild the params entry
55
+ * without re-fetching the catalog. Best-effort — absent when no such parameter.
56
+ */
57
+ function buildCursorReasoningControl(item?: ModelListItem): ReasoningControl | undefined {
58
+ const params = item?.parameters;
59
+ if (!params?.length) return undefined;
60
+ const param: ModelParameterDefinition | undefined = params.find(p => /reason|think|effort/i.test(p.id));
61
+ if (!param || !param.values?.length) return undefined;
62
+ const levels = param.values.map(v => ({
63
+ value: `${param.id}::${v.value}`,
64
+ label: v.displayName ?? reasoningLevelLabel(v.value),
65
+ }));
66
+ return { levels, default: levels[0].value };
67
+ }
68
+
69
+ function makeModel(id: string, name: string, item?: ModelListItem): EngineModel {
70
+ const reasoningControl = buildCursorReasoningControl(item);
48
71
  return {
49
72
  engine: {
50
73
  type: 'cursor',
@@ -63,6 +86,7 @@ function makeModel(id: string, name: string): EngineModel {
63
86
  reasoning: true,
64
87
  tools: true,
65
88
  structuredOutput: false,
89
+ ...(reasoningControl && { reasoningControl }),
66
90
  },
67
91
  cost: { input: 0, output: 0 },
68
92
  };
@@ -21,7 +21,7 @@
21
21
  * to Cursor's native `agents` config.
22
22
  */
23
23
 
24
- import type { SDKAgent, Run, SDKUserMessage, SDKImage, AgentDefinition, SDKCustomTool } from '@cursor/sdk';
24
+ import type { SDKAgent, Run, SDKUserMessage, SDKImage, AgentDefinition, SDKCustomTool, ModelSelection } from '@cursor/sdk';
25
25
  import type { EngineOutput, EngineModel, MessageEngine } from '$shared/types/unified';
26
26
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
27
27
  import { resolveOsPath } from '$backend/utils/paths';
@@ -82,6 +82,21 @@ class EventQueue<T> {
82
82
  }
83
83
  }
84
84
 
85
+ /**
86
+ * Build a Cursor `ModelSelection` from the base model id and the chosen
87
+ * reasoning token. The token encodes the model-parameter id as
88
+ * `"<paramId>::<value>"` (see cursor/models.ts). A plain id (no `::`) or an
89
+ * empty token yields the bare model with no params.
90
+ */
91
+ function buildCursorModelSelection(modelId: string, reasoningEffort?: string): ModelSelection {
92
+ if (!reasoningEffort || !reasoningEffort.includes('::')) return { id: modelId };
93
+ const sep = reasoningEffort.indexOf('::');
94
+ const paramId = reasoningEffort.slice(0, sep);
95
+ const value = reasoningEffort.slice(sep + 2);
96
+ if (!paramId || !value) return { id: modelId };
97
+ return { id: modelId, params: [{ id: paramId, value }] };
98
+ }
99
+
85
100
  export class CursorEngine implements AIEngine {
86
101
  readonly name = 'cursor' as const;
87
102
  private _isInitialized = false;
@@ -123,9 +138,14 @@ export class CursorEngine implements AIEngine {
123
138
  }
124
139
 
125
140
  async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
126
- const { projectPath, prompt, resume, modelId, abortController, accountId } = options;
141
+ const { projectPath, prompt, resume, modelId, reasoningEffort, abortController, accountId } = options;
127
142
  debug.log('chat', 'Cursor - Stream Query', { modelId, resume });
128
143
 
144
+ // Cursor selects reasoning via a per-model parameter. The catalog encodes
145
+ // the chosen level as `"<paramId>::<value>"` (see cursor/models.ts); rebuild
146
+ // the `ModelSelection.params` entry here. Absent/malformed → base model.
147
+ const modelSelection = buildCursorModelSelection(modelId, reasoningEffort);
148
+
129
149
  // ── Resolve account + API key ──
130
150
  const account = (accountId != null ? engineQueries.getAccount(accountId) : null) ?? getActiveCursorAccount();
131
151
  if (!account) {
@@ -228,7 +248,7 @@ export class CursorEngine implements AIEngine {
228
248
  let onAbort: (() => void) | null = null;
229
249
  try {
230
250
  const run = await agent.send(userMessage, {
231
- model: { id: modelId },
251
+ model: modelSelection,
232
252
  // Sub-agent (Task) steps aren't in `run.stream()` — they ride
233
253
  // `tool-call-delta.taskUpdate` here. Stream each completed sub-agent
234
254
  // tool call live as a child of the Agent block (parent.toolUseId).
@@ -13,7 +13,9 @@
13
13
  */
14
14
 
15
15
  import type { Api, Model } from '@earendil-works/pi-ai';
16
- import type { EngineModel } from '$shared/types/unified';
16
+ import { getSupportedThinkingLevels, clampThinkingLevel } from '@earendil-works/pi-ai';
17
+ import type { EngineModel, ReasoningControl } from '$shared/types/unified';
18
+ import { toReasoningOptions } from '$shared/constants/engines';
17
19
  import { debug } from '$shared/utils/logger';
18
20
  import { DbCredentialStore, getPiAccounts } from './credential';
19
21
  import { createPiRuntime } from './presets';
@@ -33,8 +35,24 @@ export async function fetchPiModels(): Promise<EngineModel[]> {
33
35
  }
34
36
  }
35
37
 
38
+ /**
39
+ * Pi's reasoning knob is the agent `thinkingLevel`. The pi-ai catalog reports
40
+ * the supported levels per model (`getSupportedThinkingLevels`), so the control
41
+ * is fully model-driven. Skipped when a model only supports `off` (no reasoning).
42
+ */
43
+ function buildPiReasoningControl(model: Model<Api>): ReasoningControl | undefined {
44
+ const levels = getSupportedThinkingLevels(model);
45
+ if (levels.length <= 1) return undefined;
46
+ const fallback = model.reasoning ? clampThinkingLevel(model, 'medium') : 'off';
47
+ return {
48
+ levels: toReasoningOptions(levels),
49
+ default: fallback,
50
+ };
51
+ }
52
+
36
53
  function mapPiModel(model: Model<Api>): EngineModel {
37
54
  const image = model.input.includes('image');
55
+ const reasoningControl = buildPiReasoningControl(model);
38
56
  return {
39
57
  engine: {
40
58
  type: 'pi',
@@ -47,7 +65,7 @@ function mapPiModel(model: Model<Api>): EngineModel {
47
65
  input: { text: true, image, audio: false, video: false, pdf: false },
48
66
  output: { text: true, image: false, audio: false, video: false, pdf: false },
49
67
  },
50
- capabilities: { reasoning: !!model.reasoning, tools: true, structuredOutput: true },
68
+ capabilities: { reasoning: !!model.reasoning, tools: true, structuredOutput: true, ...(reasoningControl && { reasoningControl }) },
51
69
  cost: { input: model.cost?.input ?? 0, output: model.cost?.output ?? 0 },
52
70
  };
53
71
  }
@@ -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,
@@ -30,7 +30,7 @@ export function handleStreamError(error: unknown, stderrTail?: string): void {
30
30
  const tailLower = tail.toLowerCase();
31
31
 
32
32
  if (error.message.includes('ENOENT') || error.message.includes('spawn qwen')) {
33
- throw new Error('Qwen Code CLI not found. Install it via Settings → System Tools (or `bun add -g @qwen-code/qwen-code`).');
33
+ throw new Error('Qwen Code CLI not found. Install it via Settings → Stack (or `bun add -g @qwen-code/qwen-code`).');
34
34
  }
35
35
 
36
36
  if (
@@ -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');
@@ -26,7 +26,7 @@ export interface AIEngine {
26
26
  }
27
27
  ```
28
28
 
29
- Three invariants:
29
+ Four invariants:
30
30
 
31
31
  1. **`streamQuery` is the only streaming output path.** It is an
32
32
  `AsyncGenerator<EngineOutput>`. The adapter translates SDK events into
@@ -40,6 +40,14 @@ Three invariants:
40
40
  callers **must** share a single init promise. See:
41
41
  - `claude/environment.ts::setupEnvironmentOnce`
42
42
  - `opencode/server.ts::ensureClient`
43
+ 4. **`generateStructured` callers resolve their target first.** The
44
+ `providerSlug` a client hands to a one-shot JSON call is a *hint*, not
45
+ truth — every call site pipes it through
46
+ `resolveGenerationTarget(engine, modelId, providerHint)`
47
+ (`backend/engine/resolve-model.ts`) and uses what comes back. The engine's
48
+ own catalog is the only source of truth for which provider (and account) a
49
+ model belongs to. Skipping this "works" on the five engines that ignore the
50
+ slug and fails on OpenCode, Pi, and Cline. See §10.16 point 3.
43
51
 
44
52
  ### 2.2 `index.ts` — registry & lifecycle
45
53
 
@@ -98,7 +106,8 @@ interface EngineQueryOptions {
98
106
  forkSession?: boolean;
99
107
  maxTurns?: number;
100
108
  providerSlug: string; // 'anthropic', 'openai', etc — required for opencode
101
- modelId: string; // 'claude-opus-4-7', 'gpt-5', etc
109
+ modelId: string; // 'claude-opus-5', 'gpt-5', etc
110
+ reasoningEffort?: string; // native reasoning/thinking level for this turn
102
111
  includePartialMessages?: boolean;
103
112
  abortController?: AbortController;
104
113
  accountId?: number; // override credential for a single stream
@@ -110,6 +119,61 @@ interface EngineQueryOptions {
110
119
  **cannot** write into project B. Always forward it: see `claude/stream.ts`
111
120
  calling `getEnabledMcpServers(options.mcpContext)`.
112
121
 
122
+ `reasoningEffort` is an **opaque, native-per-engine token** — there is no
123
+ cross-engine normalization. The adapter that produced the level in
124
+ `models.ts` is the one that consumes it in `stream.ts`; every other layer
125
+ (stream-manager, WS, frontend) just carries the string. `undefined` means
126
+ "no explicit choice" → the engine's own default applies. See §2.4a.
127
+
128
+ ### 2.4a Reasoning effort — `EngineModel.capabilities.reasoningControl`
129
+
130
+ A model may advertise a reasoning/thinking control from its `models.ts`:
131
+
132
+ ```ts
133
+ interface ReasoningControl {
134
+ levels: { value: string; label: string }[]; // ordered low → high
135
+ default: string; // mirrors the engine default
136
+ }
137
+ ```
138
+
139
+ Rules:
140
+
141
+ - **Capability-driven, not hardcoded.** The picker renders a level selector
142
+ **only** when the selected model carries `capabilities.reasoningControl`.
143
+ Omit the field and the UI hides the control entirely — that is how Qwen,
144
+ OpenCode, and Cline stay knob-less without a single `if (engine === …)`
145
+ anywhere in the frontend.
146
+ - **Levels are the SDK's own vocabulary.** Don't invent a shared
147
+ `low|medium|high` scale. Use `toReasoningOptions([...])` from
148
+ `$shared/constants/engines` to attach labels; `reasoningLevelLabel()` maps the
149
+ known tokens (`off`, `auto`/`adaptive`, `minimal` … `max`) and capitalizes
150
+ anything it doesn't recognise.
151
+ - **Derive from the catalog when the SDK reports it.** Copilot reads
152
+ `supportedReasoningEfforts` / `defaultReasoningEffort` off `ModelInfo`, Pi
153
+ reads `getSupportedThinkingLevels(model)`, Cursor reads the model's
154
+ `ModelParameterDefinition`. Only static catalogs (Claude, Codex) hardcode
155
+ the list.
156
+ - **The adapter clamps.** `streamQuery` must treat the incoming token as
157
+ untrusted — an unknown/stale value falls back to the engine default rather
158
+ than being forwarded to the SDK.
159
+
160
+ Where each engine's knob lives:
161
+
162
+ | Engine | SDK knob | Levels |
163
+ |---------------|-----------------------------------------|--------------------------------------------|
164
+ | `claude-code` | `thinking` + `effort` on `query()` | `off, auto, low, medium, high, xhigh, max` (static; `off` → `thinking: { type: 'disabled' }`, `auto` → adaptive with no `effort`) |
165
+ | `codex` | `modelReasoningEffort` (thread option) | `minimal, low, medium, high, xhigh` (static; reasoning-capable models only) |
166
+ | `copilot` | `SessionConfig.reasoningEffort` | from `ModelInfo.supportedReasoningEfforts` (dynamic) |
167
+ | `pi` | agent `thinkingLevel` | from `getSupportedThinkingLevels(model)` (dynamic; `clampThinkingLevel` on apply) |
168
+ | `cursor` | `ModelSelection.params[]` | from the model's reasoning-ish `ModelParameterDefinition` (dynamic) |
169
+ | `qwen`, `opencode`, `cline` | — (none exposed) | no `reasoningControl` → selector hidden |
170
+
171
+ Cursor is the one engine whose token is **not** a bare level: it encodes the
172
+ model-parameter id as `"<paramId>::<value>"` so `stream.ts` can rebuild a
173
+ `ModelSelection.params` entry without re-fetching the catalog. If a future SDK
174
+ needs more than a level name, follow that shape rather than adding a new field
175
+ to `EngineQueryOptions`.
176
+
113
177
  ### 2.5 What an adapter **MUST NOT** do
114
178
 
115
179
  - ❌ Call `ws.emit.*` — that is the stream-manager's job.
@@ -11,8 +11,12 @@ blueprint for the next engine you add.
11
11
  - [ ] `shared/types/unified/common.ts`: add `'newengine'` to `EngineType`.
12
12
  - [ ] `shared/types/unified/engine.ts`: add `'newengine'` to `EngineInfo.type`.
13
13
  - [ ] `shared/types/unified/message.ts`: add `'newengine'` to `MessageEngine.type`.
14
+ - [ ] `shared/constants/tool-icons.ts`: add the brand SVG to `TOOL_ICONS`
15
+ (`{ light, dark }`). This is the single source of truth — Settings →
16
+ Engines, Settings → Stack, the wizard, and the chat picker all read it.
14
17
  - [ ] `shared/constants/engines.ts`: add an entry in `ENGINES[]`
15
- (`type, name, description, icon.light, icon.dark`).
18
+ (`type, name, description, icon: TOOL_ICONS['newengine']`). The array's
19
+ order is the display order everywhere.
16
20
  - [ ] **Exhaustive `Record<EngineType, …>` maps & unions — forgetting any is a
17
21
  compile error, so `bun run check` after this step catches them all:**
18
22
  - `shared/constants/engine-tools.ts`: add `'newengine'` to
@@ -31,6 +35,13 @@ blueprint for the next engine you add.
31
35
  engines export a fetcher (`fetchNewengineModels(...)`) consumed by
32
36
  `getAvailableModels()`. Don't add anything to `shared/constants/engines.ts`
33
37
  for the catalog itself — the frontend loads it via `models:list`.
38
+ - [ ] (Optional) **Reasoning control.** If the SDK exposes a reasoning /
39
+ thinking / effort knob, attach `capabilities.reasoningControl`
40
+ (`{ levels, default }`) to each model that supports it — build the labels
41
+ with `toReasoningOptions([...])` from `$shared/constants/engines`, and
42
+ read the level list off the SDK payload when it reports one (Copilot, Pi,
43
+ Cursor) rather than hardcoding. Omit the field entirely when there is no
44
+ knob; the picker then hides the control. See §2.4a.
34
45
  - [ ] (Optional) `backend/engine/adapters/newengine/presets.ts` if the
35
46
  engine needs provider/region/BYOK presets exposed to the UI.
36
47
  Mirror `qwen/presets.ts`: keep runtime values in the adapter,
@@ -47,7 +58,10 @@ mandatory files; optional files use the canonical names from §2.6.
47
58
  > runtime dependency; it lives in `package.json` `devDependencies` (pinned
48
59
  > exact) and is installed on demand into `~/.clopen/stack/engines`. In the
49
60
  > adapter, reference the SDK's types only via `import type` (erased at runtime)
50
- > and resolve the real module at point of use with
61
+ > — **every** file, not just `stream.ts`; a value import left in a helper
62
+ > (`server.ts`, `models.ts`, `credential.ts`) resolves from the repo's own
63
+ > `node_modules` in dev and only breaks for end users — and resolve the real
64
+ > module at point of use with
51
65
  > `loadEngineSdk<typeof import('<pkg>')>('newengine', '<pkg>')` from
52
66
  > `backend/engine/sdk-loader.ts`. The loader throws `EngineNotReadyError`
53
67
  > (`not-installed` / `needs-update`) when the SDK is absent or version-mismatched,
@@ -94,6 +108,10 @@ mandatory files; optional files use the canonical names from §2.6.
94
108
  event after all messages (Codex, Cursor), assistant rows persist
95
109
  `usage:null` — add the engine to `stream-manager.ts::backfillUsageForStream`'s
96
110
  gate so the turn aggregate is written to every assistant row (see §10.20-I).
111
+ - [ ] **Reasoning effort (if the SDK has a knob):** read `options.reasoningEffort`
112
+ in `streamQuery` and map it onto the SDK's own option. Treat it as
113
+ untrusted — clamp/ignore an unknown token and fall back to the engine
114
+ default rather than forwarding it. See §2.4a for the per-engine table.
97
115
  - [ ] **Context window:** set `EngineModel.limit.input` to the model's real max
98
116
  when the catalog provides it; leave `0` when it doesn't — do NOT hard-code a
99
117
  value. The UI renders `0` as "?" via `getContextUsage(...).unknown` (§10.20-J).
@@ -101,6 +119,12 @@ mandatory files; optional files use the canonical names from §2.6.
101
119
  ...): void` (and any helper formatters specific to the SDK's error
102
120
  payload — see `opencode/error-handler.ts::formatSessionError` for the
103
121
  pattern).
122
+ - [ ] `generateStructured` (optional but expected — it powers AI commit
123
+ messages, branch names, and artifact authoring). Native-schema SDKs pass
124
+ the schema through; the rest use `buildJsonPrompt` + `extractJson` from
125
+ `backend/engine/structured-helpers.ts` on a tool-less one-shot run.
126
+ Leave the method `undefined` if the SDK genuinely can't do it — the WS
127
+ handlers guard on its presence. See §10.16.
104
128
  - [ ] `credential.ts` / `environment.ts` / `server.ts` / `config.ts` /
105
129
  `presets.ts` / `session-fork.ts` (optional; canonical names only).
106
130
  - [ ] Artifacts: in `streamQuery`, call `syncSkills(...)` +
@@ -177,8 +201,7 @@ mandatory files; optional files use the canonical names from §2.6.
177
201
  Engine SDKs are installed **on demand** into the clopen-managed stack dir
178
202
  (`~/.clopen/stack/engines`), not onto the machine's PATH — so you don't write a
179
203
  per-platform recipe. You only declare the pinned package(s); `resolveEngineRecipe()`
180
- handles the install. (The panel is displayed as "Stack"; its WS route/id stays
181
- `system-tools`.)
204
+ handles the install.
182
205
 
183
206
  - [ ] `package.json`: add the engine's SDK package(s) to `devDependencies` at an
184
207
  **exact** pinned version — this is the single source of truth for the
@@ -189,9 +212,9 @@ handles the install. (The panel is displayed as "Stack"; its WS route/id stays
189
212
  imports and detects install-state from; any extras pin a transitive CLI the
190
213
  SDK would otherwise float, e.g. Copilot's `@github/copilot`).
191
214
  - No resolver needed — `resolveEngineRecipe()` picks it up.
192
- - [ ] `backend/ws/system-tools/status.ts` & `install.ts`: add
215
+ - [ ] `backend/ws/stack/status.ts` & `install.ts`: add
193
216
  `'newengine'` to `TOOL_UNION`.
194
- - [ ] `frontend/components/settings/system-tools/SystemToolsSettings.svelte`:
217
+ - [ ] `frontend/components/settings/stack/StackSettings.svelte`:
195
218
  `<ToolInstallCard tool="newengine" title="NewEngine" description="..." />`.
196
219
 
197
220
  ### Stage 8 — Chat input
@@ -210,7 +233,15 @@ heavier — copy the OpenCode block.
210
233
 
211
234
  Other auto wiring:
212
235
  - [ ] The engine tab appears automatically in `EngineModelPicker` from
213
- `ENGINES`.
236
+ `ENGINES`, and its position in the shared `ENGINES` order is the order
237
+ used by every grid, tab strip, and picker (Stack card list included).
238
+ - [ ] The reasoning-level pill appears automatically for any model whose
239
+ catalog entry carries `capabilities.reasoningControl` — no frontend
240
+ change, and no engine name in the component.
241
+ - [ ] The engine's brand icon comes from the single `TOOL_ICONS` registry in
242
+ `shared/constants/tool-icons.ts`, which both `ENGINES` and the Stack
243
+ cards reference. Add the SVG **there only** — never inline it a second
244
+ time.
214
245
  - [ ] Verify: select engine → model list appears → send message → stream
215
246
  runs.
216
247
 
@@ -232,6 +263,14 @@ Then the minimum UI scenarios that must pass:
232
263
  replies → cancel mid-stream → idle → send again → resume works.
233
264
  - [ ] AskUserQuestion (if the SDK supports it) → appears in UI → submit
234
265
  answer → stream continues.
266
+ - [ ] Reasoning effort (if the engine has a knob) → the pill appears for
267
+ models that advertise one and is **absent** for models that don't →
268
+ pick a level → the Raw Message view shows `engine.reasoningEffort` →
269
+ the level survives a refresh (persisted on the session row).
270
+ - [ ] `generateStructured` on a **non-Claude** engine: Git → generate commit
271
+ message, and Artifacts → generate from a purpose. These are the two
272
+ paths that break on a stale `providerSlug` and on JSON with trailing
273
+ prose / raw newlines — Claude Code passing proves nothing (§10.16).
235
274
  - [ ] Restart Clopen → state survives (account, provider, last-used model
236
275
  in chat).
237
276
 
@@ -65,27 +65,30 @@ modelStore // models[], fetchModels(engine), refreshModels(engin
65
65
 
66
66
  ### 5.2 Settings → Stack
67
67
 
68
- The panel is displayed as **Stack** (its internal section id / WS route stays
69
- `system-tools`).
70
-
71
68
  Files:
72
- - `frontend/components/settings/system-tools/SystemToolsSettings.svelte`
73
- - `frontend/components/settings/system-tools/ToolInstallCard.svelte`
69
+ - `frontend/components/settings/stack/StackSettings.svelte`
70
+ - `frontend/components/settings/stack/ToolInstallCard.svelte`
74
71
 
75
- `SystemToolsSettings` renders one `ToolInstallCard` per tool — host tools
72
+ `StackSettings` renders one `ToolInstallCard` per tool — host tools
76
73
  (`git`, `chrome`, `cloudflared`) plus every engine SDK (`claude`, `opencode`,
77
74
  `copilot`, `codex`, `qwen`, `pi`, `cline`, `cursor`). `ToolInstallCard`:
78
75
 
79
- 1. Calls `system-tools:status` on mount.
76
+ 1. Calls `stack:status` on mount.
80
77
  2. Renders: status (installed/version/source; engines also carry
81
78
  `requiredVersion` + `needsUpdate`), an "Install" button if
82
79
  `recipe.autoInstallable`, otherwise a "Manual install" dialog.
83
- 3. While installing: `system-tools:install-start` → subscribe to
84
- `system-tools:install-stream` (per-line) → render in xterm + show
85
- exit status from `system-tools:install-finished`.
80
+ 3. While installing: `stack:install-start` → subscribe to
81
+ `stack:install-stream` (per-line) → render in xterm + show
82
+ exit status from `stack:install-finished`.
86
83
  4. The session survives navigation: if `activeSession` exists on refresh,
87
84
  re-attach to the same session id.
88
85
 
86
+ Cards are **collapsible** — a compact status row by default, expanding to
87
+ version + actions + live install output, and auto-expanding while an install
88
+ runs (the list stays scannable as engines are added). The header's brand icon
89
+ comes from `TOOL_ICONS` (`shared/constants/tool-icons.ts`), the same registry
90
+ `ENGINES` reads — no SVG is defined twice.
91
+
89
92
  Engine cards differ from host-tool cards:
90
93
  - The SDK installs on demand into `~/.clopen/stack/engines` (managed dir), not
91
94
  the machine's PATH; there is no manual command to run.
@@ -97,15 +100,35 @@ Engine cards differ from host-tool cards:
97
100
  To add a new **host** tool (e.g. `goose`):
98
101
  1. Add the literal to `ToolId` (`backend/engine/install-recipes.ts`).
99
102
  2. Add `resolveGooseRecipe()` + a case in `resolveRecipe()`.
100
- 3. Add the literal to `TOOL_UNION` (`backend/ws/system-tools/status.ts`
103
+ 3. Add the literal to `TOOL_UNION` (`backend/ws/stack/status.ts`
101
104
  and `install.ts`).
102
105
  4. Add `<ToolInstallCard tool="goose" title="Goose" description="…" />`
103
- in `SystemToolsSettings.svelte`.
106
+ in `StackSettings.svelte`.
104
107
  5. (Optional) expose detection in the `engine:<name>-status` handler so
105
108
  Settings → Engines can show an "Installed" badge.
106
109
 
107
110
  For a new **engine SDK**, you declare the pinned package instead of a resolver —
108
- see [system-tools](./system-tools.md) §7.7.
111
+ see [stack](./stack.md) §7.7.
112
+
113
+ ### 5.3 Settings → Models
114
+
115
+ `frontend/components/settings/model/EngineModelPicker.svelte` is the shared
116
+ catalog browser mounted by `AssistantSettings`, `GitSettings`, and
117
+ `ArtifactsSettings` (it is a different component from the chat-input picker of
118
+ the same name — see §6.2).
119
+
120
+ Per-model reasoning defaults are edited here: each model row that carries a
121
+ `reasoningControl` (§2.4a) gets a nested row of level buttons, rendered
122
+ **whether or not the model is selected** so it can't read as a global setting.
123
+ Clicking one calls `setReasoningDefault(modelId, level)` →
124
+ `settings.reasoningDefaults` (`null` deletes the key → back to the model's own
125
+ default). The chat pill writes the same map, so a level chosen in either place
126
+ is remembered in both.
127
+
128
+ The two generator overrides (`commitGenerator`, `artifactGenerator`) persist
129
+ `engine` + `provider` + `modelId` + `modelName` as separate fields. `GitSettings`
130
+ and `ArtifactsSettings` write them through `modelFieldsOf(...)` (§6.1) — never
131
+ one at a time.
109
132
 
110
133
  ---
111
134
 
@@ -118,13 +141,30 @@ see [system-tools](./system-tools.md) §7.7.
118
141
  ```ts
119
142
  { engine, provider, modelId, modelName,
120
143
  engineModelMemory: { [engine]: { provider, id, name } },
121
- accountId, accountName }
144
+ accountId, accountName,
145
+ profileId, // null = use the project default
146
+ reasoningEffort } // native level token; null = engine/model default
122
147
  ```
123
148
 
124
149
  This store is **local to the active session**: settings under Settings →
125
150
  Engines only seed the initial defaults via `initChatModel(...)`. Switching
126
151
  engine/model in chat input does **not** affect Settings.
127
152
 
153
+ `reasoningEffort` is the one field that is deliberately kept at its
154
+ **effective** value rather than "only what the user picked": an `$effect` in
155
+ the picker re-seeds it whenever the model changes (per-model default from
156
+ Settings → the model's own `reasoningControl.default`) and clears it to `null`
157
+ for models with no knob. That way the value sent with the turn — and stamped
158
+ onto the message for the Raw view — always matches what actually ran, and a
159
+ level left over from a different model can never leak into the next request.
160
+
161
+ > **Engine/provider/model move together.** They are three fields describing one
162
+ > choice; anything that writes one must write all three. Use `modelFieldsOf(...)`
163
+ > from `frontend/utils/model-override.ts` for the Settings-persisted
164
+ > generator configs (Git, Artifacts) instead of assigning them individually —
165
+ > a stale `provider` is invisible on five engines and fatal on three (see
166
+ > §10.16 point 3).
167
+
128
168
  ### 6.2 EngineModelPicker (in chat input)
129
169
 
130
170
  `frontend/components/chat/input/components/EngineModelPicker.svelte`:
@@ -146,6 +186,18 @@ engine/model in chat input does **not** affect Settings.
146
186
  resolves the model's provider via `ocMatchingProvider`, then writes the
147
187
  chosen account into `chatModelState.accountId` and triggers a server
148
188
  restart.
189
+ - **Reasoning-level pill** — rendered next to the model trigger **only** when
190
+ `currentModel.capabilities.reasoningControl` exists (§2.4a). Options come
191
+ straight from `reasoningControl.levels`; no engine is named anywhere in the
192
+ component. Picking a level does three things: sets
193
+ `chatModelState.reasoningEffort`, saves it as that model's default via
194
+ `setReasoningDefault(modelId, value)`, and broadcasts
195
+ `chat:reasoning-sync` to the session room.
196
+ - **Not-installed notice** — when `models:list` reports a readiness error for
197
+ the active engine (`modelStore.getError(engine)`, typically
198
+ `EngineNotReadyError`), the picker renders the same actionable notice as
199
+ Settings, with an **Open Stack** button and a Configure-engine fallback.
200
+ Both are admin-gated.
149
201
 
150
202
  ### 6.3 Send path → backend
151
203
 
@@ -163,13 +215,17 @@ ws.emit('chat:stream', {
163
215
  model: { id: chatModelState.modelId, name: chatModelState.modelName },
164
216
  account: { id: chatModelState.accountId ?? 0, name: chatModelState.accountName ?? '' },
165
217
  },
166
- sender: { id, name }
218
+ sender: { id, name },
219
+ profileId: chatModelState.profileId,
220
+ reasoningEffort: chatModelState.reasoningEffort,
167
221
  });
168
222
  ```
169
223
 
170
224
  Backend `chat:stream` then `streamManager.startStream(...)`, which:
171
225
  - Resolves `getProjectEngine(projectId, engine.type)`
172
- - Calls `engine.streamQuery({ projectPath, prompt, providerSlug: engine.provider, modelId: engine.model.id, accountId: engine.account.id !== 0 ? engine.account.id : undefined, mcpContext })`
226
+ - Persists engine/model/account + `profile_id` + `reasoning_effort` onto the
227
+ `chat_sessions` row so a refresh or a late joiner restores the same setup
228
+ - Calls `engine.streamQuery({ projectPath, prompt, providerSlug: engine.provider, modelId: engine.model.id, reasoningEffort, accountId: engine.account.id !== 0 ? engine.account.id : undefined, mcpContext })`
173
229
  - Yields `EngineOutput` → emits `chat:message` / `chat:partial` /
174
230
  `chat:notification` to the session room.
175
231
 
@@ -180,10 +236,17 @@ Backend `chat:stream` then `streamManager.startStream(...)`, which:
180
236
 
181
237
  ### 6.4 Reasoning, attachments, AskUserQuestion
182
238
 
183
- - **Reasoning**: an adapter must emit
239
+ - **Reasoning (output)**: an adapter must emit
184
240
  `StreamLifecycleEvent { reasoning: true }` to mark start/stop of the
185
241
  thinking block, then `TextDeltaEvent { reasoning: true }` for each delta.
186
242
  The frontend renders these in a separate bubble.
243
+ - **Reasoning effort (input)**: the level the user picked rides the request as
244
+ `EngineQueryOptions.reasoningEffort` and is mapped to the SDK's own knob by
245
+ the adapter (§2.4a). Three places hold a value, in precedence order:
246
+ `chatModelState.reasoningEffort` (this session) → `settings.reasoningDefaults[modelId]`
247
+ (per-model, Settings → Models) → `reasoningControl.default` (the model's own).
248
+ Nothing in the frontend branches on engine type — a model without a
249
+ `reasoningControl` simply has no pill.
187
250
  - **Attachments**: `UserMessage.content` carries `text | image | document`
188
251
  blocks. The adapter maps these to the SDK's format — Claude uses native
189
252
  content blocks, OpenCode uses `extractPromptParts()` to