opencode-ahp 1.0.1 → 1.0.4

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
@@ -5,7 +5,7 @@ Agents window** — on this machine, and on any other machine on your LAN.
5
5
 
6
6
  It works by adding one WebSocket listener to your existing opencode
7
7
  server, speaking [AHP](https://microsoft.github.io/agent-host-protocol/)
8
- (Agent Host Protocol 1.0.0) on it — the protocol VS Code uses to talk to
8
+ (Agent Host Protocol) on it — the protocol VS Code uses to talk to
9
9
  external coding agents. No separate process runs on the host, and nothing
10
10
  is installed on the client machine: VS Code ships the AHP client.
11
11
 
@@ -19,6 +19,8 @@ In the Agents window, an `opencode` host with:
19
19
  filesystem, and a session started in a picked folder runs *there*: its
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
+ The host advertises its default directory as a `file://` URI so VS Code
23
+ can pass the selected workspace folder when creating a session.
22
24
  - **Model picker** — the real opencode catalog: every provider and model
23
25
  your server exposes. Models with variants offer a **Reasoning Effort**
24
26
  picker; **Default** uses the model without a variant.
@@ -27,7 +29,7 @@ In the Agents window, an `opencode` host with:
27
29
  are hidden.
28
30
  - **Chat** — streaming text and reasoning, the full tool-call lifecycle
29
31
  (a call appears, gets approved, and shows its result as it runs), and
30
- usage totals.
32
+ context usage from the latest model call.
31
33
  - **Permissions** — when opencode asks for permission to run a tool, the
32
34
  Agents window shows an approval prompt: approve runs the tool, deny
33
35
  blocks it.
@@ -65,7 +67,7 @@ In the Agents window, an `opencode` host with:
65
67
  - **opencode v2** (≥ 2.2.6 verified; check with `opencode --version`). The
66
68
  plugin runs *inside* the opencode server — no extra process; it only
67
69
  opens one extra port.
68
- - **VS Code ≥ 1.144** (1.145.2 verified) for the Agents window and
70
+ - **VS Code ≥ 1.144** (1.148.0 verified) for the Agents window and
69
71
  `Agents: Add Remote Agent Host…`. VS Code ships the AHP client — nothing
70
72
  is installed on the client machine.
71
73
  - Node + pnpm (via [mise](https://mise.jdx.dev)) for **development only**.
@@ -66,7 +66,7 @@
66
66
  // "logEvents": true,
67
67
 
68
68
  // Host-side capability switches — never advertise what we don't
69
- // implement (in AHP 1.0.0 none of these is a wire field; discovery is
69
+ // implement (in AHP none of these is a wire field; discovery is
70
70
  // the state's optionality).
71
71
  // Default: { "changesets": true, "terminals": true, "automations": false }.
72
72
  // "changesets": false disables the diff channels (no changeset
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-ahp",
3
- "version": "1.0.1",
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",
3
+ "version": "1.0.4",
4
+ "description": "OpenCode V2 plugin: hosts Agent Host Protocol (AHP) 1.1.0 in-process so opencode is a native agent in the VS Code Agents window",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": "./src/index.ts"
@@ -40,7 +40,7 @@
40
40
  "prepublishOnly": "pnpm typecheck && pnpm test"
41
41
  },
42
42
  "dependencies": {
43
- "@microsoft/agent-host-protocol": "1.0.0",
43
+ "@microsoft/agent-host-protocol": "1.1.0",
44
44
  "@opencode/plugin": "^2.2.6"
45
45
  },
46
46
  "devDependencies": {
package/src/bridge.ts CHANGED
@@ -234,7 +234,7 @@ export type FacadeEvent =
234
234
  | { type: "tool.progress"; sessionID: string; id: string }
235
235
  | { type: "tool.success"; sessionID: string; id: string; content: FacadeToolContent[]; executed?: boolean }
236
236
  | { type: "tool.failed"; sessionID: string; id: string; error: { type: string; message: string }; executed?: boolean }
237
- | { type: "usage.updated"; sessionID: string; tokens: FacadeTokens }
237
+ | { type: "step.ended"; sessionID: string; tokens: FacadeTokens }
238
238
  | {
239
239
  type: "permission.asked";
240
240
  sessionID: string;
@@ -1037,14 +1037,14 @@ export function mapV2EventRaw(raw: unknown): V2EventOutcome {
1037
1037
  },
1038
1038
  };
1039
1039
  }
1040
- case "session.usage.updated": {
1040
+ case "session.step.ended": {
1041
1041
  const tokens = isObj(data["tokens"]) ? data["tokens"] : undefined;
1042
1042
  if (tokens === undefined) return drop("tokens");
1043
1043
  const cache = isObj(tokens["cache"]) ? tokens["cache"] : undefined;
1044
1044
  return {
1045
1045
  status: "ok",
1046
1046
  event: {
1047
- type: "usage.updated",
1047
+ type: "step.ended",
1048
1048
  sessionID,
1049
1049
  tokens: {
1050
1050
  input: num(tokens["input"]) ?? 0,
package/src/handshake.ts CHANGED
@@ -1,19 +1,22 @@
1
1
  /**
2
- * AHP 1.0.0 handshake: the `initialize` command — semver capability
3
- * negotiation via the official package's `negotiateProtocolVersion`.
2
+ * AHP handshake: the `initialize` command — semver capability negotiation
3
+ * via the official package's `negotiateProtocolVersion`.
4
4
  *
5
5
  * Version semantics (AHP versioning spec): the server picks the highest
6
6
  * client-offered version inside its supported caret baselines and echoes
7
- * that exact string back. The package we pin (1.0.0) supports the 1.0.0
8
- * and 0.9.0 baselines, so a client offering any 1.x (or 0.9.x) version
9
- * negotiates the 1.0 wire protocol; anything else gets -32005 with the
10
- * `supportedVersions` data.
7
+ * that exact string back. The package we pin (1.1.0) supports the 1.0.0
8
+ * and 0.9.0 baselines, so a client offering any 1.x or 0.9.x version
9
+ * negotiates the highest string it offered — possibly above the pin
10
+ * itself (1.x is additive-optional over the 1.0 wire: surface newer
11
+ * than the host implements is answered permissively); anything else
12
+ * gets -32005 with the `supportedVersions` data.
11
13
  */
12
14
  import {
13
15
  negotiateProtocolVersion,
14
16
  SUPPORTED_PROTOCOL_VERSIONS,
15
17
  type Implementation,
16
18
  type InitializeResult,
19
+ type PathStyle,
17
20
  type Snapshot,
18
21
  } from "@microsoft/agent-host-protocol";
19
22
  import { ROOT_CHANNEL } from "./channels.js";
@@ -34,8 +37,15 @@ export interface InitializeRequest {
34
37
  serverInfo: Implementation;
35
38
  /** Current global serverSeq (stamped onto the result). */
36
39
  serverSeq: number;
37
- /** The opencode instance's working directory, when known. */
40
+ /** The file URI of the opencode instance's working directory, when known. */
38
41
  defaultDirectory?: string;
42
+ /**
43
+ * The host environment's path grammar, stamped onto the result's
44
+ * `environment` (AHP 1.1.0 `HostEnvironment.pathStyle`): clients parse
45
+ * and format native paths with it instead of inferring from their own
46
+ * environment. The host serves a single OS, so it is always populated.
47
+ */
48
+ pathStyle: PathStyle;
39
49
  /**
40
50
  * Resolve a snapshot for an `initialSubscriptions` entry; null when the
41
51
  * channel is not subscribable (it is simply omitted from the result).
@@ -116,6 +126,7 @@ export async function handleInitialize(req: InitializeRequest): Promise<Initiali
116
126
  protocolVersion: version,
117
127
  serverSeq: req.serverSeq,
118
128
  serverInfo: req.serverInfo,
129
+ environment: { pathStyle: req.pathStyle },
119
130
  snapshots,
120
131
  ...(req.defaultDirectory ? { defaultDirectory: req.defaultDirectory } : {}),
121
132
  },
package/src/host-base.ts CHANGED
@@ -169,7 +169,8 @@ export class HostBase {
169
169
  const next = chatSummaryOf(chat);
170
170
  const changes: Record<string, unknown> = {};
171
171
  let changed = false;
172
- for (const key of ["title", "status", "activity", "modifiedAt"] as const) {
172
+ // Titles change through the session's chat catalog, independently of turn state.
173
+ for (const key of ["status", "activity", "modifiedAt"] as const) {
173
174
  if (entry[key] !== next[key]) {
174
175
  changes[key] = next[key];
175
176
  changed = true;
@@ -183,6 +184,21 @@ export class HostBase {
183
184
  }
184
185
  }
185
186
 
187
+ /** AHP updates chat titles through the session catalog, not the chat reducer. */
188
+ protected updateBackendTitle(rec: SessionRecord, chatURI: string, title: string): void {
189
+ const session = rec.sessionStore.state;
190
+ if (chatURI === rec.defaultChatURI && session.title !== title) {
191
+ this.publish({ channel: rec.channel, action: { type: ActionType.SessionTitleChanged, title } });
192
+ }
193
+ const entry = session.chats.find((chat) => chat.resource === chatURI);
194
+ if (entry !== undefined && entry.title !== title) {
195
+ this.publish({
196
+ channel: rec.channel,
197
+ action: { type: ActionType.SessionChatUpdated, chat: chatURI, changes: { title } },
198
+ });
199
+ }
200
+ }
201
+
186
202
  /**
187
203
  * Announce summary-level changes on the root channel (`root/
188
204
  * sessionSummaryChanged` notification — ephemeral, not replayed).
@@ -253,9 +269,13 @@ export class HostBase {
253
269
  /** The denormalized `SessionSummary` view of a record. */
254
270
  protected sessionSummary(rec: SessionRecord): SessionSummary {
255
271
  const s = rec.sessionStore.state;
256
- // Authoritative chat order: default first, then insertion order
257
- // (the default chat is bound first).
258
- const chats = [...rec.chats.values()].map((c) => chatSummaryOf(c.chatStore.state));
272
+ // Runtime order and activity can lead the catalog during publication;
273
+ // the catalog owns mutable titles.
274
+ const titles = new Map(s.chats.map((chat) => [chat.resource, chat.title]));
275
+ const chats = [...rec.chats.values()].map((chat) => {
276
+ const summary = chatSummaryOf(chat.chatStore.state);
277
+ return { ...summary, title: titles.get(chat.uri) ?? summary.title };
278
+ });
259
279
  let modifiedAt = rec.modifiedAt;
260
280
  for (const c of rec.chats.values()) {
261
281
  if (c.chatStore.state.modifiedAt > modifiedAt) modifiedAt = c.chatStore.state.modifiedAt;
package/src/host-chats.ts CHANGED
@@ -89,16 +89,17 @@ export class HostChats extends HostClientTools {
89
89
  }
90
90
 
91
91
  /**
92
- * `createChat` (AHP 1.0.0 chat command): create a new chat in an
93
- * existing session. The 1:1 mapping: mint a fresh
94
- * opencode session (same provider/model resolution as `createSession`)
95
- * and bind it to the client-chosen chat URI. Result: `null` (the
96
- * client waits for `session/chatAdded` on the session channel, and
97
- * rolls back with `disposeChat` when the chat never surfaces — so
98
- * everything below is published before the response). `source` and
99
- * `workingDirectories` are rejected with INVALID_PARAMS: the
100
- * capability is advertised without fork/sideChat/
101
- * multipleWorkingDirectories, so conformant clients never send them.
92
+ * `createChat` (AHP chat command): create a new chat in an existing
93
+ * session. The 1:1 mapping: mint a fresh opencode session (same
94
+ * provider/model resolution as `createSession`) and bind it to the
95
+ * client-chosen chat URI. `title` (AHP 1.1.0) seeds the chat's display
96
+ * title when present. Result: `null` (the client waits for
97
+ * `session/chatAdded` on the session channel, and rolls back with
98
+ * `disposeChat` when the chat never surfaces — so everything below is
99
+ * published before the response). `source` and `workingDirectories`
100
+ * are rejected with INVALID_PARAMS: the capability is advertised
101
+ * without fork/sideChat/multipleWorkingDirectories, so conformant
102
+ * clients never send them.
102
103
  *
103
104
  * Error codes: -32602 (invalid params, including `source`/
104
105
  * `workingDirectories`), -32001 (no such session), -32003 (chat URI
@@ -152,6 +153,13 @@ export class HostChats extends HostClientTools {
152
153
  const providers = await this.opts.facade.listCatalog();
153
154
  const provider = providers.find((p) => p.activation !== "disabled");
154
155
  const model = provider !== undefined ? firstEnabledModelRef(provider.models) : undefined;
156
+ // `title` (AHP 1.1.0 `CreateChatParams.title`): the client-selected
157
+ // initial display title; falls back to the host-minted `Chat N` when
158
+ // absent or empty.
159
+ const title =
160
+ typeof params["title"] === "string" && (params["title"] as string).length > 0
161
+ ? params["title"]
162
+ : `Chat ${rec.chats.size + 1}`;
155
163
  const now = new Date().toISOString();
156
164
  let created;
157
165
  try {
@@ -171,7 +179,7 @@ export class HostChats extends HostClientTools {
171
179
  this.sendError(socketId, msg.id, ERROR_INTERNAL, `failed to create the chat's backend session: ${errorMessage(err)}`);
172
180
  return;
173
181
  }
174
- const chat = this.newChatRuntime(chatURI, created.sessionID, `Chat ${rec.chats.size + 1}`, now);
182
+ const chat = this.newChatRuntime(chatURI, created.sessionID, title, now);
175
183
  this.bindChat(rec, chat);
176
184
  // Session-channel lifecycle (server-side, no origin): the catalog
177
185
  // mutation the client is waiting for, plus the changeset catalogue
@@ -232,7 +240,7 @@ export class HostChats extends HostClientTools {
232
240
  }
233
241
 
234
242
  /**
235
- * `disposeChat` (AHP 1.0.0 chat command): remove a chat and its
243
+ * `disposeChat` (AHP chat command): remove a chat and its
236
244
  * opencode session from the session catalog. Result: `null`. The
237
245
  * default chat cannot be disposed — a session keeps its default chat
238
246
  * (there is no re-home mechanism; disposing it would leave the
@@ -11,6 +11,14 @@ import { isRecord } from "./options.js";
11
11
  import { RpcMessage, ChatRuntime, SessionRecord } from "./host-types.js";
12
12
  import { errorMessage, normalizeToolCallResult, clientResultToFacade } from "./host-util.js";
13
13
 
14
+ /**
15
+ * The cap on a client-supplied title (UTF-16 code units). AHP sets no
16
+ * limit and opencode persists titles untruncated, so without it a client
17
+ * can bloat the session catalog, the session store, and every `action`
18
+ * echo to the channel's subscribers with an arbitrarily long title.
19
+ */
20
+ const MAX_TITLE_LENGTH = 256;
21
+
14
22
  export class HostDispatch extends HostSessions {
15
23
  /**
16
24
  * `dispatchAction` is a notification — the response is the `action`
@@ -148,7 +156,7 @@ export class HostDispatch extends HostSessions {
148
156
  this.dispatchTruncated(chat, stateAction, origin);
149
157
  return;
150
158
  case ActionType.SessionTitleChanged:
151
- await this.dispatchTitleChanged(rec, stateAction, origin);
159
+ await this.dispatchTitleChanged(rec, channel, stateAction, origin);
152
160
  return;
153
161
  case ActionType.SessionActiveClientSet:
154
162
  this.dispatchActiveClientSet(rec, stateAction, origin, clientId);
@@ -621,20 +629,26 @@ export class HostDispatch extends HostSessions {
621
629
  this.echo(channel, action, origin);
622
630
  }
623
631
 
624
- private async dispatchTitleChanged(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
632
+ private async dispatchTitleChanged(rec: SessionRecord, channel: string, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
625
633
  const a = action as { title?: unknown };
626
634
  const title = typeof a.title === "string" && a.title.length > 0 ? a.title : null;
627
635
  if (title === null) {
628
- this.echo(rec.channel, action, origin, "invalid session/titleChanged params");
636
+ this.echo(channel, action, origin, "invalid session/titleChanged params");
637
+ return;
638
+ }
639
+ if (title.length > MAX_TITLE_LENGTH) {
640
+ this.echo(channel, action, origin, `title too long: ${title.length} characters (max ${MAX_TITLE_LENGTH})`);
629
641
  return;
630
642
  }
643
+ const chat = rec.chats.get(channel);
631
644
  try {
632
- await this.opts.facade.rename({ sessionID: rec.sessionID, title });
645
+ await this.opts.facade.rename({ sessionID: chat?.sessionID ?? rec.sessionID, title });
633
646
  } catch (err) {
634
- this.echo(rec.channel, action, origin, `rename failed: ${errorMessage(err)}`);
647
+ this.echo(channel, action, origin, `rename failed: ${errorMessage(err)}`);
635
648
  return;
636
649
  }
637
- this.echo(rec.channel, action, origin);
650
+ this.echo(channel, action, origin);
651
+ this.updateBackendTitle(rec, chat?.uri ?? rec.defaultChatURI, title);
638
652
  }
639
653
 
640
654
  private dispatchActiveClientSet(
@@ -23,7 +23,7 @@ export const ERROR_PERMISSION_DENIED = -32009;
23
23
  /**
24
24
  * AHP `AlreadyExists` (-32010): the target resource already exists. This
25
25
  * host's use: a `createTerminal` for a channel that is already open.
26
- * (AHP 1.0.0 defines no "not supported" code — the -32600…-32603
26
+ * (AHP defines no "not supported" code — the -32600…-32603
27
27
  * standard range covers those shapes.)
28
28
  */
29
29
  export const ERROR_ALREADY_EXISTS = -32010;
@@ -84,17 +84,7 @@ export class HostEvents extends HostDispatch {
84
84
  }
85
85
  return;
86
86
  case "session.renamed":
87
- if (chat.uri === rec.defaultChatURI) {
88
- this.publish({ channel: rec.channel, action: { type: ActionType.SessionTitleChanged, title: ev.title } });
89
- } else {
90
- // No chat-title session action exists; the chat summary carries
91
- // the title (the chat store's own title stays original — same
92
- // pre-existing behavior as the default chat's titleChanged).
93
- this.publish({
94
- channel: rec.channel,
95
- action: { type: ActionType.SessionChatUpdated, chat: chat.uri, changes: { title: ev.title } },
96
- });
97
- }
87
+ this.updateBackendTitle(rec, chatURI, ev.title);
98
88
  return;
99
89
  case "inbox.enqueued":
100
90
  chat.lastInbox = {
@@ -340,9 +330,10 @@ export class HostEvents extends HostDispatch {
340
330
  this.clearToolTracking(chat, ev.id);
341
331
  return;
342
332
  }
343
- case "usage.updated":
344
- // Session-cumulative tokens; the chat reducer replaces the turn's
345
- // usage, so the latest cumulative values are the turn's view.
333
+ case "step.ended":
334
+ // VS Code uses the current usage as context occupancy. A later
335
+ // model call replaces this one; session totals count the same
336
+ // prefix again for every call.
346
337
  if (chat.currentTurnId === null) return;
347
338
  this.publish({
348
339
  channel: chatURI,
@@ -350,8 +341,8 @@ export class HostEvents extends HostDispatch {
350
341
  type: ActionType.ChatUsage,
351
342
  turnId: chat.currentTurnId,
352
343
  usage: {
353
- inputTokens: ev.tokens.input,
354
- outputTokens: ev.tokens.output,
344
+ inputTokens: ev.tokens.input + ev.tokens.cache.read + ev.tokens.cache.write,
345
+ outputTokens: ev.tokens.output + ev.tokens.reasoning,
355
346
  cacheReadTokens: ev.tokens.cache.read,
356
347
  ...(chat.turnModelRef !== null ? { model: chat.turnModelRef } : {}),
357
348
  },
package/src/host-rpc.ts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { HostEvents } from "./host-events.js";
6
6
  import { ActionType, ChangesetStatus, ReconnectResultType, ReconnectResult, Snapshot } from "@microsoft/agent-host-protocol";
7
- import { mapCatalog } from "./bridge.js";
7
+ import { directoryUri, mapCatalog } from "./bridge.js";
8
8
  import { ROOT_CHANNEL, parseChangesetChannel } from "./channels.js";
9
9
  import { ERROR_INVALID_PARAMS, handleInitialize } from "./handshake.js";
10
10
  import { isRecord } from "./options.js";
@@ -203,7 +203,7 @@ export class HostRpc extends HostEvents {
203
203
  break;
204
204
  case "setClientManagedSettingsPermissions":
205
205
  // VS Code-specific post-init notification: the
206
- // permissions VS Code manages in its own settings UI. AHP 1.0.0
206
+ // permissions VS Code manages in its own settings UI. AHP
207
207
  // has no counterpart — accept deliberately (parse + log), never
208
208
  // error; the connection stays up.
209
209
  this.log(
@@ -241,7 +241,8 @@ export class HostRpc extends HostEvents {
241
241
  params: msg.params,
242
242
  serverInfo: this.opts.serverInfo,
243
243
  serverSeq: this.seq.seq,
244
- defaultDirectory: this.opts.defaultDirectory,
244
+ defaultDirectory: this.opts.defaultDirectory !== undefined ? directoryUri(this.opts.defaultDirectory) : undefined,
245
+ pathStyle: this.opts.pathStyle,
245
246
  snapshotFor: (uri) => this.snapshotFor(uri),
246
247
  });
247
248
  if (!outcome.ok) {
@@ -430,7 +431,9 @@ export class HostRpc extends HostEvents {
430
431
  }
431
432
  const chat = rec.chats.get(uri);
432
433
  if (chat !== undefined) {
433
- return { resource: uri, state: chat.chatStore.state, fromSeq: this.seq.seq };
434
+ const state = chat.chatStore.state;
435
+ const title = rec.sessionStore.state.chats.find((entry) => entry.resource === uri)?.title ?? state.title;
436
+ return { resource: uri, state: { ...state, title }, fromSeq: this.seq.seq };
434
437
  }
435
438
  return null;
436
439
  }
@@ -44,7 +44,7 @@ const LIST_SESSIONS_DEFAULT_LIMIT = 100;
44
44
 
45
45
  export class HostSessions extends HostChats {
46
46
  /**
47
- * `createSession` (AHP 1.0.0 session-channel command). Creates a real
47
+ * `createSession` (AHP session-channel command). Creates a real
48
48
  * opencode session, seeds its session/chat stores, publishes the
49
49
  * session-channel lifecycle actions, announces the session on the root
50
50
  * channel, and responds `null` (per the command contract). The
@@ -145,7 +145,7 @@ export class HostSessions extends HostChats {
145
145
  activeClients = [normalizeActiveClient(ac)];
146
146
  }
147
147
 
148
- // `workingDirectories` (AHP 1.0.0): the directory the session's
148
+ // `workingDirectories`: the directory the session's
149
149
  // agent is granted tool access to. The host advertises no
150
150
  // multipleWorkingDirectories, so the spec applies — only the first
151
151
  // entry is honored (extras are logged and ignored); it must be a
@@ -312,7 +312,7 @@ export class HostSessions extends HostChats {
312
312
  // non-standard (legacy) session channels, which classify "unknown"
313
313
  // by prefix and resolve only through this set.
314
314
  this.channels.addSessionChannel(channel);
315
- const defaultChat = this.newChatRuntime(rec.defaultChatURI, created.sessionID, "Chat 1", now);
315
+ const defaultChat = this.newChatRuntime(rec.defaultChatURI, created.sessionID, sessionStore.state.title, now);
316
316
  this.bindChat(rec, defaultChat);
317
317
 
318
318
  // A createSession `activeClient` seeds the
@@ -359,7 +359,7 @@ export class HostSessions extends HostChats {
359
359
  }
360
360
 
361
361
  /**
362
- * `disposeSession` (AHP 1.0.0 session-channel command): dispose an AHP
362
+ * `disposeSession` (AHP session-channel command): dispose an AHP
363
363
  * session and every opencode backend behind it — the default backend
364
364
  * and each peer chat's backend. Result: `null`; the client's removal
365
365
  * signal is the `root/sessionRemoved` notification `removeRecord`
@@ -411,7 +411,7 @@ export class HostSessions extends HostChats {
411
411
  }
412
412
 
413
413
  /**
414
- * `listSessions` (AHP 1.0.0 root command): all opencode sessions,
414
+ * `listSessions` (AHP root command): all opencode sessions,
415
415
  * most-recently-modified first, with in-memory cursor pagination.
416
416
  * Unknown sessions are lazily registered (so their channels become
417
417
  * subscribable); registration is idempotent per opencode session id.
@@ -449,7 +449,7 @@ export class HostSessions extends HostChats {
449
449
  }
450
450
 
451
451
  /**
452
- * AHP 1.0.0 root command — the client resolves the session-creation
452
+ * AHP root command — the client resolves the session-creation
453
453
  * config schema. VS Code calls it every time the new-session composer
454
454
  * opens and STRICTLY again before the first send of a new session
455
455
  * (`_sendNewSessionRequest`), so an unimplemented host makes every
@@ -634,14 +634,14 @@ export class HostSessions extends HostChats {
634
634
  * after a restart. The owner store is LIVE (unlike a
635
635
  * fresh standalone registration), so the catalog change goes through
636
636
  * `publish` (store + any existing subscribers + the root diff), not a
637
- * direct apply. The chat title is re-derived (`Chat <n>`) — a
638
- * documented divergence from the pre-restart title. Returns undefined:
637
+ * direct apply. The chat title comes from the saved backend title.
638
+ * Returns undefined:
639
639
  * the backend gets no standalone AHP session (its session channel is
640
640
  * not registered — `sessions.get(peerID)` misses).
641
641
  */
642
642
  private reattachPeerChat(rec: SessionRecord, fs: FacadeSession, chatURI: string): undefined {
643
643
  const modifiedAt = new Date(fs.time.updated).toISOString();
644
- const chat = this.newChatRuntime(chatURI, fs.sessionID, `Chat ${rec.chats.size + 1}`, modifiedAt);
644
+ const chat = this.newChatRuntime(chatURI, fs.sessionID, fs.title ?? `Chat ${rec.chats.size + 1}`, modifiedAt);
645
645
  this.bindChat(rec, chat);
646
646
  this.publish({
647
647
  channel: rec.channel,
@@ -776,7 +776,7 @@ export class HostSessions extends HostChats {
776
776
  // Mirrors `handleCreateSession`: the channel URI stays subscribable
777
777
  // (load-bearing for non-standard legacy channels).
778
778
  this.channels.addSessionChannel(recChannel);
779
- const defaultChat = this.newChatRuntime(rec.defaultChatURI, fs.sessionID, "Chat 1", modifiedAt);
779
+ const defaultChat = this.newChatRuntime(rec.defaultChatURI, fs.sessionID, sessionStore.state.title, modifiedAt);
780
780
  this.bindChat(rec, defaultChat);
781
781
  sessionStore.apply({ type: ActionType.SessionReady });
782
782
  sessionStore.apply({ type: ActionType.SessionChatAdded, summary: chatSummaryOf(defaultChat.chatStore.state) });
@@ -141,7 +141,7 @@ export class HostTerminals extends HostResources {
141
141
  // ── pty terminals (createTerminal / disposeTerminal) ─────────────────
142
142
 
143
143
  /**
144
- * `createTerminal` (AHP 1.0.0): spawn an interactive pty shell in the
144
+ * `createTerminal` (AHP): spawn an interactive pty shell in the
145
145
  * resolved working directory and register the client-chosen channel.
146
146
  * The result is `null` per the AHP message contract — the client then
147
147
  * subscribes to the channel for the state snapshot. Errors: -32601 when
@@ -265,7 +265,7 @@ export class HostTerminals extends HostResources {
265
265
  }
266
266
 
267
267
  /**
268
- * `disposeTerminal` (AHP 1.0.0): kill the pty and drop its record.
268
+ * `disposeTerminal` (AHP): kill the pty and drop its record.
269
269
  * Idempotent success (`null`) for unknown channels — the VS Code
270
270
  * client's shutdown path disposes terminals that may already be gone
271
271
  * (its reference manager no-ops unknown URIs). Synthetic
package/src/host-turns.ts CHANGED
@@ -49,18 +49,23 @@ export class HostTurns extends HostTerminals {
49
49
  const endedTurnId = chat.currentTurnId;
50
50
  chat.currentTurnId = null;
51
51
  chat.turnStartedAt = null;
52
- const state = chat.chatStore.state;
53
- if (state.steeringMessage !== undefined) {
52
+ const steering = chat.chatStore.state.steeringMessage;
53
+ if (steering !== undefined) {
54
54
  this.publish({
55
55
  channel: chat.uri,
56
56
  action: {
57
57
  type: ActionType.ChatPendingMessageRemoved,
58
58
  kind: PendingMessageKind.Steering,
59
- id: state.steeringMessage.id,
59
+ id: steering.id,
60
60
  },
61
61
  });
62
62
  }
63
- const queued = state.queuedMessages;
63
+ // Re-read from the store, not the reference captured above: the
64
+ // official reducer upserts steering entries into the unified
65
+ // `queuedMessages`, so the removal publish just replaced the state
66
+ // object — a stale reference would still hold the consumed steering
67
+ // entry and auto-start a phantom turn from it.
68
+ const queued = chat.chatStore.state.queuedMessages;
64
69
  if (queued !== undefined && queued.length > 0) {
65
70
  const next = queued[0]!;
66
71
  this.startTurn(chat, next.message, next.id);
package/src/host-types.ts CHANGED
@@ -2,15 +2,16 @@
2
2
  * Record types shared by the host section classes: the per-socket, per-client, per-session, per-chat and per-terminal state shapes, and the HostOptions the Host is constructed with.
3
3
  */
4
4
 
5
- import { Implementation } from "@microsoft/agent-host-protocol";
5
+ import { Implementation, PathStyle } from "@microsoft/agent-host-protocol";
6
6
  import { OpencodeFacade } from "./bridge.js";
7
7
  import { ClientToolInvocation } from "./client-tools.js";
8
8
  import { ChatStateStore, ChangesetStateStore, SessionStateStore, TerminalStateStore } from "./state.js";
9
9
  import type { PathPolicy } from "./path-policy.js";
10
10
 
11
- // ActionType / ReconnectResultType are `declare const enum` in the package
12
- // but are also real runtime objects (verified against the published dist),
13
- // so the value imports are safe under both tsc (inlined) and Bun.
11
+ // ActionType / ReconnectResultType / PathStyle are `declare const enum` in
12
+ // the package but are also real runtime objects (verified against the
13
+ // published dist), so the value imports are safe under both tsc (inlined)
14
+ // and Bun.
14
15
  export interface RpcMessage {
15
16
  jsonrpc?: unknown;
16
17
  id?: unknown;
@@ -212,15 +213,22 @@ export interface HostOptions {
212
213
  serverInfo: Implementation;
213
214
  facade: OpencodeFacade;
214
215
  replayWindow: number;
215
- /** The opencode instance's working directory (InitializeResult.defaultDirectory). */
216
+ /** The opencode instance's working directory as an absolute filesystem path. */
216
217
  defaultDirectory?: string;
218
+ /**
219
+ * The host environment's native path grammar, stamped onto
220
+ * `InitializeResult.environment.pathStyle` (AHP 1.1.0): clients format
221
+ * and parse native paths with it instead of inferring from their own
222
+ * environment. The plugin entry detects the platform once at setup.
223
+ */
224
+ pathStyle: PathStyle;
217
225
  /** Advertise + serve the changeset channels (catalogues, snapshots, discard). */
218
226
  changesets: boolean;
219
227
  /**
220
228
  * Serve the terminal channels — the synthetic shell-command renderings
221
229
  * (one read-only `ahp-terminal:` channel per foreground `shell`-tool
222
230
  * call) and the interactive pty shells behind `createTerminal`. Off the
223
- * wire in 1.0.0 (no capability field) — the switch gates the
231
+ * wire (no capability field) — the switch gates the
224
232
  * host-side behavior (off: the synthetic channels never open and the
225
233
  * terminal commands answer -32601).
226
234
  */
package/src/host.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * (a `Host` class) so the whole protocol layer is unit-testable and
8
8
  * exercisable by the spike client without a WebSocket runtime.
9
9
  *
10
- * Connection model (AHP 1.0.0 lifecycle spec):
10
+ * Connection model (AHP lifecycle spec):
11
11
  * - the first request on a socket is `initialize` (new client) or
12
12
  * `reconnect` (known clientId — the host keeps a per-clientId registry
13
13
  * across sockets);
@@ -34,7 +34,7 @@
34
34
  *
35
35
  * Root session lifecycle events (`root/sessionAdded`,
36
36
  * `root/sessionRemoved`, `root/sessionSummaryChanged`) are JSON-RPC
37
- * *notifications* in AHP 1.0.0 (ephemeral, not replayed) — only
37
+ * *notifications* in AHP (ephemeral, not replayed) — only
38
38
  * `root/activeSessionsChanged` is a sequencer action.
39
39
  *
40
40
  * Module layout: this file only composes the host — the section classes
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * opencode-ahp — OpenCode V2 plugin: hosts the **Agent Host Protocol
3
- * (AHP) 1.0.0** in-process so opencode appears as a native agent in the
3
+ * (AHP)** in-process so opencode appears as a native agent in the
4
4
  * VS Code Agents window.
5
5
  *
6
6
  * This is the only module that touches the plugin `ctx` — everything
@@ -24,6 +24,7 @@
24
24
  * Every failure path logs and stays up: a bad client connection or a
25
25
  * bridge error must never take down the opencode server (R2).
26
26
  */
27
+ import { PathStyle } from "@microsoft/agent-host-protocol";
27
28
  import { execFile } from "node:child_process";
28
29
  import {
29
30
  lstat,
@@ -1026,6 +1027,9 @@ export default Plugin.define({
1026
1027
  ),
1027
1028
  replayWindow: opts.replayWindow,
1028
1029
  defaultDirectory: ctx.location.directory,
1030
+ // AHP 1.1.0: the client's path grammar for this host's native
1031
+ // paths (the client must not infer it from its own environment).
1032
+ pathStyle: process.platform === "win32" ? PathStyle.Windows : PathStyle.Posix,
1029
1033
  changesets: opts.capabilities.changesets,
1030
1034
  terminals: opts.capabilities.terminals,
1031
1035
  spawnPty: createBunSpawnPty(),
@@ -1087,7 +1091,7 @@ export default Plugin.define({
1087
1091
  }
1088
1092
  };
1089
1093
  console.log(
1090
- `${TAG} AHP 1.0.0 host listening on ws${opts.tls ? "s" : ""}://${opts.host}:${listener.port}${opts.path} ` +
1094
+ `${TAG} AHP 1.1.0 host listening on ws${opts.tls ? "s" : ""}://${opts.host}:${listener.port}${opts.path} ` +
1091
1095
  `(token ${opts.token ? "from options" : "auto-generated"}; health ${opts.healthPath})`,
1092
1096
  );
1093
1097
  } catch (e) {
package/src/options.ts CHANGED
@@ -80,7 +80,7 @@ export const BUILTIN_OPTIONS: Options = {
80
80
  // Changesets and the synthetic shell-command terminals are both on by
81
81
  // default; opt out with `capabilities.changesets: false` and
82
82
  // `capabilities.terminals: false` respectively.
83
- // Off the wire in 1.0.0 (no capability field) — the flag gates the
83
+ // Off the wire (no capability field) — the flag gates the
84
84
  // host-side behavior only.
85
85
  capabilities: { changesets: true, terminals: true, automations: false },
86
86
  };
package/src/seq.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Global action sequencer + replay window.
3
3
  *
4
- * AHP 1.0.0's `serverSeq` is a single host-wide sequence across all
4
+ * AHP's `serverSeq` is a single host-wide sequence across all
5
5
  * channels (not per-channel) — the spec's lifecycle example numbers a
6
6
  * chat action 43 while a root snapshot is taken at 42. Consequences:
7
7
  * - snapshots carry `fromSeq` = the current global seq;