opencode-ahp 0.0.0-stage → 0.1.0

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/src/index.ts ADDED
@@ -0,0 +1,361 @@
1
+ /**
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
4
+ * VS Code Agents window (plan §8.1).
5
+ *
6
+ * This is the only module that touches the plugin `ctx` (plan §7
7
+ * pure-module principle). Everything else — options, transport,
8
+ * handshake, channels, seq, state, bridge, host — is pure or
9
+ * dependency-injected and unit-tested without an OpenCode runtime.
10
+ *
11
+ * Lifecycle:
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
16
+ * once, printed once to the server log)
17
+ * 4. wire the Host (JSON-RPC router) to the transport (Bun.serve)
18
+ * 5. start the opencode event pump (maps `ctx.event.subscribe` into
19
+ * the host's AHP action stream — plan §6.1/§11)
20
+ * 6. return cleanup that stops the pump and the listener
21
+ *
22
+ * Every failure path logs and stays up: a bad client connection or a
23
+ * bridge error must never take down the opencode server (R2).
24
+ */
25
+ import { readFileSync } from "node:fs";
26
+ import { fileURLToPath } from "node:url";
27
+ import { Plugin } from "@opencode/plugin";
28
+ // Type-only import of the plugin context. The package's root entry
29
+ // intentionally re-exports no `Context` (it is only ever observed as the
30
+ // `setup` parameter of `Plugin.define`); the subpath is part of the
31
+ // package's declared exports map (`./*` → `./dist/*`).
32
+ import type { Context } from "@opencode/plugin/promise/plugin";
33
+ import type { SessionDomain } from "@opencode/plugin/promise/session";
34
+ /**
35
+ * The opencode `SessionInfo` type (the plugin package does not re-export
36
+ * it from its public entry points; `SessionDomain["get"]` returns it).
37
+ * `@opencode/client` itself is only a transitive dependency, so the type
38
+ * is derived through the plugin package's declared subpaths.
39
+ */
40
+ type SessionInfo = Awaited<ReturnType<SessionDomain["get"]>>;
41
+ import { isRecord, resolveOptions, type Options } from "./options.js";
42
+ import { createListener, type Listener } from "./transport.js";
43
+ import { Host } from "./host.js";
44
+ import {
45
+ mapV2Event,
46
+ type FacadeAgent,
47
+ type FacadeModel,
48
+ type FacadeModelRef,
49
+ type FacadeSession,
50
+ type OpencodeFacade,
51
+ } from "./bridge.js";
52
+
53
+ const TAG = "[opencode-ahp]";
54
+
55
+ /** ctx.storage key for the persisted auto-generated token. */
56
+ const TOKEN_STORAGE_KEY = "ahp.token";
57
+
58
+ function errorMessage(e: unknown): string {
59
+ return e instanceof Error ? e.message : String(e);
60
+ }
61
+
62
+ /** Raw text of the `options.jsonc` sibling of this file, or null when absent. */
63
+ function readOptionsFile(): string | null {
64
+ try {
65
+ return readFileSync(fileURLToPath(new URL("./options.jsonc", import.meta.url)), "utf8");
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * The plugin's version for `InitializeResult.serverInfo`. Read from the
73
+ * package.json two levels up (src/index.ts → package root); falls back to
74
+ * the in-repo base version when the file is unavailable.
75
+ */
76
+ function pluginVersion(): string {
77
+ try {
78
+ const raw = readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8");
79
+ const parsed: unknown = JSON.parse(raw);
80
+ if (isRecord(parsed) && typeof parsed["version"] === "string") return parsed["version"];
81
+ } catch {
82
+ // fall through to the fallback
83
+ }
84
+ return "0.1.0";
85
+ }
86
+
87
+ /** 32 random bytes, base64url — 43 chars, comfortably over the 16-char floor. */
88
+ function generateToken(): string {
89
+ const bytes = new Uint8Array(32);
90
+ crypto.getRandomValues(bytes);
91
+ return Buffer.from(bytes).toString("base64url");
92
+ }
93
+
94
+ /**
95
+ * Token from options when set; otherwise the persisted one from plugin
96
+ * storage, generated (and printed once) on first start. Persisting in
97
+ * `ctx.storage` means restarts reuse the same token — a printed token
98
+ * must not go stale on `opencode service restart` (plan §8.1).
99
+ */
100
+ async function ensureToken(ctx: Context): Promise<string> {
101
+ const existing = await ctx.storage.get(TOKEN_STORAGE_KEY);
102
+ if (typeof existing === "string" && existing.length >= 16) return existing;
103
+ const token = generateToken();
104
+ await ctx.storage.set(TOKEN_STORAGE_KEY, token);
105
+ console.log(`${TAG} AHP token (auto-generated, persisted in plugin storage): ${token}`);
106
+ return token;
107
+ }
108
+
109
+ /**
110
+ * The opencode model ref (`Model.Ref = {id, providerID, variant?}`)
111
+ * behind an opencode session info entry.
112
+ */
113
+ function modelRefOf(info: SessionInfo): FacadeModelRef | undefined {
114
+ if (info.model === undefined) return undefined;
115
+ return {
116
+ providerID: String(info.model.providerID),
117
+ modelID: String(info.model.id),
118
+ ...(info.model.variant !== undefined ? { variant: String(info.model.variant) } : {}),
119
+ };
120
+ }
121
+
122
+ /** Map an opencode `SessionInfo` to the narrow `FacadeSession`. */
123
+ function mapSessionInfo(info: SessionInfo): FacadeSession {
124
+ return {
125
+ sessionID: String(info.id),
126
+ ...(info.title !== undefined && info.title !== null ? { title: String(info.title) } : {}),
127
+ ...(info.agent !== undefined ? { agent: String(info.agent) } : {}),
128
+ ...(info.model !== undefined ? { model: modelRefOf(info) } : {}),
129
+ // SessionInfo.time carries `archived` only while archived.
130
+ ...(info.time.archived !== undefined ? { archived: true } : {}),
131
+ time: { created: info.time.created, updated: info.time.updated },
132
+ };
133
+ }
134
+
135
+ /**
136
+ * The narrow opencode surface the bridge needs (plan §3.2, §14.7, §11).
137
+ *
138
+ * The catalog and agents are re-read on every call (the host snapshots
139
+ * lazily on initialize/subscribe/reconnect, not at setup) from the
140
+ * registry read APIs: `ctx.provider.list()` (provider metadata incl.
141
+ * `activation`) joined with `ctx.model.list()` (the materialized model
142
+ * infos), and `ctx.agent.list()` (opencode's agents, incl. built-in
143
+ * Build/Plan and user-defined ones). The v2 plugin docs guarantee
144
+ * registry reads reflect every registration so far — including during
145
+ * plugin setup — so no setup-time race.
146
+ *
147
+ * Phase 1 adds the session surface: create/list/get, prompt with
148
+ * `delivery` (steer|queue), switchModel/switchAgent, interrupt, update
149
+ * (rename), permission reply, and the mapped event stream.
150
+ */
151
+ function implementFacade(ctx: Context): OpencodeFacade {
152
+ return {
153
+ async listCatalog() {
154
+ const [providers, models] = await Promise.all([ctx.provider.list(), ctx.model.list()]);
155
+ const modelsByProvider = new Map<string, FacadeModel[]>();
156
+ for (const m of models.data) {
157
+ const key = String(m.providerID);
158
+ let list = modelsByProvider.get(key);
159
+ if (!list) {
160
+ list = [];
161
+ modelsByProvider.set(key, list);
162
+ }
163
+ list.push({
164
+ providerID: key,
165
+ modelID: String(m.modelID),
166
+ name: m.name,
167
+ enabled: m.enabled,
168
+ limit: {
169
+ context: m.limit.context,
170
+ output: m.limit.output,
171
+ input: m.limit.input,
172
+ },
173
+ inputModalities: [...m.capabilities.input],
174
+ });
175
+ }
176
+ return providers.data.map((p) => ({
177
+ providerID: String(p.id),
178
+ name: p.name,
179
+ activation: p.activation,
180
+ models: modelsByProvider.get(String(p.id)) ?? [],
181
+ }));
182
+ },
183
+ async listAgents(): Promise<readonly FacadeAgent[]> {
184
+ const { data: agents } = await ctx.agent.list();
185
+ return agents.map((a) => ({
186
+ id: String(a.id),
187
+ name: a.name,
188
+ description: a.description,
189
+ model: a.model
190
+ ? { providerID: String(a.model.providerID), modelID: String(a.model.id) }
191
+ : undefined,
192
+ mode: a.mode,
193
+ hidden: a.hidden,
194
+ }));
195
+ },
196
+ // ── Phase 1: sessions ────────────────────────────────────────────────
197
+ async createSession(input?: { id?: string; title?: string; agent?: string; model?: FacadeModelRef }) {
198
+ const info = await ctx.session.create({
199
+ ...(input?.id !== undefined ? { id: input.id } : {}),
200
+ ...(input?.title !== undefined ? { title: input.title } : {}),
201
+ ...(input?.agent !== undefined ? { agent: input.agent } : {}),
202
+ ...(input?.model !== undefined
203
+ ? {
204
+ model: {
205
+ id: input.model.modelID,
206
+ providerID: input.model.providerID,
207
+ ...(input.model.variant !== undefined ? { variant: input.model.variant } : {}),
208
+ },
209
+ }
210
+ : {}),
211
+ });
212
+ return mapSessionInfo(info);
213
+ },
214
+ async listSessions() {
215
+ const { data } = await ctx.session.list();
216
+ return data.map(mapSessionInfo);
217
+ },
218
+ async getSession(sessionID: string) {
219
+ try {
220
+ return mapSessionInfo(await ctx.session.get({ sessionID }));
221
+ } catch {
222
+ return null; // gone (removed) — the pump treats null as "skip"
223
+ }
224
+ },
225
+ async prompt(input: { sessionID: string; text: string; delivery?: "steer" | "queue" }) {
226
+ const res = await ctx.session.prompt({
227
+ sessionID: input.sessionID,
228
+ text: input.text,
229
+ ...(input.delivery !== undefined ? { delivery: input.delivery } : {}),
230
+ });
231
+ return { messageID: String(res.id) };
232
+ },
233
+ async switchModel(input: { sessionID: string; model: FacadeModelRef }) {
234
+ await ctx.session.switchModel({
235
+ sessionID: input.sessionID,
236
+ model: {
237
+ id: input.model.modelID,
238
+ providerID: input.model.providerID,
239
+ ...(input.model.variant !== undefined ? { variant: input.model.variant } : {}),
240
+ },
241
+ });
242
+ },
243
+ async switchAgent(input: { sessionID: string; agent: string }) {
244
+ await ctx.session.switchAgent({ sessionID: input.sessionID, agent: input.agent });
245
+ },
246
+ async interrupt(input: { sessionID: string }) {
247
+ await ctx.session.interrupt({ sessionID: input.sessionID });
248
+ },
249
+ async rename(input: { sessionID: string; title: string }) {
250
+ await ctx.session.update({ sessionID: input.sessionID, title: input.title });
251
+ },
252
+ async replyPermission(input: { sessionID: string; requestID: string; decision: "once" | "reject" }) {
253
+ await ctx.permission.reply({
254
+ sessionID: input.sessionID,
255
+ requestID: input.requestID,
256
+ decision: input.decision,
257
+ });
258
+ },
259
+ /**
260
+ * The mapped event stream (bridge.ts `mapV2Event` is the only place
261
+ * that knows the raw wire shape). Ends without error when the host's
262
+ * pump signal aborts (teardown).
263
+ */
264
+ async *events(signal: AbortSignal) {
265
+ for await (const event of ctx.event.subscribe({ signal })) {
266
+ const mapped = mapV2Event(event);
267
+ if (mapped !== null) yield mapped;
268
+ }
269
+ },
270
+ };
271
+ }
272
+
273
+ export default Plugin.define({
274
+ id: "opencode-ahp",
275
+ async setup(ctx: Context) {
276
+ // 1. Options — resolved before anything else (plan §8.1).
277
+ let opts: Options;
278
+ try {
279
+ opts = resolveOptions(ctx.options, readOptionsFile());
280
+ } catch (e) {
281
+ console.error(`${TAG} malformed options.jsonc (${errorMessage(e)}); re-resolving without it`);
282
+ opts = resolveOptions(ctx.options, null);
283
+ }
284
+ if (!opts.enabled) {
285
+ console.log(`${TAG} disabled (enabled: false); not starting the AHP host`);
286
+ return;
287
+ }
288
+
289
+ // 2. Token.
290
+ let token: string;
291
+ try {
292
+ token = opts.token ?? (await ensureToken(ctx));
293
+ } catch (e) {
294
+ console.error(`${TAG} could not resolve an AHP token: ${errorMessage(e)}`);
295
+ return; // R2: the opencode server stays up without AHP
296
+ }
297
+
298
+ // 3. Host + transport. The host's send/close callbacks close over the
299
+ // listener variable, which is assigned immediately after the host is
300
+ // constructed (the listener's socket ids are the host's socket ids).
301
+ let listener: Listener | null = null;
302
+ let cleanupHost: (() => void) | null = null;
303
+ try {
304
+ const host = new Host({
305
+ serverInfo: { name: "opencode-ahp", version: pluginVersion(), title: "OpenCode" },
306
+ facade: implementFacade(ctx),
307
+ replayWindow: opts.replayWindow,
308
+ defaultDirectory: ctx.location.directory,
309
+ send: (socketId, message) => {
310
+ listener?.sendTo({ id: socketId }, JSON.stringify(message));
311
+ },
312
+ close: (socketId, code, reason) => {
313
+ listener?.closeConnection({ id: socketId }, code, reason);
314
+ },
315
+ log: (msg) => console.warn(`${TAG} ${msg}`),
316
+ });
317
+ listener = createListener(
318
+ {
319
+ host: opts.host,
320
+ port: opts.port,
321
+ path: opts.path,
322
+ healthPath: opts.healthPath,
323
+ token,
324
+ allowedOrigins: opts.allowedOrigins,
325
+ tls: opts.tls,
326
+ },
327
+ {
328
+ onOpen: (info) => host.onOpen(info.id),
329
+ onMessage: (info, text) => host.onMessage(info.id, text),
330
+ onClose: (info) => host.onClose(info.id),
331
+ },
332
+ );
333
+ // 5. Event pump: opencode V2 events → AHP actions (the streaming
334
+ // text/reasoning, tool lifecycle, permissions, usage, turn
335
+ // terminals, steering/queue handoff — plan §11).
336
+ host.startEventPump();
337
+ cleanupHost = () => host.stopEventPump();
338
+ console.log(
339
+ `${TAG} AHP 1.0.0 host listening on ws${opts.tls ? "s" : ""}://${opts.host}:${listener.port}${opts.path} ` +
340
+ `(token ${opts.token ? "from options" : "auto-generated"}; health ${opts.healthPath})`,
341
+ );
342
+ } catch (e) {
343
+ console.error(`${TAG} failed to start the AHP listener: ${errorMessage(e)}`);
344
+ listener?.stop();
345
+ listener = null;
346
+ return; // R2: the opencode server stays up without AHP
347
+ }
348
+
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).
355
+ return () => {
356
+ console.log(`${TAG} location teardown — stopping the AHP host (location unloaded by opencode)`);
357
+ cleanupHost?.();
358
+ listener?.stop();
359
+ };
360
+ },
361
+ });
package/src/options.ts ADDED
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Plugin option resolution (plan §8.2): ctx.options ▸ options.jsonc
3
+ * sibling file ▸ built-in defaults.
4
+ *
5
+ * Resolution is per top-level key (shallow): a key's value comes from
6
+ * the highest-priority source that provides a valid value for it. Invalid
7
+ * values fall back to the next source (no throw), except a malformed JSONC
8
+ * file, which throws so the caller can log and re-resolve without it.
9
+ * `capabilities` merges per leaf (ctx ▸ file ▸ built-in per key) so a
10
+ * partial user entry does not clobber the other flags.
11
+ */
12
+
13
+ export interface TlsOptions {
14
+ keyPath: string;
15
+ certPath: string;
16
+ }
17
+
18
+ /** What `initialize` advertises — never advertise what we don't implement. */
19
+ export interface CapabilityFlags {
20
+ changesets: boolean;
21
+ terminals: boolean;
22
+ automations: boolean;
23
+ }
24
+
25
+ export interface Options {
26
+ /** Master switch; false → no listener, the plugin is fully inert. */
27
+ enabled: boolean;
28
+ /** WS listen port. */
29
+ port: number;
30
+ /** Bind address; a non-loopback bind requires a token (R4). */
31
+ host: string;
32
+ /** WS path — VS Code's remoteAgentHosts URL carries it verbatim. */
33
+ path: string;
34
+ /** Auth token; null → auto-generate on first start and persist it. */
35
+ token: string | null;
36
+ /** Origin allowlist; the token is always required regardless (R5). */
37
+ allowedOrigins: string[] | "*";
38
+ /** Native TLS via Bun.serve (post-MVP; off-LAN transports only, D3). */
39
+ tls: TlsOptions | null;
40
+ /** Plain-HTTP health endpoint (no auth). */
41
+ healthPath: string;
42
+ /** Global actions kept for reconnect replay; older gaps → snapshot. */
43
+ replayWindow: number;
44
+ /** Advertised in `initialize` (plan §8.2). */
45
+ capabilities: CapabilityFlags;
46
+ }
47
+
48
+ export const BUILTIN_OPTIONS: Options = {
49
+ enabled: true,
50
+ port: 8765,
51
+ host: "127.0.0.1",
52
+ path: "/ahp",
53
+ token: null,
54
+ allowedOrigins: "*",
55
+ tls: null,
56
+ healthPath: "/healthz",
57
+ replayWindow: 1000,
58
+ capabilities: { changesets: false, terminals: false, automations: false },
59
+ };
60
+
61
+ export function isRecord(v: unknown): v is Record<string, unknown> {
62
+ return typeof v === "object" && v !== null && !Array.isArray(v);
63
+ }
64
+
65
+ const isString = (v: unknown): v is string => typeof v === "string" && v.length > 0;
66
+ const isBool = (v: unknown): v is boolean => typeof v === "boolean";
67
+ const isPosInt = (v: unknown): v is number =>
68
+ typeof v === "number" && Number.isInteger(v) && v > 0;
69
+ const isHttpPort = (v: unknown): v is number =>
70
+ typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 65535;
71
+ /** Absolute URL path: "/ahp" ok; "/", "", "ahp", "/ahp/" rejected. */
72
+ const isUrlPath = (v: unknown): v is string =>
73
+ typeof v === "string" && v.startsWith("/") && v.length > 1 && !v.endsWith("/");
74
+ const isNonEmptyStrArray = (v: unknown): v is string[] =>
75
+ Array.isArray(v) && v.length > 0 && v.every((x) => typeof x === "string" && x.length > 0);
76
+
77
+ function validateAllowedOrigins(v: unknown): string[] | "*" | null {
78
+ if (v === "*") return "*";
79
+ if (isNonEmptyStrArray(v)) return [...v];
80
+ return null;
81
+ }
82
+
83
+ function validateTls(v: unknown): TlsOptions | null {
84
+ if (!isRecord(v) || !isString(v["keyPath"]) || !isString(v["certPath"])) return null;
85
+ return { keyPath: v["keyPath"], certPath: v["certPath"] };
86
+ }
87
+
88
+ /** Per-leaf merge of the capability flags: ctx ▸ file ▸ built-in per key. */
89
+ function resolveCapabilities(
90
+ fileV: unknown,
91
+ ctxV: unknown,
92
+ ): CapabilityFlags {
93
+ const out: CapabilityFlags = { ...BUILTIN_OPTIONS.capabilities };
94
+ for (const key of ["changesets", "terminals", "automations"] as const) {
95
+ const cv = isRecord(ctxV) ? ctxV[key] : undefined;
96
+ if (isBool(cv)) {
97
+ out[key] = cv;
98
+ continue;
99
+ }
100
+ const fv = isRecord(fileV) ? fileV[key] : undefined;
101
+ if (isBool(fv)) out[key] = fv;
102
+ }
103
+ return out;
104
+ }
105
+
106
+ /**
107
+ * Tiny JSONC stripper: removes // and block comments (string-aware) and
108
+ * trailing commas before } / ]. No dependency; sufficient for a
109
+ * hand-written options file. (House pattern, copied from llama-sync.)
110
+ */
111
+ export function stripJsonc(text: string): string {
112
+ let out = "";
113
+ let inString = false;
114
+ let lineComment = false;
115
+ let blockComment = false;
116
+ for (let i = 0; i < text.length; i++) {
117
+ const c = text[i]!;
118
+ const n = text[i + 1];
119
+ if (lineComment) {
120
+ if (c === "\n") {
121
+ lineComment = false;
122
+ out += c;
123
+ }
124
+ continue;
125
+ }
126
+ if (blockComment) {
127
+ if (c === "*" && n === "/") {
128
+ blockComment = false;
129
+ i++;
130
+ } else if (c === "\n") {
131
+ out += c;
132
+ }
133
+ continue;
134
+ }
135
+ if (inString) {
136
+ out += c;
137
+ if (c === "\\") {
138
+ if (i + 1 < text.length) {
139
+ out += n!;
140
+ i++;
141
+ }
142
+ } else if (c === '"') {
143
+ inString = false;
144
+ }
145
+ continue;
146
+ }
147
+ if (c === '"') {
148
+ inString = true;
149
+ out += c;
150
+ continue;
151
+ }
152
+ if (c === "/" && n === "/") {
153
+ lineComment = true;
154
+ i++;
155
+ continue;
156
+ }
157
+ if (c === "/" && n === "*") {
158
+ blockComment = true;
159
+ i++;
160
+ continue;
161
+ }
162
+ out += c;
163
+ }
164
+ return out.replace(/,(\s*[}\]])/g, "$1");
165
+ }
166
+
167
+ /**
168
+ * @param ctxOptions options object from the object-form `plugins` entry
169
+ * @param fileText raw text of the `options.jsonc` sibling of src/index.ts,
170
+ * or null when the file is absent. Throws on malformed JSONC.
171
+ */
172
+ export function resolveOptions(
173
+ ctxOptions: Readonly<Record<string, unknown>> | null | undefined,
174
+ fileText: string | null | undefined,
175
+ ): Options {
176
+ let file: Record<string, unknown> = {};
177
+ if (fileText != null && fileText.trim() !== "") {
178
+ const parsed: unknown = JSON.parse(stripJsonc(fileText));
179
+ if (!isRecord(parsed)) throw new Error("options file must contain a JSON object");
180
+ file = parsed;
181
+ }
182
+ const ctx = isRecord(ctxOptions) ? ctxOptions : {};
183
+ const pick = <T>(key: string, valid: (v: unknown) => v is T, fallback: T): T => {
184
+ const cv = ctx[key];
185
+ if (cv !== undefined && valid(cv)) return cv;
186
+ const fv = file[key];
187
+ if (fv !== undefined && valid(fv)) return fv;
188
+ return fallback;
189
+ };
190
+ const pickNullable = <T>(
191
+ key: string,
192
+ valid: (v: unknown) => T | null,
193
+ fallback: T | null,
194
+ ): T | null => {
195
+ const cv = ctx[key];
196
+ if (cv !== undefined) {
197
+ const r = valid(cv);
198
+ if (r !== null) return r;
199
+ }
200
+ const fv = file[key];
201
+ if (fv !== undefined) {
202
+ const r = valid(fv);
203
+ if (r !== null) return r;
204
+ }
205
+ return fallback;
206
+ };
207
+
208
+ return {
209
+ enabled: pick("enabled", isBool, BUILTIN_OPTIONS.enabled),
210
+ port: pick("port", isHttpPort, BUILTIN_OPTIONS.port),
211
+ host: pick("host", isString, BUILTIN_OPTIONS.host),
212
+ path: pick("path", isUrlPath, BUILTIN_OPTIONS.path),
213
+ token: pickNullable(
214
+ "token",
215
+ (v): string | null => (isString(v) ? v : null),
216
+ BUILTIN_OPTIONS.token,
217
+ ),
218
+ // Non-nullable in Options. pickNullable is typed `T | null` for the
219
+ // nullable keys; here the fallback (the built-in) is never null, so the
220
+ // branch below is unreachable and only exists to narrow the type.
221
+ allowedOrigins:
222
+ pickNullable("allowedOrigins", validateAllowedOrigins, BUILTIN_OPTIONS.allowedOrigins) ??
223
+ BUILTIN_OPTIONS.allowedOrigins,
224
+ tls: pickNullable("tls", validateTls, BUILTIN_OPTIONS.tls),
225
+ healthPath: pick("healthPath", isUrlPath, BUILTIN_OPTIONS.healthPath),
226
+ replayWindow: pick("replayWindow", isPosInt, BUILTIN_OPTIONS.replayWindow),
227
+ capabilities: resolveCapabilities(file["capabilities"], ctx["capabilities"]),
228
+ };
229
+ }
package/src/seq.ts ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Global action sequencer + replay window (plan §6.1 seq.ts).
3
+ *
4
+ * Deviation from the plan's "per-channel seq" wording (plan §14): AHP
5
+ * 1.0.0's `serverSeq` is a single host-wide sequence across all channels
6
+ * — the spec's lifecycle example numbers a chat action 43 while a root
7
+ * snapshot is taken at 42. Consequences:
8
+ * - snapshots carry `fromSeq` = the current global seq;
9
+ * - reconnect replay is a *global* range (serverSeq > lastSeen) filtered
10
+ * by the client's subscriptions;
11
+ * - the replay window bounds the global buffer, not per-channel ones.
12
+ */
13
+ import type {
14
+ ActionEnvelope,
15
+ ActionOrigin,
16
+ StateAction,
17
+ URI,
18
+ } from "@microsoft/agent-host-protocol";
19
+
20
+ export const DEFAULT_REPLAY_WINDOW = 1000;
21
+
22
+ /** A published action before the sequencer stamps it. */
23
+ export interface ActionDraft {
24
+ channel: URI;
25
+ action: StateAction;
26
+ /** Present when the action came from a client dispatch (echo origin). */
27
+ origin?: ActionOrigin;
28
+ /** Present when the host rejected a client-dispatched action. */
29
+ rejectionReason?: string;
30
+ }
31
+
32
+ export class Sequencer {
33
+ private readonly size: number;
34
+ private current = 0;
35
+ private readonly buffer: ActionEnvelope[] = [];
36
+
37
+ constructor(size: number = DEFAULT_REPLAY_WINDOW) {
38
+ if (!Number.isInteger(size) || size <= 0) {
39
+ throw new Error(`replayWindow must be a positive integer, got ${String(size)}`);
40
+ }
41
+ this.size = size;
42
+ }
43
+
44
+ /** Current (last assigned) global sequence number. 0 before any action. */
45
+ get seq(): number {
46
+ return this.current;
47
+ }
48
+
49
+ /** Oldest seq still held in the replay window (seq + 1 when empty). */
50
+ get oldest(): number {
51
+ return this.buffer.length > 0 ? this.buffer[0]!.serverSeq : this.current + 1;
52
+ }
53
+
54
+ /**
55
+ * Assign the next global sequence number and retain the envelope for
56
+ * replay. Returns the completed envelope.
57
+ */
58
+ publish(draft: ActionDraft): ActionEnvelope {
59
+ const envelope: ActionEnvelope = {
60
+ channel: draft.channel,
61
+ action: draft.action,
62
+ serverSeq: ++this.current,
63
+ origin: draft.origin,
64
+ ...(draft.rejectionReason !== undefined
65
+ ? { rejectionReason: draft.rejectionReason }
66
+ : {}),
67
+ };
68
+ this.buffer.push(envelope);
69
+ if (this.buffer.length > this.size) this.buffer.shift();
70
+ return envelope;
71
+ }
72
+
73
+ /**
74
+ * All envelopes with serverSeq > since, in order. Null when the range
75
+ * has been evicted from the replay window (the caller falls back to a
76
+ * fresh snapshot).
77
+ */
78
+ since(since: number): ActionEnvelope[] | null {
79
+ const s = Math.max(0, since);
80
+ // The range (s, current] is replayable when it starts at or after the
81
+ // envelope *before* the window's oldest — a client at lastSeen =
82
+ // oldest - 1 has seen nothing that was evicted.
83
+ if (this.buffer.length > 0 && s + 1 < this.buffer[0]!.serverSeq) return null;
84
+ if (s >= this.current) return [];
85
+ return this.buffer.filter((e) => e.serverSeq > s);
86
+ }
87
+ }