@myrialabs/clopen 0.4.31 → 0.4.33
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/backend/auth/permissions.test.ts +0 -1
- package/backend/auth/permissions.ts +0 -4
- package/backend/chat/stream-manager.ts +31 -12
- package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
- package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
- package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
- package/backend/database/migrations/index.ts +14 -0
- package/backend/database/queries/db-client-connection-queries.ts +7 -2
- package/backend/database/queries/file-audit-log-queries.ts +1 -0
- package/backend/database/queries/index.ts +3 -0
- package/backend/database/queries/ssh-connection-queries.ts +244 -0
- package/backend/database/queries/ssh-known-host-queries.ts +67 -0
- package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
- package/backend/db-client/connection-manager.ts +8 -1
- package/backend/engine/README.md +16 -0
- package/backend/engine/adapters/claude/stream.ts +89 -49
- package/backend/engine/adapters/cline/stream.ts +62 -24
- package/backend/engine/adapters/codex/message-converter.ts +18 -12
- package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
- package/backend/engine/adapters/codex/stream.ts +78 -22
- package/backend/engine/adapters/copilot/stream.ts +97 -53
- package/backend/engine/adapters/cursor/stream.ts +75 -35
- package/backend/engine/adapters/opencode/server.ts +511 -134
- package/backend/engine/adapters/opencode/stream.ts +131 -79
- package/backend/engine/adapters/pi/stream.ts +63 -24
- package/backend/engine/adapters/qwen/stream.ts +92 -59
- package/backend/engine/adapters/run-registry.test.ts +75 -0
- package/backend/engine/adapters/run-registry.ts +63 -0
- package/backend/engine/config-revision.ts +150 -0
- package/backend/engine/docs/adapter-contract.md +47 -9
- package/backend/engine/docs/adding-an-engine.md +8 -0
- package/backend/engine/docs/frontend-and-chat.md +39 -0
- package/backend/engine/docs/lessons-learned.md +70 -0
- package/backend/engine/docs/quick-reference.md +3 -1
- package/backend/engine/hot-reload.ts +99 -0
- package/backend/engine/index.ts +96 -24
- package/backend/engine/types.ts +17 -5
- package/backend/files/file-watcher.ts +283 -51
- package/backend/files/git-events.test.ts +110 -0
- package/backend/git/git-dirs.test.ts +132 -0
- package/backend/git/git-dirs.ts +0 -0
- package/backend/git/git-executor.ts +22 -3
- package/backend/git/git-service.ts +1 -1
- package/backend/git/nested-repos.test.ts +224 -0
- package/backend/git/nested-repos.ts +386 -0
- package/backend/http/audio.ts +5 -32
- package/backend/http/bearer-auth.ts +47 -0
- package/backend/http/files-download.test.ts +146 -0
- package/backend/http/files-download.ts +109 -0
- package/backend/http/files-upload.ts +3 -29
- package/backend/http/ssh-sftp.ts +133 -0
- package/backend/index.ts +23 -2
- package/backend/mcp/README.md +34 -6
- package/backend/mcp/index.ts +8 -8
- package/backend/mcp/internal/config.ts +69 -19
- package/backend/mcp/internal/project-context.test.ts +40 -0
- package/backend/mcp/internal/project-context.ts +80 -7
- package/backend/mcp/internal/remote-server.test.ts +17 -2
- package/backend/mcp/internal/remote-server.ts +36 -3
- package/backend/mcp/internal/servers/helper.ts +48 -18
- package/backend/preview/browser/browser-video-capture.ts +51 -4
- package/backend/snapshot/gitignore.ts +10 -174
- package/backend/ssh/client-pool.ts +196 -0
- package/backend/ssh/connect.ts +375 -0
- package/backend/ssh/disk-usage.test.ts +134 -0
- package/backend/ssh/disk-usage.ts +214 -0
- package/backend/ssh/forwards.ts +309 -0
- package/backend/ssh/health.ts +141 -0
- package/backend/ssh/known-hosts.ts +96 -0
- package/backend/ssh/pty-backend.ts +215 -0
- package/backend/ssh/ptykit.ts +66 -0
- package/backend/ssh/sftp.test.ts +242 -0
- package/backend/ssh/sftp.ts +967 -0
- package/backend/ssh/socks5.test.ts +167 -0
- package/backend/ssh/socks5.ts +164 -0
- package/backend/ssh/tunnel.ts +87 -0
- package/backend/ws/chat/stream.ts +24 -0
- package/backend/ws/db-client/connections.ts +1 -0
- package/backend/ws/engine/codex/accounts.ts +0 -12
- package/backend/ws/engine/copilot/accounts.ts +0 -10
- package/backend/ws/engine/cursor/accounts.ts +0 -10
- package/backend/ws/engine/index.ts +17 -2
- package/backend/ws/engine/opencode/providers.ts +0 -52
- package/backend/ws/files/read.ts +1 -1
- package/backend/ws/files/watch.ts +5 -1
- package/backend/ws/git/conflict.ts +1 -1
- package/backend/ws/git/diff.ts +1 -1
- package/backend/ws/git/staging.ts +1 -1
- package/backend/ws/git/status.ts +1 -1
- package/backend/ws/index.ts +4 -0
- package/backend/ws/ssh/access.ts +31 -0
- package/backend/ws/ssh/connections.ts +224 -0
- package/backend/ws/ssh/forwards.ts +109 -0
- package/backend/ws/ssh/index.ts +18 -0
- package/backend/ws/ssh/sftp.ts +259 -0
- package/backend/ws/ssh/tunnel.ts +93 -0
- package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
- package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
- package/dist/assets/main-BbwWLJRN.js +1057 -0
- package/dist/assets/main-CCvRMXlP.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +49 -0
- package/shared/types/db-client/connection.ts +6 -0
- package/shared/types/ssh/connection.ts +80 -0
- package/shared/types/ssh/forward.ts +46 -0
- package/shared/types/ssh/index.ts +8 -0
- package/shared/types/ssh/known-host.ts +19 -0
- package/shared/types/ssh/sftp.ts +141 -0
- package/shared/utils/logger.ts +1 -0
- package/backend/ws/engine/restart.ts +0 -54
- package/dist/assets/main-VgdjTBLR.css +0 -1
- package/dist/assets/main-r0iv2PDz.js +0 -1044
|
@@ -42,7 +42,7 @@ import {
|
|
|
42
42
|
mapToolName,
|
|
43
43
|
TOOL_NAME_MAP,
|
|
44
44
|
} from './message-converter';
|
|
45
|
-
import { ensureClient,
|
|
45
|
+
import { ensureClient, acquireServer, releaseServer, getClient, getServerUrl, type ServerInstance } from './server';
|
|
46
46
|
import { syncSkills } from '$backend/skills';
|
|
47
47
|
import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
|
|
48
48
|
import { artifactFilter } from '$backend/profiles';
|
|
@@ -51,6 +51,7 @@ import { getOpenCodeProfileDisabledToolIds } from '$backend/mcp';
|
|
|
51
51
|
import { resolvePermissionsFromDb, matchesAny, type ResolvedPermissions } from '$backend/permissions';
|
|
52
52
|
import { formatSessionError, handleStreamError } from './error-handler';
|
|
53
53
|
import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
54
|
+
import { EngineRuns } from '../run-registry';
|
|
54
55
|
import { debug } from '$shared/utils/logger';
|
|
55
56
|
|
|
56
57
|
/**
|
|
@@ -99,24 +100,49 @@ function buildOpenCodeToolDisableMap(permissions: ResolvedPermissions): Record<s
|
|
|
99
100
|
// OpenCode Engine (per-project instance)
|
|
100
101
|
// ============================================================================
|
|
101
102
|
|
|
103
|
+
/**
|
|
104
|
+
* One stream in flight on this instance. Everything here used to be an instance
|
|
105
|
+
* field, which only worked while a project never had two chats streaming at once.
|
|
106
|
+
*/
|
|
107
|
+
interface OpenCodeRun {
|
|
108
|
+
/** Identity of the run — the controller the caller passed to streamQuery. */
|
|
109
|
+
controller: AbortController;
|
|
110
|
+
projectPath: string;
|
|
111
|
+
/** The pooled per-Profile server this run is bound to. */
|
|
112
|
+
server: ServerInstance | null;
|
|
113
|
+
/** The pool hold taken for this run, released when it ends. */
|
|
114
|
+
holder: { key: string; holderId: string } | null;
|
|
115
|
+
sessionId: string | null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
interface PendingQuestion {
|
|
119
|
+
requestId: string;
|
|
120
|
+
questions: Array<{ question: string }>;
|
|
121
|
+
/** The run that asked — its server is where the answer has to be posted. */
|
|
122
|
+
run: OpenCodeRun;
|
|
123
|
+
}
|
|
124
|
+
|
|
102
125
|
export class OpenCodeEngine implements AIEngine {
|
|
103
126
|
readonly name = 'opencode' as const;
|
|
104
127
|
private _isInitialized = false;
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
128
|
+
/**
|
|
129
|
+
* Every stream running on this instance, keyed by the AbortController its
|
|
130
|
+
* caller passed to streamQuery. This instance is shared by all chat sessions
|
|
131
|
+
* of a project, so anything a single stream owns — its session id, its pooled
|
|
132
|
+
* server, its pool hold — belongs here and not in an instance field. A field
|
|
133
|
+
* would hold only the most recent stream, and cancelling any chat would then
|
|
134
|
+
* abort another chat's session and leak the hold of the one it overwrote.
|
|
135
|
+
*/
|
|
136
|
+
private runs = new EngineRuns<OpenCodeRun>();
|
|
137
|
+
/** Pending question requests keyed by tool callID → the asking run's reply target. */
|
|
138
|
+
private pendingQuestions = new Map<string, PendingQuestion>();
|
|
113
139
|
|
|
114
140
|
get isInitialized(): boolean {
|
|
115
141
|
return this._isInitialized;
|
|
116
142
|
}
|
|
117
143
|
|
|
118
144
|
get isActive(): boolean {
|
|
119
|
-
return this.
|
|
145
|
+
return this.runs.isActive;
|
|
120
146
|
}
|
|
121
147
|
|
|
122
148
|
/**
|
|
@@ -136,9 +162,11 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
136
162
|
* Does NOT dispose the shared client — that's handled by disposeOpenCodeClient().
|
|
137
163
|
*/
|
|
138
164
|
async dispose(): Promise<void> {
|
|
139
|
-
|
|
165
|
+
// Shutdown/retirement: every run on this instance goes, and each releases
|
|
166
|
+
// its own hold. An instance retired mid-stream still owes the pool those holds;
|
|
167
|
+
// without them the servers it was using would never become reapable.
|
|
168
|
+
await this.stopRuns(this.runs.all());
|
|
140
169
|
this.pendingQuestions.clear();
|
|
141
|
-
this.activeServer = null;
|
|
142
170
|
this._isInitialized = false;
|
|
143
171
|
debug.log('engine', 'Open Code engine instance disposed');
|
|
144
172
|
}
|
|
@@ -168,9 +196,15 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
168
196
|
abortController
|
|
169
197
|
} = options;
|
|
170
198
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
199
|
+
const controller = abortController || new AbortController();
|
|
200
|
+
const run: OpenCodeRun = {
|
|
201
|
+
controller,
|
|
202
|
+
projectPath,
|
|
203
|
+
server: null,
|
|
204
|
+
holder: null,
|
|
205
|
+
sessionId: null,
|
|
206
|
+
};
|
|
207
|
+
this.runs.add(run);
|
|
174
208
|
|
|
175
209
|
// Active Profile for this stream. Skills go into the prompt and commands
|
|
176
210
|
// into shared dirs; materialize those first, then bind to the per-Profile
|
|
@@ -188,15 +222,15 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
188
222
|
const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
|
|
189
223
|
const subagentFilter = artifactFilter(profileId, 'subagent') ?? undefined;
|
|
190
224
|
const inlineAgents = await buildOpenCodeInlineAgents(profileId);
|
|
191
|
-
//
|
|
192
|
-
//
|
|
193
|
-
//
|
|
194
|
-
//
|
|
195
|
-
|
|
196
|
-
const
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
|
|
225
|
+
// The pool derives the key from the config it is about to spawn with, so a
|
|
226
|
+
// changed connector set, provider, credential or subagent prompt routes this
|
|
227
|
+
// stream to a server built from it — while any server still serving another
|
|
228
|
+
// stream keeps running until that stream is done. Holding the server by
|
|
229
|
+
// stream id is what makes that safe: a held server is never reaped.
|
|
230
|
+
const holderId = options.mcpContext?.streamId;
|
|
231
|
+
const server = await acquireServer({ mcpProfileFilter, subagentFilter, inlineAgents }, holderId);
|
|
232
|
+
run.server = server;
|
|
233
|
+
run.holder = holderId ? { key: server.key, holderId } : null;
|
|
200
234
|
const client = server.client;
|
|
201
235
|
|
|
202
236
|
// Resolve the permission policy once per stream; the permission event
|
|
@@ -247,7 +281,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
247
281
|
sessionId = sessionResult.data?.id || crypto.randomUUID();
|
|
248
282
|
}
|
|
249
283
|
|
|
250
|
-
|
|
284
|
+
run.sessionId = sessionId;
|
|
251
285
|
|
|
252
286
|
yield convertSystemInitMessage(sessionId, modelId);
|
|
253
287
|
yield convertStreamStart(sessionId);
|
|
@@ -255,7 +289,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
255
289
|
// 1. Subscribe to event stream FIRST (before sending prompt)
|
|
256
290
|
const eventResult = await client.event.subscribe({
|
|
257
291
|
query: { directory: projectPath },
|
|
258
|
-
signal:
|
|
292
|
+
signal: controller.signal
|
|
259
293
|
});
|
|
260
294
|
|
|
261
295
|
// 2. Send prompt asynchronously (non-blocking). Disabled tools enforce
|
|
@@ -377,7 +411,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
377
411
|
|
|
378
412
|
if (eventResult?.stream) {
|
|
379
413
|
for await (const event of eventResult.stream) {
|
|
380
|
-
if (
|
|
414
|
+
if (controller.signal.aborted) break;
|
|
381
415
|
|
|
382
416
|
const evt = event as { type: string; properties: Record<string, unknown> };
|
|
383
417
|
debug.log('engine', `[OC] event: ${evt.type}`);
|
|
@@ -752,6 +786,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
752
786
|
this.pendingQuestions.set(props.tool.callID, {
|
|
753
787
|
requestId: props.id,
|
|
754
788
|
questions: props.questions,
|
|
789
|
+
run,
|
|
755
790
|
});
|
|
756
791
|
debug.log('engine', `[OC] question.asked: stored question ${props.id} for callID ${props.tool.callID}`);
|
|
757
792
|
}
|
|
@@ -777,7 +812,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
777
812
|
if (blocked) {
|
|
778
813
|
debug.log('permissions', `⛔ Blocked tool "${rawTool}" (Clopen permission policy)`);
|
|
779
814
|
}
|
|
780
|
-
this.replyPermission(props.id, props.sessionID, blocked ? 'reject' : 'once');
|
|
815
|
+
this.replyPermission(run, props.id, props.sessionID, blocked ? 'reject' : 'once');
|
|
781
816
|
break;
|
|
782
817
|
}
|
|
783
818
|
|
|
@@ -796,39 +831,65 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
796
831
|
} catch (error) {
|
|
797
832
|
handleStreamError(error);
|
|
798
833
|
} finally {
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
this.
|
|
802
|
-
|
|
803
|
-
|
|
834
|
+
// Retire THIS run only — a concurrent stream of another chat session in
|
|
835
|
+
// the same project is still using the instance.
|
|
836
|
+
this.forgetRun(run);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* Drop a finished run: unregister it, discard the questions only it could
|
|
842
|
+
* answer, and hand its pooled server back. Until the hold is released the
|
|
843
|
+
* server is pinned, which is exactly what keeps a settings change from
|
|
844
|
+
* cutting that turn short.
|
|
845
|
+
*/
|
|
846
|
+
private forgetRun(run: OpenCodeRun): void {
|
|
847
|
+
this.runs.remove(run);
|
|
848
|
+
for (const [callId, pending] of this.pendingQuestions) {
|
|
849
|
+
if (pending.run === run) this.pendingQuestions.delete(callId);
|
|
850
|
+
}
|
|
851
|
+
if (run.holder) {
|
|
852
|
+
releaseServer(run.holder.key, run.holder.holderId);
|
|
853
|
+
run.holder = null;
|
|
804
854
|
}
|
|
805
855
|
}
|
|
806
856
|
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
857
|
+
/**
|
|
858
|
+
* Cancel one run — the one whose AbortController is `owner` — or every run
|
|
859
|
+
* when no owner is given (dispose/shutdown).
|
|
860
|
+
*
|
|
861
|
+
* Targeting matters here: an untargeted abort would tear down whichever
|
|
862
|
+
* session id and hold this instance had on hand, which is another chat's as
|
|
863
|
+
* soon as two sessions of the project stream at once.
|
|
864
|
+
*/
|
|
865
|
+
async cancel(owner: AbortController): Promise<void> {
|
|
866
|
+
await this.stopRuns(this.runs.select(owner));
|
|
867
|
+
}
|
|
811
868
|
|
|
869
|
+
/**
|
|
870
|
+
* Tear down the given runs. `cancel` passes the one run it was asked to
|
|
871
|
+
* stop; `dispose` passes them all. Nothing else may reach this.
|
|
872
|
+
*/
|
|
873
|
+
private async stopRuns(targets: OpenCodeRun[]): Promise<void> {
|
|
812
874
|
// 1. FIRST: Abort local stream processing immediately.
|
|
813
875
|
// This breaks the SSE event stream and causes the for-await loop
|
|
814
876
|
// in processStream() to throw AbortError, stopping all local processing.
|
|
815
877
|
// Must happen BEFORE the HTTP call because client.session.abort() can
|
|
816
878
|
// hang indefinitely if the OpenCode server is busy/unresponsive.
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
this.activeAbortController = null;
|
|
879
|
+
for (const run of targets) {
|
|
880
|
+
if (!run.controller.signal.aborted) run.controller.abort();
|
|
820
881
|
}
|
|
821
|
-
this._isActive = false;
|
|
822
|
-
this.activeSessionId = null;
|
|
823
|
-
this.activeProjectPath = null;
|
|
824
|
-
this.pendingQuestions.clear();
|
|
825
882
|
|
|
826
883
|
// 2. THEN: Tell the OpenCode server to stop processing (with timeout).
|
|
827
884
|
// This is a courtesy cleanup — local processing is already stopped.
|
|
828
885
|
// The server-side session would otherwise keep running (consuming
|
|
829
886
|
// LLM API calls and compute resources) until it naturally completes.
|
|
830
|
-
|
|
831
|
-
|
|
887
|
+
// The pool hold is still held here on purpose — handing the server back
|
|
888
|
+
// first could let it be reaped out from under this very call.
|
|
889
|
+
for (const run of targets) {
|
|
890
|
+
const client = run.server?.client ?? getClient();
|
|
891
|
+
const { sessionId, projectPath } = run;
|
|
892
|
+
if (!client || !sessionId) continue;
|
|
832
893
|
try {
|
|
833
894
|
await Promise.race([
|
|
834
895
|
client.session.abort({
|
|
@@ -842,32 +903,15 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
842
903
|
debug.warn('engine', 'Failed to abort Open Code session (non-fatal):', error);
|
|
843
904
|
}
|
|
844
905
|
}
|
|
845
|
-
}
|
|
846
906
|
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
*/
|
|
851
|
-
async cancelSession(sessionId: string, projectPath?: string): Promise<void> {
|
|
852
|
-
const client = this.activeServer?.client ?? getClient();
|
|
853
|
-
if (!client || !sessionId) return;
|
|
854
|
-
try {
|
|
855
|
-
await Promise.race([
|
|
856
|
-
client.session.abort({
|
|
857
|
-
path: { id: sessionId },
|
|
858
|
-
...(projectPath && { query: { directory: projectPath } }),
|
|
859
|
-
}),
|
|
860
|
-
new Promise<void>(resolve => setTimeout(resolve, 5000))
|
|
861
|
-
]);
|
|
862
|
-
debug.log('engine', 'Open Code session aborted (per-stream):', sessionId);
|
|
863
|
-
} catch (error) {
|
|
864
|
-
debug.warn('engine', 'Failed to abort Open Code session (non-fatal):', error);
|
|
865
|
-
}
|
|
907
|
+
// 3. Retire the runs. Each hands its own pooled server back; a run that
|
|
908
|
+
// never got as far as binding one simply has nothing to release.
|
|
909
|
+
for (const run of targets) this.forgetRun(run);
|
|
866
910
|
}
|
|
867
911
|
|
|
868
|
-
async interrupt(): Promise<void> {
|
|
912
|
+
async interrupt(owner: AbortController): Promise<void> {
|
|
869
913
|
// Open Code SDK doesn't have a separate interrupt — use cancel
|
|
870
|
-
await this.
|
|
914
|
+
await this.stopRuns(this.runs.select(owner));
|
|
871
915
|
}
|
|
872
916
|
|
|
873
917
|
/**
|
|
@@ -889,7 +933,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
889
933
|
const answer = answers[q.question];
|
|
890
934
|
return answer ? [answer] : [];
|
|
891
935
|
});
|
|
892
|
-
this.replyToQuestion(pending.requestId, orderedAnswers);
|
|
936
|
+
this.replyToQuestion(pending.run, pending.requestId, orderedAnswers);
|
|
893
937
|
this.pendingQuestions.delete(toolUseId);
|
|
894
938
|
return true;
|
|
895
939
|
}
|
|
@@ -903,14 +947,18 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
903
947
|
/**
|
|
904
948
|
* POST /question/{requestID}/reply to send user answers back to the OpenCode server.
|
|
905
949
|
*/
|
|
906
|
-
private replyToQuestion(requestId: string, orderedAnswers: string[][]): void {
|
|
907
|
-
const serverUrl =
|
|
950
|
+
private replyToQuestion(run: OpenCodeRun | null, requestId: string, orderedAnswers: string[][]): void {
|
|
951
|
+
const serverUrl = run?.server?.url ?? getServerUrl();
|
|
908
952
|
if (!serverUrl) {
|
|
909
953
|
debug.warn('engine', 'replyToQuestion: Server URL not available');
|
|
910
954
|
return;
|
|
911
955
|
}
|
|
912
956
|
|
|
913
|
-
|
|
957
|
+
// The answer must go back to the server that asked. Concurrent streams of
|
|
958
|
+
// one project can sit on different pooled servers (different Profiles), so
|
|
959
|
+
// a shared "current server" would post this reply into the wrong one and
|
|
960
|
+
// leave the asking session waiting forever.
|
|
961
|
+
const dirParam = run?.projectPath ? `?directory=${encodeURIComponent(run.projectPath)}` : '';
|
|
914
962
|
const url = `${serverUrl}/question/${requestId}/reply${dirParam}`;
|
|
915
963
|
debug.log('engine', `Replying to question ${requestId}:`, orderedAnswers);
|
|
916
964
|
|
|
@@ -934,14 +982,18 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
934
982
|
* Fallback: GET /question to list pending questions, find the matching one, and reply.
|
|
935
983
|
*/
|
|
936
984
|
private async fetchAndReplyToQuestion(toolUseId: string, answers: Record<string, string>): Promise<void> {
|
|
937
|
-
|
|
985
|
+
// No stored question means no known run — fall back to the single
|
|
986
|
+
// still-running one when there is exactly one, else the shared client.
|
|
987
|
+
const running = this.runs.all();
|
|
988
|
+
const run = running.length === 1 ? running[0] : null;
|
|
989
|
+
const serverUrl = run?.server?.url ?? getServerUrl();
|
|
938
990
|
if (!serverUrl) {
|
|
939
991
|
debug.warn('engine', 'fetchAndReplyToQuestion: Server URL not available');
|
|
940
992
|
return;
|
|
941
993
|
}
|
|
942
994
|
|
|
943
995
|
try {
|
|
944
|
-
const dirParam =
|
|
996
|
+
const dirParam = run?.projectPath ? `?directory=${encodeURIComponent(run.projectPath)}` : '';
|
|
945
997
|
const res = await fetch(`${serverUrl}/question${dirParam}`);
|
|
946
998
|
if (!res.ok) {
|
|
947
999
|
debug.error('engine', `Failed to list pending questions: ${res.status}`);
|
|
@@ -964,7 +1016,7 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
964
1016
|
const answer = answers[q.question];
|
|
965
1017
|
return answer ? [answer] : [];
|
|
966
1018
|
});
|
|
967
|
-
this.replyToQuestion(matching.id, orderedAnswers);
|
|
1019
|
+
this.replyToQuestion(run, matching.id, orderedAnswers);
|
|
968
1020
|
} catch (error) {
|
|
969
1021
|
debug.error('engine', 'Failed to fetch and reply to question:', error);
|
|
970
1022
|
}
|
|
@@ -976,8 +1028,8 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
976
1028
|
* by the permission policy. Uses direct HTTP since the v1 client may not have
|
|
977
1029
|
* the v2 permission.reply method.
|
|
978
1030
|
*/
|
|
979
|
-
private replyPermission(permissionId: string, sessionId: string, response: 'once' | 'reject'): void {
|
|
980
|
-
const serverUrl =
|
|
1031
|
+
private replyPermission(run: OpenCodeRun, permissionId: string, sessionId: string, response: 'once' | 'reject'): void {
|
|
1032
|
+
const serverUrl = run.server?.url ?? getServerUrl();
|
|
981
1033
|
if (!serverUrl) return;
|
|
982
1034
|
const verb = response === 'reject' ? 'rejected' : 'approved';
|
|
983
1035
|
|
|
@@ -992,12 +1044,12 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
992
1044
|
return;
|
|
993
1045
|
}
|
|
994
1046
|
// v2 endpoint not available — try v1
|
|
995
|
-
const client =
|
|
1047
|
+
const client = run.server?.client ?? getClient();
|
|
996
1048
|
if (client) {
|
|
997
1049
|
client.postSessionIdPermissionsPermissionId({
|
|
998
1050
|
path: { id: sessionId, permissionID: permissionId },
|
|
999
1051
|
body: { response },
|
|
1000
|
-
...(
|
|
1052
|
+
...(run.projectPath && { query: { directory: run.projectPath } }),
|
|
1001
1053
|
}).then(() => {
|
|
1002
1054
|
debug.log('engine', `[OC] ${verb} permission ${permissionId} (v1)`);
|
|
1003
1055
|
}).catch(err => {
|
|
@@ -39,6 +39,7 @@ import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
|
|
|
39
39
|
import { artifactFilter } from '$backend/profiles';
|
|
40
40
|
import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
|
|
41
41
|
import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
42
|
+
import { EngineRuns } from '../run-registry';
|
|
42
43
|
import { DbCredentialStore, getPiAccountForProvider, parsePiCredential } from './credential';
|
|
43
44
|
import { createPiRuntime } from './presets';
|
|
44
45
|
import { getPiAgentDir } from './environment';
|
|
@@ -88,15 +89,27 @@ class EventQueue<T> {
|
|
|
88
89
|
}
|
|
89
90
|
}
|
|
90
91
|
|
|
92
|
+
/**
|
|
93
|
+
* One stream in flight on this instance. This engine instance is shared by every
|
|
94
|
+
* chat session of a project, so the Pi session belongs here, not in an instance
|
|
95
|
+
* field — a field would hold only the most recently started stream, and
|
|
96
|
+
* cancelling any chat would then abort another chat's session.
|
|
97
|
+
*/
|
|
98
|
+
interface PiRun {
|
|
99
|
+
/** Identity of the run — the controller the caller passed to streamQuery. */
|
|
100
|
+
controller: AbortController;
|
|
101
|
+
session: AgentSession | null;
|
|
102
|
+
}
|
|
103
|
+
|
|
91
104
|
export class PiEngine implements AIEngine {
|
|
92
105
|
readonly name = 'pi' as const;
|
|
93
106
|
private _isInitialized = false;
|
|
94
|
-
private
|
|
95
|
-
|
|
96
|
-
private pendingAsks = new Map<string, PendingAsk>();
|
|
107
|
+
private runs = new EngineRuns<PiRun>();
|
|
108
|
+
/** Parked AskUserQuestion callbacks → the run that asked. */
|
|
109
|
+
private pendingAsks = new Map<string, PendingAsk & { owner: PiRun }>();
|
|
97
110
|
|
|
98
111
|
get isInitialized(): boolean { return this._isInitialized; }
|
|
99
|
-
get isActive(): boolean { return this.
|
|
112
|
+
get isActive(): boolean { return this.runs.isActive; }
|
|
100
113
|
|
|
101
114
|
async initialize(): Promise<void> {
|
|
102
115
|
if (this._isInitialized) return;
|
|
@@ -105,7 +118,8 @@ export class PiEngine implements AIEngine {
|
|
|
105
118
|
}
|
|
106
119
|
|
|
107
120
|
async dispose(): Promise<void> {
|
|
108
|
-
|
|
121
|
+
// Shutdown/retirement: every run on this instance goes.
|
|
122
|
+
await this.stopRuns(this.runs.all());
|
|
109
123
|
this.pendingAsks.clear();
|
|
110
124
|
this._isInitialized = false;
|
|
111
125
|
}
|
|
@@ -139,7 +153,9 @@ export class PiEngine implements AIEngine {
|
|
|
139
153
|
throw new Error(`Pi could not resolve model "${modelId}" for provider "${provider}".`);
|
|
140
154
|
}
|
|
141
155
|
|
|
142
|
-
|
|
156
|
+
const controller = abortController || new AbortController();
|
|
157
|
+
const run: PiRun = { controller, session: null };
|
|
158
|
+
this.runs.add(run);
|
|
143
159
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
144
160
|
const agentDir = getPiAgentDir();
|
|
145
161
|
|
|
@@ -168,7 +184,7 @@ export class PiEngine implements AIEngine {
|
|
|
168
184
|
// ── Tools: builtins (permission-filtered) + AskUserQuestion + MCP bridge + subagents ──
|
|
169
185
|
const allowedBuiltins = PI_BUILTIN_TOOLS.filter((name) => isToolAllowed(permissions, name));
|
|
170
186
|
const askTool = createAskUserQuestionTool({
|
|
171
|
-
register: (id, entry) => this.pendingAsks.set(id, entry),
|
|
187
|
+
register: (id, entry) => this.pendingAsks.set(id, { ...entry, owner: run }),
|
|
172
188
|
unregister: (id) => this.pendingAsks.delete(id),
|
|
173
189
|
});
|
|
174
190
|
const mcpTools = await buildPiMcpTools(options.mcpContext, mcpProfileFilter);
|
|
@@ -272,7 +288,7 @@ export class PiEngine implements AIEngine {
|
|
|
272
288
|
sessionManager,
|
|
273
289
|
settingsManager: SettingsManager.inMemory({ retry: PI_RETRY }),
|
|
274
290
|
});
|
|
275
|
-
|
|
291
|
+
run.session = session;
|
|
276
292
|
|
|
277
293
|
const engineMeta: MessageEngine = {
|
|
278
294
|
type: 'pi',
|
|
@@ -295,7 +311,7 @@ export class PiEngine implements AIEngine {
|
|
|
295
311
|
|
|
296
312
|
// Abort wiring: cancelling the stream aborts the Pi session.
|
|
297
313
|
const onAbort = () => { void session.abort(); };
|
|
298
|
-
|
|
314
|
+
controller.signal.addEventListener('abort', onAbort, { once: true });
|
|
299
315
|
|
|
300
316
|
// Prompt text + image attachments.
|
|
301
317
|
const promptText = prompt.content.filter((b) => b.type === 'text').map((b) => b.text).join('\n');
|
|
@@ -340,30 +356,53 @@ export class PiEngine implements AIEngine {
|
|
|
340
356
|
} catch (error) {
|
|
341
357
|
handleStreamError(error);
|
|
342
358
|
} finally {
|
|
343
|
-
|
|
359
|
+
controller.signal.removeEventListener('abort', onAbort);
|
|
344
360
|
unsubscribe();
|
|
345
361
|
try { session.dispose(); } catch { /* already disposed */ }
|
|
346
|
-
|
|
347
|
-
this.
|
|
348
|
-
this.
|
|
362
|
+
// Retire THIS run only — another chat session of the same project may
|
|
363
|
+
// still be streaming on this instance.
|
|
364
|
+
this.forgetRun(run);
|
|
349
365
|
}
|
|
350
366
|
}
|
|
351
367
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
368
|
+
/** Drop a finished run and the asks only it could answer. */
|
|
369
|
+
private forgetRun(run: PiRun): void {
|
|
370
|
+
this.runs.remove(run);
|
|
371
|
+
for (const [id, pending] of this.pendingAsks) {
|
|
372
|
+
if (pending.owner === run) this.pendingAsks.delete(id);
|
|
355
373
|
}
|
|
356
|
-
|
|
357
|
-
|
|
374
|
+
run.session = null;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Cancel the run whose AbortController is `owner`, and only that run.
|
|
379
|
+
*/
|
|
380
|
+
async cancel(owner: AbortController): Promise<void> {
|
|
381
|
+
await this.stopRuns(this.runs.select(owner));
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Tear down the given runs. `cancel` passes the one run it was asked to
|
|
386
|
+
* stop; `dispose` passes them all. Nothing else may reach this.
|
|
387
|
+
*/
|
|
388
|
+
private async stopRuns(targets: PiRun[]): Promise<void> {
|
|
389
|
+
for (const run of targets) {
|
|
390
|
+
if (!run.controller.signal.aborted) run.controller.abort();
|
|
391
|
+
const session = run.session;
|
|
392
|
+
// Drop only this run's parked asks; another run's are still live.
|
|
393
|
+
this.forgetRun(run);
|
|
394
|
+
if (session) {
|
|
395
|
+
try { await session.abort(); } catch { /* may already be idle */ }
|
|
396
|
+
}
|
|
358
397
|
}
|
|
359
|
-
this.pendingAsks.clear();
|
|
360
|
-
this.activeSession = null;
|
|
361
|
-
this.activeController = null;
|
|
362
398
|
}
|
|
363
399
|
|
|
364
|
-
async interrupt(): Promise<void> {
|
|
365
|
-
|
|
366
|
-
|
|
400
|
+
async interrupt(owner: AbortController): Promise<void> {
|
|
401
|
+
const targets = this.runs.select(owner);
|
|
402
|
+
for (const run of targets) {
|
|
403
|
+
if (run.session) {
|
|
404
|
+
try { await run.session.abort(); } catch { /* ignore */ }
|
|
405
|
+
}
|
|
367
406
|
}
|
|
368
407
|
}
|
|
369
408
|
|