opencode-ahp 0.1.5 → 0.1.6

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 CHANGED
@@ -50,16 +50,23 @@ In the Agents window, an `opencode` host with:
50
50
  `discard-changes` operation restores a file. Requires the location
51
51
  directory to be a git repository (otherwise the changesets are empty);
52
52
  opt out with `capabilities.changesets: false`.
53
- - **Terminals** — read-only `ahp-terminal:` channels rendered from
54
- `shell`-tool executions (`isPty: false`, completed-command output with
55
- exit codes): while a turn runs a foreground shell command, the terminal
56
- appears in the root catalog, streams
57
- `data` → `commandFinished` → `exited` to subscribers, and leaves the
58
- catalog at turn end (the channel state stays subscribable until the
59
- chat/session is removed). The terminals are renderings, not pty —
60
- `createTerminal`/`disposeTerminal` and client `terminal/*` actions get
61
- clean read-only errors. Opt out with
62
- `capabilities.terminals: false`.
53
+ - **Terminals** — two kinds, both in the root catalog:
54
+ - **Interactive pty shells** (`createTerminal`) — a real shell in a pty
55
+ (your `$SHELL`, default 80×24, the location's working directory):
56
+ client-chosen channel, `isPty: true`, input/resize drive the process,
57
+ `disposeTerminal` kills it. This is what makes a VS Code Agents-window
58
+ session usable — clicking it opens a working terminal.
59
+ - **Read-only renderings** of `shell`-tool executions
60
+ (`ahp-terminal:`, `isPty: false`, completed-command output with exit
61
+ codes): while a turn runs a foreground shell command, the terminal
62
+ appears in the root catalog, streams
63
+ `data` → `commandFinished` → `exited` to subscribers, and leaves the
64
+ catalog at turn end (the channel state stays subscribable until the
65
+ chat/session is removed). These are host-managed — `createTerminal`
66
+ can't target them and client `terminal/*` actions get clean
67
+ read-only errors.
68
+
69
+ Opt out of both with `capabilities.terminals: false`.
63
70
 
64
71
  ## Requirements
65
72
 
@@ -83,6 +90,13 @@ opencode plugin add opencode-ahp
83
90
  opencode plugin add github:mattzink/opencode-ahp
84
91
  ```
85
92
 
93
+ Installed copies don't auto-update. To update:
94
+
95
+ ```sh
96
+ opencode plugin update opencode-ahp
97
+ opencode service restart
98
+ ```
99
+
86
100
  **Dev (local checkout):**
87
101
 
88
102
  ```jsonc
@@ -104,20 +118,16 @@ Per-key resolution: the config entry's `options` ▸ an `options.jsonc`
104
118
  sibling of `src/index.ts` (checkouts only — copy
105
119
  [`options.example.jsonc`](options.example.jsonc)) ▸ built-in defaults.
106
120
 
121
+ [`options.example.jsonc`](options.example.jsonc) documents the full
122
+ option set — every key, its default, and what it does. A few of the
123
+ important ones:
124
+
107
125
  | Key | Default | Description |
108
126
  | --- | --- | --- |
109
- | `enabled` | `true` | Master switch; `false` → no listener, the plugin is fully inert |
110
- | `port` | `8765` | WS listen port |
111
- | `host` | `"127.0.0.1"` | Bind address; a **non-loopback bind requires an explicit `token`** (the listener refuses to start otherwise) |
112
- | `path` | `"/ahp"` | WS path — VS Code's URL carries it verbatim |
113
127
  | `token` | auto | Omit → generated on first start, persisted in opencode's plugin storage, printed once to the service log. Accepted via the `?token=` query param and `Authorization: Bearer <token>`. **Always enforced**, loopback or not |
114
- | `allowedOrigins` | `"*"` | `"*"` or an exact list, e.g. `["vscode://vscode"]`. The token is still always required regardless |
115
- | `tls` | `null` | `{ keyPath, certPath }` — native TLS termination → `wss://` (off-LAN transports, D3). PEM **file paths**; the port becomes TLS-only (plain-HTTP requests to it fail) and the health endpoint is then HTTPS: `curl -k https://…:8765/healthz`. A missing/unreadable file disables the AHP listener — the opencode server keeps running |
116
- | `healthPath` | `"/healthz"` | Health endpoint (no auth): `curl …:8765/healthz` → `ok` (over the same TLS termination when `tls` is set) |
117
- | `keepAlive` | `true` | Keep the opencode location loaded against its idle timeout (`experimental.location_idle_timeout`, default 60 min) by periodically touching an internal anchor session — with this on, **no `location_idle_timeout` config entry is needed**. The anchor (`opencode-ahp (keep-alive)`) is a real opencode session: it shows in the TUI session list but is hidden from AHP clients (opencode's plugin surface cannot archive it) |
118
- | `keepAliveIntervalMinutes` | `10` | Minutes between keep-alive touches; keep well below the effective idle timeout |
119
- | `replayWindow` | `1000` | Per-channel actions kept for reconnect replay; older gaps → fresh snapshot |
120
- | `capabilities` | `{ changesets: true, terminals: true, automations: false }` | Host-side switches — never advertise what we don't implement (in AHP 1.0.0 none of these is a wire field; discovery is the state's optionality). Set `changesets` to `false` to disable the diff channels (the session/chat snapshots then carry no changeset catalogues and changeset URIs resolve to nothing); set `terminals` to `false` to disable the synthetic shell-command terminal channels (no `root/terminals` list, `shell` calls open no `ahp-terminal:` channels) |
128
+ | `host` | `"127.0.0.1"` | Bind address; a **non-loopback bind requires an explicit `token`** (the listener refuses to start otherwise) |
129
+ | `port` | `8765` | WS listen port |
130
+ | `keepAlive` | `true` | Keep the opencode location loaded against its idle timeout by periodically touching an internal anchor session — with this on, **no `location_idle_timeout` config entry is needed**. See the example file for the anchor's visibility details |
121
131
 
122
132
  ## Remote access (local LAN)
123
133
 
@@ -250,6 +260,18 @@ node scripts/ahp-multi-chat.mjs --token <token> --base http://127.0.0.1:8765 --r
250
260
  NODE_TLS_REJECT_UNAUTHORIZED=0 node scripts/ahp-changesets.mjs --token <token> --base https://127.0.0.1:8765
251
261
  ```
252
262
 
263
+ ### Local environment (git-ignored)
264
+
265
+ `docs/local.md` is the designated place for each developer to keep
266
+ local development environment specifics — facts about their own machine
267
+ that never belong in the committed tree, such as LAN IPs and hostnames,
268
+ per-machine versions, the port and config location of a daily opencode
269
+ service, the current LAN test server token/URL, reference checkouts
270
+ (the opencode and AHP repos, the extracted VS Code AHP client
271
+ sources), and scratch roots. The file is git-ignored and optional: it
272
+ does not exist on machines that have never created it, and nothing in
273
+ this repo requires it.
274
+
253
275
  ## Publishing
254
276
 
255
277
  House pattern: push to `main` → CI (`typecheck` + `test`) → the publish
@@ -258,9 +280,6 @@ workflow computes the version as `<major>.<minor>.<run-number>` and
258
280
  repo secret is stored (one-time setup: npmjs.com → package → *Package
259
281
  settings* → *Trusted publishers* → this workflow).
260
282
 
261
- Installed copies don't auto-update: `opencode plugin update opencode-ahp`
262
- - `opencode service restart`.
263
-
264
283
  ## Documentation
265
284
 
266
285
  - [`docs/design.md`](docs/design.md) — architecture and wire-contract findings.
@@ -52,6 +52,16 @@
52
52
  // Global actions kept for reconnect replay; older gaps → fresh snapshot.
53
53
  // "replayWindow": 1000,
54
54
 
55
+ // Timestamped capture of the raw opencode event stream to the server
56
+ // log — one line per raw V2 event: `event ok` (mapped to the host),
57
+ // `event dropped (missing: <fields>)` (known type, unusable instance —
58
+ // or a malformed envelope), `event unimplemented` (no handler for the
59
+ // type) — with the raw `data` JSON (truncated to 300 chars). Off by
60
+ // default: a busy turn emits dozens of lines. The LAN test server
61
+ // script (scripts/ahp-server.mjs) enables it. Use it to attribute turn
62
+ // latency to host vs client vs model (design.md §8.1).
63
+ // "logEvents": true,
64
+
55
65
  // Host-side capability switches — never advertise what we don't
56
66
  // implement (in AHP 1.0.0 none of these is a wire field; discovery is
57
67
  // the state's optionality).
@@ -60,8 +70,10 @@
60
70
  // catalogues in the session/chat snapshots; changeset URIs resolve to
61
71
  // nothing). Changesets require the location directory to be a git
62
72
  // repository.
63
- // "terminals": false disables the synthetic shell-command terminal
64
- // channels (shell-tool calls open no ahp-terminal: channels and the
65
- // root state carries no terminals list).
73
+ // "terminals": false disables both terminal kinds: the synthetic
74
+ // shell-command terminal channels (shell-tool calls open no
75
+ // ahp-terminal: channels and the root state carries no terminals list)
76
+ // and the interactive pty shells (createTerminal/disposeTerminal
77
+ // answer not-found).
66
78
  // "capabilities": { "changesets": false, "terminals": false, "automations": false }
67
79
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-ahp",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "OpenCode V2 plugin: hosts Agent Host Protocol (AHP) 1.0.0 in-process so opencode is a native agent in the VS Code Agents window",
5
5
  "type": "module",
6
6
  "exports": {
package/src/bridge.ts CHANGED
@@ -152,6 +152,24 @@ export interface FacadeTokens {
152
152
  cache: { read: number; write: number };
153
153
  }
154
154
 
155
+ /**
156
+ * The classified result of one raw opencode V2 event (event capture,
157
+ * design §8.1):
158
+ * - `ok` — mapped into the narrow `FacadeEvent` union;
159
+ * - `dropped` — a known type whose instance carries nothing usable
160
+ * (`reason` names the missing fields), or a malformed envelope
161
+ * (not an object, missing `type`/`sessionID`);
162
+ * - `unimplemented` — an event type the host has no handler for.
163
+ *
164
+ * `mapV2Event` is the thin `ok → event, else null` wrapper over this;
165
+ * src/index.ts's events() generator uses the full outcome for the
166
+ * timestamped capture lines.
167
+ */
168
+ export type V2EventOutcome =
169
+ | { status: "ok"; event: FacadeEvent }
170
+ | { status: "dropped"; type: string; reason: string }
171
+ | { status: "unimplemented"; type: string };
172
+
155
173
  /**
156
174
  * The narrow opencode surface the bridge needs. Implemented in
157
175
  * src/index.ts against the plugin `ctx` (the only ctx call sites — this
@@ -430,76 +448,103 @@ function num(v: unknown): number | undefined {
430
448
  return typeof v === "number" && Number.isFinite(v) ? v : undefined;
431
449
  }
432
450
 
451
+ /** "a, b" — the names of the undefined values (drop reasons). */
452
+ function missingOf(vals: Record<string, unknown>): string {
453
+ return Object.keys(vals).filter((k) => vals[k] === undefined).join(", ");
454
+ }
455
+
433
456
  /**
434
- * Map a raw opencode V2 event (`{id, type, data}` — the fixture shape) to
435
- * the narrow `FacadeEvent` union, or null when the event carries nothing
436
- * the AHP host needs. Unknown types map to null (log-and-continue).
457
+ * Classify a raw opencode V2 event (`{id, type, data}` — the fixture
458
+ * shape) — `mapV2Event` is the thin `ok → event, else null` wrapper
459
+ * over this, and the timestamped capture lines (design §8.1) are
460
+ * formatted from the full outcome. Unknown types classify as
461
+ * `unimplemented` (log-and-continue, as before).
437
462
  */
438
- export function mapV2Event(raw: unknown): FacadeEvent | null {
439
- if (!isObj(raw)) return null;
463
+ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
464
+ if (!isObj(raw)) return { status: "dropped", type: "?", reason: "not an event envelope" };
440
465
  const type = str(raw["type"]);
466
+ if (type === undefined) return { status: "dropped", type: "?", reason: "missing: type" };
441
467
  const data = isObj(raw["data"]) ? raw["data"] : {};
442
468
  const sessionID = str(data["sessionID"]);
443
- if (type === undefined || sessionID === undefined) return null;
469
+ if (sessionID === undefined) return { status: "dropped", type, reason: "missing: sessionID" };
470
+
471
+ /** The `dropped` outcome for missing fields inside a known type. */
472
+ const drop = (fields: string): V2EventOutcome => ({ status: "dropped", type, reason: `missing: ${fields}` });
444
473
 
445
474
  switch (type) {
446
475
  case "session.created":
447
476
  return {
448
- type: "session.created",
449
- sessionID,
450
- title: str(data["title"]),
451
- agent: str(data["agent"]),
452
- model: mapModelRef(data["model"]),
477
+ status: "ok",
478
+ event: {
479
+ type: "session.created",
480
+ sessionID,
481
+ title: str(data["title"]),
482
+ agent: str(data["agent"]),
483
+ model: mapModelRef(data["model"]),
484
+ },
453
485
  };
454
486
  case "session.deleted":
455
- return { type: "session.deleted", sessionID };
487
+ return { status: "ok", event: { type: "session.deleted", sessionID } };
456
488
  case "session.renamed": {
457
489
  const title = str(data["title"]);
458
- return title !== undefined ? { type: "session.renamed", sessionID, title } : null;
490
+ if (title === undefined) return drop("title");
491
+ return { status: "ok", event: { type: "session.renamed", sessionID, title } };
459
492
  }
460
493
  case "session.inbox.enqueued": {
461
494
  const inboxID = str(data["inboxID"]);
462
495
  const item = isObj(data["item"]) ? data["item"] : undefined;
463
496
  const payload = item !== undefined && isObj(item["payload"]) ? item["payload"] : undefined;
464
497
  const text = payload !== undefined ? str(payload["text"]) : undefined;
465
- if (inboxID === undefined || text === undefined) return null;
498
+ if (inboxID === undefined || text === undefined)
499
+ return drop(missingOf({ inboxID, text }));
466
500
  const delivery = str(data["delivery"]) ?? str(item?.["delivery"]);
467
501
  return {
468
- type: "inbox.enqueued",
469
- sessionID,
470
- inboxID,
471
- text,
472
- delivery: delivery === "steer" || delivery === "queue" ? delivery : "default",
502
+ status: "ok",
503
+ event: {
504
+ type: "inbox.enqueued",
505
+ sessionID,
506
+ inboxID,
507
+ text,
508
+ delivery: delivery === "steer" || delivery === "queue" ? delivery : "default",
509
+ },
473
510
  };
474
511
  }
475
512
  case "session.inbox.delivered": {
476
513
  const inboxID = str(data["inboxID"]);
477
- return inboxID !== undefined ? { type: "inbox.delivered", sessionID, inboxID } : null;
514
+ if (inboxID === undefined) return drop("inboxID");
515
+ return { status: "ok", event: { type: "inbox.delivered", sessionID, inboxID } };
478
516
  }
479
517
  case "session.execution.started":
480
- return { type: "execution.started", sessionID };
518
+ return { status: "ok", event: { type: "execution.started", sessionID } };
481
519
  case "session.execution.succeeded":
482
- return { type: "execution.succeeded", sessionID };
520
+ return { status: "ok", event: { type: "execution.succeeded", sessionID } };
483
521
  case "session.execution.failed": {
484
522
  const error = isObj(data["error"]) ? data["error"] : undefined;
485
523
  return {
486
- type: "execution.failed",
487
- sessionID,
488
- error: { type: error !== undefined ? (str(error["type"]) ?? "error") : "error", message: error !== undefined ? (str(error["message"]) ?? "") : "" },
524
+ status: "ok",
525
+ event: {
526
+ type: "execution.failed",
527
+ sessionID,
528
+ error: { type: error !== undefined ? (str(error["type"]) ?? "error") : "error", message: error !== undefined ? (str(error["message"]) ?? "") : "" },
529
+ },
489
530
  };
490
531
  }
491
532
  case "session.execution.interrupted":
492
- return { type: "execution.interrupted", sessionID, reason: str(data["reason"]) ?? "user" };
533
+ return { status: "ok", event: { type: "execution.interrupted", sessionID, reason: str(data["reason"]) ?? "user" } };
493
534
  case "session.step.started": {
494
535
  const assistantMessageID = str(data["assistantMessageID"]);
495
536
  const model = mapModelRef(data["model"]);
496
- if (assistantMessageID === undefined || model === undefined) return null;
537
+ if (assistantMessageID === undefined || model === undefined)
538
+ return drop(missingOf({ assistantMessageID, model }));
497
539
  return {
498
- type: "step.started",
499
- sessionID,
500
- assistantMessageID,
501
- agent: str(data["agent"]) ?? "build",
502
- model,
540
+ status: "ok",
541
+ event: {
542
+ type: "step.started",
543
+ sessionID,
544
+ assistantMessageID,
545
+ agent: str(data["agent"]) ?? "build",
546
+ model,
547
+ },
503
548
  };
504
549
  }
505
550
  case "session.text.delta":
@@ -507,13 +552,17 @@ export function mapV2Event(raw: unknown): FacadeEvent | null {
507
552
  const assistantMessageID = str(data["assistantMessageID"]);
508
553
  const delta = str(data["delta"]);
509
554
  const ordinal = num(data["ordinal"]);
510
- if (assistantMessageID === undefined || delta === undefined || ordinal === undefined) return null;
555
+ if (assistantMessageID === undefined || delta === undefined || ordinal === undefined)
556
+ return drop(missingOf({ assistantMessageID, delta, ordinal }));
511
557
  return {
512
- type: type === "session.text.delta" ? "text.delta" : "reasoning.delta",
513
- sessionID,
514
- assistantMessageID,
515
- ordinal,
516
- delta,
558
+ status: "ok",
559
+ event: {
560
+ type: type === "session.text.delta" ? "text.delta" : "reasoning.delta",
561
+ sessionID,
562
+ assistantMessageID,
563
+ ordinal,
564
+ delta,
565
+ },
517
566
  };
518
567
  }
519
568
  case "session.text.ended":
@@ -521,71 +570,84 @@ export function mapV2Event(raw: unknown): FacadeEvent | null {
521
570
  const assistantMessageID = str(data["assistantMessageID"]);
522
571
  const text = str(data["text"]);
523
572
  const ordinal = num(data["ordinal"]);
524
- if (assistantMessageID === undefined || text === undefined || ordinal === undefined) return null;
573
+ if (assistantMessageID === undefined || text === undefined || ordinal === undefined)
574
+ return drop(missingOf({ assistantMessageID, text, ordinal }));
525
575
  return {
526
- type: type === "session.text.ended" ? "text.ended" : "reasoning.ended",
527
- sessionID,
528
- assistantMessageID,
529
- ordinal,
530
- text,
576
+ status: "ok",
577
+ event: {
578
+ type: type === "session.text.ended" ? "text.ended" : "reasoning.ended",
579
+ sessionID,
580
+ assistantMessageID,
581
+ ordinal,
582
+ text,
583
+ },
531
584
  };
532
585
  }
533
586
  case "session.tool.input.started": {
534
587
  const id = str(data["id"]);
535
588
  const name = str(data["name"]);
536
589
  const assistantMessageID = str(data["assistantMessageID"]);
537
- if (id === undefined || name === undefined || assistantMessageID === undefined) return null;
538
- return { type: "tool.input.started", sessionID, assistantMessageID, id, name };
590
+ if (id === undefined || name === undefined || assistantMessageID === undefined)
591
+ return drop(missingOf({ id, name, assistantMessageID }));
592
+ return { status: "ok", event: { type: "tool.input.started", sessionID, assistantMessageID, id, name } };
539
593
  }
540
594
  case "session.tool.input.ended": {
541
595
  const id = str(data["id"]);
542
596
  const text = str(data["text"]);
543
597
  const assistantMessageID = str(data["assistantMessageID"]);
544
- if (id === undefined || text === undefined || assistantMessageID === undefined) return null;
545
- return { type: "tool.input.ended", sessionID, assistantMessageID, id, text };
598
+ if (id === undefined || text === undefined || assistantMessageID === undefined)
599
+ return drop(missingOf({ id, text, assistantMessageID }));
600
+ return { status: "ok", event: { type: "tool.input.ended", sessionID, assistantMessageID, id, text } };
546
601
  }
547
602
  case "session.tool.progress": {
548
603
  const id = str(data["id"]);
549
- return id !== undefined ? { type: "tool.progress", sessionID, id } : null;
604
+ if (id === undefined) return drop("id");
605
+ return { status: "ok", event: { type: "tool.progress", sessionID, id } };
550
606
  }
551
607
  case "session.tool.success": {
552
608
  const id = str(data["id"]);
553
- if (id === undefined) return null;
609
+ if (id === undefined) return drop("id");
554
610
  const content = Array.isArray(data["content"])
555
611
  ? (data["content"] as unknown[]).map((c) => (isObj(c) ? mapToolContent(c) : undefined)).filter((c): c is FacadeToolContent => c !== undefined)
556
612
  : [];
557
- return { type: "tool.success", sessionID, id, content, executed: data["executed"] === true };
613
+ return { status: "ok", event: { type: "tool.success", sessionID, id, content, executed: data["executed"] === true } };
558
614
  }
559
615
  case "session.tool.failed": {
560
616
  const id = str(data["id"]);
561
617
  const error = isObj(data["error"]) ? data["error"] : undefined;
562
- if (id === undefined) return null;
618
+ if (id === undefined) return drop("id");
563
619
  return {
564
- type: "tool.failed",
565
- sessionID,
566
- id,
567
- error: { type: error !== undefined ? (str(error["type"]) ?? "error") : "error", message: error !== undefined ? (str(error["message"]) ?? "") : "" },
568
- executed: data["executed"] === true,
620
+ status: "ok",
621
+ event: {
622
+ type: "tool.failed",
623
+ sessionID,
624
+ id,
625
+ error: { type: error !== undefined ? (str(error["type"]) ?? "error") : "error", message: error !== undefined ? (str(error["message"]) ?? "") : "" },
626
+ executed: data["executed"] === true,
627
+ },
569
628
  };
570
629
  }
571
630
  case "session.usage.updated": {
572
631
  const tokens = isObj(data["tokens"]) ? data["tokens"] : undefined;
573
- if (tokens === undefined) return null;
632
+ if (tokens === undefined) return drop("tokens");
574
633
  const cache = isObj(tokens["cache"]) ? tokens["cache"] : undefined;
575
634
  return {
576
- type: "usage.updated",
577
- sessionID,
578
- tokens: {
579
- input: num(tokens["input"]) ?? 0,
580
- output: num(tokens["output"]) ?? 0,
581
- reasoning: num(tokens["reasoning"]) ?? 0,
582
- cache: { read: cache !== undefined ? (num(cache["read"]) ?? 0) : 0, write: cache !== undefined ? (num(cache["write"]) ?? 0) : 0 },
635
+ status: "ok",
636
+ event: {
637
+ type: "usage.updated",
638
+ sessionID,
639
+ tokens: {
640
+ input: num(tokens["input"]) ?? 0,
641
+ output: num(tokens["output"]) ?? 0,
642
+ reasoning: num(tokens["reasoning"]) ?? 0,
643
+ cache: { read: cache !== undefined ? (num(cache["read"]) ?? 0) : 0, write: cache !== undefined ? (num(cache["write"]) ?? 0) : 0 },
644
+ },
583
645
  },
584
646
  };
585
647
  }
586
648
  case "permission.asked": {
587
649
  const id = str(data["id"]);
588
- if (id === undefined) return null;
650
+ if (id === undefined) return drop("id");
589
651
  const source = isObj(data["source"]) && data["source"]["type"] === "tool" && str(data["source"]["id"]) !== undefined
590
652
  ? {
591
653
  type: "tool" as const,
@@ -594,26 +656,40 @@ export function mapV2Event(raw: unknown): FacadeEvent | null {
594
656
  }
595
657
  : undefined;
596
658
  return {
597
- type: "permission.asked",
598
- sessionID,
599
- id,
600
- action: str(data["action"]) ?? "",
601
- message: str(data["message"]),
602
- source,
659
+ status: "ok",
660
+ event: {
661
+ type: "permission.asked",
662
+ sessionID,
663
+ id,
664
+ action: str(data["action"]) ?? "",
665
+ message: str(data["message"]),
666
+ source,
667
+ },
603
668
  };
604
669
  }
605
670
  case "permission.replied": {
606
671
  const requestID = str(data["requestID"]);
607
672
  const reply = str(data["reply"]);
608
- return requestID !== undefined && reply !== undefined
609
- ? { type: "permission.replied", sessionID, requestID, reply }
610
- : null;
673
+ if (requestID === undefined || reply === undefined)
674
+ return drop(missingOf({ requestID, reply }));
675
+ return { status: "ok", event: { type: "permission.replied", sessionID, requestID, reply } };
611
676
  }
612
677
  default:
613
- return null;
678
+ return { status: "unimplemented", type };
614
679
  }
615
680
  }
616
681
 
682
+ /**
683
+ * Map a raw opencode V2 event to the narrow `FacadeEvent` union, or
684
+ * null when the event carries nothing the AHP host needs — the `ok`
685
+ * view of `mapV2EventRaw` (`dropped`/`unimplemented` outcomes are
686
+ * log-and-continue; the capture lines see the full outcome).
687
+ */
688
+ export function mapV2Event(raw: unknown): FacadeEvent | null {
689
+ const outcome = mapV2EventRaw(raw);
690
+ return outcome.status === "ok" ? outcome.event : null;
691
+ }
692
+
617
693
  function mapModelRef(v: unknown): FacadeModelRef | undefined {
618
694
  if (!isObj(v)) return undefined;
619
695
  const id = str(v["id"]);
@@ -635,6 +711,56 @@ function mapToolContent(c: Record<string, unknown>): FacadeToolContent | undefin
635
711
  return undefined;
636
712
  }
637
713
 
714
+ // ── event capture lines ───────────────────────────────────────────
715
+
716
+ /** The house log tag (shared with src/index.ts's console lines). */
717
+ export const EVENT_LOG_TAG = "[opencode-ahp]";
718
+
719
+ /** Max characters of the raw `data` JSON on a capture line. */
720
+ const EVENT_LOG_PAYLOAD_MAX = 300;
721
+
722
+ /**
723
+ * Local `HH:MM:SS.mmm` (zero-padded) for capture lines. The `Date` is
724
+ * passed in (not read here) so the formatter stays pure and unit-testable
725
+ * with a fixed instant.
726
+ */
727
+ export function timeStamp(date: Date): string {
728
+ const pad = (n: number, width = 2) => String(n).padStart(width, "0");
729
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`;
730
+ }
731
+
732
+ /**
733
+ * One capture line per raw opencode event (design §8.1):
734
+ *
735
+ * [opencode-ahp] 19:04:41.520 event ok: session.tool.input.started {"…"}
736
+ * [opencode-ahp] 19:04:41.525 event dropped (missing: text): session.tool.input.ended {"…"}
737
+ * [opencode-ahp] 19:04:41.530 event unimplemented: shell.created {"…"}
738
+ *
739
+ * The type is the **raw** opencode type (what the plugin received), and
740
+ * the payload is the raw `data` JSON — truncated to
741
+ * `EVENT_LOG_PAYLOAD_MAX` with an ellipsis — or the whole raw value when
742
+ * the envelope is malformed. `stamp` is precomputed (`timeStamp`) so this
743
+ * stays pure.
744
+ */
745
+ export function eventLogLine(outcome: V2EventOutcome, raw: unknown, stamp: string): string {
746
+ const type = isObj(raw) ? (str(raw["type"]) ?? "?") : "?";
747
+ const payloadSource = isObj(raw) && isObj(raw["data"]) ? raw["data"] : raw;
748
+ let payload: string;
749
+ try {
750
+ payload = JSON.stringify(payloadSource) ?? "null";
751
+ } catch {
752
+ payload = "(unserializable)";
753
+ }
754
+ if (payload.length > EVENT_LOG_PAYLOAD_MAX) payload = `${payload.slice(0, EVENT_LOG_PAYLOAD_MAX)}…`;
755
+ const kind =
756
+ outcome.status === "ok"
757
+ ? "ok"
758
+ : outcome.status === "dropped"
759
+ ? `dropped (${outcome.reason})`
760
+ : "unimplemented";
761
+ return `${EVENT_LOG_TAG} ${stamp} event ${kind}: ${type} ${payload}`;
762
+ }
763
+
638
764
  // ── state builders & summary mappers ────────────────────────────
