@myrialabs/clopen 0.4.40 → 0.4.41

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 (95) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +6 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +42 -0
  14. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  15. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  16. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  17. package/backend/database/migrations/index.ts +21 -0
  18. package/backend/database/queries/file-share-queries.ts +163 -0
  19. package/backend/database/queries/index.ts +6 -4
  20. package/backend/database/queries/profile-queries.ts +5 -3
  21. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  22. package/backend/database/queries/push-subscription-queries.ts +99 -0
  23. package/backend/database/queries/skill-queries.ts +96 -18
  24. package/backend/engine/adapters/claude/stream.ts +2 -1
  25. package/backend/engine/adapters/cline/stream.ts +3 -3
  26. package/backend/engine/adapters/codex/stream.ts +3 -3
  27. package/backend/engine/adapters/copilot/stream.ts +3 -3
  28. package/backend/engine/adapters/cursor/stream.ts +25 -3
  29. package/backend/engine/adapters/opencode/stream.ts +4 -6
  30. package/backend/engine/adapters/pi/stream.ts +2 -2
  31. package/backend/engine/adapters/qwen/stream.ts +2 -2
  32. package/backend/engine/artifact-sync.ts +26 -20
  33. package/backend/engine/docs/artifacts.md +81 -22
  34. package/backend/engine/docs/quick-reference.md +2 -1
  35. package/backend/engine/resolve-model.test.ts +108 -0
  36. package/backend/engine/resolve-model.ts +53 -10
  37. package/backend/engine/structured-helpers.ts +22 -0
  38. package/backend/files/file-shares.ts +369 -0
  39. package/backend/files/path-browsing.ts +27 -21
  40. package/backend/http/files-shared.test.ts +505 -0
  41. package/backend/http/files-shared.ts +351 -0
  42. package/backend/http/push.ts +150 -0
  43. package/backend/index.ts +8 -0
  44. package/backend/instructions/index.ts +1 -1
  45. package/backend/instructions/sync.ts +30 -6
  46. package/backend/memory/compose.ts +2 -2
  47. package/backend/memory/consolidate.ts +2 -2
  48. package/backend/memory/extract/episodic.ts +2 -2
  49. package/backend/memory/judge.ts +2 -2
  50. package/backend/profiles/service.ts +7 -6
  51. package/backend/push/sender.ts +172 -0
  52. package/backend/push/tags.ts +25 -0
  53. package/backend/push/vapid-keys.ts +77 -0
  54. package/backend/push/webpush-crypto.test.ts +200 -0
  55. package/backend/push/webpush-crypto.ts +231 -0
  56. package/backend/skills/detect.ts +28 -0
  57. package/backend/skills/index.ts +22 -4
  58. package/backend/skills/invoke.test.ts +114 -0
  59. package/backend/skills/invoke.ts +222 -0
  60. package/backend/skills/service.ts +194 -44
  61. package/backend/skills/spec.ts +35 -0
  62. package/backend/skills/sync.ts +85 -55
  63. package/backend/subagents/detect.ts +2 -3
  64. package/backend/subagents/sync.ts +15 -8
  65. package/backend/work/pull-requests.ts +2 -2
  66. package/backend/ws/chat/stream.ts +100 -8
  67. package/backend/ws/files/index.ts +4 -0
  68. package/backend/ws/files/share.ts +95 -0
  69. package/backend/ws/git/branch-name.ts +2 -2
  70. package/backend/ws/git/commit-message.ts +2 -2
  71. package/backend/ws/index.ts +3 -4
  72. package/backend/ws/profiles/crud.ts +2 -3
  73. package/backend/ws/skills/catalog.ts +5 -1
  74. package/backend/ws/skills/crud.ts +128 -22
  75. package/backend/ws/skills/index.ts +4 -1
  76. package/backend/ws/user/crud.ts +12 -3
  77. package/dist/assets/{index-D4igjF6e.js → index-CeNKKSDR.js} +1 -1
  78. package/dist/assets/{index-DONNwiXm.js → index-DW89566K.js} +1 -1
  79. package/dist/assets/{main-BrfXH1bL.js → main-Cy5DXWPT.js} +592 -590
  80. package/dist/assets/main-DJKj_4By.css +1 -0
  81. package/dist/index.html +7 -2
  82. package/dist/sw.js +112 -0
  83. package/package.json +1 -1
  84. package/shared/constants/engine-tools.ts +31 -6
  85. package/shared/constants/notification-messages.ts +142 -0
  86. package/shared/types/unified/stream.ts +7 -0
  87. package/backend/commands/detect.ts +0 -25
  88. package/backend/commands/index.ts +0 -9
  89. package/backend/commands/service.ts +0 -178
  90. package/backend/commands/store.ts +0 -45
  91. package/backend/commands/sync.ts +0 -94
  92. package/backend/database/queries/command-queries.ts +0 -82
  93. package/backend/ws/commands/crud.ts +0 -157
  94. package/backend/ws/commands/index.ts +0 -8
  95. package/dist/assets/main-CT1PygsW.css +0 -1
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Tests for the Web Push subscription store.
3
+ *
4
+ * Two invariants carry the feature. One row per device endpoint, so a phone
5
+ * that re-subscribes on every app open does not accumulate duplicates and
6
+ * receive N copies of every notification. And a purge that covers the whole
7
+ * user, because `pushNotifications` is a single per-user setting synced
8
+ * across devices — switching it off on a laptop has to silence the phone.
9
+ */
10
+
11
+ import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
12
+ import { randomUUID } from 'node:crypto';
13
+
14
+ import { initializeDatabase, closeDatabase } from '../index';
15
+ import { pushSubscriptionQueries } from './push-subscription-queries';
16
+
17
+ const userA = `user-a-${randomUUID()}`;
18
+ const userB = `user-b-${randomUUID()}`;
19
+
20
+ function subscribe(userId: string, suffix: string) {
21
+ return pushSubscriptionQueries.upsert({
22
+ userId,
23
+ endpoint: `https://push.example.com/${suffix}`,
24
+ p256dh: 'p256dh-'.padEnd(20, 'x'),
25
+ auth: 'auth-'.padEnd(16, 'x'),
26
+ userAgent: 'test-agent'
27
+ });
28
+ }
29
+
30
+ beforeAll(async () => {
31
+ await initializeDatabase();
32
+ });
33
+
34
+ beforeEach(() => {
35
+ pushSubscriptionQueries.deleteAllByUser(userA);
36
+ pushSubscriptionQueries.deleteAllByUser(userB);
37
+ });
38
+
39
+ afterAll(() => {
40
+ pushSubscriptionQueries.deleteAllByUser(userA);
41
+ pushSubscriptionQueries.deleteAllByUser(userB);
42
+ closeDatabase();
43
+ });
44
+
45
+ describe('pushSubscriptionQueries', () => {
46
+ it('keeps one row per endpoint when the same device re-subscribes', () => {
47
+ const first = subscribe(userA, 'device-1');
48
+ const second = pushSubscriptionQueries.upsert({
49
+ userId: userA,
50
+ endpoint: 'https://push.example.com/device-1',
51
+ p256dh: 'rotated-p256dh'.padEnd(20, 'x'),
52
+ auth: 'rotated-auth'.padEnd(16, 'x')
53
+ });
54
+
55
+ expect(second.id).toBe(first.id);
56
+ expect(second.p256dh).toBe('rotated-p256dh'.padEnd(20, 'x'));
57
+ expect(pushSubscriptionQueries.listByUser(userA)).toHaveLength(1);
58
+ });
59
+
60
+ it('deletes every device of one user and leaves other users untouched', () => {
61
+ subscribe(userA, 'phone');
62
+ subscribe(userA, 'tablet');
63
+ subscribe(userB, 'other-phone');
64
+
65
+ expect(pushSubscriptionQueries.deleteAllByUser(userA)).toBe(2);
66
+ expect(pushSubscriptionQueries.listByUser(userA)).toHaveLength(0);
67
+ expect(pushSubscriptionQueries.listByUser(userB)).toHaveLength(1);
68
+ });
69
+
70
+ it('scopes a single-endpoint delete to its owner', () => {
71
+ subscribe(userA, 'shared-looking-endpoint');
72
+
73
+ expect(
74
+ pushSubscriptionQueries.deleteByEndpoint(
75
+ userB,
76
+ 'https://push.example.com/shared-looking-endpoint'
77
+ )
78
+ ).toBe(false);
79
+ expect(pushSubscriptionQueries.listByUser(userA)).toHaveLength(1);
80
+ });
81
+
82
+ it('prunes a stale endpoint regardless of owner', () => {
83
+ subscribe(userA, 'expired');
84
+
85
+ expect(
86
+ pushSubscriptionQueries.deleteStaleByEndpoint('https://push.example.com/expired')
87
+ ).toBe(true);
88
+ expect(pushSubscriptionQueries.listByUser(userA)).toHaveLength(0);
89
+ });
90
+ });
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Web Push subscription storage.
3
+ *
4
+ * One row per (user, device endpoint). Subscribing twice from the same
5
+ * browser reuses the same endpoint, so upsert keeps exactly one row per
6
+ * device. Rows die two ways: explicit unsubscribe, or a 404/410 from the
7
+ * push service on send (see `backend/push/sender.ts`).
8
+ */
9
+
10
+ import { getDatabase } from '../index';
11
+
12
+ export interface PushSubscription {
13
+ id: number;
14
+ user_id: string;
15
+ endpoint: string;
16
+ p256dh: string;
17
+ auth: string;
18
+ user_agent: string | null;
19
+ created_at: string;
20
+ }
21
+
22
+ export interface PushSubscriptionInput {
23
+ userId: string;
24
+ endpoint: string;
25
+ p256dh: string;
26
+ auth: string;
27
+ userAgent?: string;
28
+ }
29
+
30
+ export const pushSubscriptionQueries = {
31
+ upsert(input: PushSubscriptionInput): PushSubscription {
32
+ const db = getDatabase();
33
+ const now = new Date().toISOString();
34
+ db.prepare(
35
+ `
36
+ INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, user_agent, created_at)
37
+ VALUES (?, ?, ?, ?, ?, ?)
38
+ ON CONFLICT(endpoint) DO UPDATE SET
39
+ user_id = excluded.user_id,
40
+ p256dh = excluded.p256dh,
41
+ auth = excluded.auth,
42
+ user_agent = excluded.user_agent
43
+ `
44
+ ).run(
45
+ input.userId,
46
+ input.endpoint,
47
+ input.p256dh,
48
+ input.auth,
49
+ input.userAgent ?? null,
50
+ now
51
+ );
52
+ return db
53
+ .prepare('SELECT * FROM push_subscriptions WHERE endpoint = ?')
54
+ .get(input.endpoint) as PushSubscription;
55
+ },
56
+
57
+ listByUser(userId: string): PushSubscription[] {
58
+ const db = getDatabase();
59
+ return db
60
+ .prepare('SELECT * FROM push_subscriptions WHERE user_id = ? ORDER BY created_at')
61
+ .all(userId) as PushSubscription[];
62
+ },
63
+
64
+ deleteByEndpoint(userId: string, endpoint: string): boolean {
65
+ const db = getDatabase();
66
+ const result = db
67
+ .prepare('DELETE FROM push_subscriptions WHERE user_id = ? AND endpoint = ?')
68
+ .run(userId, endpoint) as { changes: number | bigint };
69
+ return Number(result.changes ?? 0) > 0;
70
+ },
71
+
72
+ /**
73
+ * Drop every device this user registered.
74
+ *
75
+ * `pushNotifications` is one per-user setting shared by all of their
76
+ * devices, so turning it off anywhere has to stop the pushes everywhere —
77
+ * deleting only the calling device's endpoint would leave a phone
78
+ * receiving notifications the settings screen says are off.
79
+ */
80
+ deleteAllByUser(userId: string): number {
81
+ const db = getDatabase();
82
+ const result = db
83
+ .prepare('DELETE FROM push_subscriptions WHERE user_id = ?')
84
+ .run(userId) as { changes: number | bigint };
85
+ return Number(result.changes ?? 0);
86
+ },
87
+
88
+ /**
89
+ * Delete regardless of owner. Used when a push service reports the
90
+ * endpoint expired (404/410) — the stored user may be stale too.
91
+ */
92
+ deleteStaleByEndpoint(endpoint: string): boolean {
93
+ const db = getDatabase();
94
+ const result = db
95
+ .prepare('DELETE FROM push_subscriptions WHERE endpoint = ?')
96
+ .run(endpoint) as { changes: number | bigint };
97
+ return Number(result.changes ?? 0) > 0;
98
+ }
99
+ };
@@ -1,23 +1,35 @@
1
1
  /**
2
2
  * Skill Queries
3
3
  *
4
- * CRUD for user-managed Agent Skills — the skills managed from Settings →
5
- * Skills. The `skills` table holds only METADATA + the enable/disable toggle;
6
- * the actual SKILL.md (and any bundled resources) live on disk in the canonical
7
- * store under `{clopenDir}/skills/<slug>/` (see `backend/skills/store.ts`).
4
+ * CRUD for user-managed Agent Skills — the single artifact behind both model-
5
+ * invoked skills and user-invoked `/slash` prompts (Settings → Skills). The
6
+ * `skills` table holds only METADATA + the enable toggle; the actual SKILL.md
7
+ * (and any bundled resources) live on disk in the canonical store under
8
+ * `{clopenDir}/skills/<slug>/` (see `backend/skills/store.ts`).
8
9
  *
9
10
  * Conventions:
10
- * - `slug` : unique machine id, matches the on-disk folder name and the
11
- * SKILL.md `name` frontmatter. Only `[a-z0-9-]`.
12
- * - `source` : where the skill came from — 'custom' (created in-app),
13
- * 'imported' (pasted/uploaded), or 'marketplace' (installed from
14
- * a provider).
11
+ * - `slug` : unique machine id, matches the on-disk folder name and the
12
+ * SKILL.md `name` frontmatter. Only `[a-z0-9-]`.
13
+ * - `source` : where the skill came from — 'custom' (created in-app),
14
+ * 'imported' (pasted/uploaded), or 'marketplace' (installed
15
+ * from a provider).
16
+ * - `triggers` : comma list of how the skill can be invoked — `auto` (the
17
+ * model decides, from the description) and/or `slash` (the user
18
+ * types `/<slug>`). Migration 079 folded the old `commands`
19
+ * table in as `slash`-triggered skills.
20
+ * - `uses` : JSON array of sibling slugs force-loaded whenever this skill
21
+ * runs, so one invocation can pull in several skills at once.
15
22
  */
