@myrialabs/clopen 0.4.15 → 0.4.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/artifacts/matrix.ts +8 -0
- package/backend/artifacts/types.ts +2 -2
- package/backend/auth/permissions.ts +14 -0
- package/backend/chat/stream-manager.ts +5 -5
- package/backend/commands/detect.ts +1 -1
- package/backend/commands/sync.ts +1 -1
- package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
- package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
- package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
- package/backend/database/migrations/index.ts +21 -0
- package/backend/engine/README.md +36 -13
- package/backend/engine/adapters/cline/agent-tool.ts +64 -0
- package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
- package/backend/engine/adapters/cline/credential.ts +166 -0
- package/backend/engine/adapters/cline/error-handler.ts +49 -0
- package/backend/engine/adapters/cline/index.ts +1 -0
- package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
- package/backend/engine/adapters/cline/message-converter.ts +396 -0
- package/backend/engine/adapters/cline/models.ts +73 -0
- package/backend/engine/adapters/cline/presets.ts +128 -0
- package/backend/engine/adapters/cline/stream.ts +413 -0
- package/backend/engine/adapters/codex/credential.ts +1 -1
- package/backend/engine/adapters/codex/message-converter.ts +4 -4
- package/backend/engine/adapters/codex/session-fork.ts +1 -1
- package/backend/engine/adapters/codex/stream.ts +3 -3
- package/backend/engine/adapters/copilot/stream.ts +1 -1
- package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
- package/backend/engine/adapters/cursor/credential.ts +68 -0
- package/backend/engine/adapters/cursor/environment.ts +32 -0
- package/backend/engine/adapters/cursor/error-handler.ts +60 -0
- package/backend/engine/adapters/cursor/index.ts +1 -0
- package/backend/engine/adapters/cursor/message-converter.ts +615 -0
- package/backend/engine/adapters/cursor/models.ts +68 -0
- package/backend/engine/adapters/cursor/session-fork.ts +68 -0
- package/backend/engine/adapters/cursor/stream.ts +341 -0
- package/backend/engine/adapters/pi/agent-tool.ts +62 -0
- package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
- package/backend/engine/adapters/pi/credential.ts +137 -0
- package/backend/engine/adapters/pi/environment.ts +33 -0
- package/backend/engine/adapters/pi/error-handler.ts +46 -0
- package/backend/engine/adapters/pi/index.ts +1 -0
- package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
- package/backend/engine/adapters/pi/message-converter.ts +446 -0
- package/backend/engine/adapters/pi/models.ts +53 -0
- package/backend/engine/adapters/pi/presets.ts +133 -0
- package/backend/engine/adapters/pi/session-fork.ts +46 -0
- package/backend/engine/adapters/pi/stream.ts +427 -0
- package/backend/engine/adapters/qwen/message-converter.ts +5 -5
- package/backend/engine/adapters/qwen/stream.ts +2 -2
- package/backend/engine/docs/adapter-contract.md +7 -2
- package/backend/engine/docs/adding-an-engine.md +70 -12
- package/backend/engine/docs/artifacts.md +124 -0
- package/backend/engine/docs/database.md +4 -4
- package/backend/engine/docs/frontend-and-chat.md +22 -4
- package/backend/engine/docs/lessons-learned.md +219 -32
- package/backend/engine/docs/quick-reference.md +18 -7
- package/backend/engine/docs/websocket-routes.md +2 -2
- package/backend/engine/index.ts +9 -0
- package/backend/mcp/README.md +3 -3
- package/backend/mcp/external/config.ts +11 -0
- package/backend/mcp/index.ts +8 -0
- package/backend/mcp/internal/config.ts +33 -1
- package/backend/permissions/service.ts +5 -2
- package/backend/skills/sync.ts +1 -1
- package/backend/subagents/detect.ts +1 -1
- package/backend/subagents/sync.ts +1 -1
- package/backend/ws/chat/stream.ts +1 -1
- package/backend/ws/engine/cline/accounts.ts +317 -0
- package/backend/ws/engine/cline/index.ts +15 -0
- package/backend/ws/engine/cline/presets.ts +36 -0
- package/backend/ws/engine/cline/status.ts +49 -0
- package/backend/ws/engine/codex/accounts.ts +1 -1
- package/backend/ws/engine/cursor/accounts.ts +162 -0
- package/backend/ws/engine/cursor/index.ts +13 -0
- package/backend/ws/engine/cursor/status.ts +55 -0
- package/backend/ws/engine/index.ts +6 -0
- package/backend/ws/engine/pi/accounts.ts +319 -0
- package/backend/ws/engine/pi/index.ts +15 -0
- package/backend/ws/engine/pi/presets.ts +34 -0
- package/backend/ws/engine/pi/status.ts +50 -0
- package/backend/ws/sessions/crud.ts +2 -2
- package/backend/ws/settings/crud.ts +2 -2
- package/dist/assets/{index-EunAFLxP.js → index-BPvctwJ2.js} +1 -1
- package/dist/assets/{index-ChF_jIXj.js → index-vLKZpWQH.js} +1 -1
- package/dist/assets/{main-CTs4NXwP.js → main-BtBZvCwv.js} +359 -357
- package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
- package/dist/index.html +2 -2
- package/package.json +7 -1
- package/shared/constants/engine-tools.ts +16 -2
- package/shared/constants/engines.ts +27 -0
- package/shared/types/unified/common.ts +1 -1
- package/shared/types/unified/engine.ts +82 -1
- package/shared/types/unified/index.ts +6 -0
- package/shared/types/unified/message.ts +1 -1
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cline provider catalog.
|
|
3
|
+
*
|
|
4
|
+
* Cline ships a built-in provider catalog (Anthropic, OpenAI, Google, Bedrock,
|
|
5
|
+
* Mistral, the Cline account, OpenAI-compatible, …). Rather than hardcode them,
|
|
6
|
+
* we enumerate the catalog from `@cline/llms` (`getAllProviders`) and derive each
|
|
7
|
+
* provider's auth shape from `getProviderConfigFields` + `isOAuthProvider`, then
|
|
8
|
+
* expose the result to the login picker via `engine:cline-presets-list`.
|
|
9
|
+
*
|
|
10
|
+
* The wire types (`ClineProviderPreset`, `ClineAuthMode`, `ClineCredentialField`)
|
|
11
|
+
* live in `shared/types/unified/engine.ts` so the frontend stays typed without
|
|
12
|
+
* importing `$backend`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { Llms, getProviderConfigFields, isOAuthProvider } from '@cline/sdk';
|
|
16
|
+
import type { ClineAuthMode, ClineCredentialField, ClineProviderPreset } from '$shared/types/unified';
|
|
17
|
+
import { debug } from '$shared/utils/logger';
|
|
18
|
+
|
|
19
|
+
export type { ClineAuthMode, ClineCredentialField, ClineProviderPreset };
|
|
20
|
+
|
|
21
|
+
/** Where to obtain an API key, keyed by Cline provider id (best-effort hints). */
|
|
22
|
+
const API_KEY_URLS: Record<string, string> = {
|
|
23
|
+
anthropic: 'https://console.anthropic.com/settings/keys',
|
|
24
|
+
openai: 'https://platform.openai.com/api-keys',
|
|
25
|
+
'openai-native': 'https://platform.openai.com/api-keys',
|
|
26
|
+
gemini: 'https://aistudio.google.com/apikey',
|
|
27
|
+
google: 'https://aistudio.google.com/apikey',
|
|
28
|
+
mistral: 'https://console.mistral.ai/api-keys',
|
|
29
|
+
deepseek: 'https://platform.deepseek.com/api_keys',
|
|
30
|
+
openrouter: 'https://openrouter.ai/keys',
|
|
31
|
+
groq: 'https://console.groq.com/keys',
|
|
32
|
+
xai: 'https://console.x.ai',
|
|
33
|
+
together: 'https://api.together.ai/settings/api-keys',
|
|
34
|
+
fireworks: 'https://fireworks.ai/account/api-keys',
|
|
35
|
+
cerebras: 'https://cloud.cerebras.ai',
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** Human labels for the OAuth (sign-in) option, keyed by provider id. */
|
|
39
|
+
const OAUTH_LABELS: Record<string, string> = {
|
|
40
|
+
cline: 'Sign in with Cline',
|
|
41
|
+
anthropic: 'Sign in with Claude Pro/Max',
|
|
42
|
+
'claude-code': 'Sign in with Claude Code',
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** Human-readable field labels, keyed by the Cline config-field key. */
|
|
46
|
+
const FIELD_LABELS: Record<string, string> = {
|
|
47
|
+
apiKey: 'API key',
|
|
48
|
+
baseUrl: 'Base URL',
|
|
49
|
+
azureApiVersion: 'Azure API version',
|
|
50
|
+
awsRegion: 'AWS region',
|
|
51
|
+
awsProfile: 'AWS profile',
|
|
52
|
+
gcpProjectId: 'GCP project ID',
|
|
53
|
+
gcpRegion: 'GCP region',
|
|
54
|
+
sapClientId: 'SAP client ID',
|
|
55
|
+
sapClientSecret: 'SAP client secret',
|
|
56
|
+
sapTokenUrl: 'SAP token URL',
|
|
57
|
+
sapResourceGroup: 'SAP resource group',
|
|
58
|
+
sapDeploymentId: 'SAP deployment ID',
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const SECRET_FIELDS = new Set(['apiKey', 'sapClientSecret']);
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Map a provider's `getProviderConfigFields` shape into the wire
|
|
65
|
+
* `ClineCredentialField[]` the account form renders.
|
|
66
|
+
*/
|
|
67
|
+
export function getClineProviderFields(providerId: string): ClineCredentialField[] {
|
|
68
|
+
const config = getProviderConfigFields(providerId);
|
|
69
|
+
const out: ClineCredentialField[] = [];
|
|
70
|
+
for (const [key, req] of Object.entries(config.fields ?? {})) {
|
|
71
|
+
if (!req) continue;
|
|
72
|
+
const role: ClineCredentialField['role'] = key === 'apiKey' ? 'apiKey' : key === 'baseUrl' ? 'baseUrl' : 'field';
|
|
73
|
+
out.push({
|
|
74
|
+
key,
|
|
75
|
+
label: req.label ?? FIELD_LABELS[key] ?? key,
|
|
76
|
+
secret: SECRET_FIELDS.has(key),
|
|
77
|
+
role,
|
|
78
|
+
...(req.placeholder ? { placeholder: req.placeholder } : {}),
|
|
79
|
+
...(req.optional ? { optional: true } : {}),
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
// Providers with no declared fields still accept an API key.
|
|
83
|
+
if (out.length === 0) {
|
|
84
|
+
out.push({ key: 'apiKey', label: 'API key', secret: true, role: 'apiKey', placeholder: 'sk-…' });
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let presetsCache: ClineProviderPreset[] | null = null;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Enumerate Cline's providers and their supported auth modes. Cached — the
|
|
93
|
+
* catalog is static per process. Returns `[]` on any failure (mirrors the
|
|
94
|
+
* dynamic-catalog `[]`-on-failure contract so the picker renders empty rather
|
|
95
|
+
* than a stale list).
|
|
96
|
+
*/
|
|
97
|
+
export async function getClineProviderPresets(): Promise<ClineProviderPreset[]> {
|
|
98
|
+
if (presetsCache) return presetsCache;
|
|
99
|
+
try {
|
|
100
|
+
const presets: ClineProviderPreset[] = [];
|
|
101
|
+
for (const provider of await Llms.getAllProviders()) {
|
|
102
|
+
const config = getProviderConfigFields(provider.id);
|
|
103
|
+
const oauth = isOAuthProvider(provider.id) || config.authMethod === 'oauth';
|
|
104
|
+
const fields = getClineProviderFields(provider.id);
|
|
105
|
+
const hasApiKey = config.authMethod === 'api-key' || config.authMethod === 'local' || fields.some(f => f.role === 'apiKey');
|
|
106
|
+
|
|
107
|
+
const authModes: ClineAuthMode[] = [];
|
|
108
|
+
if (hasApiKey) authModes.push('api_key');
|
|
109
|
+
if (oauth) authModes.push('oauth');
|
|
110
|
+
if (authModes.length === 0) authModes.push('api_key');
|
|
111
|
+
|
|
112
|
+
presets.push({
|
|
113
|
+
id: provider.id,
|
|
114
|
+
name: provider.name || provider.id,
|
|
115
|
+
authModes,
|
|
116
|
+
...(authModes.includes('api_key') ? { fields } : {}),
|
|
117
|
+
...(OAUTH_LABELS[provider.id] ? { oauthLabel: OAUTH_LABELS[provider.id] } : {}),
|
|
118
|
+
...(API_KEY_URLS[provider.id] ? { apiKeyUrl: API_KEY_URLS[provider.id] } : {}),
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
presets.sort((a, b) => a.name.localeCompare(b.name));
|
|
122
|
+
presetsCache = presets;
|
|
123
|
+
return presets;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
debug.warn('engine', `Cline presets: failed to enumerate providers: ${error instanceof Error ? error.message : String(error)}`);
|
|
126
|
+
return [];
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cline Engine Adapter
|
|
3
|
+
*
|
|
4
|
+
* Wraps `@cline/sdk` into the AIEngine interface. Structurally close to the Pi
|
|
5
|
+
* adapter, with three deliberate choices:
|
|
6
|
+
*
|
|
7
|
+
* 1. **Stateless `Agent`, not `ClineCore`.** Clopen already owns session
|
|
8
|
+
* persistence (stream-manager + DB), and `ClineCore` derives its storage
|
|
9
|
+
* root from `$HOME/.cline` with no redirect env var — which would collide
|
|
10
|
+
* with the user's real Cline data. The stateless `Agent` writes nothing to
|
|
11
|
+
* disk; we bring the built-in coding tools in via `createBuiltinTools`.
|
|
12
|
+
* 2. **Subscribe, not async-generator.** `Agent.subscribe(listener)` +
|
|
13
|
+
* `agent.run()` drive output. `streamQuery` bridges that push stream into
|
|
14
|
+
* the required `AsyncGenerator<EngineOutput>` via a small pushable queue.
|
|
15
|
+
* 3. **Multi-provider, DB-backed credentials.** Each stream resolves the
|
|
16
|
+
* account matching the model's provider from `engine_accounts` and feeds its
|
|
17
|
+
* api-key (or refreshed OAuth token) into the provider-form `Agent` config.
|
|
18
|
+
*
|
|
19
|
+
* MCP tools + AskUserQuestion are bridged as in-process custom tools (Cline has
|
|
20
|
+
* no headless MCP/ask path for the stateless loop). Resume keeps context within
|
|
21
|
+
* the running server via `restore()` of the prior transcript.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { Agent, createBuiltinTools, getClineDefaultSystemPrompt } from '@cline/sdk';
|
|
25
|
+
import type { AgentTool, ToolPolicy } from '@cline/sdk';
|
|
26
|
+
import type { AgentMessage, AgentMessagePart, AgentRunResult } from '@cline/agents';
|
|
27
|
+
import type { EngineOutput, EngineModel, MessageEngine } from '$shared/types/unified';
|
|
28
|
+
import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
|
|
29
|
+
import { resolveOsPath } from '$backend/utils/paths';
|
|
30
|
+
import { debug } from '$shared/utils/logger';
|
|
31
|
+
import { engineQueries } from '$backend/database/queries/engine-queries';
|
|
32
|
+
import { syncSkills } from '$backend/skills';
|
|
33
|
+
import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
|
|
34
|
+
import { artifactFilter } from '$backend/profiles';
|
|
35
|
+
import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
|
|
36
|
+
import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
37
|
+
import { subagentQueries } from '$backend/database/queries';
|
|
38
|
+
import { readSubagentMd } from '$backend/subagents/store';
|
|
39
|
+
import { getClineAccountForProvider, parseClineCredential, resolveClineAuth } from './credential';
|
|
40
|
+
import { fetchClineModels } from './models';
|
|
41
|
+
import { buildClineMcpTools } from './mcp-tools';
|
|
42
|
+
import { createAskUserQuestionTool, formatAnswers, type PendingAsk } from './ask-question-tool';
|
|
43
|
+
import { createAgentDispatchTool, type SubagentInfo } from './agent-tool';
|
|
44
|
+
import { createClineMessageConverter } from './message-converter';
|
|
45
|
+
import { handleStreamError } from './error-handler';
|
|
46
|
+
|
|
47
|
+
/** Cline built-in coding tools (createBuiltinTools defaults; ask/submit are off). */
|
|
48
|
+
const CLINE_BUILTIN_TOOLS = ['read_files', 'search_codebase', 'run_commands', 'fetch_web_content', 'apply_patch', 'editor', 'skills'];
|
|
49
|
+
|
|
50
|
+
/** Max per-turn transcripts kept in memory before FIFO eviction (branch history). */
|
|
51
|
+
const MAX_TRACKED_SESSIONS = 500;
|
|
52
|
+
|
|
53
|
+
type ClineAgent = InstanceType<typeof Agent>;
|
|
54
|
+
|
|
55
|
+
/** Strip YAML frontmatter from a subagent markdown doc, leaving the instructions. */
|
|
56
|
+
function stripFrontmatter(md: string): string {
|
|
57
|
+
const match = md.match(/^---\n[\s\S]*?\n---\n?/);
|
|
58
|
+
return (match ? md.slice(match[0].length) : md).trim();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Minimal pushable queue bridging Cline's subscribe stream → an async generator. */
|
|
62
|
+
class EventQueue<T> {
|
|
63
|
+
private buffer: T[] = [];
|
|
64
|
+
private wake: (() => void) | null = null;
|
|
65
|
+
private done = false;
|
|
66
|
+
private error: unknown = null;
|
|
67
|
+
|
|
68
|
+
push(value: T): void { this.buffer.push(value); this.signal(); }
|
|
69
|
+
close(): void { this.done = true; this.signal(); }
|
|
70
|
+
fail(error: unknown): void { this.error = error; this.done = true; this.signal(); }
|
|
71
|
+
|
|
72
|
+
private signal(): void {
|
|
73
|
+
const wake = this.wake;
|
|
74
|
+
this.wake = null;
|
|
75
|
+
wake?.();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async *drain(): AsyncGenerator<T, void, unknown> {
|
|
79
|
+
while (true) {
|
|
80
|
+
while (this.buffer.length) yield this.buffer.shift() as T;
|
|
81
|
+
if (this.error) throw this.error;
|
|
82
|
+
if (this.done) return;
|
|
83
|
+
await new Promise<void>((resolve) => { this.wake = resolve; });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export class ClineEngine implements AIEngine {
|
|
89
|
+
readonly name = 'cline' as const;
|
|
90
|
+
private _isInitialized = false;
|
|
91
|
+
private activeController: AbortController | null = null;
|
|
92
|
+
private activeAgent: ClineAgent | null = null;
|
|
93
|
+
private pendingAsks = new Map<string, PendingAsk>();
|
|
94
|
+
/**
|
|
95
|
+
* In-memory transcript keyed by the SDK session id EMITTED for each turn.
|
|
96
|
+
* Every turn stores its resulting transcript under a fresh id and never
|
|
97
|
+
* mutates an existing entry — so a checkpoint fork (undo + continue) resumes
|
|
98
|
+
* from the exact ancestor branch instead of whatever was written last. See
|
|
99
|
+
* the branch-awareness note in `streamQuery`.
|
|
100
|
+
*/
|
|
101
|
+
private sessions = new Map<string, AgentMessage[]>();
|
|
102
|
+
|
|
103
|
+
get isInitialized(): boolean { return this._isInitialized; }
|
|
104
|
+
get isActive(): boolean { return this.activeController !== null; }
|
|
105
|
+
|
|
106
|
+
async initialize(): Promise<void> {
|
|
107
|
+
if (this._isInitialized) return;
|
|
108
|
+
this._isInitialized = true;
|
|
109
|
+
debug.log('engine', '✅ Cline engine initialized');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async dispose(): Promise<void> {
|
|
113
|
+
await this.cancel();
|
|
114
|
+
this.pendingAsks.clear();
|
|
115
|
+
this.sessions.clear();
|
|
116
|
+
this._isInitialized = false;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async getAvailableModels(): Promise<EngineModel[]> {
|
|
120
|
+
return fetchClineModels();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private buildSystemPrompt(cwd: string, providerId: string, profileId?: number): string {
|
|
124
|
+
let base: string;
|
|
125
|
+
try {
|
|
126
|
+
base = getClineDefaultSystemPrompt({ cwd, workspaceRoot: cwd, providerId, platform: process.platform });
|
|
127
|
+
} catch {
|
|
128
|
+
base = 'You are Cline, a highly skilled software engineer. Use the available tools to complete the user\'s coding task.';
|
|
129
|
+
}
|
|
130
|
+
const artifacts = buildArtifactsPromptContext(profileId);
|
|
131
|
+
return artifacts ? `${base}\n\n${artifacts}` : base;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
|
|
135
|
+
const { projectPath, prompt, resume, providerSlug, modelId, abortController, accountId } = options;
|
|
136
|
+
debug.log('chat', 'Cline - Stream Query', { providerSlug, modelId, resume });
|
|
137
|
+
|
|
138
|
+
// ── Resolve account + credential for the model's provider ──
|
|
139
|
+
const account = getClineAccountForProvider(providerSlug)
|
|
140
|
+
?? (accountId != null ? engineQueries.getAccount(accountId) : null);
|
|
141
|
+
if (!account) {
|
|
142
|
+
throw new Error(`Cline has no account for provider "${providerSlug}". Add one in Settings → Engines → Cline.`);
|
|
143
|
+
}
|
|
144
|
+
const provider = parseClineCredential(account.credential)?.provider ?? providerSlug;
|
|
145
|
+
const auth = await resolveClineAuth(account);
|
|
146
|
+
|
|
147
|
+
this.activeController = abortController || new AbortController();
|
|
148
|
+
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
149
|
+
|
|
150
|
+
// ── Active Profile scoping + artifact materialization ──
|
|
151
|
+
const profileId = options.mcpContext?.profileId;
|
|
152
|
+
const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
|
|
153
|
+
await syncSkills('cline', profileId);
|
|
154
|
+
await syncEngineArtifacts('cline', profileId);
|
|
155
|
+
|
|
156
|
+
// ── Permissions → toolPolicies (denied builtins are hidden from the model) ──
|
|
157
|
+
const permissions = resolvePermissionsFromDb('cline', options.mcpContext?.projectId, profileId);
|
|
158
|
+
|
|
159
|
+
// Late-bound handle to the stream's event queue so the subagent runner
|
|
160
|
+
// (built before the queue exists) can push its sub-activity messages into it.
|
|
161
|
+
const queueHolder: { queue: EventQueue<EngineOutput> | null } = { queue: null };
|
|
162
|
+
|
|
163
|
+
// ── Tools: builtins + AskUserQuestion + MCP bridge ──
|
|
164
|
+
const builtinTools = createBuiltinTools({
|
|
165
|
+
cwd: resolvedProjectPath,
|
|
166
|
+
enableAskQuestion: false,
|
|
167
|
+
enableSubmitAndExit: false,
|
|
168
|
+
});
|
|
169
|
+
const askTool = createAskUserQuestionTool({
|
|
170
|
+
register: (id, entry) => this.pendingAsks.set(id, entry),
|
|
171
|
+
unregister: (id) => this.pendingAsks.delete(id),
|
|
172
|
+
});
|
|
173
|
+
const mcpTools = await buildClineMcpTools(options.mcpContext, mcpProfileFilter);
|
|
174
|
+
const tools: AgentTool[] = [...builtinTools, askTool, ...mcpTools];
|
|
175
|
+
|
|
176
|
+
const toolPolicies: Record<string, ToolPolicy> = {};
|
|
177
|
+
for (const name of CLINE_BUILTIN_TOOLS) {
|
|
178
|
+
toolPolicies[name] = isToolAllowed(permissions, name) ? { autoApprove: true } : { enabled: false };
|
|
179
|
+
}
|
|
180
|
+
toolPolicies.AskUserQuestion = { autoApprove: true };
|
|
181
|
+
for (const t of mcpTools) toolPolicies[t.name] = { autoApprove: true };
|
|
182
|
+
|
|
183
|
+
// ── Subagents: Cline's stateless Agent has no native Agent/Task tool, so the
|
|
184
|
+
// "Available Subagents" preamble alone can't be invoked. Expose an `Agent`
|
|
185
|
+
// tool that actually spawns a bounded sub-`Agent` with the chosen subagent's
|
|
186
|
+
// system prompt and returns its final text. ──
|
|
187
|
+
const subagents: SubagentInfo[] = subagentQueries.getEnabled().map(s => ({ slug: s.slug, name: s.name, description: s.description }));
|
|
188
|
+
if (subagents.length > 0) {
|
|
189
|
+
const agentTool = createAgentDispatchTool({
|
|
190
|
+
subagents,
|
|
191
|
+
run: async (subagent, subPrompt, toolCallId, signal) => {
|
|
192
|
+
const md = (await readSubagentMd(subagent.slug)) ?? '';
|
|
193
|
+
const instructions = stripFrontmatter(md) || `You are the ${subagent.name} subagent. ${subagent.description}`;
|
|
194
|
+
// APPEND the subagent instructions to Cline's base coding prompt (a
|
|
195
|
+
// bare instruction strips the tool-use scaffolding). The sub-Agent gets
|
|
196
|
+
// the permission-filtered builtins ONLY — no AskUserQuestion, no MCP,
|
|
197
|
+
// and no nested Agent tool — so delegation stays bounded.
|
|
198
|
+
let base: string;
|
|
199
|
+
try {
|
|
200
|
+
base = getClineDefaultSystemPrompt({ cwd: resolvedProjectPath, workspaceRoot: resolvedProjectPath, providerId: provider, platform: process.platform });
|
|
201
|
+
} catch {
|
|
202
|
+
base = 'You are Cline, a highly skilled software engineer.';
|
|
203
|
+
}
|
|
204
|
+
const subAgent = new Agent({
|
|
205
|
+
providerId: provider,
|
|
206
|
+
modelId,
|
|
207
|
+
...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
|
|
208
|
+
...(auth.baseUrl ? { baseUrl: auth.baseUrl } : {}),
|
|
209
|
+
...(auth.options ? { options: auth.options } : {}),
|
|
210
|
+
systemPrompt: `${base}\n\n# Subagent: ${subagent.name}\n\n${instructions}`,
|
|
211
|
+
tools: builtinTools,
|
|
212
|
+
toolPolicies,
|
|
213
|
+
maxIterations: 30,
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
// Route the sub-agent's persisted messages into the PARENT stream as
|
|
217
|
+
// sub-activities: tag each with `parent.toolUseId = <Agent block id>`
|
|
218
|
+
// so the frontend folds them under the Agent tool. Only tool_use
|
|
219
|
+
// steps (+ their tool_result) are surfaced — the collapsed sub-agent
|
|
220
|
+
// view is a tool trail; the sub-agent's prose is already returned as
|
|
221
|
+
// the Agent tool's result (its `outputText`). So we drop transient
|
|
222
|
+
// events, reasoning, and text-only assistant messages.
|
|
223
|
+
const subConverter = createClineMessageConverter({
|
|
224
|
+
engine: { type: 'cline', provider, model: { id: modelId, name: modelId }, account: { id: account.id, name: account.name } },
|
|
225
|
+
sessionId: crypto.randomUUID(),
|
|
226
|
+
});
|
|
227
|
+
const unsub = subAgent.subscribe((ev) => {
|
|
228
|
+
for (const out of subConverter.convert(ev)) {
|
|
229
|
+
if (out.type === 'user') {
|
|
230
|
+
// tool_result messages — carry the sub-agent's tool outputs.
|
|
231
|
+
} else if (out.type === 'assistant' && out.content.some(b => b.type === 'tool_use')) {
|
|
232
|
+
// tool_use step — keep.
|
|
233
|
+
} else {
|
|
234
|
+
continue; // drop stream/result/init/notification/reasoning/text-only
|
|
235
|
+
}
|
|
236
|
+
out.parent = { messageId: null, sessionId: null, toolUseId: toolCallId };
|
|
237
|
+
queueHolder.queue?.push(out);
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
const onSubAbort = () => { try { subAgent.abort('Parent cancelled'); } catch { /* ignore */ } };
|
|
242
|
+
signal?.addEventListener('abort', onSubAbort, { once: true });
|
|
243
|
+
try {
|
|
244
|
+
const result = await subAgent.run(subPrompt);
|
|
245
|
+
return result.outputText ?? '';
|
|
246
|
+
} finally {
|
|
247
|
+
signal?.removeEventListener('abort', onSubAbort);
|
|
248
|
+
unsub();
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
tools.push(agentTool);
|
|
253
|
+
toolPolicies.Agent = { autoApprove: true };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const toolNames = tools.filter(t => toolPolicies[t.name]?.enabled !== false).map(t => t.name);
|
|
257
|
+
|
|
258
|
+
// ── Resume / fork (branch-aware) ──
|
|
259
|
+
// `resume` is the parent branch's per-turn session id (stream-manager
|
|
260
|
+
// derives it from the prompt's `parent.sessionId`). We ALWAYS mint a fresh
|
|
261
|
+
// id for this turn and copy the parent's transcript forward — so two turns
|
|
262
|
+
// that share the same parent (a checkpoint fork: A→B→C vs A→B1→C1) each get
|
|
263
|
+
// an independent history and never leak the sibling branch's messages.
|
|
264
|
+
const priorMessages = resume ? this.sessions.get(resume) : undefined;
|
|
265
|
+
const sessionId = crypto.randomUUID();
|
|
266
|
+
|
|
267
|
+
const systemPrompt = this.buildSystemPrompt(resolvedProjectPath, provider, profileId);
|
|
268
|
+
const agent = new Agent({
|
|
269
|
+
providerId: provider,
|
|
270
|
+
modelId,
|
|
271
|
+
...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
|
|
272
|
+
...(auth.baseUrl ? { baseUrl: auth.baseUrl } : {}),
|
|
273
|
+
...(auth.options ? { options: auth.options } : {}),
|
|
274
|
+
systemPrompt,
|
|
275
|
+
tools,
|
|
276
|
+
toolPolicies,
|
|
277
|
+
maxIterations: options.maxTurns ?? 100,
|
|
278
|
+
});
|
|
279
|
+
this.activeAgent = agent;
|
|
280
|
+
if (priorMessages?.length) agent.restore(priorMessages);
|
|
281
|
+
|
|
282
|
+
const engineMeta: MessageEngine = {
|
|
283
|
+
type: 'cline',
|
|
284
|
+
provider,
|
|
285
|
+
model: { id: modelId, name: modelId },
|
|
286
|
+
account: { id: account.id, name: account.name },
|
|
287
|
+
};
|
|
288
|
+
const converter = createClineMessageConverter({ engine: engineMeta, sessionId });
|
|
289
|
+
const queue = new EventQueue<EngineOutput>();
|
|
290
|
+
queueHolder.queue = queue;
|
|
291
|
+
const unsubscribe = agent.subscribe((event) => {
|
|
292
|
+
try {
|
|
293
|
+
for (const out of converter.convert(event)) queue.push(out);
|
|
294
|
+
} catch (error) {
|
|
295
|
+
queue.fail(error);
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
// Abort wiring: cancelling the stream aborts the Cline run.
|
|
300
|
+
const onAbort = () => { agent.abort('Cancelled'); };
|
|
301
|
+
this.activeController.signal.addEventListener('abort', onAbort, { once: true });
|
|
302
|
+
|
|
303
|
+
// Build the user turn (text + image attachments).
|
|
304
|
+
const promptText = prompt.content.filter(b => b.type === 'text').map(b => (b.type === 'text' ? b.text : '')).join('\n');
|
|
305
|
+
const content: AgentMessagePart[] = [{ type: 'text', text: promptText }];
|
|
306
|
+
for (const b of prompt.content) {
|
|
307
|
+
if (b.type === 'image') content.push({ type: 'image', image: `data:${b.mediaType};base64,${b.data}`, mediaType: b.mediaType });
|
|
308
|
+
}
|
|
309
|
+
const userMessage: AgentMessage = { id: crypto.randomUUID(), role: 'user', content, createdAt: Date.now() };
|
|
310
|
+
|
|
311
|
+
// system_init first — model + enabled tools (Cline bridges MCP as custom tools).
|
|
312
|
+
yield {
|
|
313
|
+
type: 'system_init',
|
|
314
|
+
sessionId,
|
|
315
|
+
model: modelId,
|
|
316
|
+
engine: 'cline',
|
|
317
|
+
tools: toolNames,
|
|
318
|
+
mcpServers: [],
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
const runPromise: Promise<AgentRunResult> = priorMessages?.length ? agent.continue(userMessage) : agent.run(userMessage);
|
|
322
|
+
const settle = runPromise
|
|
323
|
+
.then((result) => {
|
|
324
|
+
// Store this turn's full transcript under its OWN new id — never
|
|
325
|
+
// overwrite the parent (`resume`) entry, so sibling forks stay isolated.
|
|
326
|
+
this.sessions.set(sessionId, [...result.messages]);
|
|
327
|
+
// Bound the map so a long-lived project engine can't grow unbounded.
|
|
328
|
+
// FIFO eviction: forking from a very old (evicted) checkpoint simply
|
|
329
|
+
// starts fresh, same graceful degradation as a cross-restart resume.
|
|
330
|
+
while (this.sessions.size > MAX_TRACKED_SESSIONS) {
|
|
331
|
+
const oldest = this.sessions.keys().next().value;
|
|
332
|
+
if (oldest === undefined) break;
|
|
333
|
+
this.sessions.delete(oldest);
|
|
334
|
+
}
|
|
335
|
+
if (result.status === 'failed') {
|
|
336
|
+
queue.fail(result.error ?? new Error('Cline run failed'));
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
queue.close();
|
|
340
|
+
})
|
|
341
|
+
.catch((error) => queue.fail(error));
|
|
342
|
+
|
|
343
|
+
try {
|
|
344
|
+
for await (const out of queue.drain()) yield out;
|
|
345
|
+
await settle;
|
|
346
|
+
} catch (error) {
|
|
347
|
+
handleStreamError(error);
|
|
348
|
+
} finally {
|
|
349
|
+
this.activeController?.signal.removeEventListener('abort', onAbort);
|
|
350
|
+
unsubscribe();
|
|
351
|
+
this.activeAgent = null;
|
|
352
|
+
this.activeController = null;
|
|
353
|
+
this.pendingAsks.clear();
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async cancel(): Promise<void> {
|
|
358
|
+
if (this.activeController && !this.activeController.signal.aborted) {
|
|
359
|
+
this.activeController.abort();
|
|
360
|
+
}
|
|
361
|
+
if (this.activeAgent) {
|
|
362
|
+
try { this.activeAgent.abort('Cancelled'); } catch { /* may already be idle */ }
|
|
363
|
+
}
|
|
364
|
+
this.pendingAsks.clear();
|
|
365
|
+
this.activeAgent = null;
|
|
366
|
+
this.activeController = null;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async interrupt(): Promise<void> {
|
|
370
|
+
if (this.activeAgent) {
|
|
371
|
+
try { this.activeAgent.abort('Interrupted'); } catch { /* ignore */ }
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
|
|
376
|
+
const pending = this.pendingAsks.get(toolUseId);
|
|
377
|
+
if (!pending) {
|
|
378
|
+
debug.warn('engine', `Cline resolveUserAnswer: no pending question for ${toolUseId}`);
|
|
379
|
+
return false;
|
|
380
|
+
}
|
|
381
|
+
pending.resolve(formatAnswers(pending.questions, answers));
|
|
382
|
+
this.pendingAsks.delete(toolUseId);
|
|
383
|
+
return true;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* One-shot structured JSON generation via prompt engineering (no tools). Runs
|
|
388
|
+
* a tool-less `Agent` and parses the final assistant text.
|
|
389
|
+
*/
|
|
390
|
+
async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
|
|
391
|
+
const { prompt, providerSlug, modelId, schema, accountId } = options;
|
|
392
|
+
|
|
393
|
+
const account = getClineAccountForProvider(providerSlug)
|
|
394
|
+
?? (accountId != null ? engineQueries.getAccount(accountId) : null);
|
|
395
|
+
if (!account) throw new Error(`Cline has no account for provider "${providerSlug}".`);
|
|
396
|
+
const provider = parseClineCredential(account.credential)?.provider ?? providerSlug;
|
|
397
|
+
const auth = await resolveClineAuth(account);
|
|
398
|
+
|
|
399
|
+
const agent = new Agent({
|
|
400
|
+
providerId: provider,
|
|
401
|
+
modelId,
|
|
402
|
+
...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
|
|
403
|
+
...(auth.baseUrl ? { baseUrl: auth.baseUrl } : {}),
|
|
404
|
+
...(auth.options ? { options: auth.options } : {}),
|
|
405
|
+
systemPrompt: 'You output only valid JSON. No prose, no markdown fences.',
|
|
406
|
+
maxIterations: 1,
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
const result = await agent.run(buildJsonPrompt(prompt, schema));
|
|
410
|
+
if (!result.outputText?.trim()) throw new Error('Cline returned no structured output');
|
|
411
|
+
return extractJson<T>(result.outputText);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* `~/.codex/auth.json` and refreshes it in-place.
|
|
9
9
|
*
|
|
10
10
|
* Multi-account ChatGPT support uses the **auth-blob swap** pattern (see
|
|
11
|
-
* backend/engine/README.md §
|
|
11
|
+
* backend/engine/README.md §10.13): we snapshot `~/.codex/auth.json` content
|
|
12
12
|
* into `engine_accounts.credential` after login, and write the active
|
|
13
13
|
* account's snapshot back to the shared file on switch / stream-start.
|
|
14
14
|
*
|
|
@@ -254,7 +254,7 @@ export function convertTurnCompleted(event: TurnCompletedEvent, state: CodexStre
|
|
|
254
254
|
// Note: the per-turn `usage` aggregate is NOT attached to individual
|
|
255
255
|
// assistant messages here — they were already saved live during the turn
|
|
256
256
|
// (with usage:null). The stream-manager backfills usage after the result
|
|
257
|
-
// event by looking up each saved row's DB id. See README §
|
|
257
|
+
// event by looking up each saved row's DB id. See README §10.4.
|
|
258
258
|
|
|
259
259
|
const stopLifecycle: StreamLifecycleEvent = {
|
|
260
260
|
type: 'stream_event',
|
|
@@ -439,7 +439,7 @@ function buildToolResultUserMessage(
|
|
|
439
439
|
createdAt: new Date().toISOString(),
|
|
440
440
|
messageId: crypto.randomUUID(),
|
|
441
441
|
sessionId: state.sessionId,
|
|
442
|
-
// IMPORTANT: parent.toolUseId stays null (README §
|
|
442
|
+
// IMPORTANT: parent.toolUseId stays null (README §10.5 sharp edge).
|
|
443
443
|
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
444
444
|
engine: buildEngine(state.modelId),
|
|
445
445
|
sender: { id: '', name: '' },
|
|
@@ -463,7 +463,7 @@ function buildCommandExecutionPair(item: CommandExecutionItem, state: CodexStrea
|
|
|
463
463
|
}
|
|
464
464
|
|
|
465
465
|
function buildFileChangePair(item: FileChangeItem, state: CodexStreamState): EngineOutput[] {
|
|
466
|
-
// Codex bundles N file changes per item. Per README §
|
|
466
|
+
// Codex bundles N file changes per item. Per README §10.3 we split into N
|
|
467
467
|
// separate AssistantMessages so each shows up as its own tool block.
|
|
468
468
|
const out: EngineOutput[] = [];
|
|
469
469
|
const baseId = item.id;
|
|
@@ -557,7 +557,7 @@ function buildWebSearchPair(item: WebSearchItem, state: CodexStreamState): Engin
|
|
|
557
557
|
const block = buildToolUseBlock('WebSearch', input as unknown as Record<string, unknown>, item.id);
|
|
558
558
|
const assistant = createAssistantToolUseMessage(state, block, item.id);
|
|
559
559
|
// Synthetic tool_result so the frontend grouper attaches a non-null
|
|
560
|
-
// result at render time (README §
|
|
560
|
+
// result at render time (README §10.5). Without it `tool_use.result`
|
|
561
561
|
// stays null forever.
|
|
562
562
|
const result = buildToolResultUserMessage(
|
|
563
563
|
item.id,
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
* Earlier versions of this helper assumed a directory layout
|
|
19
19
|
* (`~/.codex/sessions/<thread_id>/`) and so `sessionStateExists()` always
|
|
20
20
|
* returned false — the fork block was silently skipped and resume reused
|
|
21
|
-
* the source thread id, breaking multi-branch checkpoints (README §
|
|
21
|
+
* the source thread id, breaking multi-branch checkpoints (README §10.10
|
|
22
22
|
* sharp edge: "reusing the same id across turns is the symptom that
|
|
23
23
|
* forking is gated or skipped").
|
|
24
24
|
*
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* instance, the `Thread` lifecycle, and an `AbortController` for cancellation.
|
|
7
7
|
*
|
|
8
8
|
* Auth: dual mode (API key + ChatGPT browser OAuth). See ./auth.ts and
|
|
9
|
-
* backend/engine/README.md §
|
|
9
|
+
* backend/engine/README.md §10.13 for the auth-blob swap pattern.
|
|
10
10
|
*
|
|
11
11
|
* MCP: reuses the existing remote MCP HTTP server at /mcp via
|
|
12
12
|
* getCodexMcpConfig() in backend/mcp/config.ts. No new MCP infrastructure.
|
|
@@ -208,7 +208,7 @@ export class CodexEngine implements AIEngine {
|
|
|
208
208
|
|
|
209
209
|
if (resume) {
|
|
210
210
|
// Fork-by-copy on EVERY resume — same semantics as Copilot
|
|
211
|
-
// (README §
|
|
211
|
+
// (README §10.10 sharp edge: never gate on options.forkSession).
|
|
212
212
|
let resumeId = resume;
|
|
213
213
|
if (sessionStateExists(resume)) {
|
|
214
214
|
const forkId = crypto.randomUUID();
|
|
@@ -279,7 +279,7 @@ export class CodexEngine implements AIEngine {
|
|
|
279
279
|
handleStreamError(error);
|
|
280
280
|
} finally {
|
|
281
281
|
// Snapshot the (possibly token-refreshed) auth.json back to DB so
|
|
282
|
-
// refreshes survive across account switches (README §
|
|
282
|
+
// refreshes survive across account switches (README §10.13 step 4).
|
|
283
283
|
try {
|
|
284
284
|
snapshotAuthJsonToActiveAccount();
|
|
285
285
|
} catch (snapshotErr) {
|
|
@@ -356,7 +356,7 @@ export class CopilotEngine implements AIEngine {
|
|
|
356
356
|
includeSubAgentStreamingEvents: false,
|
|
357
357
|
// Custom MCP tools served from Clopen's in-process remote MCP HTTP
|
|
358
358
|
// endpoint (`/mcp`). Same `clopen-mcp` namespace and URL Open Code
|
|
359
|
-
// and Codex consume — see backend/engine/README.md §
|
|
359
|
+
// and Codex consume — see backend/engine/README.md §10.12.
|
|
360
360
|
...(Object.keys(mcpConfig).length > 0 && { mcpServers: mcpConfig }),
|
|
361
361
|
};
|
|
362
362
|
|