@myrialabs/clopen 0.4.8 → 0.4.10

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 (107) hide show
  1. package/README.md +10 -7
  2. package/backend/artifacts/detect.ts +129 -0
  3. package/backend/artifacts/engine-map.ts +53 -0
  4. package/backend/artifacts/frontmatter.ts +68 -0
  5. package/backend/artifacts/generate.ts +105 -0
  6. package/backend/artifacts/index.ts +34 -0
  7. package/backend/artifacts/markers.ts +76 -0
  8. package/backend/artifacts/matrix.ts +247 -0
  9. package/backend/artifacts/slug.ts +35 -0
  10. package/backend/artifacts/sync.ts +130 -0
  11. package/backend/artifacts/types.ts +152 -0
  12. package/backend/auth/permissions.ts +51 -1
  13. package/backend/chat/stream-manager.ts +14 -1
  14. package/backend/commands/detect.ts +25 -0
  15. package/backend/commands/index.ts +9 -0
  16. package/backend/commands/service.ts +178 -0
  17. package/backend/commands/store.ts +45 -0
  18. package/backend/commands/sync.ts +94 -0
  19. package/backend/database/migrations/045_create_commands_table.ts +28 -0
  20. package/backend/database/migrations/046_create_subagents_table.ts +29 -0
  21. package/backend/database/migrations/047_create_instructions_table.ts +29 -0
  22. package/backend/database/migrations/048_add_mcp_tool_overrides.ts +23 -0
  23. package/backend/database/migrations/049_create_permission_sets_table.ts +50 -0
  24. package/backend/database/migrations/050_create_profiles_tables.ts +57 -0
  25. package/backend/database/migrations/051_add_profile_to_sessions.ts +20 -0
  26. package/backend/database/migrations/052_add_default_profile_to_projects.ts +20 -0
  27. package/backend/database/migrations/053_add_profile_to_permission_sets.ts +37 -0
  28. package/backend/database/migrations/054_drop_subagent_agent_type.ts +20 -0
  29. package/backend/database/migrations/055_artifact_model_tools_per_engine.ts +43 -0
  30. package/backend/database/migrations/index.ts +77 -0
  31. package/backend/database/queries/command-queries.ts +82 -0
  32. package/backend/database/queries/index.ts +12 -2
  33. package/backend/database/queries/instruction-queries.ts +62 -0
  34. package/backend/database/queries/mcp-server-queries.ts +25 -0
  35. package/backend/database/queries/permission-set-queries.ts +155 -0
  36. package/backend/database/queries/profile-queries.ts +118 -0
  37. package/backend/database/queries/project-queries.ts +14 -0
  38. package/backend/database/queries/session-queries.ts +21 -0
  39. package/backend/database/queries/subagent-queries.ts +92 -0
  40. package/backend/engine/adapters/claude/stream.ts +27 -3
  41. package/backend/engine/adapters/codex/stream.ts +46 -14
  42. package/backend/engine/adapters/copilot/stream.ts +58 -4
  43. package/backend/engine/adapters/opencode/message-converter.ts +22 -2
  44. package/backend/engine/adapters/opencode/server.ts +166 -210
  45. package/backend/engine/adapters/opencode/stream.ts +150 -24
  46. package/backend/engine/adapters/qwen/stream.ts +23 -3
  47. package/backend/engine/artifact-sync.ts +51 -0
  48. package/backend/engine/types.ts +6 -0
  49. package/backend/instructions/index.ts +8 -0
  50. package/backend/instructions/service.ts +63 -0
  51. package/backend/instructions/sync.ts +56 -0
  52. package/backend/mcp/external/config.ts +42 -20
  53. package/backend/mcp/external/proxy.ts +89 -5
  54. package/backend/mcp/external/tools.ts +88 -0
  55. package/backend/mcp/index.ts +38 -15
  56. package/backend/mcp/internal/config.ts +48 -11
  57. package/backend/mcp/internal/remote-server.ts +9 -1
  58. package/backend/permissions/index.ts +27 -0
  59. package/backend/permissions/materialize.ts +96 -0
  60. package/backend/permissions/resolve.test.ts +162 -0
  61. package/backend/permissions/resolve.ts +106 -0
  62. package/backend/permissions/service.ts +167 -0
  63. package/backend/profiles/index.ts +10 -0
  64. package/backend/profiles/service.ts +169 -0
  65. package/backend/project/status-manager.ts +7 -25
  66. package/backend/skills/index.ts +1 -1
  67. package/backend/skills/sync.ts +88 -128
  68. package/backend/subagents/detect.ts +23 -0
  69. package/backend/subagents/index.ts +10 -0
  70. package/backend/subagents/service.ts +166 -0
  71. package/backend/subagents/store.ts +44 -0
  72. package/backend/subagents/sync.ts +144 -0
  73. package/backend/utils/static-curl.ts +12 -54
  74. package/backend/ws/artifacts/generate.ts +51 -0
  75. package/backend/ws/artifacts/index.ts +8 -0
  76. package/backend/ws/chat/stream.ts +33 -2
  77. package/backend/ws/commands/crud.ts +157 -0
  78. package/backend/ws/commands/index.ts +8 -0
  79. package/backend/ws/git/branch.ts +4 -2
  80. package/backend/ws/git/remote.ts +21 -11
  81. package/backend/ws/index.ts +17 -1
  82. package/backend/ws/instructions/crud.ts +53 -0
  83. package/backend/ws/instructions/index.ts +8 -0
  84. package/backend/ws/mcp/crud.ts +7 -1
  85. package/backend/ws/mcp/index.ts +4 -1
  86. package/backend/ws/mcp/tools.ts +112 -0
  87. package/backend/ws/permissions/crud.ts +72 -0
  88. package/backend/ws/permissions/index.ts +8 -0
  89. package/backend/ws/profiles/crud.ts +149 -0
  90. package/backend/ws/profiles/index.ts +9 -0
  91. package/backend/ws/sessions/crud.ts +12 -0
  92. package/backend/ws/subagents/crud.ts +136 -0
  93. package/backend/ws/subagents/index.ts +8 -0
  94. package/dist/assets/{index-jGo0X72U.js → index-C3kp8wpM.js} +1 -1
  95. package/dist/assets/{index-B_F_OgoC.js → index-cVUk7das.js} +1 -1
  96. package/dist/assets/main-CuCxUeqZ.js +533 -0
  97. package/dist/assets/main-D4pdkiQK.css +1 -0
  98. package/dist/index.html +2 -2
  99. package/package.json +24 -24
  100. package/shared/constants/engine-tools.ts +56 -0
  101. package/shared/types/database/schema.ts +2 -0
  102. package/shared/types/stores/settings.ts +15 -0
  103. package/shared/types/unified/stream.ts +7 -0
  104. package/shared/utils/interactive-input.ts +71 -0
  105. package/shared/utils/logger.ts +6 -0
  106. package/dist/assets/main-BkCc3WEB.js +0 -481
  107. package/dist/assets/main-CWDwET4x.css +0 -1
