opencode-ahp 0.1.10 → 0.1.11

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-ahp",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
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
@@ -138,6 +138,15 @@ export interface FacadeSession {
138
138
  model?: FacadeModelRef;
139
139
  archived?: boolean;
140
140
  time: { created: number; updated: number };
141
+ /**
142
+ * The opencode session this one is a child of — set only for
143
+ * subagent children (opencode core creates them with a `parentID`
144
+ * pointing at the caller's session). Root sessions and forks carry
145
+ * no parentID (a fork records its origin in `fork` instead). The
146
+ * host never surfaces a parented session as an AHP session
147
+ * (mirrors the TUI's session-list filter).
148
+ */
149
+ parentID?: string;
141
150
  /**
142
151
  * Durable, core-opaque session metadata. The host uses
143
152
  * one key — `opencode-ahp` — to make the peer-chat binding survive a
@@ -165,10 +174,31 @@ export type FacadePermissionDecision = "once" | "reject";
165
174
  * wire shape; everything downstream works on this union.
166
175
  */
167
176
  export type FacadeEvent =
168
- | { type: "session.created"; sessionID: string; title?: string; agent?: string; model?: FacadeModelRef }
177
+ | {
178
+ type: "session.created";
179
+ sessionID: string;
180
+ title?: string;
181
+ agent?: string;
182
+ model?: FacadeModelRef;
183
+ /** The parent session id (subagent children); absent for root sessions and forks. */
184
+ parentID?: string;
185
+ }
169
186
  | { type: "session.deleted"; sessionID: string }
170
187
  | { type: "session.renamed"; sessionID: string; title: string }
171
- | { type: "inbox.enqueued"; sessionID: string; inboxID: string; text: string; delivery: FacadeDelivery | "default" }
188
+ | {
189
+ type: "inbox.enqueued";
190
+ sessionID: string;
191
+ inboxID: string;
192
+ text: string;
193
+ delivery: FacadeDelivery | "default";
194
+ /**
195
+ * The enqueued item is a subagent completion report (a synthetic
196
+ * item whose `payload.metadata.source` is `"subagent"` — opencode
197
+ * core's report-back for an idle child). The host origins a
198
+ * report-driven turn as a system notification, not user input.
199
+ */
200
+ subagent?: true;
201
+ }
172
202
  | { type: "inbox.delivered"; sessionID: string; inboxID: string }
173
203
  | { type: "execution.started"; sessionID: string }
174
204
  | { type: "execution.succeeded"; sessionID: string }
@@ -815,6 +845,7 @@ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
815
845
  title: str(data["title"]),
816
846
  agent: str(data["agent"]),
817
847
  model: mapModelRef(data["model"]),
848
+ parentID: str(data["parentID"]),
818
849
  },
819
850
  };
820
851
  case "session.deleted":
@@ -832,6 +863,12 @@ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
832
863
  if (inboxID === undefined || text === undefined)
833
864
  return drop(missingOf({ inboxID, text }));
834
865
  const delivery = str(data["delivery"]) ?? str(item?.["delivery"]);
866
+ // Subagent completion report: a SYNTHETIC item tagged
867
+ // `metadata.source: "subagent"` (opencode core's report-back for an
868
+ // idle child). The item type is part of the detection key — user
869
+ // items may carry arbitrary metadata too.
870
+ const metadata = payload !== undefined && isObj(payload["metadata"]) ? payload["metadata"] : undefined;
871
+ const subagent = item?.["type"] === "synthetic" && metadata !== undefined && metadata["source"] === "subagent";
835
872
  return {
836
873
  status: "ok",
837
874
  event: {
@@ -840,6 +877,7 @@ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
840
877
  inboxID,
841
878
  text,
842
879
  delivery: delivery === "steer" || delivery === "queue" ? delivery : "default",
880
+ ...(subagent ? { subagent: true as const } : {}),
843
881
  },
844
882
  };
845
883
  }
@@ -1198,6 +1236,16 @@ export function userMessage(text: string, model?: string, agentUri?: string): Me
1198
1236
  return message;
1199
1237
  }
1200
1238
 
1239
+ /**
1240
+ * The system-notification-origin AHP `Message` for a machine-generated
1241
+ * turn input — a subagent completion report waking an idle parent
1242
+ * (design §8): the turn carries the report text verbatim, but its origin
1243
+ * is `systemNotification`, not user input.
1244
+ */
1245
+ export function systemNotificationMessage(text: string): Message {
1246
+ return { text, origin: { kind: MessageKind.SystemNotification } };
1247
+ }
1248
+
1201
1249
  /** Bitmask covering the mutually-exclusive activity bits (bits 0–4). */
