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.
@@ -0,0 +1,109 @@
1
+ /**
2
+ * AHP channel registry (plan §6.1 channels.ts): URI parsing/formatting,
3
+ * per-socket subscription bookkeeping, and the set of live opencode
4
+ * sessions. Pure in-memory — no runtime dependencies.
5
+ *
6
+ * Phase 0 only the root channel is live; session/chat URI handling and
7
+ * the session registry land with Phase 1 (session support).
8
+ */
9
+
10
+ export const ROOT_CHANNEL = "ahp-root://";
11
+ const SESSION_PREFIX = "ahp-session:/";
12
+ const CHAT_PREFIX = "ahp-chat:/";
13
+
14
+ export type ChannelKind = "root" | "session" | "chat" | "unknown";
15
+
16
+ export function channelKind(uri: string): ChannelKind {
17
+ if (uri === ROOT_CHANNEL) return "root";
18
+ if (uri.startsWith(SESSION_PREFIX) && uri.length > SESSION_PREFIX.length) return "session";
19
+ if (uri.startsWith(CHAT_PREFIX) && uri.length > CHAT_PREFIX.length) return "chat";
20
+ return "unknown";
21
+ }
22
+
23
+ /**
24
+ * Channel URI of a session. opencode has one chat per session (plan §3.2
25
+ * gap, same as pi-ahp / ahp-acp-gateway), and the session's default chat
26
+ * reuses the session id.
27
+ */
28
+ export function sessionChannelURI(sessionID: string): string {
29
+ return SESSION_PREFIX + sessionID;
30
+ }
31
+
32
+ /** Channel URI of a session's (single) default chat. */
33
+ export function chatChannelURI(sessionID: string): string {
34
+ return CHAT_PREFIX + sessionID;
35
+ }
36
+
37
+ /** The session id behind a session/chat channel URI, or null. */
38
+ export function sessionIDOf(uri: string): string | null {
39
+ const kind = channelKind(uri);
40
+ if (kind === "session") return uri.slice(SESSION_PREFIX.length);
41
+ if (kind === "chat") return uri.slice(CHAT_PREFIX.length);
42
+ return null;
43
+ }
44
+
45
+ export interface SubscribeOutcome {
46
+ ok: boolean;
47
+ reason?: "unknown-uri" | "no-such-session";
48
+ }
49
+
50
+ /**
51
+ * Subscription bookkeeping keyed by transport socket id, plus the set of
52
+ * live session ids (Phase 1).
53
+ */
54
+ export class ChannelRegistry {
55
+ private readonly subs = new Map<number, Set<string>>();
56
+ private readonly sessions = new Set<string>();
57
+
58
+ /** Subscribe a socket to a channel; fails for unknown URIs or dead sessions. */
59
+ subscribe(socketId: number, uri: string): SubscribeOutcome {
60
+ const kind = channelKind(uri);
61
+ if (kind === "unknown") return { ok: false, reason: "unknown-uri" };
62
+ if (kind !== "root") {
63
+ const id = sessionIDOf(uri);
64
+ if (id === null || !this.sessions.has(id)) return { ok: false, reason: "no-such-session" };
65
+ }
66
+ let set = this.subs.get(socketId);
67
+ if (!set) {
68
+ set = new Set();
69
+ this.subs.set(socketId, set);
70
+ }
71
+ set.add(uri);
72
+ return { ok: true };
73
+ }
74
+
75
+ unsubscribe(socketId: number, uri: string): void {
76
+ this.subs.get(socketId)?.delete(uri);
77
+ }
78
+
79
+ /** URIs a socket is subscribed to (idempotent re-subscribe keeps one entry). */
80
+ subscriptionsOf(socketId: number): readonly string[] {
81
+ return [...(this.subs.get(socketId) ?? [])];
82
+ }
83
+
84
+ /** Socket ids currently subscribed to uri — broadcast targets. */
85
+ socketsSubscribedTo(uri: string): readonly number[] {
86
+ const out: number[] = [];
87
+ for (const [socketId, set] of this.subs) if (set.has(uri)) out.push(socketId);
88
+ return out;
89
+ }
90
+
91
+ /** Drop a socket's subscriptions (connection closed). */
92
+ removeSocket(socketId: number): void {
93
+ this.subs.delete(socketId);
94
+ }
95
+
96
+ // ── live sessions (Phase 1: session/chat channels) ────────────────────
97
+
98
+ addSession(sessionID: string): void {
99
+ this.sessions.add(sessionID);
100
+ }
101
+
102
+ removeSession(sessionID: string): void {
103
+ this.sessions.delete(sessionID);
104
+ }
105
+
106
+ hasSession(sessionID: string): boolean {
107
+ return this.sessions.has(sessionID);
108
+ }
109
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * AHP 1.0.0 handshake (plan §6.1 handshake.ts): the `initialize` command
3
+ * — semver capability negotiation via the official package's
4
+ * `negotiateProtocolVersion`.
5
+ *
6
+ * Version semantics (AHP versioning spec): the server picks the highest
7
+ * client-offered version inside its supported caret baselines and echoes
8
+ * that exact string back. The package we pin (1.0.0) supports the 1.0.0
9
+ * and 0.9.0 baselines, so a client offering any 1.x (or 0.9.x) version
10
+ * negotiates the 1.0 wire protocol; anything else gets -32005 with the
11
+ * `supportedVersions` data.
12
+ */
13
+ import {
14
+ negotiateProtocolVersion,
15
+ SUPPORTED_PROTOCOL_VERSIONS,
16
+ type Implementation,
17
+ type InitializeResult,
18
+ type Snapshot,
19
+ } from "@microsoft/agent-host-protocol";
20
+ import { ROOT_CHANNEL } from "./channels.js";
21
+ import { isRecord } from "./options.js";
22
+
23
+ export const ERROR_INVALID_PARAMS = -32602;
24
+ export const ERROR_UNSUPPORTED_PROTOCOL_VERSION = -32005;
25
+
26
+ export interface HandshakeError {
27
+ code: number;
28
+ message: string;
29
+ /** Required on -32005 (UnsupportedProtocolVersionErrorData). */
30
+ data?: { supportedVersions: string[] };
31
+ }
32
+
33
+ export interface InitializeRequest {
34
+ params: unknown;
35
+ serverInfo: Implementation;
36
+ /** Current global serverSeq (stamped onto the result). */
37
+ serverSeq: number;
38
+ /** The opencode instance's working directory, when known. */
39
+ defaultDirectory?: string;
40
+ /**
41
+ * Resolve a snapshot for an `initialSubscriptions` entry; null when the
42
+ * channel is not subscribable (it is simply omitted from the result).
43
+ */
44
+ snapshotFor: (uri: string) => Snapshot | null | Promise<Snapshot | null>;
45
+ }
46
+
47
+ export type InitializeOutcome =
48
+ | { ok: true; result: InitializeResult }
49
+ | { ok: false; error: HandshakeError };
50
+
51
+ const isNonEmptyString = (v: unknown): v is string => typeof v === "string" && v.length > 0;
52
+
53
+ export async function handleInitialize(req: InitializeRequest): Promise<InitializeOutcome> {
54
+ const params = req.params;
55
+ if (!isRecord(params)) {
56
+ return { ok: false, error: { code: ERROR_INVALID_PARAMS, message: "params must be an object" } };
57
+ }
58
+ if (params["channel"] !== ROOT_CHANNEL) {
59
+ return {
60
+ ok: false,
61
+ error: { code: ERROR_INVALID_PARAMS, message: `initialize must target ${ROOT_CHANNEL}` },
62
+ };
63
+ }
64
+ if (!isNonEmptyString(params["clientId"])) {
65
+ return {
66
+ ok: false,
67
+ error: { code: ERROR_INVALID_PARAMS, message: "clientId must be a non-empty string" },
68
+ };
69
+ }
70
+ const offered = params["protocolVersions"];
71
+ if (!Array.isArray(offered) || offered.length === 0 || !offered.every(isNonEmptyString)) {
72
+ return {
73
+ ok: false,
74
+ error: {
75
+ code: ERROR_INVALID_PARAMS,
76
+ message: "protocolVersions must be a non-empty array of SemVer strings",
77
+ },
78
+ };
79
+ }
80
+
81
+ let version: string | undefined;
82
+ try {
83
+ version = negotiateProtocolVersion(offered);
84
+ } catch (err) {
85
+ return {
86
+ ok: false,
87
+ error: {
88
+ code: ERROR_INVALID_PARAMS,
89
+ message: `invalid protocol version: ${err instanceof Error ? err.message : String(err)}`,
90
+ },
91
+ };
92
+ }
93
+ if (version === undefined) {
94
+ return {
95
+ ok: false,
96
+ error: {
97
+ code: ERROR_UNSUPPORTED_PROTOCOL_VERSION,
98
+ message: "unsupported protocol version",
99
+ data: { supportedVersions: [...SUPPORTED_PROTOCOL_VERSIONS] },
100
+ },
101
+ };
102
+ }
103
+
104
+ const initial = Array.isArray(params["initialSubscriptions"])
105
+ ? params["initialSubscriptions"]
106
+ : [];
107
+ const snapshots: Snapshot[] = [];
108
+ for (const uri of initial) {
109
+ if (!isNonEmptyString(uri)) continue;
110
+ const snap = await req.snapshotFor(uri);
111
+ if (snap) snapshots.push(snap);
112
+ }
113
+
114
+ return {
115
+ ok: true,
116
+ result: {
117
+ protocolVersion: version,
118
+ serverSeq: req.serverSeq,
119
+ serverInfo: req.serverInfo,
120
+ snapshots,
121
+ ...(req.defaultDirectory ? { defaultDirectory: req.defaultDirectory } : {}),
122
+ },
123
+ };
124
+ }