@@ -86,6 +86,16 @@ export const sessionQueries = {
86
86
  `).run(engine, provider, modelId, modelName, id);
87
87
  },
88
88
 
89
+ /** Persist the active profile for a session (NULL clears it). */
90
+ updateProfile(id: string, profileId: number | null): void {
91
+ const db = getDatabase();
92
+ db.prepare(`
93
+ UPDATE chat_sessions
94
+ SET profile_id = ?
95
+ WHERE id = ?
96
+ `).run(profileId, id);
97
+ },
98
+
89
99
  updateAccountId(id: string, accountId: number | null): void {
90
100
  const db = getDatabase();
91
101
  db.prepare(`
@@ -497,6 +507,17 @@ export const sessionQueries = {
497
507
  `).run(userId, sessionId);
498
508
  },
499
509
 
510
+ /**
511
+ * Mark every unread session in a project as read for a specific user
512
+ */
513
+ markAllRead(userId: string, projectId: string): void {
514
+ const db = getDatabase();
515
+ db.prepare(`
516
+ DELETE FROM user_unread_sessions
517
+ WHERE user_id = ? AND project_id = ?
518
+ `).run(userId, projectId);
519
+ },
520
+
500
521
  /**
501
522
  * Get all unread session IDs for a user within a project
502
523
  * Returns array of { sessionId, projectId }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Subagent Queries
3
+ *
4
+ * CRUD for user-managed custom Subagents (Settings → Subagents). Subagents are
5
+ * Skills-shaped (a Markdown document with frontmatter) plus a per-engine tool
6
+ * allowlist and per-engine model override (stored as JSON maps keyed by
7
+ * EngineType). The `subagents` table holds metadata + the enable toggle; the
8
+ * document body lives on disk under `{clopenDir}/subagents/<slug>.md` (see
9
+ * `backend/subagents/store.ts`).
10
+ */
11
+
12
+ import { getDatabase } from '../index';
13
+
14
+ export type SubagentSource = 'custom' | 'imported';
15
+
16
+ export interface SubagentRow {
17
+ id: number;
18
+ slug: string;
19
+ name: string;
20
+ description: string;
21
+ /** JSON map of EngineType → comma-separated tool allowlist ({} = all tools). */
22
+ tools_by_engine: string;
23
+ /** JSON map of EngineType → model id ({} = inherit everywhere). */
24
+ model_by_engine: string;
25
+ source: SubagentSource;
26
+ is_enabled: number;
27
+ created_at: string;
28
+ }
29
+
30
+ export interface SubagentInput {
31
+ slug: string;
32
+ name: string;
33
+ description: string;
34
+ /** JSON string: EngineType → comma-separated tool allowlist. */
35
+ toolsByEngine?: string;
36
+ /** JSON string: EngineType → model id. */
37
+ modelByEngine?: string;
38
+ source?: SubagentSource;
39
+ }
40
+
41
+ export const subagentQueries = {
42
+ getAll(): SubagentRow[] {
43
+ return getDatabase().prepare(`SELECT * FROM subagents ORDER BY created_at ASC`).all() as SubagentRow[];
44
+ },
45
+
46
+ getEnabled(): SubagentRow[] {
47
+ return getDatabase().prepare(`SELECT * FROM subagents WHERE is_enabled = 1 ORDER BY created_at ASC`).all() as SubagentRow[];
48
+ },
49
+
50
+ getById(id: number): SubagentRow | null {
51
+ return getDatabase().prepare(`SELECT * FROM subagents WHERE id = ?`).get(id) as SubagentRow | null;
52
+ },
53
+
54
+ getBySlug(slug: string): SubagentRow | null {
55
+ return getDatabase().prepare(`SELECT * FROM subagents WHERE slug = ?`).get(slug) as SubagentRow | null;
56
+ },
57
+
58
+ insert(input: SubagentInput): SubagentRow {
59
+ const result = getDatabase().prepare(
60
+ `INSERT INTO subagents (slug, name, description, tools_by_engine, model_by_engine, source)
61
+ VALUES (?, ?, ?, ?, ?, ?)`
62
+ ).run(
63
+ input.slug,
64
+ input.name,
65
+ input.description,
66
+ input.toolsByEngine ?? '{}',
67
+ input.modelByEngine ?? '{}',
68
+ input.source ?? 'custom'
69
+ ) as { lastInsertRowid: number | bigint };
70
+ return this.getById(Number(result.lastInsertRowid))!;
71
+ },
72
+
73
+ updateMeta(
74
+ id: number,
75
+ name: string,
76
+ description: string,
77
+ toolsByEngine: string,
78
+ modelByEngine: string
79
+ ): void {
80
+ getDatabase().prepare(
81
+ `UPDATE subagents SET name = ?, description = ?, tools_by_engine = ?, model_by_engine = ? WHERE id = ?`
82
+ ).run(name, description, toolsByEngine, modelByEngine, id);
83
+ },
84
+
85
+ setEnabled(id: number, enabled: boolean): void {
86
+ getDatabase().prepare(`UPDATE subagents SET is_enabled = ? WHERE id = ?`).run(enabled ? 1 : 0, id);
87
+ },
88
+
89
+ remove(id: number): void {
90
+ getDatabase().prepare(`DELETE FROM subagents WHERE id = ?`).run(id);
91
+ }
92
+ };
@@ -28,6 +28,9 @@ import { setupEnvironmentOnce, getEngineEnv } from './environment';
28
28
  import { handleStreamError } from './error-handler';
29
29
  import { getEnabledMcpServers, getAllowedMcpTools } from '../../../mcp';
30
30
  import { syncSkills } from '$backend/skills';
31
+ import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
32
+ import { artifactFilter } from '$backend/profiles';
33
+ import { resolvePermissionsFromDb, isToolAllowed, syncPermissions } from '$backend/permissions';
31
34
  import type { AIEngine, EngineQueryOptions } from '../../types';
32
35
  import type { EngineModel } from '$shared/types/unified';
33
36
  import { CLAUDE_CODE_MODELS } from './models';
@@ -99,13 +102,28 @@ export class ClaudeCodeEngine implements AIEngine {
99
102
  const resolvedProjectPath = resolveOsPath(projectPath);
100
103
 
101
104
  try {
105
+ // Active Profile for this stream (resolved in stream-manager). Scopes the
106
+ // materialized artifact set + MCP connectors to the profile's bundle.
107
+ const profileId = options.mcpContext?.profileId;
108
+ const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
109
+
102
110
  // Materialize enabled skills into Claude's native skills dir before the
103
111
  // session starts so the SDK picks them up via settingSources.
104
- await syncSkills('claude');
112
+ await syncSkills('claude', profileId);
113
+ // Commands, Subagents, and global Instructions share the same trigger.
114
+ await syncEngineArtifacts('claude', profileId);
115
+ // Write the resolved allow/deny into the isolated settings.json (honesty
116
+ // layer — the runtime hook below is the authoritative enforcement).
117
+ await syncPermissions('claude');
118
+
119
+ // Resolve the effective permission policy once per stream; the canUseTool
120
+ // hook consults it to actually block denied tools (Clopen otherwise
121
+ // auto-allows everything, so this hook is where deny gets its teeth).
122
+ const permissions = resolvePermissionsFromDb('claude-code', options.mcpContext?.projectId, profileId);
105
123
 
106
124
  // Get custom MCP servers and allowed tools
107
125
  // Pass mcpContext so tool handlers are bound to the correct project
108
- const mcpServers = getEnabledMcpServers(options.mcpContext);
126
+ const mcpServers = getEnabledMcpServers(options.mcpContext, mcpProfileFilter);
109
127
  const allowedMcpTools = getAllowedMcpTools();
110
128
 
111
129
  debug.log('mcp', '📦 Loading custom MCP servers...');
@@ -157,7 +175,13 @@ export class ClaudeCodeEngine implements AIEngine {
157
175
  });
158
176
  });
159
177
  }
160
- // Auto-allow all other tools
178
+ // Enforce the resolved permission policy: deny blocks the tool, an
179
+ // allowlist (when set) blocks anything not on it. Everything else is
180
+ // auto-allowed as before.
181
+ if (!isToolAllowed(permissions, _toolName)) {
182
+ debug.log('permissions', `⛔ Blocked tool "${_toolName}" (Clopen permission policy)`);
183
+ return { behavior: 'deny' as const, message: `Blocked by Clopen permission policy: ${_toolName}` };
184
+ }
161
185
  return { behavior: 'allow' as const, updatedInput: input };
162
186
  },
163
187
  ...(modelId && { model: modelId }),
@@ -28,7 +28,9 @@ import { resolveOsPath } from '$backend/utils/paths';
28
28
  import { resolveBinary } from '$backend/utils/cli';
29
29
  import { getCleanSpawnEnv } from '$backend/utils/index.js';
30
30
  import { getCodexMcpConfig } from '../../../mcp';
31
+ import { artifactFilter } from '$backend/profiles';
31
32
  import { syncSkills } from '$backend/skills';
33
+ import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
32
34
  import { CODEX_MODELS } from './models';
33
35
  import { debug } from '$shared/utils/logger';
34
36
  import { handleStreamError, buildTurnError } from './error-handler';
@@ -62,6 +64,13 @@ export class CodexEngine implements AIEngine {
62
64
  private activeController: AbortController | null = null;
63
65
  /** Account ID currently baked into `this.codex`. Same trade-off as Copilot. */
64
66
  private currentAccountId: number | null = null;
67
+ /**
68
+ * Profile connector-filter signature baked into `this.codex`. Codex takes its
69
+ * MCP set at construction, so scoping connectors to a Profile means rebuilding
70
+ * the client when the filter changes (same trade-off as an account switch).
71
+ * `'*'` = unfiltered (no profile constraint). `null` = not initialized.
72
+ */
73
+ private currentMcpFilterKey: string | null = null;
65
74
 
66
75
  get isInitialized(): boolean {
67
76
  return this._isInitialized;
@@ -71,8 +80,9 @@ export class CodexEngine implements AIEngine {
71
80
  return this.activeController !== null;
72
81
  }
73
82
 
74
- async initialize(accountId?: number): Promise<void> {
75
- if (this._isInitialized && (accountId == null || accountId === this.currentAccountId)) {
83
+ async initialize(accountId?: number, mcpProfileFilter?: Set<string>): Promise<void> {
84
+ const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
85
+ if (this._isInitialized && (accountId == null || accountId === this.currentAccountId) && mcpKey === this.currentMcpFilterKey) {
76
86
  return;
77
87
  }
78
88
 
@@ -94,7 +104,7 @@ export class CodexEngine implements AIEngine {
94
104
  applyAccountAuth(account);
95
105
 
96
106
  const codexBinary = resolveBinary('codex');
97
- const mcpConfig = getCodexMcpConfig();
107
+ const mcpConfig = getCodexMcpConfig(mcpProfileFilter);
98
108
 
99
109
  // Codex SDK takes config at construction. We pass `show_raw_agent_reasoning`
100
110
  // (so the SDK forwards reasoning text events) and forward the Clopen MCP
@@ -119,14 +129,16 @@ export class CodexEngine implements AIEngine {
119
129
  },
120
130
  });
121
131
  this.currentAccountId = account.id;
132
+ this.currentMcpFilterKey = mcpKey;
122
133
  this._isInitialized = true;
123
- debug.log('engine', `Codex engine initialized (account ${account.id}, mode=${credential.kind})`);
134
+ debug.log('engine', `Codex engine initialized (account ${account.id}, mode=${credential.kind}, mcpFilter=${mcpKey})`);
124
135
  }
125
136
 
126
137
  async dispose(): Promise<void> {
127
138
  await this.cancel();
128
139
  this.codex = null;
129
140
  this.currentAccountId = null;
141
+ this.currentMcpFilterKey = null;
130
142
  this._isInitialized = false;
131
143
  debug.log('engine', 'Codex engine disposed');
132
144
  }
@@ -139,18 +151,28 @@ export class CodexEngine implements AIEngine {
139
151
  async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
140
152
  const { projectPath, prompt, resume, modelId, abortController, accountId } = options;
141
153
 
154
+ // Active Profile for this stream — scopes the materialized artifact set AND
155
+ // (below) the MCP connector set baked into the Codex client.
156
+ const profileId = options.mcpContext?.profileId;
142
157
  // Refresh the synthetic skills preamble in CODEX_HOME before the turn.
143
- await syncSkills('codex');
144
-
145
- // Per-stream account override — same shape as Copilot. The SDK takes
146
- // the apiKey at construction time, so an account switch requires
147
- // re-creating the Codex client.
148
- if (this._isInitialized && accountId != null && accountId !== this.currentAccountId) {
149
- debug.log('engine', `Codex account switch ${this.currentAccountId} → ${accountId}; re-initialising`);
158
+ await syncSkills('codex', profileId);
159
+ await syncEngineArtifacts('codex', profileId);
160
+
161
+ // Per-stream account/profile override — the SDK bakes both the apiKey and the
162
+ // MCP set at construction, so a change in either requires re-creating the
163
+ // client. The connector filter narrows MCP to the Profile's set (like Claude/
164
+ // Qwen/Copilot do per stream); `undefined` = unfiltered → no change for the
165
+ // common no-profile path.
166
+ const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
167
+ const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
168
+ const accountChanged = this._isInitialized && accountId != null && accountId !== this.currentAccountId;
169
+ const mcpChanged = this._isInitialized && mcpKey !== this.currentMcpFilterKey;
170
+ if (accountChanged || mcpChanged) {
171
+ debug.log('engine', `Codex re-initialising (accountChanged=${accountChanged}, mcpChanged=${mcpChanged})`);
150
172
  await this.dispose();
151
173
  }
152
174
  if (!this._isInitialized || !this.codex) {
153
- await this.initialize(accountId);
175
+ await this.initialize(accountId, mcpProfileFilter);
154
176
  }
155
177
  if (!this.codex) {
156
178
  throw new Error('Codex client unavailable.');
@@ -207,7 +229,11 @@ export class CodexEngine implements AIEngine {
207
229
 
208
230
  this.activeThread = thread;
209
231
 
210
- const input = await buildCodexInput(prompt);
232
+ // Prompt-scoped engine: advertise the profile-scoped Skills/Commands/
233
+ // Subagents PER-SESSION via the prompt (not the shared global AGENTS.md /
234
+ // persistent client) so the active Profile scopes them correctly.
235
+ const artifactsContext = buildArtifactsPromptContext(profileId);
236
+ const input = await buildCodexInput(prompt, artifactsContext || undefined);
211
237
  const { events } = await thread.runStreamed(input, {
212
238
  signal: this.activeController.signal,
213
239
  });
@@ -357,9 +383,15 @@ export class CodexEngine implements AIEngine {
357
383
  // Helpers
358
384
  // ============================================================================
359
385
 
360
- async function buildCodexInput(prompt: EngineQueryOptions['prompt']): Promise<CodexInput> {
386
+ async function buildCodexInput(prompt: EngineQueryOptions['prompt'], prefixText?: string): Promise<CodexInput> {
361
387
  const items: Array<{ type: 'text'; text: string } | { type: 'local_image'; path: string }> = [];
362
388
 
389
+ // Optional per-session context (e.g. the profile-scoped skills preamble),
390
+ // prepended so it leads the turn.
391
+ if (prefixText) {
392
+ items.push({ type: 'text', text: prefixText });
393
+ }
394
+
363
395
  for (const block of prompt.content) {
364
396
  if (block.type === 'text') {
365
397
  items.push({ type: 'text', text: block.text });
@@ -13,6 +13,8 @@ import type {
13
13
  ResumeSessionConfig,
14
14
  SessionEvent,
15
15
  ModelInfo,
16
+ PermissionRequest,
17
+ PermissionRequestResult,
16
18
  } from '@github/copilot-sdk';
17
19
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
18
20
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
@@ -21,7 +23,10 @@ import { engineQueries } from '$backend/database/queries/engine-queries';
21
23
  import { resolveOsPath, getEngineUserConfigDir } from '$backend/utils/paths';
22
24
  import { debug } from '$shared/utils/logger';
23
25
  import { getCopilotMcpConfig } from '../../../mcp';
26
+ import { artifactFilter } from '$backend/profiles';
24
27
  import { syncSkills } from '$backend/skills';
28
+ import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
29
+ import { resolvePermissionsFromDb, isToolAllowed, type ResolvedPermissions } from '$backend/permissions';
25
30
  import { handleStreamError, buildSessionError } from './error-handler';
26
31
  import { fetchCopilotModels } from './models';
27
32
 
@@ -30,6 +35,33 @@ import { fetchCopilotModels } from './models';
30
35
  // `onUserInputRequest`'s return type is exactly that shape — derive
31
36
  // it from the SessionConfig field so we don't drift from the SDK.
32
37
  type UserInputResponse = Awaited<ReturnType<NonNullable<SessionConfig['onUserInputRequest']>>>;
38
+
39
+ /**
40
+ * Map a Copilot permission request to the token the permission policy matches on.
41
+ * MCP / custom tools carry a `toolName`; everything else is matched by its
42
+ * operation `kind` (`shell` / `write` / `read` / `url` / `memory` / …), which is
43
+ * why the Copilot builtin catalog lists kinds rather than tool names.
44
+ */
45
+ function copilotPermissionToken(request: PermissionRequest): string {
46
+ const named = (request as { toolName?: string }).toolName;
47
+ return named && named.trim() ? named : request.kind;
48
+ }
49
+
50
+ /**
51
+ * Enforce the resolved permission policy for one Copilot request. Returns a
52
+ * reject decision for blocked tools, or null to fall through to auto-approve.
53
+ */
54
+ function enforceCopilotPermission(
55
+ permissions: ResolvedPermissions,
56
+ request: PermissionRequest
57
+ ): PermissionRequestResult | null {
58
+ const token = copilotPermissionToken(request);
59
+ if (!isToolAllowed(permissions, token)) {
60
+ debug.log('permissions', `⛔ Blocked tool "${token}" (Clopen permission policy)`);
61
+ return { kind: 'reject', feedback: `Blocked by Clopen permission policy: ${token}` };
62
+ }
63
+ return null;
64
+ }
33
65
  import {
34
66
  createStreamConverterState,
35
67
  convertSessionStart,
@@ -194,8 +226,26 @@ export class CopilotEngine implements AIEngine {
194
226
 
195
227
  this.activeController = abortController || new AbortController();
196
228
 
229
+ // Active Profile for this stream — scopes artifacts + connectors.
230
+ const profileId = options.mcpContext?.profileId;
231
+ const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
232
+
197
233
  // Mirror enabled skills into Copilot's native skills dir before the turn.
198
- await syncSkills('copilot');
234
+ await syncSkills('copilot', profileId);
235
+ await syncEngineArtifacts('copilot', profileId);
236
+
237
+ // Copilot's skills dir (`~/.copilot/skills`) is SHARED across sessions and
238
+ // read by a PERSISTENT runtime, and its Commands/Subagents ride a synthetic
239
+ // global block — none can reliably scope to THIS session's Profile. Inject
240
+ // the profile-scoped Skills/Commands/Subagents preamble into the prompt as
241
+ // the authoritative per-session signal (synthetic commands/subagents are
242
+ // stripped from the global file; the native skill mirror still loads the
243
+ // filtered folders).
244
+ const artifactsContext = buildArtifactsPromptContext(profileId);
245
+
246
+ // Resolve the permission policy once per stream; onPermissionRequest below
247
+ // enforces it (Copilot otherwise approves every tool via approveAll).
248
+ const permissions = resolvePermissionsFromDb('copilot', options.mcpContext?.projectId, profileId);
199
249
 
200
250
  const resolvedProjectPath = resolveOsPath(projectPath);
201
251
  const state = createStreamConverterState('', modelId);
@@ -249,10 +299,11 @@ export class CopilotEngine implements AIEngine {
249
299
  this.activeController.signal.addEventListener('abort', onAbort, { once: true });
250
300
 
251
301
  try {
252
- const mcpConfig = getCopilotMcpConfig();
302
+ const mcpConfig = getCopilotMcpConfig(mcpProfileFilter);
253
303
 
254
304
  const baseConfig: ResumeSessionConfig = {
255
- onPermissionRequest: approveAll,
305
+ onPermissionRequest: (request, invocation) =>
306
+ enforceCopilotPermission(permissions, request) ?? approveAll(request, invocation),
256
307
  // Enables the agent's `ask_user` tool. Without this callback the
257
308
  // SDK reports `requestUserInput: false` to the server and the
258
309
  // tool is not exposed to the model, so the AskUserQuestion
@@ -345,7 +396,10 @@ export class CopilotEngine implements AIEngine {
345
396
  state.sessionId = session.sessionId;
346
397
 
347
398
  // Send the prompt — fire-and-forget; events arrive via the queue.
348
- const sendPromise = session.send({ prompt: extractPromptText(prompt) }).catch(error => {
399
+ const promptText = artifactsContext
400
+ ? `${artifactsContext}\n\n${extractPromptText(prompt)}`
401
+ : extractPromptText(prompt);
402
+ const sendPromise = session.send({ prompt: promptText }).catch(error => {
349
403
  debug.error('engine', 'Copilot session.send error:', error);
350
404
  pushEvent({
351
405
  type: 'session.error',
@@ -42,6 +42,7 @@ import type {
42
42
  ReadMcpResourceInput,
43
43
  TodoWriteInput,
44
44
  PatchInput,
45
+ AgentInput,
45
46
  } from '$shared/types/unified';
46
47
 
47
48
  // ============================================================
@@ -87,7 +88,7 @@ type NormalizedToolInput =
87
88
  | GlobInput | GrepInput | WebFetchInput | WebSearchInput
88
89
  | AskUserQuestionInput | TodoWriteInput
89
90
  | ListMcpResourcesInput | ReadMcpResourceInput
90
- | PatchInput
91
+ | PatchInput | AgentInput
91
92
  | Record<string, unknown>;
92
93
 
93
94
  // ============================================================
@@ -103,7 +104,7 @@ type NormalizedToolInput =
103
104
  *
104
105
  * @see https://opencode.ai/docs/tools
105
106
  */
106
- const TOOL_NAME_MAP: Record<string, string> = {
107
+ export const TOOL_NAME_MAP: Record<string, string> = {
107
108
  // File operations
108
109
  'bash': 'Bash',
109
110
  'view': 'Read',
@@ -340,6 +341,24 @@ function normalizePatchInput(raw: OCToolInput): PatchInput {
340
341
  return { filePath, patch: patchBody };
341
342
  }
342
343
 
344
+ /**
345
+ * OpenCode's `task` tool dispatches a named sub-agent. Some providers (e.g.
346
+ * GLM/z.ai via opencode) emit already-snake_case args like `subagent_type`.
347
+ * Map those to the unified `AgentInput` so the Agent tool component renders
348
+ * consistently with Claude's `Task` and Copilot's `task`.
349
+ */
350
+ function normalizeAgentInput(raw: OCToolInput): AgentInput {
351
+ return {
352
+ prompt: str(raw, 'prompt', 'prompt') || str(raw, 'task', 'task') || str(raw, 'instruction', 'instruction'),
353
+ description: str(raw, 'description', 'description'),
354
+ subagentType: optStr(raw, 'subagent_type', 'subagentType')
355
+ ?? optStr(raw, 'agent_type', 'agentType')
356
+ ?? optStr(raw, 'agent', 'agent')
357
+ ?? optStr(raw, 'name', 'name')
358
+ ?? 'general-purpose',
359
+ };
360
+ }
361
+
343
362
  // ============================================================
344
363
  // Normalizer Dispatcher
345
364
  // ============================================================
@@ -368,6 +387,7 @@ function normalizeToolInput(claudeToolName: string, raw: OCToolInput): Normalize
368
387
  case 'ReadMcpResource': return normalizeReadMcpResourceInput(raw);
369
388
  case 'TodoWrite': return normalizeTodoWriteInput(raw);
370
389
  case 'Patch': return normalizePatchInput(raw);
390
+ case 'Agent': return normalizeAgentInput(raw);
371
391
  default: {
372
392
  // Unknown tool: generic camelCase → snake_case key normalization
373
393
  const normalized: Record<string, string | number | boolean> = {};