@myrialabs/clopen 0.4.44 → 0.4.46

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 (118) hide show
  1. package/backend/artifacts/project/bridge.ts +218 -0
  2. package/backend/artifacts/project/edit.ts +243 -0
  3. package/backend/artifacts/project/index.ts +38 -0
  4. package/backend/artifacts/project/project.test.ts +181 -0
  5. package/backend/artifacts/project/scan.ts +368 -0
  6. package/backend/artifacts/project/sources.ts +100 -0
  7. package/backend/artifacts/sync.ts +1 -1
  8. package/backend/auth/permissions.ts +15 -0
  9. package/backend/chat/stream-manager.ts +20 -3
  10. package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
  11. package/backend/database/migrations/index.ts +7 -0
  12. package/backend/database/queries/index.ts +2 -0
  13. package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
  14. package/backend/engine/adapters/claude/models.test.ts +49 -0
  15. package/backend/engine/adapters/claude/models.ts +81 -562
  16. package/backend/engine/adapters/claude/stream.ts +32 -5
  17. package/backend/engine/adapters/cline/credential.ts +42 -18
  18. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  19. package/backend/engine/adapters/cline/message-converter.ts +31 -1
  20. package/backend/engine/adapters/cline/models.test.ts +77 -0
  21. package/backend/engine/adapters/cline/models.ts +89 -3
  22. package/backend/engine/adapters/cline/presets.ts +5 -0
  23. package/backend/engine/adapters/cline/stream.ts +29 -8
  24. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  25. package/backend/engine/adapters/codex/models.ts +54 -31
  26. package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
  27. package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
  28. package/backend/engine/adapters/codex/session-fork.ts +5 -0
  29. package/backend/engine/adapters/codex/stream.ts +29 -11
  30. package/backend/engine/adapters/copilot/models.test.ts +40 -0
  31. package/backend/engine/adapters/copilot/models.ts +51 -24
  32. package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
  33. package/backend/engine/adapters/copilot/permissions.ts +72 -0
  34. package/backend/engine/adapters/copilot/stream.ts +83 -70
  35. package/backend/engine/adapters/cursor/stream.ts +27 -12
  36. package/backend/engine/adapters/opencode/server.ts +14 -4
  37. package/backend/engine/adapters/opencode/stream.ts +18 -3
  38. package/backend/engine/adapters/pi/credential.test.ts +83 -0
  39. package/backend/engine/adapters/pi/credential.ts +68 -12
  40. package/backend/engine/adapters/pi/environment.ts +9 -5
  41. package/backend/engine/adapters/pi/mcp.test.ts +194 -0
  42. package/backend/engine/adapters/pi/mcp.ts +88 -0
  43. package/backend/engine/adapters/pi/message-converter.ts +6 -4
  44. package/backend/engine/adapters/pi/presets.ts +10 -5
  45. package/backend/engine/adapters/pi/stream.ts +77 -41
  46. package/backend/engine/adapters/qwen/environment.ts +39 -2
  47. package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
  48. package/backend/engine/adapters/qwen/message-converter.ts +40 -23
  49. package/backend/engine/adapters/qwen/models.test.ts +25 -0
  50. package/backend/engine/adapters/qwen/models.ts +42 -5
  51. package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
  52. package/backend/engine/adapters/qwen/session-store.ts +66 -0
  53. package/backend/engine/adapters/qwen/stream.ts +118 -87
  54. package/backend/engine/artifact-sync.ts +12 -5
  55. package/backend/engine/docs/adapter-contract.md +7 -4
  56. package/backend/engine/docs/lessons-learned.md +405 -62
  57. package/backend/engine/docs/quick-reference.md +2 -2
  58. package/backend/engine/docs/stack.md +17 -4
  59. package/backend/engine/docs/websocket-routes.md +5 -5
  60. package/backend/engine/install-recipes.test.ts +105 -5
  61. package/backend/engine/install-recipes.ts +102 -42
  62. package/backend/engine/install-runner.ts +56 -2
  63. package/backend/engine/stack-project.ts +71 -1
  64. package/backend/files/file-watcher.test.ts +77 -0
  65. package/backend/files/file-watcher.ts +92 -60
  66. package/backend/files/watch-ignore.test.ts +182 -0
  67. package/backend/files/watch-ignore.ts +244 -0
  68. package/backend/git/git-executor.ts +14 -4
  69. package/backend/index.ts +16 -1
  70. package/backend/instructions/service.ts +5 -3
  71. package/backend/instructions/sync.ts +10 -27
  72. package/backend/mcp/README.md +2 -2
  73. package/backend/mcp/external/config.ts +83 -23
  74. package/backend/mcp/external/project.ts +124 -0
  75. package/backend/mcp/external/proxy.ts +65 -11
  76. package/backend/mcp/index.ts +22 -9
  77. package/backend/mcp/internal/config.ts +42 -3
  78. package/backend/mcp/internal/remote-server.ts +11 -1
  79. package/backend/memory/embedding/install.ts +29 -1
  80. package/backend/skills/marketplace.ts +1 -1
  81. package/backend/snapshot/blob-store.ts +9 -5
  82. package/backend/snapshot/git-attribution.test.ts +42 -0
  83. package/backend/snapshot/git-attribution.ts +306 -0
  84. package/backend/snapshot/gitignore.test.ts +62 -0
  85. package/backend/snapshot/gitignore.ts +158 -78
  86. package/backend/snapshot/snapshot-service.test.ts +270 -0
  87. package/backend/snapshot/snapshot-service.ts +412 -136
  88. package/backend/snapshot/turn-activity.test.ts +52 -0
  89. package/backend/snapshot/turn-activity.ts +83 -0
  90. package/backend/snapshot/turn-changes.test.ts +58 -1
  91. package/backend/snapshot/turn-changes.ts +66 -0
  92. package/backend/utils/keyed-lock.test.ts +33 -0
  93. package/backend/utils/keyed-lock.ts +17 -0
  94. package/backend/utils/port-utils.test.ts +29 -0
  95. package/backend/utils/port-utils.ts +19 -0
  96. package/backend/worktrees/tree.ts +1 -1
  97. package/backend/ws/chat/composer.ts +504 -0
  98. package/backend/ws/chat/index.ts +3 -1
  99. package/backend/ws/chat/stream.ts +252 -440
  100. package/backend/ws/engine/cline/accounts.ts +26 -6
  101. package/backend/ws/engine/codex/accounts.test.ts +49 -0
  102. package/backend/ws/engine/codex/accounts.ts +17 -13
  103. package/backend/ws/engine/pi/accounts.ts +61 -6
  104. package/backend/ws/index.ts +4 -0
  105. package/backend/ws/project-artifacts/index.ts +236 -0
  106. package/backend/ws/snapshot/changes.ts +66 -31
  107. package/dist/assets/{index-DX5OwLOc.js → index-BTcR1byF.js} +1 -1
  108. package/dist/assets/{index-BWyhqUi5.js → index-CwuKQelV.js} +1 -1
  109. package/dist/assets/main-BiDNMWb3.css +1 -0
  110. package/dist/assets/main-BlhKWz2B.js +1241 -0
  111. package/dist/index.html +2 -2
  112. package/package.json +19 -15
  113. package/shared/types/stores/settings.ts +5 -0
  114. package/shared/types/unified/message.ts +2 -0
  115. package/backend/engine/adapters/pi/mcp-tools.ts +0 -131
  116. package/backend/engine/adapters/qwen/session-fork.ts +0 -109
  117. package/dist/assets/main-DOkwqXRU.js +0 -1215
  118. package/dist/assets/main-DzCY0n-j.css +0 -1
