opencode-ahp 0.1.4 → 0.1.6
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 +91 -37
- package/options.example.jsonc +25 -8
- package/package.json +1 -1
- package/src/bridge.ts +335 -127
- package/src/channels.ts +74 -32
- package/src/client-tools.ts +127 -0
- package/src/handshake.ts +2 -3
- package/src/host-base.ts +335 -0
- package/src/host-changesets.ts +381 -0
- package/src/host-chats.ts +300 -0
- package/src/host-client-tools.ts +205 -0
- package/src/host-dispatch.ts +593 -0
- package/src/host-errors.ts +29 -0
- package/src/host-events.ts +386 -0
- package/src/host-rpc.ts +435 -0
- package/src/host-sessions.ts +558 -0
- package/src/host-terminals.ts +654 -0
- package/src/host-turns.ts +82 -0
- package/src/host-types.ts +225 -0
- package/src/host-util.ts +194 -0
- package/src/host.ts +23 -2299
- package/src/index.ts +265 -33
- package/src/keep-alive.ts +3 -3
- package/src/options.ts +23 -9
- package/src/seq.ts +4 -5
- package/src/state.ts +40 -6
- package/src/transport.ts +6 -6
package/src/index.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* opencode-ahp — OpenCode V2 plugin: hosts the **Agent Host Protocol
|
|
3
3
|
* (AHP) 1.0.0** in-process so opencode appears as a native agent in the
|
|
4
|
-
* VS Code Agents window
|
|
4
|
+
* VS Code Agents window.
|
|
5
5
|
*
|
|
6
|
-
* This is the only module that touches the plugin `ctx`
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
6
|
+
* This is the only module that touches the plugin `ctx` — everything
|
|
7
|
+
* else (options, transport, handshake, channels, seq, state, bridge,
|
|
8
|
+
* host) is pure or dependency-injected and unit-tested without an
|
|
9
|
+
* OpenCode runtime.
|
|
10
10
|
*
|
|
11
11
|
* Lifecycle:
|
|
12
12
|
* 1. resolve options (ctx.options ▸ options.jsonc sibling ▸ built-ins;
|
|
@@ -14,12 +14,12 @@
|
|
|
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
|
|
17
|
+
* 3. keep-alive: get-or-create the anchor session and start
|
|
18
18
|
* touching it periodically so the location survives the idle timeout
|
|
19
19
|
* without any user config
|
|
20
20
|
* 4. wire the Host (JSON-RPC router) to the transport (Bun.serve)
|
|
21
21
|
* 5. start the opencode event pump (maps `ctx.event.subscribe` into
|
|
22
|
-
* the host's AHP action stream
|
|
22
|
+
* the host's AHP action stream)
|
|
23
23
|
* 6. return cleanup that stops the keep-alive, the pump, and the listener
|
|
24
24
|
*
|
|
25
25
|
* Every failure path logs and stays up: a bad client connection or a
|
|
@@ -45,19 +45,41 @@ import type { SessionDomain } from "@opencode/plugin/promise/session";
|
|
|
45
45
|
* is derived through the plugin package's declared subpaths.
|
|
46
46
|
*/
|
|
47
47
|
type SessionInfo = Awaited<ReturnType<SessionDomain["get"]>>;
|
|
48
|
+
/**
|
|
49
|
+
* The `SessionCreateInput["metadata"]` type — a JSON record per the
|
|
50
|
+
* `Session.Metadata` schema (derived the same way as `SessionInfo`).
|
|
51
|
+
*/
|
|
52
|
+
type SessionCreateMetadata = NonNullable<Parameters<SessionDomain["create"]>[0]>["metadata"];
|
|
48
53
|
import { isRecord, resolveOptions, type Options } from "./options.js";
|
|
49
54
|
import { createListener, type Listener } from "./transport.js";
|
|
50
55
|
import { Host } from "./host.js";
|
|
56
|
+
import type { SpawnPty } from "./host-types.js";
|
|
51
57
|
import { KeepAlive, KEEPALIVE_SESSION_ID } from "./keep-alive.js";
|
|
52
58
|
import { errorMessage } from "./error.js";
|
|
53
59
|
import {
|
|
54
|
-
|
|
60
|
+
eventLogLine,
|
|
61
|
+
mapV2EventRaw,
|
|
62
|
+
timeStamp,
|
|
55
63
|
type FacadeAgent,
|
|
64
|
+
type FacadeClientTool,
|
|
56
65
|
type FacadeModel,
|
|
57
66
|
type FacadeModelRef,
|
|
58
67
|
type FacadeSession,
|
|
59
68
|
type OpencodeFacade,
|
|
60
69
|
} from "./bridge.js";
|
|
70
|
+
import { normalizedName } from "./client-tools.js";
|
|
71
|
+
/**
|
|
72
|
+
* The opencode tool surface for client-provided tools. `ToolError` is
|
|
73
|
+
* the schema `Error` class (thrown from the `execute` bridge); `ToolInfo`
|
|
74
|
+
* is the promise-flavored
|
|
75
|
+
* tool registration; `ToolContext` carries the tool-call context
|
|
76
|
+
* (sessionID, the tool-call `id`, the abort `signal`).
|
|
77
|
+
*/
|
|
78
|
+
import {
|
|
79
|
+
Error as ToolError,
|
|
80
|
+
type Info as ToolInfo,
|
|
81
|
+
type ToolContext,
|
|
82
|
+
} from "@opencode/plugin/promise/tool";
|
|
61
83
|
|
|
62
84
|
const TAG = "[opencode-ahp]";
|
|
63
85
|
|
|
@@ -89,6 +111,92 @@ function pluginVersion(): string {
|
|
|
89
111
|
return "0.1.1";
|
|
90
112
|
}
|
|
91
113
|
|
|
114
|
+
/**
|
|
115
|
+
* The Bun runtime surface the pty seam uses. opencode ships as a
|
|
116
|
+
* Bun-compiled binary, so `globalThis.Bun` is present at runtime; the
|
|
117
|
+
* package's typecheck only knows the Node types, so the minimal shape is
|
|
118
|
+
* declared locally rather than taking a dev dependency on Bun's types.
|
|
119
|
+
*/
|
|
120
|
+
interface BunPty {
|
|
121
|
+
write(data: string): void;
|
|
122
|
+
resize(cols: number, rows: number): void;
|
|
123
|
+
close(): void;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
interface BunChildProcess {
|
|
127
|
+
kill(): void;
|
|
128
|
+
readonly terminal: BunPty;
|
|
129
|
+
readonly exited: Promise<number>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
interface BunLike {
|
|
133
|
+
spawn(
|
|
134
|
+
cmd: string[],
|
|
135
|
+
opts: {
|
|
136
|
+
cwd: string;
|
|
137
|
+
env: Record<string, string | undefined>;
|
|
138
|
+
terminal: {
|
|
139
|
+
cols: number;
|
|
140
|
+
rows: number;
|
|
141
|
+
name: string;
|
|
142
|
+
data(term: unknown, data: string | Uint8Array): void;
|
|
143
|
+
};
|
|
144
|
+
},
|
|
145
|
+
): BunChildProcess;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* The host's `spawnPty` seam backed by `Bun.spawn`'s `terminal` option —
|
|
150
|
+
* a real pty with no external dependency (the plugin runs inside the Bun
|
|
151
|
+
* runtime). Returns undefined when the runtime is not Bun (the terminal
|
|
152
|
+
* commands then answer -32601 instead of the host crashing). The shell is
|
|
153
|
+
* `$SHELL` (fallback /bin/bash); login shells get `-l` (fish has none).
|
|
154
|
+
* Output is decoded defensively (string or bytes) and the exit code
|
|
155
|
+
* normalized (signal-killed → undefined).
|
|
156
|
+
*/
|
|
157
|
+
function createBunSpawnPty(): SpawnPty | undefined {
|
|
158
|
+
const bun = (globalThis as { Bun?: BunLike }).Bun;
|
|
159
|
+
if (bun === undefined) return undefined;
|
|
160
|
+
const decoder = new TextDecoder();
|
|
161
|
+
return (input) => {
|
|
162
|
+
const shell = process.env.SHELL ?? "/bin/bash";
|
|
163
|
+
const base = shell.split("/").pop() ?? "";
|
|
164
|
+
const login = ["bash", "zsh", "ksh", "sh", "dash", "ash"].includes(base) ? ["-l"] : [];
|
|
165
|
+
const proc = bun.spawn([shell, ...login], {
|
|
166
|
+
cwd: input.cwd,
|
|
167
|
+
env: { ...process.env, TERM: "xterm-256color" },
|
|
168
|
+
terminal: {
|
|
169
|
+
cols: input.cols,
|
|
170
|
+
rows: input.rows,
|
|
171
|
+
name: "xterm-256color",
|
|
172
|
+
data: (_term, data) => {
|
|
173
|
+
input.onOutput(typeof data === "string" ? data : decoder.decode(data));
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
void proc.exited.then(
|
|
178
|
+
(code) => input.onExit(Number.isInteger(code) && code >= 0 ? code : undefined),
|
|
179
|
+
() => input.onExit(undefined),
|
|
180
|
+
);
|
|
181
|
+
return {
|
|
182
|
+
write: (data) => proc.terminal.write(data),
|
|
183
|
+
resize: (cols, rows) => proc.terminal.resize(cols, rows),
|
|
184
|
+
kill: () => {
|
|
185
|
+
try {
|
|
186
|
+
proc.kill();
|
|
187
|
+
} catch {
|
|
188
|
+
// already gone
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
proc.terminal.close();
|
|
192
|
+
} catch {
|
|
193
|
+
// already closed
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
92
200
|
/** 32 random bytes, base64url — 43 chars, comfortably over the 16-char floor. */
|
|
93
201
|
function generateToken(): string {
|
|
94
202
|
const bytes = new Uint8Array(32);
|
|
@@ -100,7 +208,7 @@ function generateToken(): string {
|
|
|
100
208
|
* Token from options when set; otherwise the persisted one from plugin
|
|
101
209
|
* storage, generated (and printed once) on first start. Persisting in
|
|
102
210
|
* `ctx.storage` means restarts reuse the same token — a printed token
|
|
103
|
-
* must not go stale on `opencode service restart
|
|
211
|
+
* must not go stale on `opencode service restart`.
|
|
104
212
|
*/
|
|
105
213
|
async function ensureToken(ctx: Context): Promise<string> {
|
|
106
214
|
const existing = await ctx.storage.get(TOKEN_STORAGE_KEY);
|
|
@@ -133,6 +241,9 @@ function mapSessionInfo(info: SessionInfo): FacadeSession {
|
|
|
133
241
|
...(info.model !== undefined ? { model: modelRefOf(info) } : {}),
|
|
134
242
|
// SessionInfo.time carries `archived` only while archived.
|
|
135
243
|
...(info.time.archived !== undefined ? { archived: true } : {}),
|
|
244
|
+
// Durable, core-opaque metadata: the host reads its
|
|
245
|
+
// `opencode-ahp` chat-binding marker from it on external registration.
|
|
246
|
+
...(isRecord(info.metadata) ? { metadata: info.metadata as Record<string, unknown> } : {}),
|
|
136
247
|
time: { created: info.time.created, updated: info.time.updated },
|
|
137
248
|
};
|
|
138
249
|
}
|
|
@@ -144,7 +255,7 @@ function isHiddenSessionEvent(event: unknown, hiddenSessionID: string): boolean
|
|
|
144
255
|
return isRecord(data) && data["sessionID"] === hiddenSessionID;
|
|
145
256
|
}
|
|
146
257
|
|
|
147
|
-
// ──
|
|
258
|
+
// ── changeset git helpers ──────────────────────────
|
|
148
259
|
//
|
|
149
260
|
// The plugin `ctx` has no "file content at HEAD" or "discard one file"
|
|
150
261
|
// surface (`ctx.vcs` only diffs), so the facade shells out to `git` in the
|
|
@@ -183,7 +294,7 @@ function isEnoent(err: unknown): boolean {
|
|
|
183
294
|
}
|
|
184
295
|
|
|
185
296
|
/**
|
|
186
|
-
* The narrow opencode surface the bridge needs
|
|
297
|
+
* The narrow opencode surface the bridge needs.
|
|
187
298
|
*
|
|
188
299
|
* The catalog and agents are re-read on every call (the host snapshots
|
|
189
300
|
* lazily on initialize/subscribe/reconnect, not at setup) from the
|
|
@@ -194,19 +305,43 @@ function isEnoent(err: unknown): boolean {
|
|
|
194
305
|
* registry reads reflect every registration so far — including during
|
|
195
306
|
* plugin setup — so no setup-time race.
|
|
196
307
|
*
|
|
197
|
-
*
|
|
198
|
-
*
|
|
199
|
-
*
|
|
308
|
+
* The session surface covers create/list/get, prompt with `delivery`
|
|
309
|
+
* (steer|queue), switchModel/switchAgent, interrupt, update (rename),
|
|
310
|
+
* permission reply, and the mapped event stream.
|
|
200
311
|
*
|
|
201
|
-
* `hiddenSessionID` (the keep-alive anchor
|
|
312
|
+
* `hiddenSessionID` (the keep-alive anchor) is filtered from all
|
|
202
313
|
* three session surfaces so the AHP client never sees it: `list`/snapshots
|
|
203
314
|
* (by ID), `get` (null = not found), and the event stream (by
|
|
204
315
|
* `data.sessionID` — covers `session.created` and anything a future bridge
|
|
205
316
|
* version may map).
|
|
317
|
+
*
|
|
318
|
+
* `hostRef`: the client-tool
|
|
319
|
+
* `execute` bridge needs the host, but the facade is constructed as part
|
|
320
|
+
* of the host's own options — a mutable holder assigned right after
|
|
321
|
+
* `new Host(...)` returns (the `listener` closure pattern).
|
|
322
|
+
*
|
|
323
|
+
* `logEvent`: the timestamped event-capture sink (the `logEvents`
|
|
324
|
+
* option, design §8.1) — one line per raw opencode event, or null when
|
|
325
|
+
* capture is off.
|
|
206
326
|
*/
|
|
207
|
-
|
|
327
|
+
type HostRef = { current: Host | null };
|
|
328
|
+
|
|
329
|
+
function implementFacade(
|
|
330
|
+
ctx: Context,
|
|
331
|
+
hiddenSessionID: string | null,
|
|
332
|
+
hostRef: HostRef,
|
|
333
|
+
logEvent: ((line: string) => void) | null,
|
|
334
|
+
): OpencodeFacade {
|
|
208
335
|
const locationDir = ctx.location.directory;
|
|
209
336
|
|
|
337
|
+
// The cross-session client-tool set (client-provided tools).
|
|
338
|
+
// The single `ctx.tool.transform` registration is applied on every
|
|
339
|
+
// registry rebuild (opencode rebuilds from scratch, re-running all
|
|
340
|
+
// transforms over a fresh base — verified in core `State.create`), so
|
|
341
|
+
// the sync is: replace the set, (register the transform once), reload.
|
|
342
|
+
let clientTools: FacadeClientTool[] = [];
|
|
343
|
+
let clientToolsTransformRegistered = false;
|
|
344
|
+
|
|
210
345
|
const readTextFile = async (absPath: string): Promise<string | null> => {
|
|
211
346
|
try {
|
|
212
347
|
return await fsReadFile(absPath, "utf-8");
|
|
@@ -267,8 +402,14 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
|
|
|
267
402
|
hidden: a.hidden,
|
|
268
403
|
}));
|
|
269
404
|
},
|
|
270
|
-
// ──
|
|
271
|
-
async createSession(input?: {
|
|
405
|
+
// ── sessions ────────────────────────────────────────────────
|
|
406
|
+
async createSession(input?: {
|
|
407
|
+
id?: string;
|
|
408
|
+
title?: string;
|
|
409
|
+
agent?: string;
|
|
410
|
+
model?: FacadeModelRef;
|
|
411
|
+
metadata?: Record<string, unknown>;
|
|
412
|
+
}) {
|
|
272
413
|
const info = await ctx.session.create({
|
|
273
414
|
...(input?.id !== undefined ? { id: input.id } : {}),
|
|
274
415
|
...(input?.title !== undefined ? { title: input.title } : {}),
|
|
@@ -282,6 +423,12 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
|
|
|
282
423
|
},
|
|
283
424
|
}
|
|
284
425
|
: {}),
|
|
426
|
+
// The chat-binding marker is written atomically at
|
|
427
|
+
// create (no read-merge — core projects MetadataUpdated as a full
|
|
428
|
+
// column replacement, so a later update would clobber it). Session
|
|
429
|
+
// metadata is JSON by the Session.Metadata schema; the facade keeps
|
|
430
|
+
// it unknown-typed, so the single cast lives here.
|
|
431
|
+
...(input?.metadata !== undefined ? { metadata: input.metadata as SessionCreateMetadata } : {}),
|
|
285
432
|
});
|
|
286
433
|
return mapSessionInfo(info);
|
|
287
434
|
},
|
|
@@ -299,6 +446,9 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
|
|
|
299
446
|
return null; // gone (removed) — the pump treats null as "skip"
|
|
300
447
|
}
|
|
301
448
|
},
|
|
449
|
+
async removeSession(sessionID: string) {
|
|
450
|
+
await ctx.session.remove({ sessionID });
|
|
451
|
+
},
|
|
302
452
|
async prompt(input: { sessionID: string; text: string; delivery?: "steer" | "queue" }) {
|
|
303
453
|
const res = await ctx.session.prompt({
|
|
304
454
|
sessionID: input.sessionID,
|
|
@@ -334,18 +484,22 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
|
|
|
334
484
|
});
|
|
335
485
|
},
|
|
336
486
|
/**
|
|
337
|
-
* The mapped event stream (bridge.ts `
|
|
338
|
-
* that knows the raw wire shape).
|
|
339
|
-
*
|
|
487
|
+
* The mapped event stream (bridge.ts `mapV2EventRaw` is the only
|
|
488
|
+
* place that knows the raw wire shape). With the `logEvents` option
|
|
489
|
+
* on, every event is first written as a timestamped capture line
|
|
490
|
+
* (ok / dropped with reason / unimplemented, design §8.1); only
|
|
491
|
+
* `ok` events are yielded. Ends without error when the host's pump
|
|
492
|
+
* signal aborts (teardown).
|
|
340
493
|
*/
|
|
341
494
|
async *events(signal: AbortSignal) {
|
|
342
495
|
for await (const event of ctx.event.subscribe({ signal })) {
|
|
343
496
|
if (hiddenSessionID !== null && isHiddenSessionEvent(event, hiddenSessionID)) continue;
|
|
344
|
-
const
|
|
345
|
-
if (
|
|
497
|
+
const outcome = mapV2EventRaw(event);
|
|
498
|
+
if (logEvent !== null) logEvent(eventLogLine(outcome, event, timeStamp(new Date())));
|
|
499
|
+
if (outcome.status === "ok") yield outcome.event;
|
|
346
500
|
}
|
|
347
501
|
},
|
|
348
|
-
// ──
|
|
502
|
+
// ── changesets ────────────────────────────────
|
|
349
503
|
async vcsDiffWorking() {
|
|
350
504
|
const root = await gitRepoRoot(locationDir);
|
|
351
505
|
if (root === null) return []; // not a git repo → no working diff
|
|
@@ -404,13 +558,74 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
|
|
|
404
558
|
await removeFile(absPath); // in the index but not in HEAD → delete
|
|
405
559
|
}
|
|
406
560
|
},
|
|
561
|
+
// ── client-provided tools ───────
|
|
562
|
+
async syncClientTools(tools: readonly FacadeClientTool[]) {
|
|
563
|
+
clientTools = [...tools];
|
|
564
|
+
if (!clientToolsTransformRegistered) {
|
|
565
|
+
clientToolsTransformRegistered = true;
|
|
566
|
+
// Registered once for the location lifetime (scoped: disposed on
|
|
567
|
+
// location teardown). The callback is synchronous and reads the
|
|
568
|
+
// closure `clientTools` at rebuild time; each rebuild is a fresh
|
|
569
|
+
// registry, so only (re-)adding the current set is needed.
|
|
570
|
+
await ctx.tool.transform((editor) => {
|
|
571
|
+
const added = new Set<string>();
|
|
572
|
+
for (const tool of clientTools) {
|
|
573
|
+
const id = normalizedName(tool.name);
|
|
574
|
+
if (added.has(id)) continue; // normalized-name collision → first wins
|
|
575
|
+
added.add(id);
|
|
576
|
+
editor.add({
|
|
577
|
+
name: tool.name,
|
|
578
|
+
// The AHP `inputSchema` is a raw object JSON Schema —
|
|
579
|
+
// opencode's `inputJsonSchema` passes it through verbatim
|
|
580
|
+
// and validates model inputs against it.
|
|
581
|
+
input: tool.inputSchema,
|
|
582
|
+
description: tool.description,
|
|
583
|
+
// A client tool must be a DIRECT tool: under Code Mode a
|
|
584
|
+
// tool in the `execute` catalog is invoked as nested JS
|
|
585
|
+
// (`tools.ping(...)`) that emits no tool events of its own
|
|
586
|
+
// (only the outer `execute` call does), so the host could
|
|
587
|
+
// never see the call to track + relay to the client.
|
|
588
|
+
// `codemode: false` keeps it out of the catalog and in
|
|
589
|
+
// the direct list (live finding 2026-11-08).
|
|
590
|
+
options: { codemode: false },
|
|
591
|
+
execute: async (_input: unknown, context: ToolContext) => {
|
|
592
|
+
const host = hostRef.current;
|
|
593
|
+
if (host === null) {
|
|
594
|
+
throw new ToolError({ message: "the AHP host is not running" });
|
|
595
|
+
}
|
|
596
|
+
const result = await host.executeClientTool({
|
|
597
|
+
sessionID: String(context.sessionID),
|
|
598
|
+
toolCallId: String(context.id),
|
|
599
|
+
name: tool.name,
|
|
600
|
+
signal: context.signal,
|
|
601
|
+
});
|
|
602
|
+
if (!result.ok) throw new ToolError({ message: result.error });
|
|
603
|
+
const text = [result.pastTenseMessage, result.content]
|
|
604
|
+
.filter((part): part is string => typeof part === "string" && part.length > 0)
|
|
605
|
+
.join("\n\n");
|
|
606
|
+
return {
|
|
607
|
+
...(text.length > 0 ? { content: text } : {}),
|
|
608
|
+
// No `output` (no output schema is declared — the
|
|
609
|
+
// runtime rejects one); structured content rides in
|
|
610
|
+
// the tool part's metadata.
|
|
611
|
+
...(result.structuredContent !== undefined
|
|
612
|
+
? { metadata: { structured: result.structuredContent } }
|
|
613
|
+
: {}),
|
|
614
|
+
};
|
|
615
|
+
},
|
|
616
|
+
} as unknown as ToolInfo);
|
|
617
|
+
}
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
await ctx.tool.reload();
|
|
621
|
+
},
|
|
407
622
|
};
|
|
408
623
|
}
|
|
409
624
|
|
|
410
625
|
export default Plugin.define({
|
|
411
626
|
id: "opencode-ahp",
|
|
412
627
|
async setup(ctx: Context) {
|
|
413
|
-
// 1. Options — resolved before anything else
|
|
628
|
+
// 1. Options — resolved before anything else.
|
|
414
629
|
let opts: Options;
|
|
415
630
|
try {
|
|
416
631
|
opts = resolveOptions(ctx.options, readOptionsFile());
|
|
@@ -432,8 +647,8 @@ export default Plugin.define({
|
|
|
432
647
|
return; // R2: the opencode server stays up without AHP
|
|
433
648
|
}
|
|
434
649
|
|
|
435
|
-
// 3. Keep-alive
|
|
436
|
-
// session's `session.created` fires before the event pump
|
|
650
|
+
// 3. Keep-alive. Before the host exists, so the anchor
|
|
651
|
+
// session's `session.created` fires before the event pump subscribes
|
|
437
652
|
// and never reaches AHP clients (the facade filters it from the
|
|
438
653
|
// snapshot/list surfaces regardless). A deterministic session ID means
|
|
439
654
|
// reloads reuse the same session — no accumulation in the DB.
|
|
@@ -443,7 +658,7 @@ export default Plugin.define({
|
|
|
443
658
|
let keepAlive: KeepAlive | null = null;
|
|
444
659
|
if (opts.keepAlive) {
|
|
445
660
|
keepAlive = new KeepAlive({
|
|
446
|
-
// Get-or-create. (Upstream gap
|
|
661
|
+
// Get-or-create. (Upstream gap: `SessionUpdateInput`
|
|
447
662
|
// advertises `archived`, but the plugin host's `session.update`
|
|
448
663
|
// drops it — `packages/core/src/plugin/host.ts` forwards only
|
|
449
664
|
// title/metadata/permissions, in v2.2.6 and current dev. So the
|
|
@@ -477,13 +692,24 @@ export default Plugin.define({
|
|
|
477
692
|
// constructed (the listener's socket ids are the host's socket ids).
|
|
478
693
|
let listener: Listener | null = null;
|
|
479
694
|
let cleanupHost: (() => void) | null = null;
|
|
695
|
+
// The host back-reference for the client-tool `execute` bridge (the
|
|
696
|
+
// facade is built from the host's options, so the reference lands
|
|
697
|
+
// one statement later — the `listener` pattern).
|
|
698
|
+
const hostRef: HostRef = { current: null };
|
|
480
699
|
try {
|
|
481
700
|
const host = new Host({
|
|
482
701
|
serverInfo: { name: "opencode-ahp", version: pluginVersion(), title: "OpenCode" },
|
|
483
|
-
facade: implementFacade(
|
|
702
|
+
facade: implementFacade(
|
|
703
|
+
ctx,
|
|
704
|
+
hiddenSessionID,
|
|
705
|
+
hostRef,
|
|
706
|
+
opts.logEvents ? (line) => console.log(line) : null,
|
|
707
|
+
),
|
|
484
708
|
replayWindow: opts.replayWindow,
|
|
485
709
|
defaultDirectory: ctx.location.directory,
|
|
486
710
|
changesets: opts.capabilities.changesets,
|
|
711
|
+
terminals: opts.capabilities.terminals,
|
|
712
|
+
spawnPty: createBunSpawnPty(),
|
|
487
713
|
send: (socketId, message) => {
|
|
488
714
|
listener?.sendTo({ id: socketId }, JSON.stringify(message));
|
|
489
715
|
},
|
|
@@ -492,7 +718,8 @@ export default Plugin.define({
|
|
|
492
718
|
},
|
|
493
719
|
log: (msg) => console.warn(`${TAG} ${msg}`),
|
|
494
720
|
});
|
|
495
|
-
|
|
721
|
+
hostRef.current = host; // the client-tool execute bridge can route now
|
|
722
|
+
// TLS material: read the key/cert files here so a
|
|
496
723
|
// missing/unreadable file fails before binding and takes the R2
|
|
497
724
|
// degrade path below — the transport itself stays
|
|
498
725
|
// filesystem-free (it receives the PEM contents).
|
|
@@ -520,9 +747,14 @@ export default Plugin.define({
|
|
|
520
747
|
);
|
|
521
748
|
// 5. Event pump: opencode V2 events → AHP actions (the streaming
|
|
522
749
|
// text/reasoning, tool lifecycle, permissions, usage, turn
|
|
523
|
-
// terminals, steering/queue handoff
|
|
750
|
+
// terminals, steering/queue handoff).
|
|
524
751
|
host.startEventPump();
|
|
525
|
-
cleanupHost = () =>
|
|
752
|
+
cleanupHost = () => {
|
|
753
|
+
// Kill the pty terminals before the listener stops — their final
|
|
754
|
+
// terminal/exited actions still reach subscribers while it is up.
|
|
755
|
+
host.stopTerminals();
|
|
756
|
+
host.stopEventPump();
|
|
757
|
+
};
|
|
526
758
|
console.log(
|
|
527
759
|
`${TAG} AHP 1.0.0 host listening on ws${opts.tls ? "s" : ""}://${opts.host}:${listener.port}${opts.path} ` +
|
|
528
760
|
`(token ${opts.token ? "from options" : "auto-generated"}; health ${opts.healthPath})`,
|
|
@@ -538,7 +770,7 @@ export default Plugin.define({
|
|
|
538
770
|
// 6. Cleanup: stop the keep-alive timer, stop the pump (aborts the
|
|
539
771
|
// event subscription), and stop the listener, dropping every client
|
|
540
772
|
// connection. Logged because a torn-down listener with no log line
|
|
541
|
-
// is otherwise undiagnosable
|
|
773
|
+
// is otherwise undiagnosable.
|
|
542
774
|
return () => {
|
|
543
775
|
console.log(`${TAG} location teardown — stopping the AHP host (location unloaded by opencode)`);
|
|
544
776
|
keepAlive?.stop();
|
package/src/keep-alive.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Location keep-alive
|
|
2
|
+
* Location keep-alive.
|
|
3
3
|
*
|
|
4
4
|
* opencode v2 unloads idle locations after `experimental.location_idle_timeout`
|
|
5
5
|
* (default 60 minutes). `LocationActivity` (packages/core/src/location-activity.ts)
|
|
@@ -11,14 +11,14 @@
|
|
|
11
11
|
* any user config (`location_idle_timeout: false` is no longer required).
|
|
12
12
|
*
|
|
13
13
|
* The anchor session is visible in the opencode TUI session list (the plugin
|
|
14
|
-
* surface cannot archive it
|
|
14
|
+
* surface cannot archive it); the AHP host filters it out by its
|
|
15
15
|
* deterministic ID from every client-facing surface.
|
|
16
16
|
*
|
|
17
17
|
* Cold boot is an architectural limit, not a keep-alive problem: plugins load
|
|
18
18
|
* per location (`Node.makeLocationNode`) and cannot run before the location
|
|
19
19
|
* boots, and no config boots a location at server start. The anchor session's
|
|
20
20
|
* first touch therefore only helps once the location is up — the one-time boot
|
|
21
|
-
* step stays (
|
|
21
|
+
* step stays (open the project once, or a headless location-boot request).
|
|
22
22
|
*
|
|
23
23
|
* Pure module: session access and the timer are dependency-injected, so this
|
|
24
24
|
* is unit-tested without an OpenCode runtime (house pattern).
|
package/src/options.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Plugin option resolution
|
|
3
|
-
*
|
|
2
|
+
* Plugin option resolution: ctx.options ▸ options.jsonc sibling file ▸
|
|
3
|
+
* built-in defaults.
|
|
4
4
|
*
|
|
5
5
|
* Resolution is per top-level key (shallow): a key's value comes from
|
|
6
6
|
* the highest-priority source that provides a valid value for it. Invalid
|
|
@@ -33,16 +33,16 @@ export interface Options {
|
|
|
33
33
|
path: string;
|
|
34
34
|
/** Auth token; null → auto-generate on first start and persist it. */
|
|
35
35
|
token: string | null;
|
|
36
|
-
/** Origin allowlist; the token is always required regardless
|
|
36
|
+
/** Origin allowlist; the token is always required regardless. */
|
|
37
37
|
allowedOrigins: string[] | "*";
|
|
38
|
-
/** Native TLS via Bun.serve (
|
|
38
|
+
/** Native TLS via Bun.serve on the same listener (off-LAN). */
|
|
39
39
|
tls: TlsOptions | null;
|
|
40
40
|
/** Plain-HTTP health endpoint (no auth). */
|
|
41
41
|
healthPath: string;
|
|
42
42
|
/**
|
|
43
43
|
* Keep the opencode location loaded against the idle timeout (default
|
|
44
44
|
* `experimental.location_idle_timeout`, 60 minutes) via a periodic durable
|
|
45
|
-
* touch of an internal anchor session
|
|
45
|
+
* touch of an internal anchor session. With this on, the
|
|
46
46
|
* `location_idle_timeout: false` config entry is not needed. The anchor
|
|
47
47
|
* shows in the TUI session list as "opencode-ahp (keep-alive)"; AHP
|
|
48
48
|
* clients never see it.
|
|
@@ -55,7 +55,14 @@ export interface Options {
|
|
|
55
55
|
keepAliveIntervalMinutes: number;
|
|
56
56
|
/** Global actions kept for reconnect replay; older gaps → snapshot. */
|
|
57
57
|
replayWindow: number;
|
|
58
|
-
/**
|
|
58
|
+
/**
|
|
59
|
+
* Timestamped capture of the raw opencode event stream to the server
|
|
60
|
+
* log — one `event ok|dropped|unimplemented` line per event (design
|
|
61
|
+
* §8.1). Off by default: a busy turn emits dozens of lines. The LAN
|
|
62
|
+
* test server script (scripts/ahp-server.mjs) enables it.
|
|
63
|
+
*/
|
|
64
|
+
logEvents: boolean;
|
|
65
|
+
/** Advertised in `initialize`. */
|
|
59
66
|
capabilities: CapabilityFlags;
|
|
60
67
|
}
|
|
61
68
|
|
|
@@ -71,9 +78,15 @@ export const BUILTIN_OPTIONS: Options = {
|
|
|
71
78
|
keepAlive: true,
|
|
72
79
|
keepAliveIntervalMinutes: 10,
|
|
73
80
|
replayWindow: 1000,
|
|
74
|
-
//
|
|
75
|
-
//
|
|
76
|
-
|
|
81
|
+
// Event capture is off by default (a busy turn emits dozens of lines);
|
|
82
|
+
// the LAN test server script enables it.
|
|
83
|
+
logEvents: false,
|
|
84
|
+
// Changesets and the synthetic shell-command terminals are both on by
|
|
85
|
+
// default; opt out with `capabilities.changesets: false` and
|
|
86
|
+
// `capabilities.terminals: false` respectively.
|
|
87
|
+
// Off the wire in 1.0.0 (no capability field) — the flag gates the
|
|
88
|
+
// host-side behavior only.
|
|
89
|
+
capabilities: { changesets: true, terminals: true, automations: false },
|
|
77
90
|
};
|
|
78
91
|
|
|
79
92
|
export function isRecord(v: unknown): v is Record<string, unknown> {
|
|
@@ -248,6 +261,7 @@ export function resolveOptions(
|
|
|
248
261
|
BUILTIN_OPTIONS.keepAliveIntervalMinutes,
|
|
249
262
|
),
|
|
250
263
|
replayWindow: pick("replayWindow", isPosInt, BUILTIN_OPTIONS.replayWindow),
|
|
264
|
+
logEvents: pick("logEvents", isBool, BUILTIN_OPTIONS.logEvents),
|
|
251
265
|
capabilities: resolveCapabilities(file["capabilities"], ctx["capabilities"]),
|
|
252
266
|
};
|
|
253
267
|
}
|
package/src/seq.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Global action sequencer + replay window
|
|
2
|
+
* Global action sequencer + replay window.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* snapshot is taken at 42. Consequences:
|
|
4
|
+
* AHP 1.0.0's `serverSeq` is a single host-wide sequence across all
|
|
5
|
+
* channels (not per-channel) — the spec's lifecycle example numbers a
|
|
6
|
+
* chat action 43 while a root snapshot is taken at 42. Consequences:
|
|
8
7
|
* - snapshots carry `fromSeq` = the current global seq;
|
|
9
8
|
* - reconnect replay is a *global* range (serverSeq > lastSeen) filtered
|
|
10
9
|
* by the client's subscriptions;
|
package/src/state.ts
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Channel state stores, all maintained by the official reducers from
|
|
3
3
|
* @microsoft/agent-host-protocol — the host never hand-rolls state
|
|
4
|
-
* transitions (
|
|
5
|
-
* reducers").
|
|
4
|
+
* transitions (state is computed by the official reducers).
|
|
6
5
|
*
|
|
7
|
-
* - root channel: `rootReducer
|
|
8
|
-
* - session channels: `sessionReducer
|
|
9
|
-
* - chat channels: `chatReducer
|
|
10
|
-
* - changeset channels: `changesetReducer
|
|
6
|
+
* - root channel: `rootReducer`;
|
|
7
|
+
* - session channels: `sessionReducer`;
|
|
8
|
+
* - chat channels: `chatReducer`;
|
|
9
|
+
* - changeset channels: `changesetReducer`;
|
|
10
|
+
* - terminal channels: `terminalReducer`.
|
|
11
11
|
*/
|
|
12
12
|
import {
|
|
13
13
|
chatReducer,
|
|
14
14
|
changesetReducer,
|
|
15
15
|
rootReducer,
|
|
16
16
|
sessionReducer,
|
|
17
|
+
terminalReducer,
|
|
17
18
|
type ChatAction,
|
|
18
19
|
type ChatState,
|
|
19
20
|
type ChangesetAction,
|
|
@@ -22,6 +23,8 @@ import {
|
|
|
22
23
|
type RootState,
|
|
23
24
|
type SessionAction,
|
|
24
25
|
type SessionState,
|
|
26
|
+
type TerminalAction,
|
|
27
|
+
type TerminalState,
|
|
25
28
|
} from "@microsoft/agent-host-protocol";
|
|
26
29
|
|
|
27
30
|
export interface RootStateStore {
|
|
@@ -52,6 +55,20 @@ export interface ChangesetStateStore {
|
|
|
52
55
|
apply(action: ChangesetAction): ChangesetState;
|
|
53
56
|
}
|
|
54
57
|
|
|
58
|
+
export interface TerminalStateStore {
|
|
59
|
+
/** Current terminal state (the `ahp-terminal:/…` snapshot payload). */
|
|
60
|
+
readonly state: TerminalState;
|
|
61
|
+
/** Apply a terminal-channel action through the official reducer. */
|
|
62
|
+
apply(action: TerminalAction): TerminalState;
|
|
63
|
+
/**
|
|
64
|
+
* Replace the held state outright. The one non-reducer transition the
|
|
65
|
+
* host makes: the pty-content trim (the official terminal reducer is
|
|
66
|
+
* append-only and never trims; the host mirrors the VS Code reference
|
|
67
|
+
* client's rolling-buffer trim — design §12.2).
|
|
68
|
+
*/
|
|
69
|
+
replace(state: TerminalState): TerminalState;
|
|
70
|
+
}
|
|
71
|
+
|
|
55
72
|
export function createRootStateStore(initial: RootState): RootStateStore {
|
|
56
73
|
let state: RootState = initial;
|
|
57
74
|
return {
|
|
@@ -103,3 +120,20 @@ export function createChangesetStateStore(initial: ChangesetState): ChangesetSta
|
|
|
103
120
|
},
|
|
104
121
|
};
|
|
105
122
|
}
|
|
123
|
+
|
|
124
|
+
export function createTerminalStateStore(initial: TerminalState): TerminalStateStore {
|
|
125
|
+
let state: TerminalState = initial;
|
|
126
|
+
return {
|
|
127
|
+
get state(): TerminalState {
|
|
128
|
+
return state;
|
|
129
|
+
},
|
|
130
|
+
apply(action: TerminalAction): TerminalState {
|
|
131
|
+
state = terminalReducer(state, action);
|
|
132
|
+
return state;
|
|
133
|
+
},
|
|
134
|
+
replace(next: TerminalState): TerminalState {
|
|
135
|
+
state = next;
|
|
136
|
+
return state;
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|