opencode-ahp 0.1.0 → 0.1.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
@@ -86,6 +86,8 @@ sibling of `src/index.ts` (checkouts only — copy
86
86
  | `allowedOrigins` | `"*"` | `"*"` or an exact list, e.g. `["vscode://vscode"]`. The token is still always required regardless |
87
87
  | `tls` | `null` | `{ keyPath, certPath }` — native TLS → `wss://` (post-MVP; only needed for off-LAN transports) |
88
88
  | `healthPath` | `"/healthz"` | Plain-HTTP health endpoint (no auth): `curl …:8765/healthz` → `ok` |
89
+ | `keepAlive` | `true` | Keep the opencode location loaded against its idle timeout (`experimental.location_idle_timeout`, default 60 min) by periodically touching an internal anchor session — with this on, **no `location_idle_timeout` config entry is needed**. The anchor (`opencode-ahp (keep-alive)`) is a real opencode session: it shows in the TUI session list but is hidden from AHP clients (opencode's plugin surface cannot archive it) |
90
+ | `keepAliveIntervalMinutes` | `10` | Minutes between keep-alive touches; keep well below the effective idle timeout |
89
91
  | `replayWindow` | `1000` | Per-channel actions kept for reconnect replay; older gaps → fresh snapshot |
90
92
  | `capabilities` | `{ changesets: false, terminals: false, automations: false }` | Advertised in `initialize` — never advertise what we don't implement |
91
93
 
@@ -105,10 +107,6 @@ port forward, any `wss://` proxy) are post-MVP; the host accepts any
105
107
 
106
108
  ```jsonc
107
109
  {
108
- // Required: opencode v2 unloads idle locations after 60 minutes, and
109
- // AHP WebSocket connections do NOT count as location activity —
110
- // without this the listener silently stops overnight.
111
- "experimental": { "location_idle_timeout": false },
112
110
  "plugins": [{
113
111
  "package": "opencode-ahp",
114
112
  "options": {
@@ -120,17 +118,28 @@ port forward, any `wss://` proxy) are post-MVP; the host accepts any
120
118
  }
121
119
  ```
122
120
 
121
+ No `experimental.location_idle_timeout` entry needed: by default the
122
+ plugin keeps its own location loaded (`keepAlive`, see Options) by
123
+ periodically touching an internal anchor session (visible in the TUI
124
+ session list as "opencode-ahp (keep-alive)", hidden from AHP clients)
125
+ — opencode's idle sweep never fires.
126
+
123
127
  3. **Boot the location once** — the AHP listener exists only while the
124
- location is up. Open the project once (run the `opencode` TUI in it, or
125
- open it in an IDE), or headless:
128
+ location is up, and a location boots on first use. After a fresh server
129
+ start (e.g. machine reboot), open the project once (run the `opencode`
130
+ TUI in it, or open it in an IDE), or headless:
126
131
 
127
132
  ```sh
128
133
  curl -g -u opencode:<server-password> \
129
134
  'http://127.0.0.1:<port>/api/location?location[directory]=<project-dir>'
130
135
  ```
131
136
 
132
- With `location_idle_timeout: false` the listener then stays up
133
- indefinitely.
137
+ This is a one-time step per server process: the keep-alive then holds
138
+ the location (and the listener) indefinitely, and reloading the
139
+ location (config change, `opencode service restart`) re-boots it
140
+ automatically. (The one-time boot itself is an opencode limitation —
141
+ plugins cannot run before their location has booted; a zero-touch boot
142
+ needs an upstream auto-boot option.)
134
143
  4. Verify: `curl -s http://<host-lan-ip>:<port>/healthz` → `ok`.
135
144
 
136
145
  Full two-machine walkthrough:
@@ -182,7 +191,7 @@ repo secret is stored (one-time setup: npmjs.com → package → *Package
182
191
  settings* → *Trusted publishers* → this workflow).
183
192
 
184
193
  Installed copies don't auto-update: `opencode plugin update opencode-ahp`