16
23
 
17
24
  import { getDatabase } from '../index';
18
25
 
19
26
  export type SkillSource = 'custom' | 'imported' | 'marketplace';
20
27
 
28
+ /** How a skill can be invoked. */
29
+ export type SkillTrigger = 'auto' | 'slash';
30
+
31
+ export const SKILL_TRIGGERS: SkillTrigger[] = ['auto', 'slash'];
32
+
21
33
  /** Raw DB row. */
22
34
  export interface SkillRow {
23
35
  id: number;
@@ -31,6 +43,12 @@ export interface SkillRow {
31
43
  license: string | null;
32
44
  is_enabled: number;
33
45
  created_at: string;
46
+ /** Comma-separated {@link SkillTrigger} list; never empty (defaults to `auto`). */
47
+ triggers: string;
48
+ /** Argument hint shown beside `/slug` in the chat picker (slash skills). */
49
+ argument_hint: string | null;
50
+ /** JSON array of sibling slugs force-loaded with this skill. */
51
+ uses: string;
34
52
  }
35
53
 
36
54
  export interface SkillInput {
@@ -41,6 +59,46 @@ export interface SkillInput {
41
59
  marketplaceRef?: string | null;
42
60
  version?: string | null;
43
61
  license?: string | null;
62
+ /** Comma-separated trigger list; defaults to `auto`. */
63
+ triggers?: string;
64
+ argumentHint?: string | null;
65
+ /** JSON string: array of slugs. */
66
+ uses?: string;
67
+ }
68
+
69
+ /** Parse the stored comma list into triggers, tolerating blanks/unknown values. */
70
+ export function parseTriggers(raw: string | null | undefined): SkillTrigger[] {
71
+ const list = (raw ?? '')
72
+ .split(',')
73
+ .map(t => t.trim().toLowerCase())
74
+ .filter((t): t is SkillTrigger => SKILL_TRIGGERS.includes(t as SkillTrigger));
75
+ // A skill with no recognised trigger would be invocable by nobody — fall back
76
+ // to the historical default rather than silently disappearing.
77
+ return list.length > 0 ? Array.from(new Set(list)) : ['auto'];
78
+ }
79
+
80
+ /** Serialize triggers back to the stored comma list (canonical order). */
81
+ export function stringifyTriggers(triggers: SkillTrigger[] | undefined): string {
82
+ const set = new Set(triggers ?? []);
83
+ const ordered = SKILL_TRIGGERS.filter(t => set.has(t));
84
+ return (ordered.length > 0 ? ordered : ['auto']).join(',');
85
+ }
86
+
87
+ /** Parse the stored `uses` JSON array, tolerating null/blank/corrupt values. */
88
+ export function parseUses(raw: string | null | undefined): string[] {
89
+ if (!raw) return [];
90
+ try {
91
+ const parsed = JSON.parse(raw);
92
+ if (!Array.isArray(parsed)) return [];
93
+ return Array.from(new Set(parsed.filter((v): v is string => typeof v === 'string' && !!v.trim()).map(v => v.trim())));
94
+ } catch {
95
+ return [];
96
+ }
97
+ }
98
+
99
+ /** Serialize a `uses` list to its stored JSON form. */
100
+ export function stringifyUses(uses: string[] | undefined): string {
101
+ return JSON.stringify(Array.from(new Set((uses ?? []).map(u => u.trim()).filter(Boolean))));
44
102
  }
45
103
 
46
104
  export const skillQueries = {
@@ -67,8 +125,8 @@ export const skillQueries = {
67
125
  insert(input: SkillInput): SkillRow {
68
126
  const db = getDatabase();
69
127
  const result = db.prepare(
70
- `INSERT INTO skills (slug, name, description, source, marketplace_ref, version, license)
71
- VALUES (?, ?, ?, ?, ?, ?, ?)`
128
+ `INSERT INTO skills (slug, name, description, source, marketplace_ref, version, license, triggers, argument_hint, uses)
129
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
72
130
  ).run(
73
131
  input.slug,
74
132
  input.name,
@@ -76,19 +134,39 @@ export const skillQueries = {
76
134
  input.source ?? 'custom',
77
135
  input.marketplaceRef ?? null,
78
136
  input.version ?? null,
79
- input.license ?? null
137
+ input.license ?? null,
138
+ input.triggers ?? 'auto',
139
+ input.argumentHint ?? null,
140
+ input.uses ?? '[]'
80
141
  ) as { lastInsertRowid: number | bigint };
81
142
  const id = Number(result.lastInsertRowid);
82
143
  return this.getById(id)!;
83
144
  },
84
145
 
85
- /** Update the display metadata (name/description/license) of a skill. */
86
- updateMeta(id: number, name: string, description: string, license: string | null): void {
146
+ /** Update every editable field of a skill (the SKILL.md itself is rewritten by the service). */
147
+ updateMeta(
148
+ id: number,
149
+ fields: {
150
+ name: string;
151
+ description: string;
152
+ license: string | null;
153
+ triggers: string;
154
+ argumentHint: string | null;
155
+ uses: string;
156
+ }
157
+ ): void {
87
158
  const db = getDatabase();
88
- db.prepare(`UPDATE skills SET name = ?, description = ?, license = ? WHERE id = ?`).run(
89
- name,
90
- description,
91
- license,
159
+ db.prepare(
160
+ `UPDATE skills
161
+ SET name = ?, description = ?, license = ?, triggers = ?, argument_hint = ?, uses = ?
162
+ WHERE id = ?`
163
+ ).run(
164
+ fields.name,
165
+ fields.description,
166
+ fields.license,
167
+ fields.triggers,
168
+ fields.argumentHint,
169
+ fields.uses,
92
170
  id
93
171
  );
94
172
  },
@@ -30,6 +30,7 @@ import { WorkflowTranscriptTailer } from './workflow-transcript';
30
30
  import { resolveOsPath } from '$backend/utils/paths';
31
31
  import { setupEnvironmentOnce, getEngineEnv } from './environment';
32
32
  import { handleStreamError } from './error-handler';
33
+ import { emptyGenerationError } from '../../structured-helpers';
33
34
  import { getEnabledMcpServers, getAllowedMcpTools } from '../../../mcp';
34
35
  import { syncSkills } from '$backend/skills';
35
36
  import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
@@ -591,6 +592,6 @@ export class ClaudeCodeEngine implements AIEngine {
591
592
  }
592
593
  }
593
594
 
594
- throw new Error(lastError || 'Claude Code did not return valid structured output');
595
+ throw emptyGenerationError('Claude Code', lastError || undefined);
595
596
  }
596
597
  }
@@ -33,7 +33,7 @@ import { syncSkills } from '$backend/skills';
33
33
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
34
34
  import { artifactFilter } from '$backend/profiles';
35
35
  import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
36
- import { buildJsonPrompt, extractJson } from '../../structured-helpers';
36
+ import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
37
37
  import { EngineRuns } from '../run-registry';
38
38
  import { subagentQueries } from '$backend/database/queries';
39
39
  import { readSubagentMd } from '$backend/subagents/store';
@@ -141,7 +141,7 @@ export class ClineEngine implements AIEngine {
141
141
  } catch {
142
142
  base = 'You are Cline, a highly skilled software engineer. Use the available tools to complete the user\'s coding task.';
143
143
  }
144
- const artifacts = buildArtifactsPromptContext(profileId);
144
+ const artifacts = buildArtifactsPromptContext('cline', profileId);
145
145
  return artifacts ? `${base}\n\n${artifacts}` : base;
146
146
  }
147
147
 
@@ -448,7 +448,7 @@ export class ClineEngine implements AIEngine {
448
448
  });
449
449
 
450
450
  const result = await agent.run(buildJsonPrompt(prompt, schema));
451
- if (!result.outputText?.trim()) throw new Error('Cline returned no structured output');
451
+ if (!result.outputText?.trim()) throw emptyGenerationError('Cline');
452
452
  return extractJson<T>(result.outputText);
453
453
  }
454
454
  }
@@ -23,7 +23,7 @@ import type { Codex, Thread, ThreadOptions, Input as CodexInput, ModelReasoningE
23
23
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
24
24
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
25
25
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
26
- import { extractJson } from '../../structured-helpers';
26
+ import { extractJson, emptyGenerationError } from '../../structured-helpers';
27
27
  import { engineQueries } from '$backend/database/queries/engine-queries';
28
28
  import { resolveOsPath } from '$backend/utils/paths';
29
29
  import { resolveEngineCli } from '$backend/engine/engine-cli';
@@ -287,7 +287,7 @@ export class CodexEngine implements AIEngine {
287
287
  // Prompt-scoped engine: advertise the profile-scoped Skills/Commands/
288
288
  // Subagents PER-SESSION via the prompt (not the shared global AGENTS.md /
289
289
  // persistent client) so the active Profile scopes them correctly.
290
- const artifactsContext = buildArtifactsPromptContext(profileId);
290
+ const artifactsContext = buildArtifactsPromptContext('codex', profileId);
291
291
  const input = await buildCodexInput(prompt, artifactsContext || undefined);
292
292
  const { events } = await thread.runStreamed(input, {
293
293
  signal: controller.signal,
@@ -429,7 +429,7 @@ export class CodexEngine implements AIEngine {
429
429
  });
430
430
 
431
431
  if (!turn.finalResponse) {
432
- throw new Error('Codex returned empty response');
432
+ throw emptyGenerationError('Codex');
433
433
  }
434
434
 
435
435
  return extractJson<T>(turn.finalResponse);
@@ -19,7 +19,7 @@ import type {
19
19
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
20
20
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
21
21
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
22
- import { buildJsonPrompt, extractJson } from '../../structured-helpers';
22
+ import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
23
23
  import { engineQueries } from '$backend/database/queries/engine-queries';
24
24
  import { resolveOsPath, getEngineUserConfigDir } from '$backend/utils/paths';
25
25
  import { debug } from '$shared/utils/logger';
@@ -279,7 +279,7 @@ export class CopilotEngine implements AIEngine {
279
279
  // the authoritative per-session signal (synthetic commands/subagents are
280
280
  // stripped from the global file; the native skill mirror still loads the
281
281
  // filtered folders).
282
- const artifactsContext = buildArtifactsPromptContext(profileId);
282
+ const artifactsContext = buildArtifactsPromptContext('copilot', profileId);
283
283
 
284
284
  // Resolve the permission policy once per stream; onPermissionRequest below
285
285
  // enforces it (Copilot otherwise approves every tool via approveAll).
@@ -741,7 +741,7 @@ export class CopilotEngine implements AIEngine {
741
741
  try {
742
742
  const final = await session.sendAndWait({ prompt: jsonPrompt });
743
743
  if (!final?.data?.content) {
744
- throw new Error('Copilot returned no assistant message content');
744
+ throw emptyGenerationError('GitHub Copilot', 'no assistant message content');
745
745
  }
746
746
  return extractJson<T>(final.data.content);
747
747
  } finally {
@@ -31,10 +31,11 @@ import { engineQueries } from '$backend/database/queries/engine-queries';
31
31
  import { syncSkills } from '$backend/skills';
32
32
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
33
33
  import { artifactFilter } from '$backend/profiles';
34
+ import { resolvePermissionsFromDb, excludedBuiltinTools } from '$backend/permissions';
34
35
  import { getCursorMcpConfig } from '../../../mcp';
35
36
  import { subagentQueries } from '$backend/database/queries';
36
37
  import { readSubagentMd } from '$backend/subagents/store';
37
- import { buildJsonPrompt, extractJson } from '../../structured-helpers';
38
+ import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
38
39
  import { EngineRuns } from '../run-registry';
39
40
  import { getActiveCursorAccount, resolveCursorApiKey } from './credential';
40
41
  import { getCursorStore } from './environment';
@@ -177,6 +178,20 @@ export class CursorEngine implements AIEngine {
177
178
  await syncSkills('cursor', profileId);
178
179
  await syncEngineArtifacts('cursor', profileId);
179
180
 
181
+ // ── Permissions → disallowedTools ──
182
+ // Cursor exposes no per-call permission hook, but `AgentOptions` takes a
183
+ // `disallowedTools` list that is applied before the toolset is offered to
184
+ // the model — strictly stronger than a hook, since a blocked tool is never
185
+ // even visible. Names must come from the SDK's own vocabulary (see
186
+ // ENGINE_BUILTIN_TOOLS.cursor); an unknown one throws at Agent.create.
187
+ // Not persisted on the agent, so it is passed to BOTH create and resume.
188
+ const permissions = resolvePermissionsFromDb('cursor', options.mcpContext?.projectId, profileId);
189
+ const disallowedTools = excludedBuiltinTools(permissions, 'cursor');
190
+ if (disallowedTools.length > 0) {
191
+ debug.log('engine', `Cursor permissions: withholding ${disallowedTools.length} tool(s) — ${disallowedTools.join(', ')}`);
192
+ }
193
+ const toolPolicy = disallowedTools.length > 0 ? { disallowedTools } : {};
194
+
180
195
  // ── Output queue merging the pull stream with the ask tool's push emissions ──
181
196
  const queue = new EventQueue<EngineOutput>();
182
197
  const converterHolder: { current: ReturnType<typeof createCursorMessageConverter> | null } = { current: null };
@@ -224,6 +239,7 @@ export class CursorEngine implements AIEngine {
224
239
  apiKey,
225
240
  model: { id: modelId },
226
241
  local: localOptions,
242
+ ...toolPolicy,
227
243
  ...(Object.keys(mcpServers).length ? { mcpServers } : {}),
228
244
  ...(agents ? { agents } : {}),
229
245
  })
@@ -231,6 +247,7 @@ export class CursorEngine implements AIEngine {
231
247
  apiKey,
232
248
  model: { id: modelId },
233
249
  local: localOptions,
250
+ ...toolPolicy,
234
251
  ...(Object.keys(mcpServers).length ? { mcpServers } : {}),
235
252
  ...(agents ? { agents } : {}),
236
253
  });
@@ -246,8 +263,13 @@ export class CursorEngine implements AIEngine {
246
263
  converterHolder.current = converter;
247
264
 
248
265
  // Build the user turn (text + image attachments).
266
+ //
267
+ // The artifact context rides the user message because `@cursor/sdk` has no
268
+ // system-prompt option — `AgentOptions` exposes model/tools/mcpServers/agents
269
+ // and nothing else. It is rebuilt per turn on purpose: the active Profile can
270
+ // change mid-session, and a stale advertisement is worse than a repeated one.
249
271
  const promptText = prompt.content.filter(b => b.type === 'text').map(b => (b.type === 'text' ? b.text : '')).join('\n');
250
- const artifacts = buildArtifactsPromptContext(profileId);
272
+ const artifacts = buildArtifactsPromptContext('cursor', profileId);
251
273
  const text = artifacts ? `${artifacts}\n\n${promptText}` : promptText;
252
274
  const images: SDKImage[] = [];
253
275
  for (const b of prompt.content) {
@@ -394,7 +416,7 @@ export class CursorEngine implements AIEngine {
394
416
  try {
395
417
  const run = await agent.send(buildJsonPrompt(prompt, schema));
396
418
  const result = await run.wait();
397
- if (!result.result?.trim()) throw new Error('Cursor returned no structured output');
419
+ if (!result.result?.trim()) throw emptyGenerationError('Cursor');
398
420
  return extractJson<T>(result.result);
399
421
  } finally {
400
422
  try { agent.close(); } catch { /* ignore */ }
@@ -50,7 +50,7 @@ import { buildOpenCodeInlineAgents } from '$backend/subagents';
50
50
  import { getOpenCodeProfileDisabledToolIds } from '$backend/mcp';
51
51
  import { resolvePermissionsFromDb, matchesAny, type ResolvedPermissions } from '$backend/permissions';
52
52
  import { formatSessionError, handleStreamError } from './error-handler';
53
- import { buildJsonPrompt, extractJson } from '../../structured-helpers';
53
+ import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
54
54
  import { EngineRuns } from '../run-registry';
55
55
  import { debug } from '$shared/utils/logger';
56
56
 
@@ -250,7 +250,7 @@ export class OpenCodeEngine implements AIEngine {
250
250
  // so advertise the profile-scoped set PER-SESSION by prepending it as a
251
251
  // leading context part each turn (authoritative for synthetic skills;
252
252
  // advisory on top of the native command/agent dirs).
253
- const artifactsContext = buildArtifactsPromptContext(profileId);
253
+ const artifactsContext = buildArtifactsPromptContext('opencode', profileId);
254
254
  if (artifactsContext) {
255
255
  promptParts.unshift({ type: 'text', text: artifactsContext });
256
256
  }
@@ -1147,7 +1147,7 @@ export class OpenCodeEngine implements AIEngine {
1147
1147
 
1148
1148
  const data = response.data;
1149
1149
  if (!data) {
1150
- throw new Error('OpenCode returned empty response');
1150
+ throw emptyGenerationError('OpenCode', 'no response body');
1151
1151
  }
1152
1152
 
1153
1153
  const parts = data.parts || [];
@@ -1166,9 +1166,7 @@ export class OpenCodeEngine implements AIEngine {
1166
1166
  const source = textContent || collectText('reasoning');
1167
1167
 
1168
1168
  if (!source) {
1169
- throw new Error(
1170
- `OpenCode returned no parseable content (received parts: ${parts.map((p: any) => p.type).join(', ') || 'none'})`
1171
- );
1169
+ throw emptyGenerationError('OpenCode', `received parts: ${parts.map((p: any) => p.type).join(', ') || 'none'}`);
1172
1170
  }
1173
1171
 
1174
1172
  debug.log('engine', `[OC structured] Raw text: ${source.slice(0, 200)}`);
@@ -38,7 +38,7 @@ import { syncSkills } from '$backend/skills';
38
38
  import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
39
39
  import { artifactFilter } from '$backend/profiles';
40
40
  import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
41
- import { buildJsonPrompt, extractJson } from '../../structured-helpers';
41
+ import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
42
42
  import { EngineRuns } from '../run-registry';
43
43
  import { DbCredentialStore, getPiAccountForProvider, parsePiCredential } from './credential';
44
44
  import { createPiRuntime } from './presets';
@@ -467,7 +467,7 @@ export class PiEngine implements AIEngine {
467
467
  try { session.dispose(); } catch { /* ignore */ }
468
468
  }
469
469
 
470
- if (!resultText.trim()) throw new Error('Pi returned no structured output');
470
+ if (!resultText.trim()) throw emptyGenerationError('Pi');
471
471
  return extractJson<T>(resultText);
472
472
  }
473
473
  }
@@ -39,7 +39,7 @@ import type {
39
39
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
40
40
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
41
41
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
42
- import { buildJsonPrompt, extractJson } from '../../structured-helpers';
42
+ import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
43
43
  import { resolveOsPath } from '$backend/utils/paths';
44
44
  import { debug } from '$shared/utils/logger';
45
45
  import { getEngineEnv } from './environment';
@@ -474,7 +474,7 @@ export class QwenEngine implements AIEngine {
474
474
  }
475
475
 
476
476
  if (!resultText) {
477
- throw new Error(errorMessage || 'Qwen returned no result text');
477
+ throw emptyGenerationError('Qwen Code', errorMessage || undefined);
478
478
  }
479
479
 
480
480
  return extractJson<T>(resultText);