@@ -7,7 +7,7 @@
7
7
  * query() is the only session entry point. The alternative this comment used to
8
8
  * weigh — the @alpha v2 API (unstable_v2_createSession / unstable_v2_prompt) —
9
9
  * was removed upstream in 0.3.142, before the version Clopen pins, so there is
10
- * no migration pending. prewarm() (0.3.284, @alpha) parks a spare process to
10
+ * no migration pending. prewarm() (@alpha since 0.3.284) parks a spare process to
11
11
  * take start-up cost off the first message, but everything Clopen varies per
12
12
  * stream is frozen at prewarm time — mcpServers (whose tool handlers are bound
13
13
  * to the project), hooks, canUseTool, env (git identity) — so a spare is only
@@ -36,12 +36,13 @@ import { emptyGenerationError } from '../../structured-helpers';
36
36
  import { getEnabledMcpServers, getAllowedMcpTools } from '../../../mcp';
37
37
  import { syncSkills } from '$backend/skills';
38
38
  import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
39
+ import { resolveProjectBridge, ensureClaudeProjectPlugin, buildProjectPromptContext } from '$backend/artifacts/project';
39
40
  import { artifactFilter } from '$backend/profiles';
40
41
  import { resolvePermissionsFromDb, isToolAllowed, hasAnyRestriction, syncPermissions } from '$backend/permissions';
41
42
  import type { AIEngine, EngineQueryOptions } from '../../types';
42
43
  import { EngineRuns } from '../run-registry';
43
44
  import type { EngineModel } from '$shared/types/unified';
44
- import { CLAUDE_CODE_MODELS } from './models';
45
+ import { CLAUDE_CODE_MODELS, resolveClaudeReasoning } from './models';
45
46
 
46
47
  import { debug } from '$shared/utils/logger';
47
48
 
