@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.
Files changed (94) hide show
  1. package/backend/artifacts/matrix.ts +8 -0
  2. package/backend/artifacts/types.ts +2 -2
  3. package/backend/auth/permissions.ts +14 -0
  4. package/backend/chat/stream-manager.ts +5 -5
  5. package/backend/commands/detect.ts +1 -1
  6. package/backend/commands/sync.ts +1 -1
  7. package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
  8. package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
  9. package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
  10. package/backend/database/migrations/index.ts +21 -0
  11. package/backend/engine/README.md +36 -13
  12. package/backend/engine/adapters/cline/agent-tool.ts +64 -0
  13. package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
  14. package/backend/engine/adapters/cline/credential.ts +166 -0
  15. package/backend/engine/adapters/cline/error-handler.ts +49 -0
  16. package/backend/engine/adapters/cline/index.ts +1 -0
  17. package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
  18. package/backend/engine/adapters/cline/message-converter.ts +396 -0
  19. package/backend/engine/adapters/cline/models.ts +73 -0
  20. package/backend/engine/adapters/cline/presets.ts +128 -0
  21. package/backend/engine/adapters/cline/stream.ts +413 -0
  22. package/backend/engine/adapters/codex/credential.ts +1 -1
  23. package/backend/engine/adapters/codex/message-converter.ts +4 -4
  24. package/backend/engine/adapters/codex/session-fork.ts +1 -1
  25. package/backend/engine/adapters/codex/stream.ts +3 -3
  26. package/backend/engine/adapters/copilot/stream.ts +1 -1
  27. package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
  28. package/backend/engine/adapters/cursor/credential.ts +68 -0
  29. package/backend/engine/adapters/cursor/environment.ts +32 -0
  30. package/backend/engine/adapters/cursor/error-handler.ts +60 -0
  31. package/backend/engine/adapters/cursor/index.ts +1 -0
  32. package/backend/engine/adapters/cursor/message-converter.ts +615 -0
  33. package/backend/engine/adapters/cursor/models.ts +68 -0
  34. package/backend/engine/adapters/cursor/session-fork.ts +68 -0
  35. package/backend/engine/adapters/cursor/stream.ts +341 -0
  36. package/backend/engine/adapters/pi/agent-tool.ts +62 -0
  37. package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
  38. package/backend/engine/adapters/pi/credential.ts +137 -0
  39. package/backend/engine/adapters/pi/environment.ts +33 -0
  40. package/backend/engine/adapters/pi/error-handler.ts +46 -0
  41. package/backend/engine/adapters/pi/index.ts +1 -0
  42. package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
  43. package/backend/engine/adapters/pi/message-converter.ts +446 -0
  44. package/backend/engine/adapters/pi/models.ts +53 -0
  45. package/backend/engine/adapters/pi/presets.ts +133 -0
  46. package/backend/engine/adapters/pi/session-fork.ts +46 -0
  47. package/backend/engine/adapters/pi/stream.ts +427 -0
  48. package/backend/engine/adapters/qwen/message-converter.ts +5 -5
  49. package/backend/engine/adapters/qwen/stream.ts +2 -2
  50. package/backend/engine/docs/adapter-contract.md +7 -2
  51. package/backend/engine/docs/adding-an-engine.md +70 -12
  52. package/backend/engine/docs/artifacts.md +124 -0
  53. package/backend/engine/docs/database.md +4 -4
  54. package/backend/engine/docs/frontend-and-chat.md +22 -4
  55. package/backend/engine/docs/lessons-learned.md +219 -32
  56. package/backend/engine/docs/quick-reference.md +18 -7
  57. package/backend/engine/docs/websocket-routes.md +2 -2
  58. package/backend/engine/index.ts +9 -0
  59. package/backend/mcp/README.md +3 -3
  60. package/backend/mcp/external/config.ts +11 -0
  61. package/backend/mcp/index.ts +8 -0
  62. package/backend/mcp/internal/config.ts +33 -1
  63. package/backend/permissions/service.ts +5 -2
  64. package/backend/skills/sync.ts +1 -1
  65. package/backend/subagents/detect.ts +1 -1
  66. package/backend/subagents/sync.ts +1 -1
  67. package/backend/ws/chat/stream.ts +1 -1
  68. package/backend/ws/engine/cline/accounts.ts +317 -0
  69. package/backend/ws/engine/cline/index.ts +15 -0
  70. package/backend/ws/engine/cline/presets.ts +36 -0
  71. package/backend/ws/engine/cline/status.ts +49 -0
  72. package/backend/ws/engine/codex/accounts.ts +1 -1
  73. package/backend/ws/engine/cursor/accounts.ts +162 -0
  74. package/backend/ws/engine/cursor/index.ts +13 -0
  75. package/backend/ws/engine/cursor/status.ts +55 -0
  76. package/backend/ws/engine/index.ts +6 -0
  77. package/backend/ws/engine/pi/accounts.ts +319 -0
  78. package/backend/ws/engine/pi/index.ts +15 -0
  79. package/backend/ws/engine/pi/presets.ts +34 -0
  80. package/backend/ws/engine/pi/status.ts +50 -0
  81. package/backend/ws/sessions/crud.ts +2 -2
  82. package/backend/ws/settings/crud.ts +2 -2
  83. package/dist/assets/{index-EunAFLxP.js → index-BPvctwJ2.js} +1 -1
  84. package/dist/assets/{index-ChF_jIXj.js → index-vLKZpWQH.js} +1 -1
  85. package/dist/assets/{main-CTs4NXwP.js → main-BtBZvCwv.js} +359 -357
  86. package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
  87. package/dist/index.html +2 -2
  88. package/package.json +7 -1
  89. package/shared/constants/engine-tools.ts +16 -2
  90. package/shared/constants/engines.ts +27 -0
  91. package/shared/types/unified/common.ts +1 -1
  92. package/shared/types/unified/engine.ts +82 -1
  93. package/shared/types/unified/index.ts +6 -0
  94. package/shared/types/unified/message.ts +1 -1
