@myrialabs/clopen 0.4.40 → 0.4.42

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 (141) 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 +50 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/index.ts +18 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
  20. package/backend/database/migrations/082_create_git_identities.ts +122 -0
  21. package/backend/database/migrations/index.ts +28 -0
  22. package/backend/database/queries/file-share-queries.ts +163 -0
  23. package/backend/database/queries/git-identity-queries.ts +290 -0
  24. package/backend/database/queries/index.ts +8 -4
  25. package/backend/database/queries/profile-queries.ts +5 -3
  26. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  27. package/backend/database/queries/push-subscription-queries.ts +99 -0
  28. package/backend/database/queries/skill-queries.ts +96 -18
  29. package/backend/engine/adapters/claude/environment.ts +11 -1
  30. package/backend/engine/adapters/claude/stream.ts +3 -2
  31. package/backend/engine/adapters/cline/stream.ts +3 -3
  32. package/backend/engine/adapters/codex/stream.ts +38 -6
  33. package/backend/engine/adapters/copilot/stream.ts +3 -3
  34. package/backend/engine/adapters/cursor/stream.ts +25 -3
  35. package/backend/engine/adapters/opencode/server.ts +26 -2
  36. package/backend/engine/adapters/opencode/stream.ts +8 -7
  37. package/backend/engine/adapters/pi/stream.ts +2 -2
  38. package/backend/engine/adapters/qwen/stream.ts +5 -3
  39. package/backend/engine/artifact-sync.ts +26 -20
  40. package/backend/engine/docs/artifacts.md +81 -22
  41. package/backend/engine/docs/quick-reference.md +2 -1
  42. package/backend/engine/resolve-model.test.ts +108 -0
  43. package/backend/engine/resolve-model.ts +53 -10
  44. package/backend/engine/structured-helpers.ts +22 -0
  45. package/backend/engine/types.ts +10 -0
  46. package/backend/files/file-shares.ts +369 -0
  47. package/backend/files/path-browsing.ts +27 -21
  48. package/backend/git/git-executor.ts +28 -2
  49. package/backend/git/git-service.ts +59 -40
  50. package/backend/git/identity/cli.test.ts +58 -0
  51. package/backend/git/identity/cli.ts +201 -0
  52. package/backend/git/identity/credential-helper.test.ts +242 -0
  53. package/backend/git/identity/env.test.ts +214 -0
  54. package/backend/git/identity/env.ts +193 -0
  55. package/backend/git/identity/import-local.test.ts +199 -0
  56. package/backend/git/identity/import-local.ts +141 -0
  57. package/backend/git/identity/index.ts +78 -0
  58. package/backend/git/identity/keys.ts +183 -0
  59. package/backend/git/identity/resolve.ts +140 -0
  60. package/backend/git/identity/scope-config.test.ts +145 -0
  61. package/backend/git/identity/scope-config.ts +175 -0
  62. package/backend/git/identity/service.ts +297 -0
  63. package/backend/http/files-shared.test.ts +505 -0
  64. package/backend/http/files-shared.ts +351 -0
  65. package/backend/http/push.ts +150 -0
  66. package/backend/index.ts +24 -0
  67. package/backend/instructions/index.ts +1 -1
  68. package/backend/instructions/sync.ts +30 -6
  69. package/backend/memory/compose.ts +2 -2
  70. package/backend/memory/consolidate.ts +2 -2
  71. package/backend/memory/extract/episodic.ts +2 -2
  72. package/backend/memory/judge.ts +2 -2
  73. package/backend/preview/browser/browser-console-manager.ts +214 -34
  74. package/backend/preview/browser/browser-pool.ts +526 -123
  75. package/backend/preview/browser/browser-preview-service.ts +192 -8
  76. package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
  77. package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
  78. package/backend/preview/browser/browser-tab-manager.ts +291 -65
  79. package/backend/preview/browser/capture-profile.ts +15 -1
  80. package/backend/preview/browser/types.ts +26 -1
  81. package/backend/profiles/service.ts +7 -6
  82. package/backend/push/sender.ts +172 -0
  83. package/backend/push/tags.ts +25 -0
  84. package/backend/push/vapid-keys.ts +77 -0
  85. package/backend/push/webpush-crypto.test.ts +200 -0
  86. package/backend/push/webpush-crypto.ts +231 -0
  87. package/backend/skills/detect.ts +28 -0
  88. package/backend/skills/index.ts +22 -4
  89. package/backend/skills/invoke.test.ts +114 -0
  90. package/backend/skills/invoke.ts +222 -0
  91. package/backend/skills/service.ts +194 -44
  92. package/backend/skills/spec.ts +35 -0
  93. package/backend/skills/sync.ts +85 -55
  94. package/backend/subagents/detect.ts +2 -3
  95. package/backend/subagents/sync.ts +15 -8
  96. package/backend/terminal/ptykit.ts +24 -0
  97. package/backend/work/pull-requests.ts +2 -2
  98. package/backend/ws/chat/stream.ts +100 -8
  99. package/backend/ws/files/index.ts +4 -0
  100. package/backend/ws/files/share.ts +95 -0
  101. package/backend/ws/git/branch-name.ts +2 -2
  102. package/backend/ws/git/branch.ts +17 -6
  103. package/backend/ws/git/commit-message.ts +2 -2
  104. package/backend/ws/git/commit.ts +6 -5
  105. package/backend/ws/git/conflict.ts +3 -2
  106. package/backend/ws/git/identity-context.ts +91 -0
  107. package/backend/ws/git/identity.ts +200 -0
  108. package/backend/ws/git/index.ts +3 -1
  109. package/backend/ws/git/remote.ts +57 -11
  110. package/backend/ws/index.ts +3 -4
  111. package/backend/ws/preview/browser/data.ts +60 -0
  112. package/backend/ws/preview/browser/interact.ts +6 -0
  113. package/backend/ws/preview/browser/tab-info.ts +9 -1
  114. package/backend/ws/preview/browser/tab.ts +64 -8
  115. package/backend/ws/preview/index.ts +21 -0
  116. package/backend/ws/profiles/crud.ts +2 -3
  117. package/backend/ws/skills/catalog.ts +5 -1
  118. package/backend/ws/skills/crud.ts +128 -22
  119. package/backend/ws/skills/index.ts +4 -1
  120. package/backend/ws/user/crud.ts +12 -3
  121. package/bin/clopen.ts +9 -0
  122. package/dist/assets/{index-D4igjF6e.js → index-BynqyvF4.js} +1 -1
  123. package/dist/assets/{index-DONNwiXm.js → index-DLoJsmNQ.js} +1 -1
  124. package/dist/assets/{main-BrfXH1bL.js → main-CUyZAmqt.js} +601 -592
  125. package/dist/assets/main-DVCW3cfr.css +1 -0
  126. package/dist/index.html +7 -2
  127. package/dist/sw.js +112 -0
  128. package/package.json +2 -2
  129. package/shared/constants/engine-tools.ts +31 -6
  130. package/shared/constants/notification-messages.ts +142 -0
  131. package/shared/types/git-identity.ts +112 -0
  132. package/shared/types/unified/stream.ts +7 -0
  133. package/backend/commands/detect.ts +0 -25
  134. package/backend/commands/index.ts +0 -9
  135. package/backend/commands/service.ts +0 -178
  136. package/backend/commands/store.ts +0 -45
  137. package/backend/commands/sync.ts +0 -94
  138. package/backend/database/queries/command-queries.ts +0 -82
  139. package/backend/ws/commands/crud.ts +0 -157
  140. package/backend/ws/commands/index.ts +0 -8
  141. package/dist/assets/main-CT1PygsW.css +0 -1
