@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/index.ts ADDED
@@ -0,0 +1,827 @@
1
+ /**
2
+ * pi <-> Pippi desk-pet bridge.
3
+ *
4
+ * Watches a pi session and pushes the agent-neutral JSON feed the firmware
5
+ * speaks (REFERENCE.md) over BLE, and turns the device's A/B buttons into
6
+ * approve/deny for risky tool calls.
7
+ *
8
+ * Layout:
9
+ * index.ts this file — pi events + /pippi command
10
+ * bridge.ts session model, snapshot rendering, prompt gate, folder push
11
+ * approvals.ts which tool calls deserve an interrupt
12
+ * transport.ts what a link has to be able to do, and the null one
13
+ * ble.ts the real link: BlueZ over D-Bus
14
+ * bluez.ts the D-Bus wire format, with no libraries under it
15
+ * simulate.ts a pippi made of TypeScript, for tests and demos
16
+ * claims.ts which pi window may hold the pet
17
+ * state.ts persisted device + daily token counter
18
+ * usage.ts the pet's provider-quota row, asked over pi's event bus
19
+ *
20
+ * Run:
21
+ * pi -e ./bridges/pi # or list the dir in settings.json "extensions"
22
+ * /pippi scan
23
+ * /pippi connect AA:BB:CC:DD:EE:FF
24
+ *
25
+ * Env:
26
+ * PI_PIPPI_DISABLE=1 load but stay off
27
+ * PI_PIPPI_TRANSPORT=ble|simulate|null
28
+ * PI_PIPPI_APPROVALS=off|dangerous|all
29
+ * PI_PIPPI_APPROVAL_TIMEOUT=<sec> 0 waits forever (default 60)
30
+ * PI_PIPPI_ON_TIMEOUT=block|allow default block
31
+ * PI_PIPPI_RECLAIM=<sec> how long to chase a pippi that dropped by
32
+ * itself (reset, flash, battery swap) before
33
+ * giving up and waiting for Enter. Default
34
+ * 120; 0 never chases. One chase per press of
35
+ * Enter, so two windows cannot fight -- see
36
+ * the reclaim note in README.md.
37
+ * PI_PIPPI_OWNER=<name> default: git user.name, else $USER
38
+ * PI_PIPPI_PROVIDER=<id> default: the session's model provider;
39
+ * the badge on the right of the pet. Set it
40
+ * when the provider pi is told about is a
41
+ * proxy -- llama-swap serving Qwen should
42
+ * wear Qwen's mark, and only the person who
43
+ * configured the box can say so.
44
+ * PI_PIPPI_TAG=<label> default: the working directory's name;
45
+ * shown on the device beside an approval
46
+ * PI_PIPPI_DEVICE=<address> override the saved device
47
+ * PI_PIPPI_TURN_EVENTS=1 send {"evt":"turn"} (firmware ignores today)
48
+ * PI_PIPPI_WIRE_LOG=<path> append every tx/rx line for debugging
49
+ * PI_PIPPI_CLAIM_DIR=<dir> default /tmp/pi-pippi-claims
50
+ * PI_PIPPI_STATE_DIR=<dir> default $XDG_CACHE_HOME/pi-pippi
51
+ */
52
+
53
+ import * as fs from "node:fs";
54
+ import * as path from "node:path";
55
+
56
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
57
+
58
+ import { classifyToolCall, parsePolicy, previewInput } from "./approvals.ts";
59
+ import { BluezTransport } from "./ble.ts";
60
+ import { askWithDeadline, PippiBridge, type ApprovalOutcome } from "./bridge.ts";
61
+ import { ClaimBoard } from "./claims.ts";
62
+ import { MAX_PROMPT_TAG_BYTES, sanitizeTag, truncateBytes } from "./protocol.ts";
63
+ import { FileStateStore, guessOwner, guessSessionTag } from "./state.ts";
64
+ import { SimTransport } from "./simulate.ts";
65
+ import { NullTransport, type BridgeTransport } from "./transport.ts";
66
+ import { UsageService, usageReportSpec } from "./usage.ts";
67
+
68
+ // The stand-in is announced once per distinct spec, not once per poll: the polls
69
+ // are on a timer and the log is read by a person.
70
+ let warnedSpec: string | undefined;
71
+ let warnedBad: string | undefined;
72
+
73
+ const STATUS_KEY = "pippi";
74
+
75
+ interface ContentBlockLike {
76
+ type: string;
77
+ text?: string;
78
+ id?: string;
79
+ name?: string;
80
+ arguments?: Record<string, unknown>;
81
+ }
82
+
83
+ function envFlag(value: string | undefined): boolean {
84
+ return ["1", "true", "on", "yes"].includes((value ?? "").trim().toLowerCase());
85
+ }
86
+
87
+ function envInt(value: string | undefined, fallback: number): number {
88
+ const parsed = Number.parseInt(value ?? "", 10);
89
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
90
+ }
91
+
92
+ /**
93
+ * The link to the pet: BlueZ in this process, a scripted stand-in, or nothing.
94
+ *
95
+ * The claim board is made here rather than inside the transport because the bridge
96
+ * keeps one too and the two must agree: a stamp written on Enter and a stamp read
97
+ * before a reconnect are the same fact, and handing one object to both is what
98
+ * stops a session from competing with itself.
99
+ */
100
+ function makeTransport(board: ClaimBoard): BridgeTransport {
101
+ const mode = (process.env.PI_PIPPI_TRANSPORT ?? "ble").trim().toLowerCase();
102
+ if (mode === "null" || mode === "none" || mode === "off") return new NullTransport();
103
+ if (mode === "simulate" || mode === "sim") return new SimTransport();
104
+ return new BluezTransport({ board });
105
+ }
106
+
107
+ /** Map pi assistant content onto the Anthropic-style blocks REFERENCE.md expects. */
108
+ export function toAnthropicBlocks(content: ContentBlockLike[]): Array<Record<string, unknown>> {
109
+ const blocks: Array<Record<string, unknown>> = [];
110
+ for (const block of content) {
111
+ if (block.type === "text" && block.text) blocks.push({ type: "text", text: block.text });
112
+ else if (block.type === "toolCall") {
113
+ blocks.push({ type: "tool_use", id: block.id, name: block.name, input: block.arguments ?? {} });
114
+ }
115
+ }
116
+ return blocks;
117
+ }
118
+
119
+ export default function activate(pi: ExtensionAPI): void {
120
+ const store = new FileStateStore();
121
+ // One board for the process: the bridge stamps it, the transport reads it, and
122
+ // they have to be looking at the same directory to mean the same thing.
123
+ const claimBoard = new ClaimBoard();
124
+ let lastCtx: ExtensionContext | undefined;
125
+ let lastError = "";
126
+
127
+ // The one place a message reaches the human: recorded for /pippi's status, and
128
+ // raised in the window when it matters. Everything below logs through this, and
129
+ // nothing outside `activate` may, since both halves need the closing state.
130
+ const bridgeLog = (level: string, message: string): void => {
131
+ if (level === "error") lastError = message;
132
+ if (lastCtx?.hasUI && level === "error") lastCtx.ui.notify(`pippi: ${message}`, "warning");
133
+ };
134
+
135
+ const bridge = new PippiBridge(makeTransport(claimBoard), store, {
136
+ onLog: bridgeLog,
137
+ onStatus: () => renderStatus(lastCtx),
138
+ // The pet's "ctx" gauge: how full this session's context window is. pi
139
+ // reports a null percent before the first response and again right after a
140
+ // compaction; the bridge omits the field there and the device shows "n/a".
141
+ contextUsage: () => lastCtx?.getContextUsage?.()?.percent ?? null,
142
+ // The pet's "usage" row: what this account has left, from whichever extension
143
+ // answers the usage protocol on pi's event bus. Undefined means no such service
144
+ // in this session, and the device draws no row at all.
145
+ usage: () => usage.current,
146
+ });
147
+
148
+ /**
149
+ * Provider allowance and balance for the pet's usage row. The data belongs to
150
+ * another extension: this speaks the `usage:query:v1` protocol over pi's event bus
151
+ * and imports nothing from whoever answers, so a session without a usage service
152
+ * behaves exactly as it did before the row existed — which is to say, the row is
153
+ * not drawn.
154
+ *
155
+ * Created with the extension; it does no work until a session starts it, asks
156
+ * nothing while no pippi is connected, and stops asking when the provider says it
157
+ * has nothing for the model in use.
158
+ */
159
+ const usage = new UsageService(pi.events, { // Five minutes. Every poll is a refresh — a cache-only read is documented to
160
+ // miss for every provider today — so this cadence is the rate at which we ask a
161
+ // provider about someone's account, and it is set to match the freshness the
162
+ // usage extension itself keeps on screen. Quota windows are measured in hours.
163
+ intervalMs: envInt(process.env.PI_PIPPI_USAGE_INTERVAL, 300) * 1000,
164
+ context: () => lastCtx,
165
+ // A request against the user's quota, on a timer, for a pet that is switched off
166
+ // or unpaired is traffic for nobody.
167
+ wanted: () => bridge.connected,
168
+ // Below this percentage of an allowance a bar blinks red on the panel. Unset
169
+ // means the device's own default (5%), so the ordinary configuration sends
170
+ // nothing; 0 means never blink.
171
+ usageLow: () => {
172
+ const raw = process.env.PI_PIPPI_USAGE_LOW;
173
+ if (raw === undefined || raw.trim() === "") return undefined;
174
+ const value = Number(raw);
175
+ return Number.isFinite(value) ? Math.max(0, Math.min(100, Math.round(value))) : undefined;
176
+ },
177
+ onChange: () => bridge.noteUsage(),
178
+ // A report from the command line instead of a provider. Both situations it
179
+ // exists for are ones the panel cannot otherwise be seen working in: a model
180
+ // served by a local backend has no subscription and no balance to draw down, and
181
+ // the second quota window of an account that has only used one takes a week of
182
+ // real use to produce. It answers its own question, so it exercises the layout
183
+ // and the clamps and nothing of the query itself -- see `usageReportSpec`.
184
+ report: () => {
185
+ const raw = process.env.PI_PIPPI_USAGE_SPEC?.trim();
186
+ if (!raw) return undefined;
187
+ const report = usageReportSpec(raw);
188
+ if (report && warnedSpec !== raw) {
189
+ warnedSpec = raw;
190
+ bridgeLog("info", `usage rows are not from a provider: PI_PIPPI_USAGE_SPEC=${raw}`);
191
+ } else if (!report && warnedBad !== raw) {
192
+ warnedBad = raw;
193
+ bridgeLog("error", `PI_PIPPI_USAGE_SPEC="${raw}" does not parse; the usage row stays off`);
194
+ return undefined;
195
+ }
196
+ return report;
197
+ },
198
+ log: (message) => bridgeLog("info", message),
199
+ });
200
+
201
+ const disabled = envFlag(process.env.PI_PIPPI_DISABLE);
202
+ const onTimeoutAllow = (process.env.PI_PIPPI_ON_TIMEOUT ?? "block").trim().toLowerCase() === "allow";
203
+ // The provider pi reports is a fact about the endpoint; this is a fact about what
204
+ // is on the other end of it. Whitespace-only counts as unset: `PI_PIPPI_PROVIDER=`
205
+ // in a shell profile is somebody meaning "no override", not "draw an empty badge".
206
+ const providerOverride = process.env.PI_PIPPI_PROVIDER?.trim() || undefined;
207
+
208
+ // ------------------------------------------------------------------ startup
209
+
210
+ // A pippi follows the human. Typed input in this window claims the device from
211
+ // whichever other pi session holds it; see PippiBridge.noteUserInput.
212
+ pi.on("input", async (event) => {
213
+ // "rpc" and "extension" sources are not a human at a keyboard: another
214
+ // process scripting pi, or our own sendUserMessage, must not be able to move
215
+ // the pet out from under the window someone is typing in.
216
+ if (event.source !== "interactive") return undefined;
217
+ bridge.noteUserInput();
218
+ return undefined;
219
+ });
220
+
221
+ pi.on("session_start", async (event, ctx) => {
222
+ lastCtx = ctx;
223
+ if (disabled) {
224
+ renderStatus(ctx);
225
+ return;
226
+ }
227
+ try {
228
+ // Before start, so the first snapshot out of the gate already says who is
229
+ // answering: restoring a session does not fire model_select, and this is the
230
+ // only place a resumed window finds out.
231
+ bridge.noteProvider(providerOverride ?? ctx.model?.provider);
232
+ await bridge.start({
233
+ claimBoard,
234
+ owner: guessOwner(),
235
+ device: process.env.PI_PIPPI_DEVICE,
236
+ approvals: parsePolicy(process.env.PI_PIPPI_APPROVALS),
237
+ approvalTimeoutMs: envInt(process.env.PI_PIPPI_APPROVAL_TIMEOUT, 60) * 1000,
238
+ reclaimMs: envInt(process.env.PI_PIPPI_RECLAIM, 120) * 1000,
239
+ turnEvents: envFlag(process.env.PI_PIPPI_TURN_EVENTS),
240
+ tag: guessSessionTag(),
241
+ });
242
+ } catch (error) {
243
+ // A missing BLE stack, or no bus to ask, must never break a pi session.
244
+ lastError = error instanceof Error ? error.message : String(error);
245
+ }
246
+ bridge.noteSession(String((event as { reason?: string }).reason ?? "startup"));
247
+ // The usage row's clock starts here, not at load: the queries are about the
248
+ // session's provider and credential, and neither is meaningful before one exists.
249
+ usage.start();
250
+ renderStatus(ctx);
251
+ });
252
+
253
+ pi.on("session_shutdown", async (_event, ctx) => {
254
+ try {
255
+ ctx.ui.setStatus?.(STATUS_KEY, undefined);
256
+ } catch {
257
+ /* TUI already gone */
258
+ }
259
+ // Before the bridge goes away, so a report in flight is abandoned rather than
260
+ // delivered to a device that is no longer ours to paint.
261
+ await usage.stop();
262
+ await bridge.stop();
263
+ });
264
+
265
+ // A provider that said "no report for this model" stays asleep until the model
266
+ // changes, which is the one thing that can make the answer different. The badge
267
+ // rides the same event for the same reason: the model is what it is drawn from.
268
+ pi.on("model_select", async (event) => {
269
+ usage.modelChanged();
270
+ bridge.noteProvider(providerOverride ?? event.model?.provider);
271
+ });
272
+
273
+ // --------------------------------------------------------------- live state
274
+
275
+ pi.on("agent_start", async (_event, ctx) => {
276
+ lastCtx = ctx;
277
+ bridge.noteAgentStart();
278
+ renderStatus(ctx);
279
+ });
280
+
281
+ pi.on("agent_settled", async (event, ctx) => {
282
+ lastCtx = ctx;
283
+ bridge.noteAgentSettled(Boolean((event as { aborted?: boolean }).aborted));
284
+ renderStatus(ctx);
285
+ });
286
+
287
+ pi.on("tool_execution_start", async (event, ctx) => {
288
+ lastCtx = ctx;
289
+ const args = (event.args ?? {}) as Record<string, unknown>;
290
+ bridge.noteToolStart(event.toolCallId, event.toolName, previewInput(event.toolName, args));
291
+ });
292
+
293
+ pi.on("tool_execution_end", async (event) => {
294
+ bridge.noteToolEnd(event.toolCallId, Boolean(event.isError));
295
+ });
296
+
297
+ // pi's own blocking dialogs: report "waiting" without offering the device a
298
+ // decision it cannot deliver (the prompt object implies answerability).
299
+ pi.on("ui_prompt_start", async (event, ctx) => {
300
+ lastCtx = ctx;
301
+ bridge.noteUiPrompt(true, String((event as { kind?: string }).kind ?? ""), (event as { title?: string }).title);
302
+ renderStatus(ctx);
303
+ });
304
+
305
+ pi.on("ui_prompt_end", async (_event, ctx) => {
306
+ lastCtx = ctx;
307
+ bridge.noteUiPrompt(false);
308
+ renderStatus(ctx);
309
+ });
310
+
311
+ // Throughput: pi reports token counts but no clock, so the bridge times the
312
+ // stream itself. message_start is the earliest mark available for a response
313
+ // and the first content event is the first token; message_end supplies the
314
+ // token counts to divide by. See PippiBridge.noteResponseSpeed.
315
+ pi.on("message_start", async (event) => {
316
+ if (disabled) return;
317
+ if ((event.message as { role?: string } | undefined)?.role === "assistant") bridge.noteResponseStart();
318
+ });
319
+
320
+ pi.on("message_update", async (event) => {
321
+ if (disabled) return;
322
+ const kind = (event.assistantMessageEvent as { type?: string } | undefined)?.type;
323
+ if (typeof kind === "string" && /_(start|delta)$/.test(kind)) bridge.noteFirstToken();
324
+ });
325
+
326
+ pi.on("message_end", async (event) => {
327
+ // PI_PIPPI_DISABLE means "stay out of the filesystem": without this guard a
328
+ // disabled bridge still rewrites state.json on every assistant message.
329
+ if (disabled) return;
330
+ const message = event.message as unknown as
331
+ | { role?: string; usage?: { input?: number; cacheRead?: number; cacheWrite?: number; output?: number }; content?: ContentBlockLike[] }
332
+ | undefined;
333
+ if (message?.role !== "assistant") return; // Close the timing before the token counters so the speed rows and the
334
+ // token rows reach the device from the same snapshot.
335
+ bridge.noteResponseSpeed(message.usage ?? {});
336
+ const output = message.usage?.output;
337
+ if (typeof output === "number") bridge.noteAssistantUsage(output);
338
+ });
339
+
340
+ // REFERENCE.md turn events. Current firmware ignores them, so they are
341
+ // opt-in and always size-capped by protocol.ts.
342
+ pi.on("turn_end", async (event) => {
343
+ if (disabled) return;
344
+ const message = event.message as unknown as { role?: string; content?: ContentBlockLike[] } | undefined;
345
+ if (message?.role !== "assistant" || !Array.isArray(message.content)) return;
346
+ const blocks = toAnthropicBlocks(message.content);
347
+ if (blocks.length > 0) bridge.sendTurn("assistant", blocks);
348
+ });
349
+
350
+ // ------------------------------------------------------------- approval gate
351
+
352
+ pi.on("tool_call", async (event, ctx) => {
353
+ lastCtx = ctx;
354
+ // Deliberately not gated on `bridge.connected`: an unattached session is the
355
+ // interesting case, not the skip case. Whether the question can be asked at
356
+ // all is decided by requestApproval, which takes the pippi over from whichever
357
+ // session holds it and falls back to this terminal. Skipping here because the
358
+ // pet happens to be showing another window would make "unattached" mean "no
359
+ // approvals" -- which is how a background session used to run `rm -rf` free.
360
+ if (disabled || !bridge.isEnabled || bridge.config.approvals === "off") {
361
+ return undefined;
362
+ }
363
+
364
+ const input = (event.input ?? {}) as Record<string, unknown>;
365
+ const decision = classifyToolCall(bridge.config.approvals, event.toolName, input, { cwd: ctx.cwd });
366
+ if (!decision.gate) return undefined;
367
+
368
+ const preview = truncateBytes(previewInput(event.toolName, input), 200);
369
+ const localPrompt = ctx.hasUI
370
+ ? async (signal: AbortSignal): Promise<boolean> => {
371
+ // confirm() resolves false when dismissed with Escape, which is a
372
+ // refusal. When the device answers first, bridge.ts aborts this
373
+ // signal and the dialog closes without counting as anything.
374
+ const answer = await ctx.ui.confirm(
375
+ `Allow ${decision.tool}?`,
376
+ `${preview}\n\nWhy: ${decision.risk ?? "policy"}\n\nThe pippi device shows the same prompt: A approves, B denies.`,
377
+ { signal },
378
+ );
379
+ return answer === true;
380
+ }
381
+ : undefined;
382
+
383
+ try {
384
+ ctx.ui.setStatus?.(STATUS_KEY, `⏳ approve ${decision.tool}? (device: A allow / B deny)`);
385
+ } catch {
386
+ /* no TUI */
387
+ }
388
+
389
+ const outcome: ApprovalOutcome = await bridge.requestApproval({
390
+ tool: decision.tool,
391
+ hint: decision.hint,
392
+ signal: ctx.signal,
393
+ localPrompt,
394
+ });
395
+ renderStatus(ctx);
396
+
397
+ if (outcome === "once") return undefined;
398
+ if (outcome === "deny") {
399
+ return { block: true, reason: `Denied on the pippi device (risk: ${decision.risk ?? decision.tool}).` };
400
+ }
401
+ if (outcome === "timeout") {
402
+ if (onTimeoutAllow) return undefined;
403
+ return {
404
+ block: true,
405
+ reason: `No approval within ${Math.round(bridge.config.approvalTimeoutMs / 1000)}s (risk: ${decision.risk ?? "policy"}). Re-run the request, or use /pippi approvals off.`,
406
+ };
407
+ }
408
+ // "unavailable" means the human was never asked: this session does not hold
409
+ // the pippi (another window claimed it, or the pet is asleep) and no device
410
+ // answer arrived. Allowing the call would make "the pet is showing a different
411
+ // session" indistinguishable from "approvals are off", so fall back to the
412
+ // terminal, which is the one approval surface still ours.
413
+ if (localPrompt) {
414
+ // Bounded by the same clock the pet was given: an unanswered dialog in a
415
+ // terminal is a tool call parked forever, and "forever" is the one thing an
416
+ // approval is not allowed to be now that the pippi side keeps time.
417
+ const answered = await askWithDeadline(
418
+ localPrompt,
419
+ bridge.config.approvalTimeoutMs,
420
+ ctx.signal,
421
+ );
422
+ if (answered === true) return undefined;
423
+ if (answered === false) {
424
+ return { block: true, reason: `Denied in the terminal (risk: ${decision.risk ?? decision.tool}).` };
425
+ }
426
+ // null: dismissed without a decision. Neither surface may invent one, and a
427
+ // headless-ish dismissal must not deadlock pi either.
428
+ }
429
+ notify(ctx, "No pippi on this session and no answer in the terminal; letting pi continue.", "warning");
430
+ return undefined;
431
+ });
432
+
433
+ // ------------------------------------------------------------ /pippi command
434
+
435
+ pi.registerCommand("pippi", {
436
+ description: "Desk-pet bridge: status, connect, approvals, character push",
437
+ getArgumentCompletions: (prefix: string) => {
438
+ const options = [
439
+ "status",
440
+ "scan",
441
+ "connect",
442
+ "forget",
443
+ "on",
444
+ "off",
445
+ "approvals",
446
+ "name",
447
+ "owner",
448
+ "push",
449
+ "ping",
450
+ "help",
451
+ ];
452
+ const trimmed = prefix.trim();
453
+ const matches = options.filter((option) => option.startsWith(trimmed));
454
+ return matches.length > 0 ? matches.map((value) => ({ value, label: value })) : null;
455
+ },
456
+ handler: async (args: string, ctx: ExtensionContext) => {
457
+ lastCtx = ctx;
458
+ const [sub = "status", ...rest] = args.trim().split(/\s+/);
459
+ // Typing a /pippi command is the human choosing this window, and extension
460
+ // commands never reach the `input` event, so the claim has to happen here --
461
+ // except for the commands whose whole point is letting go of the pippi.
462
+ if (sub !== "off" && sub !== "forget") bridge.noteUserInput();
463
+ switch (sub) {
464
+ case "status": {
465
+ await showStatus(ctx);
466
+ break;
467
+ }
468
+ case "scan": {
469
+ await scan(ctx);
470
+ break;
471
+ }
472
+ case "connect": {
473
+ await connect(rest.join(" "), ctx);
474
+ break;
475
+ }
476
+ case "forget": {
477
+ // Stop wanting it back before letting go of it, or the unpair below
478
+ // reads as an unasked-for drop and the bridge goes chasing a device the
479
+ // human has just told it to forget.
480
+ bridge.forgetDevice();
481
+ if (bridge.connected) await bridge.sendCommand("unpair");
482
+ store.save({ device: undefined, deviceName: undefined });
483
+ notify(ctx, "Forgot pippi; it will not auto-connect.", "info");
484
+ renderStatus(ctx);
485
+ break;
486
+ }
487
+ case "on":
488
+ case "off": {
489
+ bridge.setEnabled(sub === "on");
490
+ renderStatus(ctx);
491
+ notify(ctx, `Pippi bridge ${sub}.`, "info");
492
+ break;
493
+ }
494
+ case "approvals": {
495
+ const policy = parsePolicy(rest.join(" "));
496
+ if (!policy) {
497
+ notify(ctx, `Approvals: ${bridge.config.approvals}. Set with /pippi approvals off|dangerous|all`, "info");
498
+ break;
499
+ }
500
+ bridge.config.approvals = policy;
501
+ store.save({ approvals: policy });
502
+ notify(ctx, `Approvals: ${policy}.`, "info");
503
+ renderStatus(ctx);
504
+ break;
505
+ }
506
+ case "tag": {
507
+ // No argument: report. Several windows need to be told apart, and the
508
+ // only way to do that from inside one of them is to ask it what it is
509
+ // called -- the pet shows the same string.
510
+ const wanted = rest.join(" ").trim();
511
+ if (!wanted) {
512
+ const current = bridge.config.tag;
513
+ notify(
514
+ ctx,
515
+ current
516
+ ? `This session is "${current}" on the pet. Set with /pippi tag <name> (max ${MAX_PROMPT_TAG_BYTES} characters, ASCII).`
517
+ : `This session sends no tag. Set with /pippi tag <name> (max ${MAX_PROMPT_TAG_BYTES} characters, ASCII).`,
518
+ "info",
519
+ );
520
+ break;
521
+ }
522
+ const tag = sanitizeTag(wanted);
523
+ if (!tag) {
524
+ // Refuse rather than quietly send nothing: a tag made of emoji or CJK
525
+ // is the device font's problem, and swallowing the request would look
526
+ // like the command did nothing at all.
527
+ notify(
528
+ ctx,
529
+ `A tag has to be ${MAX_PROMPT_TAG_BYTES} printable ASCII characters the pet can draw.`,
530
+ "warning",
531
+ );
532
+ break;
533
+ }
534
+ bridge.setTag(tag);
535
+ notify(ctx, `This session is "${tag}" on the pet.`, "info");
536
+ break;
537
+ }
538
+ case "name": {
539
+ const name = rest.join(" ").trim();
540
+ if (!name) {
541
+ notify(ctx, "Usage: /pippi name <pet name>", "info");
542
+ break;
543
+ }
544
+ const ack = await bridge.sendCommand("name", { name: truncateBytes(name, 24) });
545
+ notify(ctx, ack.ok ? `Named the pet “${name}”.` : `Name failed: ${ack.error ?? "no ack"}`, ack.ok ? "info" : "error");
546
+ break;
547
+ }
548
+ case "owner": {
549
+ const name = rest.join(" ").trim() || guessOwner();
550
+ if (!name) {
551
+ notify(ctx, "Usage: /pippi owner <name>", "info");
552
+ break;
553
+ }
554
+ bridge.config.owner = name;
555
+ const ack = await bridge.sendCommand("owner", { name: truncateBytes(name, 24) });
556
+ notify(ctx, ack.ok ? `Owner set to ${name}.` : `Owner failed: ${ack.error ?? "no ack"}`, ack.ok ? "info" : "error");
557
+ break;
558
+ }
559
+ case "ping": {
560
+ const status = await bridge.pollStatus();
561
+ notify(
562
+ ctx,
563
+ status
564
+ ? `Pippi replied: ${JSON.stringify(status).slice(0, 200)}`
565
+ : "No status reply from pippi.",
566
+ status ? "info" : "warning",
567
+ );
568
+ break;
569
+ }
570
+ case "push": {
571
+ await pushCharacter(rest.join(" ").trim(), ctx);
572
+ break;
573
+ }
574
+ default: {
575
+ notify(
576
+ ctx,
577
+ [
578
+ "/pippi status connection, battery, policy, tokens",
579
+ "/pippi scan scan for NUS devices",
580
+ "/pippi connect [address] connect (no arg = scan and pick)",
581
+ "/pippi forget unpair and forget the device",
582
+ "/pippi on|off enable/disable the bridge",
583
+ "/pippi approvals <policy> off | dangerous | all",
584
+ "/pippi tag [name] what this window is called on the pet",
585
+ "/pippi name <name> rename the pet",
586
+ "/pippi owner [name] set the owner name",
587
+ "/pippi push <folder> stream a character pack",
588
+ "/pippi ping poll the device",
589
+ ].join("\n"),
590
+ "info",
591
+ );
592
+ }
593
+ }
594
+ },
595
+ });
596
+
597
+ // -------------------------------------------------------------------- helpers
598
+
599
+ function notify(ctx: ExtensionContext, message: string, level: "info" | "warning" | "error"): void {
600
+ try {
601
+ ctx.ui.notify?.(message, level);
602
+ } catch {
603
+ /* headless modes no-op */
604
+ }
605
+ }
606
+
607
+ function setStatus(ctx: ExtensionContext, text: string | undefined): void {
608
+ try {
609
+ ctx.ui.setStatus?.(STATUS_KEY, text);
610
+ } catch {
611
+ /* headless modes no-op */
612
+ }
613
+ }
614
+
615
+ function renderStatus(ctx?: ExtensionContext): void {
616
+ if (!ctx || !ctx.hasUI) return;
617
+ if (disabled) return setStatus(ctx, "pippi off (PI_PIPPI_DISABLE)");
618
+ if (!bridge.isEnabled) return setStatus(ctx, "pippi off");
619
+ const state = bridge.state;
620
+ if (!state.connected) {
621
+ // Two different silences: never attached here (Enter will attach) versus
622
+ // attached and lost it (the pippi is asleep, or another window has it).
623
+ if (!bridge.hasAttachedOnce) return setStatus(ctx, "○ pippi: standby (Enter to attach)");
624
+ // A third while it is being chased: no action for the human, and saying so
625
+ // is what keeps them from pressing Enter and interrupting the retry.
626
+ if (bridge.reclaiming) return setStatus(ctx, "○ pippi: reconnecting…");
627
+ // A fourth, and this one is not going to fix itself: the chase stopped because
628
+ // taking it back again would be a fight, and the human's Enter is the only
629
+ // thing that ends it. Without this line the pet just looks dead.
630
+ if (bridge.fought) return setStatus(ctx, "○ pippi: another window has it (Enter to take it back)");
631
+ return setStatus(ctx, `○ pippi: disconnected${state.error ? ` — ${state.error}` : ""}`);
632
+ }
633
+ const status = bridge.status;
634
+ const snapshot = bridge.buildSnapshot();
635
+ const parts = [`● ${state.name ?? bridge.config.device ?? "pippi"}`];
636
+ if (status?.bat?.pct !== undefined) parts.push(`${status.bat.pct}%`);
637
+ if (status?.sec === false) parts.push("insecure");
638
+ parts.push(snapshot.running ? "busy" : snapshot.waiting ? "waiting" : "idle");
639
+ setStatus(ctx, parts.join(" · "));
640
+ }
641
+
642
+ async function showStatus(ctx: ExtensionContext): Promise<void> {
643
+ if (bridge.connected) await bridge.pollStatus();
644
+ const status = bridge.status;
645
+ const snapshot = bridge.buildSnapshot();
646
+ const state = bridge.state;
647
+ const lines = [
648
+ `Pippi bridge: ${bridge.isEnabled ? "enabled" : "disabled"} (transport: ${bridge.kind})`,
649
+ `Link: ${
650
+ state.connected
651
+ ? `connected — ${state.name ?? "unnamed"} ${state.address ?? ""}${state.mtu ? ` mtu ${state.mtu}` : ""}`.trim()
652
+ : `disconnected${state.error ? ` — ${state.error}` : ""}`
653
+ }`,
654
+ `Encryption: ${status?.sec === undefined ? "unknown (poll /pippi ping)" : status.sec ? "LE Secure Connections" : "none"}`,
655
+ `Battery: ${
656
+ status?.bat?.pct !== undefined
657
+ ? `${status.bat.pct}% (${status.bat.mV ?? "?"}mV${status.bat.mA !== undefined ? `, ${status.bat.mA}mA` : ""}${status.bat.usb ? ", USB" : ""})`
658
+ : "unknown"
659
+ }`,
660
+ `Device: up ${status?.sys?.up ?? "?"}s, free heap ${status?.sys?.heap ?? "?"}, fs free ${status?.sys?.fsFree ?? "?"}`,
661
+ `Pet: level ${status?.stats?.lvl ?? "?"}, approved ${status?.stats?.appr ?? 0}, denied ${status?.stats?.deny ?? 0}`,
662
+ `Approvals: ${bridge.config.approvals}, timeout ${Math.round(bridge.config.approvalTimeoutMs / 1000)}s → ${onTimeoutAllow ? "allow" : "block"}`,
663
+ // The string the pet draws beside a pending approval, so "which window is
664
+ // asking?" can be answered from the window rather than from the desk.
665
+ `Session tag: ${bridge.config.tag ?? "none (/pippi tag <name>)"}`,
666
+ `Tokens: ${snapshot.tokens} this session, ${snapshot.tokens_today} today`,
667
+ // Same number the pet's "ctx" gauge draws, so a terminal can confirm the
668
+ // gauge is being fed. "unknown" matches the device's n/a: pi has no
669
+ // window size before the first response, and reports usage as unknown
670
+ // right after a compaction.
671
+ `Context: ${snapshot.ctx === undefined ? "unknown (no window reported)" : `${snapshot.ctx}%`}`,
672
+ `Snapshot: total ${snapshot.total} running ${snapshot.running} waiting ${snapshot.waiting} msg "${snapshot.msg}"`,
673
+ ];
674
+ if (lastError) lines.push(`Last error: ${lastError}`);
675
+ notify(ctx, lines.join("\n"), "info");
676
+ renderStatus(ctx);
677
+ }
678
+
679
+ async function scan(ctx: ExtensionContext): Promise<void> {
680
+ setStatus(ctx, "pippi: scanning…");
681
+ const results = await bridge.scan(8000);
682
+ setStatus(ctx, undefined);
683
+ if (results.length === 0) {
684
+ notify(
685
+ ctx,
686
+ "No pippi devices found. Wake the device with a button press and check settings → bluetooth.",
687
+ "warning",
688
+ );
689
+ return;
690
+ }
691
+ notify(ctx, results.map((r) => `${r.name || "unnamed"} ${r.address} ${r.rssi ?? "?"}dBm`).join("\n"), "info");
692
+ }
693
+
694
+ async function connect(target: string, ctx: ExtensionContext): Promise<void> {
695
+ let chosen = target.trim();
696
+ if (!chosen) {
697
+ setStatus(ctx, "pippi: scanning…");
698
+ const results = await bridge.scan(8000);
699
+ setStatus(ctx, undefined);
700
+ if (results.length === 0) {
701
+ notify(ctx, "No pippi devices found.", "warning");
702
+ return;
703
+ }
704
+ if (!ctx.hasUI) {
705
+ notify(
706
+ ctx,
707
+ `Found: ${results.map((r) => `${r.name || "unnamed"} ${r.address}`).join(", ")}. Use /pippi connect <address>.`,
708
+ "info",
709
+ );
710
+ return;
711
+ }
712
+ const pick = await ctx.ui.select(
713
+ "Connect to which pippi?",
714
+ results.map((r) => `${r.name || "unnamed"} ${r.address}`),
715
+ );
716
+ if (!pick) return;
717
+ chosen = pick.trim().split(/\s+/).pop() ?? "";
718
+ }
719
+ if (!chosen) return;
720
+ setStatus(ctx, `pippi: connecting to ${chosen}…`);
721
+ await bridge.connectTo(chosen);
722
+ // The link comes up asynchronously; give it a few seconds.
723
+ for (let attempt = 0; attempt < 20 && !bridge.connected; attempt++) await sleep(500);
724
+ if (bridge.connected) {
725
+ await bridge.pollStatus();
726
+ notify(ctx, `Connected to ${bridge.state.name ?? chosen}.`, "info");
727
+ } else {
728
+ notify(
729
+ ctx,
730
+ `Could not connect to ${chosen}${bridge.state.error ? `: ${bridge.state.error}` : ""}. If pairing starts, type the 6-digit passkey the device shows.`,
731
+ "error",
732
+ );
733
+ }
734
+ renderStatus(ctx);
735
+ }
736
+
737
+ async function pushCharacter(dir: string, ctx: ExtensionContext): Promise<void> {
738
+ if (!dir) {
739
+ notify(ctx, "Usage: /pippi push <folder> (flat folder: manifest.json + GIFs)", "info");
740
+ return;
741
+ }
742
+ if (!bridge.connected) {
743
+ notify(ctx, "Not connected to a pippi.", "warning");
744
+ return;
745
+ }
746
+ const root = path.resolve(ctx.cwd ?? process.cwd(), dir);
747
+ const files = collectCharacterFiles(root);
748
+ if ("error" in files) {
749
+ notify(ctx, files.error, "error");
750
+ return;
751
+ }
752
+ if (files.length === 0) {
753
+ notify(ctx, `${root} has no transferable files.`, "warning");
754
+ return;
755
+ }
756
+ const packName = characterName(root, files);
757
+ const total = files.reduce((sum, file) => sum + file.data.length, 0);
758
+ notify(ctx, `Pushing “${packName}” (${files.length} files, ${total} bytes)…`, "info");
759
+ let lastBucket = -1;
760
+ const result = await bridge.pushCharacter(files, {
761
+ name: packName,
762
+ onProgress: (sent) => {
763
+ const bucket = Math.floor((sent / Math.max(1, total)) * 20);
764
+ if (bucket !== lastBucket) {
765
+ lastBucket = bucket;
766
+ setStatus(ctx, `pippi: push ${bucket * 5}%`);
767
+ }
768
+ },
769
+ });
770
+ setStatus(ctx, undefined);
771
+ notify(ctx, result.ok ? `Pushed “${packName}” to the pippi.` : `Push failed: ${result.error}`, result.ok ? "info" : "error");
772
+ }
773
+ }
774
+
775
+ /**
776
+ * Folder-push payload: flat, regular files, dotfiles skipped (REFERENCE.md).
777
+ * Returns { error } instead of throwing so callers can surface a clean message.
778
+ */
779
+ export function collectCharacterFiles(
780
+ root: string,
781
+ ): Array<{ name: string; data: Buffer }> | { error: string } {
782
+ let names: string[];
783
+ try {
784
+ names = fs.readdirSync(root);
785
+ } catch (error) {
786
+ return { error: `Cannot read ${root}: ${(error as Error).message}` };
787
+ }
788
+ const files: Array<{ name: string; data: Buffer }> = [];
789
+ for (const name of [...names].sort()) {
790
+ if (name.startsWith(".")) continue;
791
+ const full = path.join(root, name);
792
+ let stat: fs.Stats;
793
+ try {
794
+ stat = fs.statSync(full);
795
+ } catch {
796
+ continue;
797
+ }
798
+ if (!stat.isFile() || stat.size === 0) continue;
799
+ try {
800
+ files.push({ name, data: fs.readFileSync(full) });
801
+ } catch {
802
+ continue;
803
+ }
804
+ }
805
+ return files;
806
+ }
807
+
808
+ /** manifest.json "name" wins over the folder name, like the desktop bridge. */
809
+ export function characterName(root: string, files: Array<{ name: string; data: Buffer }>): string {
810
+ const manifest = files.find((file) => file.name === "manifest.json");
811
+ if (manifest) {
812
+ try {
813
+ const parsed = JSON.parse(manifest.data.toString("utf8")) as { name?: unknown };
814
+ if (typeof parsed.name === "string" && parsed.name.trim()) return parsed.name.trim();
815
+ } catch {
816
+ /* fall back to the folder name */
817
+ }
818
+ }
819
+ return path.basename(root);
820
+ }
821
+
822
+ function sleep(ms: number): Promise<void> {
823
+ return new Promise((resolve) => {
824
+ const timer = setTimeout(resolve, ms);
825
+ timer.unref?.();
826
+ });
827
+ }