opencode-ahp 0.1.5 → 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.
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Turn lifecycle section (design §8): host-minted turn ids, turn start/claim, and the turn-terminal handoff (steering/queue, changeset + terminal catalog refresh).
3
+ */
4
+
5
+ import { HostTerminals } from "./host-terminals.js";
6
+ import { ActionType, PendingMessageKind, Message } from "@microsoft/agent-host-protocol";
7
+ import { userMessage } from "./bridge.js";
8
+ import { ChatRuntime } from "./host-types.js";
9
+
10
+ export class HostTurns extends HostTerminals {
11
+ // ── turn helpers ───────────────────────────────────────────────────────
12
+ protected mintTurnId(): string {
13
+ this.turnCounter += 1;
14
+ return `turn_${Date.now().toString(36)}_${this.turnCounter.toString(36)}`;
15
+ }
16
+
17
+ protected turnDuration(chat: ChatRuntime): number {
18
+ return Math.max(0, Date.now() - (chat.turnStartedAt ?? Date.now()));
19
+ }
20
+
21
+ /** Claim a turn (write-ahead) and publish `chat/turnStarted`. */
22
+ protected startTurn(chat: ChatRuntime, message: Message, queuedMessageId?: string): void {
23
+ const turnId = this.mintTurnId();
24
+ chat.currentTurnId = turnId;
25
+ chat.turnStartedAt = Date.now();
26
+ this.publish({
27
+ channel: chat.uri,
28
+ action: {
29
+ type: ActionType.ChatTurnStarted,
30
+ turnId,
31
+ startedAt: new Date().toISOString(),
32
+ message,
33
+ ...(queuedMessageId !== undefined ? { queuedMessageId } : {}),
34
+ },
35
+ });
36
+ }
37
+
38
+ /**
39
+ * After a turn terminal: clear the steering message opencode consumed
40
+ * during the turn, and auto-start the next turn from the queue (the
41
+ * queued prompt was already sent with `delivery: "queue"` — opencode
42
+ * starts it automatically; this only updates the AHP state).
43
+ *
44
+ * Then refresh the session's changesets — the turn's captured
45
+ * "after" content is read from disk here, and the uncommitted/session/
46
+ * turn changesets recompute (async: awaits the facade).
47
+ */
48
+ protected async finishTurn(chat: ChatRuntime): Promise<void> {
49
+ const endedTurnId = chat.currentTurnId;
50
+ chat.currentTurnId = null;
51
+ chat.turnStartedAt = null;
52
+ const state = chat.chatStore.state;
53
+ if (state.steeringMessage !== undefined) {
54
+ this.publish({
55
+ channel: chat.uri,
56
+ action: {
57
+ type: ActionType.ChatPendingMessageRemoved,
58
+ kind: PendingMessageKind.Steering,
59
+ id: state.steeringMessage.id,
60
+ },
61
+ });
62
+ }
63
+ const queued = state.queuedMessages;
64
+ if (queued !== undefined && queued.length > 0) {
65
+ const next = queued[0]!;
66
+ this.startTurn(chat, next.message, next.id);
67
+ } else if (chat.lastInbox !== null && chat.lastInbox.delivery === "queue") {
68
+ // A queued prompt from outside AHP (e.g. the TUI).
69
+ this.startTurn(chat, userMessage(chat.lastInbox.text));
70
+ }
71
+ // The ended turn's command terminals leave the
72
+ // root catalog now (retention — their state stays subscribable until
73
+ // the chat/record is removed). Runs after the possible
74
+ // chained startTurn so the published list is the post-handoff one.
75
+ if (this.opts.terminals && endedTurnId !== null && this.terminals.size > 0) {
76
+ this.refreshTerminals();
77
+ }
78
+ if (this.opts.changesets && endedTurnId !== null) {
79
+ await this.refreshTurnChangesets(this.byChannel.get(chat.uri)!, chat, endedTurnId);
80
+ }
81
+ }
82
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Record types shared by the host section classes: the per-socket, per-client, per-session, per-chat and per-terminal state shapes, and the HostOptions the Host is constructed with.
3
+ */
4
+
5
+ import { ActionType, ReconnectResultType, Implementation, SessionSummary } from "@microsoft/agent-host-protocol";
6
+ import { OpencodeFacade } from "./bridge.js";
7
+ import { ClientToolInvocation } from "./client-tools.js";
8
+ import { ChatStateStore, ChangesetStateStore, SessionStateStore, TerminalStateStore } from "./state.js";
9
+
10
+ // ActionType / ReconnectResultType are `declare const enum` in the package
11
+ // but are also real runtime objects (verified against the published dist),
12
+ // so the value imports are safe under both tsc (inlined) and Bun.
13
+ export interface RpcMessage {
14
+ jsonrpc?: unknown;
15
+ id?: unknown;
16
+ method?: unknown;
17
+ params?: unknown;
18
+ }
19
+
20
+ export interface SocketState {
21
+ initialized: boolean;
22
+ /** Negotiated version (set by initialize, inherited on reconnect). */
23
+ version: string | null;
24
+ clientId: string | null;
25
+ }
26
+
27
+ /**
28
+ * Per-clientId registry record — survives socket closes so `reconnect`
29
+ * can replay for the same client (AHP lifecycle spec).
30
+ */
31
+ export interface ClientRecord {
32
+ version: string;
33
+ socketId: number | null;
34
+ }
35
+
36
+ /**
37
+ * Everything the host tracks for one AHP chat — the backing opencode
38
+ * session, its chat-state store, and the per-turn tracking the event
39
+ * pump needs to join opencode events to AHP turns. One AHP chat ↔ one
40
+ * opencode session.
41
+ */
42
+ export interface ChatRuntime {
43
+ /** The AHP chat channel URI (`ahp-chat:/…`). */
44
+ uri: string;
45
+ /** The opencode session id backing this chat (`ses_…`). */
46
+ sessionID: string;
47
+ chatStore: ChatStateStore;
48
+ // ── turn tracking (event-pump join state) ────────────────────────────
49
+ /** The AHP turnId the pump joins opencode events to, or null. */
50
+ currentTurnId: string | null;
51
+ turnStartedAt: number | null;
52
+ /** `<providerID>/<modelID>` captured from `session.step.started` (usage model ref). */
53
+ turnModelRef: string | null;
54
+ // ── part / tool tracking ─────────────────────────────────────────────
55
+ /** Emitted part keys (`<assistantMessageID>:<kind>:<ordinal>`). */
56
+ parts: Set<string>;
57
+ /** toolCallId → raw JSON input text (`session.tool.input.ended.text`). */
58
+ toolInput: Map<string, string>;
59
+ /** toolCallId → opencode tool name (`session.tool.input.started.name`). */
60
+ toolName: Map<string, string>;
61
+ /** toolCallIds that already received `chat/toolCallReady`. */
62
+ toolReady: Set<string>;
63
+ /** toolCallId → opencode permission request id. */
64
+ permissionForTool: Map<string, string>;
65
+ /** opencode permission request id → toolCallId. */
66
+ toolForPermission: Map<string, string>;
67
+ /**
68
+ * toolCallId → client-executed tool call tracking (created at
69
+ * `tool.input.started`, removed at the opencode-side terminal).
70
+ */
71
+ clientToolCalls: Map<string, ClientToolInvocation>;
72
+ /** The most recent `session.inbox.enqueued` (external/TUI prompt tracking). */
73
+ lastInbox: { text: string; delivery: string } | null;
74
+ // ── changesets ────────────────────────────────────────────────
75
+ /**
76
+ * Live chat-owned changeset stores (uncommitted + turn), keyed by
77
+ * changeset URI (created on subscribe). The session-kind changeset
78
+ * store lives on the record instead (the session channel owns it).
79
+ */
80
+ changesets: Map<string, ChangesetStateStore>;
81
+ /**
82
+ * Per-turn file snapshots for the turn changesets: turnId → absPath →
83
+ * captured {before (pre-edit disk read), after (disk at turn end)}.
84
+ * `null` = the file was absent on that side. Kept until the chat is
85
+ * removed (content refs + discard-restore read them).
86
+ */
87
+ turnSnapshots: Map<string, Map<string, { before: string | null; after: string | null }>>;
88
+ }
89
+
90
+ /**
91
+ * Everything the host knows about one AHP session: the session store,
92
+ * its chat catalog (default chat first, then insertion order), and the
93
+ * denormalized summary fields for root notifications. `sessionID` is the
94
+ * default chat's opencode id — the key of the `sessions` map and the
95
+ * event-pump join key for the default chat.
96
+ */
97
+ export interface SessionRecord {
98
+ /** The default chat's opencode session id (`ses_…`). */
99
+ sessionID: string;
100
+ /** The AHP session channel URI (`ahp-session:/<suffix>`). */
101
+ channel: string;
102
+ /** Identity `SessionSummary.provider` (fixed at registration). */
103
+ provider: string;
104
+ createdAt: string;
105
+ /** Denormalized `SessionSummary.modifiedAt` (ISO; lexicographic = chronological). */
106
+ modifiedAt: string;
107
+ sessionStore: SessionStateStore;
108
+ /** Chat runtimes keyed by chat channel URI (default first, insertion order). */
109
+ chats: Map<string, ChatRuntime>;
110
+ /** The chat channel URI that receives input when none is selected. */
111
+ defaultChatURI: string;
112
+ /** The session-kind changeset store (owned by the session channel). */
113
+ sessionChangesets: Map<string, ChangesetStateStore>;
114
+ }
115
+
116
+ /**
117
+ * The host's handle to a spawned pty process (the injected `spawnPty`
118
+ * seam's return): forward input to the process, resize its window, and
119
+ * kill it (client dispose / location teardown).
120
+ */
121
+ export interface PtyProcess {
122
+ write(data: string): void;
123
+ resize(cols: number, rows: number): void;
124
+ kill(): void;
125
+ }
126
+
127
+ /** Everything the host tells the `spawnPty` seam to start an interactive shell. */
128
+ export interface SpawnPtyInput {
129
+ /** The spawn working directory (absolute path, inside the location directory). */
130
+ cwd: string;
131
+ cols: number;
132
+ rows: number;
133
+ /** pty output — the `terminal/data` source. */
134
+ onOutput: (data: string) => void;
135
+ /** Process exit; `code` undefined when killed without an exit code. */
136
+ onExit: (code: number | undefined) => void;
137
+ }
138
+
139
+ /**
140
+ * Spawns an interactive pty shell for `createTerminal`. Injected by the
141
+ * plugin entry (the Bun runtime provides it — `Bun.spawn` with the
142
+ * `terminal` option); unit tests inject a fake. Undefined when the
143
+ * runtime cannot spawn ptys (the terminal commands then answer -32601).
144
+ */
145
+ export type SpawnPty = (input: SpawnPtyInput) => PtyProcess;
146
+
147
+ /** Fields shared by every terminal record. */
148
+ interface TerminalRecordBase {
149
+ /** The terminal channel URI (synthetic: `ahp-terminal:/<toolCallId>`; pty: client-chosen). */
150
+ uri: string;
151
+ /** The official-reducer store (the snapshot payload). */
152
+ store: TerminalStateStore;
153
+ /** Date.now() at creation (the synthetic kind uses it as the `durationMs` baseline). */
154
+ startedAt: number;
155
+ }
156
+
157
+ /**
158
+ * A read-only rendering of a
159
+ * `shell`-tool command execution (`isPty: false`, command parts only).
160
+ * Opened at the tool call's `tool.input.ended` (the command line is only
161
+ * known there); the record outlives its turn — the root catalog drops it
162
+ * at turn end (retention), and the channel state stays subscribable until
163
+ * the owning chat/record is removed.
164
+ */
165
+ export interface SyntheticTerminalRecord extends TerminalRecordBase {
166
+ kind: "synthetic";
167
+ /** The AHP session record that owns the channel (claim `session`). */
168
+ rec: SessionRecord;
169
+ /** The chat whose turn ran the command (claim `chat`). */
170
+ chat: ChatRuntime;
171
+ /** The opencode tool call id (also the `commandId`, scoped to the URI). */
172
+ toolCallId: string;
173
+ /** The AHP turnId the command executed in — the catalog membership key. */
174
+ turnId: string;
175
+ commandLine: string;
176
+ }
177
+
178
+ /**
179
+ * An interactive pseudoterminal shell spawned for a client via
180
+ * `createTerminal` (design §12.2): a client-chosen channel URI, a real
181
+ * shell process in a resolved working directory, and a lifecycle of its
182
+ * own (input/resize to the process, claim/title/clear through the
183
+ * official reducer). Listed in the root catalog while the record is
184
+ * alive (running or exited) until the client disposes it or the location
185
+ * tears down.
186
+ */
187
+ export interface PtyTerminalRecord extends TerminalRecordBase {
188
+ kind: "pty";
189
+ /** The spawned process handle (the `spawnPty` seam's return). */
190
+ process: PtyProcess;
191
+ /** The resolved spawn working directory (absolute path). */
192
+ cwd: string;
193
+ }
194
+
195
+ export type TerminalRecord = SyntheticTerminalRecord | PtyTerminalRecord;
196
+
197
+ export interface HostOptions {
198
+ serverInfo: Implementation;
199
+ facade: OpencodeFacade;
200
+ replayWindow: number;
201
+ /** The opencode instance's working directory (InitializeResult.defaultDirectory). */
202
+ defaultDirectory?: string;
203
+ /** Advertise + serve the changeset channels (catalogues, snapshots, discard). */
204
+ changesets: boolean;
205
+ /**
206
+ * Serve the terminal channels — the synthetic shell-command renderings
207
+ * (one read-only `ahp-terminal:` channel per foreground `shell`-tool
208
+ * call) and the interactive pty shells behind `createTerminal`. Off the
209
+ * wire in 1.0.0 (no capability field) — the switch gates the
210
+ * host-side behavior (off: the synthetic channels never open and the
211
+ * terminal commands answer -32601).
212
+ */
213
+ terminals: boolean;
214
+ /**
215
+ * The pty spawn seam for `createTerminal` (undefined when the runtime
216
+ * cannot spawn ptys — the command then answers -32601). The plugin
217
+ * entry provides the Bun-backed factory; tests inject a fake.
218
+ */
219
+ spawnPty?: SpawnPty;
220
+ /** Deliver a JSON-serializable frame to a connection. */
221
+ send: (socketId: number, message: unknown) => void;
222
+ /** Close one connection (a superseded duplicate clientId). */
223
+ close?: (socketId: number, code?: number, reason?: string) => void;
224
+ log?: (message: string) => void;
225
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Free-function helpers for the host section classes — wire normalizers, result mappers, path confinement, AHP-marker parsing, shell exit-code extraction — plus the two tuning constants (AHP metadata key, external-register grace window).
3
+ */
4
+
5
+ import { resolve as resolvePath } from "node:path";
6
+ import { ToolResultContentType, SessionActiveClient, StringOrMarkdown, ToolCallResult, ToolResultContent } from "@microsoft/agent-host-protocol";
7
+ import { FacadeClientToolResult, FacadeModelRef, FacadeToolContent } from "./bridge.js";
8
+ import { normalizeToolDefinitions } from "./client-tools.js";
9
+ import { channelKind } from "./channels.js";
10
+ import { isRecord } from "./options.js";
11
+
12
+ /**
13
+ * Grace before the pump registers an externally created session
14
+ * (`session.created`): a concurrent `createSession` may still be resolving
15
+ * for the same opencode session under a client-chosen channel; the slower
16
+ * path is healed by the delete+recreate remap in `handleCreateSession`.
17
+ */
18
+ export const EXTERNAL_REGISTER_GRACE_MS = 250;
19
+
20
+ /**
21
+ * The exit code of a successful `shell`-tool result, read from its LAST
22
+ * text content part. opencode's shell tool
23
+ * appends a trailing `Exit code: N` notice part only for non-zero exits
24
+ * and signals (`Exit code: 137 (SIGKILL)` — the 128+signum convention
25
+ * parses as the numeric status); a zero exit carries no notice.
26
+ * Spawn failures arrive as `tool.failed` instead (no code available
27
+ * there). `null` when the last part carries an `Exit code:` line with a
28
+ * non-numeric value (e.g. `Exit code: unknown`) — the actions then
29
+ * omit the field.
30
+ */
31
+ export function shellExitCodeOf(content: FacadeToolContent[]): number | null {
32
+ const last = content
33
+ .map((c) => (c.type === "text" && typeof c.text === "string" ? c.text : null))
34
+ .filter((t): t is string => t !== null)
35
+ .pop();
36
+ if (last === undefined) return 0; // no output, no notice — clean zero exit
37
+ const numeric = /Exit code: (-?\d+)\b/.exec(last);
38
+ if (numeric !== null) return Number.parseInt(numeric[1]!, 10);
39
+ return /Exit code:/.test(last) ? null : 0;
40
+ }
41
+
42
+ /**
43
+ * Durability: the opencode session-metadata key carrying the AHP
44
+ * markers. Two shapes, same key:
45
+ * - on a peer-chat backend:
46
+ * `{ chat: <chat channel URI>, owner: <the opencode session id of
47
+ * the owning AHP session> }` — `owner` is the opencode id, not the
48
+ * channel suffix (a client-chosen suffix differs from the minted
49
+ * opencode id);
50
+ * - on the default backend of a minted-id session:
51
+ * `{ channel: <session channel URI> }` — the client-chosen session
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
+ */
56
+ export const AHP_METADATA_KEY = "opencode-ahp";
57
+
58
+ /**
59
+ * 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.
63
+ */
64
+ export function parseAhpMarker(metadata: unknown): { chat?: string; owner?: string; channel?: string } | null {
65
+ if (!isRecord(metadata)) return null;
66
+ const marker = metadata[AHP_METADATA_KEY];
67
+ if (!isRecord(marker)) return null;
68
+ const out: { chat?: string; owner?: string; channel?: string } = {};
69
+ const chat = marker["chat"];
70
+ if (typeof chat === "string" && channelKind(chat) === "chat") out.chat = chat;
71
+ const owner = marker["owner"];
72
+ if (typeof owner === "string" && owner.startsWith("ses")) out.owner = owner;
73
+ const channel = marker["channel"];
74
+ if (typeof channel === "string" && channelKind(channel) === "session") out.channel = channel;
75
+ return Object.keys(out).length > 0 ? out : null;
76
+ }
77
+
78
+ export function sameAgents(a: unknown, b: unknown): boolean {
79
+ return JSON.stringify(a) === JSON.stringify(b);
80
+ }
81
+
82
+ export function errorMessage(e: unknown): string {
83
+ return e instanceof Error ? e.message : String(e);
84
+ }
85
+
86
+ /** Short, stable description of untrusted params for log lines. */
87
+ export function describeParams(params: unknown): string {
88
+ if (!isRecord(params)) return String(typeof params);
89
+ try {
90
+ const raw = JSON.stringify(Object.keys(params));
91
+ return raw.length > 120 ? raw.slice(0, 120) + "…" : raw;
92
+ } catch {
93
+ return "unserializable";
94
+ }
95
+ }
96
+
97
+ /** The first enabled model of a provider, as a FacadeModelRef. */
98
+ export function firstEnabledModelRef(models: readonly { providerID: string; modelID: string; enabled: boolean }[]): FacadeModelRef | undefined {
99
+ const m = models.find((x) => x.enabled);
100
+ return m !== undefined ? { providerID: m.providerID, modelID: m.modelID } : undefined;
101
+ }
102
+
103
+ /** Normalize an untrusted `activeClient` payload (untrusted JSON-RPC). */
104
+ export function normalizeActiveClient(ac: Record<string, unknown>): SessionActiveClient {
105
+ return {
106
+ clientId: ac["clientId"] as string,
107
+ tools: normalizeToolDefinitions(ac["tools"]),
108
+ ...(typeof ac["displayName"] === "string" ? { displayName: ac["displayName"] as string } : {}),
109
+ };
110
+ }
111
+
112
+ /**
113
+ * Wire-validate a client-dispatched `toolCallComplete` result:
114
+ * `success` is the one field the host depends on (it decides
115
+ * the facade result + the Tool.Error path); the rest is stored
116
+ * verbatim for the AHP state mirror.
117
+ */
118
+ export function normalizeToolCallResult(raw: unknown): ToolCallResult | null {
119
+ if (typeof raw !== "object" || raw === null) return null;
120
+ const r = raw as Record<string, unknown>;
121
+ if (typeof r["success"] !== "boolean") return null;
122
+ const pastTense = r["pastTenseMessage"];
123
+ return {
124
+ success: r["success"],
125
+ pastTenseMessage:
126
+ typeof pastTense === "string"
127
+ ? pastTense
128
+ : (isRecord(pastTense) && typeof pastTense["markdown"] === "string"
129
+ ? (pastTense["markdown"] as string)
130
+ : ""),
131
+ ...(Array.isArray(r["content"]) ? { content: r["content"] as ToolResultContent[] } : {}),
132
+ ...(isRecord(r["structuredContent"]) ? { structuredContent: r["structuredContent"] as Record<string, unknown> } : {}),
133
+ ...(isRecord(r["error"]) ? { error: r["error"] as { message: string; code?: string } } : {}),
134
+ };
135
+ }
136
+
137
+ /** StringOrMarkdown → plain string (the facade result carries text). */
138
+ function stringOrMarkdownToText(v: StringOrMarkdown | undefined): string {
139
+ if (v === undefined) return "";
140
+ if (typeof v === "string") return v;
141
+ return typeof v.markdown === "string" ? v.markdown : "";
142
+ }
143
+
144
+ /**
145
+ * A validated client `ToolCallResult` → the opencode-side result:
146
+ * success:false → the `Tool.Error` message (the model sees the
147
+ * failure); success → the text content blocks joined (non-text blocks
148
+ * stay in the AHP state for the client's UI; the model gets the text +
149
+ * the past-tense message).
150
+ */
151
+ export function clientResultToFacade(result: ToolCallResult): FacadeClientToolResult {
152
+ if (!result.success) {
153
+ return { ok: false, error: result.error?.message ?? "the client reported a tool failure" };
154
+ }
155
+ const texts: string[] = [];
156
+ for (const c of result.content ?? []) {
157
+ // The content came from the wire (untrusted) — guard the shape.
158
+ if (c.type === ToolResultContentType.Text && typeof c.text === "string") texts.push(c.text);
159
+ }
160
+ const content = texts.join("\n\n");
161
+ return {
162
+ ok: true,
163
+ pastTenseMessage: stringOrMarkdownToText(result.pastTenseMessage),
164
+ ...(content.length > 0 ? { content } : {}),
165
+ ...(result.structuredContent !== undefined ? { structuredContent: result.structuredContent } : {}),
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Map opencode tool result content blocks to AHP `ToolResultContent`
171
+ * (only text blocks are representable; file/patch text is
172
+ * carried as text).
173
+ */
174
+ export function mapToolResultContent(content: readonly { type: string; text?: string }[]): ToolResultContent[] {
175
+ const out: ToolResultContent[] = [];
176
+ for (const c of content) {
177
+ if (c.type === "text" || c.type === "file" || c.type === "patch") {
178
+ out.push({ type: ToolResultContentType.Text, text: c.text ?? "" });
179
+ }
180
+ }
181
+ return out;
182
+ }
183
+
184
+ /**
185
+ * True when `child` is `parent` itself or strictly inside it (both resolved
186
+ * first, so relative segments and `..` cannot escape the comparison). Used
187
+ * to confine turn-snapshot paths and `resourceRead`/`invokeChangesetOperation`
188
+ * targets to the location directory.
189
+ */
190
+ export function isPathInside(child: string, parent: string): boolean {
191
+ const a = resolvePath(child);
192
+ const b = resolvePath(parent);
193
+ return a === b || a.startsWith(b + "/");
194
+ }