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/LICENSE +21 -0
- package/README.md +188 -2
- package/options.example.jsonc +44 -0
- package/package.json +50 -4
- package/src/bridge.ts +722 -0
- package/src/channels.ts +109 -0
- package/src/handshake.ts +124 -0
- package/src/host.ts +1795 -0
- package/src/index.ts +361 -0
- package/src/options.ts +229 -0
- package/src/seq.ts +87 -0
- package/src/state.ts +81 -0
- package/src/transport.ts +270 -0
package/src/state.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Channel state stores, all maintained by the official reducers from
|
|
3
|
+
* @microsoft/agent-host-protocol — the host never hand-rolls state
|
|
4
|
+
* transitions (plan §6.1 state.ts: "state computed by the official
|
|
5
|
+
* reducers").
|
|
6
|
+
*
|
|
7
|
+
* - root channel: `rootReducer` (Phase 0);
|
|
8
|
+
* - session channels: `sessionReducer` (Phase 1);
|
|
9
|
+
* - chat channels: `chatReducer` (Phase 1).
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
chatReducer,
|
|
13
|
+
rootReducer,
|
|
14
|
+
sessionReducer,
|
|
15
|
+
type ChatAction,
|
|
16
|
+
type ChatState,
|
|
17
|
+
type RootAction,
|
|
18
|
+
type RootState,
|
|
19
|
+
type SessionAction,
|
|
20
|
+
type SessionState,
|
|
21
|
+
} from "@microsoft/agent-host-protocol";
|
|
22
|
+
|
|
23
|
+
export interface RootStateStore {
|
|
24
|
+
/** Current root state (the `ahp-root://` snapshot payload). */
|
|
25
|
+
readonly state: RootState;
|
|
26
|
+
/** Apply a root action through the official reducer; returns the new state. */
|
|
27
|
+
apply(action: RootAction): RootState;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SessionStateStore {
|
|
31
|
+
/** Current session state (the `ahp-session:/…` snapshot payload). */
|
|
32
|
+
readonly state: SessionState;
|
|
33
|
+
/** Apply a session-channel action through the official reducer. */
|
|
34
|
+
apply(action: SessionAction): SessionState;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ChatStateStore {
|
|
38
|
+
/** Current chat state (the `ahp-chat:/…` snapshot payload). */
|
|
39
|
+
readonly state: ChatState;
|
|
40
|
+
/** Apply a chat-channel action through the official reducer. */
|
|
41
|
+
apply(action: ChatAction): ChatState;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createRootStateStore(initial: RootState): RootStateStore {
|
|
45
|
+
let state: RootState = initial;
|
|
46
|
+
return {
|
|
47
|
+
get state(): RootState {
|
|
48
|
+
return state;
|
|
49
|
+
},
|
|
50
|
+
apply(action: RootAction): RootState {
|
|
51
|
+
state = rootReducer(state, action);
|
|
52
|
+
return state;
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function createSessionStateStore(initial: SessionState): SessionStateStore {
|
|
58
|
+
let state: SessionState = initial;
|
|
59
|
+
return {
|
|
60
|
+
get state(): SessionState {
|
|
61
|
+
return state;
|
|
62
|
+
},
|
|
63
|
+
apply(action: SessionAction): SessionState {
|
|
64
|
+
state = sessionReducer(state, action);
|
|
65
|
+
return state;
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function createChatStateStore(initial: ChatState): ChatStateStore {
|
|
71
|
+
let state: ChatState = initial;
|
|
72
|
+
return {
|
|
73
|
+
get state(): ChatState {
|
|
74
|
+
return state;
|
|
75
|
+
},
|
|
76
|
+
apply(action: ChatAction): ChatState {
|
|
77
|
+
state = chatReducer(state, action);
|
|
78
|
+
return state;
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
package/src/transport.ts
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AHP transport (plan §6.1 transport.ts).
|
|
3
|
+
*
|
|
4
|
+
* Two layers:
|
|
5
|
+
*
|
|
6
|
+
* 1. **Pure policy functions** — token extraction/comparison, Origin
|
|
7
|
+
* policy, path routing, loopback check. Unit-tested without a runtime.
|
|
8
|
+
* 2. **A thin listener** behind the `Listener` interface. The reference
|
|
9
|
+
* implementation uses `Bun.serve` (opencode v2 is Bun-based, so the
|
|
10
|
+
* in-process plugin runtime has it — verified by the Phase 0 spike,
|
|
11
|
+
* R6). If the plugin context ever forbids raw listeners, a `ws`-
|
|
12
|
+
* package implementation drops in here with no changes to the
|
|
13
|
+
* protocol layer.
|
|
14
|
+
*
|
|
15
|
+
* Authentication happens at the WebSocket **upgrade** (AHP transport
|
|
16
|
+
* spec), not after it: a missing/invalid token or a disallowed Origin
|
|
17
|
+
* never gets a socket. `?token=` query param first, then
|
|
18
|
+
* `Authorization: Bearer <token>`.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
// ── pure policy ──────────────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
/** True for addresses that only reach this machine (127.0.0.0/8, ::1, localhost). */
|
|
24
|
+
export function isLoopback(host: string): boolean {
|
|
25
|
+
const h = host.toLowerCase().replace(/^\[|\]$/g, "");
|
|
26
|
+
if (h === "localhost" || h === "::1" || h === "0:0:0:0:0:0:0:1") return true;
|
|
27
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
|
|
28
|
+
if (m) return m[1] === "127";
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The one header the token policy reads. A plain object so it is
|
|
34
|
+
* unit-testable; HTTP header names are case-insensitive, so both casings
|
|
35
|
+
* of `authorization` are accepted (the transport layer passes Bun's
|
|
36
|
+
* `Headers.get("authorization")`, which already lowercases).
|
|
37
|
+
*/
|
|
38
|
+
export interface AuthorizationHeaders {
|
|
39
|
+
authorization?: string | null;
|
|
40
|
+
Authorization?: string | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Extract the presented token: `?token=` query param first, then
|
|
45
|
+
* `Authorization: Bearer <token>`. Null when neither carries a value.
|
|
46
|
+
*/
|
|
47
|
+
export function extractToken(url: URL, headers: AuthorizationHeaders | null | undefined): string | null {
|
|
48
|
+
const q = url.searchParams.get("token");
|
|
49
|
+
if (q) return q;
|
|
50
|
+
const auth = headers?.authorization ?? headers?.Authorization;
|
|
51
|
+
if (typeof auth === "string") {
|
|
52
|
+
const m = /^Bearer\s+(\S+)$/i.exec(auth.trim());
|
|
53
|
+
if (m?.[1]) return m[1];
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Constant-time token comparison (no early exit on the first differing
|
|
60
|
+
* byte). A null or empty presentation is never valid.
|
|
61
|
+
*/
|
|
62
|
+
export function tokenValid(expected: string, presented: string | null): boolean {
|
|
63
|
+
if (expected.length === 0 || presented === null) return false;
|
|
64
|
+
const a = new TextEncoder().encode(expected);
|
|
65
|
+
const b = new TextEncoder().encode(presented);
|
|
66
|
+
let diff = a.length === b.length ? 0 : 1;
|
|
67
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
68
|
+
diff |= (a[i] ?? 0) ^ (b[i] ?? 0);
|
|
69
|
+
}
|
|
70
|
+
return diff === 0;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Origin policy (plan R5). The token is the only credential; this only
|
|
75
|
+
* filters *which* browser origins may attempt a connection. A null Origin
|
|
76
|
+
* (non-browser clients: VS Code's own connection, CLI clients) always
|
|
77
|
+
* passes — browser-origin filtering is the real attack surface.
|
|
78
|
+
*/
|
|
79
|
+
export function originAllowed(
|
|
80
|
+
allowed: string[] | "*",
|
|
81
|
+
origin: string | null | undefined,
|
|
82
|
+
): boolean {
|
|
83
|
+
if (origin === null || origin === undefined) return true;
|
|
84
|
+
if (allowed === "*") return true;
|
|
85
|
+
return allowed.includes(origin);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type Route = "ahp" | "health" | "other";
|
|
89
|
+
|
|
90
|
+
/** Route an HTTP request against the AHP path and the health path. */
|
|
91
|
+
export function routePath(url: URL, paths: { ahp: string; health: string }): Route {
|
|
92
|
+
if (url.pathname === paths.health) return "health";
|
|
93
|
+
if (url.pathname === paths.ahp) return "ahp";
|
|
94
|
+
return "other";
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ── listener ─────────────────────────────────────────────────────────────
|
|
98
|
+
|
|
99
|
+
export interface ListenerOptions {
|
|
100
|
+
host: string;
|
|
101
|
+
port: number;
|
|
102
|
+
path: string;
|
|
103
|
+
healthPath: string;
|
|
104
|
+
/** When null, a non-loopback bind refuses to start (R4). */
|
|
105
|
+
token: string | null;
|
|
106
|
+
allowedOrigins: string[] | "*";
|
|
107
|
+
tls?: { keyPath: string; certPath: string } | null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Transport-local connection identity. */
|
|
111
|
+
export interface ConnectionInfo {
|
|
112
|
+
readonly id: number;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface TransportCallbacks {
|
|
116
|
+
onOpen(info: ConnectionInfo): void;
|
|
117
|
+
/** Text frames only; binary frames are decoded as UTF-8. */
|
|
118
|
+
onMessage(info: ConnectionInfo, text: string): void;
|
|
119
|
+
onClose(info: ConnectionInfo): void;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface Listener {
|
|
123
|
+
/** Actual port (differs from the option only when port 0 was given). */
|
|
124
|
+
readonly port: number;
|
|
125
|
+
/** Send a frame to a connection. No-op once the socket is closed. */
|
|
126
|
+
sendTo(info: ConnectionInfo, data: string): void;
|
|
127
|
+
/** Close one connection (e.g. a superseded duplicate clientId). */
|
|
128
|
+
closeConnection(info: ConnectionInfo, code?: number, reason?: string): void;
|
|
129
|
+
/** Stop the listener and close every open connection. */
|
|
130
|
+
stop(): void;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ── minimal Bun surface (accessed via globalThis so Node typecheck and
|
|
134
|
+
// vitest stay clean — no @types/bun dependency) ───────────────────────
|
|
135
|
+
|
|
136
|
+
interface BunWebSocket {
|
|
137
|
+
send(data: string): void;
|
|
138
|
+
close(code?: number, reason?: string): void;
|
|
139
|
+
readonly readyState: number;
|
|
140
|
+
/** Data passed to server.upgrade(). */
|
|
141
|
+
readonly data: unknown;
|
|
142
|
+
}
|
|
143
|
+
interface BunRequest {
|
|
144
|
+
url: string;
|
|
145
|
+
headers: { get(name: string): string | null };
|
|
146
|
+
}
|
|
147
|
+
interface BunUpgradeResult {
|
|
148
|
+
success: boolean;
|
|
149
|
+
response?: Response;
|
|
150
|
+
}
|
|
151
|
+
interface BunServer {
|
|
152
|
+
port: number;
|
|
153
|
+
stop(): void;
|
|
154
|
+
upgrade(req: BunRequest, options?: { data?: unknown }): BunUpgradeResult;
|
|
155
|
+
}
|
|
156
|
+
interface BunServeOptions {
|
|
157
|
+
hostname: string;
|
|
158
|
+
port: number;
|
|
159
|
+
tls?: { key: string; cert: string };
|
|
160
|
+
fetch(req: BunRequest, server: BunServer): Response | Promise<Response> | undefined;
|
|
161
|
+
websocket: {
|
|
162
|
+
open(ws: BunWebSocket): void;
|
|
163
|
+
/** Text frames arrive as strings, binary frames as ArrayBuffers. */
|
|
164
|
+
message(ws: BunWebSocket, message: string | ArrayBuffer): void;
|
|
165
|
+
close(ws: BunWebSocket): void;
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
interface BunRuntime {
|
|
169
|
+
serve(options: BunServeOptions): BunServer;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const bunOf = (): BunRuntime | undefined => (globalThis as { Bun?: BunRuntime }).Bun;
|
|
173
|
+
|
|
174
|
+
const textDecoder = new TextDecoder();
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Start the AHP listener. Throws before binding when a non-loopback
|
|
178
|
+
* address is given without a token (R4) or when the runtime lacks
|
|
179
|
+
* `Bun.serve` (R6 — the fallback implementation would be added here).
|
|
180
|
+
*/
|
|
181
|
+
export function createListener(opts: ListenerOptions, callbacks: TransportCallbacks): Listener {
|
|
182
|
+
if (!isLoopback(opts.host) && !opts.token) {
|
|
183
|
+
throw new Error(
|
|
184
|
+
`refusing to bind ${opts.host} (non-loopback) without a token (R4); set options.token`,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
const bun = bunOf();
|
|
188
|
+
if (!bun) {
|
|
189
|
+
throw new Error(
|
|
190
|
+
"Bun.serve is not available in this runtime (R6); expected inside the " +
|
|
191
|
+
"Bun-based opencode v2 server — a `ws`-package fallback would go here",
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const openSockets = new Map<number, BunWebSocket>();
|
|
196
|
+
let nextId = 1;
|
|
197
|
+
|
|
198
|
+
const server = bun.serve({
|
|
199
|
+
hostname: opts.host,
|
|
200
|
+
port: opts.port,
|
|
201
|
+
...(opts.tls ? { tls: { key: opts.tls.keyPath, cert: opts.tls.certPath } } : {}),
|
|
202
|
+
fetch(req, srv) {
|
|
203
|
+
const url = new URL(req.url);
|
|
204
|
+
switch (routePath(url, { ahp: opts.path, health: opts.healthPath })) {
|
|
205
|
+
case "health":
|
|
206
|
+
return new Response("ok\n", {
|
|
207
|
+
status: 200,
|
|
208
|
+
headers: { "content-type": "text/plain" },
|
|
209
|
+
});
|
|
210
|
+
case "ahp": {
|
|
211
|
+
const expected = opts.token;
|
|
212
|
+
if (
|
|
213
|
+
expected !== null &&
|
|
214
|
+
!tokenValid(expected, extractToken(url, { authorization: req.headers.get("authorization") }))
|
|
215
|
+
) {
|
|
216
|
+
return new Response("unauthorized", { status: 401 });
|
|
217
|
+
}
|
|
218
|
+
if (!originAllowed(opts.allowedOrigins, req.headers.get("origin"))) {
|
|
219
|
+
return new Response("origin not allowed", { status: 403 });
|
|
220
|
+
}
|
|
221
|
+
const info: ConnectionInfo = { id: nextId++ };
|
|
222
|
+
const upgraded = srv.upgrade(req, { data: info });
|
|
223
|
+
if (!upgraded.success) {
|
|
224
|
+
return upgraded.response ?? new Response("upgrade failed", { status: 500 });
|
|
225
|
+
}
|
|
226
|
+
// Bun handles the 101 response itself.
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
default:
|
|
230
|
+
return new Response("not found", { status: 404 });
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
websocket: {
|
|
234
|
+
open(ws) {
|
|
235
|
+
const info = ws.data as ConnectionInfo;
|
|
236
|
+
openSockets.set(info.id, ws);
|
|
237
|
+
callbacks.onOpen(info);
|
|
238
|
+
},
|
|
239
|
+
message(ws, message) {
|
|
240
|
+
const info = ws.data as ConnectionInfo;
|
|
241
|
+
const text = typeof message === "string" ? message : textDecoder.decode(message);
|
|
242
|
+
callbacks.onMessage(info, text);
|
|
243
|
+
},
|
|
244
|
+
close(ws) {
|
|
245
|
+
const info = ws.data as ConnectionInfo;
|
|
246
|
+
openSockets.delete(info.id);
|
|
247
|
+
callbacks.onClose(info);
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
return {
|
|
253
|
+
get port() {
|
|
254
|
+
return server.port;
|
|
255
|
+
},
|
|
256
|
+
sendTo(info, data) {
|
|
257
|
+
const ws = openSockets.get(info.id);
|
|
258
|
+
if (!ws || ws.readyState !== 1) return; // 1 = OPEN
|
|
259
|
+
ws.send(data);
|
|
260
|
+
},
|
|
261
|
+
closeConnection(info, code, reason) {
|
|
262
|
+
const ws = openSockets.get(info.id);
|
|
263
|
+
if (ws && ws.readyState === 1) ws.close(code, reason);
|
|
264
|
+
},
|
|
265
|
+
stop() {
|
|
266
|
+
server.stop();
|
|
267
|
+
openSockets.clear();
|
|
268
|
+
},
|
|
269
|
+
};
|
|
270
|
+
}
|