opencode-ahp 0.1.6 → 0.1.8

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
@@ -127,7 +127,6 @@ important ones:
127
127
  | `token` | auto | Omit → generated on first start, persisted in opencode's plugin storage, printed once to the service log. Accepted via the `?token=` query param and `Authorization: Bearer <token>`. **Always enforced**, loopback or not |
128
128
  | `host` | `"127.0.0.1"` | Bind address; a **non-loopback bind requires an explicit `token`** (the listener refuses to start otherwise) |
129
129
  | `port` | `8765` | WS listen port |
130
- | `keepAlive` | `true` | Keep the opencode location loaded against its idle timeout by periodically touching an internal anchor session — with this on, **no `location_idle_timeout` config entry is needed**. See the example file for the anchor's visibility details |
131
130
 
132
131
  ## Remote access (local LAN)
133
132
 
@@ -156,11 +155,22 @@ port forward, any `wss://` proxy) are operational; the host accepts any
156
155
  }
157
156
  ```
158
157
 
159
- No `experimental.location_idle_timeout` entry needed: by default the
160
- plugin keeps its own location loaded (`keepAlive`, see Options) by
161
- periodically touching an internal anchor session (visible in the TUI
162
- session list as "opencode-ahp (keep-alive)", hidden from AHP clients)
163
- — opencode's idle sweep never fires.
158
+ **Mandatory for now: disable the location idle timeout.** opencode
159
+ unloads a location after it has been idle for
160
+ `experimental.location_idle_timeout` (default 60 minutes), and a
161
+ plugin cannot prevent the sweep — events a plugin publishes carry no
162
+ location, so they never count as location activity (see
163
+ [`docs/design.md`](docs/design.md) §15.3). Add, to the project's
164
+ `opencode.jsonc` (the one that selects this location):
165
+
166
+ ```jsonc
167
+ {
168
+ "experimental": { "location_idle_timeout": false }
169
+ }
170
+ ```
171
+
172
+ With this set, the location (and the AHP listener) stays loaded
173
+ indefinitely once booted.
164
174
 
165
175
  3. **Boot the location once** — the AHP listener exists only while the
166
176
  location is up, and a location boots on first use. After a fresh server
@@ -172,12 +182,13 @@ port forward, any `wss://` proxy) are operational; the host accepts any
172
182
  'http://127.0.0.1:<port>/api/location?location[directory]=<project-dir>'
173
183
  ```
174
184
 
175
- This is a one-time step per server process: the keep-alive then holds
176
- the location (and the listener) indefinitely, and reloading the
177
- location (config change, `opencode service restart`) re-boots it
178
- automatically. (The one-time boot itself is an opencode limitation —
179
- plugins cannot run before their location has booted; a zero-touch boot
180
- needs an upstream auto-boot option.)
185
+ This is a one-time step per server process: with
186
+ `location_idle_timeout: false` (step 2) the location (and the
187
+ listener) then stays loaded indefinitely, and reloading the location
188
+ (config change, `opencode service restart`) re-boots it automatically.
189
+ (The one-time boot itself is an opencode limitation — plugins cannot
190
+ run before their location has booted; a zero-touch boot needs an
191
+ upstream auto-boot option.)
181
192
  4. Verify: `curl -s http://<host-lan-ip>:<port>/healthz` → `ok`.
182
193
 
183
194
  Full two-machine walkthrough (and the complete testing strategy: unit,
@@ -37,18 +37,6 @@
37
37
  // Plain-HTTP health endpoint (no auth).
38
38
  // "healthPath": "/healthz",
39
39
 
40
- // Keep the opencode location loaded against the idle timeout
41
- // (experimental.location_idle_timeout, default 60 min) by touching an
42
- // internal anchor session periodically. On, the
43
- // location_idle_timeout config entry is not needed. The anchor shows in
44
- // the TUI session list as "opencode-ahp (keep-alive)"; AHP clients never
45
- // see it.
46
- // "keepAlive": true,
47
-
48
- // Minutes between keep-alive touches; keep well below the effective idle
49
- // timeout (10 leaves sixfold headroom under the 60-minute default).
50
- // "keepAliveIntervalMinutes": 10,
51
-
52
40
  // Global actions kept for reconnect replay; older gaps → fresh snapshot.
53
41
  // "replayWindow": 1000,
54
42
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-ahp",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
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
@@ -855,6 +855,63 @@ export function userMessage(text: string, model?: string, agentUri?: string): Me
855
855
  return message;
856
856
  }
