@byok-sdk/server 0.11.0 → 0.13.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/dist/hub.d.ts DELETED
@@ -1,931 +0,0 @@
1
- import type { WebSocket } from 'ws';
2
- import { type Envelope, type AgentMessagePublishPayload, type AgentMessageServerContext, type AgentHomeProjectionCompletionRequest, type AgentHomeProjectionReadback, type RuntimeId, type RuntimeInfo, type TaskState, type ToolsetId } from '@byok-sdk/protocol';
3
- import type { DeviceRegistry } from './auth';
4
- import { RateLimiter } from './rate-limiter';
5
- import type { TaskStore } from './task-store';
6
- import type { ByokServerEvent, AgentContentReadRequest, AgentHomeProjectionRequest, AgentEgressReceipt, DispatchInput, FreshAgentEgressDispatchInput, HubStats, MachineInfo, TaskHandle, TaskSnapshot } from './types';
7
- /**
8
- * The connection hub: tracks each device's live transport (WS or long-poll —
9
- * never both at once, see {@link takeOverAsLongPoll}), routes `dispatch()`'d
10
- * tasks to a device, and processes inbound task.* envelopes from daemons.
11
- *
12
- * Routing (M1): every `task.*` envelope carries a *required* envelope
13
- * `task_id` — the sole routing key, both directions. No payload duplicates
14
- * it, and none of the handlers below need to guard against a missing one
15
- * (the wire schema already rejects such an envelope before it reaches here).
16
- *
17
- * Inbound gate ({@link handleInbound}): the single choke point both
18
- * transports (`ws-server.ts`'s WS message handler, `http.ts`'s
19
- * `POST /byok/messages`) call instead of reaching into per-type handlers
20
- * directly. Runs, in order: (1) type-allow — only `DAEMON_TO_SERVER_TYPES`
21
- * plus the authenticated long-poll `conn.hello` snapshot may pass, a server
22
- * -> daemon type arriving inbound is rejected (P2); (2)
23
- * ownership (N2) — an envelope for a task already owned by a *different*
24
- * device is dropped and logged, never force-failed (force-failing on an
25
- * authz mismatch would let an attacker who merely guesses a `taskId` kill
26
- * the real owner's task); (3) dedup (N3) — an envelope `id` already seen
27
- * from this device is a no-op, making the at-least-once wire (§9)
28
- * effectively at-most-once server-side; (4) dispatch to the per-type
29
- * handler. Because ownership is enforced once, centrally, here, the
30
- * handlers below no longer carry their own device-mismatch checks.
31
- *
32
- * Outbound delivery (M1, §1.2/§9): every server -> daemon envelope
33
- * (`conn.ack`, either task offer, `task.approve/reject/cancel/steer`) gets a fresh
34
- * per-device monotonic `seq` and is retained in a capped ring buffer
35
- * ({@link OUTBOX_RING_CAPACITY} entries) so it can be redelivered — in `seq`
36
- * order, skipping anything whose task has since reached a terminal state —
37
- * on reconnect (`redeliverAfterReconnect`) or long-poll
38
- * (`pollEvents`/`collectRelevant`). `conn.ack` has no task association, so
39
- * it's retained (for seq-counting purposes only) but never redelivered.
40
- * Exception (N1/F4): `task.cancel`/`task.reject` are exempt from the
41
- * terminal-task skip (`OutboxEntry.redeliverThroughTerminal`) because both
42
- * move their own task to a terminal state before being queued — without the
43
- * exemption they could never qualify for redelivery even when the original
44
- * send never reached the daemon.
45
- *
46
- * State-machine (M1): `task.claim` only claims (`Offered -> Claimed`); it no
47
- * longer implies `Running`. The daemon reports `Claimed -> Running`
48
- * explicitly via `task.started` once its runtime session actually starts
49
- * (§3.1). `task.decline` reports a pre-claim fail-closed rejection
50
- * (`Offered -> Failed`, §3.2). `task.cancelled` is dual-purpose: an
51
- * idempotent ack when the server already cancelled the task itself, or the
52
- * authoritative trigger when the daemon observed the cancellation first
53
- * (§3.3). Per §9, `task.complete`/`task.fail`/`task.cancelled` arriving for
54
- * an already-terminal task are silently dropped as stale/duplicate — not a
55
- * warning; this is what naturally resolves the M0 gatekeeper's cancel-race
56
- * `console.warn` finding (a late `task.fail`/`task.cancelled` racing a
57
- * server-initiated cancel is exactly this case).
58
- *
59
- * Task lease (M2): a periodic sweep (started in the constructor) reaps a
60
- * `Claimed`/`Running`/`AwaitApproval` task to
61
- * `Failed(retryable: true, reason: 'lease-expired')` once its owning device
62
- * has been dark (disconnected, or long-poll-silent) AND the task itself has
63
- * had no inbound activity for `taskLeaseMs` — see the "task-lease reaper"
64
- * section further down for the full design, including why this does not
65
- * reintroduce the disconnect-alone-fails-the-task bug M1 removed above.
66
- */
67
- /**
68
- * M4 Phase 3: thrown by {@link ConnectionHub.approveTask}/{@link
69
- * ConnectionHub.rejectTask} for a `taskId` this hub has no record of at all
70
- * — mirrors `task-store.ts`'s `IllegalTaskTransitionError` (typed error
71
- * class + `instanceof` dispatch is this codebase's own established idiom for
72
- * mapping a domain error to the right status code). Distinguished from
73
- * {@link TaskNotAwaitingApprovalError} so a caller CAN tell the two failure
74
- * modes apart (e.g. 404 vs. 409) instead of only ever seeing a single
75
- * generic `Error`. There is no bearer-authed HTTP route for this on
76
- * `http.ts`'s own app (see that file's own closing comment for why) — the
77
- * supported entry point is calling `approveTask`/`rejectTask` directly, or
78
- * via `TaskHandle.approve()`/`reject()` (thin wrappers over the same two
79
- * methods); an embedder builds its own operator-facing surface on top of
80
- * that, exactly like `examples/basic/server.ts`'s own
81
- * `/api/tasks/:taskId/approve`/`reject` routes do.
82
- */
83
- export declare class UnknownTaskError extends Error {
84
- readonly taskId: string;
85
- constructor(taskId: string);
86
- }
87
- /**
88
- * Thrown by {@link ConnectionHub.approveTask}/{@link ConnectionHub.rejectTask}
89
- * when the task exists but isn't currently `AwaitApproval` — see {@link
90
- * UnknownTaskError}'s own doc comment for why this is a distinct class.
91
- * `verb` keeps the exact pre-existing message wording per call site
92
- * ("cannot approve ..." vs. "cannot reject ...") byte-for-byte unchanged —
93
- * this message is user-visible today (e.g. `examples/basic`'s own
94
- * `/api/tasks/:taskId/approve` surfaces `err.message` straight to the
95
- * caller), so only the error's TYPE changes here, not its text.
96
- */
97
- export declare class TaskNotAwaitingApprovalError extends Error {
98
- readonly taskId: string;
99
- readonly state: TaskState;
100
- constructor(taskId: string, state: TaskState, verb: 'approve' | 'reject');
101
- }
102
- /**
103
- * M5 (approval targeting): thrown by {@link ConnectionHub.approveTask}/
104
- * {@link ConnectionHub.rejectTask} when an operator-supplied
105
- * `opts.approvalId` is provided but does NOT match this hub's own
106
- * last-recorded {@link TaskSnapshot.pendingApprovalId} for `taskId` — i.e.
107
- * the caller is targeting a SPECIFIC approval that this server's record
108
- * shows has already been superseded by a newer one (see `onAwaitApproval`'s
109
- * own doc comment for how that happens). Distinct from
110
- * {@link TaskNotAwaitingApprovalError} (the task isn't `AwaitApproval` at
111
- * all right now — checked FIRST, so it still wins when both would apply):
112
- * this error means the task genuinely IS awaiting approval, just not the one
113
- * the caller thinks it is. Thrown before any state change and before any
114
- * wire message is sent — a stale-id call has zero side effects, same as any
115
- * other validation failure in this file.
116
- */
117
- export declare class StaleApprovalError extends Error {
118
- readonly taskId: string;
119
- readonly requestedApprovalId: string;
120
- readonly currentApprovalId: string | undefined;
121
- constructor(taskId: string, requestedApprovalId: string, currentApprovalId: string | undefined);
122
- }
123
- /**
124
- * S0 (GAP-002): why {@link ConnectionHub.steerTask} refused. Stable strings —
125
- * a caller (an embedder's operator UI, an HTTP surface mapping this to a
126
- * status code) switches on these rather than matching error text.
127
- *
128
- * - `task_terminal` — the task already reached `Complete`/`Failed`/
129
- * `Cancelled`. Checked FIRST, so a terminal task that is also (obviously)
130
- * not `Running` reports the more specific truth, and a steer racing a
131
- * terminal transition always resolves terminal-first.
132
- * - `task_not_running` — the task exists and is live, but is `Offered`/
133
- * `Claimed`/`AwaitApproval`; there is no running turn to steer yet.
134
- * - `steer_unsupported_runtime` — the runtime that CLAIMED this task cannot
135
- * be steered, per the claim-time capability snapshot
136
- * (`TaskSnapshot.claimedRuntimeCapabilities`, sourced from the claiming
137
- * adapter's own `task.claim.capabilities`). Fail-closed: a MISSING snapshot
138
- * rejects under this same code, because "unknown" is not "supported" (see
139
- * {@link SteerRejectedError}'s own doc comment).
140
- */
141
- export type SteerRejectionCode = 'steer_unsupported_runtime' | 'task_not_running' | 'task_terminal';
142
- /**
143
- * S0 (GAP-002): thrown by {@link ConnectionHub.steerTask} instead of the
144
- * pre-S0 generic `Error`, so a caller can tell WHY a steer was refused
145
- * without matching on message text — same typed-error idiom as
146
- * {@link UnknownTaskError}/{@link TaskNotAwaitingApprovalError}/
147
- * {@link StaleApprovalError} above.
148
- *
149
- * The gap this closes: pre-S0 `steerTask` sent `task.steer` to ANY `Running`
150
- * task, but only pi's adapter implements steering — Claude's and Codex's
151
- * throw on receipt (`claude-adapter.ts`, `codex-adapter.ts`), which stalls
152
- * the client's redelivery cursor at that seq and loops forever. So the
153
- * decision has to be made server-side, from per-runtime truth, BEFORE an
154
- * envelope exists.
155
- *
156
- * Fail-closed on unknown, deliberately: `steer_unsupported_runtime` covers
157
- * both "the claiming adapter reported `steer: false`" and "this server has no
158
- * capability snapshot for this task at all" (a pre-D-4 daemon whose claim
159
- * carried no `capabilities`, a task record predating S0). Refusing an unknown
160
- * is a recoverable operator-visible error; guessing "supported" reintroduces
161
- * the exact permanent cursor stall this gate exists to prevent.
162
- *
163
- * Thrown before any state change and before any wire message is built — a
164
- * rejected steer has zero side effects, same as every other validation
165
- * failure in this file.
166
- *
167
- * SINGLE SOURCE, deliberately: the gate reads the claim payload and NOTHING
168
- * from the connection layer — not {@link getDeviceCapabilities} (the
169
- * CONNECTION-level `conn.hello` flag list) and not `ConnectionState.runtimes`.
170
- * Two reasons, either sufficient. First, scope: connection-level data is
171
- * discovery describing a daemon BUILD, not the per-runtime, per-task,
172
- * claim-time truth this gate needs — conflating the two is the original bug.
173
- * Second, lifecycle: the authenticated `conn.hello` snapshot on either
174
- * transport describes the device build, while the claim establishes the
175
- * exact task↔runtime binding. Only the latter shares a lifecycle with the
176
- * thing this gate judges. Adding a connection-level fallback here would
177
- * restore the scope defect and is what this design exists to forbid.
178
- */
179
- export declare class SteerRejectedError extends Error {
180
- readonly taskId: string;
181
- readonly code: SteerRejectionCode;
182
- /** The task's state at the moment the steer was refused. */
183
- readonly state: TaskState;
184
- /** `TaskSnapshot.claimedRuntime` — `undefined` when nothing was ever recorded (which is itself a reason `steer_unsupported_runtime` can fire). */
185
- readonly runtime: RuntimeId | undefined;
186
- constructor(taskId: string, code: SteerRejectionCode,
187
- /** The task's state at the moment the steer was refused. */
188
- state: TaskState,
189
- /** `TaskSnapshot.claimedRuntime` — `undefined` when nothing was ever recorded (which is itself a reason `steer_unsupported_runtime` can fire). */
190
- runtime: RuntimeId | undefined);
191
- }
192
- export type AgentHomeProjectionCompletionErrorCode = 'not_found' | 'conflict' | 'invalid';
193
- export declare class AgentHomeProjectionCompletionError extends Error {
194
- readonly code: AgentHomeProjectionCompletionErrorCode;
195
- constructor(code: AgentHomeProjectionCompletionErrorCode, message: string);
196
- }
197
- export declare class ConnectionHub {
198
- private readonly taskStore;
199
- private readonly devices;
200
- /** See {@link CreateByokServerOptions.taskLeaseMs} — already defaulted by `createByokServer` before reaching here. */
201
- private readonly taskLeaseMs;
202
- /**
203
- * M4 Phase 4 (part A): per-device inbound-envelope token bucket — see
204
- * {@link CreateByokServerOptions.rateLimit} (already defaulted by
205
- * `createByokServer` before reaching here) and {@link handleInbound}'s
206
- * own doc comment for where it's enforced. Defaults to a fresh
207
- * default-configured `RateLimiter` so every existing direct-construction
208
- * call site (this hub is constructed directly by several tests) keeps
209
- * working unchanged.
210
- */
211
- private readonly rateLimiter;
212
- private readonly agentMessage?;
213
- private readonly connections;
214
- private readonly outboxes;
215
- /** Idempotency window per device (N3) — recent inbound envelope ids, capped at {@link DEDUP_RING_CAPACITY}. */
216
- private readonly dedupRings;
217
- private readonly longPollWaiters;
218
- private readonly runtimes;
219
- private readonly serverEvents;
220
- /** First-write-wins reliable facts; the reference composition's bounded in-memory readback. */
221
- private readonly agentEgressReceipts;
222
- private readonly agentMessageRequirements;
223
- private readonly agentMessageReceipts;
224
- private readonly agentMessageTaskPayloads;
225
- /** Accepted requests are the authority that later receipts/transfers must echo exactly. */
226
- private readonly agentContentReadRequests;
227
- /** Content-free explicit-read audit facts keyed by exact authenticated device/request identity. */
228
- private readonly agentContentReceipts;
229
- /** Immutable requested projection facts, keyed by authenticated device/request. */
230
- private readonly agentHomeProjectionRequests;
231
- /** First terminal completion for each exact projection request. */
232
- private readonly agentHomeProjectionCompletions;
233
- /**
234
- * Per-task last-inbound-activity timestamp (epoch ms) — the task-lease
235
- * reaper's condition (c), see the "task-lease reaper" section below. Reset
236
- * on every accepted inbound `task.*` envelope ({@link recordTaskActivity},
237
- * called from {@link dispatchToHandler}); cleared once the task reaches a
238
- * terminal state ({@link onStateChange}), so this map only ever holds
239
- * entries for currently non-terminal claimed tasks.
240
- */
241
- private readonly taskActivity;
242
- /** The task-lease reaper's own periodic sweep timer — see the constructor and `sweepLeases` below. */
243
- private readonly leaseReaperTimer;
244
- /** {@link ConnectionHub.stats}'s `uptimeMs` origin — this hub's own construction instant. */
245
- private readonly startedAtMs;
246
- /** {@link ConnectionHub.stats}'s `envelopesIn` — every {@link handleInbound} call, every outcome. */
247
- private envelopesInCount;
248
- /** {@link ConnectionHub.stats}'s `envelopesOut` — every envelope built via the single outbound choke point, {@link sendToDevice}. */
249
- private envelopesOutCount;
250
- /** {@link ConnectionHub.stats}'s `dedupDrops` (N3). */
251
- private dedupDropCount;
252
- /** {@link ConnectionHub.stats}'s `rateLimitEvents` — see {@link handleRateLimited}. */
253
- private rateLimitEventCount;
254
- /**
255
- * M4 Phase 4 (gatekeeper LOW advisory): devices that have already had a
256
- * `device.rate_limited` embedder event emitted for their CURRENT
257
- * over-budget episode — see {@link handleRateLimited}'s own doc comment.
258
- * Coalescing state only; {@link rateLimitEventCount} still counts every
259
- * single hit regardless of what this suppresses.
260
- */
261
- private readonly rateLimitEventEmittedFor;
262
- constructor(taskStore: TaskStore, devices: DeviceRegistry,
263
- /** See {@link CreateByokServerOptions.taskLeaseMs} — already defaulted by `createByokServer` before reaching here. */
264
- taskLeaseMs: number,
265
- /**
266
- * M4 Phase 4 (part A): per-device inbound-envelope token bucket — see
267
- * {@link CreateByokServerOptions.rateLimit} (already defaulted by
268
- * `createByokServer` before reaching here) and {@link handleInbound}'s
269
- * own doc comment for where it's enforced. Defaults to a fresh
270
- * default-configured `RateLimiter` so every existing direct-construction
271
- * call site (this hub is constructed directly by several tests) keeps
272
- * working unchanged.
273
- */
274
- rateLimiter?: RateLimiter, agentMessage?: {
275
- consume(input: {
276
- readonly deviceId: string;
277
- readonly taskId: string;
278
- readonly context: AgentMessageServerContext;
279
- readonly payload: AgentMessagePublishPayload;
280
- }): {
281
- readonly outcome: 'accepted' | 'held' | 'refused';
282
- readonly reasonCode?: string;
283
- };
284
- } | undefined);
285
- /**
286
- * Stop the task-lease reaper's sweep timer — called by `ByokServer.stop()`
287
- * (`index.ts`) on shutdown. Idempotent: clearing an already-cleared
288
- * interval is a safe no-op.
289
- */
290
- stopLeaseReaper(): void;
291
- /** The top-level `events` feed returned by `createByokServer` — see {@link ByokServerEvent}. */
292
- subscribeServerEvents(): AsyncIterable<ByokServerEvent>;
293
- /**
294
- * A daemon completed the WS handshake (`conn.hello`). Does not itself send
295
- * `conn.ack` or redeliver — see {@link sendConnAck}/{@link redeliverAfterReconnect}.
296
- *
297
- * `capabilities` (M5, hello-capability plumbing): the daemon's own
298
- * `conn.hello.capabilities` — previously silently ignored end to end (a
299
- * verified gap: `ws-server.ts` forwarded only `runtimes`). Optional so
300
- * every pre-M5 direct-construction call site (several tests construct a
301
- * `ConnectionHub` and call this directly) keeps working unchanged; a
302
- * connection this hub never learns capabilities for simply reads back
303
- * `undefined` from {@link getDeviceCapabilities}.
304
- */
305
- registerConnection(deviceId: string, ws: WebSocket, runtimes: RuntimeInfo[] | undefined, capabilities?: readonly string[], configuredToolsets?: readonly ToolsetId[], clientVersion?: string): void;
306
- sendConnAck(deviceId: string, capabilities: string[]): void;
307
- /**
308
- * Reconnection procedure step 3 (§9): redeliver, in `seq` order, every
309
- * retained envelope with `seq > cursor` that still belongs to a
310
- * non-terminal task. Called after `conn.ack` (step 2), per the spec.
311
- */
312
- redeliverAfterReconnect(deviceId: string, cursor: number): void;
313
- /**
314
- * A device's WS socket closed. `ws` identifies *which* socket closed: if
315
- * it's no longer the one this device's connection state points at (a
316
- * newer WS reconnected, or long-poll took over — "last transport wins"),
317
- * this close is for a stale/superseded socket and the device isn't
318
- * actually gone, so the bookkeeping below is skipped entirely.
319
- *
320
- * M1 note: the M0 server force-failed/cancelled every in-flight task for a
321
- * device the instant it disconnected, on the stated premise that "a task
322
- * still in flight for a device that just disconnected can't be resumed, so
323
- * it's terminated" — true only in the absence of a redelivery cursor. M1
324
- * adds exactly that (§9): a task's in-flight state is retained
325
- * independently of any one connection, specifically so it can survive a
326
- * disconnect and resume via redelivery once the device reconnects. Failing
327
- * tasks here would make that feature unreachable in practice (nothing
328
- * would ever still be non-terminal by the time a reconnect happened), so
329
- * this now only updates connection bookkeeping and leaves task state
330
- * alone. A task left in-flight by a device that never reconnects stays
331
- * that way until the SaaS embedder explicitly cancels it — no
332
- * disconnect-timeout is specified by the protocol, so none is invented
333
- * here (see the M1-2 report's contract-gap notes).
334
- */
335
- handleDisconnect(deviceId: string, ws: WebSocket): void;
336
- /**
337
- * Drop every piece of hub state keyed by `deviceId` — called when the
338
- * device's registration is DELETED (§6.3 revocation, composed in
339
- * `index.ts`). Presence, its undelivered outbox, its inbound-dedup ring,
340
- * any held long-poll, and its rate-limit episode suppression only ever
341
- * existed to serve a row the directory can no longer name; leaving them
342
- * would keep a deleted device visible as live state and would let a
343
- * re-paired device inherit the dead one's dedup window and seq cursor.
344
- *
345
- * What the device DID is not revocation's business and is untouched here:
346
- * task records (`taskStore`), egress and content receipts, and projection
347
- * facts are history, not credentials.
348
- *
349
- * A live socket is closed rather than left attached — a still-open WS whose
350
- * next envelope would re-create the presence entry we just deleted is a
351
- * half-applied revocation. The close is detached first so `handleDisconnect`
352
- * sees no connection state and skips its disconnect bookkeeping: the device
353
- * is not going dark, it is gone.
354
- */
355
- forgetDevice(deviceId: string): void;
356
- /**
357
- * Resolve immediately if there are already-relevant events past `cursor`;
358
- * otherwise hold for up to `holdMs` and resolve with an empty result if
359
- * nothing arrives. A device may be connected via WS or long-poll, not
360
- * both simultaneously — a poll here supersedes (closes) any live WS for
361
- * this device ("last one wins", documented at the type level on
362
- * {@link ConnectionState}).
363
- */
364
- pollEvents(deviceId: string, cursor: number, holdMs: number): Promise<{
365
- events: Envelope[];
366
- cursor: number;
367
- }>;
368
- /** Make long-poll this device's active transport, closing any live WS ("last one wins", §8). */
369
- private takeOverAsLongPoll;
370
- /** Resolve (settle) any long-poll request currently held open for `deviceId`, if one exists. */
371
- private settleLongPollWaiter;
372
- /**
373
- * Single inbound choke point for every daemon -> server envelope (N2/N3/
374
- * P2) — called by both the WS path (`ws-server.ts`) and the long-poll send
375
- * path (`POST /byok/messages`, `http.ts`) in place of reaching into
376
- * per-type handlers directly. Runs a fixed gate, in order:
377
- *
378
- * 0. **rate limit (M4 Phase 4, part A)** — one token debited from this
379
- * device's bucket ({@link rateLimiter}) for EVERY inbound envelope,
380
- * before anything else runs (including the type-allow check below) —
381
- * a flood of garbage-typed envelopes must cost the same budget as a
382
- * flood of well-formed ones. Checked first specifically so an
383
- * over-budget device is turned away as cheaply as possible, before any
384
- * taskStore lookup or dedup bookkeeping. See {@link handleRateLimited}
385
- * for what happens on exceed (never a silent drop).
386
- * 1. **type-allow (P2)** — only {@link DAEMON_TO_SERVER_TYPES} may pass; a
387
- * server -> daemon type arriving inbound is rejected before it's
388
- * dispatched or counted accepted. `conn.hello` is the one non-task
389
- * exception, and is accepted only from the bearer-authenticated
390
- * long-poll route with an exact device/product/protocol match.
391
- * 2. **ownership (N2)** — an envelope for a task already owned by a
392
- * *different* device is dropped (logged), never force-failed:
393
- * force-failing on an authz mismatch would let an attacker who merely
394
- * guesses a `taskId` kill the real owner's task (a DoS). A task with no
395
- * owner yet, or that doesn't exist at all, is not rejected here — the
396
- * per-type handler's own no-op-on-missing-record behavior covers the
397
- * latter.
398
- * 3. **dedup (N3)** — an envelope `id` already seen from this device is a
399
- * no-op: the wire is at-least-once (§9), this makes server-side
400
- * processing at-most-once. Check-and-record is synchronous (Node is
401
- * single-threaded), so it's atomic with respect to any other envelope
402
- * for this device.
403
- * 4. **dispatch** — handed to the existing per-type `on*` handler.
404
- *
405
- * Returns which outcome applied. A duplicate still counts as `accepted` on
406
- * the `POST /byok/messages` wire (§8.2) — an idempotent replay is a
407
- * wire-level success even though no handler ran a second time; only
408
- * `rejected`/`rate_limited` (gate steps 0-2) are excluded from that count.
409
- */
410
- handleInbound(deviceId: string, envelope: Envelope, authenticatedProductId?: string): 'accepted' | 'duplicate' | 'rejected' | 'rate_limited';
411
- /**
412
- * Store before acking. Replays must agree on every identity/cursor/hash
413
- * field and receive the original receipt id; a same event id with changed
414
- * facts is rejected rather than treated as an update.
415
- */
416
- private handleAgentEgressReliable;
417
- private handleAgentMessagePublish;
418
- private sendAgentMessageDisposition;
419
- private handleAgentContentReceipt;
420
- private sendAgentEgressAck;
421
- private sendAgentContentReceiptAck;
422
- private agentEgressReceiptKey;
423
- /** Record the authenticated long-poll equivalent of the WS opening frame. */
424
- private registerLongPollHello;
425
- /**
426
- * M4 Phase 4 (part A): `deviceId` just exceeded its inbound-envelope rate
427
- * limit. Never a silent drop: counts the occurrence
428
- * ({@link rateLimitEventCount}, surfaced via {@link stats} — every single
429
- * hit, unconditionally) and, the FIRST time in this over-budget episode
430
- * only, emits an embedder-facing `device.rate_limited`
431
- * {@link ByokServerEvent} — see that variant's own doc comment (`types.ts`)
432
- * for the full per-transport enforcement shape.
433
- *
434
- * Gatekeeper LOW advisory (event amplification): a single flood can make
435
- * `handleInbound` call this many times in a row — e.g. several WS frames
436
- * already in flight before the close below actually lands, or a
437
- * long-poll device retrying its `POST /byok/messages` before its bucket
438
- * has refilled. Without coalescing, an embedder subscribed to
439
- * `events.subscribe()` would see one `device.rate_limited` per hit, which
440
- * is noisy for what is really ONE ongoing episode of one device
441
- * flooding. `rateLimitEventEmittedFor` suppresses the repeats: this
442
- * method only pushes the event the first time it sees a given `deviceId`
443
- * since `handleInbound`'s own success path last cleared it (i.e. since
444
- * this device was last confirmed back under budget) — the COUNTER above
445
- * is entirely unaffected by this and still increments on every call,
446
- * unconditionally.
447
- *
448
- * This method only handles the WS half of the enforcement shape (closing
449
- * the live connection, if any, so the client's existing backoff+reconnect
450
- * takes over — mirrors `takeOverAsLongPoll`'s own `ws.close`, the only
451
- * other place this hub closes a device's socket directly); a long-poll
452
- * device has no live `ws` to close here at all (`conn.ws` is `undefined`
453
- * while long-polling — see {@link ConnectionState}), so `http.ts`'s
454
- * `/byok/messages` handler maps this same `'rate_limited'` `handleInbound`
455
- * outcome to an HTTP 429 for that transport instead.
456
- */
457
- private handleRateLimited;
458
- /**
459
- * Idempotency check-and-record (N3): `true` (duplicate) if `id` was
460
- * already seen for `deviceId`; otherwise records it and returns `false`.
461
- * Bounded to {@link DEDUP_RING_CAPACITY} ids per device — a ring, not an
462
- * unbounded set — evicting the oldest once full.
463
- */
464
- private checkAndRecordDuplicate;
465
- /**
466
- * Route one already-gated envelope (see {@link handleInbound}) to its
467
- * per-type handler. Type-allow/ownership/dedup have already run by the
468
- * time this executes, so the handlers below no longer need their own
469
- * device-mismatch checks — that authz decision now lives solely in
470
- * `handleInbound` (N2).
471
- *
472
- * Also the task-lease reaper's activity checkpoint
473
- * ({@link recordTaskActivity}): every envelope for a task that currently
474
- * *exists and is non-terminal* counts as proof of life for `taskId`'s
475
- * lease, regardless of what its per-type handler below ends up doing with
476
- * it (including a no-op/stale drop) — see the "task-lease reaper" section
477
- * further down for why. Deliberately gated on the record's existence and
478
- * non-terminal state *here*, before dispatch: `taskActivity` must never
479
- * gain an entry for a taskId that doesn't exist (a nonexistent/garbage id
480
- * an authenticated-but-malicious daemon could send indefinitely — an
481
- * unbounded-growth vector, since `taskId`s aren't deduped the way envelope
482
- * `id`s are) or for one that's already terminal (a stale/late message for
483
- * a finished task — `onStateChange` deletes the entry on the *real*
484
- * terminal transition, but a stale message arriving *after* that would
485
- * otherwise silently recreate it, since every per-type handler's own
486
- * terminal/unknown-task guard runs — and early-returns — only *after*
487
- * this would already have recorded activity).
488
- */
489
- private dispatchToHandler;
490
- /** Reset the task-lease reaper's per-task clock (condition (c) in the "task-lease reaper" section below). */
491
- private recordTaskActivity;
492
- /**
493
- * Ownership (record.deviceId matching the connection's authenticated
494
- * deviceId) is enforced centrally by {@link handleInbound} (N2) before this
495
- * runs; only the idempotent-claim CAS and the first-claim device patch
496
- * happen here.
497
- *
498
- * M5 (claimed runtime, docs/protocol.md §3.1): `payload.runtime` — the
499
- * ACTUAL adapter the daemon selected (`TaskRunner.pickAdapter`,
500
- * `packages/client`'s `task-runner.ts`) — is recorded into
501
- * `TaskSnapshot.claimedRuntime` alongside the device patch, distinct from
502
- * the pre-existing `TaskSnapshot.runtime` (the merely REQUESTED runtime,
503
- * untouched here and set only once, at `dispatch()` time). Only ever
504
- * written on the FIRST real claim: the idempotent-CAS early return above
505
- * fires before this for a retried claim from a device that already owns
506
- * the task, so a redelivered/retried `task.claim` can never overwrite an
507
- * already-recorded `claimedRuntime` — including with a stale or absent
508
- * value from an out-of-order retry.
509
- *
510
- * S0/D-4 (claim-time capability snapshot): `payload.capabilities` — the
511
- * claiming adapter's OWN self-report, carried on this same `task.claim`
512
- * (docs/protocol.md §2.4) — supplies
513
- * `TaskSnapshot.claimedRuntimeCapabilities`, written in the same patch and
514
- * therefore under the same write-exactly-once property as `claimedRuntime`.
515
- *
516
- * Taken from the payload and from nowhere else. This hub deliberately does
517
- * NOT consult connection state (`conn.hello.runtimes[]`) for it — see
518
- * {@link SteerRejectedError} for why that source is structurally wrong for a
519
- * control decision, and that field's own doc comment (`types.ts`) for why
520
- * this is snapshotted rather than read live at steer time. A claim that
521
- * carries no `capabilities` (a pre-D-4 daemon) records `undefined`, which
522
- * the gate reads as "unknown" and refuses.
523
- */
524
- private onClaim;
525
- /**
526
- * `Claimed -> Running` (§3.1) — a daemon actually starting the runtime
527
- * session, distinct from merely claiming. Ownership is already enforced
528
- * by {@link handleInbound} (N2) before this runs.
529
- */
530
- private onStarted;
531
- /**
532
- * `Offered -> Failed` (§3.2) — a fail-closed pre-claim rejection. Only
533
- * ever legal from `Offered`; anything else is stale. Ownership is already
534
- * enforced by {@link handleInbound} (N2) before this runs.
535
- */
536
- private onDecline;
537
- private onProgress;
538
- private onArtifact;
539
- private onAwaitApproval;
540
- private onComplete;
541
- private onFail;
542
- /**
543
- * Dual-purpose on receipt (§3.3): if the server already moved this task to
544
- * `Cancelled` on its own action (the common case — `cancelTask()` is
545
- * authoritative immediately, §4), this is a late idempotent ack — silent,
546
- * not a warning (this is the other half of the M0 gatekeeper finding this
547
- * change resolves). Otherwise it's the authoritative trigger for a
548
- * cancellation the daemon observed that the server didn't initiate.
549
- * Ownership is already enforced by {@link handleInbound} (N2) before this
550
- * runs.
551
- */
552
- private onCancelled;
553
- /**
554
- * M4 (additive-minor, `task.approval_resolved`): the EXPLICIT counterpart
555
- * to {@link resumeIfImplicitlyApproved} — a daemon that resolved a pending
556
- * approval entirely LOCALLY now reports it immediately, instead of the
557
- * server only finding out after the fact once evidence (a later
558
- * `task.progress`/`task.artifact`/`task.complete`) proves it.
559
- *
560
- * Relationship to the implicit path (both stay, permanently — this is not
561
- * a replacement): {@link resumeIfImplicitlyApproved} remains completely
562
- * untouched as the fallback for (a) an old daemon that predates this
563
- * message, and (b) a daemon connected to an old server that never
564
- * advertised the `approval_resolved` capability flag (`version.ts`) at
565
- * handshake time — in either case the daemon never sends this message at
566
- * all (see `packages/client`'s `task-runner.ts`), and the server keeps
567
- * inferring the resolution from evidence exactly as it did before this
568
- * message existed. When THIS message does arrive first, it already moves
569
- * the record out of `AwaitApproval` (see below) — so by the time any
570
- * following `task.progress`/etc. reaches `onProgress`/`onArtifact`/
571
- * `onComplete`, `resumeIfImplicitlyApproved`'s own `record.state !==
572
- * 'AwaitApproval'` guard is already true and it no-ops, never firing its
573
- * own `task.approval_resolved_implicit` event a second time for the same
574
- * resolution. The two mechanisms race harmlessly: whichever one the
575
- * server processes first is the one that actually performs the
576
- * transition; the other is naturally inert once it runs.
577
- *
578
- * Three outcomes, mirroring this file's existing per-type idempotency
579
- * conventions:
580
- * - `AwaitApproval` (the expected case): legal transition to `Running`
581
- * (an existing `TASK_TRANSITIONS` edge, the same one `approveTask`
582
- * itself uses) plus a `task.approval_resolved` {@link ByokServerEvent}
583
- * carrying `approvalId`/`decision`/`resolvedBy` for an embedder to
584
- * observe.
585
- * - Already `Running` (evidence — or the implicit path — already beat
586
- * this message to it): idempotent no-op, silent, mirroring
587
- * `onStarted`'s own already-running guard.
588
- * - Terminal, or a state that was never `AwaitApproval` in the first
589
- * place (`Offered`/`Claimed` — a genuinely out-of-sequence report):
590
- * stale no-op with a `console.warn`, matching this file's existing
591
- * stale-message convention (`forceFailOrDrop`, `handleInbound`'s
592
- * ownership-mismatch drop) — never force-failed, since a late/
593
- * redelivered report about a task that has already moved on is not
594
- * evidence of anything currently wrong with it.
595
- *
596
- * This is also the residual-race resolution the accompanying protocol/docs
597
- * update documents: a SaaS decision (`approveTask`/`rejectTask`) already in
598
- * flight when the local resolution happens can still land on the server
599
- * FIRST and move the record to a terminal state before this message
600
- * arrives — in that case this message hits the terminal branch above and
601
- * is a stale no-op, exactly like any other late message for an
602
- * already-terminal task. The window for that crossing is now
603
- * network-latency-sized (how long this message takes to arrive), not
604
- * "until the next progress message" the way the pre-existing implicit-only
605
- * inference left it.
606
- */
607
- private onApprovalResolved;
608
- /**
609
- * M5 (approval targeting): single low-level wrapper around
610
- * `TaskStore.transition` that every ACTUAL state-changing write in this
611
- * file goes through — {@link applyOrFail}'s legal-transition branch,
612
- * {@link forceFailOrDrop}, and {@link resumeIfImplicitlyApproved} (the one
613
- * caller that transitions WITHOUT going through `applyOrFail` at all).
614
- * Two responsibilities, folded in here once rather than duplicated at
615
- * each call site:
616
- *
617
- * 1. Clears `pendingApprovalId` whenever `record` is LEAVING
618
- * `AwaitApproval` (`record.state === 'AwaitApproval' && to !==
619
- * 'AwaitApproval'`) — the id this hub last recorded for a task's
620
- * pending approval ({@link onAwaitApproval}) is meaningless the
621
- * instant that task is no longer awaiting it. Clearing it here,
622
- * centrally, is what guarantees a FUTURE `AwaitApproval` cycle for
623
- * the SAME task always starts from a clean slate instead of silently
624
- * inheriting a stale id from a previous cycle (which would make a
625
- * stale-approval check against the NEW cycle's real pending id
626
- * spuriously pass just because a leftover value happened to still be
627
- * sitting in the record).
628
- * 2. Calls {@link onStateChange} — every call site already did this
629
- * immediately after its own `transition` call; folding it in here
630
- * removes the duplication and the chance of a future call site
631
- * forgetting it.
632
- */
633
- private transitionTask;
634
- /**
635
- * Apply `taskId`'s state -> `target`. If that's illegal per
636
- * `TASK_TRANSITIONS`, fall back to `Failed` (if reachable from the current
637
- * state); this is the "illegal transition = error + task.fail path" rule.
638
- */
639
- private applyOrFail;
640
- /**
641
- * M4 Phase 3 hardening (orchestrator-directed fix for the server-state-
642
- * machine trace finding): a task can be resolved entirely OUT-OF-BAND, on
643
- * the daemon side only (M4 Phase 3's local `approvals.resolve`
644
- * control-socket path, `packages/client`) — the server never sees a wire
645
- * `task.approve`/`task.reject` for it, so its own record sits in
646
- * `AwaitApproval` even though the daemon already resumed and moved on.
647
- *
648
- * The daemon is the execution authority in this security model (the SaaS
649
- * only ever *proposes* — see docs/spec.md); the daemon sending ANY further
650
- * task.* traffic for a task the server still thinks is `AwaitApproval` is
651
- * itself sufficient proof the approval was resolved locally, one way or
652
- * another. Rather than force-failing/dropping that traffic (the pre-fix
653
- * behavior — `onProgress`/`onArtifact`'s own `!== 'Running'` guard,
654
- * `onComplete`'s illegal-transition fallback), this applies the exact same
655
- * `AwaitApproval -> Running` edge `approveTask` already uses (a
656
- * pre-existing legal `TASK_TRANSITIONS` edge, not a new one) through the
657
- * normal transition path — `taskStore.transition` + `onStateChange`, same
658
- * as `applyOrFail`'s own legal-transition branch — so every existing
659
- * consumer of task state (§, `TaskHandle.events()`, the lease reaper's
660
- * `taskActivity`) observes it exactly as it would a real wire
661
- * `task.approve`. Then emits `task.approval_resolved_implicit` (a
662
- * `ByokServerEvent`, NOT a wire message — see that type's own doc comment)
663
- * so an embedder can distinguish this from an operator-driven approval.
664
- *
665
- * M4 (additive-minor, superseding this method's own former "deferred"
666
- * framing): a first-class `task.approval_resolved` WIRE notification now
667
- * exists (`onApprovalResolved`, below) — a daemon that supports it, talking
668
- * to a server that advertised the `approval_resolved` capability flag
669
- * (`version.ts`), reports a local resolution explicitly and immediately
670
- * instead of leaving the server to infer it here. This method is
671
- * UNTOUCHED and remains the permanent fallback for the N/N-1 cases where
672
- * that explicit report never arrives (an old daemon, or an old server this
673
- * daemon is talking to) — see `onApprovalResolved`'s own doc comment for
674
- * the full relationship between the two paths, including why they can
675
- * never both fire for the same resolution.
676
- *
677
- * No-op (returns `record` unchanged) for any state other than
678
- * `AwaitApproval` — every other guard (terminal, pre-claim, already-
679
- * Running) keeps exactly its current behavior. `onFail`/`onCancelled`
680
- * never call this: `Failed`/`Cancelled` are already direct, legal edges
681
- * from `AwaitApproval`, so they never hit the illegal-transition path this
682
- * exists to avoid in the first place.
683
- */
684
- private resumeIfImplicitlyApproved;
685
- /**
686
- * A daemon message didn't fit the task's current state (e.g. progress
687
- * while AwaitApproval). Force the task to `Failed` if that's reachable;
688
- * otherwise it's already terminal (or `Offered`, which has no Failed edge)
689
- * and there's nothing safe to do but log + drop.
690
- */
691
- private forceFailOrDrop;
692
- private onStateChange;
693
- /**
694
- * Task lease: a backstop for a device that goes dark mid-task and never
695
- * comes back — distinct from, and layered on top of, M1's redelivery
696
- * (docs/protocol.md §9), which already handles "device reconnects within
697
- * the window, nothing lost." Decision (user+design): reuse the existing
698
- * `Failed` terminal state and its `retryable` flag —
699
- * `Failed(retryable: true, reason: 'lease-expired')` — exactly like any
700
- * other `task.fail`. The embedder is expected to treat this exactly like
701
- * any other retryable failure: re-dispatch as a brand-new task.
702
- *
703
- * Implemented as a periodic sweep (see the constructor), not a per-task
704
- * timer, so a device that goes dark *after* being idle-but-connected for a
705
- * while is still caught on a later tick without needing extra bookkeeping
706
- * at disconnect time. `sweepLeases` reaps a task only when ALL of the
707
- * following hold, checked fresh on every tick (never cached):
708
- *
709
- * (a) the task is in a non-terminal *claimed* state — `Claimed`,
710
- * `Running`, or `AwaitApproval` ({@link isClaimedState}). `Offered`
711
- * is excluded: it has no owning device yet, so there's nothing to
712
- * be "dark".
713
- * (b) the owning device is dark right now ({@link deviceDarkSince}
714
- * returns a timestamp rather than `undefined`) — disconnected
715
- * outright, or (long-poll only) hasn't been seen since before the
716
- * lease window. A live WS connection is never dark from the
717
- * reaper's point of view: `heartbeat.ts` already independently
718
- * proves liveness at the transport level and flips
719
- * `connected: false` via `handleDisconnect` once it stops getting
720
- * pongs — the reaper just reads that flag rather than re-deriving
721
- * it. `deviceDarkSince` also returns *when* darkness started
722
- * ({@link ConnectionState.darkSince}, set the instant
723
- * `handleDisconnect` flips the connection dark) — that instant
724
- * feeds condition (c), below.
725
- * (c) a full `taskLeaseMs` has elapsed since the *later* of: the task's
726
- * own last inbound-activity timestamp ({@link taskActivity}, reset
727
- * in {@link dispatchToHandler} on every accepted envelope for a
728
- * known, non-terminal task — claim, started, progress, artifact,
729
- * await_approval, anything), and (b)'s dark-since instant. Taking
730
- * the *later* of the two — not the activity timestamp alone — is
731
- * what makes a device going dark start a fresh, full countdown
732
- * instead of reusing whatever (possibly already-stale) activity
733
- * timestamp the task happened to have: a task can be legitimately
734
- * idle *while connected* for longer than `taskLeaseMs` (a long turn
735
- * with no progress events, or just a quiet stretch) without being
736
- * touched — see (b) — but the instant such a task's device
737
- * disconnects, that stale activity timestamp must NOT immediately
738
- * satisfy (c) on its own, or the task would get reaped within one
739
- * sweep tick of disconnect instead of waiting the full window. That
740
- * was a real bug (a disconnect-after-long-idle reap effectively
741
- * indistinguishable from the M0 disconnect-alone-fails-the-task
742
- * behavior M1 removed, below); anchoring (c) to
743
- * `max(lastActivity, darkSince)` fixes it — idle time that elapsed
744
- * *before* the device went dark no longer counts toward the lease,
745
- * only silence *after* dark-start does.
746
- *
747
- * (b) and (c) are deliberately independent clocks, not one merged check.
748
- * The property this most exists to protect: a *connected*, momentarily
749
- * idle device mid-turn must never be reaped, no matter how long
750
- * `taskLeaseMs` is — condition (b) alone blocks that regardless of (c).
751
- * This is also what keeps this from reintroducing the M0 bug M1
752
- * deliberately removed (see `handleDisconnect`'s own doc comment above) —
753
- * M0 force-failed a task the instant its device disconnected; M1
754
- * correctly stopped doing that so a task could survive a disconnect and
755
- * resume via redelivery. This reaper does not revert that: disconnect
756
- * ALONE still does nothing here either — (c) still has to independently
757
- * hold, and per the `max(...)` above it only will once a full
758
- * `taskLeaseMs` has genuinely elapsed *since the device went dark*, no
759
- * matter how stale the task's own activity timestamp already was at that
760
- * moment.
761
- *
762
- * Interaction with redelivery (§9): redelivery is what handles "the
763
- * device came back within the window" — nothing to reap, normal traffic
764
- * resumes. This reaper is what handles "it never came back." Idempotent
765
- * claim (`onClaim`'s CAS) still protects server-side bookkeeping if a
766
- * device wakes up *after* its task was already reaped and retries a stale
767
- * claim/progress/etc. for it: every per-type handler's existing
768
- * stale/terminal-task guard (§9) drops it as a no-op, same as any other
769
- * late message for an already-terminal task — no new guard was needed for
770
- * that here.
771
- *
772
- * Accepted residual (by design, not a bug): idempotent claim protects
773
- * *server-side* state, not the device's own local side effects. A dark
774
- * device that wakes up after its task has already been reaped may still
775
- * be mid-way through running real local work (file writes, shell
776
- * commands, whatever the runtime adapter was doing) for a task the server
777
- * has since moved on from — and that the embedder may have already
778
- * re-dispatched elsewhere. There is no way to remotely guarantee a
779
- * truly-dark device stops running; the mitigation is entirely
780
- * `taskLeaseMs` being set far larger than any realistic task duration, so
781
- * this can only happen to a device that was genuinely gone for a very
782
- * long time, not a normal slow turn.
783
- */
784
- private sweepLeases;
785
- /**
786
- * Condition (b) above: `undefined` while `deviceId`'s connection counts as
787
- * alive (never reapable, no matter how stale (c) is); otherwise the
788
- * epoch-ms instant it began counting as "dark" for lease purposes.
789
- * `sweepLeases` combines this with (c)'s own last-activity instant via
790
- * `max(...)` so the full `taskLeaseMs` silence window is always measured
791
- * from whichever of the two happened later.
792
- */
793
- private deviceDarkSince;
794
- /** Reap one lease-expired task through the exact same TaskStore/canTransition path — and terminal-event emission — as any other `task.fail` (see {@link applyOrFail}). */
795
- private reapTask;
796
- dispatch(input: DispatchInput): Promise<TaskHandle>;
797
- dispatchFreshAgentEgress(input: FreshAgentEgressDispatchInput): Promise<TaskHandle>;
798
- private dispatchInternal;
799
- /** Capability-gated control-plane read request; no request enters the outbox on omission. */
800
- requestAgentContentRead(input: AgentContentReadRequest): Promise<void>;
801
- /** Task-free exact-device projection; no task record, runtime or session is created. */
802
- enqueueAgentHomeProjection(input: AgentHomeProjectionRequest): Promise<AgentHomeProjectionReadback>;
803
- readAgentHomeProjection(deviceId: string, requestId: string): AgentHomeProjectionReadback | undefined;
804
- completeAgentHomeProjection(deviceId: string, input: AgentHomeProjectionCompletionRequest): AgentHomeProjectionReadback;
805
- private buildTaskHandle;
806
- /** Idempotent: cancelling an already-terminal task is a no-op, not an error. */
807
- private cancelTask;
808
- /**
809
- * M4 Phase 3: made public (was private through M3) so an embedder can call
810
- * it directly from its own operator-facing surface — there is no
811
- * bearer-authed HTTP route for this on `http.ts`'s own app (see
812
- * `UnknownTaskError`'s own doc comment for why, and
813
- * `examples/basic/server.ts`'s `/api/tasks/:taskId/approve` for the
814
- * intended shape of that embedder-built surface). See this file's own
815
- * `UnknownTaskError`/`TaskNotAwaitingApprovalError` doc comments for why
816
- * the two failure modes are now distinct typed errors rather than a
817
- * single generic `Error`. Every thrown message's TEXT is byte-for-byte
818
- * unchanged from M2/M3 — only the error's type changed (this is still also
819
- * reachable via `TaskHandle.approve()`, unaffected).
820
- */
821
- /**
822
- * M5 (approval targeting, docs/protocol.md §5.3): `opts.approvalId`
823
- * targets a SPECIFIC pending approval rather than "whichever one is
824
- * currently pending" (the pre-M5 default, unchanged when `opts` is
825
- * omitted). Validated FIRST, before any state change or wire send: if
826
- * `opts.approvalId` is supplied and this hub has a recorded
827
- * `pendingApprovalId` for `taskId` that DIFFERS, throws
828
- * {@link StaleApprovalError} — no transition, no `task.approve` sent. If
829
- * this hub never recorded a `pendingApprovalId` (a legacy daemon that
830
- * never reported one), the call proceeds untargeted exactly as before.
831
- * The outgoing `task.approve` carries `approvalId`: the caller-supplied
832
- * one if given, else this hub's own recorded one, else omitted entirely
833
- * (legacy wire shape) — so the daemon can apply its own exact-match check
834
- * whenever this server has an id to offer at all.
835
- */
836
- approveTask(taskId: string, opts?: {
837
- approvalId?: string;
838
- }): Promise<void>;
839
- /**
840
- * M4 Phase 3: made public — see {@link ConnectionHub.approveTask}'s own
841
- * doc comment for the full rationale (identical reasoning applies here).
842
- * M5: same `opts.approvalId` targeting semantics as `approveTask` above —
843
- * see that method's own doc comment.
844
- */
845
- rejectTask(taskId: string, reason?: string, opts?: {
846
- approvalId?: string;
847
- }): Promise<void>;
848
- /**
849
- * S0 (GAP-002): a task-level gate, evaluated in full before any envelope is
850
- * built — see {@link SteerRejectedError} for the gap this closes and why an
851
- * unknown capability must refuse rather than proceed. Order matters:
852
- *
853
- * 1. unknown task — unchanged pre-S0 `Error` (this is not a steer-policy
854
- * decision, and `TaskHandle.steer` can only be reached with a taskId
855
- * this hub minted, so it's a programming error, not an operator one);
856
- * 2. terminal (`Complete`/`Failed`/`Cancelled`) -> `task_terminal`,
857
- * checked BEFORE the `Running` check so a steer racing a terminal
858
- * transition always resolves terminal-first;
859
- * 3. not `Running` (`Offered`/`Claimed`/`AwaitApproval`) ->
860
- * `task_not_running`;
861
- * 4. the claim-time snapshot does not positively say `steer: true` ->
862
- * `steer_unsupported_runtime`, including when there is no snapshot at
863
- * all (fail-closed);
864
- * 5. only then, the pre-existing device-liveness check and the send.
865
- *
866
- * Step 4 reads `TaskSnapshot.claimedRuntimeCapabilities` — the per-runtime,
867
- * per-task value frozen at claim time from the claiming adapter's own
868
- * `task.claim.capabilities` — and reads NO connection state whatsoever:
869
- * not {@link getDeviceCapabilities}, not `ConnectionState.runtimes`, and
870
- * with no fallback to either when the snapshot is absent. See
871
- * {@link SteerRejectedError} for why a connection-sourced input is wrong
872
- * in scope (it describes a daemon build, not this task's runtime).
873
- */
874
- private steerTask;
875
- private pickFirstConnectedDevice;
876
- /**
877
- * Build a server -> daemon envelope with a fresh per-device `seq`, retain
878
- * it in that device's outbox ring buffer, and deliver it now if a live
879
- * transport is available (WS send, or wake a pending long-poll).
880
- *
881
- * `opts`'s type mirrors `createEnvelope`'s own per-type conditional
882
- * requiredness (finding F1) minus `seq` (computed fresh right here on
883
- * every call, never caller-supplied) — so every one of this method's 6
884
- * callers below must supply `taskId` for the 5 types that need it
885
- * (everything except `conn.ack`), same as calling `createEnvelope`
886
- * directly would require.
887
- */
888
- private sendToDevice;
889
- private deliverToDevice;
890
- /**
891
- * Retained envelopes for `deviceId` with `seq > cursor` that still belong
892
- * to a non-terminal task — OR are explicitly exempted from that filter
893
- * (`redeliverThroughTerminal`, N1/F4: `task.cancel`/`task.reject`) — in
894
- * `seq` order. The `seq > cursor` bound is what naturally stops an
895
- * exempted entry from redelivering forever: once the daemon acks it (its
896
- * reported cursor advances past that `seq`), it no longer qualifies here
897
- * on any future reconnect/poll.
898
- */
899
- private collectRelevant;
900
- private isTaskTerminal;
901
- /** The highest `seq` assigned to `deviceId` so far — the redelivery cursor to hand back on a poll/reconnect. */
902
- private currentCursor;
903
- private getOrCreateOutbox;
904
- listMachines(): MachineInfo[];
905
- /**
906
- * M5 (approval targeting, hello-capability plumbing): the capability flags
907
- * `deviceId`'s CURRENT connection advertised in its `conn.hello` —
908
- * `undefined` if this hub has no connection state for the device at all,
909
- * or one that never had capabilities recorded (a pre-M5 daemon, or a
910
- * device this hub only ever saw over long-poll with no prior WS hello —
911
- * see `ConnectionState.capabilities`'s own doc comment). Read fresh from
912
- * live connection state, mirroring `listMachines()`'s own convention; an
913
- * embedder can use this to distinguish a targeting-capable device from a
914
- * legacy one for its own observability/UI purposes (see `version.ts`'s
915
- * `approval-targeting` flag doc comment for why this is informational
916
- * only, never a correctness gate).
917
- */
918
- getDeviceCapabilities(deviceId: string): readonly string[] | undefined;
919
- private hasDeviceCapabilities;
920
- getAgentEgressReceipt(deviceId: string, eventId: string): AgentEgressReceipt | undefined;
921
- getTask(taskId: string): TaskSnapshot | undefined;
922
- listTasks(): TaskSnapshot[];
923
- /**
924
- * A plain, serializable snapshot of this hub's current state, derived from
925
- * existing structures (`connections`, `taskStore`) plus the small counters
926
- * this file already maintains for exactly this purpose — no new
927
- * bookkeeping structures beyond those counters. See {@link HubStats}
928
- * (`types.ts`) for the full field-by-field contract.
929
- */
930
- stats(): HubStats;
931
- }