opencode-ahp 0.1.5 → 0.1.7

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 CHANGED
@@ -53,10 +53,13 @@ type SessionCreateMetadata = NonNullable<Parameters<SessionDomain["create"]>[0]>
53
53
  import { isRecord, resolveOptions, type Options } from "./options.js";
54
54
  import { createListener, type Listener } from "./transport.js";
55
55
  import { Host } from "./host.js";
56
+ import type { SpawnPty } from "./host-types.js";
56
57
  import { KeepAlive, KEEPALIVE_SESSION_ID } from "./keep-alive.js";
57
58
  import { errorMessage } from "./error.js";
58
59
  import {
59
- mapV2Event,
60
+ eventLogLine,
61
+ mapV2EventRaw,
62
+ timeStamp,
60
63
  type FacadeAgent,
61
64
  type FacadeClientTool,
62
65
  type FacadeModel,
@@ -108,6 +111,92 @@ function pluginVersion(): string {
108
111
  return "0.1.1";
109
112
  }
110
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
+
111
200
  /** 32 random bytes, base64url — 43 chars, comfortably over the 16-char floor. */
112
201
  function generateToken(): string {
113
202
  const bytes = new Uint8Array(32);
@@ -230,10 +319,19 @@ function isEnoent(err: unknown): boolean {
230
319
  * `execute` bridge needs the host, but the facade is constructed as part
231
320
  * of the host's own options — a mutable holder assigned right after
232
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.
233
326
  */
234
327
  type HostRef = { current: Host | null };
235
328
 
236
- function implementFacade(ctx: Context, hiddenSessionID: string | null, hostRef: HostRef): OpencodeFacade {
329
+ function implementFacade(
330
+ ctx: Context,
331
+ hiddenSessionID: string | null,
332
+ hostRef: HostRef,
333
+ logEvent: ((line: string) => void) | null,
334
+ ): OpencodeFacade {
237
335
  const locationDir = ctx.location.directory;
238
336
 
239
337
  // The cross-session client-tool set (client-provided tools).
@@ -386,15 +484,19 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null, hostRef:
386
484
  });
387
485
  },
388
486
  /**
389
- * The mapped event stream (bridge.ts `mapV2Event` is the only place
390
- * that knows the raw wire shape). Ends without error when the host's
391
- * pump signal aborts (teardown).
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).
392
493
  */
393
494
  async *events(signal: AbortSignal) {
394
495
  for await (const event of ctx.event.subscribe({ signal })) {
395
496
  if (hiddenSessionID !== null && isHiddenSessionEvent(event, hiddenSessionID)) continue;
396
- const mapped = mapV2Event(event);
397
- if (mapped !== null) yield mapped;
497
+ const outcome = mapV2EventRaw(event);
498
+ if (logEvent !== null) logEvent(eventLogLine(outcome, event, timeStamp(new Date())));
499
+ if (outcome.status === "ok") yield outcome.event;
398
500
  }
399
501
  },
400
502
  // ── changesets ────────────────────────────────
@@ -597,11 +699,17 @@ export default Plugin.define({
597
699
  try {
598
700
  const host = new Host({
599
701
  serverInfo: { name: "opencode-ahp", version: pluginVersion(), title: "OpenCode" },
600
- facade: implementFacade(ctx, hiddenSessionID, hostRef),
702
+ facade: implementFacade(
703
+ ctx,
704
+ hiddenSessionID,
705
+ hostRef,
706
+ opts.logEvents ? (line) => console.log(line) : null,
707
+ ),
601
708
  replayWindow: opts.replayWindow,
602
709
  defaultDirectory: ctx.location.directory,
603
710
  changesets: opts.capabilities.changesets,
604
711
  terminals: opts.capabilities.terminals,
712
+ spawnPty: createBunSpawnPty(),
605
713
  send: (socketId, message) => {
606
714
  listener?.sendTo({ id: socketId }, JSON.stringify(message));
607
715
  },
@@ -641,7 +749,12 @@ export default Plugin.define({
641
749
  // text/reasoning, tool lifecycle, permissions, usage, turn
642
750
  // terminals, steering/queue handoff).
643
751
  host.startEventPump();
644
- cleanupHost = () => host.stopEventPump();
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
+ };
645
758
  console.log(
646
759
  `${TAG} AHP 1.0.0 host listening on ws${opts.tls ? "s" : ""}://${opts.host}:${listener.port}${opts.path} ` +
647
760
  `(token ${opts.token ? "from options" : "auto-generated"}; health ${opts.healthPath})`,
package/src/options.ts CHANGED
@@ -55,6 +55,13 @@ export interface Options {
55
55
  keepAliveIntervalMinutes: number;
56
56
  /** Global actions kept for reconnect replay; older gaps → snapshot. */
57
57
  replayWindow: number;
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;
58
65
  /** Advertised in `initialize`. */
59
66
  capabilities: CapabilityFlags;
60
67
  }
@@ -71,6 +78,9 @@ export const BUILTIN_OPTIONS: Options = {
71
78
  keepAlive: true,
72
79
  keepAliveIntervalMinutes: 10,
73
80
  replayWindow: 1000,
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,
74
84
  // Changesets and the synthetic shell-command terminals are both on by
75
85
  // default; opt out with `capabilities.changesets: false` and
76
86
  // `capabilities.terminals: false` respectively.
@@ -251,6 +261,7 @@ export function resolveOptions(
251
261
  BUILTIN_OPTIONS.keepAliveIntervalMinutes,
252
262
  ),
253
263
  replayWindow: pick("replayWindow", isPosInt, BUILTIN_OPTIONS.replayWindow),
264
+ logEvents: pick("logEvents", isBool, BUILTIN_OPTIONS.logEvents),
254
265
  capabilities: resolveCapabilities(file["capabilities"], ctx["capabilities"]),
255
266
  };
256
267
  }
package/src/state.ts CHANGED
@@ -60,6 +60,13 @@ export interface TerminalStateStore {
60
60
  readonly state: TerminalState;
61
61
  /** Apply a terminal-channel action through the official reducer. */
62
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;
63
70
  }
64
71
 
65
72
  export function createRootStateStore(initial: RootState): RootStateStore {
@@ -124,5 +131,9 @@ export function createTerminalStateStore(initial: TerminalState): TerminalStateS
124
131
  state = terminalReducer(state, action);
125
132
  return state;
126
133
  },
134
+ replace(next: TerminalState): TerminalState {
135
+ state = next;
136
+ return state;
137
+ },
127
138
  };
128
139
  }