857
857
 
858
+ /** Bitmask covering the mutually-exclusive activity bits (bits 0–4). */
859
+ const STATUS_ACTIVITY_MASK = (1 << 5) - 1;
860
+
861
+ /**
862
+ * The bit that uniquely marks an input-needed status: `InputNeeded` (24)
863
+ * *includes* the `InProgress` bit (8), so `status & InputNeeded` also
864
+ * matches plain in-progress — bit 16 (`InputNeeded & ~InProgress`) is the
865
+ * discriminator (the same bit the official reducer's
866
+ * `withInputNeededStatus` clears on drain).
867
+ */
868
+ const INPUT_NEEDED_MARKER = (SessionStatus.InputNeeded & ~SessionStatus.InProgress) as SessionStatus;
869
+
870
+ /**
871
+ * Derive `SessionSummary.status` per the AHP aggregation rules: the
872
+ * activity bits (0–4) come from the default chat, else the most recently
873
+ * modified chat; they are **promoted** to `InputNeeded` whenever any chat
874
+ * is blocked on input, else to `Error` whenever any chat is in an error
875
+ * state. The orthogonal flags (`IsRead` / `IsArchived`) are session-scoped
876
+ * and are preserved from `sessionStatus`.
877
+ *
878
+ * The activity bits are deliberately NOT taken from `sessionStatus`: the
879
+ * session reducer only reaches them through the input-queue path, and that
880
+ * path cannot lower them back to `Idle` once a turn ends (draining the
881
+ * queue leaves `InProgress` behind — the official reducer's "unblocked
882
+ * turn falls back to `InProgress`" assumes the session was promoted to
883
+ * `InProgress` when the turn started, which it is not; only the chat is).
884
+ * The chat summaries are the activity source of truth.
885
+ */
886
+ export function sessionSummaryStatus(
887
+ sessionStatus: SessionStatus,
888
+ chats: readonly ChatSummary[],
889
+ defaultChat: string | undefined,
890
+ ): SessionStatus {
891
+ const flags = sessionStatus & ~STATUS_ACTIVITY_MASK;
892
+ let source = defaultChat !== undefined ? chats.find((c) => c.resource === defaultChat) : undefined;
893
+ if (source === undefined) {
894
+ for (const c of chats) {
895
+ if (source === undefined || c.modifiedAt > source.modifiedAt) source = c;
896
+ }
897
+ }
898
+ let promoted: SessionStatus | undefined;
899
+ for (const c of chats) {
900
+ if (c.status & INPUT_NEEDED_MARKER) {
901
+ promoted = SessionStatus.InputNeeded;
902
+ break;
903
+ }
904
+ if (c.status & SessionStatus.Error) promoted = SessionStatus.Error;
905
+ }
906
+ const activity =
907
+ promoted !== undefined
908
+ ? promoted
909
+ : source !== undefined
910
+ ? ((source.status & STATUS_ACTIVITY_MASK) as SessionStatus)
911
+ : SessionStatus.Idle;
912
+ return (flags | activity) as SessionStatus;
913
+ }
914
+
858
915
  /**
859
916
  * Build the `SessionSummary` for root notifications / `listSessions` from
860
917
  * a live record's denormalized fields. `chats` is the full catalog in
package/src/host-base.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import { ActionType, ChangesetStatus, ActionEnvelope, ActionOrigin, ChatAction, ChatSummary, ChangesetAction, RootAction, SessionAction, SessionSummary, StateAction, TerminalAction } from "@microsoft/agent-host-protocol";
6
- import { buildSessionSummary, chatSummaryOf, directoryUri, FacadeSession } from "./bridge.js";
6
+ import { buildSessionSummary, chatSummaryOf, directoryUri, sessionSummaryStatus, type FacadeSession } from "./bridge.js";
7
7
  import { ChannelRegistry, ChannelKind, ROOT_CHANNEL, channelKind, parseChangesetChannel, sessionIDOf } from "./channels.js";
8
8
  import { Sequencer } from "./seq.js";
9
9
  import { createChangesetStateStore, createRootStateStore, ChangesetStateStore, RootStateStore } from "./state.js";
@@ -154,7 +154,9 @@ export class HostBase {
154
154
  * Propagate a changed chat summary into the session store's chat catalog
155
155
  * (`session/chatUpdated`) — the session status itself is only
156
156
  * reducer-reachable for read/archive/input-needed bits, so the chat
157
- * summary is the activity source of truth.
157
+ * summary is the activity source of truth (the summary-level
158
+ * `SessionSummary.status` is aggregated from the chats by
159
+ * `sessionSummaryStatus`, never read back from the session store).
158
160
  */