1202
1250
  const STATUS_ACTIVITY_MASK = (1 << 5) - 1;
1203
1251
 
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import { HostSessions } from "./host-sessions.js";
6
- import { ActionType, SessionInputRequestKind, ToolCallStatus, isClientDispatchable, ActionOrigin, ChatToolCallCompleteAction, ChatToolCallConfirmedAction, ChatToolCallContentChangedAction, ChatToolCallResultConfirmedAction, ChatTurnCancelledAction, ChatTurnStartedAction, ChangesetFilesReviewChangedAction, Message, SessionActiveClient, SessionCustomizationToggledAction, SessionMcpServerStartRequestedAction, SessionMcpServerStopRequestedAction, SessionToolConfirmationRequest, StateAction, ToolCallResult } from "@microsoft/agent-host-protocol";
6
+ import { ActionType, SessionInputRequestKind, ToolCallStatus, isClientDispatchable, ActionOrigin, ChatToolCallCompleteAction, ChatToolCallConfirmedAction, ChatToolCallContentChangedAction, ChatToolCallResultConfirmedAction, ChatTruncatedAction, ChatTurnCancelledAction, ChatTurnStartedAction, ChangesetFilesReviewChangedAction, Message, SessionActiveClient, SessionCustomizationToggledAction, SessionMcpServerStartRequestedAction, SessionMcpServerStopRequestedAction, SessionToolConfirmationRequest, StateAction, ToolCallResult } from "@microsoft/agent-host-protocol";
7
7
  import { FacadeDelivery, MCP_CUSTOMIZATION_ID_PREFIX } from "./bridge.js";
8
8
  import { normalizeToolDefinitions } from "./client-tools.js";
9
9
  import { channelKind, parseChangesetChannel } from "./channels.js";
