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.
package/src/bridge.ts CHANGED
@@ -14,8 +14,10 @@ import { sessionChangesetURI, turnChangesetURI, uncommittedChangesetURI } from "
14
14
  import {
15
15
  ChangesetOperationScope,
16
16
  ChangesetOperationStatus,
17
+ CustomizationEnablementKind,
17
18
  CustomizationLoadStatus,
18
19
  CustomizationType,
20
+ McpServerStatus,
19
21
  MessageKind,
20
22
  SessionLifecycle,
21
23
  SessionStatus,
@@ -29,11 +31,15 @@ import {
29
31
  type Customization,
30
32
  type DirectoryCustomization,
31
33
  type FileEdit,
34
+ type McpServerCustomization,
35
+ type McpServerState,
32
36
  type Message,
33
37
  type SessionActiveClient,
34
38
  type SessionState,
35
39
  type SessionSummary,
36
40
  type SessionModelInfo,
41
+ type SkillCustomization,
42
+ type ToolDefinition,
37
43
  } from "@microsoft/agent-host-protocol";
38
44
 
39
45
  export type ProviderActivation = "auto" | "enabled" | "disabled";
@@ -73,6 +79,51 @@ export interface FacadeAgent {
73
79
  hidden: boolean;
74
80
  }
75
81
 
82
+ /**
83
+ * An opencode MCP server's connection status (opencode `Mcp.Status`).
84
+ * The status, not the config: `ctx.mcp.list()` reports what is
85
+ * configured for the location as it stands right now.
86
+ */
87
+ export type FacadeMcpStatus = "connected" | "pending" | "disabled" | "failed" | "needs_auth";
88
+
89
+ /**
90
+ * Narrow opencode MCP server, from `ctx.mcp.list()`. `title` is the
91
+ * configured display name; `error` carries detail text for
92
+ * `failed` / `needs_auth` only.
93
+ */
94
+ export interface FacadeMcpServer {
95
+ name: string;
96
+ title?: string;
97
+ status: FacadeMcpStatus;
98
+ error?: string;
99
+ }
100
+
101
+ /**
102
+ * Narrow opencode skill, from `ctx.skill.list()`. `path` is an
103
+ * absolute filesystem path for on-disk skills, or a virtual URI for
104
+ * built-in ones (`skill://…`).
105
+ */
106
+ export interface FacadeSkill {
107
+ id: string;
108
+ name: string;
109
+ description?: string;
110
+ /** Absent or `true` = the model may auto-invoke; `false` = user-selected only. */
111
+ autoinvoke?: boolean;
112
+ path: string;
113
+ }
114
+
115
+ /**
116
+ * Narrow opencode tool, from `ctx.tool.list()`. `input` is the raw
117
+ * `Tool.Info.input` — an Effect codec, a Standard Schema instance, or
118
+ * a plain JSON-Schema object (the mapper is shape-detecting; the
119
+ * bridge keeps no schema-library dependency).
120
+ */
121
+ export interface FacadeTool {
122
+ name: string;
123
+ description?: string;
124
+ input?: unknown;
125
+ }
126
+
76
127
  export interface FacadeModelRef {
77
128
  providerID: string;
78
129
  modelID: string;
@@ -93,6 +144,13 @@ export interface FacadeSession {
93
144
  * restart; everything else is passed through opaquely.
94
145
  */
95
146
  metadata?: Record<string, unknown>;
147
+ /**
148
+ * The location the session lives in (opencode `SessionInfo.location`):
149
+ * the directory its agent has tool access to. A session created through
150
+ * this host with `workingDirectories` (or created elsewhere in another
151
+ * location) carries a directory other than the plugin's own location.
152
+ */
153
+ location?: { directory: string };
96
154
  }
97
155
 
98
156
  /** `SessionPromptInput.delivery` (steer | queue; absent = default). */
@@ -184,6 +242,25 @@ export interface OpencodeFacade {
184
242
  listCatalog(): Promise<readonly FacadeProvider[]>;
185
243
  /** Live opencode agents (`ctx.agent.list()`). */
186
244
  listAgents(): Promise<readonly FacadeAgent[]>;
245
+ // ── session customization catalog ────────────────────────────
246
+ /**
247
+ * The MCP servers configured for this location (`ctx.mcp.list()`) —
248
+ * names with their current connection status.
249
+ */
250
+ listMcpServers(): Promise<readonly FacadeMcpServer[]>;
251
+ /** The skills available in this location (`ctx.skill.list()`). */
252
+ listSkills(): Promise<readonly FacadeSkill[]>;
253
+ /** The tools registered in this location (`ctx.tool.list()`). */
254
+ listTools(): Promise<readonly FacadeTool[]>;
255
+ /**
256
+ * Toggle the `disabled` flag of a configured MCP server and re-reconcile
257
+ * the MCP registry (`ctx.mcp.transform` + `ctx.mcp.reload`). A disabled
258
+ * server is disconnected and reports status `disabled`; a re-enabled one
259
+ * connects again and the reload resolves only once the status is
260
+ * settled. Runtime-only: the config file is untouched and the decision
261
+ * is lost on location restart/reload.
262
+ */
263
+ setMcpDisabled(name: string, disabled: boolean): Promise<void>;
187
264
  // ── sessions ─────────────────────────────────────────────────
188
265
  /**
189
266
  * Create an opencode session. `id` is only passed through when it is a
@@ -196,6 +273,11 @@ export interface OpencodeFacade {
196
273
  model?: FacadeModelRef;
197
274
  /** Durable session metadata — the host's chat-binding marker rides here. */
198
275
  metadata?: Record<string, unknown>;
276
+ /**
277
+ * The location to create the session in (opencode v2: the target
278
+ * location boots on first use). Absent = the plugin's own location.
279
+ */
280
+ location?: { directory: string };
199
281
  }): Promise<FacadeSession>;
200
282
  /** All opencode sessions for this location. */
201
283
  listSessions(): Promise<readonly FacadeSession[]>;
@@ -230,16 +312,17 @@ export interface OpencodeFacade {
230
312
  // ── changesets ───────────────────────────────────────────────
231
313
  /**
232
314
  * Working-tree diff vs HEAD (uncommitted changes, untracked files
233
- * included), with **absolute** file paths. `[]` when the location is
315
+ * included), with **absolute** file paths, for `directory` (absent →
316
+ * the plugin's own location directory). `[]` when the directory is
234
317
  * not a git repo, has no changes, or the diff fails (R2: degrade to
235
318
  * empty, never throw).
236
319
  */
237
- vcsDiffWorking(): Promise<readonly FacadeDiffFile[]>;
320
+ vcsDiffWorking(directory?: string): Promise<readonly FacadeDiffFile[]>;
238
321
  /**
239
322
  * The file's content in HEAD (`git show HEAD:<rel>`), or null when the
240
- * location is not a repo, HEAD is missing, or the file is not tracked.
323
+ * repo is missing, HEAD is missing, or the file is not tracked.
241
324
  */
242
- gitHeadFile(absPath: string): Promise<string | null>;
325
+ gitHeadFile(absPath: string, directory?: string): Promise<string | null>;
243
326
  /** Read a UTF-8 file from disk, or null when it does not exist. */
244
327
  readFile(absPath: string): Promise<string | null>;
245
328
  /** Write a UTF-8 file (creating parent directories as needed). */
@@ -247,10 +330,33 @@ export interface OpencodeFacade {
247
330
  /** Delete a file; no-op when it does not exist. */
248
331
  deleteFile(absPath: string): Promise<void>;
249
332
  /**
250
- * Discard changes to one file: tracked → `git checkout HEAD -- <rel>`
251
- * (fallback delete), untracked → delete.
333
+ * Discard changes to one file in `directory` (absent → the plugin's
334
+ * own location): tracked → `git checkout HEAD -- <rel>` (fallback
335
+ * delete), untracked → delete.
336
+ */
337
+ discardFile(absPath: string, directory?: string): Promise<void>;
338
+ // ── resources ─────────────────────────────────────────────────
339
+ /**
340
+ * Resolve the metadata of an absolute filesystem path for
341
+ * `resourceResolve`. With `followSymlinks` true (the default),
342
+ * symlinks are followed and `path` in the result is the canonical
343
+ * (realpath) path; with false the link itself is stat'd and `type` is
344
+ * `symlink`. Throws a Node `ErrnoException` (ENOENT/EACCES/…) on
345
+ * failure — the host maps the code.
252
346
  */
253
- discardFile(absPath: string): Promise<void>;
347
+ resolveResource(absPath: string, followSymlinks?: boolean): Promise<FacadeResourceInfo>;
348
+ /**
349
+ * List one directory's entries (name + type only) for `resourceList`.
350
+ * Throws a Node `ErrnoException` when the path is missing, not a
351
+ * directory, or inaccessible.
352
+ */
353
+ listDirectory(absPath: string): Promise<readonly FacadeDirectoryEntry[]>;
354
+ /**
355
+ * Create a directory with all missing parents for `resourceMkdir`
356
+ * (`mkdir -p`: an existing directory is a no-op success). Throws a
357
+ * Node `ErrnoException` on failure.
358
+ */
359
+ mkdirResource(absPath: string): Promise<void>;
254
360
  // ── client-provided tools ─────────────────────────
255
361
  /**
256
362
  * Replace the location's registered client tools with `tools` (the
@@ -303,6 +409,26 @@ export interface FacadeDiffFile {
303
409
  status: "added" | "deleted" | "modified";
304
410
  }
305
411
 
412
+ /**
413
+ * The facade's shape of `resourceResolve` metadata. `path` is the
414
+ * canonical (realpath) path when `followSymlinks` was true; `mtime`/
415
+ * `ctime` are epoch milliseconds (the host formats the ISO strings).
416
+ */
417
+ export interface FacadeResourceInfo {
418
+ path: string;
419
+ type: "file" | "directory" | "symlink";
420
+ size: number;
421
+ mtime: number;
422
+ ctime: number;
423
+ }
424
+
425
+ /** One `resourceList` entry (name + type; no size/mtime — the spec's
426
+ * list result does not carry them). */
427
+ export interface FacadeDirectoryEntry {
428
+ name: string;
429
+ type: "file" | "directory";
430
+ }
431
+
306
432
  // ── catalog mappers ─────────────────────────────────────────────
307
433
 
308
434
  /**
@@ -354,7 +480,7 @@ export function mapAgentCustomizations(agents: readonly FacadeAgent[]): AgentCus
354
480
  * Attached to every `AgentInfo.customizations` (feeds the Agents
355
481
  * window's agent picker before any session exists) and to live
356
482
  * `SessionState.customizations` (the picker reads session-state
357
- * customizations — the root-cause fix for the empty dropdown, 2026-11-08).
483
+ * customizations — the root-cause fix for the empty dropdown).
358
484
  * `writable: false` — clients never write agents into the
359
485
  * workspace through this host.
360
486
  */
@@ -376,9 +502,217 @@ export function agentDirectoryCustomization(
376
502
  };
377
503
  }
378
504
 
505
+ /**
506
+ * A skill's `path` as a customization URI: an absolute filesystem
507
+ * path becomes a `file://` URI; a virtual path (built-in skills use
508
+ * `skill://…`) is already URI-shaped and passes through. Both are
509
+ * stable per skill, and id = uri (the host is the minting publisher).
510
+ */
511
+ export function skillUri(path: string): string {
512
+ return /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(path) ? path : pathToFileURL(path).href;
513
+ }
514
+
515
+ /**
516
+ * Map opencode skills to AHP `SkillCustomization` children:
517
+ * - `id` = `uri` = the skill's `path` (see {@link skillUri});
518
+ * - `autoinvoke === false` → `disableModelInvocation: true` (the
519
+ * model must not pick it; the user can still select it);
520
+ * - `description` passes through.
521
+ */
522
+ export function mapSkillCustomizations(skills: readonly FacadeSkill[]): SkillCustomization[] {
523
+ const out: SkillCustomization[] = [];
524
+ for (const skill of skills) {
525
+ const uri = skillUri(skill.path);
526
+ const child: SkillCustomization = {
527
+ type: CustomizationType.Skill,
528
+ id: uri,
529
+ uri,
530
+ name: skill.name,
531
+ };
532
+ if (skill.description !== undefined) child.description = skill.description;
533
+ if (skill.autoinvoke === false) child.disableModelInvocation = true;
534
+ out.push(child);
535
+ }
536
+ return out;
537
+ }
538
+
539
+ /**
540
+ * The skills directory container that carries the skill children —
541
+ * the sibling of {@link agentDirectoryCustomization}. A
542
+ * `DirectoryCustomization` holds a single child type
543
+ * (`contents` is singular), so skills get their own container over
544
+ * the same directory URI; the id is suffixed so both coexist in
545
+ * `SessionState.customizations`.
546
+ */
547
+ export function skillDirectoryCustomization(
548
+ directory: string,
549
+ skills: readonly FacadeSkill[],
550
+ ): DirectoryCustomization {
551
+ const name = directory.split(/[\\/]/).filter(Boolean).pop() ?? "workspace";
552
+ return {
553
+ type: CustomizationType.Directory,
554
+ id: `opencode:directory:${directory}:skills`,
555
+ uri: pathToFileURL(directory).href,
556
+ name,
557
+ enabled: true,
558
+ contents: CustomizationType.Skill,
559
+ writable: false,
560
+ load: { kind: CustomizationLoadStatus.Loaded },
561
+ children: mapSkillCustomizations(skills),
562
+ };
563
+ }
564
+
565
+ /** The id prefix of the host's MCP-server customization entries. */
566
+ export const MCP_CUSTOMIZATION_ID_PREFIX = "opencode:mcp/";
567
+
568
+ /**
569
+ * opencode's `Mcp.Status` → AHP `McpServerState`:
570
+ * - `connected` → ready, `pending` → starting, `disabled` → stopped;
571
+ * - `failed` → error (the status carries a message);
572
+ * - `needs_auth` → error too: AHP's `auth-required` state requires
573
+ * the RFC 9728 `ProtectedResourceMetadata` (an https `resource`
574
+ * URI), which opencode's status does not carry (message only) —
575
+ * the degradation keeps the panel honest without inventing a
576
+ * resource identifier.
577
+ */
578
+ export function mcpServerState(server: FacadeMcpServer): McpServerState {
579
+ switch (server.status) {
580
+ case "connected":
581
+ return { kind: McpServerStatus.Ready };
582
+ case "pending":
583
+ return { kind: McpServerStatus.Starting };
584
+ case "disabled":
585
+ return { kind: McpServerStatus.Stopped };
586
+ case "needs_auth":
587
+ return {
588
+ kind: McpServerStatus.Error,
589
+ error: {
590
+ errorType: "mcp.auth-required",
591
+ message: server.error ?? "MCP server requires authentication",
592
+ },
593
+ };
594
+ case "failed":
595
+ return {
596
+ kind: McpServerStatus.Error,
597
+ error: { errorType: "mcp.failed", message: server.error ?? "MCP server failed to start" },
598
+ };
599
+ }
600
+ }
601
+
602
+ /**
603
+ * Map opencode MCP servers to **top-level** AHP
604
+ * `McpServerCustomization` entries — the protocol's slot for a
605
+ * "globally-configured MCP server that isn't bundled in a plugin or
606
+ * directory":
607
+ * - `id` = `opencode:mcp/<name>` (stable per configured server);
608
+ * - `uri` = the session's directory URI (the server is configured
609
+ * for that directory's location — the closest provenance the
610
+ * status list carries);
611
+ * - `name` = the configured display title, falling back to the
612
+ * config name;
613
+ * - `enablement` = a single Workspace entry with `enabled: false`
614
+ * for a server whose status is `disabled` (file- or toggle-
615
+ * disabled — the status list does not distinguish). The panel's
616
+ * effective-enabled value is `enablement[0].enabled ?? true`, so
617
+ * an enabled server omits the field; without it the client would
618
+ * render the toggle as on while the state says `stopped`.
619
+ *
620
+ * Snapshot semantics: the state is whatever opencode reports when the
621
+ * session registers (or when the host re-snapshots after an MCP
622
+ * toggle — the re-push replaces the full customization list).
623
+ * opencode's `mcp.status.changed` event carries only the server name
624
+ * (no state payload) and is not otherwise acted on, so the host
625
+ * re-snapshots per registration rather than live-pushing (futures.md).
626
+ */
627
+ export function mapMcpServerCustomizations(
628
+ servers: readonly FacadeMcpServer[],
629
+ directory: string,
630
+ ): McpServerCustomization[] {
631
+ const uri = pathToFileURL(directory).href;
632
+ return servers.map((server) => ({
633
+ type: CustomizationType.McpServer,
634
+ id: `${MCP_CUSTOMIZATION_ID_PREFIX}${server.name}`,
635
+ uri,
636
+ name: server.title ?? server.name,
637
+ state: mcpServerState(server),
638
+ ...(server.status === "disabled"
639
+ ? { enablement: [{ kind: CustomizationEnablementKind.Workspace, uri, enabled: false }] }
640
+ : {}),
641
+ }));
642
+ }
643
+
644
+ /**
645
+ * A facade tool's raw `input` as an AHP `inputSchema`, or null when
646
+ * there is no input at all. The AHP shape is fixed
647
+ * (`{ type: "object", properties?, required? }`); opencode's
648
+ * `Tool.Info.input` is a union of three value-schema forms, and the
649
+ * bridge stays dependency-free, so the mapping is shape-detecting:
650
+ * - a plain JSON-Schema object literal → keep `type` / `properties`
651
+ * / `required` (the fields AHP accepts), validated in shape;
652
+ * - a Standard Schema v1 instance (branded
653
+ * `Symbol.for("standard-schema")`), an Effect codec, or any other
654
+ * opaque object → degrade to `{ type: "object" }` — the input is
655
+ * always an object, but no JSON-Schema shape is extractable
656
+ * without a schema compiler;
657
+ * - anything that is not an object (no input) → null (no
658
+ * `inputSchema` at all).
659
+ */
660
+ export function inputSchemaOf(input: unknown): ToolDefinition["inputSchema"] | null {
661
+ if (input === null || typeof input !== "object") return null;
662
+ const candidate = input as Record<string, unknown>;
663
+ if (
664
+ candidate["type"] === "object" &&
665
+ (candidate["properties"] === undefined ||
666
+ (typeof candidate["properties"] === "object" && candidate["properties"] !== null)) &&
667
+ (candidate["required"] === undefined ||
668
+ (Array.isArray(candidate["required"]) &&
669
+ candidate["required"].every((r) => typeof r === "string")))
670
+ ) {
671
+ const schema: NonNullable<ToolDefinition["inputSchema"]> = { type: "object" };
672
+ if (candidate["properties"] !== undefined) {
673
+ schema.properties = candidate["properties"] as Record<string, object>;
674
+ }
675
+ if (Array.isArray(candidate["required"])) {
676
+ schema.required = candidate["required"] as string[];
677
+ }
678
+ return schema;
679
+ }
680
+ // Opaque schema forms (Standard Schema brand, Effect codec, …).
681
+ return { type: "object" };
682
+ }
683
+
684
+ /**
685
+ * Map the opencode tool registry to AHP `ToolDefinition[]` (the
686
+ * session's `serverTools`):
687
+ * - `input` → `inputSchema` via {@link inputSchemaOf} (absent input
688
+ * omits the field);
689
+ * - `excluded` — names the cross-session union of every live
690
+ * session's active-client tools registers in the same location
691
+ * registry — are dropped: those tools already reach the model
692
+ * (and the client) through the client itself and must not echo
693
+ * back as server tools.
694
+ */
695
+ export function mapServerTools(
696
+ tools: readonly FacadeTool[],
697
+ excluded: ReadonlySet<string> = new Set(),
698
+ ): ToolDefinition[] {
699
+ const out: ToolDefinition[] = [];
700
+ for (const tool of tools) {
701
+ if (excluded.has(tool.name)) continue;
702
+ const def: ToolDefinition = { name: tool.name };
703
+ if (tool.description !== undefined && tool.description.length > 0) {
704
+ def.description = tool.description;
705
+ }
706
+ const inputSchema = inputSchemaOf(tool.input);
707
+ if (inputSchema !== null) def.inputSchema = inputSchema;
708
+ out.push(def);
709
+ }
710
+ return out;
711
+ }
712
+
379
713
  /**
380
714
  * Map the opencode catalog to the AHP root state's `agents` list.
381
- * Mapping locked 2026-11-07:
715
+ * Mapping locked:
382
716
  * - one AgentInfo per opencode provider;
383
717
  * - providers with activation "disabled" are excluded;
384
718
  * - models with enabled: false are excluded;
@@ -778,9 +1112,13 @@ export function modelRefString(model?: FacadeModelRef): string | null {
778
1112
  * `status` starts at `Idle | IsRead` (33) — the session reducer can only
779
1113
  * move the read/archive/input-needed bits, so the *activity* source of
780
1114
  * truth is the chat status (synced via `session/chatUpdated`).
781
- * `customizations` carries the workspace agent directory container — the
782
- * same one the root catalog builds — because VS Code's agent dropdown reads
783
- * `SessionState.customizations` (root-state customizations are NOT read).
1115
+ * `customizations` carries the session customization catalog (design
1116
+ * §7.5) — the workspace agent directory container, the sibling skills
1117
+ * directory container, and the top-level MCP server entries — because
1118
+ * VS Code's agent dropdown and Customizations panel read
1119
+ * `SessionState.customizations` (root-state customizations are NOT
1120
+ * read). `serverTools` carries the host-side tool list (opencode's
1121
+ * registry minus client-contributed tools).
784
1122
  */
785
1123
  export function initialSessionState(input: {
786
1124
  sessionID: string;
@@ -788,6 +1126,8 @@ export function initialSessionState(input: {
788
1126
  title: string;
789
1127
  activeClients?: SessionActiveClient[];
790
1128
  customizations?: Customization[];
1129
+ /** The session's `serverTools` (AHP `SessionState.serverTools`). */
1130
+ serverTools?: ToolDefinition[];
791
1131
  status?: SessionStatus;
792
1132
  changesets?: Changeset[];
793
1133
  /**
@@ -814,6 +1154,9 @@ export function initialSessionState(input: {
814
1154
  ...(input.customizations !== undefined && input.customizations.length > 0
815
1155
  ? { customizations: input.customizations }
816
1156
  : {}),
1157
+ ...(input.serverTools !== undefined && input.serverTools.length > 0
1158
+ ? { serverTools: input.serverTools }
1159
+ : {}),
817
1160
  ...(input.changesets !== undefined ? { changesets: input.changesets } : {}),
818
1161
  };
819
1162
  }
package/src/channels.ts CHANGED
@@ -5,6 +5,10 @@
5
5
  *
6
6
  * Channel kinds: root, session, chat, changeset
7
7
  * (`<owner>/changeset/{uncommitted|session|turn/<turnId>}`), and terminal.
8
+ * Sessions may also live on a non-standard `<scheme>:/<suffix>` channel
9
+ * (client legacy addressing — `isSessionChannel`); such URIs classify
10
+ * "unknown" by prefix and are tracked in the registry's live
11
+ * session-channel set instead.
8
12
  */
9
13
 
10
14
  export const ROOT_CHANNEL = "ahp-root://";
@@ -12,6 +16,16 @@ const SESSION_PREFIX = "ahp-session:/";
12
16
  const CHAT_PREFIX = "ahp-chat:/";
13
17
  const CHANGASET_MARKER = "/changeset/";
14
18
  const TERMINAL_PREFIX = "ahp-terminal:/";
19
+ /**
20
+ * The non-standard session-channel form real clients send: `<scheme>:/
21
+ * <suffix>` — a scheme token, a single slash (empty authority), a
22
+ * non-empty suffix. VS Code's legacy addressing (hosts predating the
23
+ * `vscode.ahpSessionUris` capability) and the AHP Swift reference client
24
+ * both create sessions under `<provider>:/<uuid>`. The spec's
25
+ * client-chosen URI is exemplified, not mandated — the host accepts this
26
+ * form and echoes the channel back verbatim (design §6).
27
+ */
28
+ const LEGACY_SESSION_RE = /^([a-z][a-z0-9+.-]*):\/([^/].*)$/i;
15
29
 
16
30
  export type ChannelKind = "root" | "session" | "chat" | "changeset" | "terminal" | "unknown";
17
31
 
@@ -56,11 +70,29 @@ export function terminalChannelURI(toolCallId: string): string {
56
70
  return TERMINAL_PREFIX + toolCallId;
57
71
  }
58
72
 
73
+ /**
74
+ * Whether `uri` is a session channel in a form the host accepts: the
75
+ * standard `ahp-session:/<suffix>`, or the non-standard
76
+ * `<scheme>:/<suffix>` form clients use for legacy addressing
77
+ * (design §6). Chat, root, terminal, and changeset URIs never qualify.
78
+ */
79
+ export function isSessionChannel(uri: string): boolean {
80
+ const kind = channelKind(uri);
81
+ if (kind !== "unknown") return kind === "session";
82
+ return LEGACY_SESSION_RE.test(uri);
83
+ }
84
+
59
85
  /** The session id behind a session/chat channel URI, or null. */
60
86
  export function sessionIDOf(uri: string): string | null {
61
87
  const kind = channelKind(uri);
62
88
  if (kind === "session") return uri.slice(SESSION_PREFIX.length);
63
89
  if (kind === "chat") return uri.slice(CHAT_PREFIX.length);
90
+ // The legacy session form (<scheme>:/<suffix>, see isSessionChannel):
91
+ // the suffix is everything after the first ":/".
92
+ if (kind === "unknown") {
93
+ const m = LEGACY_SESSION_RE.exec(uri);
94
+ if (m !== null) return m[2] ?? null;
95
+ }
64
96
  return null;
65
97
  }
66
98
 
@@ -136,24 +168,31 @@ export interface SubscribeOutcome {
136
168
 
137
169
  /**
138
170
  * Subscription bookkeeping keyed by transport socket id, plus the set of
139
- * live session ids and the set of live terminal channel URIs (the host
140
- * adds/removes them as terminals are opened and torn down — synthetic
141
- * `ahp-terminal:` channels AND client-chosen pty terminal channels from
142
- * `createTerminal`, whose URIs classify "unknown" by prefix alone).
171
+ * live session ids, the set of live session CHANNEL URIs (the host
172
+ * adds/removes them in step with the session records — needed for
173
+ * non-standard `<scheme>:/<suffix>` session channels, which classify
174
+ * "unknown" by prefix alone), and the set of live terminal channel URIs
175
+ * (synthetic `ahp-terminal:` channels AND client-chosen pty terminal
176
+ * channels from `createTerminal`, whose URIs classify "unknown" by
177
+ * prefix alone).
143
178
  */
144
179
  export class ChannelRegistry {
145
180
  private readonly subs = new Map<number, Set<string>>();
146
181
  private readonly sessions = new Set<string>();
182
+ private readonly sessionChannels = new Set<string>();
147
183
  private readonly terminals = new Set<string>();
148
184
 
149
185
  /** Subscribe a socket to a channel; fails for unknown URIs, dead sessions, or gone terminals. */
150
186
  subscribe(socketId: number, uri: string): SubscribeOutcome {
151
187
  const kind = channelKind(uri);
152
188
  if (kind === "unknown") {
153
- // A client-chosen terminal URI (a live pty terminal) classifies
154
- // "unknown" by prefix; it is subscribable while the host keeps it
155
- // in the live-terminal set (in step with the record map).
156
- if (!this.terminals.has(uri)) return { ok: false, reason: "unknown-uri" };
189
+ // A non-standard (legacy) session channel or a client-chosen
190
+ // terminal URI (a live pty terminal) classifies "unknown" by
191
+ // prefix; each is subscribable while the host keeps it in its
192
+ // live set (in step with the record maps).
193
+ if (!this.sessionChannels.has(uri) && !this.terminals.has(uri)) {
194
+ return { ok: false, reason: "unknown-uri" };
195
+ }
157
196
  } else if (kind !== "root") {
158
197
  let id: string | null;
159
198
  if (kind === "changeset") {
@@ -212,6 +251,20 @@ export class ChannelRegistry {
212
251
  return this.sessions.has(sessionID);
213
252
  }
214
253
 
254
+ // ── live session channel URIs (non-standard forms) ────────────────────
255
+
256
+ addSessionChannel(uri: string): void {
257
+ this.sessionChannels.add(uri);
258
+ }
259
+
260
+ removeSessionChannel(uri: string): void {
261
+ this.sessionChannels.delete(uri);
262
+ }
263
+
264
+ hasSessionChannel(uri: string): boolean {
265
+ return this.sessionChannels.has(uri);
266
+ }
267
+
215
268
  // ── live terminals (synthetic channels + client-chosen pty channels) ──
216
269
 
217
270
  addTerminal(uri: string): void {
package/src/host-base.ts CHANGED
@@ -8,6 +8,7 @@ import { ChannelRegistry, ChannelKind, ROOT_CHANNEL, channelKind, parseChangeset
8
8
  import { Sequencer } from "./seq.js";
9
9
  import { createChangesetStateStore, createRootStateStore, ChangesetStateStore, RootStateStore } from "./state.js";
10
10
  import { SocketState, ClientRecord, ChatRuntime, SessionRecord, TerminalRecord, HostOptions } from "./host-types.js";
11
+ import { isPathInside } from "./host-util.js";
11
12
 
12
13
  export class HostBase {
13
14
  protected readonly seq: Sequencer;
@@ -82,13 +83,15 @@ export class HostBase {
82
83
  }
83
84
 
84
85
  /**
85
- * Channel kind with live-terminal awareness: client-chosen pty terminal
86
- * URIs (from `createTerminal`) classify "unknown" by prefix alone —
87
- * they classify "terminal" while their record is live.
86
+ * Channel kind with live-resource awareness: client-chosen pty terminal
87
+ * URIs (from `createTerminal`) and non-standard (legacy) session
88
+ * channels (`<scheme>:/<suffix>`) classify "unknown" by prefix alone —
89
+ * they classify "terminal"/"session" while their record is live.
88
90
  */
89
91
  protected kindOf(uri: string): ChannelKind {
90
92
  const kind = channelKind(uri);
91
93
  if (kind !== "unknown") return kind;
94
+ if (this.channels.hasSessionChannel(uri)) return "session";
92
95
  return this.terminals.has(uri) ? "terminal" : kind;
93
96
  }
94
97
 
@@ -213,6 +216,40 @@ export class HostBase {
213
216
  return this.opts.defaultDirectory !== undefined ? [directoryUri(this.opts.defaultDirectory)] : undefined;
214
217
  }
215
218
 
219
+ /**
220
+ * The AHP `workingDirectories` this record's session carries
221
+ * (`SessionMetadata.workingDirectories`): the session's own working
222
+ * directory (`rec.directory`), falling back to the location directory
223
+ * for legacy records without one. VS Code groups its session list by
224
+ * this workspace (the folder name, host-suffixed for remote hosts);
225
+ * sessions without it fall into the "Unknown" bucket. `undefined` when
226
+ * neither the record nor the location carries a directory.
227
+ */
228
+ protected workingDirectoriesOf(rec: SessionRecord): string[] | undefined {
229
+ const dir = rec.directory ?? this.opts.defaultDirectory;
230
+ return dir !== undefined ? [directoryUri(dir)] : undefined;
231
+ }
232
+
233
+ /**
234
+ * The session directory containing `absPath` — the confinement
235
+ * boundary for `resourceRead` file targets and `head` content refs.
236
+ * The location directory is checked first, then each live session's
237
+ * own directory; the first directory that contains the path wins.
238
+ * `undefined` when nothing contains the path (the caller answers
239
+ * -32009, permission denied).
240
+ */
241
+ protected containingSessionDir(absPath: string): string | undefined {
242
+ const candidates: string[] = [];
243
+ if (this.opts.defaultDirectory !== undefined) candidates.push(this.opts.defaultDirectory);
244
+ for (const rec of this.sessions.values()) {
245
+ if (rec.directory !== undefined && !candidates.includes(rec.directory)) candidates.push(rec.directory);
246
+ }
247
+ for (const dir of candidates) {
248
+ if (isPathInside(absPath, dir)) return dir;
249
+ }
250
+ return undefined;
251
+ }
252
+
216
253
  /** The denormalized `SessionSummary` view of a record. */
217
254
  protected sessionSummary(rec: SessionRecord): SessionSummary {
218
255
  const s = rec.sessionStore.state;
@@ -238,7 +275,7 @@ export class HostBase {
238
275
  modifiedAt,
239
276
  chats,
240
277
  defaultChat: rec.defaultChatURI,
241
- workingDirectories: this.workingDirectories(),
278
+ workingDirectories: this.workingDirectoriesOf(rec),
242
279
  });
243
280
  }
244
281