@@ -0,0 +1,98 @@
1
+ /**
2
+ * AskUserQuestion custom tool for Cursor.
3
+ *
4
+ * Cursor exposes in-process callback tools via `local.customTools` (surfaced to
5
+ * the model as the `custom-user-tools` MCP server). We register a canonical
6
+ * `AskUserQuestion` tool whose `execute` BLOCKS until the user answers through the
7
+ * chat UI — the same contract Claude's `canUseTool` / Cline's custom ask tool
8
+ * provide.
9
+ *
10
+ * The Cursor custom-tool context carries no abort signal, so a parked question is
11
+ * released either by `resolveUserAnswer(toolCallId, answers)` (the user answered)
12
+ * or by the engine's `cancel()` sweep over `pendingAsks`.
13
+ */
14
+
15
+ import type { SDKCustomTool, SDKJsonValue } from '@cursor/sdk';
16
+ import type { AskUserQuestion } from '$shared/types/unified';
17
+
18
+ export interface PendingAsk {
19
+ questions: AskUserQuestion[];
20
+ resolve: (text: string) => void;
21
+ }
22
+
23
+ export interface AskToolBindings {
24
+ register: (toolCallId: string, entry: PendingAsk) => void;
25
+ unregister: (toolCallId: string) => void;
26
+ /**
27
+ * Surface the AskUserQuestion tool_use into the stream with the COMPLETE
28
+ * questions. Sourced from `execute`'s args (always fully populated) rather
29
+ * than the stream's `tool_call` args, which can arrive empty/partial for large
30
+ * question sets — the bug behind `questions: []` in the UI.
31
+ */
32
+ emit: (toolCallId: string, questions: AskUserQuestion[]) => void;
33
+ }
34
+
35
+ /** Format the user's answers in the shared OpenCode/Qwen/Pi/Cline wording. */
36
+ export function formatAnswers(questions: AskUserQuestion[], answers: Record<string, string>): string {
37
+ const pairs: string[] = [];
38
+ for (const [key, value] of Object.entries(answers)) {
39
+ const idx = Number.parseInt(key, 10);
40
+ const q = Number.isFinite(idx) ? questions[idx] : undefined;
41
+ const label = q?.question ?? q?.header ?? key;
42
+ pairs.push(`"${label}"="${value}"`);
43
+ }
44
+ if (pairs.length === 0) return 'User did not provide any answers.';
45
+ return `User has answered your questions: ${pairs.join(', ')}. You can now continue with the user's answers in mind.`;
46
+ }
47
+
48
+ const ASK_INPUT_SCHEMA: Record<string, SDKJsonValue> = {
49
+ type: 'object',
50
+ properties: {
51
+ questions: {
52
+ type: 'array',
53
+ description: 'One or more multiple-choice questions to ask the user.',
54
+ items: {
55
+ type: 'object',
56
+ properties: {
57
+ question: { type: 'string', description: 'The full question text.' },
58
+ header: { type: 'string', description: 'A short (max 12 char) label for the question.' },
59
+ multiSelect: { type: 'boolean', description: 'Whether multiple options may be selected.' },
60
+ options: {
61
+ type: 'array',
62
+ items: {
63
+ type: 'object',
64
+ properties: {
65
+ label: { type: 'string' },
66
+ description: { type: 'string' },
67
+ },
68
+ required: ['label', 'description'],
69
+ },
70
+ },
71
+ },
72
+ required: ['question', 'header', 'options'],
73
+ },
74
+ },
75
+ },
76
+ required: ['questions'],
77
+ };
78
+
79
+ export function createAskUserQuestionTool(bindings: AskToolBindings): SDKCustomTool {
80
+ return {
81
+ description:
82
+ 'Ask the user one or more multiple-choice questions when you need a decision only they can make. Blocks until the user answers in the UI.',
83
+ inputSchema: ASK_INPUT_SCHEMA,
84
+ execute(args, context) {
85
+ const questions = (Array.isArray(args?.questions) ? args.questions : []) as unknown as AskUserQuestion[];
86
+ const toolCallId = context.toolCallId ?? '';
87
+ return new Promise<string>((resolve) => {
88
+ if (!toolCallId) {
89
+ resolve('User did not answer the question.');
90
+ return;
91
+ }
92
+ // Emit the tool_use with the complete questions from THIS call's args.
93
+ bindings.emit(toolCallId, questions);
94
+ bindings.register(toolCallId, { questions, resolve });
95
+ });
96
+ },
97
+ };
98
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Cursor credential storage.
3
+ *
4
+ * Cursor authenticates with a single `CURSOR_API_KEY` (a user API key from the
5
+ * Cursor dashboard, or a team service-account key). Unlike the multi-provider
6
+ * engines (Cline/Qwen), a Cursor account is single-provider: one `engine_providers`
7
+ * row (`slug = 'cursor'`) owns every stored account, and the account's
8
+ * `credential` carries just the key.
9
+ *
10
+ * The key is passed to `Agent.create({ apiKey })` per stream — there is no shared
11
+ * dotfile to swap, so multi-account within Clopen is a pure DB `is_active` switch
12
+ * (see `backend/engine/README.md` §10.13). Stored as a JSON wrapper
13
+ * (`{ "apiKey": "…" }`) for forward-compatibility, but a raw key string is also
14
+ * accepted.
15
+ */
16
+
17
+ import { engineQueries, type EngineAccount } from '$backend/database/queries/engine-queries';
18
+
19
+ export interface CursorCredential {
20
+ apiKey: string;
21
+ }
22
+
23
+ /** The single `engine_providers` row that owns every Cursor account. */
24
+ export function getCursorProvider() {
25
+ return engineQueries.getProviderBySlug('cursor', 'cursor');
26
+ }
27
+
28
+ /** Every stored Cursor account. */
29
+ export function getCursorAccounts(): EngineAccount[] {
30
+ const provider = getCursorProvider();
31
+ return provider ? engineQueries.getAccountsByProvider(provider.id) : [];
32
+ }
33
+
34
+ /** The active Cursor account (or the most recently added one as a fallback). */
35
+ export function getActiveCursorAccount(): EngineAccount | null {
36
+ const active = engineQueries.getActiveAccountForEngine('cursor');
37
+ if (active) return active;
38
+ const accounts = getCursorAccounts();
39
+ return accounts.length ? accounts[accounts.length - 1] : null;
40
+ }
41
+
42
+ /** Parse a stored `engine_accounts.credential` blob into a Cursor credential. */
43
+ export function parseCursorCredential(stored: string | null | undefined): CursorCredential | null {
44
+ if (!stored) return null;
45
+ const trimmed = stored.trim();
46
+ if (!trimmed) return null;
47
+ if (trimmed.startsWith('{')) {
48
+ try {
49
+ const parsed = JSON.parse(trimmed) as Partial<CursorCredential>;
50
+ return parsed?.apiKey ? { apiKey: parsed.apiKey } : null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ // Raw API key.
56
+ return { apiKey: trimmed };
57
+ }
58
+
59
+ export function serializeCursorCredential(cred: CursorCredential): string {
60
+ return JSON.stringify(cred);
61
+ }
62
+
63
+ /** Resolve the API key for an account, throwing if it is unusable. */
64
+ export function resolveCursorApiKey(account: EngineAccount): string {
65
+ const parsed = parseCursorCredential(account.credential);
66
+ if (!parsed) throw new Error('Cursor account has no usable API key.');
67
+ return parsed.apiKey;
68
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Cursor session-store isolation.
3
+ *
4
+ * Cursor local agents persist to disk. The SDK's default backend is on-disk
5
+ * SQLite under `getDefaultSdkStateRoot()` (which needs the native `sqlite3`
6
+ * addon), and it would write under the user's own state root. We sidestep both
7
+ * concerns by pointing every agent at a portable `JsonlLocalAgentStore` rooted in
8
+ * Clopen's ISOLATED engine dir (`{clopenDir}/engine/cursor/user/agents/`), never
9
+ * `~/.cursor` (README §10.19).
10
+ *
11
+ * The store is keyed per project so concurrent projects never collide, and a
12
+ * resume/fork within a project reuses the same store instance directory.
13
+ */
14
+
15
+ import { join } from 'node:path';
16
+ import { JsonlLocalAgentStore } from '@cursor/sdk';
17
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
18
+
19
+ /** Root dir holding every project's isolated Cursor agent store. */
20
+ export function getCursorStoreRoot(): string {
21
+ return join(getEngineUserConfigDir('cursor'), 'agents');
22
+ }
23
+
24
+ /** Per-project isolated store directory. */
25
+ function getCursorStoreDir(projectPath: string): string {
26
+ return join(getCursorStoreRoot(), projectPath.replace(/[^a-zA-Z0-9]/g, '-') || 'default');
27
+ }
28
+
29
+ /** A per-project `JsonlLocalAgentStore` for a stream (create + resume + fork). */
30
+ export function getCursorStore(projectPath: string): JsonlLocalAgentStore {
31
+ return new JsonlLocalAgentStore(getCursorStoreDir(projectPath));
32
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Cursor SDK error handler.
3
+ *
4
+ * Cursor runs in-process (local agent), so there is no CLI stderr to fold in.
5
+ * Swallow abort/cancel errors, normalise the common `CursorSdkError` categories
6
+ * (auth, rate limit, bad model/config), and otherwise re-throw a sanitised
7
+ * message. Mirrors the Cline/Pi pattern.
8
+ */
9
+
10
+ export function handleStreamError(error: unknown): void {
11
+ if (!(error instanceof Error)) {
12
+ throw error;
13
+ }
14
+
15
+ if (
16
+ error.name === 'AbortError'
17
+ || error.message.includes('aborted')
18
+ || error.message.includes('cancelled')
19
+ || error.message.includes('Cancelled')
20
+ ) {
21
+ return;
22
+ }
23
+
24
+ const lower = error.message.toLowerCase();
25
+
26
+ // Free-tier / plan gating: the Cursor agent API is Pro-only. A free key is
27
+ // valid but its agent quota is limited — surface a clear, actionable message
28
+ // instead of the raw SDK error.
29
+ if (lower.includes('plan_required') || lower.includes('upgrade to pro') || lower.includes('not available for free users')) {
30
+ throw new Error('Cursor agent runs require a paid plan. This API key is valid but its account is on the free tier — upgrade to Cursor Pro to use this engine.');
31
+ }
32
+
33
+ // Transient connectivity to Cursor's backend (the SDK's connect-rpc key
34
+ // exchange). Seen most often with rate-limited / exhausted keys; surface a
35
+ // clear, retryable message rather than the raw NetworkError.
36
+ if (lower.includes('socket connection was closed') || lower.includes('api key exchange endpoint') || lower.includes('failed to connect')) {
37
+ throw new Error('Cursor could not reach its backend (connection closed). This is usually transient or a rate-limited key — retry, and verify your account has agent quota.');
38
+ }
39
+
40
+ if (
41
+ error.name === 'AuthenticationError'
42
+ || lower.includes('unauthorized')
43
+ || lower.includes('invalid api key')
44
+ || lower.includes('expired')
45
+ || lower.includes('401')
46
+ ) {
47
+ throw new Error('Cursor is not authenticated. Add or re-enter a valid API key in Settings → Engines → Cursor.');
48
+ }
49
+
50
+ if (error.name === 'RateLimitError' || lower.includes('rate limit') || lower.includes('quota') || lower.includes('429')) {
51
+ throw new Error('Cursor rate limit or usage cap exceeded. Try again later or switch account.');
52
+ }
53
+
54
+ if (error.name === 'ConfigurationError' || lower.includes('model') && (lower.includes('not found') || lower.includes('unsupported') || lower.includes('invalid'))) {
55
+ throw new Error('Cursor could not resolve the selected model. Pick a model your key supports.');
56
+ }
57
+
58
+ const message = error.message.replace(/^Error:\s*/, '') || error.name || 'Unknown error';
59
+ throw new Error(message);
60
+ }
@@ -0,0 +1 @@
1
+ export { CursorEngine } from './stream';