159
161
  private syncChatSummary(rec: SessionRecord, chatURI: string): void {
160
162
  const chat = rec.chats.get(chatURI)?.chatStore.state;
@@ -225,7 +227,12 @@ export class HostBase {
225
227
  channel: rec.channel,
226
228
  provider: rec.provider,
227
229
  title: s.title,
228
- status: s.status,
230
+ // Activity bits aggregated from the chat summaries (AHP rule): the
231
+ // session store's own status cannot source them — its reducer only
232
+ // reaches them through the input-queue path, which leaves
233
+ // `InProgress` set after an input-needed round trip when the turn
234
+ // ends. The `IsRead`/`IsArchived` flags stay session-scoped.
235
+ status: sessionSummaryStatus(s.status, chats, rec.defaultChatURI),
229
236
  activity: s.activity,
230
237
  createdAt: rec.createdAt,
231
238
  modifiedAt,
package/src/host-util.ts CHANGED
@@ -50,16 +50,14 @@ export function shellExitCodeOf(content: FacadeToolContent[]): number | null {
50
50
  * - on the default backend of a minted-id session:
51
51
  * `{ channel: <session channel URI> }` — the client-chosen session
52
52
  * channel (a "ses" suffix is its own opencode id and needs none).
53
- * (The keep-alive anchor uses the same key with a STRING value —
54
- * `parseAhpMarker` ignores non-record markers.)
55
53
  */
56
54
  export const AHP_METADATA_KEY = "opencode-ahp";
57
55
 
58
56
  /**
59
57
  * Parse the AHP markers from an opencode session's durable metadata.
60
- * Defensive: a malformed shape (missing key, non-record marker — e.g.
61
- * the keep-alive anchor — or wrong-kind fields) means "no marker" —
62
- * standalone registration under the opencode id.
58
+ * Defensive: a malformed shape (missing key, non-record marker, or
59
+ * wrong-kind fields) means "no marker" — standalone registration under
60
+ * the opencode id.
63
61
  */
64
62
  export function parseAhpMarker(metadata: unknown): { chat?: string; owner?: string; channel?: string } | null {
65
63
  if (!isRecord(metadata)) return null;
package/src/index.ts CHANGED
@@ -14,13 +14,10 @@
14
14
  * `enabled: false` → the plugin is fully inert (no listener)
15
15
  * 2. token: explicit option, else persisted in ctx.storage (generated
16
16
  * once, printed once to the server log)
17
- * 3. keep-alive: get-or-create the anchor session and start
18
- * touching it periodically so the location survives the idle timeout
19
- * without any user config
20
- * 4. wire the Host (JSON-RPC router) to the transport (Bun.serve)
21
- * 5. start the opencode event pump (maps `ctx.event.subscribe` into
17
+ * 3. wire the Host (JSON-RPC router) to the transport (Bun.serve)
18
+ * 4. start the opencode event pump (maps `ctx.event.subscribe` into
22
19
  * the host's AHP action stream)
23
- * 6. return cleanup that stops the keep-alive, the pump, and the listener
20
+ * 5. return cleanup that stops the pump and the listener
24
21
  *
25
22
  * Every failure path logs and stays up: a bad client connection or a
26
23
  * bridge error must never take down the opencode server (R2).
@@ -54,7 +51,6 @@ import { isRecord, resolveOptions, type Options } from "./options.js";
54
51
  import { createListener, type Listener } from "./transport.js";
55
52
  import { Host } from "./host.js";
56
53
  import type { SpawnPty } from "./host-types.js";
57
- import { KeepAlive, KEEPALIVE_SESSION_ID } from "./keep-alive.js";
58
54
  import { errorMessage } from "./error.js";
59
55
  import {
60
56
  eventLogLine,
@@ -248,13 +244,6 @@ function mapSessionInfo(info: SessionInfo): FacadeSession {
248
244
  };
249
245
  }
250
246
 
251
- /** True when a raw V2 event envelope (`{id, type, data}`) belongs to a session. */
252
- function isHiddenSessionEvent(event: unknown, hiddenSessionID: string): boolean {
253
- if (!isRecord(event)) return false;
254
- const data = event["data"];
255
- return isRecord(data) && data["sessionID"] === hiddenSessionID;
256
- }
257
-
258
247
  // ── changeset git helpers ──────────────────────────
259
248
  //
260
249
  // The plugin `ctx` has no "file content at HEAD" or "discard one file"
@@ -309,12 +298,6 @@ function isEnoent(err: unknown): boolean {
309
298
  * (steer|queue), switchModel/switchAgent, interrupt, update (rename),
310
299
  * permission reply, and the mapped event stream.
311
300
  *
312
- * `hiddenSessionID` (the keep-alive anchor) is filtered from all
313
- * three session surfaces so the AHP client never sees it: `list`/snapshots
314
- * (by ID), `get` (null = not found), and the event stream (by
315
- * `data.sessionID` — covers `session.created` and anything a future bridge
316
- * version may map).
317
- *
318
301
  * `hostRef`: the client-tool
319
302
  * `execute` bridge needs the host, but the facade is constructed as part
320
303
  * of the host's own options — a mutable holder assigned right after
@@ -328,7 +311,6 @@ type HostRef = { current: Host | null };
328
311
 
329
312
  function implementFacade(
330
313
  ctx: Context,
331
- hiddenSessionID: string | null,
332
314
  hostRef: HostRef,
333
315
  logEvent: ((line: string) => void) | null,
334
316
  ): OpencodeFacade {
@@ -434,12 +416,9 @@ function implementFacade(
434
416
  },
435
417
  async listSessions() {
436
418
  const { data } = await ctx.session.list();
437
- return data
438
- .filter((s) => String(s.id) !== hiddenSessionID)
439
- .map(mapSessionInfo);
419
+ return data.map(mapSessionInfo);
440
420
  },
441
421
  async getSession(sessionID: string) {
442
- if (sessionID === hiddenSessionID) return null;
443
422
  try {
444
423
  return mapSessionInfo(await ctx.session.get({ sessionID }));
445
424
  } catch {
@@ -493,7 +472,6 @@ function implementFacade(
493
472
  */
494
473
  async *events(signal: AbortSignal) {
495
474
  for await (const event of ctx.event.subscribe({ signal })) {
496
- if (hiddenSessionID !== null && isHiddenSessionEvent(event, hiddenSessionID)) continue;
497
475
  const outcome = mapV2EventRaw(event);
498
476
  if (logEvent !== null) logEvent(eventLogLine(outcome, event, timeStamp(new Date())));
499
477
  if (outcome.status === "ok") yield outcome.event;
@@ -647,47 +625,7 @@ export default Plugin.define({
647
625
  return; // R2: the opencode server stays up without AHP
648
626
  }
649
627
 
650
- // 3. Keep-alive. Before the host exists, so the anchor
651
- // session's `session.created` fires before the event pump subscribes
652
- // and never reaches AHP clients (the facade filters it from the
653
- // snapshot/list surfaces regardless). A deterministic session ID means
654
- // reloads reuse the same session — no accumulation in the DB.
655
- // start() never throws: on failure the keep-alive stays off and
656
- // opencode's idle timeout applies as before (R2).
657
- const hiddenSessionID = opts.keepAlive ? KEEPALIVE_SESSION_ID : null;
658
- let keepAlive: KeepAlive | null = null;
659
- if (opts.keepAlive) {
660
- keepAlive = new KeepAlive({
661
- // Get-or-create. (Upstream gap: `SessionUpdateInput`
662
- // advertises `archived`, but the plugin host's `session.update`
663
- // drops it — `packages/core/src/plugin/host.ts` forwards only
664
- // title/metadata/permissions, in v2.2.6 and current dev. So the
665
- // anchor cannot be archived from a plugin; it is visible in the
666
- // opencode TUI session list as "opencode-ahp (keep-alive)" and is
667
- // filtered out of every AHP surface by ID instead.)
668
- ensureSession: async () => {
669
- try {
670
- await ctx.session.get({ sessionID: KEEPALIVE_SESSION_ID });
671
- } catch {
672
- await ctx.session.create({
673
- id: KEEPALIVE_SESSION_ID,
674
- title: "opencode-ahp (keep-alive)",
675
- metadata: { "opencode-ahp": "keep-alive" },
676
- });
677
- }
678
- },
679
- touch: () =>
680
- ctx.session.update({
681
- sessionID: KEEPALIVE_SESSION_ID,
682
- metadata: { "opencode-ahp": "keep-alive", keepAliveAt: Date.now() },
683
- }),
684
- intervalMs: opts.keepAliveIntervalMinutes * 60_000,
685
- log: (msg) => console.warn(`${TAG} ${msg}`),
686
- });
687
- await keepAlive.start();
688
- }
689
-
690
- // 4. Host + transport. The host's send/close callbacks close over the
628
+ // 3. Host + transport. The host's send/close callbacks close over the
691
629
  // listener variable, which is assigned immediately after the host is
692
630
  // constructed (the listener's socket ids are the host's socket ids).
693
631
  let listener: Listener | null = null;
@@ -701,7 +639,6 @@ export default Plugin.define({
701
639
  serverInfo: { name: "opencode-ahp", version: pluginVersion(), title: "OpenCode" },
702
640
  facade: implementFacade(
703
641
  ctx,
704
- hiddenSessionID,
705
642
  hostRef,
706
643
  opts.logEvents ? (line) => console.log(line) : null,
707
644
  ),
@@ -745,7 +682,7 @@ export default Plugin.define({
745
682
  onClose: (info) => host.onClose(info.id),
746
683
  },
747
684
  );
748
- // 5. Event pump: opencode V2 events → AHP actions (the streaming
685
+ // 4. Event pump: opencode V2 events → AHP actions (the streaming
749
686
  // text/reasoning, tool lifecycle, permissions, usage, turn
750
687
  // terminals, steering/queue handoff).
751
688
  host.startEventPump();
@@ -761,19 +698,16 @@ export default Plugin.define({
761
698
  );
762
699
  } catch (e) {
763
700
  console.error(`${TAG} failed to start the AHP listener: ${errorMessage(e)}`);
764
- keepAlive?.stop(); // don't hold the location for a dead AHP host
765
701
  listener?.stop();
766
702
  listener = null;
767
703
  return; // R2: the opencode server stays up without AHP
768
704
  }
769
705
 
770
- // 6. Cleanup: stop the keep-alive timer, stop the pump (aborts the
771
- // event subscription), and stop the listener, dropping every client
772
- // connection. Logged because a torn-down listener with no log line
773
- // is otherwise undiagnosable.
706
+ // 5. Cleanup: stop the pump (aborts the event subscription) and stop
707
+ // the listener, dropping every client connection. Logged because a
708
+ // torn-down listener with no log line is otherwise undiagnosable.
774
709
  return () => {
775
710
  console.log(`${TAG} location teardown — stopping the AHP host (location unloaded by opencode)`);
776
- keepAlive?.stop();
777
711
  cleanupHost?.();
778
712
  listener?.stop();
779
713
  };
package/src/options.ts CHANGED
@@ -39,20 +39,6 @@ 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. 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;
56
42
  /** Global actions kept for reconnect replay; older gaps → snapshot. */
57
43
  replayWindow: number;
58
44
  /**
@@ -75,8 +61,6 @@ export const BUILTIN_OPTIONS: Options = {
75
61
  allowedOrigins: "*",
76
62
  tls: null,
77
63
  healthPath: "/healthz",
78
- keepAlive: true,
79
- keepAliveIntervalMinutes: 10,
80
64
  replayWindow: 1000,
81
65
  // Event capture is off by default (a busy turn emits dozens of lines);
82
66
  // the LAN test server script enables it.
@@ -254,12 +238,6 @@ export function resolveOptions(
254
238
  BUILTIN_OPTIONS.allowedOrigins,
255
239
  tls: pickNullable("tls", validateTls, BUILTIN_OPTIONS.tls),
256
240
  healthPath: pick("healthPath", isUrlPath, BUILTIN_OPTIONS.healthPath),
257
- keepAlive: pick("keepAlive", isBool, BUILTIN_OPTIONS.keepAlive),
258
- keepAliveIntervalMinutes: pick(
259
- "keepAliveIntervalMinutes",
260
- isPosInt,
261
- BUILTIN_OPTIONS.keepAliveIntervalMinutes,
262
- ),
263
241
  replayWindow: pick("replayWindow", isPosInt, BUILTIN_OPTIONS.replayWindow),
264
242
  logEvents: pick("logEvents", isBool, BUILTIN_OPTIONS.logEvents),
265
243
  capabilities: resolveCapabilities(file["capabilities"], ctx["capabilities"]),
package/src/keep-alive.ts DELETED
@@ -1,125 +0,0 @@
1
- /**
2
- * Location keep-alive.
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); 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 (open the project once, or a headless location-boot request).
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
- }