opencode-ahp 0.1.12 → 1.0.2

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
@@ -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.
@@ -345,11 +347,18 @@ this repo requires it.
345
347
 
346
348
  The published package is [`opencode-ahp` on npm](https://www.npmjs.com/package/opencode-ahp).
347
349
 
348
- Publishing is CI-only: push to `main` → CI (`typecheck` + `test`) → the
349
- publish workflow computes the version as `<major>.<minor>.<run-number>`
350
- and `npm publish`es via **npm trusted publishing (OIDC)** — no npm token
351
- or repo secret is stored (one-time setup: npmjs.com → package →
352
- *Package settings* → *Trusted publishers* → this workflow).
350
+ Publishing is CI-only, on a **daily schedule** (09:00 America/Denver) with
351
+ a manual trigger (Actions tab → *Create release* → *Run workflow*) for urgent
352
+ releases — a push to `main` no longer publishes on its own, so merged PRs
353
+ (batched, including external contributors') don't each get a release.
354
+ Each run first guards on commits since the last release tag and skips if
355
+ there are none; a published build is `npm publish`ed and tagged
356
+ `v<version>` as a GitHub release listing the commits since the previous
357
+ one. The version is computed as `<major>.<minor>.<run-number>` — run
358
+ numbers are consumed by skipped runs too, so the sequence has gaps — via
359
+ **npm trusted publishing (OIDC)** — no npm token or repo secret is stored
360
+ (one-time setup: npmjs.com → package → *Package settings* → *Trusted
361
+ publishers* → this workflow).
353
362
 
354
363
  ## Documentation
355
364
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-ahp",
3
- "version": "0.1.12",
3
+ "version": "1.0.2",
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
@@ -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
@@ -34,7 +34,7 @@ export interface InitializeRequest {
34
34
  serverInfo: Implementation;
35
35
  /** Current global serverSeq (stamped onto the result). */
36
36
  serverSeq: number;
37
- /** The opencode instance's working directory, when known. */
37
+ /** The file URI of the opencode instance's working directory, when known. */
38
38
  defaultDirectory?: string;
39
39
  /**
40
40
  * Resolve a snapshot for an `initialSubscriptions` entry; null when the
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;
@@ -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(
@@ -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";
@@ -241,7 +241,7 @@ 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
245
  snapshotFor: (uri) => this.snapshotFor(uri),
246
246
  });
247
247
  if (!outcome.ok) {
@@ -430,7 +430,9 @@ export class HostRpc extends HostEvents {
430
430
  }
431
431
  const chat = rec.chats.get(uri);
432
432
  if (chat !== undefined) {
433
- return { resource: uri, state: chat.chatStore.state, fromSeq: this.seq.seq };
433
+ const state = chat.chatStore.state;
434
+ const title = rec.sessionStore.state.chats.find((entry) => entry.resource === uri)?.title ?? state.title;
435
+ return { resource: uri, state: { ...state, title }, fromSeq: this.seq.seq };
434
436
  }
435
437
  return null;
436
438
  }
@@ -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
@@ -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) });
package/src/host-types.ts CHANGED
@@ -212,7 +212,7 @@ export interface HostOptions {
212
212
  serverInfo: Implementation;
213
213
  facade: OpencodeFacade;
214
214
  replayWindow: number;
215
- /** The opencode instance's working directory (InitializeResult.defaultDirectory). */
215
+ /** The opencode instance's working directory as an absolute filesystem path. */
216
216
  defaultDirectory?: string;
217
217
  /** Advertise + serve the changeset channels (catalogues, snapshots, discard). */
218
218
  changesets: boolean;
package/src/index.ts CHANGED
@@ -122,7 +122,7 @@ function pluginVersion(): string {
122
122
  } catch {
123
123
  // fall through to the fallback
124
124
  }
125
- return "0.1.1";
125
+ return "1.0.0";
126
126
  }
127
127
 
128
128
  /**