opencode-ahp 0.1.10 → 0.1.12

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
@@ -20,7 +20,8 @@ In the Agents window, an `opencode` host with:
20
20
  agent, changesets, terminal, and file reads are scoped to that
21
21
  directory (sessions without one use the plugin's own location).
22
22
  - **Model picker** — the real opencode catalog: every provider and model
23
- your server exposes.
23
+ your server exposes. Models with variants offer a **Reasoning Effort**
24
+ picker; **Default** uses the model without a variant.
24
25
  - **Agent picker** — opencode's user-invocable agents (Build, Plan, and
25
26
  anything you define) appear as selectable agents; subagent-only agents
26
27
  are hidden.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-ahp",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
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
@@ -34,6 +34,7 @@ import {
34
34
  type McpServerCustomization,
35
35
  type McpServerState,
36
36
  type Message,
37
+ type ModelSelection,
37
38
  type SessionActiveClient,
38
39
  type SessionState,
39
40
  type SessionSummary,
@@ -52,6 +53,8 @@ export interface FacadeModel {
52
53
  limit: { context?: number; output?: number; input?: number };
53
54
  /** ModelInfo.capabilities.input (e.g. ["text", "image"]). */
54
55
  inputModalities: string[];
56
+ /** Selectable OpenCode variant IDs, in catalog order. */
57
+ variants?: readonly string[];
55
58
  }
56
59
 
57
60
  export interface FacadeProvider {
@@ -130,6 +133,23 @@ export interface FacadeModelRef {
130
133
  variant?: string;
131
134
  }
132
135
 
136
+ // VS Code groups this AHP model config key with the reasoning controls.
137
+ const REASONING_EFFORT = "reasoningEffort";
138
+ const DEFAULT_VARIANT = "";
139
+
140
+ export function modelRefFromSelection(selection?: ModelSelection): FacadeModelRef | undefined {
141
+ const id = selection?.id;
142
+ if (typeof id !== "string") return undefined;
143
+ const sep = id.indexOf("/");
144
+ if (sep <= 0 || sep === id.length - 1) return undefined;
145
+ const variant = selection?.config?.[REASONING_EFFORT];
146
+ return {
147
+ providerID: id.slice(0, sep),
148
+ modelID: id.slice(sep + 1),
149
+ ...(typeof variant === "string" && variant !== DEFAULT_VARIANT ? { variant } : {}),
150
+ };
151
+ }
152
+
133
153
  /** A narrow opencode session (`ctx.session.*` → `SessionInfo`). */
134
154
  export interface FacadeSession {
135
155
  sessionID: string;
@@ -138,6 +158,15 @@ export interface FacadeSession {
138
158
  model?: FacadeModelRef;
139
159
  archived?: boolean;
140
160
  time: { created: number; updated: number };
161
+ /**
162
+ * The opencode session this one is a child of — set only for
163
+ * subagent children (opencode core creates them with a `parentID`
164
+ * pointing at the caller's session). Root sessions and forks carry
165
+ * no parentID (a fork records its origin in `fork` instead). The
166
+ * host never surfaces a parented session as an AHP session
167
+ * (mirrors the TUI's session-list filter).
168
+ */
169
+ parentID?: string;
141
170
  /**
142
171
  * Durable, core-opaque session metadata. The host uses
143
172
  * one key — `opencode-ahp` — to make the peer-chat binding survive a
@@ -165,10 +194,31 @@ export type FacadePermissionDecision = "once" | "reject";
165
194
  * wire shape; everything downstream works on this union.
166
195
  */
167
196
  export type FacadeEvent =
168
- | { type: "session.created"; sessionID: string; title?: string; agent?: string; model?: FacadeModelRef }
197
+ | {
198
+ type: "session.created";
199
+ sessionID: string;
200
+ title?: string;
201
+ agent?: string;
202
+ model?: FacadeModelRef;
203
+ /** The parent session id (subagent children); absent for root sessions and forks. */
204
+ parentID?: string;
205
+ }
169
206
  | { type: "session.deleted"; sessionID: string }
170
207
  | { type: "session.renamed"; sessionID: string; title: string }
171
- | { type: "inbox.enqueued"; sessionID: string; inboxID: string; text: string; delivery: FacadeDelivery | "default" }
208
+ | {
209
+ type: "inbox.enqueued";
210
+ sessionID: string;
211
+ inboxID: string;
212
+ text: string;
213
+ delivery: FacadeDelivery | "default";
214
+ /**
215
+ * The enqueued item is a subagent completion report (a synthetic
216
+ * item whose `payload.metadata.source` is `"subagent"` — opencode
217
+ * core's report-back for an idle child). The host origins a
218
+ * report-driven turn as a system notification, not user input.
219
+ */
220
+ subagent?: true;
221
+ }
172
222
  | { type: "inbox.delivered"; sessionID: string; inboxID: string }
173
223
  | { type: "execution.started"; sessionID: string }
174
224
  | { type: "execution.succeeded"; sessionID: string }
@@ -719,7 +769,9 @@ export function mapServerTools(
719
769
  * - SessionModelInfo.id is a "<providerID>/<modelID>" ref;
720
770
  * - maxContextWindow ← limit.context · maxOutputTokens ← limit.output
721
771
  * · maxPromptTokens ← limit.input;
722
- * - supportsVision ← capabilities.input contains "image".
772
+ * - supportsVision ← capabilities.input contains "image";
773
+ * - configSchema exposes model variants as reasoning choices, with Default
774
+ * selecting the base model without a variant.
723
775
  *
724
776
  * With opencode agents + a workspace directory, every
725
777
  * AgentInfo also carries the same workspace directory container with the
@@ -751,6 +803,22 @@ export function mapCatalog(
751
803
  if (model.limit.context !== undefined) info.maxContextWindow = model.limit.context;
752
804
  if (model.limit.output !== undefined) info.maxOutputTokens = model.limit.output;
753
805
  if (model.limit.input !== undefined) info.maxPromptTokens = model.limit.input;
806
+ const variants = [...new Set(model.variants)].filter((id) => id !== DEFAULT_VARIANT);
807
+ if (variants.length > 0) {
808
+ info.configSchema = {
809
+ type: "object",
810
+ properties: {
811
+ [REASONING_EFFORT]: {
812
+ type: "string",
813
+ title: "Reasoning Effort",
814
+ description: "Select an OpenCode model variant, or use the model's default settings.",
815
+ default: DEFAULT_VARIANT,
816
+ enum: [DEFAULT_VARIANT, ...variants],
817
+ enumLabels: ["Default", ...variants.map((id) => id.charAt(0).toUpperCase() + id.slice(1))],
818
+ },
819
+ },
820
+ };
821
+ }
754
822
  models.push(info);
755
823
  }
756
824
  out.push({
@@ -815,6 +883,7 @@ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
815
883
  title: str(data["title"]),
816
884
  agent: str(data["agent"]),
817
885
  model: mapModelRef(data["model"]),
886
+ parentID: str(data["parentID"]),
818
887
  },
819
888
  };
820
889
  case "session.deleted":
@@ -832,6 +901,12 @@ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
832
901
  if (inboxID === undefined || text === undefined)
833
902
  return drop(missingOf({ inboxID, text }));
834
903
  const delivery = str(data["delivery"]) ?? str(item?.["delivery"]);
904
+ // Subagent completion report: a SYNTHETIC item tagged
905
+ // `metadata.source: "subagent"` (opencode core's report-back for an
906
+ // idle child). The item type is part of the detection key — user
907
+ // items may carry arbitrary metadata too.
908
+ const metadata = payload !== undefined && isObj(payload["metadata"]) ? payload["metadata"] : undefined;
909
+ const subagent = item?.["type"] === "synthetic" && metadata !== undefined && metadata["source"] === "subagent";
835
910
  return {
836
911
  status: "ok",
837
912
  event: {
@@ -840,6 +915,7 @@ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
840
915
  inboxID,
841
916
  text,
842
917
  delivery: delivery === "steer" || delivery === "queue" ? delivery : "default",
918
+ ...(subagent ? { subagent: true as const } : {}),
843
919
  },
844
920
  };
845
921
  }
@@ -1198,6 +1274,16 @@ export function userMessage(text: string, model?: string, agentUri?: string): Me
1198
1274
  return message;
1199
1275
  }
1200
1276
 
1277
+ /**
1278
+ * The system-notification-origin AHP `Message` for a machine-generated
1279
+ * turn input — a subagent completion report waking an idle parent
1280
+ * (design §8): the turn carries the report text verbatim, but its origin
1281
+ * is `systemNotification`, not user input.
1282
+ */
1283
+ export function systemNotificationMessage(text: string): Message {
1284
+ return { text, origin: { kind: MessageKind.SystemNotification } };
1285
+ }
1286
+
1201
1287
  /** Bitmask covering the mutually-exclusive activity bits (bits 0–4). */
1202
1288
  const STATUS_ACTIVITY_MASK = (1 << 5) - 1;
1203
1289
 
package/src/host-chats.ts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { HostClientTools } from "./host-client-tools.js";
6
6
  import { ActionType, Message } from "@microsoft/agent-host-protocol";
7
- import { agentIDFromUri, chatChangesetCatalog, chatSummaryOf, initialChatState } from "./bridge.js";
7
+ import { agentIDFromUri, chatChangesetCatalog, chatSummaryOf, initialChatState, modelRefFromSelection } from "./bridge.js";
8
8
  import { channelKind, isSessionChannel, sessionIDOf } from "./channels.js";
9
9
  import { ERROR_INVALID_PARAMS } from "./handshake.js";
10
10
  import { isRecord } from "./options.js";
@@ -287,13 +287,9 @@ export class HostChats extends HostClientTools {
287
287
  */
288
288
  protected async applyMessageSelection(chat: ChatRuntime, message: Message): Promise<string | null> {
289
289
  try {
290
- if (message.model?.id !== undefined && message.model.id.includes("/")) {
291
- const sep = message.model.id.indexOf("/");
292
- const providerID = message.model.id.slice(0, sep);
293
- const modelID = message.model.id.slice(sep + 1);
294
- if (providerID.length > 0 && modelID.length > 0) {
295
- await this.opts.facade.switchModel({ sessionID: chat.sessionID, model: { providerID, modelID } });
296
- }
290
+ const model = modelRefFromSelection(message.model);
291
+ if (model !== undefined) {
292
+ await this.opts.facade.switchModel({ sessionID: chat.sessionID, model });
297
293
  }
298
294
  if (message.agent?.uri !== undefined) {
299
295
  const agentID = agentIDFromUri(message.agent.uri);
@@ -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
@@ -595,6 +599,7 @@ function implementFacade(
595
599
  input: m.limit.input,
596
600
  },
597
601
  inputModalities: [...m.capabilities.input],
602
+ variants: m.variants.map((variant) => String(variant.id)),
598
603
  });
599
604
  }
600
605
  return providers.data.map((p) => ({
@@ -1067,8 +1072,19 @@ export default Plugin.define({
1067
1072
  cleanupHost = () => {
1068
1073
  // Kill the pty terminals before the listener stops — their final
1069
1074
  // terminal/exited actions still reach subscribers while it is up.
1070
- host.stopTerminals();
1071
- host.stopEventPump();
1075
+ // Per-step guards (design §13.4): a failing step is logged and
1076
+ // must not skip the later ones — skipping the pump abort leaves
1077
+ // the ctx.event.subscribe iteration running.
1078
+ try {
1079
+ host.stopTerminals();
1080
+ } catch (e) {
1081
+ console.error(`${TAG} location teardown: stopTerminals failed (${errorMessage(e)})`);
1082
+ }
1083
+ try {
1084
+ host.stopEventPump();
1085
+ } catch (e) {
1086
+ console.error(`${TAG} location teardown: stopEventPump failed (${errorMessage(e)})`);
1087
+ }
1072
1088
  };
1073
1089
  console.log(
1074
1090
  `${TAG} AHP 1.0.0 host listening on ws${opts.tls ? "s" : ""}://${opts.host}:${listener.port}${opts.path} ` +
@@ -1076,7 +1092,11 @@ export default Plugin.define({
1076
1092
  );
1077
1093
  } catch (e) {
1078
1094
  console.error(`${TAG} failed to start the AHP listener: ${errorMessage(e)}`);
1079
- listener?.stop();
1095
+ try {
1096
+ listener?.stop();
1097
+ } catch (stopErr) {
1098
+ console.error(`${TAG} failed to stop the half-started AHP listener: ${errorMessage(stopErr)}`);
1099
+ }
1080
1100
  listener = null;
1081
1101
  return; // R2: the opencode server stays up without AHP
1082
1102
  }
@@ -1084,10 +1104,19 @@ export default Plugin.define({
1084
1104
  // 5. Cleanup: stop the pump (aborts the event subscription) and stop
1085
1105
  // the listener, dropping every client connection. Logged because a
1086
1106
  // torn-down listener with no log line is otherwise undiagnosable.
1107
+ // Teardown runs as a finalizer in the location's activation scope
1108
+ // (design §13.4): every step is individually guarded, and the
1109
+ // listener stop — the step that releases the port — runs
1110
+ // unconditionally and last, so an earlier failure can neither skip it
1111
+ // nor throw out of the finalizer.
1087
1112
  return () => {
1088
1113
  console.log(`${TAG} location teardown — stopping the AHP host (location unloaded by opencode)`);
1089
1114
  cleanupHost?.();
1090
- listener?.stop();
1115
+ try {
1116
+ listener?.stop();
1117
+ } catch (e) {
1118
+ console.error(`${TAG} location teardown: listener stop failed (${errorMessage(e)})`);
1119
+ }
1091
1120
  };
1092
1121
  },
1093
1122
  });