639
765
 
640
766
  const STATUS_IDLE_READ = (SessionStatus.Idle | SessionStatus.IsRead) as SessionStatus;
@@ -664,6 +790,15 @@ export function initialSessionState(input: {
664
790
  customizations?: Customization[];
665
791
  status?: SessionStatus;
666
792
  changesets?: Changeset[];
793
+ /**
794
+ * The session's working directories (AHP `SessionMetadata.workingDirectories`):
795
+ * the location directory the session's agent has tool access to. VS Code's
796
+ * session list groups sessions by this workspace (label = the folder name,
797
+ * host-suffixed for remote hosts); a session without it lands in the
798
+ * "Unknown" bucket. Single entry — the host advertises no
799
+ * `multipleWorkingDirectories` capability, so clients may not mutate it.
800
+ */
801
+ workingDirectories?: string[];
667
802
  }): SessionState {
668
803
  return {
669
804
  provider: input.provider,
@@ -673,6 +808,9 @@ export function initialSessionState(input: {
673
808
  activeClients: input.activeClients ?? [],
674
809
  chats: [],
675
810
  defaultChat: undefined,
811
+ ...(input.workingDirectories !== undefined && input.workingDirectories.length > 0
812
+ ? { workingDirectories: input.workingDirectories }
813
+ : {}),
676
814
  ...(input.customizations !== undefined && input.customizations.length > 0
677
815
  ? { customizations: input.customizations }
678
816
  : {}),
@@ -732,6 +870,10 @@ export function buildSessionSummary(input: {
732
870
  modifiedAt: string;
733
871
  chats: ChatSummary[];
734
872
  defaultChat: string;
873
+ /** The session's working directories (see `initialSessionState`) — the root
874
+ * channel's session catalog carries the same `SessionMetadata` the session
875
+ * channel does, so the list must show the same workspace. */
876
+ workingDirectories?: string[];
735
877
  }): SessionSummary {
736
878
  return {
737
879
  resource: input.channel,
@@ -739,6 +881,9 @@ export function buildSessionSummary(input: {
739
881
  title: input.title,
740
882
  status: input.status,
741
883
  ...(input.activity !== undefined ? { activity: input.activity } : {}),
884
+ ...(input.workingDirectories !== undefined && input.workingDirectories.length > 0
885
+ ? { workingDirectories: input.workingDirectories }
886
+ : {}),
742
887
  createdAt: input.createdAt,
743
888
  modifiedAt: input.modifiedAt,
744
889
  chats: input.chats,
package/src/channels.ts CHANGED
@@ -137,7 +137,9 @@ export interface SubscribeOutcome {
137
137
  /**
138
138
  * Subscription bookkeeping keyed by transport socket id, plus the set of
139
139
  * live session ids and the set of live terminal channel URIs (the host
140
- * adds/removes them as synthetic terminals are opened and torn down).
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).
141
143
  */
142
144
  export class ChannelRegistry {
143
145
  private readonly subs = new Map<number, Set<string>>();
@@ -147,8 +149,12 @@ export class ChannelRegistry {
147
149
  /** Subscribe a socket to a channel; fails for unknown URIs, dead sessions, or gone terminals. */
148
150
  subscribe(socketId: number, uri: string): SubscribeOutcome {
149
151
  const kind = channelKind(uri);
150
- if (kind === "unknown") return { ok: false, reason: "unknown-uri" };
151
- if (kind !== "root") {
152
+ 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" };
157
+ } else if (kind !== "root") {
152
158
  let id: string | null;
153
159
  if (kind === "changeset") {
154
160
  const parsed = parseChangesetChannel(uri);
@@ -206,7 +212,7 @@ export class ChannelRegistry {
206
212
  return this.sessions.has(sessionID);
207
213
  }
208
214
 
209
- // ── live terminals (synthetic shell-command terminals) ────────────────
215
+ // ── live terminals (synthetic channels + client-chosen pty channels) ──
210
216
 
211
217
  addTerminal(uri: string): void {
212
218
  this.terminals.add(uri);