@@ -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
  },
@@ -57,8 +57,16 @@ export async function setupEnvironmentOnce(): Promise<void> {
57
57
  *
58
58
  * When accountId is provided, overrides the OAuth token with that
59
59
  * specific account's token instead of the globally active account.
60
+ *
61
+ * `extraEnv` is applied last and carries per-turn values the caller resolved —
62
+ * in practice the requester's git identity, so a `git commit` the agent runs
63
+ * through its shell tool is authored by the same person the Git panel would
64
+ * attribute it to.
60
65
  */
61
- export function getEngineEnv(accountId?: number): Record<string, string> {
66
+ export function getEngineEnv(
67
+ accountId?: number,
68
+ extraEnv?: Record<string, string>
69
+ ): Record<string, string> {
62
70
  // Start from clean env (no Bun/npm/Vite pollution)
63
71
  const env = getCleanSpawnEnv();
64
72
  // Apply our overrides
@@ -77,6 +85,8 @@ export function getEngineEnv(accountId?: number): Record<string, string> {
77
85
  }
78
86
  }
79
87
 
88
+ if (extraEnv) Object.assign(env, extraEnv);
89
+
80
90
  return env;
81
91
  }
82
92
 
@@ -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';
@@ -225,7 +226,7 @@ export class ClaudeCodeEngine implements AIEngine {
225
226
  permissionMode: 'bypassPermissions' as PermissionMode,
226
227
  allowDangerouslySkipPermissions: true,
227
228
  cwd: resolvedProjectPath,
228
- env: getEngineEnv(accountId),
229
+ env: getEngineEnv(accountId, options.gitIdentityEnv),
229
230
  systemPrompt: { type: "preset", preset: "claude_code" },
230
231
  settingSources: ["user", "project", "local"],
231
232
  forkSession: true,
@@ -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';
@@ -64,6 +64,17 @@ interface CodexRun {
64
64
  thread: Thread | null;
65
65
  }
66
66
 
67
+ /**
68
+ * A stable key for an identity environment, so "same identity?" is a string
69
+ * compare rather than a deep object compare. Sorted because the builder's key
70
+ * order is an implementation detail, not a difference.
71
+ */
72
+ function gitIdentityKey(env: Record<string, string>): string {
73
+ const keys = Object.keys(env).sort();
74
+ if (keys.length === 0) return '';
75
+ return keys.map((k) => `${k}=${env[k]}`).join('\u0000');
76
+ }
77
+
67
78
  export class CodexEngine implements AIEngine {
68
79
  readonly name = 'codex' as const;
69
80
 
@@ -104,6 +115,17 @@ export class CodexEngine implements AIEngine {
104
115
  * satisfying that type.
105
116
  */
106
117
  private pendingProjectId: string | null = null;
118
+ /**
119
+ * Git identity baked into the current client, as a comparable key.
120
+ *
121
+ * The SDK takes `env` at construction and does not re-read it, so the
122
+ * identity is part of what the client IS — exactly like the account and the
123
+ * MCP set. Stored as a stable string so a turn can ask "is this still the
124
+ * right client" without deep-comparing the environment.
125
+ */
126
+ private currentGitIdentityKey: string | null = null;
127
+ /** Identity for the client `initialize()` is about to build. */
128
+ private pendingGitIdentityEnv: Record<string, string> = {};
107
129
 
108
130
  get isInitialized(): boolean {
109
131
  return this._isInitialized;
@@ -161,7 +183,7 @@ export class CodexEngine implements AIEngine {
161
183
  this.codex = new Codex({
162
184
  apiKey: credential.kind === 'api_key' ? credential.apiKey : undefined,
163
185
  ...(codexCli ? { codexPathOverride: codexCli.path } : {}),
164
- env: { ...getCleanSpawnEnv(), CODEX_HOME: getCodexHomeDir() },
186
+ env: { ...getCleanSpawnEnv(), CODEX_HOME: getCodexHomeDir(), ...this.pendingGitIdentityEnv },
165
187
  config: {
166
188
  show_raw_agent_reasoning: true,
167
189
  ...(Object.keys(mcpConfig).length > 0 ? { mcp_servers: mcpConfig } : {}),
@@ -170,6 +192,7 @@ export class CodexEngine implements AIEngine {
170
192
  this.currentAccountId = account.id;
171
193
  this.currentMcpFilterKey = mcpKey;
172
194
  this.currentProjectId = projectId;
195
+ this.currentGitIdentityKey = gitIdentityKey(this.pendingGitIdentityEnv);
173
196
  this._isInitialized = true;
174
197
  debug.log('engine', `Codex engine initialized (account ${account.id}, mode=${credential.kind}, mcpFilter=${mcpKey}, project=${projectId ?? 'none'})`);
175
198
  }
@@ -180,6 +203,7 @@ export class CodexEngine implements AIEngine {
180
203
  this.currentAccountId = null;
181
204
  this.currentMcpFilterKey = null;
182
205
  this.currentProjectId = null;
206
+ this.currentGitIdentityKey = null;
183
207
  this._isInitialized = false;
184
208
  debug.log('engine', 'Codex engine disposed');
185
209
  }
@@ -219,11 +243,19 @@ export class CodexEngine implements AIEngine {
219
243
  // ended up opening tabs in another.
220
244
  const streamProjectId = options.mcpContext?.projectId ?? null;
221
245
  const projectChanged = this._isInitialized && streamProjectId !== null && streamProjectId !== this.currentProjectId;
222
- if (accountChanged || mcpChanged || projectChanged) {
223
- debug.log('engine', `Codex re-initialising (accountChanged=${accountChanged}, mcpChanged=${mcpChanged}, projectChanged=${projectChanged})`);
246
+ // One client serves every turn, so a turn requested by a different user —
247
+ // or in a project bound to a different identity — must not inherit the
248
+ // previous requester's git identity. Re-creating the client is the only
249
+ // way to change an env the SDK already baked.
250
+ const streamGitIdentityEnv = options.gitIdentityEnv ?? {};
251
+ const identityChanged =
252
+ this._isInitialized && gitIdentityKey(streamGitIdentityEnv) !== this.currentGitIdentityKey;
253
+ if (accountChanged || mcpChanged || projectChanged || identityChanged) {
254
+ debug.log('engine', `Codex re-initialising (accountChanged=${accountChanged}, mcpChanged=${mcpChanged}, projectChanged=${projectChanged}, identityChanged=${identityChanged})`);
224
255
  await this.dispose();
225
256
  }
226
257
  this.pendingProjectId = streamProjectId;
258
+ this.pendingGitIdentityEnv = streamGitIdentityEnv;
227
259
  if (!this._isInitialized || !this.codex) {
228
260
  await this.initialize(accountId, mcpProfileFilter);
229
261
  }
@@ -287,7 +319,7 @@ export class CodexEngine implements AIEngine {
287
319
  // Prompt-scoped engine: advertise the profile-scoped Skills/Commands/
288
320
  // Subagents PER-SESSION via the prompt (not the shared global AGENTS.md /
289
321
  // persistent client) so the active Profile scopes them correctly.
290
- const artifactsContext = buildArtifactsPromptContext(profileId);
322
+ const artifactsContext = buildArtifactsPromptContext('codex', profileId);
291
323
  const input = await buildCodexInput(prompt, artifactsContext || undefined);
292
324
  const { events } = await thread.runStreamed(input, {
293
325
  signal: controller.signal,
@@ -429,7 +461,7 @@ export class CodexEngine implements AIEngine {
429
461
  });
430
462
 
431
463
  if (!turn.finalResponse) {
432
- throw new Error('Codex returned empty response');
464
+ throw emptyGenerationError('Codex');
433
465
  }
434
466
 
435
467
  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 */ }
@@ -142,6 +142,19 @@ export interface ServerConfigSpec {
142
142
  subagentFilter?: Set<string>;
143
143
  /** Inline agent definitions (undefined/empty = the engine's default set). */
144
144
  inlineAgents?: Record<string, OpenCodeInlineAgent>;
145
+ /**
146
+ * Git identity of whoever asked for this turn, as a `GIT_CONFIG_*` block.
147
+ *
148
+ * Folded into the signature for the same reason the connector set and the
149
+ * provider credentials are: the server process is spawned with it and cannot
150
+ * re-read it. One server serves every turn routed to it, so without this a
151
+ * second user's turn would reuse a server carrying the FIRST user's identity
152
+ * and commit under their name.
153
+ *
154
+ * In the ordinary case — one person, one identity — the block is identical
155
+ * every turn and the signature does not move, so no extra server is spawned.
156
+ */
157
+ gitIdentityEnv?: Record<string, string>;
145
158
  }
146
159
 
147
160
  /** Everything needed to spawn a server, plus the key derived from it. */
@@ -150,6 +163,7 @@ interface SpawnPlan {
150
163
  scopeKey: string;
151
164
  configContent: string;
152
165
  envVars: Record<string, string>;
166
+ gitIdentityEnv: Record<string, string>;
153
167
  }
154
168
 
155
169
  /**
@@ -653,13 +667,20 @@ async function resolvePlan(spec: ServerConfigSpec): Promise<SpawnPlan> {
653
667
  // models.dev catalog it reads lives in `settings`, which bumps no revision.
654
668
  const providerConfig = generateOpenCodeProviderConfig();
655
669
  const configContent = assembleConfigContent(config, providerConfig.enabledProviders, spec.inlineAgents);
670
+ // Sorted so the key order the builder happens to emit is not mistaken for a
671
+ // different identity.
672
+ const gitIdentityEnv = spec.gitIdentityEnv ?? {};
673
+ const gitIdentityKey = Object.keys(gitIdentityEnv)
674
+ .sort()
675
+ .map((k) => `${k}=${gitIdentityEnv[k]}`)
676
+ .join('\u0000');
656
677
  const signature = hashConfig(
657
- `${configContent}‖${JSON.stringify(providerConfig.envVars)}‖${fingerprint}‖${internalBridgeExposure()}`
678
+ `${configContent}‖${JSON.stringify(providerConfig.envVars)}‖${fingerprint}‖${internalBridgeExposure()}‖${gitIdentityKey}`
658
679
  );
659
680
  const key = `${scopeKey}#${signature}`;
660
681
 
661
682
  currentKeyByScope.set(scopeKey, key);
662
- return { key, scopeKey, configContent, envVars: providerConfig.envVars };
683
+ return { key, scopeKey, configContent, envVars: providerConfig.envVars, gitIdentityEnv };
663
684
  }
664
685
 
665
686
  // ============================================================================
@@ -955,6 +976,9 @@ async function spawnServerOnce(
955
976
  env: {
956
977
  ...process.env,
957
978
  ...plan.envVars,
979
+ // The identity this server was keyed on, so a `git commit` the agent
980
+ // runs is authored by the person whose turn spawned it.
981
+ ...plan.gitIdentityEnv,
958
982
  XDG_CONFIG_HOME: configDir,
959
983
  XDG_DATA_HOME: dataDir,
960
984
  XDG_STATE_HOME: dataDir,
@@ -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
 
@@ -228,7 +228,10 @@ export class OpenCodeEngine implements AIEngine {
228
228
  // stream keeps running until that stream is done. Holding the server by
229
229
  // stream id is what makes that safe: a held server is never reaped.
230
230
  const holderId = options.mcpContext?.streamId;
231
- const server = await acquireServer({ mcpProfileFilter, subagentFilter, inlineAgents }, holderId);
231
+ const server = await acquireServer(
232
+ { mcpProfileFilter, subagentFilter, inlineAgents, gitIdentityEnv: options.gitIdentityEnv },
233
+ holderId
234
+ );
232
235
  run.server = server;
233
236
  run.holder = holderId ? { key: server.key, holderId } : null;
234
237
  const client = server.client;
@@ -250,7 +253,7 @@ export class OpenCodeEngine implements AIEngine {
250
253
  // so advertise the profile-scoped set PER-SESSION by prepending it as a
251
254
  // leading context part each turn (authoritative for synthetic skills;
252
255
  // advisory on top of the native command/agent dirs).
253
- const artifactsContext = buildArtifactsPromptContext(profileId);
256
+ const artifactsContext = buildArtifactsPromptContext('opencode', profileId);
254
257
  if (artifactsContext) {
255
258
  promptParts.unshift({ type: 'text', text: artifactsContext });
256
259
  }
@@ -1147,7 +1150,7 @@ export class OpenCodeEngine implements AIEngine {
1147
1150
 
1148
1151
  const data = response.data;
1149
1152
  if (!data) {
1150
- throw new Error('OpenCode returned empty response');
1153
+ throw emptyGenerationError('OpenCode', 'no response body');
1151
1154
  }
1152
1155
 
1153
1156
  const parts = data.parts || [];
@@ -1166,9 +1169,7 @@ export class OpenCodeEngine implements AIEngine {
1166
1169
  const source = textContent || collectText('reasoning');
1167
1170
 
1168
1171
  if (!source) {
1169
- throw new Error(
1170
- `OpenCode returned no parseable content (received parts: ${parts.map((p: any) => p.type).join(', ') || 'none'})`
1171
- );
1172
+ throw emptyGenerationError('OpenCode', `received parts: ${parts.map((p: any) => p.type).join(', ') || 'none'}`);
1172
1173
  }
1173
1174
 
1174
1175
  debug.log('engine', `[OC structured] Raw text: ${source.slice(0, 200)}`);