185
- + `opencode service restart`.
194
+ - `opencode service restart`.
186
195
 
187
196
  ## License
188
197
 
@@ -35,6 +35,18 @@
35
35
  // Plain-HTTP health endpoint (no auth).
36
36
  // "healthPath": "/healthz",
37
37
 
38
+ // Keep the opencode location loaded against the idle timeout
39
+ // (experimental.location_idle_timeout, default 60 min) by touching an
40
+ // internal anchor session periodically (plan §15). On, the
41
+ // location_idle_timeout config entry is not needed. The anchor shows in
42
+ // the TUI session list as "opencode-ahp (keep-alive)"; AHP clients never
43
+ // see it.
44
+ // "keepAlive": true,
45
+
46
+ // Minutes between keep-alive touches; keep well below the effective idle
47
+ // timeout (10 leaves sixfold headroom under the 60-minute default).
48
+ // "keepAliveIntervalMinutes": 10,
49
+
38
50
  // Global actions kept for reconnect replay; older gaps → fresh snapshot.
39
51
  // "replayWindow": 1000,
40
52
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-ahp",
3
- "version": "0.1.0",
3
+ "version": "0.1.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/error.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** Normalize an unknown thrown value to a loggable message. */
2
+ export function errorMessage(e: unknown): string {
3
+ return e instanceof Error ? e.message : String(e);
4
+ }
package/src/index.ts CHANGED
@@ -10,14 +10,17 @@
10
10
  *
11
11
  * Lifecycle:
12
12
  * 1. resolve options (ctx.options ▸ options.jsonc sibling ▸ built-ins;
13
- * a malformed sibling file → one error log + re-resolve without it)
14
- * 2. `enabled: false` → the plugin is fully inert (no listener)
15
- * 3. token: explicit option, else persisted in ctx.storage (generated
13
+ * a malformed sibling file → one error log + re-resolve without it);
14
+ * `enabled: false` → the plugin is fully inert (no listener)
15
+ * 2. token: explicit option, else persisted in ctx.storage (generated
16
16
  * once, printed once to the server log)
17
+ * 3. keep-alive (plan §15): get-or-create the anchor session and start
18
+ * touching it periodically so the location survives the idle timeout
19
+ * without any user config
17
20
  * 4. wire the Host (JSON-RPC router) to the transport (Bun.serve)
