opencode-ahp 0.1.8 → 0.1.9

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.
@@ -3,13 +3,39 @@
3
3
  */
4
4
 
5
5
  import { HostChats } from "./host-chats.js";
6
- import { ActionType, SessionStatus, ResolveSessionConfigResult, SessionActiveClient, SessionSummary } from "@microsoft/agent-host-protocol";
7
- import { agentDirectoryCustomization, chatChangesetCatalog, chatSummaryOf, directoryUri, initialSessionState, mapAgentCustomizations, sessionChangesetCatalog, FacadeSession } from "./bridge.js";
8
- import { ROOT_CHANNEL, channelKind, chatChannelURI, sessionChannelURI, sessionIDOf } from "./channels.js";
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 } 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
- * Error codes: -32002 (no agent for the requested provider),
27
- * -32003 (the session URI already exists).
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" || channelKind(channel) !== "session") {
33
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createSession requires an ahp-session:/… channel");
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
- const created = await this.opts.facade.createSession({
90
- id: passID,
91
- model,
92
- // Durability: a minted-id default backend carries
93
- // the client-chosen session channel in its opencode metadata —
94
- // after a restart the session resurfaces under the ORIGINAL channel
95
- // instead of its opencode id (a "ses" suffix IS the opencode id and
96
- // needs no marker).
97
- ...(passID === undefined ? { metadata: { [AHP_METADATA_KEY]: { channel } } } : {}),
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
- const agents = await this.opts.facade.listAgents();
118
- const customizations =
119
- mapAgentCustomizations(agents).length > 0 && this.opts.defaultDirectory !== undefined
120
- ? [agentDirectoryCustomization(this.opts.defaultDirectory, agents)]
121
- : undefined;
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
- workingDirectories: this.workingDirectories(),
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
 
@@ -244,10 +406,12 @@ export class HostSessions extends HostChats {
244
406
  * agent/model choice rides session-state customizations and the
245
407
  * per-turn message — so the honest answer is an empty schema with
246
408
  * empty values. `provider` / `workingDirectory` / `config` are
247
- * accepted and deliberately unused: sessions run in the location
248
- * directory and the host advertises no config properties (which also
249
- * keeps `sessionConfigCompletions` unreachable — it only serves
250
- * `enumDynamic` properties this schema does not carry).
409
+ * accepted and deliberately unused: a session's working directory
410
+ * comes from `createSession`'s `workingDirectories` (the location
411
+ * directory when absent), and the host advertises no config
412
+ * properties (which also keeps `sessionConfigCompletions` unreachable
413
+ * — it only serves `enumDynamic` properties this schema does not
414
+ * carry).
251
415
  */
252
416
  protected handleResolveSessionConfig(socketId: number, msg: RpcMessage): void {
253
417
  const params = isRecord(msg.params) ? msg.params : {};
@@ -286,6 +450,64 @@ export class HostSessions extends HostChats {
286
450
  this.registerExternal(fs);
287
451
  }
288
452
 
453
+ /**
454
+ * The session customization catalog snapshot (design §7.5): the
455
+ * location's agents (their directory container), skills (the
456
+ * sibling directory container), MCP servers (top-level entries),
457
+ * and the server tools (opencode's registry minus the names the
458
+ * cross-session active-client union contributes). Every list is an
459
+ * independent R2 seam — a failure logs and degrades to empty, the
460
+ * session is created or registered either way.
461
+ *
462
+ * Location-scoped: the facade lists read the host's own location,
463
+ * so a cross-location session shows the host location's catalog
464
+ * (the same provenance caveat as the agents).
465
+ *
466
+ * `extraExcluded` seeds the server-tools exclusion set with names
467
+ * that are client-contributed but not in the cross-session union
468
+ * yet — the session's own `createSession.activeClient` tools, whose
469
+ * record does not exist while the snapshot runs.
470
+ */
471
+ private async sessionCatalog(directory: string, extraExcluded?: ReadonlySet<string>): Promise<{
472
+ customizations: Customization[];
473
+ serverTools: ToolDefinition[];
474
+ }> {
475
+ const [agents, skills, mcpServers, tools] = await Promise.all([
476
+ this.opts.facade.listAgents().catch((err): FacadeAgent[] => {
477
+ this.log(`catalog listAgents failed: ${errorMessage(err)}`);
478
+ return [];
479
+ }),
480
+ this.opts.facade.listSkills().catch((err): FacadeSkill[] => {
481
+ this.log(`catalog listSkills failed: ${errorMessage(err)}`);
482
+ return [];
483
+ }),
484
+ this.opts.facade.listMcpServers().catch((err): FacadeMcpServer[] => {
485
+ this.log(`catalog listMcpServers failed: ${errorMessage(err)}`);
486
+ return [];
487
+ }),
488
+ this.opts.facade.listTools().catch((err): FacadeTool[] => {
489
+ this.log(`catalog listTools failed: ${errorMessage(err)}`);
490
+ return [];
491
+ }),
492
+ ]);
493
+ const customizations: Customization[] = [];
494
+ if (mapAgentCustomizations(agents).length > 0) {
495
+ customizations.push(agentDirectoryCustomization(directory, agents));
496
+ }
497
+ if (skills.length > 0) {
498
+ customizations.push(skillDirectoryCustomization(directory, skills));
499
+ }
500
+ customizations.push(...mapMcpServerCustomizations(mcpServers, directory));
501
+ const excluded = new Set(this.clientToolNames());
502
+ if (extraExcluded !== undefined) {
503
+ for (const name of extraExcluded) excluded.add(name);
504
+ }
505
+ return {
506
+ customizations,
507
+ serverTools: mapServerTools(tools, excluded),
508
+ };
509
+ }
510
+
289
511
  /**
290
512
  * Register an opencode session the host did not create (TUI, another
291
513
  * client, or a session resurfacing after a restart).
@@ -455,6 +677,9 @@ export class HostSessions extends HostChats {
455
677
  private registerExternalStandalone(fs: FacadeSession, channel?: string): SessionRecord {
456
678
  const recChannel = channel ?? sessionChannelURI(fs.sessionID);
457
679
  const modifiedAt = new Date(fs.time.updated).toISOString();
680
+ // The session's own location (a cross-location session — created with
681
+ // `workingDirectories` or elsewhere) — its working directory.
682
+ const sessionDir = fs.location?.directory;
458
683
  const sessionStore = createSessionStateStore(
459
684
  initialSessionState({
460
685
  sessionID: fs.sessionID,
@@ -463,7 +688,7 @@ export class HostSessions extends HostChats {
463
688
  status: fs.archived
464
689
  ? ((SessionStatus.Idle | SessionStatus.IsRead | SessionStatus.IsArchived) as SessionStatus)
465
690
  : undefined, // Idle | IsRead | IsArchived
466
- workingDirectories: this.workingDirectories(),
691
+ workingDirectories: sessionDir !== undefined ? [directoryUri(sessionDir)] : this.workingDirectories(),
467
692
  }),
468
693
  );
469
694
  const rec: SessionRecord = {
@@ -476,6 +701,7 @@ export class HostSessions extends HostChats {
476
701
  chats: new Map(),
477
702
  defaultChatURI: chatChannelURI(fs.sessionID),
478
703
  sessionChangesets: new Map(),
704
+ ...(sessionDir !== undefined ? { directory: sessionDir } : {}),
479
705
  };
480
706
  this.sessions.set(fs.sessionID, rec);
481
707
  this.byChannel.set(recChannel, rec);
@@ -484,6 +710,9 @@ export class HostSessions extends HostChats {
484
710
  // suffix too (mirroring `handleCreateSession`).
485
711
  const suffix = sessionIDOf(recChannel) as string;
486
712
  if (suffix !== fs.sessionID) this.channels.addSession(suffix);
713
+ // Mirrors `handleCreateSession`: the channel URI stays subscribable
714
+ // (load-bearing for non-standard legacy channels).
715
+ this.channels.addSessionChannel(recChannel);
487
716
  const defaultChat = this.newChatRuntime(rec.defaultChatURI, fs.sessionID, "Chat 1", modifiedAt);
488
717
  this.bindChat(rec, defaultChat);
489
718
  sessionStore.apply({ type: ActionType.SessionReady });
@@ -508,9 +737,62 @@ export class HostSessions extends HostChats {
508
737
  action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
509
738
  });
510
739
  this.notifyRoot("root/sessionAdded", { channel: ROOT_CHANNEL, summary: this.sessionSummary(rec) });
740
+ // The catalog snapshot cannot await the facade in this synchronous
741
+ // path — it lands as a fire-and-forget change-action pair after the
742
+ // announcement (design §7.5).
743
+ void this.syncExternalCatalog(rec);
511
744
  return rec;
512
745
  }
513
746
 
747
+ /**
748
+ * Fire-and-forget catalog application for an externally-registered
749
+ * session (design §7.5): snapshot the catalog, then apply
750
+ * `session/customizationsChanged` and `session/serverToolsChanged`
751
+ * (both full-replacement) to the LIVE store through `publish` —
752
+ * a client that subscribed in the meantime holds a snapshot without
753
+ * the catalog and receives the change actions; the store converges
754
+ * either way. Skipped when the record is already gone (removed
755
+ * mid-flight) and R2-guarded — the session stays usable, just
756
+ * without its customization surface.
757
+ */
758
+ private async syncExternalCatalog(rec: SessionRecord): Promise<void> {
759
+ try {
760
+ const directory = rec.directory ?? this.opts.defaultDirectory;
761
+ if (directory === undefined) return;
762
+ const catalog = await this.sessionCatalog(directory);
763
+ if (this.sessions.get(rec.sessionID) !== rec) return; // removed mid-flight
764
+ if (catalog.customizations.length > 0) {
765
+ this.publish({
766
+ channel: rec.channel,
767
+ action: { type: ActionType.SessionCustomizationsChanged, customizations: catalog.customizations },
768
+ });
769
+ }
770
+ if (catalog.serverTools.length > 0) {
771
+ this.publish({
772
+ channel: rec.channel,
773
+ action: { type: ActionType.SessionServerToolsChanged, tools: catalog.serverTools },
774
+ });
775
+ }
776
+ } catch (err) {
777
+ this.log(`external session catalog sync failed: ${errorMessage(err)}`);
778
+ }
779
+ }
780
+
781
+ /**
782
+ * Re-snapshot and re-push the per-location catalog (customizations +
783
+ * server tools, both full-replacement) to EVERY live session — for
784
+ * when a shared per-location input changes after registration (an
785
+ * MCP server toggled): each session's panel shows the same MCP
786
+ * entries and tool registry, so every session converges on the new
787
+ * state. Reuses the per-record sync (R2-guarded; records removed
788
+ * mid-flight are skipped).
789
+ */
790
+ protected async reannounceCatalogs(): Promise<void> {
791
+ for (const rec of [...this.sessions.values()]) {
792
+ await this.syncExternalCatalog(rec);
793
+ }
794
+ }
795
+
514
796
  /** Drop a session record and announce the removal on the root channel. */
515
797
  protected removeRecord(rec: SessionRecord): void {
516
798
  const hadClients = rec.sessionStore.state.activeClients.length > 0;
@@ -544,6 +826,7 @@ export class HostSessions extends HostChats {
544
826
  const id = sessionIDOf(rec.channel);
545
827
  if (id !== null) this.channels.removeSession(id);
546
828
  this.channels.removeSession(rec.sessionID);
829
+ this.channels.removeSessionChannel(rec.channel);
547
830
  this.publish({
548
831
  channel: ROOT_CHANNEL,
549
832
  action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
@@ -12,7 +12,7 @@
12
12
  */
13
13
 
14
14
  import { fileURLToPath } from "node:url";
15
- import { HostChangesets } from "./host-changesets.js";
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 HostChangesets {
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
- const cwd = this.resolveTerminalCwd(typeof params["cwd"] === "string" ? params["cwd"] : undefined);
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
- * location directory. Accepted: a plain `file://` URI (what the VS
288
- * Code client sends — it unwraps its own wrapper before the wire), the
289
- * client's `vscode-agent-host:`/`agent-host:` wrapper (supported for
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 location directory — falls back to the location
292
- * directory: the shell is a tool of the session's agent and must not
293
- * be spawned outside its working root.
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
- const fallback = this.opts.defaultDirectory ?? process.cwd();
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
- if (this.opts.defaultDirectory !== undefined && !isPathInside(path, this.opts.defaultDirectory)) {
315
- this.log(`terminal cwd ${path} is outside the location directory; clamping to ${fallback}`);
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;
package/src/host-types.ts CHANGED
@@ -6,6 +6,7 @@ import { ActionType, ReconnectResultType, Implementation, SessionSummary } from
6
6
  import { OpencodeFacade } from "./bridge.js";
7
7
  import { ClientToolInvocation } from "./client-tools.js";
8
8
  import { ChatStateStore, ChangesetStateStore, SessionStateStore, TerminalStateStore } from "./state.js";
9
+ import type { PathPolicy } from "./path-policy.js";
9
10
 
10
11
  // ActionType / ReconnectResultType are `declare const enum` in the package
11
12
  // but are also real runtime objects (verified against the published dist),
@@ -111,6 +112,14 @@ export interface SessionRecord {
111
112
  defaultChatURI: string;
112
113
  /** The session-kind changeset store (owned by the session channel). */
113
114
  sessionChangesets: Map<string, ChangesetStateStore>;
115
+ /**
116
+ * The directory the session's agent has tool access to (its
117
+ * `workingDirectories` first entry, or the location directory the
118
+ * session was created in). `undefined` for legacy sessions created
119
+ * before working-directory support — they behave as if they live in
120
+ * the location directory.
121
+ */
122
+ directory?: string;
114
123
  }
115
124
 
116
125
  /**
@@ -217,6 +226,14 @@ export interface HostOptions {
217
226
  * entry provides the Bun-backed factory; tests inject a fake.
218
227
  */
219
228
  spawnPty?: SpawnPty;
229
+ /**
230
+ * The directory allowlist (the `allowedWorkingDirectories` option,
231
+ * design §3.3): undefined → unrestricted. When restricted, a
232
+ * client-named path must resolve under one of the prefixes (after
233
+ * symlink resolution) — the `createSession.workingDirectories` target
234
+ * and the unconfined `resource*` commands; a denial is a flat -32009.
235
+ */
236
+ pathPolicy?: PathPolicy;
220
237
  /** Deliver a JSON-serializable frame to a connection. */
221
238
  send: (socketId: number, message: unknown) => void;
222
239
  /** Close one connection (a superseded duplicate clientId). */
package/src/host-util.ts CHANGED
@@ -6,7 +6,7 @@ import { resolve as resolvePath } from "node:path";
6
6
  import { ToolResultContentType, SessionActiveClient, StringOrMarkdown, ToolCallResult, ToolResultContent } from "@microsoft/agent-host-protocol";
7
7
  import { FacadeClientToolResult, FacadeModelRef, FacadeToolContent } from "./bridge.js";
8
8
  import { normalizeToolDefinitions } from "./client-tools.js";
9
- import { channelKind } from "./channels.js";
9
+ import { channelKind, isSessionChannel } from "./channels.js";
10
10
  import { isRecord } from "./options.js";
11
11
 
12
12
  /**
@@ -69,7 +69,10 @@ export function parseAhpMarker(metadata: unknown): { chat?: string; owner?: stri
69
69
  const owner = marker["owner"];
70
70
  if (typeof owner === "string" && owner.startsWith("ses")) out.owner = owner;
71
71
  const channel = marker["channel"];
72
- if (typeof channel === "string" && channelKind(channel) === "session") out.channel = channel;
72
+ // isSessionChannel, not channelKind === "session": a session created
73
+ // on a non-standard (legacy) channel must resurface under the ORIGINAL
74
+ // channel after a restart, not fall back to the opencode id.
75
+ if (typeof channel === "string" && isSessionChannel(channel)) out.channel = channel;
73
76
  return Object.keys(out).length > 0 ? out : null;
74
77
  }
75
78
 
@@ -188,5 +191,8 @@ export function mapToolResultContent(content: readonly { type: string; text?: st
188
191
  export function isPathInside(child: string, parent: string): boolean {
189
192
  const a = resolvePath(child);
190
193
  const b = resolvePath(parent);
194
+ // The root contains every absolute path (the `b + "/"` join would
195
+ // otherwise compare against `"//"`).
196
+ if (b === "/") return a === "/" || a.startsWith("/");
191
197
  return a === b || a.startsWith(b + "/");
192
198
  }
package/src/host.ts CHANGED
@@ -38,9 +38,9 @@
38
38
  * `root/activeSessionsChanged` is a sequencer action.
39
39
  *
40
40
  * Module layout: this file only composes the host — the section classes
41
- * (host-base.ts → host-changesets.ts → host-terminals.ts → host-turns.ts →
42
- * host-client-tools.ts → host-chats.ts → host-sessions.ts → host-dispatch.ts →
43
- * host-events.ts → host-rpc.ts) form a linear chain, each extending the
41
+ * (host-base.ts → host-changesets.ts → host-resources.ts → host-terminals.ts
42
+ * → host-turns.ts → host-client-tools.ts → host-chats.ts → host-sessions.ts
43
+ * → host-dispatch.ts → host-events.ts → host-rpc.ts) form a linear chain, each extending the
44
44
  * previous one; shared state lives in HostBase, and a section may only
45
45
  * call members declared at or below it in the chain (that is what keeps
46
46
  * the split type-safe).