@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.
- package/README.md +10 -7
- package/backend/artifacts/detect.ts +129 -0
- package/backend/artifacts/engine-map.ts +53 -0
- package/backend/artifacts/frontmatter.ts +68 -0
- package/backend/artifacts/generate.ts +105 -0
- package/backend/artifacts/index.ts +34 -0
- package/backend/artifacts/markers.ts +76 -0
- package/backend/artifacts/matrix.ts +247 -0
- package/backend/artifacts/slug.ts +35 -0
- package/backend/artifacts/sync.ts +130 -0
- package/backend/artifacts/types.ts +152 -0
- package/backend/auth/permissions.ts +51 -1
- package/backend/chat/stream-manager.ts +14 -1
- package/backend/commands/detect.ts +25 -0
- package/backend/commands/index.ts +9 -0
- package/backend/commands/service.ts +178 -0
- package/backend/commands/store.ts +45 -0
- package/backend/commands/sync.ts +94 -0
- package/backend/database/migrations/045_create_commands_table.ts +28 -0
- package/backend/database/migrations/046_create_subagents_table.ts +29 -0
- package/backend/database/migrations/047_create_instructions_table.ts +29 -0
- package/backend/database/migrations/048_add_mcp_tool_overrides.ts +23 -0
- package/backend/database/migrations/049_create_permission_sets_table.ts +50 -0
- package/backend/database/migrations/050_create_profiles_tables.ts +57 -0
- package/backend/database/migrations/051_add_profile_to_sessions.ts +20 -0
- package/backend/database/migrations/052_add_default_profile_to_projects.ts +20 -0
- package/backend/database/migrations/053_add_profile_to_permission_sets.ts +37 -0
- package/backend/database/migrations/054_drop_subagent_agent_type.ts +20 -0
- package/backend/database/migrations/055_artifact_model_tools_per_engine.ts +43 -0
- package/backend/database/migrations/index.ts +77 -0
- package/backend/database/queries/command-queries.ts +82 -0
- package/backend/database/queries/index.ts +12 -2
- package/backend/database/queries/instruction-queries.ts +62 -0
- package/backend/database/queries/mcp-server-queries.ts +25 -0
- package/backend/database/queries/permission-set-queries.ts +155 -0
- package/backend/database/queries/profile-queries.ts +118 -0
- package/backend/database/queries/project-queries.ts +14 -0
- package/backend/database/queries/session-queries.ts +21 -0
- package/backend/database/queries/subagent-queries.ts +92 -0
- package/backend/engine/adapters/claude/stream.ts +27 -3
- package/backend/engine/adapters/codex/stream.ts +46 -14
- package/backend/engine/adapters/copilot/stream.ts +58 -4
- package/backend/engine/adapters/opencode/message-converter.ts +22 -2
- package/backend/engine/adapters/opencode/server.ts +166 -210
- package/backend/engine/adapters/opencode/stream.ts +150 -24
- package/backend/engine/adapters/qwen/stream.ts +23 -3
- package/backend/engine/artifact-sync.ts +51 -0
- package/backend/engine/types.ts +6 -0
- package/backend/instructions/index.ts +8 -0
- package/backend/instructions/service.ts +63 -0
- package/backend/instructions/sync.ts +56 -0
- package/backend/mcp/external/config.ts +42 -20
- package/backend/mcp/external/proxy.ts +89 -5
- package/backend/mcp/external/tools.ts +88 -0
- package/backend/mcp/index.ts +38 -15
- package/backend/mcp/internal/config.ts +48 -11
- package/backend/mcp/internal/remote-server.ts +9 -1
- package/backend/permissions/index.ts +27 -0
- package/backend/permissions/materialize.ts +96 -0
- package/backend/permissions/resolve.test.ts +162 -0
- package/backend/permissions/resolve.ts +106 -0
- package/backend/permissions/service.ts +167 -0
- package/backend/profiles/index.ts +10 -0
- package/backend/profiles/service.ts +169 -0
- package/backend/project/status-manager.ts +7 -25
- package/backend/skills/index.ts +1 -1
- package/backend/skills/sync.ts +88 -128
- package/backend/subagents/detect.ts +23 -0
- package/backend/subagents/index.ts +10 -0
- package/backend/subagents/service.ts +166 -0
- package/backend/subagents/store.ts +44 -0
- package/backend/subagents/sync.ts +144 -0
- package/backend/utils/static-curl.ts +12 -54
- package/backend/ws/artifacts/generate.ts +51 -0
- package/backend/ws/artifacts/index.ts +8 -0
- package/backend/ws/chat/stream.ts +33 -2
- package/backend/ws/commands/crud.ts +157 -0
- package/backend/ws/commands/index.ts +8 -0
- package/backend/ws/git/branch.ts +4 -2
- package/backend/ws/git/remote.ts +21 -11
- package/backend/ws/index.ts +17 -1
- package/backend/ws/instructions/crud.ts +53 -0
- package/backend/ws/instructions/index.ts +8 -0
- package/backend/ws/mcp/crud.ts +7 -1
- package/backend/ws/mcp/index.ts +4 -1
- package/backend/ws/mcp/tools.ts +112 -0
- package/backend/ws/permissions/crud.ts +72 -0
- package/backend/ws/permissions/index.ts +8 -0
- package/backend/ws/profiles/crud.ts +149 -0
- package/backend/ws/profiles/index.ts +9 -0
- package/backend/ws/sessions/crud.ts +12 -0
- package/backend/ws/subagents/crud.ts +136 -0
- package/backend/ws/subagents/index.ts +8 -0
- package/dist/assets/{index-jGo0X72U.js → index-C3kp8wpM.js} +1 -1
- package/dist/assets/{index-B_F_OgoC.js → index-cVUk7das.js} +1 -1
- package/dist/assets/main-CuCxUeqZ.js +533 -0
- package/dist/assets/main-D4pdkiQK.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +24 -24
- package/shared/constants/engine-tools.ts +56 -0
- package/shared/types/database/schema.ts +2 -0
- package/shared/types/stores/settings.ts +15 -0
- package/shared/types/unified/stream.ts +7 -0
- package/shared/utils/interactive-input.ts +71 -0
- package/shared/utils/logger.ts +6 -0
- package/dist/assets/main-BkCc3WEB.js +0 -481
- package/dist/assets/main-CWDwET4x.css +0 -1
|
@@ -38,13 +38,62 @@ import {
|
|
|
38
38
|
convertReasoningStreamStop,
|
|
39
39
|
convertSubtaskToolUseOnly,
|
|
40
40
|
getToolInput,
|
|
41
|
+
mapToolName,
|
|
42
|
+
TOOL_NAME_MAP,
|
|
41
43
|
} from './message-converter';
|
|
42
|
-
import { ensureClient, getClient, getServerUrl } from './server';
|
|
44
|
+
import { ensureClient, ensureServer, hashConfig, getClient, getServerUrl, type ServerInstance } from './server';
|
|
43
45
|
import { syncSkills } from '$backend/skills';
|
|
46
|
+
import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
|
|
47
|
+
import { artifactFilter } from '$backend/profiles';
|
|
48
|
+
import { buildOpenCodeInlineAgents } from '$backend/subagents';
|
|
49
|
+
import { getOpenCodeProfileDisabledToolIds } from '$backend/mcp';
|
|
50
|
+
import { resolvePermissionsFromDb, matchesAny, type ResolvedPermissions } from '$backend/permissions';
|
|
44
51
|
import { formatSessionError, handleStreamError } from './error-handler';
|
|
45
52
|
import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
46
53
|
import { debug } from '$shared/utils/logger';
|
|
47
54
|
|
|
55
|
+
/**
|
|
56
|
+
* Whether a permission policy blocks an OpenCode tool. Matched under BOTH the
|
|
57
|
+
* raw OpenCode tool id (e.g. `bash`) and its canonical `mapToolName` form (e.g.
|
|
58
|
+
* `Bash`, `mcp__server__tool`), so a rule written in either naming takes effect.
|
|
59
|
+
* Deny wins; a non-empty allowlist blocks anything not matched under either name.
|
|
60
|
+
*/
|
|
61
|
+
function isOpenCodeToolBlocked(permissions: ResolvedPermissions, rawTool: string): boolean {
|
|
62
|
+
const names = Array.from(new Set([rawTool, mapToolName(rawTool)].filter(Boolean)));
|
|
63
|
+
if (names.some(n => matchesAny(permissions.deny, n))) return true;
|
|
64
|
+
if (permissions.allow.length > 0 && !names.some(n => matchesAny(permissions.allow, n))) return true;
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Per-prompt tool disable map (`{ toolId: false }`) enforcing the resolved
|
|
70
|
+
* permission policy UP FRONT — OpenCode's `permission.asked` event only fires for
|
|
71
|
+
* a subset of built-in tools (edit/bash/webfetch/…), never for read-only or MCP
|
|
72
|
+
* tools, so a deny on those would otherwise be silently ignored (this is exactly
|
|
73
|
+
* why a profile's MCP-tool deny worked on Claude's `canUseTool` but not here).
|
|
74
|
+
* Passing the blocked tools as disabled removes them from the model's toolset
|
|
75
|
+
* entirely — the OpenCode analogue of Claude/Qwen `excludeTools`.
|
|
76
|
+
*
|
|
77
|
+
* Coverage: every known built-in tool id plus each EXACT `mcp__<ns>__<tool>` deny
|
|
78
|
+
* (mapped to OpenCode's `<ns>_<tool>` id). Wildcard MCP denies and allowlist-vs-
|
|
79
|
+
* MCP remain best-effort (the full live MCP tool list isn't known synchronously
|
|
80
|
+
* here) and still fall back to the bridge / permission.asked path.
|
|
81
|
+
*/
|
|
82
|
+
function buildOpenCodeToolDisableMap(permissions: ResolvedPermissions): Record<string, boolean> {
|
|
83
|
+
const disable: Record<string, boolean> = {};
|
|
84
|
+
// Built-in tools: test every OpenCode tool id we know the canonical name for.
|
|
85
|
+
for (const rawTool of Object.keys(TOOL_NAME_MAP)) {
|
|
86
|
+
if (isOpenCodeToolBlocked(permissions, rawTool)) disable[rawTool] = false;
|
|
87
|
+
}
|
|
88
|
+
// Exact MCP-tool denies → OpenCode's underscore-joined id (`<ns>_<tool>`).
|
|
89
|
+
for (const pattern of permissions.deny) {
|
|
90
|
+
if (pattern.endsWith('*')) continue;
|
|
91
|
+
const m = /^mcp__(.+?)__(.+)$/.exec(pattern);
|
|
92
|
+
if (m) disable[`${m[1]}_${m[2]}`] = false;
|
|
93
|
+
}
|
|
94
|
+
return disable;
|
|
95
|
+
}
|
|
96
|
+
|
|
48
97
|
// ============================================================================
|
|
49
98
|
// OpenCode Engine (per-project instance)
|
|
50
99
|
// ============================================================================
|
|
@@ -56,6 +105,8 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
56
105
|
private activeAbortController: AbortController | null = null;
|
|
57
106
|
private activeSessionId: string | null = null;
|
|
58
107
|
private activeProjectPath: string | null = null;
|
|
108
|
+
/** The pooled per-Profile server this instance's active stream is bound to. */
|
|
109
|
+
private activeServer: ServerInstance | null = null;
|
|
59
110
|
/** Pending question requests keyed by tool callID → { requestId, questions } */
|
|
60
111
|
private pendingQuestions = new Map<string, { requestId: string; questions: Array<{ question: string }> }>();
|
|
61
112
|
|
|
@@ -86,6 +137,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
86
137
|
async dispose(): Promise<void> {
|
|
87
138
|
await this.cancel();
|
|
88
139
|
this.pendingQuestions.clear();
|
|
140
|
+
this.activeServer = null;
|
|
89
141
|
this._isInitialized = false;
|
|
90
142
|
debug.log('engine', 'Open Code engine instance disposed');
|
|
91
143
|
}
|
|
@@ -106,8 +158,6 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
106
158
|
* This ensures no events are missed between sending and subscribing.
|
|
107
159
|
*/
|
|
108
160
|
async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
|
|
109
|
-
const client = await ensureClient();
|
|
110
|
-
|
|
111
161
|
const {
|
|
112
162
|
projectPath,
|
|
113
163
|
prompt,
|
|
@@ -121,8 +171,38 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
121
171
|
this._isActive = true;
|
|
122
172
|
this.activeProjectPath = projectPath;
|
|
123
173
|
|
|
124
|
-
//
|
|
125
|
-
|
|
174
|
+
// Active Profile for this stream. Skills go into the prompt and commands
|
|
175
|
+
// into shared dirs; materialize those first, then bind to the per-Profile
|
|
176
|
+
// server that bakes the rest.
|
|
177
|
+
const profileId = options.mcpContext?.profileId;
|
|
178
|
+
await syncSkills('opencode', profileId);
|
|
179
|
+
await syncEngineArtifacts('opencode', profileId);
|
|
180
|
+
|
|
181
|
+
// Bind this stream to the pooled server whose baked config matches the
|
|
182
|
+
// Profile: MCP narrowed to the Profile's connectors (drops excluded EXTERNAL
|
|
183
|
+
// servers) plus the Profile's subagents INLINE — Open Code caches its agent
|
|
184
|
+
// registry from a shared dir at boot, so an isolated server is the only way
|
|
185
|
+
// to scope it. The signature keys the pool: identical scoping reuses one
|
|
186
|
+
// server, different Profiles get isolated servers, concurrently.
|
|
187
|
+
const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
|
|
188
|
+
const subagentFilter = artifactFilter(profileId, 'subagent') ?? undefined;
|
|
189
|
+
const inlineAgents = await buildOpenCodeInlineAgents(profileId);
|
|
190
|
+
// Key = filtered MCP set + subagent set + a hash of the agents' CONTENT, so
|
|
191
|
+
// editing a subagent's prompt/model (same set) also spawns a fresh server
|
|
192
|
+
// rather than reusing a stale one. `subagentFilter` is subsumed by the
|
|
193
|
+
// content hash but kept for a readable key.
|
|
194
|
+
const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
|
|
195
|
+
const agentKey = subagentFilter ? [...subagentFilter].sort().join(',') : '*';
|
|
196
|
+
const serverKey = `mcp:${mcpKey}|agents:${agentKey}:${hashConfig(JSON.stringify(inlineAgents))}`;
|
|
197
|
+
const server = await ensureServer(serverKey, { mcpProfileFilter, inlineAgents });
|
|
198
|
+
this.activeServer = server;
|
|
199
|
+
const client = server.client;
|
|
200
|
+
|
|
201
|
+
// Resolve the permission policy once per stream; the permission event
|
|
202
|
+
// handler enforces it (OpenCode otherwise auto-approves every tool). Tool
|
|
203
|
+
// identity is matched in the canonical `mapToolName` form so a rule like
|
|
204
|
+
// `mcp__server__tool` works across Claude and OpenCode alike.
|
|
205
|
+
const permissions = resolvePermissionsFromDb('opencode', options.mcpContext?.projectId, profileId);
|
|
126
206
|
|
|
127
207
|
debug.log('chat', 'Open Code - Stream Query');
|
|
128
208
|
debug.log('chat', { prompt });
|
|
@@ -130,6 +210,16 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
130
210
|
try {
|
|
131
211
|
const promptParts = this.extractPromptParts(prompt);
|
|
132
212
|
|
|
213
|
+
// Prompt-scoped engine: the persistent server reads Skills/Commands/
|
|
214
|
+
// Subagents through shared channels it doesn't reliably re-read per turn,
|
|
215
|
+
// so advertise the profile-scoped set PER-SESSION by prepending it as a
|
|
216
|
+
// leading context part each turn (authoritative for synthetic skills;
|
|
217
|
+
// advisory on top of the native command/agent dirs).
|
|
218
|
+
const artifactsContext = buildArtifactsPromptContext(profileId);
|
|
219
|
+
if (artifactsContext) {
|
|
220
|
+
promptParts.unshift({ type: 'text', text: artifactsContext });
|
|
221
|
+
}
|
|
222
|
+
|
|
133
223
|
// Create or fork a session
|
|
134
224
|
// When resuming, fork the session to create a new branch
|
|
135
225
|
// (like Claude Code's forkSession: true) so each checkpoint
|
|
@@ -167,12 +257,25 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
167
257
|
signal: this.activeAbortController.signal
|
|
168
258
|
});
|
|
169
259
|
|
|
170
|
-
// 2. Send prompt asynchronously (non-blocking)
|
|
260
|
+
// 2. Send prompt asynchronously (non-blocking). Disabled tools enforce
|
|
261
|
+
// the deny policy up front (covers read-only + MCP tools that never fire
|
|
262
|
+
// a permission event — see buildOpenCodeToolDisableMap).
|
|
263
|
+
const disabledTools = buildOpenCodeToolDisableMap(permissions);
|
|
264
|
+
// Profile connector scoping (INTERNAL): the shared `clopen-mcp` bridge is
|
|
265
|
+
// all-or-nothing, so disable — for THIS session only (per-prompt `tools`
|
|
266
|
+
// map → concurrency-safe) — the tools of every internal connector the
|
|
267
|
+
// active Profile excludes. External connectors are already absent from
|
|
268
|
+
// this Profile's server (see the pooled server config). No-op when the
|
|
269
|
+
// profile doesn't constrain connectors.
|
|
270
|
+
for (const toolId of getOpenCodeProfileDisabledToolIds(mcpProfileFilter)) {
|
|
271
|
+
disabledTools[toolId] = false;
|
|
272
|
+
}
|
|
171
273
|
client.session.promptAsync({
|
|
172
274
|
path: { id: sessionId },
|
|
173
275
|
body: {
|
|
174
276
|
parts: promptParts as any,
|
|
175
277
|
...(providerSlug && modelId ? { model: { providerID: providerSlug, modelID: modelId } } : {}),
|
|
278
|
+
...(Object.keys(disabledTools).length > 0 ? { tools: disabledTools } : {}),
|
|
176
279
|
},
|
|
177
280
|
query: { directory: projectPath },
|
|
178
281
|
}).catch(error => {
|
|
@@ -188,6 +291,9 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
188
291
|
let streamingText = '';
|
|
189
292
|
const emittedToolParts = new Set<string>(); // Tool parts already emitted as tool_use
|
|
190
293
|
const completedToolParts = new Set<string>(); // Tool parts whose tool_result was emitted
|
|
294
|
+
// callID/partId → raw tool name, so a `permission.asked` event (which
|
|
295
|
+
// carries only a callID) can be resolved to the tool being permitted.
|
|
296
|
+
const callIdToTool = new Map<string, string>();
|
|
191
297
|
const emittedReasoningParts = new Set<string>(); // Reasoning parts already flushed
|
|
192
298
|
let reasoningStreamActive = false; // Whether reasoning is currently streaming
|
|
193
299
|
let reasoningText = ''; // Accumulated reasoning text
|
|
@@ -350,6 +456,14 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
350
456
|
const toolPart = part as ToolPart;
|
|
351
457
|
const msg = assistantMessages.get(msgId);
|
|
352
458
|
|
|
459
|
+
// Register the tool name against its callID/partId as early as
|
|
460
|
+
// possible (even while pending) so a permission request can be
|
|
461
|
+
// resolved to it before the tool executes.
|
|
462
|
+
if (toolPart.tool) {
|
|
463
|
+
if (toolPart.callID) callIdToTool.set(toolPart.callID, toolPart.tool);
|
|
464
|
+
callIdToTool.set(toolPart.id, toolPart.tool);
|
|
465
|
+
}
|
|
466
|
+
|
|
353
467
|
// Flush reasoning before tool rendering to preserve order
|
|
354
468
|
if (msg && reasoningStreamActive) {
|
|
355
469
|
yield* flushReasoning(msg);
|
|
@@ -638,17 +752,26 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
638
752
|
break;
|
|
639
753
|
}
|
|
640
754
|
|
|
641
|
-
// v2 permission event —
|
|
642
|
-
// (
|
|
755
|
+
// v2 permission event — consult the permission policy, then
|
|
756
|
+
// approve (default) or reject the tool. OpenCode otherwise
|
|
757
|
+
// bypasses every tool permission.
|
|
643
758
|
case 'permission.asked':
|
|
644
759
|
case 'permission.updated': {
|
|
645
760
|
const props = evt.properties as {
|
|
646
761
|
id: string;
|
|
647
762
|
sessionID: string;
|
|
648
763
|
callID?: string;
|
|
764
|
+
type?: string;
|
|
649
765
|
};
|
|
650
766
|
if (props.sessionID !== sessionId) break;
|
|
651
|
-
|
|
767
|
+
// Resolve the tool being permitted (callID → tool name captured
|
|
768
|
+
// from the tool-part stream; fall back to the event `type`).
|
|
769
|
+
const rawTool = (props.callID && callIdToTool.get(props.callID)) || props.type;
|
|
770
|
+
const blocked = rawTool ? isOpenCodeToolBlocked(permissions, rawTool) : false;
|
|
771
|
+
if (blocked) {
|
|
772
|
+
debug.log('permissions', `⛔ Blocked tool "${rawTool}" (Clopen permission policy)`);
|
|
773
|
+
}
|
|
774
|
+
this.replyPermission(props.id, props.sessionID, blocked ? 'reject' : 'once');
|
|
652
775
|
break;
|
|
653
776
|
}
|
|
654
777
|
|
|
@@ -698,7 +821,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
698
821
|
// This is a courtesy cleanup — local processing is already stopped.
|
|
699
822
|
// The server-side session would otherwise keep running (consuming
|
|
700
823
|
// LLM API calls and compute resources) until it naturally completes.
|
|
701
|
-
const client = getClient();
|
|
824
|
+
const client = this.activeServer?.client ?? getClient();
|
|
702
825
|
if (client && sessionId) {
|
|
703
826
|
try {
|
|
704
827
|
await Promise.race([
|
|
@@ -720,7 +843,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
720
843
|
* Used by stream-manager for per-project isolation (instead of global cancel).
|
|
721
844
|
*/
|
|
722
845
|
async cancelSession(sessionId: string, projectPath?: string): Promise<void> {
|
|
723
|
-
const client = getClient();
|
|
846
|
+
const client = this.activeServer?.client ?? getClient();
|
|
724
847
|
if (!client || !sessionId) return;
|
|
725
848
|
try {
|
|
726
849
|
await Promise.race([
|
|
@@ -775,7 +898,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
775
898
|
* POST /question/{requestID}/reply to send user answers back to the OpenCode server.
|
|
776
899
|
*/
|
|
777
900
|
private replyToQuestion(requestId: string, orderedAnswers: string[][]): void {
|
|
778
|
-
const serverUrl = getServerUrl();
|
|
901
|
+
const serverUrl = this.activeServer?.url ?? getServerUrl();
|
|
779
902
|
if (!serverUrl) {
|
|
780
903
|
debug.warn('engine', 'replyToQuestion: Server URL not available');
|
|
781
904
|
return;
|
|
@@ -805,7 +928,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
805
928
|
* Fallback: GET /question to list pending questions, find the matching one, and reply.
|
|
806
929
|
*/
|
|
807
930
|
private async fetchAndReplyToQuestion(toolUseId: string, answers: Record<string, string>): Promise<void> {
|
|
808
|
-
const serverUrl = getServerUrl();
|
|
931
|
+
const serverUrl = this.activeServer?.url ?? getServerUrl();
|
|
809
932
|
if (!serverUrl) {
|
|
810
933
|
debug.warn('engine', 'fetchAndReplyToQuestion: Server URL not available');
|
|
811
934
|
return;
|
|
@@ -842,38 +965,41 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
842
965
|
}
|
|
843
966
|
|
|
844
967
|
/**
|
|
845
|
-
*
|
|
846
|
-
*
|
|
968
|
+
* Reply to a permission request. `response` is `'once'` to approve (the
|
|
969
|
+
* default, keeping the session unblocked) or `'reject'` to deny a tool blocked
|
|
970
|
+
* by the permission policy. Uses direct HTTP since the v1 client may not have
|
|
971
|
+
* the v2 permission.reply method.
|
|
847
972
|
*/
|
|
848
|
-
private
|
|
849
|
-
const serverUrl = getServerUrl();
|
|
973
|
+
private replyPermission(permissionId: string, sessionId: string, response: 'once' | 'reject'): void {
|
|
974
|
+
const serverUrl = this.activeServer?.url ?? getServerUrl();
|
|
850
975
|
if (!serverUrl) return;
|
|
976
|
+
const verb = response === 'reject' ? 'rejected' : 'approved';
|
|
851
977
|
|
|
852
978
|
// Try v2 endpoint first (/permission/{requestID}/reply), fall back to v1
|
|
853
979
|
fetch(`${serverUrl}/permission/${permissionId}/reply`, {
|
|
854
980
|
method: 'POST',
|
|
855
981
|
headers: { 'Content-Type': 'application/json' },
|
|
856
|
-
body: JSON.stringify({ reply:
|
|
982
|
+
body: JSON.stringify({ reply: response }),
|
|
857
983
|
}).then(res => {
|
|
858
984
|
if (res.ok) {
|
|
859
|
-
debug.log('engine', `[OC]
|
|
985
|
+
debug.log('engine', `[OC] ${verb} permission ${permissionId} (v2)`);
|
|
860
986
|
return;
|
|
861
987
|
}
|
|
862
988
|
// v2 endpoint not available — try v1
|
|
863
|
-
const client = getClient();
|
|
989
|
+
const client = this.activeServer?.client ?? getClient();
|
|
864
990
|
if (client) {
|
|
865
991
|
client.postSessionIdPermissionsPermissionId({
|
|
866
992
|
path: { id: sessionId, permissionID: permissionId },
|
|
867
|
-
body: { response
|
|
993
|
+
body: { response },
|
|
868
994
|
...(this.activeProjectPath && { query: { directory: this.activeProjectPath } }),
|
|
869
995
|
}).then(() => {
|
|
870
|
-
debug.log('engine', `[OC]
|
|
996
|
+
debug.log('engine', `[OC] ${verb} permission ${permissionId} (v1)`);
|
|
871
997
|
}).catch(err => {
|
|
872
|
-
debug.error('engine', 'Failed to
|
|
998
|
+
debug.error('engine', 'Failed to reply to permission (v1):', err);
|
|
873
999
|
});
|
|
874
1000
|
}
|
|
875
1001
|
}).catch(error => {
|
|
876
|
-
debug.error('engine', 'Failed to
|
|
1002
|
+
debug.error('engine', 'Failed to reply to permission:', error);
|
|
877
1003
|
});
|
|
878
1004
|
}
|
|
879
1005
|
|
|
@@ -46,7 +46,10 @@ import { handleStreamError } from './error-handler';
|
|
|
46
46
|
import { createSdkMessageConverter, toSdkUserMessage, type SdkMessageConverter } from './message-converter';
|
|
47
47
|
import { fetchQwenModels } from './models';
|
|
48
48
|
import { getQwenMcpConfig } from '../../../mcp';
|
|
49
|
+
import { artifactFilter } from '$backend/profiles';
|
|
49
50
|
import { syncSkills } from '$backend/skills';
|
|
51
|
+
import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
|
|
52
|
+
import { resolvePermissionsFromDb, isToolAllowed, excludedBuiltinTools } from '$backend/permissions';
|
|
50
53
|
import { forkQwenSessionState, sessionStateExists } from './session-fork';
|
|
51
54
|
|
|
52
55
|
interface PendingAskUserQuestion {
|
|
@@ -138,9 +141,17 @@ export class QwenEngine implements AIEngine {
|
|
|
138
141
|
|
|
139
142
|
this.activeController = abortController || new AbortController();
|
|
140
143
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
144
|
+
// Active Profile for this stream — scopes artifacts + connectors.
|
|
145
|
+
const profileId = options.mcpContext?.profileId;
|
|
146
|
+
const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
|
|
141
147
|
// Refresh the synthetic skills preamble in the Qwen memory file.
|
|
142
|
-
await syncSkills('qwen');
|
|
143
|
-
|
|
148
|
+
await syncSkills('qwen', profileId);
|
|
149
|
+
await syncEngineArtifacts('qwen', profileId);
|
|
150
|
+
const mcpConfig = getQwenMcpConfig(mcpProfileFilter);
|
|
151
|
+
|
|
152
|
+
// Resolve the permission policy once per stream; canUseTool enforces it
|
|
153
|
+
// (Qwen otherwise auto-allows everything). Tool names arrive snake_cased.
|
|
154
|
+
const permissions = resolvePermissionsFromDb('qwen', options.mcpContext?.projectId, profileId);
|
|
144
155
|
|
|
145
156
|
// Fork-by-copy on EVERY resume — same semantics as Claude
|
|
146
157
|
// (`forkSession: true`), OpenCode (`client.session.fork()`),
|
|
@@ -236,7 +247,11 @@ export class QwenEngine implements AIEngine {
|
|
|
236
247
|
// entry. The AUQ flow code (canUseTool handler, converter
|
|
237
248
|
// state, resolveUserAnswer, recordUserAnswer) is intentionally
|
|
238
249
|
// kept in place so reverting is a one-line change.
|
|
239
|
-
|
|
250
|
+
// `canUseTool` (permissionMode 'default') only fires for WRITE tools,
|
|
251
|
+
// so read-only tools can't be blocked there. `excludeTools` has the
|
|
252
|
+
// highest permission priority, so denied/non-allowlisted built-ins are
|
|
253
|
+
// hidden from the model entirely. MCP tools are filtered at the bridge.
|
|
254
|
+
excludeTools: ['ask_user_question', ...excludedBuiltinTools(permissions, 'qwen')],
|
|
240
255
|
canUseTool: async (toolName, input, ctx) => {
|
|
241
256
|
// Qwen SDK passes the registered (snake_case) tool name here —
|
|
242
257
|
// `ToolNames.ASK_USER_QUESTION = "ask_user_question"` — NOT the
|
|
@@ -273,6 +288,11 @@ export class QwenEngine implements AIEngine {
|
|
|
273
288
|
};
|
|
274
289
|
});
|
|
275
290
|
}
|
|
291
|
+
// Enforce the resolved permission policy before auto-allowing.
|
|
292
|
+
if (!isToolAllowed(permissions, toolName)) {
|
|
293
|
+
debug.log('permissions', `⛔ Blocked tool "${toolName}" (Clopen permission policy)`);
|
|
294
|
+
return { behavior: 'deny' as const, message: `Blocked by Clopen permission policy: ${toolName}` };
|
|
295
|
+
}
|
|
276
296
|
// Auto-allow everything else.
|
|
277
297
|
return { behavior: 'allow' as const, updatedInput: input };
|
|
278
298
|
},
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-stream materialization of the artifact-framework features that sit
|
|
3
|
+
* alongside Skills — Commands, Subagents, and (global) Instructions.
|
|
4
|
+
*
|
|
5
|
+
* Called at stream start by every engine adapter, right after `syncSkills`, so
|
|
6
|
+
* the newly-added features share the exact same trigger point without each
|
|
7
|
+
* adapter growing three separate calls.
|
|
8
|
+
*
|
|
9
|
+
* GLOBAL scope only: writing project-scoped instructions into a repo's
|
|
10
|
+
* `CLAUDE.md` / `AGENTS.md` touches the working tree, which the project's rules
|
|
11
|
+
* require to be an explicit, user-visible action — never silent at stream start.
|
|
12
|
+
* Each underlying sync swallows its own errors, so this never throws.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { syncCommands, buildCommandsPromptContext } from '$backend/commands';
|
|
16
|
+
import { syncSubagents, buildSubagentsPromptContext } from '$backend/subagents';
|
|
17
|
+
import { syncInstructions } from '$backend/instructions';
|
|
18
|
+
import { buildSkillsPromptContext } from '$backend/skills';
|
|
19
|
+
import type { ArtifactEngine } from '$backend/artifacts';
|
|
20
|
+
|
|
21
|
+
export async function syncEngineArtifacts(engine: ArtifactEngine, profileId?: number): Promise<void> {
|
|
22
|
+
// Sequential, NOT Promise.all: on synthetic engines (Codex/OpenCode) all three
|
|
23
|
+
// write their own managed block into the SAME memory file (AGENTS.md). Running
|
|
24
|
+
// them concurrently would race the read-modify-write and drop blocks. Each call
|
|
25
|
+
// swallows its own errors, so a failure in one doesn't stop the others.
|
|
26
|
+
//
|
|
27
|
+
// `profileId` scopes Commands/Subagents to the active Profile's bundle (see
|
|
28
|
+
// `backend/profiles`). Instructions are NOT profile-bundled — they always sync
|
|
29
|
+
// their full global set.
|
|
30
|
+
await syncCommands(engine, profileId);
|
|
31
|
+
await syncSubagents(engine, profileId);
|
|
32
|
+
await syncInstructions(engine);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The combined, profile-scoped Skills + Commands + Subagents preamble that
|
|
37
|
+
* prompt-scoped engines (OpenCode/Codex/Copilot) inject into each turn's prompt.
|
|
38
|
+
*
|
|
39
|
+
* Their runtimes read these artifacts through a channel that is SHARED across
|
|
40
|
+
* sessions and not reliably re-read per turn (a persistent server/client and/or
|
|
41
|
+
* a global memory file), so the on-disk/global-file filter can't express a
|
|
42
|
+
* per-session Profile. Injecting the scoped set into the prompt is the one
|
|
43
|
+
* channel that is genuinely per-session. Returns '' when nothing applies.
|
|
44
|
+
*/
|
|
45
|
+
export function buildArtifactsPromptContext(profileId?: number): string {
|
|
46
|
+
return [
|
|
47
|
+
buildSkillsPromptContext(profileId),
|
|
48
|
+
buildCommandsPromptContext(profileId),
|
|
49
|
+
buildSubagentsPromptContext(profileId)
|
|
50
|
+
].filter(Boolean).join('\n\n');
|
|
51
|
+
}
|
package/backend/engine/types.ts
CHANGED
|
@@ -16,6 +16,12 @@ export interface McpExecutionContext {
|
|
|
16
16
|
projectId?: string;
|
|
17
17
|
chatSessionId?: string;
|
|
18
18
|
streamId?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Active Profile for this stream (resolved in stream-manager from the
|
|
21
|
+
* session's choice or the project default). Scopes the materialized artifact
|
|
22
|
+
* set + MCP connectors to the profile's bundle. Undefined = no active profile.
|
|
23
|
+
*/
|
|
24
|
+
profileId?: number;
|
|
19
25
|
}
|
|
20
26
|
|
|
21
27
|
/** Options passed to engine.streamQuery() */
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project Instructions — public facade. Settings → Instructions manages a
|
|
3
|
+
* marker-region block injected into each engine's memory file (global + project).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export { instructionService } from './service';
|
|
7
|
+
export type { InstructionDTO } from './service';
|
|
8
|
+
export { syncInstructions } from './sync';
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Instruction service — reads/writes the Clopen-managed instruction block for
|
|
3
|
+
* the single global scope and per project. The content is materialized into each
|
|
4
|
+
* engine's memory file as a MARKER-REGION (see `sync.ts`), so hand-written parts
|
|
5
|
+
* of `CLAUDE.md` / `AGENTS.md` are never touched.
|
|
6
|
+
*
|
|
7
|
+
* This is distinct from Skills/Commands/Subagents (which are discrete
|
|
8
|
+
* installable artifacts): Instructions is one managed block of prose per scope.
|
|
9
|
+
* No prior "memory" feature exists in the app, so there is nothing to duplicate.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { instructionQueries } from '$backend/database/queries';
|
|
13
|
+
import { ARTIFACT_ENGINES, memoryFileName, type ArtifactEngine } from '$backend/artifacts';
|
|
14
|
+
|
|
15
|
+
export interface InstructionDTO {
|
|
16
|
+
scope: 'global' | 'project';
|
|
17
|
+
projectId: string | null;
|
|
18
|
+
content: string;
|
|
19
|
+
enabled: boolean;
|
|
20
|
+
updatedAt: string | null;
|
|
21
|
+
/** Per-engine memory file the block is injected into (for UI transparency). */
|
|
22
|
+
engineFiles: { engine: ArtifactEngine; fileName: string }[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function engineFiles(): { engine: ArtifactEngine; fileName: string }[] {
|
|
26
|
+
return ARTIFACT_ENGINES.map(engine => ({ engine, fileName: memoryFileName(engine) }));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const instructionService = {
|
|
30
|
+
getGlobal(): InstructionDTO {
|
|
31
|
+
const row = instructionQueries.getGlobal();
|
|
32
|
+
return {
|
|
33
|
+
scope: 'global',
|
|
34
|
+
projectId: null,
|
|
35
|
+
content: row?.content ?? '',
|
|
36
|
+
enabled: row ? row.is_enabled === 1 : true,
|
|
37
|
+
updatedAt: row?.updated_at ?? null,
|
|
38
|
+
engineFiles: engineFiles()
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
saveGlobal(content: string, enabled: boolean): InstructionDTO {
|
|
43
|
+
instructionQueries.upsert('global', null, content, enabled);
|
|
44
|
+
return this.getGlobal();
|
|
45
|
+
},
|
|
46
|
+
|
|
47
|
+
getForProject(projectId: string): InstructionDTO {
|
|
48
|
+
const row = instructionQueries.getForProject(projectId);
|
|
49
|
+
return {
|
|
50
|
+
scope: 'project',
|
|
51
|
+
projectId,
|
|
52
|
+
content: row?.content ?? '',
|
|
53
|
+
enabled: row ? row.is_enabled === 1 : true,
|
|
54
|
+
updatedAt: row?.updated_at ?? null,
|
|
55
|
+
engineFiles: engineFiles()
|
|
56
|
+
};
|
|
57
|
+
},
|
|
58
|
+
|
|
59
|
+
saveForProject(projectId: string, content: string, enabled: boolean): InstructionDTO {
|
|
60
|
+
instructionQueries.upsert('project', projectId, content, enabled);
|
|
61
|
+
return this.getForProject(projectId);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Engine sync for Instructions — writes the managed instruction block into each
|
|
3
|
+
* engine's memory file as a marker-region (`<!-- CLOPEN:INSTRUCTIONS:START … -->`).
|
|
4
|
+
* Global scope always applies; project scope applies to the repo memory file
|
|
5
|
+
* when a project is being streamed.
|
|
6
|
+
*
|
|
7
|
+
* Ownership is MARKER-REGION: only the delimited block is Clopen's; the rest of
|
|
8
|
+
* `CLAUDE.md` / `AGENTS.md` (hand-written by the user) is preserved verbatim.
|
|
9
|
+
* Writing into a project's `CLAUDE.md` touches the repo working tree, so callers
|
|
10
|
+
* pass the repo path explicitly — this is never silent guesswork.
|
|
11
|
+
*
|
|
12
|
+
* Never throws — a stream never breaks because instructions couldn't sync.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { instructionQueries } from '$backend/database/queries';
|
|
16
|
+
import { debug } from '$shared/utils/logger';
|
|
17
|
+
import { resolveArtifact, writeManagedBlock, markersFor, type ArtifactEngine } from '$backend/artifacts';
|
|
18
|
+
|
|
19
|
+
const MARKERS = markersFor('INSTRUCTIONS');
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Sync the global (and, when a project is provided, project) instruction block
|
|
23
|
+
* into one engine's memory file(s).
|
|
24
|
+
*/
|
|
25
|
+
export async function syncInstructions(
|
|
26
|
+
engine: ArtifactEngine,
|
|
27
|
+
project?: { id: string; path: string }
|
|
28
|
+
): Promise<void> {
|
|
29
|
+
try {
|
|
30
|
+
// Global scope → engine's isolated global memory file.
|
|
31
|
+
const global = instructionQueries.getGlobal();
|
|
32
|
+
const globalTarget = resolveArtifact('instruction', { engine, scope: 'global' }).locateEffective({ engine, scope: 'global' });
|
|
33
|
+
const globalBlock = global && global.is_enabled === 1 ? global.content : '';
|
|
34
|
+
if (globalTarget) await writeManagedBlock(globalTarget, globalBlock, MARKERS);
|
|
35
|
+
|
|
36
|
+
// Project scope → repo memory file (touches the working tree).
|
|
37
|
+
if (project) {
|
|
38
|
+
const row = instructionQueries.getForProject(project.id);
|
|
39
|
+
const projectTarget = resolveArtifact('instruction', { engine, scope: 'project', projectPath: project.path }).locateEffective({
|
|
40
|
+
engine,
|
|
41
|
+
scope: 'project',
|
|
42
|
+
projectPath: project.path
|
|
43
|
+
});
|
|
44
|
+
const projectBlock = row && row.is_enabled === 1 ? row.content : '';
|
|
45
|
+
// Only write when there is a managed block to add/update or a prior one to
|
|
46
|
+
// clear — avoids creating an empty repo memory file for nothing.
|
|
47
|
+
if (projectTarget && (projectBlock || row)) {
|
|
48
|
+
await writeManagedBlock(projectTarget, projectBlock, MARKERS);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
debug.log('instructions', `📝 Synced instructions → ${engine}${project ? ' (+project)' : ''}`);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
debug.warn('instructions', `⚠️ Instruction sync for ${engine} failed (continuing without):`, error);
|
|
55
|
+
}
|
|
56
|
+
}
|