18
21
  * 5. start the opencode event pump (maps `ctx.event.subscribe` into
19
22
  * the host's AHP action stream — plan §6.1/§11)
20
- * 6. return cleanup that stops the pump and the listener
23
+ * 6. return cleanup that stops the keep-alive, the pump, and the listener
21
24
  *
22
25
  * Every failure path logs and stays up: a bad client connection or a
23
26
  * bridge error must never take down the opencode server (R2).
@@ -41,6 +44,8 @@ type SessionInfo = Awaited<ReturnType<SessionDomain["get"]>>;
41
44
  import { isRecord, resolveOptions, type Options } from "./options.js";
42
45
  import { createListener, type Listener } from "./transport.js";
43
46
  import { Host } from "./host.js";
47
+ import { KeepAlive, KEEPALIVE_SESSION_ID } from "./keep-alive.js";
48
+ import { errorMessage } from "./error.js";
44
49
  import {
45
50
  mapV2Event,
46
51
  type FacadeAgent,
@@ -55,10 +60,6 @@ const TAG = "[opencode-ahp]";
55
60
  /** ctx.storage key for the persisted auto-generated token. */
56
61
  const TOKEN_STORAGE_KEY = "ahp.token";
57
62
 
58
- function errorMessage(e: unknown): string {
59
- return e instanceof Error ? e.message : String(e);
60
- }
61
-
62
63
  /** Raw text of the `options.jsonc` sibling of this file, or null when absent. */
63
64
  function readOptionsFile(): string | null {
64
65
  try {
@@ -81,7 +82,7 @@ function pluginVersion(): string {
81
82
  } catch {
82
83
  // fall through to the fallback
83
84
  }
84
- return "0.1.0";
85
+ return "0.1.1";
85
86
  }
86
87
 
87
88
  /** 32 random bytes, base64url — 43 chars, comfortably over the 16-char floor. */
@@ -132,6 +133,13 @@ function mapSessionInfo(info: SessionInfo): FacadeSession {
132
133
  };
133
134
  }
134
135
 
136
+ /** True when a raw V2 event envelope (`{id, type, data}`) belongs to a session. */
137
+ function isHiddenSessionEvent(event: unknown, hiddenSessionID: string): boolean {
138
+ if (!isRecord(event)) return false;
139
+ const data = event["data"];
140
+ return isRecord(data) && data["sessionID"] === hiddenSessionID;
141
+ }
142
+
135
143
  /**
136
144
  * The narrow opencode surface the bridge needs (plan §3.2, §14.7, §11).
137
145
  *
@@ -147,8 +155,14 @@ function mapSessionInfo(info: SessionInfo): FacadeSession {
147
155
  * Phase 1 adds the session surface: create/list/get, prompt with
148
156
  * `delivery` (steer|queue), switchModel/switchAgent, interrupt, update
149
157
  * (rename), permission reply, and the mapped event stream.
158
+ *
159
+ * `hiddenSessionID` (the keep-alive anchor, plan §15) is filtered from all
160
+ * three session surfaces so the AHP client never sees it: `list`/snapshots
161
+ * (by ID), `get` (null = not found), and the event stream (by
162
+ * `data.sessionID` — covers `session.created` and anything a future bridge
163
+ * version may map).
150
164
  */
151
- function implementFacade(ctx: Context): OpencodeFacade {
165
+ function implementFacade(ctx: Context, hiddenSessionID: string | null): OpencodeFacade {
152
166
  return {
153
167
  async listCatalog() {
154
168
  const [providers, models] = await Promise.all([ctx.provider.list(), ctx.model.list()]);
@@ -213,9 +227,12 @@ function implementFacade(ctx: Context): OpencodeFacade {
213
227
  },
214
228
  async listSessions() {
215
229
  const { data } = await ctx.session.list();
216
- return data.map(mapSessionInfo);
230
+ return data
231
+ .filter((s) => String(s.id) !== hiddenSessionID)
232
+ .map(mapSessionInfo);
217
233
  },
218
234
  async getSession(sessionID: string) {
235
+ if (sessionID === hiddenSessionID) return null;
219
236
  try {
220
237
  return mapSessionInfo(await ctx.session.get({ sessionID }));
221
238
  } catch {
@@ -263,6 +280,7 @@ function implementFacade(ctx: Context): OpencodeFacade {
263
280
  */
264
281
  async *events(signal: AbortSignal) {
265
282
  for await (const event of ctx.event.subscribe({ signal })) {
283
+ if (hiddenSessionID !== null && isHiddenSessionEvent(event, hiddenSessionID)) continue;
266
284
  const mapped = mapV2Event(event);
267
285
  if (mapped !== null) yield mapped;
268
286
  }
@@ -295,7 +313,47 @@ export default Plugin.define({
295
313
  return; // R2: the opencode server stays up without AHP
296
314
  }
297
315
 
298
- // 3. Host + transport. The host's send/close callbacks close over the
316
+ // 3. Keep-alive (plan §15). Before the host exists, so the anchor
317
+ // session's `session.created` fires before the event pump subscribesbscribes
318
+ // and never reaches AHP clients (the facade filters it from the
319
+ // snapshot/list surfaces regardless). A deterministic session ID means
320
+ // reloads reuse the same session — no accumulation in the DB.
321
+ // start() never throws: on failure the keep-alive stays off and
322
+ // opencode's idle timeout applies as before (R2).
323
+ const hiddenSessionID = opts.keepAlive ? KEEPALIVE_SESSION_ID : null;
324
+ let keepAlive: KeepAlive | null = null;
325
+ if (opts.keepAlive) {
326
+ keepAlive = new KeepAlive({
327
+ // Get-or-create. (Upstream gap, plan §15: `SessionUpdateInput`
328
+ // advertises `archived`, but the plugin host's `session.update`
329
+ // drops it — `packages/core/src/plugin/host.ts` forwards only
330
+ // title/metadata/permissions, in v2.2.6 and current dev. So the
331
+ // anchor cannot be archived from a plugin; it is visible in the
332
+ // opencode TUI session list as "opencode-ahp (keep-alive)" and is
333
+ // filtered out of every AHP surface by ID instead.)
334
+ ensureSession: async () => {
335
+ try {
336
+ await ctx.session.get({ sessionID: KEEPALIVE_SESSION_ID });
337
+ } catch {
338
+ await ctx.session.create({
339
+ id: KEEPALIVE_SESSION_ID,
340
+ title: "opencode-ahp (keep-alive)",
341
+ metadata: { "opencode-ahp": "keep-alive" },
342
+ });
343
+ }
344
+ },
345
+ touch: () =>
346
+ ctx.session.update({
347
+ sessionID: KEEPALIVE_SESSION_ID,
348
+ metadata: { "opencode-ahp": "keep-alive", keepAliveAt: Date.now() },
349
+ }),
350
+ intervalMs: opts.keepAliveIntervalMinutes * 60_000,
351
+ log: (msg) => console.warn(`${TAG} ${msg}`),
352
+ });
353
+ await keepAlive.start();
354
+ }
355
+
356
+ // 4. Host + transport. The host's send/close callbacks close over the
299
357
  // listener variable, which is assigned immediately after the host is
300
358
  // constructed (the listener's socket ids are the host's socket ids).
301
359
  let listener: Listener | null = null;
@@ -303,7 +361,7 @@ export default Plugin.define({
303
361
  try {
304
362
  const host = new Host({
305
363
  serverInfo: { name: "opencode-ahp", version: pluginVersion(), title: "OpenCode" },
306
- facade: implementFacade(ctx),
364
+ facade: implementFacade(ctx, hiddenSessionID),
307
365
  replayWindow: opts.replayWindow,
308
366
  defaultDirectory: ctx.location.directory,
309
367
  send: (socketId, message) => {
@@ -341,19 +399,19 @@ export default Plugin.define({
341
399
  );
342
400
  } catch (e) {
343
401
  console.error(`${TAG} failed to start the AHP listener: ${errorMessage(e)}`);
402
+ keepAlive?.stop(); // don't hold the location for a dead AHP host
344
403
  listener?.stop();
345
404
  listener = null;
346
405
  return; // R2: the opencode server stays up without AHP
347
406
  }
348
407
 
349
- // 4. Cleanup: stop the pump (aborts the event subscription) and stop
350
- // the listener, dropping every client connection. Logged because
351
- // opencode silently unloads idle locations
352
- // (`experimental.location_idle_timeout`, default 60 minutes) and a
353
- // torn-down listener with no log line is otherwise undiagnosable
354
- // (plan §14.8).
408
+ // 6. Cleanup: stop the keep-alive timer, stop the pump (aborts the
409
+ // event subscription), and stop the listener, dropping every client
410
+ // connection. Logged because a torn-down listener with no log line
411
+ // is otherwise undiagnosable (plan §14.8).
355
412
  return () => {
356
413
  console.log(`${TAG} location teardown — stopping the AHP host (location unloaded by opencode)`);
414
+ keepAlive?.stop();
357
415
  cleanupHost?.();
358
416
  listener?.stop();
359
417
  };
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Location keep-alive (plan §15).
3
+ *
4
+ * opencode v2 unloads idle locations after `experimental.location_idle_timeout`
5
+ * (default 60 minutes). `LocationActivity` (packages/core/src/location-activity.ts)
6
+ * "touches" a location on every **durable** session event and evicts it on a
7
+ * one-minute sweep only when it is past its TTL, unoccupied, and unretained.
8
+ * `Session.setMetadata` publishes the durable `session.metadata.updated` event
9
+ * unconditionally, so periodically updating the metadata of a dedicated anchor
10
+ * session keeps the location — and with it the AHP listener — loaded without
11
+ * any user config (`location_idle_timeout: false` is no longer required).
12
+ *
13
+ * The anchor session is visible in the opencode TUI session list (the plugin
14
+ * surface cannot archive it — plan §15); the AHP host filters it out by its
15
+ * deterministic ID from every client-facing surface.
16
+ *
17
+ * Cold boot is an architectural limit, not a keep-alive problem: plugins load
18
+ * per location (`Node.makeLocationNode`) and cannot run before the location
19
+ * boots, and no config boots a location at server start. The anchor session's
20
+ * first touch therefore only helps once the location is up — the one-time boot
21
+ * step stays (README "Remote access").
22
+ *
23
+ * Pure module: session access and the timer are dependency-injected, so this
24
+ * is unit-tested without an OpenCode runtime (house pattern).
25
+ */
26
+
27
+ import { errorMessage } from "./error.js";
28
+
29
+ /**
30
+ * Deterministic anchor-session ID. Valid per the `Session.ID` schema (any
31
+ * `ses`-prefixed string); deterministic so reloads reuse the same session
32
+ * instead of accumulating one per boot cycle, and so the AHP facade can
33
+ * filter it by a constant (no metadata reads, no list scans).
34
+ */
35
+ export const KEEPALIVE_SESSION_ID = "ses_ahp_keepalive";
36
+
37
+ export interface KeepAliveDeps {
38
+ /**
39
+ * Get-or-create the anchor session. Resolves when the session is usable;
40
+ * rejects (→ keep-alive stays off, logged) when it is not.
41
+ */
42
+ readonly ensureSession: () => Promise<void>;
43
+ /** One durable touch of the anchor session (`session.metadata.updated`). */
44
+ readonly touch: () => Promise<void>;
45
+ /**
46
+ * Interval between touches in ms. Must be well below the effective
47
+ * `location_idle_timeout` (default 60 minutes) — the default 10 minutes
48
+ * leaves sixfold headroom.
49
+ */
50
+ readonly intervalMs: number;
51
+ readonly log: (msg: string) => void;
52
+ /** Injectable for tests; defaults to `setInterval`. */
53
+ readonly schedule?: (fn: () => void, ms: number) => unknown;
54
+ /** Injectable for tests; defaults to `clearInterval`. */
55
+ readonly unschedule?: (handle: unknown) => void;
56
+ }
57
+
58
+ /**
59
+ * Periodic durable touch of the anchor session. Every failure path logs and
60
+ * stays up (R2): a failing touch retries on the next tick, a failing anchor
61
+ * setup leaves the keep-alive off (opencode's idle timeout applies as before).
62
+ */
63
+ export class KeepAlive {
64
+ private timer: unknown = null;
65
+ private inFlight = false;
66
+ private stopped = false;
67
+ private ready = false;
68
+
69
+ constructor(private readonly deps: KeepAliveDeps) {}
70
+
71
+ /**
72
+ * Ensures the anchor session and starts ticking. Never throws.
73
+ * @returns true when the keep-alive is active.
74
+ */
75
+ async start(): Promise<boolean> {
76
+ try {
77
+ await this.deps.ensureSession();
78
+ } catch (e) {
79
+ this.deps.log(
80
+ `keep-alive could not prepare its anchor session (${errorMessage(e)}); ` +
81
+ `opencode's idle timeout applies (experimental.location_idle_timeout)`,
82
+ );
83
+ return false;
84
+ }
85
+ this.ready = true;
86
+ this.startTicking();
87
+ this.deps.log(
88
+ `keep-alive active: the anchor session is touched every ${Math.round(this.deps.intervalMs / 60_000)} min, ` +
89
+ `holding the location against the idle timeout`,
90
+ );
91
+ return true;
92
+ }
93
+
94
+ /** Starts the periodic touch. Idempotent; a no-op before a ready session. */
95
+ startTicking(): void {
96
+ if (!this.ready || this.timer !== null || this.stopped) return;
97
+ const schedule = this.deps.schedule ?? ((fn: () => void, ms: number) => setInterval(fn, ms));
98
+ this.timer = schedule(() => {
99
+ void this.tick();
100
+ }, this.deps.intervalMs);
101
+ }
102
+
103
+ /** One touch. Guarded against overlap; never throws. */
104
+ async tick(): Promise<void> {
105
+ if (!this.ready || this.stopped || this.inFlight) return;
106
+ this.inFlight = true;
107
+ try {
108
+ await this.deps.touch();
109
+ } catch (e) {
110
+ this.deps.log(`keep-alive touch failed (${errorMessage(e)}); retrying on the next tick`);
111
+ } finally {
112
+ this.inFlight = false;
113
+ }
114
+ }
115
+
116
+ /** Stops the periodic touch (location teardown). Idempotent. */
117
+ stop(): void {
118
+ this.stopped = true;
119
+ if (this.timer !== null) {
120
+ const unschedule = this.deps.unschedule ?? ((handle: unknown) => clearInterval(handle as ReturnType<typeof setInterval>));
121
+ unschedule(this.timer);
122
+ this.timer = null;
123
+ }
124
+ }
125
+ }
package/src/options.ts CHANGED
@@ -39,6 +39,20 @@ export interface Options {
39
39
  tls: TlsOptions | null;
40
40
  /** Plain-HTTP health endpoint (no auth). */
41
41
  healthPath: string;
42
+ /**
43
+ * Keep the opencode location loaded against the idle timeout (default
44
+ * `experimental.location_idle_timeout`, 60 minutes) via a periodic durable
45
+ * touch of an internal anchor session (plan §15). With this on, the
46
+ * `location_idle_timeout: false` config entry is not needed. The anchor
47
+ * shows in the TUI session list as "opencode-ahp (keep-alive)"; AHP
48
+ * clients never see it.
49
+ */
50
+ keepAlive: boolean;
51
+ /**
52
+ * Minutes between keep-alive touches; must be well below the effective
53
+ * idle timeout. 10 leaves sixfold headroom under the 60-minute default.
54
+ */
55
+ keepAliveIntervalMinutes: number;
42
56
  /** Global actions kept for reconnect replay; older gaps → snapshot. */
43
57
  replayWindow: number;
44
58
  /** Advertised in `initialize` (plan §8.2). */
@@ -54,6 +68,8 @@ export const BUILTIN_OPTIONS: Options = {
54
68
  allowedOrigins: "*",
55
69
  tls: null,
56
70
  healthPath: "/healthz",
71
+ keepAlive: true,
72
+ keepAliveIntervalMinutes: 10,
57
73
  replayWindow: 1000,
58
74
  capabilities: { changesets: false, terminals: false, automations: false },
59
75
  };
@@ -223,6 +239,12 @@ export function resolveOptions(
223
239
  BUILTIN_OPTIONS.allowedOrigins,
224
240
  tls: pickNullable("tls", validateTls, BUILTIN_OPTIONS.tls),
225
241
  healthPath: pick("healthPath", isUrlPath, BUILTIN_OPTIONS.healthPath),
242
+ keepAlive: pick("keepAlive", isBool, BUILTIN_OPTIONS.keepAlive),
243
+ keepAliveIntervalMinutes: pick(
244
+ "keepAliveIntervalMinutes",
245
+ isPosInt,
246
+ BUILTIN_OPTIONS.keepAliveIntervalMinutes,
247
+ ),
226
248
  replayWindow: pick("replayWindow", isPosInt, BUILTIN_OPTIONS.replayWindow),
227
249
  capabilities: resolveCapabilities(file["capabilities"], ctx["capabilities"]),
228
250
  };