@@ -143,6 +143,10 @@ export class HostDispatch extends HostSessions {
143
143
  if (chat === undefined) { noChat(); return; }
144
144
  await this.dispatchTurnCancelled(chat, stateAction, origin);
145
145
  return;
146
+ case ActionType.ChatTruncated:
147
+ if (chat === undefined) { noChat(); return; }
148
+ this.dispatchTruncated(chat, stateAction, origin);
149
+ return;
146
150
  case ActionType.SessionTitleChanged:
147
151
  await this.dispatchTitleChanged(rec, stateAction, origin);
148
152
  return;
@@ -574,6 +578,28 @@ export class HostDispatch extends HostSessions {
574
578
  await this.finishTurn(chat);
575
579
  }
576
580
 
581
+ /**
582
+ * `chat/truncated` (client-dispatchable): the client trims the chat's
583
+ * turn history in the shared state (the documented use case: truncate,
584
+ * then dispatch a new `chat/turnStarted` with an edited message).
585
+ * State-only on this host — the official reducer trims the stored turns
586
+ * (to and including `turnId`, or to none when it is omitted) and drops
587
+ * the active turn (status → idle); opencode's message history has no
588
+ * counterpart and is untouched, and an in-flight execution is not
589
+ * interrupted: its late events land on a store that no longer carries
590
+ * the turn, and the reducer no-ops them. An unknown `turnId` follows
591
+ * the official reducer's no-op (accepted, state unchanged).
592
+ */
593
+ private dispatchTruncated(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): void {
594
+ const chatURI = chat.uri;
595
+ const a = action as ChatTruncatedAction;
596
+ if (a.turnId !== undefined && (typeof a.turnId !== "string" || a.turnId.length === 0)) {
597
+ this.echo(chatURI, action, origin, "invalid chat/truncated params (turnId must be a non-empty string)");
598
+ return;
599
+ }
600
+ this.echo(chatURI, action, origin);
601
+ }
602
+
577
603
  /**
578
604
  * `changeset/filesReviewChanged` (the only client-dispatchable changeset
579
605
  * action): validate the channel resolves to a live store, then echo —
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { HostDispatch } from "./host-dispatch.js";
6
6
  import { ActionType, ResponsePartKind, SessionInputRequestKind, ToolCallContributorKind, ToolCallStatus, ErrorResponsePart, SessionToolClientExecutionRequest, SessionToolConfirmationRequest } from "@microsoft/agent-host-protocol";
7
- import { displayNameFor, pastTenseMessageFor, userMessage, FacadeEvent } from "./bridge.js";
7
+ import { displayNameFor, pastTenseMessageFor, systemNotificationMessage, userMessage, FacadeEvent } from "./bridge.js";
8
8
  import { EXTERNAL_REGISTER_GRACE_MS, errorMessage, mapToolResultContent } from "./host-util.js";
9
9
 
10
10
  export class HostEvents extends HostDispatch {
@@ -42,6 +42,10 @@ export class HostEvents extends HostDispatch {
42
42
  // ── opencode event pump handlers ───────────────────────────────────────
43
43
  private async handleEvent(ev: FacadeEvent): Promise<void> {
44
44
  if (ev.type === "session.created") {
45
+ // Subagent children (a `parentID` in the created event) never
46
+ // surface as AHP sessions — skip them before the deferral so no
47
+ // grace timer or existence fetch runs for them (design §7.2).
48
+ if (ev.parentID !== undefined) return;
45
49
  // Every live chat has its own opencode session, so a
46
50
  // created event for an already-bound id is ours (a createChat
47
51
  // backend) and never an external session.
@@ -93,7 +97,11 @@ export class HostEvents extends HostDispatch {
93
97
  }
94
98
  return;
95
99
  case "inbox.enqueued":
96
- chat.lastInbox = { text: ev.text, delivery: ev.delivery };
100
+ chat.lastInbox = {
101
+ text: ev.text,
102
+ delivery: ev.delivery,
103
+ ...(ev.subagent !== undefined ? { subagent: true } : {}),
104
+ };
97
105
  return;
98
106
  case "inbox.delivered":
99
107
  // Steering consumption is handled at turn end (finishTurn).
@@ -101,8 +109,20 @@ export class HostEvents extends HostDispatch {
101
109
  case "execution.started":
102
110
  if (chat.currentTurnId !== null) return; // write-ahead already claimed the turn
103
111
  // Orphan turn (an external TUI prompt, or a handoff this host did
104
- // not initiate): start it with the last-seen inbox message.
105
- this.startTurn(chat, chat.lastInbox !== null ? userMessage(chat.lastInbox.text) : userMessage(""));
112
+ // not initiate): start it with the last-seen inbox message. A
113
+ // subagent completion report waking an idle parent is
114
+ // machine-generated input, not a user prompt — the turn message
115
+ // carries the report text verbatim under a system-notification
116
+ // origin (design §8).
117
+ const inbox = chat.lastInbox;
118
+ this.startTurn(
119
+ chat,
120
+ inbox === null
121
+ ? userMessage("")
122
+ : inbox.subagent
123
+ ? systemNotificationMessage(inbox.text)
124
+ : userMessage(inbox.text),
125
+ );
106
126
  return;
107
127
  case "execution.succeeded":
108
128
  if (chat.currentTurnId === null) return;
@@ -565,6 +565,12 @@ export class HostSessions extends HostChats {
565
565
  * client, or a session resurfacing after a restart).
566
566
  * Outcomes:
567
567
  *
568
+ * - the session has a parent (a subagent child — opencode core
569
+ * creates children with a `parentID`) → skip (undefined): children
570
+ * are internal to the parent's opencode session and never surface
571
+ * as AHP sessions (mirrors the TUI's parentID session-list filter;
572
+ * forks are not children — they carry no `parentID` — and register
573
+ * normally);
568
574
  * - the opencode id already backs a chat of a live record → skip
569
575
  * (undefined); `listSessions` must not surface peer-chat backends
570
576
  * as their own AHP sessions;
@@ -581,6 +587,11 @@ export class HostSessions extends HostChats {
581
587
  * opencode id (the record).
582
588
  */
583
589
  private registerExternal(fs: FacadeSession): SessionRecord | undefined {
590
+ // Subagent children never surface (design §7.2): the single seam for
591
+ // every external-registration path (the event-pump deferral, the
592
+ // listSessions scan) — a skipped record gets no AHP session, no
593
+ // channel, and no root announcement.
594
+ if (fs.parentID !== undefined) return undefined;
584
595
  const existing = this.sessions.get(fs.sessionID);
585
596
  if (existing !== undefined) return existing;
586
597
  if (this.byOpencode.has(fs.sessionID)) return undefined;
package/src/host-types.ts CHANGED
@@ -70,8 +70,13 @@ export interface ChatRuntime {
70
70
  * `tool.input.started`, removed at the opencode-side terminal).
71
71
  */
72
72
  clientToolCalls: Map<string, ClientToolInvocation>;
73
- /** The most recent `session.inbox.enqueued` (external/TUI prompt tracking). */
74
- lastInbox: { text: string; delivery: string } | null;
73
+ /**
74
+ * The most recent `session.inbox.enqueued` (external/TUI prompt
75
+ * tracking). `subagent` marks a synthetic completion report — a
76
+ * report-driven orphan turn originates its message as a system
77
+ * notification, not user input (design §8).
78
+ */
79
+ lastInbox: { text: string; delivery: string; subagent?: true } | null;
75
80
  // ── changesets ────────────────────────────────────────────────
76
81
  /**
77
82
  * Live chat-owned changeset stores (uncommitted + turn), keyed by
package/src/index.ts CHANGED
@@ -253,6 +253,10 @@ function mapSessionInfo(info: SessionInfo): FacadeSession {
253
253
  ...(info.title !== undefined && info.title !== null ? { title: String(info.title) } : {}),
254
254
  ...(info.agent !== undefined ? { agent: String(info.agent) } : {}),
255
255
  ...(info.model !== undefined ? { model: modelRefOf(info) } : {}),
256
+ // Subagent children carry their parent's opencode session id; root
257
+ // sessions and forks (which record their origin in `fork`) do not.
258
+ // The host never surfaces a parented session (mirrors the TUI filter).
259
+ ...(info.parentID !== undefined && info.parentID !== null ? { parentID: String(info.parentID) } : {}),
256
260
  // SessionInfo.time carries `archived` only while archived.
257
261
  ...(info.time.archived !== undefined ? { archived: true } : {}),
258
262
  // Durable, core-opaque metadata: the host reads its
@@ -1067,8 +1071,19 @@ export default Plugin.define({
1067
1071
  cleanupHost = () => {
1068
1072
  // Kill the pty terminals before the listener stops — their final
1069
1073
  // terminal/exited actions still reach subscribers while it is up.
1070
- host.stopTerminals();
1071
- host.stopEventPump();
1074
+ // Per-step guards (design §13.4): a failing step is logged and
1075
+ // must not skip the later ones — skipping the pump abort leaves
1076
+ // the ctx.event.subscribe iteration running.
1077
+ try {
1078
+ host.stopTerminals();
1079
+ } catch (e) {
1080
+ console.error(`${TAG} location teardown: stopTerminals failed (${errorMessage(e)})`);
1081
+ }
1082
+ try {
1083
+ host.stopEventPump();
1084
+ } catch (e) {
1085
+ console.error(`${TAG} location teardown: stopEventPump failed (${errorMessage(e)})`);
1086
+ }
1072
1087
  };
1073
1088
  console.log(
1074
1089
  `${TAG} AHP 1.0.0 host listening on ws${opts.tls ? "s" : ""}://${opts.host}:${listener.port}${opts.path} ` +
@@ -1076,7 +1091,11 @@ export default Plugin.define({
1076
1091
  );
1077
1092
  } catch (e) {
1078
1093
  console.error(`${TAG} failed to start the AHP listener: ${errorMessage(e)}`);
1079
- listener?.stop();
1094
+ try {
1095
+ listener?.stop();
1096
+ } catch (stopErr) {
1097
+ console.error(`${TAG} failed to stop the half-started AHP listener: ${errorMessage(stopErr)}`);
1098
+ }
1080
1099
  listener = null;
1081
1100
  return; // R2: the opencode server stays up without AHP
1082
1101
  }
@@ -1084,10 +1103,19 @@ export default Plugin.define({
1084
1103
  // 5. Cleanup: stop the pump (aborts the event subscription) and stop
1085
1104
  // the listener, dropping every client connection. Logged because a
1086
1105
  // torn-down listener with no log line is otherwise undiagnosable.
1106
+ // Teardown runs as a finalizer in the location's activation scope
1107
+ // (design §13.4): every step is individually guarded, and the
1108
+ // listener stop — the step that releases the port — runs
1109
+ // unconditionally and last, so an earlier failure can neither skip it
1110
+ // nor throw out of the finalizer.
1087
1111
  return () => {
1088
1112
  console.log(`${TAG} location teardown — stopping the AHP host (location unloaded by opencode)`);
1089
1113
  cleanupHost?.();
1090
- listener?.stop();
1114
+ try {
1115
+ listener?.stop();
1116
+ } catch (e) {
1117
+ console.error(`${TAG} location teardown: listener stop failed (${errorMessage(e)})`);
1118
+ }
1091
1119
  };
1092
1120
  },
1093
1121
  });