opencode-ahp 0.1.8 → 0.1.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 +171 -112
- package/options.example.jsonc +16 -1
- package/package.json +1 -1
- package/src/bridge.ts +355 -13
- package/src/channels.ts +61 -8
- package/src/host-base.ts +42 -5
- package/src/host-changesets.ts +30 -14
- package/src/host-chats.ts +12 -3
- package/src/host-client-tools.ts +20 -1
- package/src/host-dispatch.ts +67 -2
- package/src/host-events.ts +2 -2
- package/src/host-resources.ts +177 -0
- package/src/host-rpc.ts +12 -0
- package/src/host-sessions.ts +367 -32
- package/src/host-terminals.ts +47 -15
- package/src/host-types.ts +18 -1
- package/src/host-util.ts +8 -2
- package/src/host.ts +3 -3
- package/src/index.ts +386 -8
- package/src/options.ts +22 -0
- package/src/path-policy.ts +85 -0
- package/src/transport.ts +11 -2
package/src/host-sessions.ts
CHANGED
|
@@ -1,15 +1,41 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Session section (design §7): `createSession`/`listSessions`/`resolveSessionConfig`, external session registration (TUI/restart resurfacing, AHP markers, peer-chat re-attach), and record removal.
|
|
2
|
+
* Session section (design §7): `createSession`/`disposeSession`/`listSessions`/`resolveSessionConfig`, external session registration (TUI/restart resurfacing, AHP markers, peer-chat re-attach), and record removal.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { HostChats } from "./host-chats.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
6
|
+
import { isAbsolute } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import {
|
|
9
|
+
ActionType,
|
|
10
|
+
SessionStatus,
|
|
11
|
+
ResolveSessionConfigResult,
|
|
12
|
+
SessionActiveClient,
|
|
13
|
+
SessionSummary,
|
|
14
|
+
type Customization,
|
|
15
|
+
type ToolDefinition,
|
|
16
|
+
} from "@microsoft/agent-host-protocol";
|
|
17
|
+
import {
|
|
18
|
+
agentDirectoryCustomization,
|
|
19
|
+
chatChangesetCatalog,
|
|
20
|
+
chatSummaryOf,
|
|
21
|
+
directoryUri,
|
|
22
|
+
initialSessionState,
|
|
23
|
+
mapAgentCustomizations,
|
|
24
|
+
mapMcpServerCustomizations,
|
|
25
|
+
mapServerTools,
|
|
26
|
+
sessionChangesetCatalog,
|
|
27
|
+
skillDirectoryCustomization,
|
|
28
|
+
FacadeAgent,
|
|
29
|
+
FacadeMcpServer,
|
|
30
|
+
FacadeSession,
|
|
31
|
+
FacadeSkill,
|
|
32
|
+
FacadeTool,
|
|
33
|
+
} from "./bridge.js";
|
|
34
|
+
import { ROOT_CHANNEL, chatChannelURI, isSessionChannel, sessionChannelURI, sessionIDOf } from "./channels.js";
|
|
9
35
|
import { ERROR_INVALID_PARAMS } from "./handshake.js";
|
|
10
36
|
import { isRecord } from "./options.js";
|
|
11
37
|
import { createSessionStateStore } from "./state.js";
|
|
12
|
-
import { ERROR_NO_PROVIDER, ERROR_SESSION_EXISTS } from "./host-errors.js";
|
|
38
|
+
import { ERROR_INTERNAL, ERROR_NO_PROVIDER, ERROR_PERMISSION_DENIED, ERROR_SESSION_EXISTS, ERROR_SESSION_NOT_FOUND } from "./host-errors.js";
|
|
13
39
|
import { RpcMessage, SessionRecord } from "./host-types.js";
|
|
14
40
|
import { EXTERNAL_REGISTER_GRACE_MS, AHP_METADATA_KEY, parseAhpMarker, errorMessage, firstEnabledModelRef, normalizeActiveClient } from "./host-util.js";
|
|
15
41
|
|
|
@@ -21,16 +47,53 @@ export class HostSessions extends HostChats {
|
|
|
21
47
|
* `createSession` (AHP 1.0.0 session-channel command). Creates a real
|
|
22
48
|
* opencode session, seeds its session/chat stores, publishes the
|
|
23
49
|
* session-channel lifecycle actions, announces the session on the root
|
|
24
|
-
* channel, and responds `null` (per the command contract).
|
|
50
|
+
* channel, and responds `null` (per the command contract). The
|
|
51
|
+
* optional `workingDirectories` first entry (a `file://` URI) targets
|
|
52
|
+
* that directory's opencode location — the session's agent gets tool
|
|
53
|
+
* access there; without it the session runs in the plugin's own
|
|
54
|
+
* location (no multipleWorkingDirectories capability: extras are
|
|
55
|
+
* ignored).
|
|
25
56
|
*
|
|
26
|
-
*
|
|
27
|
-
* -
|
|
57
|
+
* The client-chosen session channel is accepted in the standard
|
|
58
|
+
* `ahp-session:/<suffix>` form or the non-standard `<scheme>:/<suffix>`
|
|
59
|
+
* form (VS Code's legacy addressing and the AHP reference client both
|
|
60
|
+
* send `<provider>:/<uuid>`); it is echoed back verbatim and stays
|
|
61
|
+
* subscribable through the registry's session-channel set (design §6).
|
|
62
|
+
*
|
|
63
|
+
* Error codes: -32602 (invalid params, including `workingDirectories`),
|
|
64
|
+
* -32002 (no agent for the requested provider),
|
|
65
|
+
* -32003 (the session URI already exists),
|
|
66
|
+
* -32603 (backend session creation failure, e.g. the target location
|
|
67
|
+
* cannot be booted).
|
|
28
68
|
*/
|
|
29
69
|
protected async handleCreateSession(socketId: number, msg: RpcMessage): Promise<void> {
|
|
30
70
|
const params = isRecord(msg.params) ? msg.params : {};
|
|
31
71
|
const channel = params["channel"];
|
|
32
|
-
if (typeof channel !== "string" ||
|
|
33
|
-
|
|
72
|
+
if (typeof channel !== "string" || !isSessionChannel(channel)) {
|
|
73
|
+
// Log the offending channel — a -32602 here used to go out silently,
|
|
74
|
+
// which made a client's channel error unattributable on our side.
|
|
75
|
+
this.log(`createSession rejected: channel is not a session URI: ${JSON.stringify(channel)}`);
|
|
76
|
+
this.sendError(
|
|
77
|
+
socketId,
|
|
78
|
+
msg.id,
|
|
79
|
+
ERROR_INVALID_PARAMS,
|
|
80
|
+
`createSession requires a session channel (ahp-session:/… or <provider>:/…); got ${JSON.stringify(
|
|
81
|
+
channel,
|
|
82
|
+
)}`,
|
|
83
|
+
);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
// A channel already taken by a live pty terminal would leave two
|
|
87
|
+
// resource sets claiming one URI (dispatch resolves it as the
|
|
88
|
+
// session, the terminal becomes unreachable). Keep the sets disjoint.
|
|
89
|
+
if (this.channels.hasTerminal(channel)) {
|
|
90
|
+
this.log(`createSession rejected: channel is a live terminal channel: ${channel}`);
|
|
91
|
+
this.sendError(
|
|
92
|
+
socketId,
|
|
93
|
+
msg.id,
|
|
94
|
+
ERROR_INVALID_PARAMS,
|
|
95
|
+
`createSession channel ${channel} is already a live terminal channel`,
|
|
96
|
+
);
|
|
34
97
|
return;
|
|
35
98
|
}
|
|
36
99
|
const suffix = sessionIDOf(channel) as string;
|
|
@@ -82,20 +145,103 @@ export class HostSessions extends HostChats {
|
|
|
82
145
|
activeClients = [normalizeActiveClient(ac)];
|
|
83
146
|
}
|
|
84
147
|
|
|
148
|
+
// `workingDirectories` (AHP 1.0.0): the directory the session's
|
|
149
|
+
// agent is granted tool access to. The host advertises no
|
|
150
|
+
// multipleWorkingDirectories, so the spec applies — only the first
|
|
151
|
+
// entry is honored (extras are logged and ignored); it must be a
|
|
152
|
+
// `file://` URI. Absent → the session runs in the plugin's own
|
|
153
|
+
// location (opencode fills in the location). A directory that does
|
|
154
|
+
// not exist is rejected when opencode boots the target location —
|
|
155
|
+
// the createSession call below fails with a message.
|
|
156
|
+
let sessionDir: string | undefined;
|
|
157
|
+
const wdParam = params["workingDirectories"];
|
|
158
|
+
if (wdParam !== undefined) {
|
|
159
|
+
if (!Array.isArray(wdParam) || wdParam.length === 0) {
|
|
160
|
+
this.sendError(
|
|
161
|
+
socketId,
|
|
162
|
+
msg.id,
|
|
163
|
+
ERROR_INVALID_PARAMS,
|
|
164
|
+
"createSession `workingDirectories` must be a non-empty array of file URIs",
|
|
165
|
+
);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (wdParam.length > 1) {
|
|
169
|
+
this.log(
|
|
170
|
+
`createSession: ignoring ${wdParam.length - 1} extra workingDirectories (no multipleWorkingDirectories capability)`,
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
const first = wdParam[0];
|
|
174
|
+
if (typeof first !== "string" || first.length === 0) {
|
|
175
|
+
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createSession `workingDirectories`[0] must be a file URI");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
let dir: string;
|
|
179
|
+
try {
|
|
180
|
+
dir = fileURLToPath(first);
|
|
181
|
+
} catch {
|
|
182
|
+
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `createSession \`workingDirectories\`[0] is not a file URI: ${first}`);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
// A directory URI may carry a trailing slash (RFC 8089) — drop it
|
|
186
|
+
// so the record's directory is the plain path.
|
|
187
|
+
if (dir.length > 1 && dir.endsWith("/")) dir = dir.slice(0, -1);
|
|
188
|
+
if (dir.length === 0 || !isAbsolute(dir)) {
|
|
189
|
+
this.sendError(
|
|
190
|
+
socketId,
|
|
191
|
+
msg.id,
|
|
192
|
+
ERROR_INVALID_PARAMS,
|
|
193
|
+
`createSession \`workingDirectories\`[0] is not an absolute file URI: ${first}`,
|
|
194
|
+
);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
sessionDir = dir;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// The directory allowlist (the `allowedWorkingDirectories` option):
|
|
201
|
+
// when restricted, the target must resolve under one of the prefixes
|
|
202
|
+
// (after symlink resolution). A denial is a flat -32009 (the message
|
|
203
|
+
// is deliberately the same for every denied path — no existence
|
|
204
|
+
// oracle); the full detail goes to the log.
|
|
205
|
+
if (sessionDir !== undefined) {
|
|
206
|
+
const policy = this.opts.pathPolicy;
|
|
207
|
+
if (policy !== undefined && !(await policy.allows(sessionDir))) {
|
|
208
|
+
this.log(
|
|
209
|
+
`createSession: working directory ${sessionDir} is not permitted by host policy (channel: ${channel})`,
|
|
210
|
+
);
|
|
211
|
+
this.sendError(
|
|
212
|
+
socketId,
|
|
213
|
+
msg.id,
|
|
214
|
+
ERROR_PERMISSION_DENIED,
|
|
215
|
+
"working directory is not permitted by host policy",
|
|
216
|
+
);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
85
221
|
// opencode SessionIDs must start with "ses": pass the suffix through
|
|
86
222
|
// only when it already is one; otherwise let opencode mint an id and
|
|
87
223
|
// record the suffix→id mapping (the record key is the opencode id).
|
|
88
224
|
const passID = suffix.startsWith("ses") ? suffix : undefined;
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
225
|
+
let created;
|
|
226
|
+
try {
|
|
227
|
+
created = await this.opts.facade.createSession({
|
|
228
|
+
id: passID,
|
|
229
|
+
model,
|
|
230
|
+
// Durability: a minted-id default backend carries
|
|
231
|
+
// the client-chosen session channel in its opencode metadata —
|
|
232
|
+
// after a restart the session resurfaces under the ORIGINAL channel
|
|
233
|
+
// instead of its opencode id (a "ses" suffix IS the opencode id and
|
|
234
|
+
// needs no marker).
|
|
235
|
+
...(passID === undefined ? { metadata: { [AHP_METADATA_KEY]: { channel } } } : {}),
|
|
236
|
+
// A `workingDirectories` first entry targets that directory's
|
|
237
|
+
// location (opencode boots it on first use); absent → the plugin's
|
|
238
|
+
// own location (the plugin host fills it in).
|
|
239
|
+
...(sessionDir !== undefined ? { location: { directory: sessionDir } } : {}),
|
|
240
|
+
});
|
|
241
|
+
} catch (err) {
|
|
242
|
+
this.sendError(socketId, msg.id, ERROR_INTERNAL, `failed to create the session: ${errorMessage(err)}`);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
99
245
|
|
|
100
246
|
// Slow-create race: the pump may have registered this opencode session
|
|
101
247
|
// under its own id as an external session while `createSession` was in
|
|
@@ -114,11 +260,21 @@ export class HostSessions extends HostChats {
|
|
|
114
260
|
this.removeRecord(interim);
|
|
115
261
|
}
|
|
116
262
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
263
|
+
// The session customization catalog snapshot (design §7.5): the
|
|
264
|
+
// session's own working directory — the location directory for a
|
|
265
|
+
// session without one. Absent (the options never provide one)
|
|
266
|
+
// degrades to no catalog, mirroring the legacy agents-only
|
|
267
|
+
// behavior. The session's own `activeClient` tools are excluded
|
|
268
|
+
// too — the record is not registered yet, so the cross-session
|
|
269
|
+
// union does not carry them.
|
|
270
|
+
const catalogDir = sessionDir ?? this.opts.defaultDirectory;
|
|
271
|
+
const ownClientTools = new Set(
|
|
272
|
+
activeClients.flatMap((client) => client.tools.map((tool) => tool.name)),
|
|
273
|
+
);
|
|
274
|
+
const catalog =
|
|
275
|
+
catalogDir !== undefined
|
|
276
|
+
? await this.sessionCatalog(catalogDir, ownClientTools)
|
|
277
|
+
: { customizations: [], serverTools: [] as ToolDefinition[] };
|
|
122
278
|
const now = new Date().toISOString();
|
|
123
279
|
const sessionStore = createSessionStateStore(
|
|
124
280
|
initialSessionState({
|
|
@@ -126,8 +282,9 @@ export class HostSessions extends HostChats {
|
|
|
126
282
|
provider: created.model?.providerID ?? provider?.providerID ?? "opencode",
|
|
127
283
|
title: created.title ?? "New Session",
|
|
128
284
|
activeClients,
|
|
129
|
-
customizations,
|
|
130
|
-
|
|
285
|
+
customizations: catalog.customizations,
|
|
286
|
+
serverTools: catalog.serverTools,
|
|
287
|
+
workingDirectories: sessionDir !== undefined ? [directoryUri(sessionDir)] : this.workingDirectories(),
|
|
131
288
|
}),
|
|
132
289
|
);
|
|
133
290
|
const rec: SessionRecord = {
|
|
@@ -142,6 +299,7 @@ export class HostSessions extends HostChats {
|
|
|
142
299
|
chats: new Map(),
|
|
143
300
|
defaultChatURI: chatChannelURI(created.sessionID),
|
|
144
301
|
sessionChangesets: new Map(),
|
|
302
|
+
...(sessionDir !== undefined ? { directory: sessionDir } : {}),
|
|
145
303
|
};
|
|
146
304
|
this.sessions.set(created.sessionID, rec);
|
|
147
305
|
this.byChannel.set(channel, rec);
|
|
@@ -150,6 +308,10 @@ export class HostSessions extends HostChats {
|
|
|
150
308
|
// resolve in the registry.
|
|
151
309
|
this.channels.addSession(suffix);
|
|
152
310
|
this.channels.addSession(created.sessionID);
|
|
311
|
+
// The channel URI itself must stay subscribable — load-bearing for
|
|
312
|
+
// non-standard (legacy) session channels, which classify "unknown"
|
|
313
|
+
// by prefix and resolve only through this set.
|
|
314
|
+
this.channels.addSessionChannel(channel);
|
|
153
315
|
const defaultChat = this.newChatRuntime(rec.defaultChatURI, created.sessionID, "Chat 1", now);
|
|
154
316
|
this.bindChat(rec, defaultChat);
|
|
155
317
|
|
|
@@ -196,6 +358,58 @@ export class HostSessions extends HostChats {
|
|
|
196
358
|
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
|
|
197
359
|
}
|
|
198
360
|
|
|
361
|
+
/**
|
|
362
|
+
* `disposeSession` (AHP 1.0.0 session-channel command): dispose an AHP
|
|
363
|
+
* session and every opencode backend behind it — the default backend
|
|
364
|
+
* and each peer chat's backend. Result: `null`; the client's removal
|
|
365
|
+
* signal is the `root/sessionRemoved` notification `removeRecord`
|
|
366
|
+
* publishes (with the `root/activeSessionsChanged` count update),
|
|
367
|
+
* which always precedes the response. The channel is accepted in the
|
|
368
|
+
* same standard/legacy forms `createSession` echoes back, and an
|
|
369
|
+
* unknown channel answers -32001 (a channel that was a session but is
|
|
370
|
+
* already gone — e.g. disposed twice or deleted in the TUI first).
|
|
371
|
+
*
|
|
372
|
+
* The AHP-side unbind goes FIRST (the same race guard as
|
|
373
|
+
* `disposeChatBackend`): opencode's `session.deleted` event for each
|
|
374
|
+
* backend races this call through the event pump, and the pump's
|
|
375
|
+
* `byOpencode` guard must see the bindings already dropped — for the
|
|
376
|
+
* default backend a late binding would run `removeRecord` a second
|
|
377
|
+
* time (duplicate `root/sessionRemoved`), for a peer it would publish
|
|
378
|
+
* a `session/chatRemoved` for a chat whose record is already gone.
|
|
379
|
+
* `removeRecord` fires the peer backends' removals on the way (its
|
|
380
|
+
* standing behavior for the external-deletion path); the default
|
|
381
|
+
* backend is removed here, awaited, so a `listSessions` after the
|
|
382
|
+
* response does not resurface it lazily. R2: a failed backend removal
|
|
383
|
+
* still drops the AHP session — the lingering opencode session shows
|
|
384
|
+
* up in the TUI (and lazily in `listSessions`) until deleted there.
|
|
385
|
+
*/
|
|
386
|
+
protected async handleDisposeSession(socketId: number, msg: RpcMessage): Promise<void> {
|
|
387
|
+
const params = isRecord(msg.params) ? msg.params : {};
|
|
388
|
+
const channel = params["channel"];
|
|
389
|
+
if (typeof channel !== "string" || !isSessionChannel(channel)) {
|
|
390
|
+
this.sendError(
|
|
391
|
+
socketId,
|
|
392
|
+
msg.id,
|
|
393
|
+
ERROR_INVALID_PARAMS,
|
|
394
|
+
"disposeSession requires a session channel (ahp-session:/… or <provider>:/…)",
|
|
395
|
+
);
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const rec = this.byChannel.get(channel);
|
|
399
|
+
if (rec === undefined) {
|
|
400
|
+
this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such session: ${channel}`);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const defaultBackend = rec.sessionID;
|
|
404
|
+
this.removeRecord(rec);
|
|
405
|
+
try {
|
|
406
|
+
await this.opts.facade.removeSession(defaultBackend);
|
|
407
|
+
} catch (err) {
|
|
408
|
+
this.log(`failed to remove the session's opencode session ${defaultBackend}: ${errorMessage(err)}`);
|
|
409
|
+
}
|
|
410
|
+
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
|
|
411
|
+
}
|
|
412
|
+
|
|
199
413
|
/**
|
|
200
414
|
* `listSessions` (AHP 1.0.0 root command): all opencode sessions,
|
|
201
415
|
* most-recently-modified first, with in-memory cursor pagination.
|
|
@@ -244,10 +458,12 @@ export class HostSessions extends HostChats {
|
|
|
244
458
|
* agent/model choice rides session-state customizations and the
|
|
245
459
|
* per-turn message — so the honest answer is an empty schema with
|
|
246
460
|
* empty values. `provider` / `workingDirectory` / `config` are
|
|
247
|
-
* accepted and deliberately unused:
|
|
248
|
-
*
|
|
249
|
-
*
|
|
250
|
-
*
|
|
461
|
+
* accepted and deliberately unused: a session's working directory
|
|
462
|
+
* comes from `createSession`'s `workingDirectories` (the location
|
|
463
|
+
* directory when absent), and the host advertises no config
|
|
464
|
+
* properties (which also keeps `sessionConfigCompletions` unreachable
|
|
465
|
+
* — it only serves `enumDynamic` properties this schema does not
|
|
466
|
+
* carry).
|
|
251
467
|
*/
|
|
252
468
|
protected handleResolveSessionConfig(socketId: number, msg: RpcMessage): void {
|
|
253
469
|
const params = isRecord(msg.params) ? msg.params : {};
|
|
@@ -286,6 +502,64 @@ export class HostSessions extends HostChats {
|
|
|
286
502
|
this.registerExternal(fs);
|
|
287
503
|
}
|
|
288
504
|
|
|
505
|
+
/**
|
|
506
|
+
* The session customization catalog snapshot (design §7.5): the
|
|
507
|
+
* location's agents (their directory container), skills (the
|
|
508
|
+
* sibling directory container), MCP servers (top-level entries),
|
|
509
|
+
* and the server tools (opencode's registry minus the names the
|
|
510
|
+
* cross-session active-client union contributes). Every list is an
|
|
511
|
+
* independent R2 seam — a failure logs and degrades to empty, the
|
|
512
|
+
* session is created or registered either way.
|
|
513
|
+
*
|
|
514
|
+
* Location-scoped: the facade lists read the host's own location,
|
|
515
|
+
* so a cross-location session shows the host location's catalog
|
|
516
|
+
* (the same provenance caveat as the agents).
|
|
517
|
+
*
|
|
518
|
+
* `extraExcluded` seeds the server-tools exclusion set with names
|
|
519
|
+
* that are client-contributed but not in the cross-session union
|
|
520
|
+
* yet — the session's own `createSession.activeClient` tools, whose
|
|
521
|
+
* record does not exist while the snapshot runs.
|
|
522
|
+
*/
|
|
523
|
+
private async sessionCatalog(directory: string, extraExcluded?: ReadonlySet<string>): Promise<{
|
|
524
|
+
customizations: Customization[];
|
|
525
|
+
serverTools: ToolDefinition[];
|
|
526
|
+
}> {
|
|
527
|
+
const [agents, skills, mcpServers, tools] = await Promise.all([
|
|
528
|
+
this.opts.facade.listAgents().catch((err): FacadeAgent[] => {
|
|
529
|
+
this.log(`catalog listAgents failed: ${errorMessage(err)}`);
|
|
530
|
+
return [];
|
|
531
|
+
}),
|
|
532
|
+
this.opts.facade.listSkills().catch((err): FacadeSkill[] => {
|
|
533
|
+
this.log(`catalog listSkills failed: ${errorMessage(err)}`);
|
|
534
|
+
return [];
|
|
535
|
+
}),
|
|
536
|
+
this.opts.facade.listMcpServers().catch((err): FacadeMcpServer[] => {
|
|
537
|
+
this.log(`catalog listMcpServers failed: ${errorMessage(err)}`);
|
|
538
|
+
return [];
|
|
539
|
+
}),
|
|
540
|
+
this.opts.facade.listTools().catch((err): FacadeTool[] => {
|
|
541
|
+
this.log(`catalog listTools failed: ${errorMessage(err)}`);
|
|
542
|
+
return [];
|
|
543
|
+
}),
|
|
544
|
+
]);
|
|
545
|
+
const customizations: Customization[] = [];
|
|
546
|
+
if (mapAgentCustomizations(agents).length > 0) {
|
|
547
|
+
customizations.push(agentDirectoryCustomization(directory, agents));
|
|
548
|
+
}
|
|
549
|
+
if (skills.length > 0) {
|
|
550
|
+
customizations.push(skillDirectoryCustomization(directory, skills));
|
|
551
|
+
}
|
|
552
|
+
customizations.push(...mapMcpServerCustomizations(mcpServers, directory));
|
|
553
|
+
const excluded = new Set(this.clientToolNames());
|
|
554
|
+
if (extraExcluded !== undefined) {
|
|
555
|
+
for (const name of extraExcluded) excluded.add(name);
|
|
556
|
+
}
|
|
557
|
+
return {
|
|
558
|
+
customizations,
|
|
559
|
+
serverTools: mapServerTools(tools, excluded),
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
289
563
|
/**
|
|
290
564
|
* Register an opencode session the host did not create (TUI, another
|
|
291
565
|
* client, or a session resurfacing after a restart).
|
|
@@ -455,6 +729,9 @@ export class HostSessions extends HostChats {
|
|
|
455
729
|
private registerExternalStandalone(fs: FacadeSession, channel?: string): SessionRecord {
|
|
456
730
|
const recChannel = channel ?? sessionChannelURI(fs.sessionID);
|
|
457
731
|
const modifiedAt = new Date(fs.time.updated).toISOString();
|
|
732
|
+
// The session's own location (a cross-location session — created with
|
|
733
|
+
// `workingDirectories` or elsewhere) — its working directory.
|
|
734
|
+
const sessionDir = fs.location?.directory;
|
|
458
735
|
const sessionStore = createSessionStateStore(
|
|
459
736
|
initialSessionState({
|
|
460
737
|
sessionID: fs.sessionID,
|
|
@@ -463,7 +740,7 @@ export class HostSessions extends HostChats {
|
|
|
463
740
|
status: fs.archived
|
|
464
741
|
? ((SessionStatus.Idle | SessionStatus.IsRead | SessionStatus.IsArchived) as SessionStatus)
|
|
465
742
|
: undefined, // Idle | IsRead | IsArchived
|
|
466
|
-
workingDirectories: this.workingDirectories(),
|
|
743
|
+
workingDirectories: sessionDir !== undefined ? [directoryUri(sessionDir)] : this.workingDirectories(),
|
|
467
744
|
}),
|
|
468
745
|
);
|
|
469
746
|
const rec: SessionRecord = {
|
|
@@ -476,6 +753,7 @@ export class HostSessions extends HostChats {
|
|
|
476
753
|
chats: new Map(),
|
|
477
754
|
defaultChatURI: chatChannelURI(fs.sessionID),
|
|
478
755
|
sessionChangesets: new Map(),
|
|
756
|
+
...(sessionDir !== undefined ? { directory: sessionDir } : {}),
|
|
479
757
|
};
|
|
480
758
|
this.sessions.set(fs.sessionID, rec);
|
|
481
759
|
this.byChannel.set(recChannel, rec);
|
|
@@ -484,6 +762,9 @@ export class HostSessions extends HostChats {
|
|
|
484
762
|
// suffix too (mirroring `handleCreateSession`).
|
|
485
763
|
const suffix = sessionIDOf(recChannel) as string;
|
|
486
764
|
if (suffix !== fs.sessionID) this.channels.addSession(suffix);
|
|
765
|
+
// Mirrors `handleCreateSession`: the channel URI stays subscribable
|
|
766
|
+
// (load-bearing for non-standard legacy channels).
|
|
767
|
+
this.channels.addSessionChannel(recChannel);
|
|
487
768
|
const defaultChat = this.newChatRuntime(rec.defaultChatURI, fs.sessionID, "Chat 1", modifiedAt);
|
|
488
769
|
this.bindChat(rec, defaultChat);
|
|
489
770
|
sessionStore.apply({ type: ActionType.SessionReady });
|
|
@@ -508,9 +789,62 @@ export class HostSessions extends HostChats {
|
|
|
508
789
|
action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
|
|
509
790
|
});
|
|
510
791
|
this.notifyRoot("root/sessionAdded", { channel: ROOT_CHANNEL, summary: this.sessionSummary(rec) });
|
|
792
|
+
// The catalog snapshot cannot await the facade in this synchronous
|
|
793
|
+
// path — it lands as a fire-and-forget change-action pair after the
|
|
794
|
+
// announcement (design §7.5).
|
|
795
|
+
void this.syncExternalCatalog(rec);
|
|
511
796
|
return rec;
|
|
512
797
|
}
|
|
513
798
|
|
|
799
|
+
/**
|
|
800
|
+
* Fire-and-forget catalog application for an externally-registered
|
|
801
|
+
* session (design §7.5): snapshot the catalog, then apply
|
|
802
|
+
* `session/customizationsChanged` and `session/serverToolsChanged`
|
|
803
|
+
* (both full-replacement) to the LIVE store through `publish` —
|
|
804
|
+
* a client that subscribed in the meantime holds a snapshot without
|
|
805
|
+
* the catalog and receives the change actions; the store converges
|
|
806
|
+
* either way. Skipped when the record is already gone (removed
|
|
807
|
+
* mid-flight) and R2-guarded — the session stays usable, just
|
|
808
|
+
* without its customization surface.
|
|
809
|
+
*/
|
|
810
|
+
private async syncExternalCatalog(rec: SessionRecord): Promise<void> {
|
|
811
|
+
try {
|
|
812
|
+
const directory = rec.directory ?? this.opts.defaultDirectory;
|
|
813
|
+
if (directory === undefined) return;
|
|
814
|
+
const catalog = await this.sessionCatalog(directory);
|
|
815
|
+
if (this.sessions.get(rec.sessionID) !== rec) return; // removed mid-flight
|
|
816
|
+
if (catalog.customizations.length > 0) {
|
|
817
|
+
this.publish({
|
|
818
|
+
channel: rec.channel,
|
|
819
|
+
action: { type: ActionType.SessionCustomizationsChanged, customizations: catalog.customizations },
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
if (catalog.serverTools.length > 0) {
|
|
823
|
+
this.publish({
|
|
824
|
+
channel: rec.channel,
|
|
825
|
+
action: { type: ActionType.SessionServerToolsChanged, tools: catalog.serverTools },
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
} catch (err) {
|
|
829
|
+
this.log(`external session catalog sync failed: ${errorMessage(err)}`);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* Re-snapshot and re-push the per-location catalog (customizations +
|
|
835
|
+
* server tools, both full-replacement) to EVERY live session — for
|
|
836
|
+
* when a shared per-location input changes after registration (an
|
|
837
|
+
* MCP server toggled): each session's panel shows the same MCP
|
|
838
|
+
* entries and tool registry, so every session converges on the new
|
|
839
|
+
* state. Reuses the per-record sync (R2-guarded; records removed
|
|
840
|
+
* mid-flight are skipped).
|
|
841
|
+
*/
|
|
842
|
+
protected async reannounceCatalogs(): Promise<void> {
|
|
843
|
+
for (const rec of [...this.sessions.values()]) {
|
|
844
|
+
await this.syncExternalCatalog(rec);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
514
848
|
/** Drop a session record and announce the removal on the root channel. */
|
|
515
849
|
protected removeRecord(rec: SessionRecord): void {
|
|
516
850
|
const hadClients = rec.sessionStore.state.activeClients.length > 0;
|
|
@@ -544,6 +878,7 @@ export class HostSessions extends HostChats {
|
|
|
544
878
|
const id = sessionIDOf(rec.channel);
|
|
545
879
|
if (id !== null) this.channels.removeSession(id);
|
|
546
880
|
this.channels.removeSession(rec.sessionID);
|
|
881
|
+
this.channels.removeSessionChannel(rec.channel);
|
|
547
882
|
this.publish({
|
|
548
883
|
channel: ROOT_CHANNEL,
|
|
549
884
|
action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
|
package/src/host-terminals.ts
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
14
|
import { fileURLToPath } from "node:url";
|
|
15
|
-
import {
|
|
15
|
+
import { HostResources } from "./host-resources.js";
|
|
16
16
|
import {
|
|
17
17
|
ActionOrigin,
|
|
18
18
|
ActionType,
|
|
@@ -137,7 +137,7 @@ function unwrapAgentHostCwd(raw: string): string | null {
|
|
|
137
137
|
return url.pathname.length > 0 ? url.pathname : null;
|
|
138
138
|
}
|
|
139
139
|
|
|
140
|
-
export class HostTerminals extends
|
|
140
|
+
export class HostTerminals extends HostResources {
|
|
141
141
|
// ── pty terminals (createTerminal / disposeTerminal) ─────────────────
|
|
142
142
|
|
|
143
143
|
/**
|
|
@@ -165,7 +165,10 @@ export class HostTerminals extends HostChangesets {
|
|
|
165
165
|
}
|
|
166
166
|
// The channel must be client-chosen: anything that classifies as a
|
|
167
167
|
// host channel (ahp-root/session/chat/changeset/terminal) is refused —
|
|
168
|
-
// including the reserved `ahp-terminal:` synthetic prefix.
|
|
168
|
+
// including the reserved `ahp-terminal:` synthetic prefix. A
|
|
169
|
+
// non-standard (legacy) session channel classifies "unknown" by
|
|
170
|
+
// prefix but is refused while live — the two resource sets must stay
|
|
171
|
+
// disjoint (dispatch resolves such URIs as sessions).
|
|
169
172
|
if (channelKind(channel) !== "unknown") {
|
|
170
173
|
this.sendError(
|
|
171
174
|
socketId,
|
|
@@ -175,6 +178,15 @@ export class HostTerminals extends HostChangesets {
|
|
|
175
178
|
);
|
|
176
179
|
return;
|
|
177
180
|
}
|
|
181
|
+
if (this.channels.hasSessionChannel(channel)) {
|
|
182
|
+
this.sendError(
|
|
183
|
+
socketId,
|
|
184
|
+
msg.id,
|
|
185
|
+
ERROR_INVALID_REQUEST,
|
|
186
|
+
`createTerminal channel ${channel} is already a live session channel`,
|
|
187
|
+
);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
178
190
|
const socket = this.sockets.get(socketId);
|
|
179
191
|
const claim = normalizeTerminalClaim(params["claim"], socket?.clientId ?? null);
|
|
180
192
|
if (claim === null) {
|
|
@@ -195,7 +207,14 @@ export class HostTerminals extends HostChangesets {
|
|
|
195
207
|
this.sendError(socketId, msg.id, ERROR_METHOD_NOT_FOUND, "interactive terminal spawning is unavailable in this runtime");
|
|
196
208
|
return;
|
|
197
209
|
}
|
|
198
|
-
|
|
210
|
+
// A session claim scopes the cwd to that session's own working
|
|
211
|
+
// directory; a client claim (VS Code client-claims its pty terminals
|
|
212
|
+
// while opening them in the session's folder) may open in the
|
|
213
|
+
// location directory or in any live session's own working directory
|
|
214
|
+
// (see resolveTerminalCwd).
|
|
215
|
+
const sessionDir =
|
|
216
|
+
claim.kind === TerminalClaimKind.Session ? this.byChannel.get(claim.session)?.directory : undefined;
|
|
217
|
+
const cwd = this.resolveTerminalCwd(typeof params["cwd"] === "string" ? params["cwd"] : undefined, sessionDir);
|
|
199
218
|
const cols = positiveInt(params["cols"]) ?? 80;
|
|
200
219
|
const rows = positiveInt(params["rows"]) ?? 24;
|
|
201
220
|
const name = typeof params["name"] === "string" && params["name"].length > 0 ? params["name"] : undefined;
|
|
@@ -284,16 +303,24 @@ export class HostTerminals extends HostChangesets {
|
|
|
284
303
|
|
|
285
304
|
/**
|
|
286
305
|
* Resolve a `createTerminal` cwd to an absolute path inside the
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
* client
|
|
306
|
+
* terminal's confinement boundary. A session-claimed terminal is
|
|
307
|
+
* scoped to its session's own working directory. A client-claimed
|
|
308
|
+
* terminal (VS Code client-claims its pty terminals but opens them in
|
|
309
|
+
* the session's folder) may open in the location directory or in any
|
|
310
|
+
* live session's own working directory — the same confinement as
|
|
311
|
+
* `resourceRead` file targets (`containingSessionDir`). Accepted: a
|
|
312
|
+
* plain `file://` URI (what the VS Code client sends — it unwraps its
|
|
313
|
+
* own wrapper before the wire), the client's
|
|
314
|
+
* `vscode-agent-host:`/`agent-host:` wrapper (supported for
|
|
290
315
|
* robustness), and a bare absolute path. Anything malformed — and
|
|
291
|
-
* anything outside the
|
|
292
|
-
*
|
|
293
|
-
*
|
|
316
|
+
* anything outside the boundary — falls back to the boundary: the
|
|
317
|
+
* shell is a tool of the session's agent and must not be spawned
|
|
318
|
+
* outside its working roots.
|
|
294
319
|
*/
|
|
295
|
-
protected resolveTerminalCwd(raw: string | undefined): string {
|
|
296
|
-
|
|
320
|
+
protected resolveTerminalCwd(raw: string | undefined, sessionDir?: string): string {
|
|
321
|
+
// The fallback when no usable cwd is given: the claimed session's
|
|
322
|
+
// working directory, else the location directory.
|
|
323
|
+
const fallback = sessionDir ?? this.opts.defaultDirectory ?? process.cwd();
|
|
297
324
|
if (raw === undefined || raw.length === 0) return fallback;
|
|
298
325
|
let path: string | null = null;
|
|
299
326
|
if (raw.startsWith("file://")) {
|
|
@@ -311,8 +338,14 @@ export class HostTerminals extends HostChangesets {
|
|
|
311
338
|
this.log(`terminal cwd ${raw} is not a usable path; falling back to ${fallback}`);
|
|
312
339
|
return fallback;
|
|
313
340
|
}
|
|
314
|
-
|
|
315
|
-
|
|
341
|
+
// The clamp boundary: the claimed session's working directory, else
|
|
342
|
+
// the directory containing the requested cwd among the location
|
|
343
|
+
// directory and the live sessions' own directories (a client-claimed
|
|
344
|
+
// terminal opened in a cross-location session's folder), else the
|
|
345
|
+
// location directory.
|
|
346
|
+
const boundary = sessionDir ?? this.containingSessionDir(path) ?? this.opts.defaultDirectory;
|
|
347
|
+
if (boundary !== undefined && !isPathInside(path, boundary)) {
|
|
348
|
+
this.log(`terminal cwd ${path} is outside the session's working directory; clamping to ${fallback}`);
|
|
316
349
|
return fallback;
|
|
317
350
|
}
|
|
318
351
|
return path;
|
|
@@ -570,7 +603,6 @@ export class HostTerminals extends HostChangesets {
|
|
|
570
603
|
* record itself is retained (retention); only the state moves on.
|
|
571
604
|
*/
|
|
572
605
|
protected finishTerminal(
|
|
573
|
-
chat: ChatRuntime,
|
|
574
606
|
toolCallId: string,
|
|
575
607
|
result: { ok: true; content: FacadeToolContent[] } | { ok: false; message: string },
|
|
576
608
|
): void {
|