@clothespin/pi-pippi 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/bridge.ts ADDED
@@ -0,0 +1,1759 @@
1
+ /**
2
+ * PippiBridge: the pi-side brain of the integration.
3
+ *
4
+ * It owns nothing about Bluetooth (see transport.ts) and nothing about pi's
5
+ * event names (see index.ts). In between it keeps a session model, renders it
6
+ * into the agent-neutral snapshot the firmware expects, and brokers
7
+ * permission prompts so a button press on the device can allow or block a pi
8
+ * tool call.
9
+ *
10
+ * Design notes worth knowing before editing:
11
+ * - The firmware stores ONE prompt at a time (src/data.h:19-21), so approval
12
+ * requests are queued and answered sequentially even though pi may
13
+ * preflight several tool calls in one turn.
14
+ * - Snapshots are coalesced (min interval) because the device's BLE RX ring
15
+ * is 2048 bytes (src/ble_bridge.cpp:20); a state change per token would
16
+ * overflow it. A 10s keepalive guarantees the device's 30s liveness check.
17
+ * - Every send goes through protocol.ts so no line can exceed the device's
18
+ * 1024 byte line buffer.
19
+ */
20
+
21
+ import {
22
+ type ApprovalPolicy,
23
+ } from "./approvals.ts";
24
+ import {
25
+ type PermissionDecision,
26
+ type Phase,
27
+ type Snapshot,
28
+ type TurnEvent,
29
+ type UsageInfo,
30
+ clampSnapshot,
31
+ compareVersions,
32
+ encodeLine,
33
+ encodeSnapshot,
34
+ encodeTurn,
35
+ localMidnightEpoch,
36
+ oneLine,
37
+ providerBadgeKey,
38
+ timeSync,
39
+ truncateBytes,
40
+ MAX_ENTRIES,
41
+ MAX_PROMPT_HINT_BYTES,
42
+ MIN_FIRMWARE_VERSION,
43
+ } from "./protocol.ts";
44
+ import { ClaimBoard, type Verdict } from "./claims.ts";
45
+ import type { BridgeTransport, ScanResult, TransportState } from "./transport.ts";
46
+
47
+ export type { ApprovalPolicy };
48
+
49
+ export type ApprovalOutcome = "once" | "deny" | "timeout" | "unavailable";
50
+
51
+ export interface PersistedState {
52
+ /** Address (or advertised name) of the device to reconnect to. */
53
+ device?: string;
54
+ deviceName?: string;
55
+ /** Daily token counter: output tokens since `dayEpoch` (local midnight). */
56
+ dayEpoch?: number;
57
+ tokensToday?: number;
58
+ approvals?: ApprovalPolicy;
59
+ enabled?: boolean;
60
+ }
61
+
62
+ export interface StateStore {
63
+ load(): PersistedState;
64
+ save(patch: PersistedState): void;
65
+ }
66
+
67
+ /** In-memory store; the default in tests and when the FS is unavailable. */
68
+ export class MemoryStateStore implements StateStore {
69
+ private state: PersistedState;
70
+ constructor(initial: PersistedState = {}) {
71
+ this.state = { ...initial };
72
+ }
73
+ load(): PersistedState {
74
+ return { ...this.state };
75
+ }
76
+ save(patch: PersistedState): void {
77
+ this.state = { ...this.state, ...patch };
78
+ }
79
+ }
80
+
81
+ export interface BridgeConfig {
82
+ /** Owner first name pushed once per connect ({"cmd":"owner"}). */
83
+ owner?: string;
84
+ /** Saved device address/name; empty means "only connect on demand". */
85
+ device?: string;
86
+ /**
87
+ * Advertised name of that device, kept alongside the address because a scan
88
+ * is how the bridge checks whether the pippi is free to be taken back, and a
89
+ * pippi saved by name (PI_PIPPI_DEVICE) has no address to compare.
90
+ */
91
+ deviceName?: string;
92
+ approvals: ApprovalPolicy;
93
+ /** ms to wait for a decision on the device before giving up. 0 = forever. */
94
+ approvalTimeoutMs: number;
95
+ keepaliveMs: number;
96
+ statusPollMs: number;
97
+ /** Send {"evt":"turn"} events. Current firmware ignores them; off by default. */
98
+ turnEvents: boolean;
99
+ /** Minimum gap between two snapshots triggered by state changes. */
100
+ minSnapshotGapMs: number;
101
+ /**
102
+ * How long a blocked tool call waits for this session to take the pippi over
103
+ * from another pi process before asking in the terminal instead.
104
+ *
105
+ * Timed against what a claim costs, not against patience: release_link, a
106
+ * link that may have to come back to life, and a connect the adapter will not
107
+ * rush -- 5-6s measured, end to end. A budget under that does not fail fast, it
108
+ * fails *often*: the tool call gives up mid-claim, the terminal gets the asking,
109
+ * and the claim the human started carries on underneath anyway.
110
+ */
111
+ claimBudgetMs: number;
112
+ /**
113
+ * How long a claim waits before it happens, when the link is not already ours.
114
+ *
115
+ * Claiming is violent by construction: `release_link` first, so a claim that starts
116
+ * while another window's claim is in flight does not just lose the race -- it breaks
117
+ * the handover it lost to, and both sides start over. The grace is the window in
118
+ * which the press that was actually meant can land and be seen by the board, so the
119
+ * claim that goes through is the one the human is looking at.
120
+ *
121
+ * It is not a lock and cannot be: two windows can start their timers at the same
122
+ * moment and both sit for the same interval. What it buys is the overwhelmingly
123
+ * common case -- a press here and a keystroke there a few hundred milliseconds apart
124
+ * -- for that much latency on a claim that would have won anyway. Zero skips it, and
125
+ * a link already held skips it too, because there is no handover to protect.
126
+ */
127
+ claimPreDelayMs: number;
128
+ /**
129
+ * How long to keep taking the pippi back after it fell off a live link with
130
+ * nobody asking for it -- a reset, a flash, a battery swap, a walk out of
131
+ * range. 0 means never: let go of the radio and wait for Enter.
132
+ */
133
+ reclaimMs: number;
134
+ /**
135
+ * Pause before the first auto-reclaim.
136
+ *
137
+ * Two seconds, where it used to be twelve. The twelve was a guess at somebody else's
138
+ * claim: another window's takeover takes 4-6s to land, during which the pippi is
139
+ * attached to nobody and advertising to everyone, and a scan into that gap read as
140
+ * "free" and used to start a fight over it. The delay is not guarding that any more,
141
+ * because the delay was never the thing that could: the board is re-read before every
142
+ * attempt, and a session that is not the leader does not reach for the radio. What is
143
+ * left is the pippi itself -- seconds after a reset it is still in its bootloader, and
144
+ * a scan then proves nothing except that we can scan -- so the first pause is one
145
+ * short nap and the ladder below does the waiting.
146
+ */
147
+ reclaimFirstMs: number;
148
+ /**
149
+ * Where the claim board lives. Default: a directory under the system temp
150
+ * filesystem, which is the same one every other pi process on this machine reads
151
+ * -- see claims.ts. Set it to a private directory in tests, where "another
152
+ * session" is simulated and must not be able to see the real one.
153
+ */
154
+ claimDir?: string;
155
+ /**
156
+ * A claim board to use instead of the one in `claimDir`. For tests, where two
157
+ * "windows" run in one process and need identities that are not both this pid.
158
+ */
159
+ claimBoard?: ClaimBoard;
160
+ /**
161
+ * Short label for this session, sent with a pending permission prompt so the
162
+ * device can show which pi window is asking. Deliberately not persisted: a tag
163
+ * that followed you into every window would read the same everywhere and tell
164
+ * you nothing.
165
+ */
166
+ tag?: string;
167
+ /**
168
+ * How long a question on the panel outlives a link that dropped underneath it.
169
+ *
170
+ * The alternative -- calling the question off the moment the link wobbles -- throws away
171
+ * the answer the human is about to press, because the panel keeps showing a dialog it
172
+ * was never told to clear. See `holdPromptThroughDrop`. Short enough that a pippi which
173
+ * is genuinely gone still ends up asking in the terminal.
174
+ */
175
+ promptLinkGraceMs: number;
176
+ }
177
+
178
+ export const DEFAULT_CONFIG: BridgeConfig = {
179
+ approvals: "dangerous",
180
+ approvalTimeoutMs: 60_000,
181
+ keepaliveMs: 10_000,
182
+ statusPollMs: 15_000,
183
+ turnEvents: false,
184
+ minSnapshotGapMs: 400,
185
+ claimBudgetMs: 10_000,
186
+ claimPreDelayMs: 250,
187
+ reclaimMs: 120_000,
188
+ reclaimFirstMs: 2_000,
189
+ promptLinkGraceMs: 20_000,
190
+ };
191
+
192
+ export interface ApprovalRequest {
193
+ /** Short tool label shown on the device (budget: 19 bytes). */
194
+ tool: string;
195
+ /** One-line preview of the arguments (budget: 43 bytes). */
196
+ hint: string;
197
+ /** Correlates the device ack; must match prompt.id exactly. */
198
+ id?: string;
199
+ /** Abandoned prompt (Esc in pi) — resolves the request as "unavailable". */
200
+ signal?: AbortSignal;
201
+ /**
202
+ * Optional terminal prompt raced against the device. First answer wins;
203
+ * the loser is dismissed via the abort signal. Resolve null for "the dialog
204
+ * was dismissed without an answer" (Escape, or dismissed because the device
205
+ * already answered) so neither side invents a decision.
206
+ */
207
+ localPrompt?: (signal: AbortSignal) => Promise<boolean | null>;
208
+ }
209
+
210
+ /**
211
+ * How long to stop trying to take the pippi over after a failed attempt, for
212
+ * approval-driven claims only. A background session cannot reach the pet when it
213
+ * is asleep, and paying `claimBudgetMs` on every gated tool call -- while yanking
214
+ * the link from the window the human is in each time -- is worse than asking in
215
+ * the terminal. Enter and `/pippi connect` are human decisions and ignore this.
216
+ */
217
+ const CLAIM_COOLDOWN_MS = 15_000;
218
+
219
+ // Auto-reclaim cadence, after the grace in DEFAULT_CONFIG. The gap doubles so a
220
+ // pippi that is switched off costs one short scan every twenty seconds rather
221
+ // than a hammering on the adapter -- a wedged `org.bluez.Error.InProgress` is
222
+ // what an unbounded retry loop left behind last time this was tried.
223
+ const RECLAIM_MAX_DELAY_MS = 20_000;
224
+ /** How long to listen for advertisements before deciding the pippi is not there. */
225
+ const RECLAIM_SCAN_MS = 2_500;
226
+
227
+ /** `approvalTimeoutMs: 0` means the prompt waits forever, so the mask cannot expire
228
+ * with it: a crashed question would take the pippi out of circulation. */
229
+ const MASK_TTL_NO_TIMEOUT_MS = 300_000;
230
+
231
+ /** How often a claim waiting on somebody else's question asks whether it is over. */
232
+ const MASK_POLL_MS = 250;
233
+
234
+ /**
235
+ * How long a question must have been on the panel before a dropped link counts as something
236
+ * to wait out rather than as a pippi that is gone.
237
+ *
238
+ * The bridge cannot ask the radio whether a snapshot landed: a link that is dead but which
239
+ * BlueZ has not noticed yet looks identical, from here, to one that died a second after the
240
+ * panel drew the question, and the transport only reports the gap some time after the write.
241
+ * So the only evidence available is how long the question has been up. Under this much time
242
+ * nobody has read it, let alone answered it, and holding it buys nothing while a tool call
243
+ * waits; over it, a finger may already be on the button and the question rides the drop.
244
+ *
245
+ * Exported for tests, which have to sit past the window to ask the question they are really
246
+ * asking; a copy of the number in a test file is a number that drifts.
247
+ */
248
+ export const PROMPT_UNSEEN_MS = 1_000;
249
+
250
+ /** How long a mask outlives its last refresh. */
251
+ function maskTtlFor(config: BridgeConfig): number {
252
+ return config.approvalTimeoutMs > 0 ? config.approvalTimeoutMs : MASK_TTL_NO_TIMEOUT_MS;
253
+ }
254
+
255
+ async function withBudget(work: Promise<void>, budgetMs: number): Promise<void> {
256
+ let timer: ReturnType<typeof setTimeout> | undefined;
257
+ await Promise.race([
258
+ work.catch(() => undefined),
259
+ // Not `unref`: this timer is the only thing that ends the wait when the claim
260
+ // underneath never answers, and a caller parked on `await` cannot make progress
261
+ // without it -- see the approval timeout for the symptom.
262
+ new Promise<void>((resolve) => {
263
+ timer = setTimeout(resolve, budgetMs);
264
+ }),
265
+ ]);
266
+ clearTimeout(timer);
267
+ }
268
+
269
+ export interface DeviceStatus {
270
+ name?: string;
271
+ owner?: string;
272
+ sec?: boolean;
273
+ /** The firmware's release stamp; the compatibility handshake's answer. */
274
+ version?: string;
275
+ /** The git-describe build beneath the release stamp, when the firmware has one. */
276
+ build?: string;
277
+ bat?: { pct?: number; mV?: number; mA?: number; usb?: boolean };
278
+ sys?: { up?: number; heap?: number; fsFree?: number; fsTotal?: number };
279
+ stats?: { appr?: number; deny?: number; vel?: number; nap?: number; lvl?: number };
280
+ at: number;
281
+ }
282
+
283
+ export interface BridgeEvents {
284
+ onLog?: (level: "info" | "warn" | "error", message: string) => void;
285
+ onStatus?: (status: DeviceStatus) => void;
286
+ onState?: (state: TransportState) => void;
287
+ /**
288
+ * Pull for context-window pressure, 0-100 percent, shown on the device as
289
+ * the "ctx" gauge. Return null when it cannot be known — pi has no window
290
+ * size before the first model response, and reports usage as unknown right
291
+ * after a compaction — and the field is left off the snapshot so the pet
292
+ * reads "n/a" instead of an empty gauge.
293
+ */
294
+ contextUsage?: () => number | null | undefined;
295
+ /**
296
+ * Pull for the provider allowance or balance row. Unlike the gauge above, the
297
+ * device does not show "n/a" when this is absent: no usage means no row, since
298
+ * what it describes belongs to a session that may have no usage service at all.
299
+ * Return undefined for "nothing to show".
300
+ */
301
+ usage?: () => UsageInfo | undefined;
302
+ }
303
+
304
+ interface ToolRow {
305
+ id: string;
306
+ name: string;
307
+ startedAt: number;
308
+ }
309
+
310
+ let promptCounter = 0;
311
+ function newPromptId(): string {
312
+ promptCounter += 1;
313
+ return `pi${Date.now().toString(36)}${promptCounter.toString(36)}`;
314
+ }
315
+
316
+ export class PippiBridge {
317
+ readonly config: BridgeConfig;
318
+ private readonly transport: BridgeTransport;
319
+ private readonly store: StateStore;
320
+ private readonly events: BridgeEvents;
321
+
322
+ private enabled = true;
323
+ private sessionOpen = false;
324
+ private running = false;
325
+ private completed = false;
326
+ private stopped = false;
327
+ private uiPrompt = false;
328
+ private uiPromptLabel = "";
329
+ private lastActivity = "";
330
+ // The badge key, not the raw provider id: derived once per change by noteProvider
331
+ // so a snapshot cannot go out with a spelling the device has no art for.
332
+ private providerKey?: string;
333
+ private entries: string[] = [];
334
+ private tools = new Map<string, ToolRow>();
335
+ private tokensTotal = 0;
336
+ private tokensToday = 0;
337
+ private dayEpoch = localMidnightEpoch();
338
+ private activePrompt?: {
339
+ id: string;
340
+ tool: string;
341
+ hint: string;
342
+ resolve: (outcome: ApprovalOutcome) => void;
343
+ };
344
+ /**
345
+ * The last approval this session closed, as `<id> → <outcome> (<why>)`.
346
+ *
347
+ * Diagnostics, and the only answer to the one approval failure that is otherwise
348
+ * unobservable: the human presses A, the device answers, and the bridge has already
349
+ * stopped asking -- so it logs "unknown prompt" and the tool call sits in a terminal
350
+ * waiting for an answer the human believes it already got. Naming the outcome that
351
+ * closed the question is what tells a dropped decision apart from a late one.
352
+ */
353
+ private lastPromptClosed?: string;
354
+ /** See `holdPromptThroughDrop`: armed when the link goes down with a question open. */
355
+ private promptGrace?: ReturnType<typeof setTimeout>;
356
+ /**
357
+ * A question this bridge put on the panel, and which the panel therefore has. The
358
+ * difference matters the moment the link goes: a question the panel is holding may
359
+ * already be answered by a finger on **A**, while one that never arrived is merely
360
+ * undeliverable. Set when a snapshot carrying the live prompt id went out over a live
361
+ * link; cleared with the question.
362
+ */
363
+ private promptOnPanel = false;
364
+ /**
365
+ * When the question appeared on the panel, or undefined if it never did. A question that
366
+ * has been up for less than `PROMPT_UNSEEN_MS` has not been seen by anyone, let alone
367
+ * answered, and that is what separates "the link wobbled under a question somebody may
368
+ * already have answered" from "this pippi is gone" -- which the bridge cannot tell apart
369
+ * at write time, because a link BlueZ has not noticed dying looks identical from here.
370
+ */
371
+ private promptDrawnAt?: number;
372
+ private gateChain: Promise<void> = Promise.resolve();
373
+ private pendingAcks = new Map<string, { resolve: (msg: Record<string, unknown>) => void }>();
374
+ private keepalive?: ReturnType<typeof setInterval>;
375
+ private statusPoll?: ReturnType<typeof setInterval>;
376
+ private completeTimer?: ReturnType<typeof setTimeout>;
377
+ private snapshotTimer?: ReturnType<typeof setTimeout>;
378
+ private dirty = false;
379
+ private lastSnapshotAt = 0;
380
+ private lastStatus?: DeviceStatus;
381
+ private versionChecked = false;
382
+ private unsubscribe?: () => void;
383
+
384
+ /**
385
+ * Streaming timings for the assistant response currently in flight. Zero
386
+ * means the mark has not been made: a response that never started cannot be
387
+ * timed, and one that produced no tokens has no decode rate.
388
+ */
389
+ private responseStartMs = 0;
390
+ private firstTokenMs = 0;
391
+ /**
392
+ * Rolling means of the last SPEED_WINDOW samples, tokens/second. A mean and
393
+ * not the last sample because these numbers land on a 6px font next to
394
+ * counters that never move — a reading that jumps 3x between tool calls reads
395
+ * as a glitch rather than a measurement.
396
+ */
397
+ private prefillSamples: number[] = [];
398
+ private decodeSamples: number[] = [];
399
+ private static readonly SPEED_WINDOW = 5;
400
+ /**
401
+ * Sub-50ms windows are dominated by request setup, not by the model. The
402
+ * division is still honest arithmetic, but the number it prints is noise, so
403
+ * the sample is dropped instead.
404
+ */
405
+ private static readonly MIN_TIMED_MS = 50;
406
+
407
+ /** Edge detection on the transport's connected flag, so a one-shot burst runs once per link-up. */
408
+ private linkUp = false;
409
+ private everLinkUp = false;
410
+ private claimFailedAt = 0;
411
+ private claimInFlight?: Promise<void>;
412
+ /**
413
+ * One approval-driven claim at a time. pi runs the gated tool calls of a single
414
+ * assistant turn concurrently, so `requestApproval` can be entered five times in
415
+ * one tick, and each entry used to reach for the radio on its own.
416
+ */
417
+ private approvalClaim?: Promise<void>;
418
+ /** The claim failure already told the human about, so one wall is said once. */
419
+ private lastClaimError = "";
420
+ /** Non-null between an unasked-for link drop and either getting it back or giving up. */
421
+ private reclaim?: { deadline: number; delay: number; startedAt: number };
422
+ private reclaimTimer?: ReturnType<typeof setTimeout>;
423
+ private reclaimScanning = false;
424
+ /**
425
+ * Set when this window is not the one the human is using: another process
426
+ * stamped the claim board more recently, which is a decision made in a window
427
+ * this one cannot see. It is the difference between a status line that says
428
+ * "disconnected" and one that says what actually happened and what ends it, and
429
+ * it clears the next time a keyboard is used here.
430
+ */
431
+ private displaced = false;
432
+ /**
433
+ * Who may claim the pippi, read off a directory of files named by pid. The
434
+ * bridge stamps it on human input and consults it before reaching for the pet on
435
+ * its own, which is the only way to know that another window -- not the pippi --
436
+ * ended its claim. See claims.ts.
437
+ */
438
+ private board: ClaimBoard;
439
+
440
+ constructor(transport: BridgeTransport, store: StateStore, events: BridgeEvents = {}) {
441
+ this.transport = transport;
442
+ this.store = store;
443
+ this.events = events;
444
+ this.config = { ...DEFAULT_CONFIG };
445
+ this.board = new ClaimBoard({ dir: this.config.claimDir });
446
+ this.board.onLog = (level, message) => this.events.onLog?.(level, message);
447
+ this.board.maskTtlMs = maskTtlFor(this.config);
448
+ }
449
+
450
+ // ---------------------------------------------------------------- lifecycle
451
+
452
+ /** Called from pi's session_start. Never throws: a broken device must not break pi. */
453
+ async start(config: Partial<BridgeConfig> = {}): Promise<void> {
454
+ // Keys the caller set explicitly win over persisted state; the rest fall
455
+ // back to whatever a previous session saved.
456
+ const explicit = new Set(
457
+ Object.entries(config)
458
+ .filter(([, value]) => value !== undefined && value !== "")
459
+ .map(([key]) => key),
460
+ );
461
+ Object.assign(this.config, config);
462
+ // The board is process-wide, so config can only re-point it, never replace it
463
+ // mid-flight without stranding the stamp a human already wrote.
464
+ if (config.claimBoard) {
465
+ this.board = config.claimBoard;
466
+ this.board.onLog = (level, message) => this.events.onLog?.(level, message);
467
+ } else if (config.claimDir && config.claimDir !== this.board.dirPath) {
468
+ this.board = new ClaimBoard({ dir: config.claimDir });
469
+ this.board.onLog = (level, message) => this.events.onLog?.(level, message);
470
+ }
471
+ // A mask means as long as a question can still be on the screen, so it ages with
472
+ // the timeout this session is running under rather than with the board's own idea.
473
+ this.board.maskTtlMs = maskTtlFor(this.config);
474
+ this.applyPersisted(explicit);
475
+ this.sessionOpen = true;
476
+ this.linkUp = false;
477
+ this.unsubscribe?.();
478
+ this.unsubscribe = this.transport.subscribe((event) => {
479
+ if (event.type === "line") this.handleDeviceLine(event.line);
480
+ else if (event.type === "state") {
481
+ this.handleTransportState(event.state);
482
+ this.events.onState?.(event.state);
483
+ } else if (event.type === "log") {
484
+ this.events.onLog?.(event.level, event.message);
485
+ } else if (event.type === "claim_lost") {
486
+ this.handleDisplaced(event.holder);
487
+ } else if (event.type === "bond_stale") {
488
+ // The transport stopped dialing for a reason no retry can fix, so the
489
+ // reclaim ladder has nothing left to contribute -- and it is not idle
490
+ // hand-wringing either: every cycle is another refused pairing, another
491
+ // passkey on the panel, and another window's claim checked and re-checked.
492
+ // The sentence the transport logged is the fix; Enter starts dialing over.
493
+ this.endReclaim();
494
+ }
495
+ });
496
+ await this.transport.start().catch((error) => {
497
+ this.events.onLog?.("error", `transport failed to start: ${errorMessage(error)}`);
498
+ });
499
+ this.startTimers();
500
+ // Deliberately not connecting. Several pi processes can be open at once and
501
+ // there is one pippi, so a session that attached merely by starting would
502
+ // steal the pet from the window the human is actually in. `connect` happens
503
+ // on human input (noteUserInput) or on an explicit command.
504
+ if (this.enabled && this.config.device && this.config.device !== "") {
505
+ this.events.onLog?.("info", "standby: press Enter in this session to attach the pippi");
506
+ }
507
+ }
508
+
509
+ /** Called from pi's session_shutdown. Idempotent. */
510
+ async stop(): Promise<void> {
511
+ const wasOpen = this.sessionOpen;
512
+ this.sessionOpen = false;
513
+ this.endReclaim();
514
+ this.stopTimers();
515
+ this.rejectActivePrompt("unavailable", "this session is closing");
516
+ if (wasOpen && this.connected) {
517
+ // Say goodbye. A total:0 snapshot tells the pet the session closed now,
518
+ // instead of leaving it on "busy" until its ~30s snapshot timeout.
519
+ this.running = false;
520
+ this.uiPrompt = false;
521
+ this.completed = false;
522
+ this.sendSnapshot(true);
523
+ }
524
+ this.unsubscribe?.();
525
+ this.unsubscribe = undefined;
526
+ await this.transport.close().catch(() => undefined);
527
+ }
528
+
529
+ setEnabled(enabled: boolean): void {
530
+ this.enabled = enabled;
531
+ this.store.save({ enabled });
532
+ if (!enabled) {
533
+ this.endReclaim();
534
+ void this.transport.close().catch(() => undefined);
535
+ this.stopTimers();
536
+ } else {
537
+ this.startTimers();
538
+ // Enabling is a human decision, so it is what dates the claim -- but the claim
539
+ // is what the rest of this is for, so a stamp that fails stops it here.
540
+ if (this.stampClaim()) void this.connect();
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Our own transport refused to reconnect because the claim board found a stamp newer
546
+ * than ours: a human is working in another window, and BlueZ will let it in
547
+ * whenever it likes. Stand down and say so.
548
+ *
549
+ * This is the only way to find out, which is the entire reason the board exists. A link belongs to the adapter, so the one under us does not have to
550
+ * drop for the pet to stop being ours -- and when it does not drop, this
551
+ * session keeps reporting a pippi it is not attached to, pushing snapshots the
552
+ * device ignores and queueing approval prompts nobody will ever see there. The
553
+ * newest human decision wins, so this one closes the link it no longer owns
554
+ * rather than arguing with a connection.
555
+ */
556
+ private handleDisplaced(holder: number | undefined): void {
557
+ if (!this.sessionOpen) return;
558
+ this.endReclaim();
559
+ this.displaced = true;
560
+ this.events.onLog?.(
561
+ "warn",
562
+ `pid ${holder ?? "?"} claimed the pippi in another window; press Enter here to take it back`,
563
+ );
564
+ void this.transport.close().catch(() => undefined);
565
+ }
566
+
567
+ get isEnabled(): boolean {
568
+ return this.enabled;
569
+ }
570
+
571
+ get kind(): string {
572
+ return this.transport.kind;
573
+ }
574
+
575
+ /**
576
+ * False until this session has held the link. Distinguishes "another session or
577
+ * no attempt yet" from "we attached and then lost it", which are different
578
+ * things to show a human: one needs Enter, the other needs the pippi waking up.
579
+ */
580
+ get hasAttachedOnce(): boolean {
581
+ return this.everLinkUp;
582
+ }
583
+
584
+ get connected(): boolean {
585
+ return this.transport.state.connected;
586
+ }
587
+
588
+ /**
589
+ * True between an unasked-for link drop and getting the pippi back (or giving
590
+ * up): the difference between "disconnected" and "disconnected, working on it".
591
+ */
592
+ get reclaiming(): boolean {
593
+ return this.reclaim !== undefined;
594
+ }
595
+
596
+ /**
597
+ * True while the last word on this link belongs to another window: we stopped
598
+ * chasing because chasing it would be a fight, and only Enter here changes that.
599
+ */
600
+ get fought(): boolean {
601
+ return this.displaced;
602
+ }
603
+
604
+ get state(): TransportState {
605
+ return this.transport.state;
606
+ }
607
+
608
+ get status(): DeviceStatus | undefined {
609
+ return this.lastStatus;
610
+ }
611
+
612
+ scan(timeoutMs?: number): Promise<ScanResult[]> {
613
+ return this.transport.scan(timeoutMs);
614
+ }
615
+
616
+ /** Remember a device and (re)connect to it. */
617
+ async connectTo(target: string, name?: string): Promise<void> {
618
+ this.store.save({ device: target, deviceName: name });
619
+ this.config.device = target;
620
+ if (name !== undefined) this.config.deviceName = name;
621
+ // The device is remembered even when the claim fails -- that was the human's
622
+ // choice, not the radio's -- but the claim is what the connect is, and a failed
623
+ // stamp means it was not made.
624
+ if (!this.stampClaim()) return;
625
+ await this.connect();
626
+ }
627
+
628
+ /**
629
+ * Connect, taking the link from another pi session if it holds one.
630
+ *
631
+ * Every caller is a human decision -- Enter in this window (noteUserInput),
632
+ * `/pippi connect`, `/pippi on`, a tool call that needs an answer from a
633
+ * background session -- except the reclaim ladder, which calls it on its own
634
+ * schedule and is bounded by chaseable() and the claim board instead. Nothing here
635
+ * retries on its own: if it did, N open sessions would each reconnect the moment
636
+ * the pet dropped, which is worse than not connected because it makes the
637
+ * adapter unusable for all of them.
638
+ */
639
+ /**
640
+ * The one route by which this session reaches for the radio, whether the cause is a
641
+ * keystroke or the chase below. What it pointedly does not do is stamp the board:
642
+ * every caller that represents a human decision stamps it first, and if this did too
643
+ * then a retry would date a claim by when the radio got around to it -- which is how a
644
+ * chase makes itself the newest claim on the board forever, in every window,
645
+ * independently.
646
+ */
647
+ async connect(): Promise<void> {
648
+ if (!this.enabled || !this.sessionOpen) return;
649
+ if (!this.config.device || this.config.device === "") return;
650
+ await this.transport.claim(this.config.device).catch((error) => {
651
+ // One failure, one message. A pippi that is asleep, out of range, or behind a
652
+ // wedged BlueZ fails the same way every time, and a session doing work starts a
653
+ // fresh attempt every few seconds -- so the same fact would arrive as a wall of
654
+ // lines and bury the terminal it was meant to inform.
655
+ const message = errorMessage(error);
656
+ if (message === this.lastClaimError) return;
657
+ this.lastClaimError = message;
658
+ this.events.onLog?.("error", `connect failed: ${message}`);
659
+ });
660
+ }
661
+
662
+ /**
663
+ * `/pippi forget`: this session stops wanting the device, so the reclaim policy
664
+ * stops chasing it. The store is the caller's to clear (it also drops the
665
+ * pairing), and the bridge keeps working: typing here just has nothing to
666
+ * attach to until a scan finds a pippi again.
667
+ */
668
+ forgetDevice(): void {
669
+ this.endReclaim();
670
+ this.config.device = undefined;
671
+ this.config.deviceName = undefined;
672
+ }
673
+
674
+ /**
675
+ * Human input arrived in this pi window, so the pippi follows it here.
676
+ *
677
+ * This is the whole session-hopping policy: the pet belongs to whoever the
678
+ * human last typed at, and since there is one human, claims cannot race. It is
679
+ * called for typed input only -- never for agent activity, tool events or
680
+ * timers -- so a busy background session cannot win the device away from the
681
+ * session being driven. Idempotent while already attached, because it is called
682
+ * on every Enter.
683
+ */
684
+ noteUserInput(): void {
685
+ // Stamped before the early returns, and before anything else: this touch is
686
+ // what a claim is drawn from later, including a chase this session starts after
687
+ // the human has walked away from the keyboard. It also ends a lost claim, which
688
+ // is exactly what the message asking for Enter is on about. If the board refused
689
+ // it, this keystroke bought nothing and is not spent: stay as we were -- attached
690
+ // if attached, yielded if yielded -- and let the next Enter ask again.
691
+ if (!this.stampClaim()) return;
692
+ if (!this.enabled || this.connected) return;
693
+ if (this.claimInFlight) return;
694
+ const claim = this.connect();
695
+ this.claimInFlight = claim;
696
+ claim.finally(() => {
697
+ if (this.claimInFlight === claim) this.claimInFlight = undefined;
698
+ });
699
+ }
700
+
701
+ // ------------------------------------------------------------ session model
702
+
703
+ /**
704
+ * Relabel this session on the device's approval line. Marking dirty is the
705
+ * whole point of the method: somebody retags because they are about to look at
706
+ * the pet, and a tag that appeared only at the next keepalive would look broken.
707
+ */
708
+ setTag(tag: string | undefined): void {
709
+ this.config.tag = tag;
710
+ this.markDirty();
711
+ }
712
+
713
+ noteSession(reason: string): void {
714
+ this.sessionOpen = true;
715
+ this.pushEntry(`session ${reason}`);
716
+ this.markDirty();
717
+ }
718
+
719
+ noteAgentStart(): void {
720
+ this.running = true;
721
+ this.completed = false;
722
+ this.stopped = false;
723
+ this.lastActivity = "thinking";
724
+ this.markDirty();
725
+ }
726
+
727
+ /** agent_settled: pi will not continue automatically. Drives "done" / "stopped". */
728
+ noteAgentSettled(aborted: boolean): void {
729
+ this.running = false;
730
+ this.lastActivity = aborted ? "stopped" : "done";
731
+ clearTimeout(this.completeTimer);
732
+ if (aborted) {
733
+ // An abort is not a celebration: the pet gets a brief, distinct signal
734
+ // instead of the completion animation.
735
+ this.stopped = true;
736
+ this.completeTimer = setTimeout(() => {
737
+ this.stopped = false;
738
+ this.markDirty();
739
+ }, 10_000);
740
+ } else {
741
+ this.completed = true;
742
+ this.completeTimer = setTimeout(() => {
743
+ this.completed = false;
744
+ this.markDirty();
745
+ }, 15_000);
746
+ }
747
+ this.completeTimer.unref?.();
748
+ this.markDirty();
749
+ }
750
+
751
+ noteToolStart(toolCallId: string, toolName: string, hint: string): void {
752
+ this.tools.set(toolCallId, { id: toolCallId, name: toolName, startedAt: Date.now() });
753
+ this.lastActivity = toolName;
754
+ this.pushEntry(`${toolName} ${truncateBytes(oneLine(hint), 60)}`.trim());
755
+ this.markDirty();
756
+ }
757
+
758
+ noteToolEnd(toolCallId: string, isError: boolean): void {
759
+ const row = this.tools.get(toolCallId);
760
+ this.tools.delete(toolCallId);
761
+ if (row && isError) {
762
+ this.pushEntry(`✗ ${row.name} failed`);
763
+ this.markDirty();
764
+ }
765
+ }
766
+
767
+ /** ctx.ui.select/confirm/input/editor spans: waiting, but not device-answerable. */
768
+ noteUiPrompt(active: boolean, kind?: string, title?: string): void {
769
+ this.uiPrompt = active;
770
+ this.uiPromptLabel = active ? oneLine(title || kind || "input") : "";
771
+ this.markDirty();
772
+ }
773
+
774
+ /**
775
+ * Who is answering, as pi names it: `event.model.provider` from model_select,
776
+ * and `ctx.model.provider` when a session starts, because restoring a session
777
+ * does not fire model_select and a resumed window would otherwise sit there with
778
+ * no badge on a panel that has been asleep long enough to need one.
779
+ *
780
+ * `undefined` is an answer, and it is "no provider": the device clears its field
781
+ * and draws nothing, which is what a session that has not picked a model yet
782
+ * deserves. A change is the only thing worth a snapshot -- pi re-announces the
783
+ * same model on more events than one would like, and a pet that repaints for
784
+ * those learns nothing.
785
+ */
786
+ noteProvider(provider: string | undefined): void {
787
+ const next = providerBadgeKey(provider);
788
+ if (next === this.providerKey) return;
789
+ this.providerKey = next;
790
+ this.markDirty();
791
+ }
792
+
793
+ /**
794
+ * Timing marks for one assistant response. The bridge measures speed itself
795
+ * because providers report token counts but no clock: `prefill` is prompt
796
+ * tokens over time-to-first-token, `decode` is output tokens over streaming
797
+ * time. Measured from the message stream, so prefill includes whatever the
798
+ * provider spends before the first token (queueing and cache reads) — it is
799
+ * the latency you wait through, which is the number worth glancing at.
800
+ */
801
+ noteResponseStart(): void {
802
+ this.responseStartMs = Date.now();
803
+ this.firstTokenMs = 0;
804
+ }
805
+
806
+ /** First content delta. Later deltas are ignored; only this one is the mark. */
807
+ noteFirstToken(): void {
808
+ if (!this.responseStartMs || this.firstTokenMs) return;
809
+ this.firstTokenMs = Date.now();
810
+ }
811
+
812
+ /**
813
+ * Which half of the response is in progress. Read off the same two marks the
814
+ * speed measurement uses, never tracked alongside them: a phase kept in its
815
+ * own field can disagree with the timestamps that define it, and the status
816
+ * LED would then be wrong about the only thing it is there to say. Both marks
817
+ * clear in noteResponseSpeed, so "finished" needs no third state.
818
+ */
819
+ private responsePhase(): Phase | undefined {
820
+ if (!this.responseStartMs) return undefined;
821
+ return this.firstTokenMs ? "decode" : "prefill";
822
+ }
823
+
824
+ noteResponseSpeed(usage: { input?: number; cacheRead?: number; cacheWrite?: number; output?: number }): void {
825
+ const started = this.responseStartMs;
826
+ const first = this.firstTokenMs;
827
+ if (!started || !first || first < started) return;
828
+ const now = Date.now();
829
+
830
+ const counted = (value: number | undefined): number =>
831
+ Number.isFinite(value) && (value as number) > 0 ? (value as number) : 0;
832
+ // Every prompt token the model had to read, cache hits included: a cached
833
+ // prompt is still processed, and leaving it out would report a slower
834
+ // prefill on exactly the requests that were cheapest.
835
+ const prompt = counted(usage.input) + counted(usage.cacheRead) + counted(usage.cacheWrite);
836
+ const prefillWindow = first - started;
837
+ let sampled = this.pushSample(this.prefillSamples, prompt, prefillWindow);
838
+
839
+ const output = counted(usage.output);
840
+ sampled = this.pushSample(this.decodeSamples, output, now - first) || sampled;
841
+
842
+ this.responseStartMs = 0;
843
+ this.firstTokenMs = 0;
844
+ if (sampled) this.markDirty();
845
+ }
846
+
847
+ /**
848
+ * Add one rate to a rolling window: `tokens` produced in `windowMs`.
849
+ * A rate that needs no division is a rate that had nothing in it, and a
850
+ * window too short to hold is request setup rather than the model -- either
851
+ * way the arithmetic would print noise, so the sample is refused and the
852
+ * caller is told nothing changed. That keeps meanRate a plain mean, with no
853
+ * poison-sample guard needed there too.
854
+ */
855
+ private pushSample(samples: number[], tokens: number, windowMs: number): boolean {
856
+ if (!(tokens > 0) || !(windowMs >= PippiBridge.MIN_TIMED_MS)) return false;
857
+ const rate = tokens / (windowMs / 1000);
858
+ if (!Number.isFinite(rate) || rate <= 0) return false;
859
+ samples.push(rate);
860
+ if (samples.length > PippiBridge.SPEED_WINDOW) samples.shift();
861
+ return true;
862
+ }
863
+
864
+ /** Mean of a sample window, or undefined when nothing has been timed yet. */
865
+ private meanRate(samples: number[]): number | undefined {
866
+ if (!samples.length) return undefined;
867
+ return samples.reduce((sum, n) => sum + n, 0) / samples.length;
868
+ }
869
+
870
+ noteAssistantUsage(outputTokens: number): void {
871
+ if (!Number.isFinite(outputTokens) || outputTokens <= 0) return;
872
+ this.rolloverDay();
873
+ this.tokensTotal += outputTokens;
874
+ this.tokensToday += outputTokens;
875
+ this.store.save({ dayEpoch: this.dayEpoch, tokensToday: this.tokensToday });
876
+ this.markDirty();
877
+ }
878
+
879
+ /**
880
+ * The usage row, if there is one. A snapshot must not fail because a report was
881
+ * shaped oddly on the way here, so anything thrown is treated as "no row".
882
+ */
883
+ private readUsage(): UsageInfo | undefined {
884
+ const provider = this.events.usage;
885
+ if (!provider) return undefined;
886
+ try {
887
+ return provider();
888
+ } catch {
889
+ return undefined;
890
+ }
891
+ }
892
+
893
+ /** A usage report arrived or expired; the row has to travel again. */
894
+ noteUsage(): void {
895
+ this.markDirty();
896
+ }
897
+
898
+ private applyPersisted(explicit: ReadonlySet<string> = new Set()): void {
899
+ let persisted: PersistedState;
900
+ try {
901
+ persisted = this.store.load();
902
+ } catch (error) {
903
+ this.events.onLog?.("warn", `state unavailable: ${errorMessage(error)}`);
904
+ return;
905
+ }
906
+ if (persisted.device && !explicit.has("device")) this.config.device = persisted.device;
907
+ if (persisted.deviceName && !explicit.has("deviceName")) this.config.deviceName = persisted.deviceName;
908
+ if (persisted.approvals && !explicit.has("approvals")) this.config.approvals = persisted.approvals;
909
+ if (persisted.enabled !== undefined) this.enabled = persisted.enabled;
910
+ this.dayEpoch = localMidnightEpoch();
911
+ this.tokensToday = persisted.dayEpoch === this.dayEpoch ? (persisted.tokensToday ?? 0) : 0;
912
+ }
913
+
914
+ private rolloverDay(): void {
915
+ const now = localMidnightEpoch();
916
+ if (now !== this.dayEpoch) {
917
+ this.dayEpoch = now;
918
+ this.tokensToday = 0;
919
+ }
920
+ }
921
+
922
+ // ---------------------------------------------------------------- snapshot
923
+
924
+ private pushEntry(text: string): void {
925
+ const stamped = `${clockTime()} ${truncateBytes(oneLine(text), 80)}`;
926
+ // Newest first, which is what the device's pane and its byte-budget trim both
927
+ // assume: dropping from the tail is dropping the oldest thing the pet knew.
928
+ this.entries = [stamped, ...this.entries.filter((entry) => entry !== stamped)].slice(0, MAX_ENTRIES);
929
+ }
930
+
931
+ buildSnapshot(): Snapshot {
932
+ this.rolloverDay();
933
+ const prompt = this.activePrompt
934
+ ? {
935
+ id: this.activePrompt.id,
936
+ tool: this.activePrompt.tool,
937
+ hint: this.activePrompt.hint,
938
+ tag: this.config.tag,
939
+ }
940
+ : undefined;
941
+ return clampSnapshot({
942
+ total: this.sessionOpen ? 1 : 0,
943
+ running: this.running ? 1 : 0,
944
+ waiting: this.activePrompt ? 1 : this.uiPrompt ? 1 : 0,
945
+ completed: this.completed,
946
+ msg: this.summaryLine(),
947
+ entries: this.entries,
948
+ tokens: this.tokensTotal,
949
+ tokens_today: this.tokensToday,
950
+ ctx: this.readContextUsage(),
951
+ prefill: this.meanRate(this.prefillSamples),
952
+ decode: this.meanRate(this.decodeSamples),
953
+ phase: this.responsePhase(),
954
+ provider: this.providerKey,
955
+ // The usage row is absent rather than zeroed when this session has no usage
956
+ // service, which is the ordinary case and not a failure: the device draws no
957
+ // row, and cannot mistake "we never asked" for "nothing spent".
958
+ usage: this.readUsage(),
959
+ prompt,
960
+ });
961
+ }
962
+
963
+ /**
964
+ * Context-window pressure for the gauge. A gauge is never worth breaking a
965
+ * snapshot over: a caller without a provider, a null/NaN reading, or one
966
+ * that throws all mean the same thing — send no `ctx` and let the device
967
+ * show "n/a".
968
+ */
969
+ private readContextUsage(): number | undefined {
970
+ const provider = this.events.contextUsage;
971
+ if (!provider) return undefined;
972
+ try {
973
+ const percent = provider();
974
+ return percent === null || percent === undefined || !Number.isFinite(percent)
975
+ ? undefined
976
+ : percent;
977
+ } catch {
978
+ return undefined;
979
+ }
980
+ }
981
+
982
+ private summaryLine(): string {
983
+ if (this.activePrompt) return `approve: ${this.activePrompt.tool}`;
984
+ if (this.uiPrompt) return truncateBytes(`needs ${this.uiPromptLabel || "input"}`, 23);
985
+ if (this.running) return this.lastActivity ? `busy: ${this.lastActivity}` : "busy";
986
+ if (this.completed) return "done";
987
+ if (this.stopped) return "stopped";
988
+ return "idle";
989
+ }
990
+
991
+ private markDirty(): void {
992
+ this.dirty = true;
993
+ if (!this.connected) return;
994
+ const sinceLast = Date.now() - this.lastSnapshotAt;
995
+ const wait = Math.max(0, this.config.minSnapshotGapMs - sinceLast);
996
+ if (wait === 0) {
997
+ this.sendSnapshot();
998
+ return;
999
+ }
1000
+ if (this.snapshotTimer) return;
1001
+ this.snapshotTimer = setTimeout(() => {
1002
+ this.snapshotTimer = undefined;
1003
+ this.sendSnapshot();
1004
+ }, wait);
1005
+ this.snapshotTimer.unref?.();
1006
+ }
1007
+
1008
+ private sendSnapshot(force = false): void {
1009
+ if (!this.connected) return;
1010
+ if (!force && !this.dirty) return;
1011
+ this.dirty = false;
1012
+ this.lastSnapshotAt = Date.now();
1013
+ const line = encodeSnapshot(this.buildSnapshot());
1014
+ this.transport.write(line);
1015
+ // Written, not merely composed: this is the point at which the panel has the question
1016
+ // and a press on it means something. `buildSnapshot` puts the live prompt in its own
1017
+ // snapshots, so the id is the test -- an old question in a late snapshot must not
1018
+ // vouch for a new one.
1019
+ if (this.activePrompt && line.includes(this.activePrompt.id)) {
1020
+ this.promptOnPanel = true;
1021
+ this.promptDrawnAt ??= Date.now();
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * Look up, on a schedule, the one thing that is otherwise invisible from here:
1027
+ * that this session no longer owns the pippi.
1028
+ *
1029
+ * A BlueZ link belongs to the adapter rather than to the process that opened it,
1030
+ * which was measured, not theorized: with one window holding the link, a second
1031
+ * window's claim connected, both sessions' replies arrived interleaved, and the
1032
+ * first window never saw a disconnect -- it kept reporting an attached pet and
1033
+ * writing snapshots to a device that had moved on, queueing approval prompts no
1034
+ * one would ever read on it. When the link does drop, `claim_lost` already tells
1035
+ * us. When it does not, this is the only way to find out, and the keepalive is
1036
+ * the only moment we are guaranteed to be looking.
1037
+ *
1038
+ * Only a newer stamp means a takeover. A mask means another window is holding a
1039
+ * question, which is nobody's business but the one asking it -- the pet is not
1040
+ * changing hands, so neither do we.
1041
+ */
1042
+ private noticeIfTaken(): void {
1043
+ if (!this.connected) return;
1044
+ const verdict = this.board.check();
1045
+ if (verdict.allowed || verdict.reason !== "stale") return;
1046
+ this.handleDisplaced(verdict.beatenBy);
1047
+ }
1048
+
1049
+ private startTimers(): void {
1050
+ if (!this.keepalive) {
1051
+ this.keepalive = setInterval(() => {
1052
+ this.noticeIfTaken();
1053
+ this.sendSnapshot(true);
1054
+ }, this.config.keepaliveMs);
1055
+ this.keepalive.unref?.();
1056
+ }
1057
+ if (!this.statusPoll) {
1058
+ this.statusPoll = setInterval(() => {
1059
+ if (this.connected) void this.pollStatus();
1060
+ }, this.config.statusPollMs);
1061
+ this.statusPoll.unref?.();
1062
+ }
1063
+ }
1064
+
1065
+ private stopTimers(): void {
1066
+ clearInterval(this.keepalive);
1067
+ clearInterval(this.statusPoll);
1068
+ clearTimeout(this.snapshotTimer);
1069
+ clearTimeout(this.completeTimer);
1070
+ this.keepalive = undefined;
1071
+ this.statusPoll = undefined;
1072
+ this.snapshotTimer = undefined;
1073
+ }
1074
+
1075
+ private handleTransportState(state: TransportState): void {
1076
+ if (state.connected) {
1077
+ // The question, if there is one, is on the panel again -- see holdPromptThroughDrop.
1078
+ clearTimeout(this.promptGrace);
1079
+ this.promptGrace = undefined;
1080
+ // Transports may repeat the same state; re-running the burst would put
1081
+ // duplicate time/owner/status/snapshot frames on the wire.
1082
+ if (this.linkUp) return;
1083
+ this.linkUp = true;
1084
+ this.everLinkUp = true;
1085
+ this.versionChecked = false;
1086
+ this.claimFailedAt = 0;
1087
+ this.lastClaimError = "";
1088
+ this.displaced = false;
1089
+ this.noteReclaimed();
1090
+ // One-shot on connect: time sync then owner (REFERENCE.md).
1091
+ this.transport.write(encodeLine(timeSync()));
1092
+ if (this.config.owner) {
1093
+ this.transport.write(encodeLine({ cmd: "owner", name: this.config.owner }));
1094
+ }
1095
+ void this.pollStatus();
1096
+ this.sendSnapshot(true);
1097
+ } else {
1098
+ const wasUp = this.linkUp;
1099
+ this.linkUp = false;
1100
+ if (wasUp && this.enabled) {
1101
+ // The pet is gone, and the two ways that happens are indistinguishable
1102
+ // from here: the human took it to another window, or the pippi fell over.
1103
+ // What used to settle that was a heuristic about how recently this session
1104
+ // had the link, and it settled it wrong often enough to trade the pet
1105
+ // between two windows nine times in a minute. Now the question goes to the
1106
+ // claim board, where the answer is a fact rather than a guess -- and the
1107
+ // transport is closed either way, because a link left held would
1108
+ // reconnect without asking anybody.
1109
+ if (this.chaseable()) this.armReclaim();
1110
+ else void this.transport.close().catch(() => undefined);
1111
+ }
1112
+ // The link went away with a question up. It does not answer it, so an answer can
1113
+ // no longer arrive *for now* -- but the panel still shows the question, so the
1114
+ // question is not over either. See holdPromptThroughDrop for why this stopped being
1115
+ // a `rejectActivePrompt`, and note the ordering: the snapshot that re-draws it is
1116
+ // sent by the up branch, which is also where the grace is cancelled.
1117
+ this.holdPromptThroughDrop();
1118
+ }
1119
+ }
1120
+
1121
+ /**
1122
+ * True when there is a saved pippi worth chasing, this session has ever been
1123
+ * typed at, and nothing in it says "leave it alone" (`/pippi off` and
1124
+ * session_shutdown both `endReclaim` and clear any timer already running).
1125
+ *
1126
+ * The stamp on the claim board is not decoration: a session only ever reaches for
1127
+ * the pippi without being asked if a human asked for it here once. A background
1128
+ * agent that attached through an approval has no such stamp, so when the human's
1129
+ * Enter in another window takes the pet, the background session lets go instead
1130
+ * of helping itself back.
1131
+ */
1132
+ private chaseable(): boolean {
1133
+ return (
1134
+ this.sessionOpen &&
1135
+ this.config.reclaimMs > 0 &&
1136
+ !this.displaced &&
1137
+ this.board.hasOwnStamp() &&
1138
+ (this.config.device ?? "") !== ""
1139
+ );
1140
+ }
1141
+
1142
+ /**
1143
+ * Whether this session may reach for the pippi on its own, which is not the same
1144
+ * question as whether a human asked it to. Says so out loud when the answer is no,
1145
+ * because the reason it is no is another window -- invisible from here in every
1146
+ * other way -- and "press Enter there, or here" is the whole of what a human can
1147
+ * do about it.
1148
+ */
1149
+ private boardAllowsClaim(): boolean {
1150
+ const verdict = this.board.check();
1151
+ if (verdict.allowed) return true;
1152
+ this.displaced = true;
1153
+ this.events.onLog?.("warn", this.boardReason(verdict));
1154
+ return false;
1155
+ }
1156
+
1157
+ /**
1158
+ * Date this window's claim on behalf of a human decision, and answer whether this
1159
+ * session may now act. A claim *is* this date -- the board is not a record of a
1160
+ * claim, it is the claim -- so a stamp that could not be written means there was no
1161
+ * claim to make, and the pippi stays exactly where it is until the human asks again.
1162
+ * The write failing is not a fault to work around: it may be the filesystem refusing
1163
+ * exactly the collision the board exists to avoid.
1164
+ */
1165
+ private stampClaim(): boolean {
1166
+ if (!this.board.touch()) return false;
1167
+ this.displaced = false;
1168
+ return true;
1169
+ }
1170
+
1171
+ /**
1172
+ * Two refusals, because they have two remedies. Somebody else was typed in more
1173
+ * recently: pressing Enter here settles that. Somebody else has a question on the
1174
+ * screen: pressing Enter here would be interrupting it, and the asking does not have
1175
+ * to happen on the pet at all.
1176
+ */
1177
+ private boardReason(verdict: { beatenBy: number; ageMs: number; reason: "masked" | "stale" }): string {
1178
+ const age = Math.max(1, Math.round(verdict.ageMs / 1000));
1179
+ return verdict.reason === "masked"
1180
+ ? `pid ${verdict.beatenBy} has a question on the pippi; leaving the pippi with it`
1181
+ : `another window (pid ${verdict.beatenBy}) was typed in ${age}s ago; ` +
1182
+ "leaving the pippi with it -- press Enter here to take it back";
1183
+ }
1184
+
1185
+ /**
1186
+ * Take back a pippi that dropped by itself, on the strength of the last time a
1187
+ * human asked for it in this window.
1188
+ *
1189
+ * Each attempt asks whether the pippi is advertising first, which is the closest
1190
+ * thing to asking whether another window has it: a connected peripheral stops
1191
+ * advertising, so a pippi a window *holds* cannot be found. What the scan cannot
1192
+ * see is a window *claiming* -- a claim is release_link and then a 4-6s connect,
1193
+ * and for those seconds the pippi is advertising and looks free to everybody.
1194
+ * That is why the scan is not what keeps two windows honest, and cannot be: the
1195
+ * claim board is. Every attempt here asks it first, so a chase stops the moment
1196
+ * another window becomes the one a human touched last -- and the grace above is
1197
+ * what makes the first collision rare enough to ignore. Worst case: one flap, no
1198
+ * loop, and Enter anywhere ends it.
1199
+ *
1200
+ * The transport is closed on the way in deliberately: its own link loop
1201
+ * reconnects with no idea who might be holding the link, and that decision belongs
1202
+ * to the bridge.
1203
+ */
1204
+ private armReclaim(): void {
1205
+ void this.transport.close().catch(() => undefined);
1206
+ if (this.reclaim) return;
1207
+ const now = Date.now();
1208
+ this.reclaim = {
1209
+ deadline: now + this.config.reclaimMs,
1210
+ delay: this.config.reclaimFirstMs,
1211
+ startedAt: now,
1212
+ };
1213
+ this.events.onLog?.("info", "pippi link lost; taking it back");
1214
+ this.scheduleReclaim();
1215
+ }
1216
+
1217
+ private scheduleReclaim(): void {
1218
+ if (!this.reclaim) return;
1219
+ clearTimeout(this.reclaimTimer);
1220
+ this.reclaimTimer = setTimeout(() => {
1221
+ this.reclaimTimer = undefined;
1222
+ void this.reclaimOnce();
1223
+ }, this.reclaim.delay);
1224
+ this.reclaimTimer.unref?.();
1225
+ }
1226
+
1227
+ private async reclaimOnce(): Promise<void> {
1228
+ const cycle = this.reclaim;
1229
+ if (!cycle || !this.enabled || !this.sessionOpen) return this.endReclaim();
1230
+ if (this.connected) return this.endReclaim();
1231
+ // A scan while the human's own claim is in flight would race it, and losing
1232
+ // that race means nothing good: their Enter is the newer decision.
1233
+ if (this.claimInFlight || this.reclaimScanning) {
1234
+ this.scheduleReclaim();
1235
+ return;
1236
+ }
1237
+ // The board is asked before the radio is, on every attempt: it is two syscalls,
1238
+ // and it is the only thing that can tell a pippi another window is holding from
1239
+ // a pippi that fell over. A chase that ignores it is a claim, and a claim is a
1240
+ // disconnect on whoever has the link.
1241
+ if (!this.boardAllowsClaim()) return this.endReclaim();
1242
+ if (Date.now() >= cycle.deadline) {
1243
+ this.endReclaim();
1244
+ this.events.onLog?.(
1245
+ "warn",
1246
+ `pippi did not come back after ${Math.max(1, Math.round(this.config.reclaimMs / 1000))}s; press Enter here to attach it`,
1247
+ );
1248
+ return;
1249
+ }
1250
+ this.reclaimScanning = true;
1251
+ const waiting = await this.pippiWaiting();
1252
+ this.reclaimScanning = false;
1253
+ // Either the timer was cancelled (a claim landed, the bridge was turned off)
1254
+ // or a newer drop re-armed it while the scan was out; either way this
1255
+ // continuation has no business scheduling a second attempt on top of it.
1256
+ if (!this.reclaim) return;
1257
+ if (waiting) await this.connect();
1258
+ if (!this.reclaim || this.connected) return;
1259
+ cycle.delay = Math.min(cycle.delay * 2, RECLAIM_MAX_DELAY_MS);
1260
+ this.scheduleReclaim();
1261
+ }
1262
+
1263
+ /**
1264
+ * Is the pippi awake and unclaimed right now? A scan that fails and a scan
1265
+ * that found nothing get the same answer -- not found -- and both mean "ask
1266
+ * again later" rather than "grab it anyway", so a busy adapter cannot turn
1267
+ * into a link stolen from another window.
1268
+ */
1269
+ private async pippiWaiting(): Promise<boolean> {
1270
+ const device = (this.config.device ?? "").trim().toLowerCase();
1271
+ const name = (this.config.deviceName ?? "").trim().toLowerCase();
1272
+ if (!device) return false;
1273
+ try {
1274
+ const seen = await this.transport.scan(RECLAIM_SCAN_MS);
1275
+ return seen.some((r) => {
1276
+ const address = (r.address ?? "").trim().toLowerCase();
1277
+ const found = (r.name ?? "").trim().toLowerCase();
1278
+ return address === device || (found !== "" && found === name);
1279
+ });
1280
+ } catch {
1281
+ return false;
1282
+ }
1283
+ }
1284
+
1285
+ /** Stop chasing without a word: used when something else already explained it. */
1286
+ private endReclaim(): void {
1287
+ clearTimeout(this.reclaimTimer);
1288
+ this.reclaimTimer = undefined;
1289
+ this.reclaim = undefined;
1290
+ }
1291
+
1292
+ /** Called from the link-up edge: the chase is over, and it worked. */
1293
+ private noteReclaimed(): void {
1294
+ if (!this.reclaim) return;
1295
+ const secs = Math.max(1, Math.round((Date.now() - this.reclaim.startedAt) / 1000));
1296
+ this.endReclaim();
1297
+ this.events.onLog?.("info", `pippi back after ${secs}s`);
1298
+ }
1299
+
1300
+ // ------------------------------------------------------------- device lines
1301
+
1302
+ private handleDeviceLine(line: Record<string, unknown>): void {
1303
+ if (line.ack !== undefined) {
1304
+ const waiter = this.pendingAcks.get(String(line.ack));
1305
+ if (waiter) {
1306
+ this.pendingAcks.delete(String(line.ack));
1307
+ waiter.resolve(line);
1308
+ }
1309
+ return;
1310
+ }
1311
+ if (line.cmd === "permission") {
1312
+ const decision = line as unknown as PermissionDecision;
1313
+ const active = this.activePrompt;
1314
+ if (!active || decision.id !== active.id) {
1315
+ // An error, not a warning, and it reaches the window: a human pressed a button on
1316
+ // the device, saw the pet acknowledge it, and nothing happened to their tool call.
1317
+ // Silent is the one thing this branch may not be.
1318
+ this.events.onLog?.(
1319
+ "error",
1320
+ `answer for ${decision.id} arrived while ${
1321
+ active ? `a different question was open (${active.id})` : "no question was open"
1322
+ }` +
1323
+ (this.lastPromptClosed ? `; the last question closed as ${this.lastPromptClosed}` : "") +
1324
+ ". The tool call is still waiting where it was asked.",
1325
+ );
1326
+ return;
1327
+ }
1328
+ const outcome = decision.decision === "once" ? "once" : "deny";
1329
+ this.events.onLog?.("info", `${decision.id} answered ${outcome} on the pippi`);
1330
+ active.resolve(outcome);
1331
+ return;
1332
+ }
1333
+ // Anything else (unexpected cmd, future firmware events) is just liveness.
1334
+ }
1335
+
1336
+ /** Send a command with a `cmd` field and await its matching ack. */
1337
+ async sendCommand(
1338
+ cmd: string,
1339
+ payload: Record<string, unknown> = {},
1340
+ timeoutMs = 5_000,
1341
+ ): Promise<Record<string, unknown>> {
1342
+ if (!this.connected) return { ack: cmd, ok: false, error: "not connected" };
1343
+ if (this.pendingAcks.has(cmd)) return { ack: cmd, ok: false, error: "command in flight" };
1344
+ return await new Promise<Record<string, unknown>>((resolve) => {
1345
+ const timer = setTimeout(() => {
1346
+ if (this.pendingAcks.delete(cmd)) resolve({ ack: cmd, ok: false, error: "ack timeout" });
1347
+ }, timeoutMs);
1348
+ timer.unref?.();
1349
+ this.pendingAcks.set(cmd, {
1350
+ resolve: (msg) => {
1351
+ clearTimeout(timer);
1352
+ resolve(msg);
1353
+ },
1354
+ });
1355
+ this.transport.write(encodeLine({ cmd, ...payload }));
1356
+ });
1357
+ }
1358
+
1359
+ async pollStatus(): Promise<DeviceStatus | undefined> {
1360
+ const ack = await this.sendCommand("status", {}, 4_000);
1361
+ if (!ack.ok) return undefined;
1362
+ const status = { ...(ack.data as Record<string, unknown> | undefined), at: Date.now() } as DeviceStatus;
1363
+ this.lastStatus = status;
1364
+ // The compatibility handshake (REFERENCE.md): the first status ack after a
1365
+ // connect names the firmware, and we compare it against the floor this
1366
+ // bridge was tested against. Once per link, because the poll repeats every
1367
+ // couple of seconds and the same warning on every beat is noise that
1368
+ // buries the one useful line.
1369
+ if (this.linkUp && !this.versionChecked) {
1370
+ this.versionChecked = true;
1371
+ const cmp = typeof status.version === "string"
1372
+ ? compareVersions(status.version, MIN_FIRMWARE_VERSION)
1373
+ : null;
1374
+ if (cmp === null) {
1375
+ this.events.onLog?.(
1376
+ "warn",
1377
+ `firmware did not report a version; expected at least v${MIN_FIRMWARE_VERSION} -- treating it as unknown, not compatible`,
1378
+ );
1379
+ } else if (cmp < 0) {
1380
+ this.events.onLog?.(
1381
+ "warn",
1382
+ `firmware version v${status.version} is older than this bridge's floor v${MIN_FIRMWARE_VERSION}; fields may go missing`,
1383
+ );
1384
+ }
1385
+ }
1386
+ this.events.onStatus?.(status);
1387
+ return status;
1388
+ }
1389
+
1390
+ // ------------------------------------------------------------- approval gate
1391
+
1392
+ /**
1393
+ * Ask the human to approve a tool call. Queued: the device shows one prompt
1394
+ * at a time, so concurrent tool calls line up rather than clobber each
1395
+ * other's prompt id.
1396
+ */
1397
+ async requestApproval(request: ApprovalRequest): Promise<ApprovalOutcome> {
1398
+ if (!this.enabled || this.config.approvals === "off") {
1399
+ return Promise.resolve("unavailable" as const);
1400
+ }
1401
+ if (!this.connected) {
1402
+ // A question that blocks a tool is worth interrupting another session for:
1403
+ // wherever the human is looking, that is where the answer has to be given.
1404
+ // But the radio may simply be off, and a tool call must not be parked behind
1405
+ // it -- so the wait is budgeted, and failures cool off. A claim that lands
1406
+ // later still attaches.
1407
+ // Read before the claim, not after: if the claim is what takes a while, an abort
1408
+ // during it is a human who changed their mind, and that must not be mistaken for
1409
+ // a claim nobody made.
1410
+ const humanInitiated = request.signal === undefined || !request.signal.aborted;
1411
+ await this.claimForApproval(humanInitiated);
1412
+ if (!this.connected) return "unavailable" as const;
1413
+ return this.queueApproval(request);
1414
+ }
1415
+ return this.queueApproval(request);
1416
+ }
1417
+
1418
+ private claimForApproval(humanInitiated = false): Promise<void> {
1419
+ if (this.claimFailedAt !== 0 && Date.now() - this.claimFailedAt < CLAIM_COOLDOWN_MS) return Promise.resolve();
1420
+ // Shared, not per call. Five gated tool calls in one turn are one trip to the
1421
+ // radio: without this each of them put a `Disconnect` on the bus, started its own
1422
+ // dial, and had that dial taken away by the next one -- five disconnects and four
1423
+ // logged failures for what is one attempt to ask one question.
1424
+ this.approvalClaim ??= this.acquireApprovalClaim(humanInitiated).finally(() => {
1425
+ this.approvalClaim = undefined;
1426
+ });
1427
+ return this.approvalClaim;
1428
+ }
1429
+
1430
+ private async acquireApprovalClaim(humanInitiated: boolean): Promise<void> {
1431
+ // An approval does not go through the board's ranking, and it is worth being exact
1432
+ // about why: the other window is not asking anything, this one has a tool call
1433
+ // parked on an answer that has to be given where a human can see it, and losing
1434
+ // that contest to an idle window is how a question ends up with nobody in it.
1435
+ // What it does respect is a question already on the screen -- so it waits for the
1436
+ // mask, then claims, then puts its own question up and masks the rest.
1437
+ if (!(await this.waitForMask())) return;
1438
+ await this.preDelayFor(humanInitiated ? "human" : "approval");
1439
+ // The first mask is a reservation, taken before the radio is touched: a question
1440
+ // five seconds away from being on the screen should already keep another window
1441
+ // from settling in. The prompt's own `touchMask` then restamps it, and that second
1442
+ // write is the one the arithmetic runs on -- the deadline moves to when the question
1443
+ // actually appeared, which is when the pet's dialog started its own count.
1444
+ this.board.touchMask();
1445
+ // The mask is written whether or not the claim can be, because the question is
1446
+ // real either way: it gets asked in the terminal regardless. What a failed stamp
1447
+ // cancels is asking it of the pet -- no claim, no radio.
1448
+ if (this.stampClaim()) await withBudget(this.connect(), this.config.claimBudgetMs);
1449
+ if (!this.connected) {
1450
+ this.claimFailedAt = Date.now();
1451
+ this.board.clearMask();
1452
+ }
1453
+ }
1454
+
1455
+ /**
1456
+ * How long to sit before taking the radio, depending on who asked. A human-driven
1457
+ * claim is capped by the approval timeout it is parked behind -- delaying a claim
1458
+ * past the moment its own question stops mattering is just a longer way of failing
1459
+ * -- and a claim nobody is waiting on gets the configured grace.
1460
+ */
1461
+ private async preDelayFor(priority: "human" | "approval"): Promise<void> {
1462
+ // Nothing held and nothing targetable: there is no handover in flight to protect,
1463
+ // and a session with no pippi configured has to fall through to the terminal right
1464
+ // away -- waiting first would be a silent tax on every gated tool call in a window
1465
+ // that is not using the pet at all.
1466
+ if (this.connected || (this.config.device ?? "") === "") return;
1467
+ const configured = this.config.claimPreDelayMs;
1468
+ const ms = priority === "human"
1469
+ ? Math.min(configured, this.config.approvalTimeoutMs)
1470
+ : configured;
1471
+ if (ms <= 0) return;
1472
+ await new Promise((resolve) => setTimeout(resolve, ms));
1473
+ }
1474
+
1475
+ /**
1476
+ * Wait out another session's question. Bounded by that question's own timeout -- the
1477
+ * clock it runs on is not ours, and past that point it is either answered or gone --
1478
+ * and then the ask falls back to the terminal, which is the degraded path the bridge
1479
+ * already has for a pippi it cannot reach.
1480
+ */
1481
+ private async waitForMask(): Promise<boolean> {
1482
+ for (;;) {
1483
+ const held = this.board.maskHeld();
1484
+ if (held === undefined) return true;
1485
+ // The wait is the mask's remaining life and nothing more. Somebody else's
1486
+ // question has a start time in that file's mtime and a length in a constant both
1487
+ // processes read the same way, so the moment it stops meaning anything is
1488
+ // computable rather than something to poll for and hope about -- waiting the full
1489
+ // timeout from here would be a second question's worth of delay charged to this
1490
+ // one, and waiting past it at all would mean this session outlasted the only
1491
+ // evidence it was acting on.
1492
+ const left = this.board.maskTtlMs - held.ageMs;
1493
+ if (left <= 0) {
1494
+ this.events.onLog?.(
1495
+ "warn",
1496
+ `pid ${this.board.maskOwner()} has had a question on the pippi for ` +
1497
+ `${Math.max(1, Math.round(held.ageMs / 1000))}s; asking in the terminal`,
1498
+ );
1499
+ return false;
1500
+ }
1501
+ await new Promise((resolve) => setTimeout(resolve, Math.min(MASK_POLL_MS, left)));
1502
+ }
1503
+ }
1504
+
1505
+ private queueApproval(request: ApprovalRequest): Promise<ApprovalOutcome> {
1506
+ const run = this.gateChain.then(() => this.runApproval(request));
1507
+ // Keep the queue alive even if a single approval rejects.
1508
+ this.gateChain = run.then(
1509
+ () => undefined,
1510
+ () => undefined,
1511
+ );
1512
+ return run;
1513
+ }
1514
+
1515
+ private runApproval(request: ApprovalRequest): Promise<ApprovalOutcome> {
1516
+ if (!this.connected) return Promise.resolve("unavailable");
1517
+ const id = request.id ?? newPromptId();
1518
+ const tool = truncateBytes(oneLine(request.tool), 19);
1519
+ const hint = truncateBytes(oneLine(request.hint), MAX_PROMPT_HINT_BYTES);
1520
+
1521
+ return new Promise<ApprovalOutcome>((resolve) => {
1522
+ const controller = new AbortController();
1523
+ let settled = false;
1524
+ let timer: ReturnType<typeof setTimeout> | undefined;
1525
+
1526
+ const finish = (outcome: ApprovalOutcome, why = "") => {
1527
+ if (settled) return;
1528
+ settled = true;
1529
+ this.lastPromptClosed = `${id} → ${outcome}${why ? ` (${why})` : ""}`;
1530
+ clearTimeout(timer);
1531
+ // The question is answered, so a link that went down underneath it has no more
1532
+ // claim on anyone's attention.
1533
+ clearTimeout(this.promptGrace);
1534
+ this.promptGrace = undefined;
1535
+ this.promptOnPanel = false;
1536
+ this.promptDrawnAt = undefined;
1537
+ this.board.clearMask();
1538
+ request.signal?.removeEventListener("abort", onAbort);
1539
+ controller.abort();
1540
+ this.activePrompt = undefined;
1541
+ this.sendSnapshot(true);
1542
+ resolve(outcome);
1543
+ };
1544
+ // pi's own abort signal, which is the agent's, not the human's: a new message, an
1545
+ // Escape, or anything else that cancels the tool call lands here. It is worth
1546
+ // naming in the log because it is the one path where the pippi's answer can arrive
1547
+ // for a question this session has already given up on.
1548
+ const onAbort = () => finish("unavailable", "pi called off the tool call");
1549
+
1550
+ this.activePrompt = { id, tool, hint, resolve: finish };
1551
+ this.promptOnPanel = false;
1552
+ this.promptDrawnAt = undefined;
1553
+ request.signal?.addEventListener("abort", onAbort, { once: true });
1554
+ // Mask, then draw, and only once. The mtime of that file is when the question
1555
+ // started -- the same instant the pet's own dialog starts -- and every party
1556
+ // decides whether the question is still live by the same subtraction against the
1557
+ // same constant. Refreshing it would move the start time, which is the one thing
1558
+ // the arithmetic is not allowed to lose: a refreshed mask is an approval that
1559
+ // outlives its own timeout and quietly grounds every other window on the machine.
1560
+ // The claim stamp beside it is a different matter: this session already made its
1561
+ // claim to get here, so a stamp that fails at this point costs the pet's screen
1562
+ // and does not call off a question the human is about to answer in the terminal.
1563
+ this.stampClaim();
1564
+ this.board.touchMask();
1565
+ this.sendSnapshot(true);
1566
+
1567
+ if (this.config.approvalTimeoutMs > 0) {
1568
+ // Ref'd, on purpose, and this line is the whole approval contract. A timer can
1569
+ // be marked `unref` to tell node not to stay alive for it, and this one was --
1570
+ // which reads as harmless, because the process has a terminal and a radio and
1571
+ // something else always pending. But somebody is waiting on the *outcome* of
1572
+ // this timer: an awaited tool call has no other way to end. So on a quiet
1573
+ // process the loop empties, node exits with the await abandoned, and the session
1574
+ // side of an approval waits forever while the device clears its own prompt on
1575
+ // schedule. Anything that resolves a promise somebody is holding is a handle.
1576
+ timer = setTimeout(() => finish("timeout", "no answer in time"), this.config.approvalTimeoutMs);
1577
+ }
1578
+
1579
+ if (request.localPrompt) {
1580
+ void Promise.resolve()
1581
+ .then(() => request.localPrompt!(controller.signal))
1582
+ .then((answer) => {
1583
+ if (answer === null || answer === undefined) return;
1584
+ finish(answer ? "once" : "deny", "answered in the terminal");
1585
+ })
1586
+ .catch(() => {
1587
+ /* no local answer; the device and the timeout still apply */
1588
+ });
1589
+ }
1590
+ });
1591
+ }
1592
+
1593
+ private rejectActivePrompt(outcome: ApprovalOutcome, why: string): void {
1594
+ const id = this.activePrompt?.id;
1595
+ if (id) {
1596
+ this.lastPromptClosed = `${id} → ${outcome} (${why})`;
1597
+ this.events.onLog?.("warn", `calling off ${id}: ${why}`);
1598
+ }
1599
+ this.activePrompt?.resolve(outcome);
1600
+ this.activePrompt = undefined;
1601
+ }
1602
+
1603
+ /**
1604
+ * The link went down with a question outstanding. The question stays open.
1605
+ *
1606
+ * It used to be called off here, and that was wrong in a way the panel cannot show:
1607
+ * the device keeps drawing a question it was never told to clear, the human presses A,
1608
+ * the answer arrives for a prompt this session stopped tracking -- and the tool call is
1609
+ * still waiting in a terminal, for a decision they believe they already gave. A button
1610
+ * press on a screen that still shows the question is a fact about the world, and the
1611
+ * bridge has no business disagreeing with it.
1612
+ *
1613
+ * So the prompt rides the drop. `handleTransportState` sends a snapshot when the link
1614
+ * comes back and `buildSnapshot` derives the prompt from `activePrompt`, so the same
1615
+ * question with the same id goes back to the panel and an answer to it resolves again.
1616
+ * The grace timer is what keeps a pippi that is really gone from turning that into an
1617
+ * infinite wait, and it is the only thing standing between `approvalTimeoutMs: 0` and a
1618
+ * tool call that never ends because a device was switched off.
1619
+ */
1620
+ private holdPromptThroughDrop(): void {
1621
+ const active = this.activePrompt;
1622
+ if (!active || this.promptGrace) return;
1623
+ const grace = this.config.promptLinkGraceMs;
1624
+ const drawnFor = this.promptDrawnAt === undefined ? -1 : Date.now() - this.promptDrawnAt;
1625
+ if (!this.promptOnPanel || grace <= 0 || drawnFor < PROMPT_UNSEEN_MS) {
1626
+ // Either the panel never had it, or it has had it for less than a second: nobody could
1627
+ // have answered it yet, so there is no press in flight to honour. A pippi that cannot
1628
+ // be reached is undeliverable, which is not the same as unanswered, and the session
1629
+ // should hear that now rather than after a grace nobody could use. (The transport
1630
+ // reports a dead link late, so "how long the question was up" is the only evidence this
1631
+ // side of the radio has that the question was ever drawn at all.)
1632
+ this.rejectActivePrompt("unavailable", "the link went down before anyone could answer");
1633
+ return;
1634
+ }
1635
+ // The approval timer keeps running. It is the human's deadline for answering, not the
1636
+ // radio's, and a second of Bluetooth is not a reason to hand them more time: pausing it
1637
+ // would need the timer hoisted out of `runApproval` into a field and a resume path, for a
1638
+ // story ("the radio ate my timeout") nobody acting on the outcome cares about. What the
1639
+ // grace adds on top is a second, shorter bound, and it is the one that decides what a
1640
+ // pippi that never comes back is called -- `unavailable`, not `timeout`.
1641
+ this.events.onLog?.(
1642
+ "info",
1643
+ `link dropped with ${active.id} on the panel; holding the question for ${Math.round(grace / 1000)}s`,
1644
+ );
1645
+ this.promptGrace = setTimeout(() => {
1646
+ this.promptGrace = undefined;
1647
+ this.rejectActivePrompt("unavailable", `the pippi had not come back in ${Math.round(grace / 1000)}s`);
1648
+ }, grace);
1649
+ }
1650
+
1651
+ // ------------------------------------------------------------- turn events
1652
+
1653
+ sendTurn(role: "assistant", content: unknown[]): void {
1654
+ if (!this.config.turnEvents || !this.connected) return;
1655
+ const event: TurnEvent = { evt: "turn", role, content };
1656
+ const line = encodeTurn(event);
1657
+ if (line) this.transport.write(line);
1658
+ else this.events.onLog?.("info", "turn event dropped (too large)");
1659
+ }
1660
+
1661
+ // ------------------------------------------------------------- folder push
1662
+
1663
+ /**
1664
+ * Stream a flat character folder to the device (REFERENCE.md "Folder push").
1665
+ * Sequential and ack-driven; the device decodes as it goes.
1666
+ */
1667
+ async pushCharacter(
1668
+ files: Array<{ name: string; data: Buffer }>,
1669
+ options: { name?: string; total?: number; onProgress?: (sent: number, total: number) => void } = {},
1670
+ ): Promise<{ ok: boolean; error?: string }> {
1671
+ if (!this.connected) return { ok: false, error: "not connected" };
1672
+ const total = options.total ?? files.reduce((sum, file) => sum + file.data.length, 0);
1673
+ const begin = await this.sendCommand("char_begin", { name: options.name ?? "pet", total }, 6_000);
1674
+ if (!begin.ok) return { ok: false, error: String(begin.error ?? "char_begin rejected") };
1675
+
1676
+ let sent = 0;
1677
+ for (const file of files) {
1678
+ const start = await this.sendCommand("file", { path: file.name, size: file.data.length }, 6_000);
1679
+ if (!start.ok) return { ok: false, error: `file ${file.name}: ${start.error ?? "rejected"}` };
1680
+ for (let offset = 0; offset < file.data.length; offset += 256) {
1681
+ const chunk = file.data.subarray(offset, offset + 256).toString("base64");
1682
+ const ack = await this.sendCommand("chunk", { d: chunk }, 4_000);
1683
+ if (!ack.ok) return { ok: false, error: `chunk ${offset} of ${file.name}: ${ack.error ?? "failed"}` };
1684
+ sent += Math.min(256, file.data.length - offset);
1685
+ options.onProgress?.(sent, total);
1686
+ }
1687
+ const end = await this.sendCommand("file_end", {}, 10_000);
1688
+ if (!end.ok) return { ok: false, error: `file_end ${file.name}: ${end.error ?? "failed"}` };
1689
+ if (typeof end.n === "number" && end.n !== file.data.length) {
1690
+ return { ok: false, error: `${file.name}: device wrote ${end.n} of ${file.data.length} bytes` };
1691
+ }
1692
+ }
1693
+ const done = await this.sendCommand("char_end", {}, 10_000);
1694
+ return done.ok ? { ok: true } : { ok: false, error: String(done.error ?? "char_end failed") };
1695
+ }
1696
+ }
1697
+
1698
+ /**
1699
+ * Ask a human in the terminal, but not past the approval window.
1700
+ *
1701
+ * The approval timeout is a constant, and every party on this machine already has it:
1702
+ * that is what makes the mask work without a single message between sessions -- a
1703
+ * question is live while `now - mtime(APPROVAL) <= TIMEOUT` and is not afterwards, and
1704
+ * nobody has to be told. The terminal had not got that memo. A dialog there is waiting
1705
+ * for an answer with no clock attached to it, so a session whose pet was unavailable
1706
+ * parked the tool call indefinitely, and the only thing that ever ended was a human
1707
+ * walking over to the keyboard. Same constant, same arithmetic, one fewer way for the
1708
+ * surfaces of one approval to disagree about whether the question is still being asked.
1709
+ *
1710
+ * Expiry is a `null`, the same value a dismissed dialog returns: neither surface may
1711
+ * invent an answer, and a window that closed is not a denial -- it is the absence of
1712
+ * one, which the caller already knows how to report.
1713
+ */
1714
+ export async function askWithDeadline(
1715
+ ask: (signal: AbortSignal) => Promise<boolean | null>,
1716
+ timeoutMs: number,
1717
+ signal?: AbortSignal,
1718
+ ): Promise<boolean | null> {
1719
+ const controller = new AbortController();
1720
+ signal?.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
1721
+ if (signal?.aborted) controller.abort(signal.reason);
1722
+ if (timeoutMs <= 0) {
1723
+ // No window configured means the human is in no hurry, not that the asking is off.
1724
+ try {
1725
+ return await ask(controller.signal);
1726
+ } catch {
1727
+ return null;
1728
+ }
1729
+ }
1730
+ let timer: ReturnType<typeof setTimeout> | undefined;
1731
+ try {
1732
+ return await Promise.race([
1733
+ ask(controller.signal),
1734
+ // Ref'd, like the prompt's own timer: a promise somebody is holding can only be
1735
+ // ended by a handle, so a timer that is allowed to be skipped is a tool call that
1736
+ // is allowed to hang.
1737
+ new Promise<null>((resolve) => {
1738
+ timer = setTimeout(() => {
1739
+ controller.abort(new Error("approval window closed"));
1740
+ resolve(null);
1741
+ }, timeoutMs);
1742
+ }),
1743
+ ]);
1744
+ } catch {
1745
+ return null;
1746
+ } finally {
1747
+ clearTimeout(timer);
1748
+ }
1749
+ }
1750
+
1751
+ export function clockTime(date = new Date()): string {
1752
+ const hh = String(date.getHours()).padStart(2, "0");
1753
+ const mm = String(date.getMinutes()).padStart(2, "0");
1754
+ return `${hh}:${mm}`;
1755
+ }
1756
+
1757
+ export function errorMessage(error: unknown): string {
1758
+ return error instanceof Error ? error.message : String(error);
1759
+ }