okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221host: Harness runtime launcher, Gateway client and Strata profile generatorbf63faab2

main
6.5 KiB147 linesraw
1/**
2 * A client for the Harness Gateway (the `dsh web` HTTP + WebSocket surface).
3 *
4 * Two carriers, both authenticated by the cookie the launch URL's token buys:
5 *   - HTTP unary RPC:   POST /api/<method>  with the gateway's envelope
6 *   - WebSocket mux:    /api/remote.mux     carrying many independent logical streams
7 *
8 * The streams used here are `$events` (Host notifications and the approval waterfall) and
9 * `session/follow` (a session's durable event log plus live assistant frames).
10 *
11 * Node 24's global WebSocket accepts a `headers` option, which is how the cookie reaches the upgrade.
12 * No dependency is added to the host.
13 */
14
15export class GatewayError extends Error {
16  constructor(message, { code = 'gateway/error', details } = {}) {
17    super(message);
18    this.name = 'GatewayError';
19    this.code = code;
20    this.details = details;
21  }
22}
23
24export class GatewayClient {
25  #base; #token; #cookie = null; #rpcId = 0; #ws = null; #wsReady = null; #streams = new Map(); #nextStream = 0;
26  #closed = false; #reconnectTimer = null; #onState;
27
28  /**
29   * @param {{baseUrl: string, token: string, onState?: (state: 'open'|'closed') => void}} options
30   */
31  constructor({ baseUrl, token, onState = () => {} }) {
32    this.#base = baseUrl.replace(/\/+$/, '');
33    this.#token = token;
34    this.#onState = onState;
35  }
36
37  /** Exchange the launch token for the API cookie. */
38  async connect() {
39    const res = await fetch(`${this.#base}/?token=${encodeURIComponent(this.#token)}`, { redirect: 'manual' });
40    const cookie = (res.headers.get('set-cookie') ?? '').split(';')[0];
41    if (!cookie.startsWith('dsh-auth-')) throw new GatewayError(`the agent refused the launch token (HTTP ${res.status})`, { code: 'gateway/auth' });
42    this.#cookie = cookie;
43  }
44
45  /** One unary call. Resolves with the value, rejects with a GatewayError carrying the gateway's code. */
46  async rpc(method, args = {}, { signal } = {}) {
47    if (!this.#cookie) throw new GatewayError('not connected', { code: 'gateway/not-connected' });
48    const rpcId = `h${++this.#rpcId}`;
49    const res = await fetch(`${this.#base}/api/${method}`, {
50      method: 'POST',
51      headers: { 'content-type': 'application/json', cookie: this.#cookie },
52      body: JSON.stringify({ type: 'client-request', rpcId, method, payload: { args } }),
53      signal,
54    });
55    let body;
56    try { body = await res.json(); } catch { throw new GatewayError(`${method}: the agent returned a non-JSON answer (HTTP ${res.status})`, { code: 'gateway/bad-response' }); }
57    const result = body?.result;
58    if (!result?.ok) {
59      const e = result?.error ?? {};
60      throw new GatewayError(`${method}: ${e.message ?? `HTTP ${res.status}`}`, { code: e.code ?? 'gateway/error', details: e.details });
61    }
62    return result.value;
63  }
64
65  /**
66   * Open a logical stream on the mux. Handlers: `onItem(value)`, `onEnd()`, `onError(error)`.
67   * The stream is re-opened after a socket reconnect and `onItem` receives it from the start again
68   * (a `session/follow` opens with a fresh snapshot, so callers de-duplicate by sequence number).
69   */
70  openStream(endpoint, args, handlers) {
71    const streamId = `s${++this.#nextStream}`;
72    const entry = { streamId, endpoint, args, ...handlers, closed: false };
73    this.#streams.set(streamId, entry);
74    void this.#ensureSocket().then(() => this.#sendOpen(entry), () => {});
75    return {
76      streamId,
77      close: () => {
78        entry.closed = true;
79        this.#streams.delete(streamId);
80        if (this.#ws?.readyState === 1) {
81          try { this.#ws.send(JSON.stringify({ type: 'cancel', streamId })); } catch { /* socket going away */ }
82        }
83      },
84    };
85  }
86
87  /** Answer one forwarded approval waterfall. `outcome` is `allowed-once`, `rejected`, or `next`. */
88  async answerEvent({ clientId, eventId, outcome }) {
89    const wire = outcome === 'next' ? { kind: 'next' } : { kind: 'result', value: outcome };
90    return this.rpc('$events/result', { clientId, eventId, outcome: wire });
91  }
92
93  close() {
94    this.#closed = true;
95    clearTimeout(this.#reconnectTimer);
96    for (const s of this.#streams.values()) s.closed = true;
97    this.#streams.clear();
98    try { this.#ws?.close(); } catch { /* already closed */ }
99    this.#ws = null;
100  }
101
102  // -- socket ---------------------------------------------------------------------------------------
103
104  #ensureSocket() {
105    if (this.#closed) return Promise.reject(new GatewayError('closed', { code: 'gateway/closed' }));
106    if (this.#ws && this.#ws.readyState === 1) return Promise.resolve();
107    if (this.#wsReady) return this.#wsReady;
108    this.#wsReady = new Promise((resolve, reject) => {
109      const url = `${this.#base.replace(/^http/, 'ws')}/api/remote.mux`;
110      const ws = new WebSocket(url, { headers: { cookie: this.#cookie } });
111      this.#ws = ws;
112      ws.onopen = () => { this.#wsReady = null; this.#onState('open'); resolve(); };
113      ws.onmessage = e => this.#onMessage(String(e.data));
114      ws.onerror = () => { /* the close handler reports it */ };
115      ws.onclose = () => {
116        const wasReady = this.#wsReady;
117        this.#wsReady = null;
118        if (this.#ws === ws) this.#ws = null;
119        this.#onState('closed');
120        if (wasReady) reject(new GatewayError('the agent socket closed before it opened', { code: 'gateway/socket' }));
121        if (this.#closed) return;
122        // Streams are re-opened by a new socket; a dropped socket must not strand a follower.
123        clearTimeout(this.#reconnectTimer);
124        if (this.#streams.size) this.#reconnectTimer = setTimeout(() => {
125          this.#ensureSocket().then(() => { for (const s of this.#streams.values()) this.#sendOpen(s); }).catch(() => {
126            for (const s of [...this.#streams.values()]) s.onError?.(new GatewayError('the agent socket could not be re-opened', { code: 'gateway/socket' }));
127          });
128        }, 500);
129      };
130    });
131    return this.#wsReady;
132  }
133
134  #sendOpen(entry) {
135    if (entry.closed || this.#ws?.readyState !== 1) return;
136    this.#ws.send(JSON.stringify({ type: 'open', streamId: entry.streamId, endpoint: entry.endpoint, payload: { args: entry.args } }));
137  }
138
139  #onMessage(text) {
140    let m; try { m = JSON.parse(text); } catch { return; }
141    const s = this.#streams.get(m.streamId);
142    if (!s) return;
143    if (m.type === 'item') s.onItem?.(m.value);
144    else if (m.type === 'end') { this.#streams.delete(s.streamId); s.onEnd?.(); }
145    else if (m.type === 'error') s.onError?.(new GatewayError(m.error?.message ?? 'stream failed', { code: m.error?.code, details: m.error?.details }));
146  }
147}