opencode-ahp 0.1.5 → 0.1.7

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
@@ -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
  : {}),
@@ -717,6 +855,63 @@ export function userMessage(text: string, model?: string, agentUri?: string): Me
717
855
  return message;
718
856
  }
719
857
 
858
+ /** Bitmask covering the mutually-exclusive activity bits (bits 0–4). */
859
+ const STATUS_ACTIVITY_MASK = (1 << 5) - 1;
860
+
861
+ /**
862
+ * The bit that uniquely marks an input-needed status: `InputNeeded` (24)
863
+ * *includes* the `InProgress` bit (8), so `status & InputNeeded` also
864
+ * matches plain in-progress — bit 16 (`InputNeeded & ~InProgress`) is the
865
+ * discriminator (the same bit the official reducer's
866
+ * `withInputNeededStatus` clears on drain).
867
+ */
868
+ const INPUT_NEEDED_MARKER = (SessionStatus.InputNeeded & ~SessionStatus.InProgress) as SessionStatus;
869
+
870
+ /**
871
+ * Derive `SessionSummary.status` per the AHP aggregation rules: the
872
+ * activity bits (0–4) come from the default chat, else the most recently
873
+ * modified chat; they are **promoted** to `InputNeeded` whenever any chat
874
+ * is blocked on input, else to `Error` whenever any chat is in an error
875
+ * state. The orthogonal flags (`IsRead` / `IsArchived`) are session-scoped
876
+ * and are preserved from `sessionStatus`.
877
+ *
878
+ * The activity bits are deliberately NOT taken from `sessionStatus`: the
879
+ * session reducer only reaches them through the input-queue path, and that
880
+ * path cannot lower them back to `Idle` once a turn ends (draining the
881
+ * queue leaves `InProgress` behind — the official reducer's "unblocked
882
+ * turn falls back to `InProgress`" assumes the session was promoted to
883
+ * `InProgress` when the turn started, which it is not; only the chat is).
884
+ * The chat summaries are the activity source of truth.
885
+ */
886
+ export function sessionSummaryStatus(
887
+ sessionStatus: SessionStatus,
888
+ chats: readonly ChatSummary[],
889
+ defaultChat: string | undefined,
890
+ ): SessionStatus {
891
+ const flags = sessionStatus & ~STATUS_ACTIVITY_MASK;
892
+ let source = defaultChat !== undefined ? chats.find((c) => c.resource === defaultChat) : undefined;
893
+ if (source === undefined) {
894
+ for (const c of chats) {
895
+ if (source === undefined || c.modifiedAt > source.modifiedAt) source = c;
896
+ }
897
+ }
898
+ let promoted: SessionStatus | undefined;
899
+ for (const c of chats) {
900
+ if (c.status & INPUT_NEEDED_MARKER) {
901
+ promoted = SessionStatus.InputNeeded;
902
+ break;
903
+ }
904
+ if (c.status & SessionStatus.Error) promoted = SessionStatus.Error;
905
+ }
906
+ const activity =
907
+ promoted !== undefined
908
+ ? promoted
909
+ : source !== undefined
910
+ ? ((source.status & STATUS_ACTIVITY_MASK) as SessionStatus)
911
+ : SessionStatus.Idle;
912
+ return (flags | activity) as SessionStatus;
913
+ }
914
+
720
915
  /**
721
916
  * Build the `SessionSummary` for root notifications / `listSessions` from
722
917
  * a live record's denormalized fields. `chats` is the full catalog in
@@ -732,6 +927,10 @@ export function buildSessionSummary(input: {
732
927
  modifiedAt: string;
733
928
  chats: ChatSummary[];
734
929
  defaultChat: string;
930
+ /** The session's working directories (see `initialSessionState`) — the root
931
+ * channel's session catalog carries the same `SessionMetadata` the session
932
+ * channel does, so the list must show the same workspace. */
933
+ workingDirectories?: string[];
735
934
  }): SessionSummary {
736
935
  return {
737
936
  resource: input.channel,
@@ -739,6 +938,9 @@ export function buildSessionSummary(input: {
739
938
  title: input.title,
740
939
  status: input.status,
741
940
  ...(input.activity !== undefined ? { activity: input.activity } : {}),
941
+ ...(input.workingDirectories !== undefined && input.workingDirectories.length > 0
942
+ ? { workingDirectories: input.workingDirectories }
943
+ : {}),
742
944
  createdAt: input.createdAt,
743
945
  modifiedAt: input.modifiedAt,
744
946
  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);