@myrialabs/clopen 0.4.14 → 0.4.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/artifacts/matrix.ts +8 -0
- package/backend/artifacts/types.ts +2 -2
- package/backend/auth/permissions.ts +16 -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/056_support_mssql_driver.ts +137 -0
- 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 +28 -0
- package/backend/database/queries/engine-queries.ts +13 -0
- package/backend/database/queries/message-queries.ts +43 -1
- package/backend/db-client/connection-manager.ts +8 -2
- package/backend/db-client/drivers/mssql.ts +829 -0
- package/backend/db-client/drivers/mysql.ts +33 -4
- package/backend/db-client/drivers/postgres.ts +55 -5
- package/backend/db-client/drivers/sql-builders.test.ts +70 -0
- package/backend/db-client/drivers/sql-builders.ts +9 -2
- package/backend/db-client/pool-config.ts +32 -0
- package/backend/db-client/query-executor.test.ts +42 -0
- package/backend/db-client/query-executor.ts +47 -3
- 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/opencode/config.ts +9 -0
- package/backend/engine/adapters/opencode/models.ts +10 -1
- package/backend/engine/adapters/opencode/server.ts +110 -2
- 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/index.ts +6 -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/preview/browser/browser-preview-service.ts +15 -6
- package/backend/preview/browser/browser-video-capture.ts +232 -100
- package/backend/preview/browser/scripts/video-stream.ts +216 -56
- package/backend/preview/browser/types.ts +24 -12
- 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 +13 -5
- package/backend/ws/db-client/connections.ts +2 -1
- package/backend/ws/db-client/query.ts +41 -4
- package/backend/ws/db-client/schema.ts +45 -1
- package/backend/ws/engine/claude/accounts.ts +37 -13
- 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 +37 -5
- package/backend/ws/engine/copilot/accounts.ts +12 -0
- 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/opencode/providers.ts +72 -1
- 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/engine/qwen/accounts.ts +22 -0
- package/backend/ws/messages/crud.ts +13 -0
- package/backend/ws/preview/browser/interact.ts +10 -8
- package/backend/ws/preview/browser/webcodecs.ts +26 -2
- package/backend/ws/sessions/crud.ts +2 -2
- package/backend/ws/settings/crud.ts +2 -2
- package/dist/assets/{index-CDZf6lfv.js → index-BPvctwJ2.js} +1 -1
- package/dist/assets/{index-BWf-DDJN.js → index-vLKZpWQH.js} +1 -1
- package/dist/assets/{main-C15mQTCW.js → main-BtBZvCwv.js} +428 -386
- package/dist/assets/main-D7ATW8pp.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +11 -1
- package/shared/constants/engine-tools.ts +16 -2
- package/shared/constants/engines.ts +27 -0
- package/shared/types/db-client/connection.ts +1 -1
- package/shared/types/db-client/query.ts +4 -1
- 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
- package/shared/utils/db-client/split-sql.test.ts +13 -0
- package/shared/utils/db-client/split-sql.ts +38 -1
- package/shared/utils/subagent-wire-trim.ts +87 -0
- package/dist/assets/main-Ba5ZGlY4.css +0 -1
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor fork-on-resume.
|
|
3
|
+
*
|
|
4
|
+
* Clopen's multi-branch checkpoints require every resumed turn to fork so the
|
|
5
|
+
* source branch's history is never mutated (README §10.10). Cursor has no native
|
|
6
|
+
* fork — `Agent.resume(agentId)` continues the SAME agent in place — so we fork by
|
|
7
|
+
* copying the parent agent's persisted state under a fresh `agentId`:
|
|
8
|
+
*
|
|
9
|
+
* 1. read the parent agent document (metadata + `latestCheckpoint` pointer)
|
|
10
|
+
* 2. copy every content-addressed checkpoint blob to the new agent id
|
|
11
|
+
* 3. write a new agent document seeded with the parent's checkpoint pointer
|
|
12
|
+
*
|
|
13
|
+
* The conversation transcript lives in the checkpoint blobs, so the resumed agent
|
|
14
|
+
* replays the exact ancestor branch. Runs / run-events (the streaming log) are
|
|
15
|
+
* intentionally NOT copied — they are per-turn history, not conversation context.
|
|
16
|
+
*
|
|
17
|
+
* Returns the new agent id, or `undefined` when the parent is missing on disk
|
|
18
|
+
* (evicted / cross-restart) so the caller can gracefully start a fresh agent.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { JsonlLocalAgentStore } from '@cursor/sdk';
|
|
22
|
+
import { debug } from '$shared/utils/logger';
|
|
23
|
+
|
|
24
|
+
/** Page through a checkpoint blob-id listing (id-based cursor). */
|
|
25
|
+
async function listAllCheckpointBlobIds(store: JsonlLocalAgentStore, agentId: string): Promise<string[]> {
|
|
26
|
+
const ids: string[] = [];
|
|
27
|
+
let cursor: string | undefined;
|
|
28
|
+
do {
|
|
29
|
+
const page = await store.checkpoints.list({ filter: { agentIds: [agentId], cursor, limit: 500 } });
|
|
30
|
+
ids.push(...page.items);
|
|
31
|
+
cursor = page.nextCursor;
|
|
32
|
+
} while (cursor);
|
|
33
|
+
return ids;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function forkCursorAgent(store: JsonlLocalAgentStore, parentAgentId: string): Promise<string | undefined> {
|
|
37
|
+
const parent = await store.agents.get({ agentId: parentAgentId });
|
|
38
|
+
if (!parent) {
|
|
39
|
+
debug.warn('engine', `Cursor fork: parent agent ${parentAgentId} not found on disk, starting fresh`);
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const newAgentId = `agent-${crypto.randomUUID()}`;
|
|
44
|
+
|
|
45
|
+
// Copy every checkpoint blob (content-addressed) to the new agent id.
|
|
46
|
+
const blobIds = await listAllCheckpointBlobIds(store, parentAgentId);
|
|
47
|
+
for (const blobId of blobIds) {
|
|
48
|
+
const data = await store.checkpoints.get({ agentId: parentAgentId, blobId });
|
|
49
|
+
if (data) await store.checkpoints.create({ agentId: newAgentId, blobId, data });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Seed the new agent document with the parent's checkpoint pointer. `Date.now()`
|
|
53
|
+
// is fine here (backend runtime, not a workflow script).
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
await store.agents.create({
|
|
56
|
+
agent: {
|
|
57
|
+
...parent,
|
|
58
|
+
agentId: newAgentId,
|
|
59
|
+
status: 'idle',
|
|
60
|
+
activeRunId: null,
|
|
61
|
+
createdAt: now,
|
|
62
|
+
updatedAt: now,
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
debug.log('engine', `Cursor resumed agent ${parentAgentId} → fork ${newAgentId} (${blobIds.length} checkpoint blob(s))`);
|
|
67
|
+
return newAgentId;
|
|
68
|
+
}
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor Engine Adapter
|
|
3
|
+
*
|
|
4
|
+
* Wraps `@cursor/sdk` into the AIEngine interface. Key choices:
|
|
5
|
+
*
|
|
6
|
+
* 1. **Local agents.** `Agent.create({ local: { cwd, store } })` runs the coding
|
|
7
|
+
* agent in-process against the project workspace. Cloud agents (Cursor VMs +
|
|
8
|
+
* GitHub repos) don't fit Clopen's local-project workflow and can't take the
|
|
9
|
+
* in-process custom tools we need, so they're not used.
|
|
10
|
+
* 2. **Native async-generator stream.** `agent.send()` returns a `Run` whose
|
|
11
|
+
* `run.stream()` is already an `AsyncGenerator<SDKMessage>` — no subscribe
|
|
12
|
+
* bridge (unlike Cline/Pi). The message-converter maps each event.
|
|
13
|
+
* 3. **Single-account, API-key auth.** One `CURSOR_API_KEY` per account, passed
|
|
14
|
+
* to `Agent.create({ apiKey })`; multi-account is a pure DB `is_active` swap.
|
|
15
|
+
* 4. **Isolated JSONL store + fork-on-resume.** State lives in Clopen's isolated
|
|
16
|
+
* engine dir via a `JsonlLocalAgentStore` (never `~/.cursor`); every resume
|
|
17
|
+
* forks by copying the parent agent's checkpoints (README §10.10 / §10.19).
|
|
18
|
+
*
|
|
19
|
+
* MCP servers ride Cursor's native `mcpServers` config (the shared `clopen-mcp`
|
|
20
|
+
* bridge). AskUserQuestion is bridged as an in-process custom tool. Subagents map
|
|
21
|
+
* to Cursor's native `agents` config.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { Agent, Cursor } from '@cursor/sdk';
|
|
25
|
+
import type { SDKAgent, Run, SDKUserMessage, SDKImage, AgentDefinition, SDKCustomTool } from '@cursor/sdk';
|
|
26
|
+
import type { EngineOutput, EngineModel, MessageEngine } from '$shared/types/unified';
|
|
27
|
+
import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
|
|
28
|
+
import { resolveOsPath } from '$backend/utils/paths';
|
|
29
|
+
import { debug } from '$shared/utils/logger';
|
|
30
|
+
import { engineQueries } from '$backend/database/queries/engine-queries';
|
|
31
|
+
import { syncSkills } from '$backend/skills';
|
|
32
|
+
import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
|
|
33
|
+
import { artifactFilter } from '$backend/profiles';
|
|
34
|
+
import { getCursorMcpConfig } from '../../../mcp';
|
|
35
|
+
import { subagentQueries } from '$backend/database/queries';
|
|
36
|
+
import { readSubagentMd } from '$backend/subagents/store';
|
|
37
|
+
import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
38
|
+
import { getActiveCursorAccount, resolveCursorApiKey } from './credential';
|
|
39
|
+
import { getCursorStore } from './environment';
|
|
40
|
+
import { forkCursorAgent } from './session-fork';
|
|
41
|
+
import { fetchCursorModels } from './models';
|
|
42
|
+
import { createAskUserQuestionTool, formatAnswers, type PendingAsk } from './ask-question-tool';
|
|
43
|
+
import { createCursorMessageConverter } from './message-converter';
|
|
44
|
+
import { handleStreamError } from './error-handler';
|
|
45
|
+
|
|
46
|
+
/** Strip YAML frontmatter from a subagent markdown doc, leaving the instructions. */
|
|
47
|
+
function stripFrontmatter(md: string): string {
|
|
48
|
+
const match = md.match(/^---\n[\s\S]*?\n---\n?/);
|
|
49
|
+
return (match ? md.slice(match[0].length) : md).trim();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Minimal pushable queue merging Cursor's pull stream (`run.stream()`) with the
|
|
54
|
+
* push emissions of the in-process AskUserQuestion custom tool into one ordered
|
|
55
|
+
* async generator. The ask tool fires from inside the SDK's tool executor (a
|
|
56
|
+
* separate async flow from the stream loop), so a plain `for await` can't carry
|
|
57
|
+
* its emission — the queue is the merge point.
|
|
58
|
+
*/
|
|
59
|
+
class EventQueue<T> {
|
|
60
|
+
private buffer: T[] = [];
|
|
61
|
+
private wake: (() => void) | null = null;
|
|
62
|
+
private done = false;
|
|
63
|
+
private error: unknown = null;
|
|
64
|
+
|
|
65
|
+
push(value: T): void { this.buffer.push(value); this.signal(); }
|
|
66
|
+
close(): void { this.done = true; this.signal(); }
|
|
67
|
+
fail(error: unknown): void { this.error = error; this.done = true; this.signal(); }
|
|
68
|
+
|
|
69
|
+
private signal(): void {
|
|
70
|
+
const wake = this.wake;
|
|
71
|
+
this.wake = null;
|
|
72
|
+
wake?.();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async *drain(): AsyncGenerator<T, void, unknown> {
|
|
76
|
+
while (true) {
|
|
77
|
+
while (this.buffer.length) yield this.buffer.shift() as T;
|
|
78
|
+
if (this.error) throw this.error;
|
|
79
|
+
if (this.done) return;
|
|
80
|
+
await new Promise<void>((resolve) => { this.wake = resolve; });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export class CursorEngine implements AIEngine {
|
|
86
|
+
readonly name = 'cursor' as const;
|
|
87
|
+
private _isInitialized = false;
|
|
88
|
+
private activeController: AbortController | null = null;
|
|
89
|
+
private activeRun: Run | null = null;
|
|
90
|
+
private activeAgent: SDKAgent | null = null;
|
|
91
|
+
private pendingAsks = new Map<string, PendingAsk>();
|
|
92
|
+
|
|
93
|
+
get isInitialized(): boolean { return this._isInitialized; }
|
|
94
|
+
get isActive(): boolean { return this.activeController !== null; }
|
|
95
|
+
|
|
96
|
+
async initialize(): Promise<void> {
|
|
97
|
+
if (this._isInitialized) return;
|
|
98
|
+
this._isInitialized = true;
|
|
99
|
+
debug.log('engine', '✅ Cursor engine initialized');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async dispose(): Promise<void> {
|
|
103
|
+
await this.cancel();
|
|
104
|
+
this.pendingAsks.clear();
|
|
105
|
+
this._isInitialized = false;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async getAvailableModels(): Promise<EngineModel[]> {
|
|
109
|
+
return fetchCursorModels();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Build the `agents` config from Clopen's enabled subagents (Cursor-native). */
|
|
113
|
+
private async buildAgents(): Promise<Record<string, AgentDefinition> | undefined> {
|
|
114
|
+
const subagents = subagentQueries.getEnabled();
|
|
115
|
+
if (subagents.length === 0) return undefined;
|
|
116
|
+
const agents: Record<string, AgentDefinition> = {};
|
|
117
|
+
for (const s of subagents) {
|
|
118
|
+
const md = (await readSubagentMd(s.slug)) ?? '';
|
|
119
|
+
const prompt = stripFrontmatter(md) || `You are the ${s.name} subagent. ${s.description}`;
|
|
120
|
+
agents[s.slug] = { description: s.description || s.name, prompt, model: 'inherit' };
|
|
121
|
+
}
|
|
122
|
+
return agents;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
|
|
126
|
+
const { projectPath, prompt, resume, modelId, abortController, accountId } = options;
|
|
127
|
+
debug.log('chat', 'Cursor - Stream Query', { modelId, resume });
|
|
128
|
+
|
|
129
|
+
// ── Resolve account + API key ──
|
|
130
|
+
const account = (accountId != null ? engineQueries.getAccount(accountId) : null) ?? getActiveCursorAccount();
|
|
131
|
+
if (!account) {
|
|
132
|
+
throw new Error('Cursor is not configured. Add an API key in Settings → Engines → Cursor.');
|
|
133
|
+
}
|
|
134
|
+
const apiKey = resolveCursorApiKey(account);
|
|
135
|
+
|
|
136
|
+
this.activeController = abortController || new AbortController();
|
|
137
|
+
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
138
|
+
|
|
139
|
+
// ── Active Profile scoping + artifact materialization ──
|
|
140
|
+
const profileId = options.mcpContext?.profileId;
|
|
141
|
+
const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
|
|
142
|
+
await syncSkills('cursor', profileId);
|
|
143
|
+
await syncEngineArtifacts('cursor', profileId);
|
|
144
|
+
|
|
145
|
+
// ── Output queue merging the pull stream with the ask tool's push emissions ──
|
|
146
|
+
const queue = new EventQueue<EngineOutput>();
|
|
147
|
+
const converterHolder: { current: ReturnType<typeof createCursorMessageConverter> | null } = { current: null };
|
|
148
|
+
|
|
149
|
+
// ── Tools: AskUserQuestion (in-process custom tool) + MCP (native config) ──
|
|
150
|
+
const askTool: SDKCustomTool = createAskUserQuestionTool({
|
|
151
|
+
register: (id, entry) => this.pendingAsks.set(id, entry),
|
|
152
|
+
unregister: (id) => this.pendingAsks.delete(id),
|
|
153
|
+
// Emit the tool_use with the COMPLETE questions from execute's args.
|
|
154
|
+
emit: (id, questions) => {
|
|
155
|
+
const c = converterHolder.current;
|
|
156
|
+
if (c) for (const out of c.emitAskUserQuestion(id, questions)) queue.push(out);
|
|
157
|
+
},
|
|
158
|
+
});
|
|
159
|
+
const customTools: Record<string, SDKCustomTool> = { AskUserQuestion: askTool };
|
|
160
|
+
const mcpServers = getCursorMcpConfig(mcpProfileFilter);
|
|
161
|
+
const agents = await this.buildAgents();
|
|
162
|
+
|
|
163
|
+
const store = getCursorStore(projectPath);
|
|
164
|
+
const engineMeta: MessageEngine = {
|
|
165
|
+
type: 'cursor',
|
|
166
|
+
provider: 'cursor',
|
|
167
|
+
model: { id: modelId, name: modelId },
|
|
168
|
+
account: { id: account.id, name: account.name },
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
// ── Resume / fork (branch-aware) ──
|
|
172
|
+
// `resume` is the parent agent id. We ALWAYS fork (copy the parent's
|
|
173
|
+
// checkpoints under a fresh agent id) so sibling branches stay isolated.
|
|
174
|
+
let forkedAgentId: string | undefined;
|
|
175
|
+
if (resume) {
|
|
176
|
+
try {
|
|
177
|
+
forkedAgentId = await forkCursorAgent(store, resume);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
debug.warn('engine', `Cursor fork failed (${error instanceof Error ? error.message : String(error)}), starting fresh`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const localOptions = { cwd: resolvedProjectPath, store, customTools };
|
|
184
|
+
let agent: SDKAgent;
|
|
185
|
+
try {
|
|
186
|
+
agent = forkedAgentId
|
|
187
|
+
? await Agent.resume(forkedAgentId, {
|
|
188
|
+
apiKey,
|
|
189
|
+
model: { id: modelId },
|
|
190
|
+
local: localOptions,
|
|
191
|
+
...(Object.keys(mcpServers).length ? { mcpServers } : {}),
|
|
192
|
+
...(agents ? { agents } : {}),
|
|
193
|
+
})
|
|
194
|
+
: await Agent.create({
|
|
195
|
+
apiKey,
|
|
196
|
+
model: { id: modelId },
|
|
197
|
+
local: localOptions,
|
|
198
|
+
...(Object.keys(mcpServers).length ? { mcpServers } : {}),
|
|
199
|
+
...(agents ? { agents } : {}),
|
|
200
|
+
});
|
|
201
|
+
} catch (error) {
|
|
202
|
+
this.activeController = null;
|
|
203
|
+
handleStreamError(error);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
this.activeAgent = agent;
|
|
207
|
+
const sessionId = agent.agentId;
|
|
208
|
+
|
|
209
|
+
const converter = createCursorMessageConverter({ engine: engineMeta, sessionId });
|
|
210
|
+
converterHolder.current = converter;
|
|
211
|
+
|
|
212
|
+
// Build the user turn (text + image attachments).
|
|
213
|
+
const promptText = prompt.content.filter(b => b.type === 'text').map(b => (b.type === 'text' ? b.text : '')).join('\n');
|
|
214
|
+
const artifacts = buildArtifactsPromptContext(profileId);
|
|
215
|
+
const text = artifacts ? `${artifacts}\n\n${promptText}` : promptText;
|
|
216
|
+
const images: SDKImage[] = [];
|
|
217
|
+
for (const b of prompt.content) {
|
|
218
|
+
if (b.type === 'image') images.push({ data: b.data, mimeType: b.mediaType });
|
|
219
|
+
}
|
|
220
|
+
const userMessage: SDKUserMessage = { text, ...(images.length ? { images } : {}) };
|
|
221
|
+
|
|
222
|
+
// Cursor's `run.stream()` yields each text/thinking chunk as its own
|
|
223
|
+
// SDKMessage; the converter streams every chunk live as a transient
|
|
224
|
+
// stream_event AND accumulates it, flushing ONE consolidated reasoning /
|
|
225
|
+
// assistant message per block. The pull stream + the ask tool's push
|
|
226
|
+
// emissions are merged through the queue.
|
|
227
|
+
let onAbort: (() => void) | null = null;
|
|
228
|
+
try {
|
|
229
|
+
const run = await agent.send(userMessage, {
|
|
230
|
+
model: { id: modelId },
|
|
231
|
+
// Sub-agent (Task) steps aren't in `run.stream()` — they ride
|
|
232
|
+
// `tool-call-delta.taskUpdate` here. Stream each completed sub-agent
|
|
233
|
+
// tool call live as a child of the Agent block (parent.toolUseId).
|
|
234
|
+
onDelta: ({ update }) => {
|
|
235
|
+
const u = update as { type?: string; callId?: string; taskUpdate?: unknown };
|
|
236
|
+
if (u.type === 'tool-call-delta' && u.taskUpdate && u.callId) {
|
|
237
|
+
const c = converterHolder.current;
|
|
238
|
+
if (c) for (const out of c.emitSubagentActivity(u.callId, u.taskUpdate)) queue.push(out);
|
|
239
|
+
}
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
this.activeRun = run;
|
|
243
|
+
|
|
244
|
+
// Abort wiring: cancelling the stream cancels the Cursor run.
|
|
245
|
+
onAbort = () => { run.cancel().catch(() => { /* already terminal */ }); };
|
|
246
|
+
this.activeController.signal.addEventListener('abort', onAbort, { once: true });
|
|
247
|
+
|
|
248
|
+
// Drive the pull stream + result in the background, funnelling into the queue.
|
|
249
|
+
const settle = (async () => {
|
|
250
|
+
try {
|
|
251
|
+
if (run.supports('stream')) {
|
|
252
|
+
for await (const message of run.stream()) {
|
|
253
|
+
for (const out of converter.convert(message)) queue.push(out);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const result = await run.wait();
|
|
257
|
+
for (const out of converter.finalize(result)) queue.push(out);
|
|
258
|
+
queue.close();
|
|
259
|
+
} catch (error) {
|
|
260
|
+
queue.fail(error);
|
|
261
|
+
}
|
|
262
|
+
})();
|
|
263
|
+
|
|
264
|
+
for await (const out of queue.drain()) yield out;
|
|
265
|
+
await settle;
|
|
266
|
+
} catch (error) {
|
|
267
|
+
handleStreamError(error);
|
|
268
|
+
} finally {
|
|
269
|
+
if (onAbort) this.activeController?.signal.removeEventListener('abort', onAbort);
|
|
270
|
+
try { agent.close(); } catch { /* fire-and-forget */ }
|
|
271
|
+
this.activeRun = null;
|
|
272
|
+
this.activeAgent = null;
|
|
273
|
+
this.activeController = null;
|
|
274
|
+
this.pendingAsks.clear();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async cancel(): Promise<void> {
|
|
279
|
+
// Release any parked AskUserQuestion callbacks so a blocked run can settle.
|
|
280
|
+
for (const [, pending] of this.pendingAsks) {
|
|
281
|
+
pending.resolve('User did not answer the question.');
|
|
282
|
+
}
|
|
283
|
+
this.pendingAsks.clear();
|
|
284
|
+
|
|
285
|
+
// Abort the local controller first (cuts the for-await loop), then RPC.
|
|
286
|
+
if (this.activeController && !this.activeController.signal.aborted) {
|
|
287
|
+
this.activeController.abort();
|
|
288
|
+
}
|
|
289
|
+
this.activeController = null;
|
|
290
|
+
|
|
291
|
+
if (this.activeRun) {
|
|
292
|
+
try { await this.activeRun.cancel(); } catch { /* may already be terminal */ }
|
|
293
|
+
}
|
|
294
|
+
this.activeRun = null;
|
|
295
|
+
this.activeAgent = null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async interrupt(): Promise<void> {
|
|
299
|
+
if (this.activeRun) {
|
|
300
|
+
try { await this.activeRun.cancel(); } catch { /* ignore */ }
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
|
|
305
|
+
const pending = this.pendingAsks.get(toolUseId);
|
|
306
|
+
if (!pending) {
|
|
307
|
+
debug.warn('engine', `Cursor resolveUserAnswer: no pending question for ${toolUseId}`);
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
pending.resolve(formatAnswers(pending.questions, answers));
|
|
311
|
+
this.pendingAsks.delete(toolUseId);
|
|
312
|
+
return true;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* One-shot structured JSON generation. Cursor local agents always expose the
|
|
317
|
+
* built-in coding tools, so we instruct the model to answer with JSON only and
|
|
318
|
+
* parse the final result text.
|
|
319
|
+
*/
|
|
320
|
+
async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
|
|
321
|
+
const { prompt, modelId, schema, projectPath, accountId } = options;
|
|
322
|
+
|
|
323
|
+
const account = (accountId != null ? engineQueries.getAccount(accountId) : null) ?? getActiveCursorAccount();
|
|
324
|
+
if (!account) throw new Error('Cursor is not configured.');
|
|
325
|
+
const apiKey = resolveCursorApiKey(account);
|
|
326
|
+
|
|
327
|
+
const agent = await Agent.create({
|
|
328
|
+
apiKey,
|
|
329
|
+
model: { id: modelId },
|
|
330
|
+
local: { cwd: resolveOsPath(projectPath), store: getCursorStore(projectPath) },
|
|
331
|
+
});
|
|
332
|
+
try {
|
|
333
|
+
const run = await agent.send(buildJsonPrompt(prompt, schema));
|
|
334
|
+
const result = await run.wait();
|
|
335
|
+
if (!result.result?.trim()) throw new Error('Cursor returned no structured output');
|
|
336
|
+
return extractJson<T>(result.result);
|
|
337
|
+
} finally {
|
|
338
|
+
try { agent.close(); } catch { /* ignore */ }
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
@@ -67,6 +67,15 @@ export function generateOpenCodeProviderConfig(): OpenCodeProviderConfigResult {
|
|
|
67
67
|
|
|
68
68
|
for (const provider of providers) {
|
|
69
69
|
const activeAccount = engineQueries.getActiveAccount(provider.id);
|
|
70
|
+
|
|
71
|
+
// Custom providers (api_url set) are OpenAI-compatible endpoints that
|
|
72
|
+
// don't need env-var management — the config injection in server.ts
|
|
73
|
+
// handles npm + baseURL + model discovery from /v1/models.
|
|
74
|
+
if (provider.api_url) {
|
|
75
|
+
enabledProviders.push(provider.slug);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
|
|
70
79
|
if (!activeAccount) continue;
|
|
71
80
|
|
|
72
81
|
enabledProviders.push(provider.slug);
|
|
@@ -22,8 +22,17 @@ export async function fetchOpenCodeModels(client: OpencodeClient): Promise<Engin
|
|
|
22
22
|
|
|
23
23
|
for (const provider of providers) {
|
|
24
24
|
const providerModels: Record<string, Model> = provider.models ?? {};
|
|
25
|
+
const modelOrder = (provider.options._modelOrder as string[]) ?? [];
|
|
25
26
|
|
|
26
|
-
|
|
27
|
+
const entries = modelOrder.length > 0
|
|
28
|
+
? [...Object.entries(providerModels)].sort((a, b) => {
|
|
29
|
+
const ai = modelOrder.indexOf(a[0]);
|
|
30
|
+
const bi = modelOrder.indexOf(b[0]);
|
|
31
|
+
return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi);
|
|
32
|
+
})
|
|
33
|
+
: Object.entries(providerModels);
|
|
34
|
+
|
|
35
|
+
for (const [, model] of entries) {
|
|
27
36
|
models.push({
|
|
28
37
|
engine: {
|
|
29
38
|
type: 'opencode',
|
|
@@ -25,8 +25,8 @@ import { join } from 'path';
|
|
|
25
25
|
import type { OpencodeClient } from '@opencode-ai/sdk';
|
|
26
26
|
import type { Subprocess } from 'bun';
|
|
27
27
|
import { getOpenCodeMcpConfig } from '../../../mcp';
|
|
28
|
-
import { settingsQueries } from '../../../database/queries';
|
|
29
|
-
import { generateOpenCodeProviderConfig } from './config';
|
|
28
|
+
import { engineQueries, settingsQueries } from '../../../database/queries';
|
|
29
|
+
import { generateOpenCodeProviderConfig, parseCredentialMap } from './config';
|
|
30
30
|
import type { OpenCodeInlineAgent } from '$backend/subagents';
|
|
31
31
|
import { resolveBinaryWithRefresh } from '$backend/utils/cli';
|
|
32
32
|
import { getEngineUserConfigDir } from '$backend/utils/paths';
|
|
@@ -195,6 +195,114 @@ async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerI
|
|
|
195
195
|
if (Object.keys(mcpConfig).length > 0) mergedConfig.mcp = mcpConfig;
|
|
196
196
|
if (providerConfig.enabledProviders.length > 0) mergedConfig.enabled_providers = providerConfig.enabledProviders;
|
|
197
197
|
if (spec.inlineAgents && Object.keys(spec.inlineAgents).length > 0) mergedConfig.agent = spec.inlineAgents;
|
|
198
|
+
|
|
199
|
+
// Inject provider definitions for custom OpenAI-compatible providers
|
|
200
|
+
// (those with api_url set). Unlike models.dev catalog providers, custom
|
|
201
|
+
// providers need their npm + baseURL passed explicitly so the opencode
|
|
202
|
+
// server can discover models from their /v1/models endpoint.
|
|
203
|
+
const providerSection: Record<string, unknown> = {};
|
|
204
|
+
const opencodeProviders = engineQueries.getEnabledProviders('opencode');
|
|
205
|
+
for (const provider of opencodeProviders) {
|
|
206
|
+
if (!provider.api_url) continue;
|
|
207
|
+
|
|
208
|
+
// Resolve the active account's credential so we can (a) authenticate the
|
|
209
|
+
// endpoint and (b) substitute `${VAR}` placeholders in the base URL.
|
|
210
|
+
// Multi-secret providers (e.g. Cloudflare Workers AI, whose URL embeds
|
|
211
|
+
// ${CLOUDFLARE_ACCOUNT_ID} and whose bearer is CLOUDFLARE_API_KEY) store
|
|
212
|
+
// every secret as a JSON bundle; single-key providers store a raw string.
|
|
213
|
+
const activeAccount = engineQueries.getActiveAccount(provider.id);
|
|
214
|
+
let baseURL = provider.api_url;
|
|
215
|
+
let apiKey: string | undefined;
|
|
216
|
+
if (activeAccount?.credential) {
|
|
217
|
+
const credMap = parseCredentialMap(activeAccount.credential);
|
|
218
|
+
if (credMap) {
|
|
219
|
+
baseURL = baseURL.replace(/\$\{(\w+)\}/g, (_m, name) => credMap[name] ?? '');
|
|
220
|
+
const keys = Object.keys(credMap);
|
|
221
|
+
const tokenKey = keys.find(k => /API[_-]?(?:KEY|TOKEN)$/i.test(k)) ?? keys.find(k => /(?:KEY|TOKEN)$/i.test(k));
|
|
222
|
+
if (tokenKey) apiKey = credMap[tokenKey];
|
|
223
|
+
} else {
|
|
224
|
+
apiKey = activeAccount.credential;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const models: Record<string, { name: string; limit: { context: number; output: number } }> = {};
|
|
229
|
+
// Per-model limits live in `modelLimits`; legacy provider-level
|
|
230
|
+
// contextLimit/outputLimit remain a fallback for older rows.
|
|
231
|
+
let defaultContext = 128000;
|
|
232
|
+
let defaultOutput = 16384;
|
|
233
|
+
let modelLimits: Record<string, { context?: number; output?: number }> = {};
|
|
234
|
+
let modelNames: Record<string, string> = {};
|
|
235
|
+
let hiddenSet = new Set<string>();
|
|
236
|
+
try {
|
|
237
|
+
const opts = JSON.parse(provider.options || '{}') as {
|
|
238
|
+
models?: string[];
|
|
239
|
+
modelNames?: Record<string, string>;
|
|
240
|
+
hiddenModels?: string[];
|
|
241
|
+
modelLimits?: Record<string, { context?: number; output?: number }>;
|
|
242
|
+
contextLimit?: number;
|
|
243
|
+
outputLimit?: number;
|
|
244
|
+
};
|
|
245
|
+
if (opts.contextLimit) defaultContext = opts.contextLimit;
|
|
246
|
+
if (opts.outputLimit) defaultOutput = opts.outputLimit;
|
|
247
|
+
if (opts.modelLimits) modelLimits = opts.modelLimits;
|
|
248
|
+
if (opts.modelNames) modelNames = opts.modelNames;
|
|
249
|
+
if (opts.hiddenModels) hiddenSet = new Set(opts.hiddenModels);
|
|
250
|
+
} catch {
|
|
251
|
+
// malformed options — proceed to auto-discover
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const addModel = (id: string) => {
|
|
255
|
+
const lim = modelLimits[id];
|
|
256
|
+
models[id] = { name: modelNames[id] || id, limit: { context: lim?.context || defaultContext, output: lim?.output || defaultOutput } };
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
try {
|
|
260
|
+
const opts = JSON.parse(provider.options || '{}') as { models?: string[] };
|
|
261
|
+
if (opts.models && opts.models.length > 0) {
|
|
262
|
+
for (const id of opts.models) {
|
|
263
|
+
if (!hiddenSet.has(id)) addModel(id);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
} catch {
|
|
267
|
+
// malformed options — proceed to auto-discover
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Auto-discover models from /v1/models if none stored in options
|
|
271
|
+
if (Object.keys(models).length === 0) {
|
|
272
|
+
try {
|
|
273
|
+
const baseUrl = baseURL.replace(/\/+$/, '');
|
|
274
|
+
const res = await fetch(`${baseUrl}/models`, {
|
|
275
|
+
headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
|
|
276
|
+
signal: AbortSignal.timeout(3000),
|
|
277
|
+
});
|
|
278
|
+
if (res.ok) {
|
|
279
|
+
const body = await res.json() as { data?: { id: string }[] };
|
|
280
|
+
for (const m of body.data ?? []) {
|
|
281
|
+
addModel(m.id);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
// Provider may not be running — models will be empty.
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
let modelOrder: string[] | undefined;
|
|
290
|
+
try {
|
|
291
|
+
const o = JSON.parse(provider.options || '{}') as { models?: string[] };
|
|
292
|
+
if (o.models && o.models.length > 0) modelOrder = o.models.filter(id => !hiddenSet.has(id));
|
|
293
|
+
} catch { /* ignore */ }
|
|
294
|
+
const providerOptions: Record<string, unknown> = { baseURL };
|
|
295
|
+
if (apiKey) providerOptions.apiKey = apiKey;
|
|
296
|
+
if (modelOrder) providerOptions._modelOrder = modelOrder;
|
|
297
|
+
providerSection[provider.slug] = {
|
|
298
|
+
npm: provider.npm || '@ai-sdk/openai-compatible',
|
|
299
|
+
name: provider.name,
|
|
300
|
+
options: providerOptions,
|
|
301
|
+
models: models,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
if (Object.keys(providerSection).length > 0) mergedConfig.provider = providerSection;
|
|
305
|
+
|
|
198
306
|
const configContent = Object.keys(mergedConfig).length > 0 ? JSON.stringify(mergedConfig) : '{}';
|
|
199
307
|
|
|
200
308
|
const proc = Bun.spawn(args, {
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent dispatch tool for Pi.
|
|
3
|
+
*
|
|
4
|
+
* Pi has no native Agent/Task primitive, so the synthetic "Available Subagents"
|
|
5
|
+
* preamble (materialized into AGENTS.md) is informational only — the model can
|
|
6
|
+
* describe subagents but can't invoke them. This custom `Agent` tool closes that
|
|
7
|
+
* gap: calling it spawns a fresh sub-session with the subagent's system prompt,
|
|
8
|
+
* runs the delegated prompt to completion, and returns the final text as the
|
|
9
|
+
* tool result. Sub-activity does not stream to the main UI (it runs inside the
|
|
10
|
+
* tool), but the delegation actually happens.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { Type } from 'typebox';
|
|
14
|
+
import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
|
|
15
|
+
|
|
16
|
+
export interface SubagentInfo {
|
|
17
|
+
slug: string;
|
|
18
|
+
name: string;
|
|
19
|
+
description: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface AgentDispatchBindings {
|
|
23
|
+
/** Enabled subagents advertised to the model. */
|
|
24
|
+
subagents: SubagentInfo[];
|
|
25
|
+
/**
|
|
26
|
+
* Run one subagent against a prompt; resolve with its final text output.
|
|
27
|
+
* `toolCallId` is the parent Agent tool_use id — the runner tags the
|
|
28
|
+
* subagent's messages with it so they render as sub-activities.
|
|
29
|
+
*/
|
|
30
|
+
run: (subagent: SubagentInfo, prompt: string, toolCallId: string, signal?: AbortSignal) => Promise<string>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const AGENT_PARAMS = Type.Object({
|
|
34
|
+
subagentType: Type.String({ description: 'The slug of the subagent to delegate to.' }),
|
|
35
|
+
description: Type.String({ description: 'A short (3-5 word) description of the delegated task.' }),
|
|
36
|
+
prompt: Type.String({ description: 'The full, self-contained task/instructions for the subagent.' }),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
export function createAgentDispatchTool(bindings: AgentDispatchBindings): ToolDefinition {
|
|
40
|
+
const catalog = bindings.subagents.map(s => `- ${s.slug}: ${s.name} — ${s.description}`).join('\n');
|
|
41
|
+
return {
|
|
42
|
+
name: 'Agent',
|
|
43
|
+
label: 'Agent',
|
|
44
|
+
description:
|
|
45
|
+
'Delegate a self-contained subtask to a specialized subagent. Pass the subagent slug as `subagentType` and the task as `prompt`. Available subagents:\n' + catalog,
|
|
46
|
+
parameters: AGENT_PARAMS,
|
|
47
|
+
execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal) => {
|
|
48
|
+
const p = params as { subagentType?: string; prompt?: string };
|
|
49
|
+
const match = bindings.subagents.find(s => s.slug === p.subagentType || s.name === p.subagentType);
|
|
50
|
+
if (!match) {
|
|
51
|
+
const names = bindings.subagents.map(s => s.slug).join(', ') || '(none configured)';
|
|
52
|
+
return { content: [{ type: 'text' as const, text: `No subagent named "${p.subagentType}". Available: ${names}` }], details: {} };
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
const text = await bindings.run(match, p.prompt ?? '', _toolCallId, signal);
|
|
56
|
+
return { content: [{ type: 'text' as const, text: text.trim() || '(subagent produced no output)' }], details: {} };
|
|
57
|
+
} catch (error) {
|
|
58
|
+
return { content: [{ type: 'text' as const, text: `Subagent "${match.slug}" failed: ${error instanceof Error ? error.message : String(error)}` }], details: {} };
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
} as ToolDefinition;
|
|
62
|
+
}
|