@@ -138,7 +139,6 @@ export class ClaudeCodeEngine implements AIEngine {
138
139
  resume,
139
140
  maxTurns = undefined,
140
141
  modelId,
141
- reasoningEffort,
142
142
  includePartialMessages = false,
143
143
  abortController,
144
144
  accountId
@@ -146,7 +146,9 @@ export class ClaudeCodeEngine implements AIEngine {
146
146
 
147
147
  // Map the chosen reasoning level to Claude's knobs: `off` disables thinking
148
148
  // entirely, `auto`/unset keeps adaptive thinking (Claude decides how much),
149
- // and an explicit effort level pairs adaptive thinking with `effort`.
149
+ // and an explicit effort level pairs adaptive thinking with `effort`. The
150
+ // level is first held to what this model offers (see models.ts).
151
+ const reasoningEffort = resolveClaudeReasoning(modelId, options.reasoningEffort);
150
152
  const claudeEffort = new Set<string>(['low', 'medium', 'high', 'xhigh', 'max']);
151
153
  const thinkingConfig: Options['thinking'] = reasoningEffort === 'off'
152
154
  ? { type: 'disabled' }
@@ -181,6 +183,25 @@ export class ClaudeCodeEngine implements AIEngine {
181
183
  // equivalent — the PreToolUse hook below is the authoritative enforcement.
182
184
  await syncPermissions('claude');
183
185
 
186
+ // The repository's own artifacts Claude doesn't read natively (it reads
187
+ // `.claude/*` and CLAUDE.md itself via settingSources). All three ride
188
+ // per-query options, so nothing is written into the repo or into the
189
+ // isolated config dir another session shares:
190
+ // - skills (e.g. `.agents/skills`) → a Clopen-owned local plugin;
191
+ // - subagents (e.g. `.agents/agents`) → the SDK `agents` option;
192
+ // - AGENTS.md + the Clopen-only project block → the appended system prompt.
193
+ const projectBridge = await resolveProjectBridge('claude', resolvedProjectPath, options.mcpContext?.projectId);
194
+ const projectPlugin = await ensureClaudeProjectPlugin(projectBridge);
195
+ const projectInstructions = buildProjectPromptContext(projectBridge, { instructions: true });
196
+ const projectAgents = projectBridge.subagents.length > 0
197
+ ? Object.fromEntries(projectBridge.subagents.map(sub => [sub.slug, {
198
+ description: sub.description || sub.name,
199
+ prompt: sub.prompt,
200
+ ...(sub.tools && { tools: sub.tools }),
201
+ ...(sub.model && { model: sub.model })
202
+ }]))
203
+ : undefined;
204
+
184
205
  // Resolve the effective permission policy once per stream. Enforcement
185
206
  // lives in the PreToolUse hook, NOT in canUseTool: under
186
207
  // permissionMode 'bypassPermissions' the CLI auto-approves a tool call
@@ -229,8 +250,14 @@ export class ClaudeCodeEngine implements AIEngine {
229
250
  allowDangerouslySkipPermissions: true,
230
251
  cwd: resolvedProjectPath,
231
252
  env: getEngineEnv(accountId, options.gitIdentityEnv),
232
- systemPrompt: { type: "preset", preset: "claude_code" },
253
+ systemPrompt: projectInstructions
254
+ ? { type: "preset", preset: "claude_code", append: projectInstructions }
255
+ : { type: "preset", preset: "claude_code" },
233
256
  settingSources: ["user", "project", "local"],
257
+ // The plugin carries skills only; its MCP discovery is off because
258
+ // project MCP servers come through Clopen's trust-gated bridge.
259
+ ...(projectPlugin && { plugins: [{ type: 'local' as const, path: projectPlugin, skipMcpDiscovery: true }] }),
260
+ ...(projectAgents && { agents: projectAgents }),
234
261
  forkSession: true,
235
262
  // Reasoning level → thinking/effort (see thinkingConfig above). Adaptive
236
263
  // thinking with summarized display keeps Opus 4.6+ emitting visible
@@ -23,6 +23,7 @@ import type { OAuthCredentials, ProviderSettings } from '@cline/sdk';
23
23
  import { engineQueries, type EngineAccount } from '$backend/database/queries/engine-queries';
24
24
  import { debug } from '$shared/utils/logger';
25
25
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
26
+ import { createKeyedLock } from '$backend/utils/keyed-lock';
26
27
 
27
28
  export type ClineAuthMethod = 'api_key' | 'oauth';
28
29
 
@@ -106,6 +107,24 @@ export interface ResolvedClineAuth {
106
107
  /** Refresh window: refresh an OAuth token that expires within the next minute. */
107
108
  const OAUTH_REFRESH_BUFFER_MS = 60_000;
108
109
 
110
+ /**
111
+ * One refresh per account at a time. Concurrent streams each resolve auth, and
112
+ * a refresh token spent twice gets the grant revoked by providers that rotate
113
+ * it; the second caller re-reads the row inside the lock and finds it fresh.
114
+ */
115
+ const withAccountLock = createKeyedLock<number>();
116
+
117
+ /**
118
+ * Replace an account's stored credential (re-login, edited key) in line with
119
+ * any refresh in flight, so the refresh can't land afterwards and put the old
120
+ * grant back.
121
+ */
122
+ export function writeClineAccountCredential(accountId: number, serialized: string): Promise<void> {
123
+ return withAccountLock(accountId, async () => {
124
+ engineQueries.updateAccountCredential(accountId, serialized);
125
+ });
126
+ }
127
+
109
128
  /**
110
129
  * Resolve the auth an `Agent` needs for one account. For OAuth accounts this
111
130
  * refreshes a near-expired access token (persisting the rotated blob back to the
@@ -126,31 +145,36 @@ export async function resolveClineAuth(account: EngineAccount): Promise<Resolved
126
145
 
127
146
  // OAuth: refresh if near-expiry, then format the access token as an api key.
128
147
  const { getProviderAuthHandler, formatProviderOAuthApiKey } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
129
- let creds = parsed.oauth as OAuthCredentials;
130
148
  const handler = getProviderAuthHandler(parsed.provider);
131
- const nearExpiry = typeof creds.expires === 'number' && creds.expires <= Date.now() + OAUTH_REFRESH_BUFFER_MS;
132
- if (handler && creds.refresh && nearExpiry) {
133
- try {
134
- const settings = {
135
- auth: {
136
- accessToken: creds.access,
137
- refreshToken: creds.refresh,
138
- expiresAt: creds.expires,
139
- ...(creds.accountId ? { accountId: creds.accountId } : {}),
140
- },
141
- } as ProviderSettings;
142
- const refreshed = await handler.refresh({ settings, credentials: creds });
143
- if (refreshed?.access) {
144
- creds = refreshed;
149
+ const isNearExpiry = (c: OAuthCredentials) => typeof c.expires === 'number' && c.expires <= Date.now() + OAUTH_REFRESH_BUFFER_MS;
150
+ let creds = parsed.oauth as OAuthCredentials;
151
+ if (handler && creds.refresh && isNearExpiry(creds)) {
152
+ creds = await withAccountLock(account.id, async () => {
153
+ // The row, not the caller's snapshot: another stream may have refreshed it.
154
+ const current = (parseClineCredential(engineQueries.getAccount(account.id)?.credential)?.oauth ?? parsed.oauth) as OAuthCredentials;
155
+ if (!current.refresh || !isNearExpiry(current)) return current;
156
+ try {
157
+ const settings = {
158
+ auth: {
159
+ accessToken: current.access,
160
+ refreshToken: current.refresh,
161
+ expiresAt: current.expires,
162
+ ...(current.accountId ? { accountId: current.accountId } : {}),
163
+ },
164
+ } as ProviderSettings;
165
+ const refreshed = await handler.refresh({ settings, credentials: current });
166
+ if (!refreshed?.access) return current;
145
167
  engineQueries.updateAccountCredential(
146
168
  account.id,
147
169
  serializeClineCredential({ ...parsed, oauth: refreshed }),
148
170
  );
149
171
  debug.log('engine', `Cline: refreshed OAuth token for provider "${parsed.provider}" (account ${account.id})`);
172
+ return refreshed;
173
+ } catch (error) {
174
+ debug.warn('engine', `Cline OAuth refresh failed for "${parsed.provider}" (using stored token): ${error instanceof Error ? error.message : String(error)}`);
175
+ return current;
150
176
  }
151
- } catch (error) {
152
- debug.warn('engine', `Cline OAuth refresh failed for "${parsed.provider}" (using stored token): ${error instanceof Error ? error.message : String(error)}`);
153
- }
177
+ });
154
178
  }
155
179
 
156
180
  let apiKey: string;
@@ -25,6 +25,9 @@ import {
25
25
  getEnabledExternalServers,
26
26
  listExternalServerTools,
27
27
  callExternalServerTool,
28
+ getTrustedProjectServers,
29
+ listProjectServerTools,
30
+ callProjectServerTool,
28
31
  projectContextService,
29
32
  serverMetadata,
30
33
  } from '../../../mcp';
@@ -92,12 +95,31 @@ export async function buildClineMcpTools(
92
95
  }
93
96
 
94
97
  // ── External servers (proxied upstream) ──
95
- for (const server of getEnabledExternalServers(profileFilter)) {
98
+ // Installed servers (profile-filtered) plus the project's approved
99
+ // `.agents/mcp.json` servers, which never shadow an installed namespace.
100
+ const upstreams: { label: string; namespace: string; list: () => ReturnType<typeof listExternalServerTools>; call: (tool: string, args: unknown) => Promise<unknown> }[] =
101
+ getEnabledExternalServers(profileFilter).map(s => ({
102
+ label: s.slug,
103
+ namespace: s.namespace,
104
+ list: () => listExternalServerTools(s.slug),
105
+ call: (tool: string, args: unknown) => callExternalServerTool(s.slug, tool, args)
106
+ }));
107
+ const taken = new Set(upstreams.map(u => u.namespace));
108
+ for (const s of getTrustedProjectServers(context?.projectId)) {
109
+ if (taken.has(s.namespace)) continue;
110
+ upstreams.push({
111
+ label: s.namespace,
112
+ namespace: s.namespace,
113
+ list: () => listProjectServerTools(s.projectId, s.name),
114
+ call: (tool: string, args: unknown) => callProjectServerTool(s.projectId, s.name, tool, args)
115
+ });
116
+ }
117
+ for (const server of upstreams) {
96
118
  let externalTools;
97
119
  try {
98
- externalTools = await listExternalServerTools(server.slug);
120
+ externalTools = await server.list();
99
121
  } catch (error) {
100
- debug.warn('mcp', `Cline MCP bridge: could not list tools for "${server.slug}" (skipping):`, error);
122
+ debug.warn('mcp', `Cline MCP bridge: could not list tools for "${server.label}" (skipping):`, error);
101
123
  continue;
102
124
  }
103
125
  for (const tool of externalTools) {
@@ -108,7 +130,7 @@ export async function buildClineMcpTools(
108
130
  description: `${tool.description ?? tool.name}${schemaText}`,
109
131
  inputSchema: OPEN_PARAMS,
110
132
  async execute(params: unknown) {
111
- const result = (await callExternalServerTool(server.slug, tool.name, params ?? {})) as { content?: unknown } | undefined;
133
+ const result = (await server.call(tool.name, params ?? {})) as { content?: unknown } | undefined;
112
134
  return toResultText(result?.content);
113
135
  },
114
136
  }) as AgentTool);
@@ -158,6 +158,9 @@ function mapFinishReason(raw: AgentModelFinishReason | null | undefined): StopRe
158
158
  case 'max-tokens': return 'max_tokens';
159
159
  case 'aborted': return 'interrupted';
160
160
  case 'error': return 'end_turn';
161
+ case 'content-filter': return 'end_turn';
162
+ // The SDK never treats `unknown` as a completed turn (it may be cut off).
163
+ case 'unknown': return null;
161
164
  default: return null;
162
165
  }
163
166
  }
@@ -234,7 +237,18 @@ export function createClineMessageConverter(options: ClineConverterOptions): Cli
234
237
  if (part.text) reasoning += (reasoning ? '\n' : '') + part.text;
235
238
  } else if (part.type === 'text') {
236
239
  if (part.text.trim()) blocks.push({ type: 'text', text: part.text });
240
+ } else if (part.type === 'media') {
241
+ // Model-generated media (image-output models). The unified assistant
242
+ // blocks carry no media type, so keep a visible trace instead of
243
+ // dropping it silently.
244
+ const { media } = part;
245
+ const label = `${media.modality} (${media.mediaType})`;
246
+ blocks.push({ type: 'text', text: media.source.type === 'url' ? `[Generated ${label}](${media.source.url})` : `[Generated ${label} not shown]` });
237
247
  } else if (part.type === 'tool-call') {
248
+ // Provider-executed tools (web search, image generation) run inside the
249
+ // model request and never get a local tool result, so a tool_use block
250
+ // would sit pending forever. Clopen passes no `modelTools`; skip them.
251
+ if (part.execution === 'provider') continue;
238
252
  const call = part as AgentToolCallPart;
239
253
  const canonical = canonicaliseToolName(call.toolName);
240
254
  const finalName = toCanonicalToolName(canonical);
@@ -254,7 +268,7 @@ export function createClineMessageConverter(options: ClineConverterOptions): Cli
254
268
  return { reasoning, blocks };
255
269
  }
256
270
 
257
- function convertAssistantMessage(msg: AgentMessage, finishReason: AgentModelFinishReason): EngineOutput[] {
271
+ function convertAssistantContent(msg: AgentMessage, finishReason: AgentModelFinishReason): EngineOutput[] {
258
272
  const outputs: EngineOutput[] = [];
259
273
  const { reasoning, blocks } = mapAssistantContent(msg.content);
260
274
  const usage = msg.metrics ? mapUsage(msg.metrics) : null;
@@ -307,6 +321,22 @@ export function createClineMessageConverter(options: ClineConverterOptions): Cli
307
321
  return outputs;
308
322
  }
309
323
 
324
+ function convertAssistantMessage(msg: AgentMessage, finishReason: AgentModelFinishReason): EngineOutput[] {
325
+ const outputs = convertAssistantContent(msg, finishReason);
326
+ if (finishReason === 'content-filter') {
327
+ // A filtered turn that produced nothing fails the run with the SDK's own
328
+ // message; one that produced part of an answer lands here, cut short.
329
+ outputs.push({
330
+ type: 'notification',
331
+ sessionId,
332
+ level: 'warning',
333
+ title: 'Response filtered',
334
+ message: 'The provider\'s content filter stopped this response early. Retrying is unlikely to help — try rephrasing the request.',
335
+ } as NotificationEvent);
336
+ }
337
+ return outputs;
338
+ }
339
+
310
340
  function convertToolResults(msg: AgentMessage): UserMessage[] {
311
341
  const out: UserMessage[] = [];
312
342
  for (const part of msg.content) {
@@ -0,0 +1,77 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { buildClineReasoningControl, isClineChatModel, resolveClineReasoning, type CatalogModel } from './models';
3
+
4
+ type Options = CatalogModel['reasoningOptions'];
5
+
6
+ // Shapes taken from the @cline/llms catalog.
7
+ const EFFORT_ONLY: Options = [{ type: 'effort', values: ['low', 'medium', 'high', 'xhigh', 'max'] }];
8
+ const TOGGLE_AND_EFFORT: Options = [{ type: 'toggle' }, { type: 'effort', values: ['low', 'medium', 'high', 'xhigh', 'max'] }];
9
+ const EFFORT_WITH_NONE: Options = [{ type: 'effort', values: ['none', 'low', 'medium', 'high'] }];
10
+ const TOGGLE_ONLY: Options = [{ type: 'toggle' }];
11
+ const BUDGET_ONLY: Options = [{ type: 'budget_tokens', min: 1024 }];
12
+
13
+ const levelsOf = (options: Options) => buildClineReasoningControl(options)?.levels.map(l => l.value);
14
+
15
+ describe('isClineChatModel', () => {
16
+ test('a language model that reads and writes text is chat', () => {
17
+ expect(isClineChatModel({ operation: 'language', modalities: { input: ['text', 'image'], output: ['text'] } })).toBe(true);
18
+ });
19
+
20
+ test('entries without operation or modalities stay chat', () => {
21
+ expect(isClineChatModel({})).toBe(true);
22
+ });
23
+
24
+ test('transcription and media-generation models are not chat', () => {
25
+ expect(isClineChatModel({ operation: 'transcription', modalities: { input: ['audio'], output: ['text'] } })).toBe(false);
26
+ expect(isClineChatModel({ operation: 'image-generation' })).toBe(false);
27
+ expect(isClineChatModel({ modalities: { input: ['text'], output: ['image'] } })).toBe(false);
28
+ });
29
+ });
30
+
31
+ describe('Cline reasoning levels', () => {
32
+ test('effort tiers without a way to turn thinking off offer no Off', () => {
33
+ expect(levelsOf(EFFORT_ONLY)).toEqual(['auto', 'low', 'medium', 'high', 'xhigh', 'max']);
34
+ });
35
+
36
+ test('a toggle or a none effort adds Off', () => {
37
+ expect(levelsOf(TOGGLE_AND_EFFORT)).toEqual(['off', 'auto', 'low', 'medium', 'high', 'xhigh', 'max']);
38
+ expect(levelsOf(EFFORT_WITH_NONE)).toEqual(['off', 'auto', 'low', 'medium', 'high']);
39
+ });
40
+
41
+ test('a toggle-only model offers Off / Auto / On', () => {
42
+ expect(levelsOf(TOGGLE_ONLY)).toEqual(['off', 'auto', 'on']);
43
+ });
44
+
45
+ test('budget-only and option-less models get no selector', () => {
46
+ expect(buildClineReasoningControl(BUDGET_ONLY)).toBeUndefined();
47
+ expect(buildClineReasoningControl([])).toBeUndefined();
48
+ expect(buildClineReasoningControl(undefined)).toBeUndefined();
49
+ });
50
+
51
+ test('the default is always Auto, one of the levels', () => {
52
+ for (const options of [EFFORT_ONLY, TOGGLE_AND_EFFORT, EFFORT_WITH_NONE, TOGGLE_ONLY]) {
53
+ const control = buildClineReasoningControl(options);
54
+ expect(control?.default).toBe('auto');
55
+ expect(control?.levels.some(l => l.value === 'auto')).toBe(true);
56
+ }
57
+ });
58
+ });
59
+
60
+ describe('resolveClineReasoning', () => {
61
+ test('an offered effort becomes reasoningEffort', () => {
62
+ expect(resolveClineReasoning('xhigh', EFFORT_ONLY)).toEqual({ reasoningEffort: 'xhigh' });
63
+ });
64
+
65
+ test('off and on drive the thinking flag', () => {
66
+ expect(resolveClineReasoning('off', TOGGLE_AND_EFFORT)).toEqual({ thinking: false });
67
+ expect(resolveClineReasoning('on', TOGGLE_ONLY)).toEqual({ thinking: true });
68
+ });
69
+
70
+ test('auto, unknown and no longer offered levels send nothing', () => {
71
+ expect(resolveClineReasoning('auto', EFFORT_ONLY)).toEqual({});
72
+ expect(resolveClineReasoning(undefined, EFFORT_ONLY)).toEqual({});
73
+ expect(resolveClineReasoning('off', EFFORT_ONLY)).toEqual({});
74
+ expect(resolveClineReasoning('max', EFFORT_WITH_NONE)).toEqual({});
75
+ expect(resolveClineReasoning('high', BUDGET_ONLY)).toEqual({});
76
+ });
77
+ });
@@ -9,15 +9,99 @@
9
9
  * so the chat's send path can resolve the matching account by provider. Returns
10
10
  * `[]` on any failure (mirrors the OpenCode/Qwen/Pi dynamic-catalog contract —
11
11
  * the picker renders empty rather than a stale list).
12
+ *
13
+ * The catalog also lists models a chat turn cannot use (transcription, image /
14
+ * speech / video generation — e.g. `vercel-ai-gateway`'s `flux-*` and
15
+ * `*-transcribe-*`); `isClineChatModel` keeps those out of the picker.
12
16
  */
13
17
 
14
18
  import type { Llms } from '@cline/sdk';
15
- import type { EngineModel } from '$shared/types/unified';
19
+ import type { EngineModel, ReasoningControl } from '$shared/types/unified';
20
+ import { toReasoningOptions } from '$shared/constants/engines';
16
21
  import { debug } from '$shared/utils/logger';
17
22
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
18
23
  import { getClineAccounts, parseClineCredential } from './credential';
19
24
 
20
- type CatalogModel = Awaited<ReturnType<typeof Llms.getModelsForProvider>>[string];
25
+ export type CatalogModel = Awaited<ReturnType<typeof Llms.getModelsForProvider>>[string];
26
+
27
+ /**
28
+ * Whether a catalog model can run a text chat turn. Mirrors the SDK's own
29
+ * `supportsChatModalities` + `operation` gate (not re-exported by
30
+ * `@cline/sdk`): missing metadata counts as chat for older catalog entries;
31
+ * otherwise the model must take text in, give text out, and run as a
32
+ * `language` operation.
33
+ */
34
+ export function isClineChatModel(info: Pick<CatalogModel, 'operation' | 'modalities'>): boolean {
35
+ if (info.operation && info.operation !== 'language') return false;
36
+ const modalities = info.modalities;
37
+ if (!modalities) return true;
38
+ return modalities.input.includes('text') && modalities.output.includes('text');
39
+ }
40
+
41
+ /** The SDK's effort ladder, low → high (`REASONING_LEVELS` minus `none`). */
42
+ const CLINE_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;
43
+ type ClineEffort = (typeof CLINE_EFFORTS)[number];
44
+
45
+ type ReasoningOptions = CatalogModel['reasoningOptions'];
46
+
47
+ /**
48
+ * Per-model reasoning levels, from the catalog's `reasoningOptions`:
49
+ * - `off` — thinking disabled; only where the model can turn it off (a
50
+ * `toggle` option, or `none` among its efforts).
51
+ * - `auto` — no knob sent; the SDK applies the model's own default.
52
+ * - `low`…`max` — the efforts the model advertises.
53
+ * - `on` — thinking enabled, for toggle-only models with no effort tiers.
54
+ * Budget-only models (`budget_tokens` alone, e.g. Claude Sonnet 4.5) get no
55
+ * selector: the SDK has no level to map them to.
56
+ */
57
+ function clineReasoningLevels(options: ReasoningOptions): string[] {
58
+ if (!options?.length) return [];
59
+ const toggle = options.some(o => o.type === 'toggle');
60
+ const effortValues = new Set<string | null>(options.find(o => o.type === 'effort')?.values ?? []);
61
+ const efforts = CLINE_EFFORTS.filter(e => effortValues.has(e));
62
+ const levels: string[] = [];
63
+ if (toggle || effortValues.has('none')) levels.push('off');
64
+ levels.push('auto');
65
+ levels.push(...efforts);
66
+ if (efforts.length === 0 && toggle) levels.push('on');
67
+ return levels.length > 1 ? levels : [];
68
+ }
69
+
70
+ export function buildClineReasoningControl(options: ReasoningOptions): ReasoningControl | undefined {
71
+ const levels = clineReasoningLevels(options);
72
+ if (levels.length === 0) return undefined;
73
+ return { levels: toReasoningOptions(levels), default: 'auto' };
74
+ }
75
+
76
+ /** `Agent` config fields carrying a reasoning level. */
77
+ export interface ClineReasoningConfig {
78
+ thinking?: boolean;
79
+ reasoningEffort?: ClineEffort;
80
+ }
81
+
82
+ /**
83
+ * Map a chosen level onto the `Agent` knobs. A level the model doesn't offer
84
+ * (stale per-model memory, a model swapped under the chat) and `auto` both send
85
+ * nothing, so the model's own default applies rather than an invented value.
86
+ */
87
+ export function resolveClineReasoning(level: string | undefined, options: ReasoningOptions): ClineReasoningConfig {
88
+ if (!level || !clineReasoningLevels(options).includes(level)) return {};
89
+ if (level === 'off') return { thinking: false };
90
+ if (level === 'on') return { thinking: true };
91
+ if ((CLINE_EFFORTS as readonly string[]).includes(level)) return { reasoningEffort: level as ClineEffort };
92
+ return {};
93
+ }
94
+
95
+ /** Catalog entry for one model, or undefined when the provider doesn't list it. */
96
+ export async function getClineModelInfo(providerId: string, modelId: string): Promise<CatalogModel | undefined> {
97
+ try {
98
+ const { Llms } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
99
+ return (await Llms.getModelsForProvider(providerId))[modelId];
100
+ } catch (error) {
101
+ debug.warn('engine', `Cline: could not read catalog entry for "${providerId}/${modelId}": ${error instanceof Error ? error.message : String(error)}`);
102
+ return undefined;
103
+ }
104
+ }
21
105
 
22
106
  export async function fetchClineModels(): Promise<EngineModel[]> {
23
107
  try {
@@ -39,7 +123,7 @@ export async function fetchClineModels(): Promise<EngineModel[]> {
39
123
  continue;
40
124
  }
41
125
  for (const [modelId, info] of Object.entries(models)) {
42
- out.push(mapClineModel(providerId, modelId, info));
126
+ if (isClineChatModel(info)) out.push(mapClineModel(providerId, modelId, info));
43
127
  }
44
128
  }
45
129
  debug.log('engine', `Cline getAvailableModels: ${out.length} models across ${providers.size} provider(s)`);
@@ -53,6 +137,7 @@ export async function fetchClineModels(): Promise<EngineModel[]> {
53
137
  function mapClineModel(providerId: string, modelId: string, info: CatalogModel): EngineModel {
54
138
  const caps = info.capabilities ?? [];
55
139
  const image = caps.includes('images');
140
+ const reasoningControl = buildClineReasoningControl(info.reasoningOptions);
56
141
  return {
57
142
  engine: {
58
143
  type: 'cline',
@@ -69,6 +154,7 @@ function mapClineModel(providerId: string, modelId: string, info: CatalogModel):
69
154
  reasoning: caps.includes('reasoning'),
70
155
  tools: caps.includes('tools'),
71
156
  structuredOutput: caps.includes('structured_output'),
157
+ ...(reasoningControl && { reasoningControl }),
72
158
  },
73
159
  cost: { input: info.pricing?.input ?? 0, output: info.pricing?.output ?? 0 },
74
160
  };
@@ -15,6 +15,7 @@
15
15
  import type { ClineAuthMode, ClineCredentialField, ClineProviderPreset } from '$shared/types/unified';
16
16
  import { debug } from '$shared/utils/logger';
17
17
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
18
+ import { isClineChatModel } from './models';
18
19
 
19
20
  export type { ClineAuthMode, ClineCredentialField, ClineProviderPreset };
20
21
 
@@ -101,6 +102,10 @@ export async function getClineProviderPresets(): Promise<ClineProviderPreset[]>
101
102
  const { Llms, getProviderConfigFields, isOAuthProvider } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
102
103
  const presets: ClineProviderPreset[] = [];
103
104
  for (const provider of await Llms.getAllProviders()) {
105
+ // Speech/media-only providers (e.g. ElevenLabs) list models but none a
106
+ // chat turn can use — an account there would leave the picker empty.
107
+ const models = Object.values(await Llms.getModelsForProvider(provider.id).catch(() => ({})));
108
+ if (models.length > 0 && !models.some(isClineChatModel)) continue;
104
109
  const config = getProviderConfigFields(provider.id);
105
110
  const oauth = isOAuthProvider(provider.id) || config.authMethod === 'oauth';
106
111
  const fields = await getClineProviderFields(provider.id);
@@ -31,6 +31,7 @@ import { debug } from '$shared/utils/logger';
31
31
  import { engineQueries } from '$backend/database/queries/engine-queries';
32
32
  import { syncSkills } from '$backend/skills';
33
33
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
34
+ import { resolveProjectBridge, type ProjectBridge } from '$backend/artifacts/project';
34
35
  import { artifactFilter } from '$backend/profiles';
35
36
  import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
36
37
  import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
@@ -38,7 +39,7 @@ import { EngineRuns } from '../run-registry';
38
39
  import { subagentQueries } from '$backend/database/queries';
39
40
  import { readSubagentMd } from '$backend/subagents/store';
40
41
  import { getClineAccountForProvider, parseClineCredential, resolveClineAuth } from './credential';
41
- import { fetchClineModels } from './models';
42
+ import { fetchClineModels, getClineModelInfo, resolveClineReasoning } from './models';
42
43
  import { buildClineMcpTools } from './mcp-tools';
43
44
  import { createAskUserQuestionTool, formatAnswers, type PendingAsk } from './ask-question-tool';
44
45
  import { createAgentDispatchTool, type SubagentInfo } from './agent-tool';
@@ -133,7 +134,7 @@ export class ClineEngine implements AIEngine {
133
134
  return fetchClineModels();
134
135
  }
135
136
 
136
- private async buildSystemPrompt(cwd: string, providerId: string, profileId?: number): Promise<string> {
137
+ private async buildSystemPrompt(cwd: string, providerId: string, profileId?: number, project?: ProjectBridge): Promise<string> {
137
138
  const { getClineDefaultSystemPrompt } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
138
139
  let base: string;
139
140
  try {
@@ -141,12 +142,12 @@ export class ClineEngine implements AIEngine {
141
142
  } catch {
142
143
  base = 'You are Cline, a highly skilled software engineer. Use the available tools to complete the user\'s coding task.';
143
144
  }
144
- const artifacts = buildArtifactsPromptContext('cline', profileId);
145
+ const artifacts = buildArtifactsPromptContext('cline', profileId, project);
145
146
  return artifacts ? `${base}\n\n${artifacts}` : base;
146
147
  }
147
148
 
148
149
  async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
149
- const { projectPath, prompt, resume, providerSlug, modelId, abortController, accountId } = options;
150
+ const { projectPath, prompt, resume, providerSlug, modelId, reasoningEffort, abortController, accountId } = options;
150
151
  debug.log('chat', 'Cline - Stream Query', { providerSlug, modelId, resume });
151
152
 
152
153
  // ── Resolve account + credential for the model's provider ──
@@ -157,6 +158,11 @@ export class ClineEngine implements AIEngine {
157
158
  }
158
159
  const provider = parseClineCredential(account.credential)?.provider ?? providerSlug;
159
160
  const auth = await resolveClineAuth(account);
161
+ // Reasoning level → `thinking` / `reasoningEffort`, gated by the model's
162
+ // catalog options. Shared with the subagent so delegated work thinks alike.
163
+ const reasoning = reasoningEffort
164
+ ? resolveClineReasoning(reasoningEffort, (await getClineModelInfo(provider, modelId))?.reasoningOptions)
165
+ : {};
160
166
 
161
167
  const controller = abortController || new AbortController();
162
168
  const run: ClineRun = { controller, agent: null };
@@ -168,6 +174,9 @@ export class ClineEngine implements AIEngine {
168
174
  const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
169
175
  await syncSkills('cline', profileId);
170
176
  await syncEngineArtifacts('cline', profileId);
177
+ // Cline (stateless Agent) reads nothing from the repo, so every project
178
+ // artifact — skills, subagents, AGENTS.md — reaches it through Clopen.
179
+ const projectBridge = await resolveProjectBridge('cline', resolvedProjectPath, options.mcpContext?.projectId);
171
180
 
172
181
  // ── Permissions → toolPolicies (denied builtins are hidden from the model) ──
173
182
  const permissions = resolvePermissionsFromDb('cline', options.mcpContext?.projectId, profileId);
@@ -201,13 +210,23 @@ export class ClineEngine implements AIEngine {
201
210
  // "Available Subagents" preamble alone can't be invoked. Expose an `Agent`
202
211
  // tool that actually spawns a bounded sub-`Agent` with the chosen subagent's
203
212
  // system prompt and returns its final text. ──
204
- const subagents: SubagentInfo[] = subagentQueries.getEnabled().map(s => ({ slug: s.slug, name: s.name, description: s.description }));
213
+ // Project subagents join the same tool; an installed subagent wins a slug clash.
214
+ const installedSubagents = subagentQueries.getEnabled();
215
+ const installedSlugs = new Set(installedSubagents.map(s => s.slug));
216
+ const projectSubagents = new Map(projectBridge.subagents.filter(s => !installedSlugs.has(s.slug)).map(s => [s.slug, s]));
217
+ const subagents: SubagentInfo[] = [
218
+ ...installedSubagents.map(s => ({ slug: s.slug, name: s.name, description: s.description })),
219
+ ...[...projectSubagents.values()].map(s => ({ slug: s.slug, name: s.name, description: s.description })),
220
+ ];
205
221
  if (subagents.length > 0) {
206
222
  const agentTool = await createAgentDispatchTool({
207
223
  subagents,
208
224
  run: async (subagent, subPrompt, toolCallId, signal) => {
209
- const md = (await readSubagentMd(subagent.slug)) ?? '';
210
- const instructions = stripFrontmatter(md) || `You are the ${subagent.name} subagent. ${subagent.description}`;
225
+ const projectSubagent = projectSubagents.get(subagent.slug);
226
+ const md = projectSubagent ? '' : ((await readSubagentMd(subagent.slug)) ?? '');
227
+ const instructions = projectSubagent?.prompt
228
+ || stripFrontmatter(md)
229
+ || `You are the ${subagent.name} subagent. ${subagent.description}`;
211
230
  // APPEND the subagent instructions to Cline's base coding prompt (a
212
231
  // bare instruction strips the tool-use scaffolding). The sub-Agent gets
213
232
  // the permission-filtered builtins ONLY — no AskUserQuestion, no MCP,
@@ -224,6 +243,7 @@ export class ClineEngine implements AIEngine {
224
243
  ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
225
244
  ...(auth.baseUrl ? { baseUrl: auth.baseUrl } : {}),
226
245
  ...(auth.options ? { options: auth.options } : {}),
246
+ ...reasoning,
227
247
  systemPrompt: `${base}\n\n# Subagent: ${subagent.name}\n\n${instructions}`,
228
248
  tools: builtinTools,
229
249
  toolPolicies,
@@ -281,13 +301,14 @@ export class ClineEngine implements AIEngine {
281
301
  const priorMessages = resume ? this.sessions.get(resume) : undefined;
282
302
  const sessionId = crypto.randomUUID();
283
303
 
284
- const systemPrompt = await this.buildSystemPrompt(resolvedProjectPath, provider, profileId);
304
+ const systemPrompt = await this.buildSystemPrompt(resolvedProjectPath, provider, profileId, projectBridge);
285
305
  const agent = new Agent({
286
306
  providerId: provider,
287
307
  modelId,
288
308
  ...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
289
309
  ...(auth.baseUrl ? { baseUrl: auth.baseUrl } : {}),
290
310
  ...(auth.options ? { options: auth.options } : {}),
311
+ ...reasoning,
291
312
  systemPrompt,
292
313
  tools,
293
314
  toolPolicies,
@@ -470,7 +470,7 @@ function buildFileChangePair(item: FileChangeItem, state: CodexStreamState): Eng
470
470
  const isFailed = item.status === 'failed';
471
471
 
472
472
  // SDK doesn't carry file content on FileUpdateChange — pull it from the
473
- // rollout JSONL's `patch_apply_end` event so Edit blocks render the real
473
+ // rollout JSONL's patch event so Edit blocks render the real
474
474
  // before/after text and Write blocks the real file body. Falls back to
475
475
  // empty strings if the rollout isn't readable.
476
476
  const changedPaths = item.changes.map(change => change.path);