@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/CHANGELOG.md +13 -0
- package/README.md +415 -2
- package/approvals.ts +552 -0
- package/ble.ts +1062 -0
- package/bluez.ts +962 -0
- package/bridge.ts +1759 -0
- package/claims.ts +453 -0
- package/index.ts +827 -0
- package/package.json +53 -4
- package/protocol.ts +593 -0
- package/simulate.ts +249 -0
- package/state.ts +91 -0
- package/transport.ts +183 -0
- package/usage.ts +959 -0
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clothespin/pi-pippi",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "pi extension that drives an M5Stack desk-pet pippi over BLE",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi-extension",
|
|
9
|
+
"pippi",
|
|
10
|
+
"m5stack",
|
|
11
|
+
"ble"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/clothespin/pi-pippi.git",
|
|
17
|
+
"directory": "bridges/pi"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/clothespin/pi-pippi#readme",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/clothespin/pi-pippi/issues"
|
|
22
|
+
},
|
|
23
|
+
"pi": {
|
|
24
|
+
"extensions": [
|
|
25
|
+
"./index.ts"
|
|
26
|
+
]
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"index.ts",
|
|
30
|
+
"approvals.ts",
|
|
31
|
+
"ble.ts",
|
|
32
|
+
"bluez.ts",
|
|
33
|
+
"bridge.ts",
|
|
34
|
+
"claims.ts",
|
|
35
|
+
"protocol.ts",
|
|
36
|
+
"simulate.ts",
|
|
37
|
+
"state.ts",
|
|
38
|
+
"transport.ts",
|
|
39
|
+
"usage.ts",
|
|
40
|
+
"README.md",
|
|
41
|
+
"CHANGELOG.md"
|
|
42
|
+
],
|
|
43
|
+
"scripts": {
|
|
44
|
+
"test": "node --import ./tests/sandbox_board.mjs --test tests/",
|
|
45
|
+
"test:protocol": "node --test tests/protocol.test.ts"
|
|
46
|
+
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@earendil-works/pi-coding-agent": "^1.7.0",
|
|
52
|
+
"@types/node": "^26.6.11",
|
|
53
|
+
"typescript": "^7.0.2"
|
|
54
|
+
}
|
|
55
|
+
}
|
package/protocol.ts
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pippi wire protocol: constants, payload types, and encoders that respect
|
|
3
|
+
* the *device-side* buffer budgets.
|
|
4
|
+
*
|
|
5
|
+
* The budgets below are not style preferences. They come from the firmware, and
|
|
6
|
+
* they are named by symbol rather than by line number: line numbers move whenever
|
|
7
|
+
* a comment grows, and a stale one is worse than none.
|
|
8
|
+
*
|
|
9
|
+
* data.h TamaState::msg[24] -> 23 UTF-8 bytes + NUL
|
|
10
|
+
* data.h TamaState::TRANSCRIPT_MAX = 12 -> at most 12 entries, 91 bytes each,
|
|
11
|
+
* which is how far back the device's pane scrolls
|
|
12
|
+
* data.h TamaState::promptId[40] -> 39 bytes
|
|
13
|
+
* data.h TamaState::promptTool[20] -> 19 bytes
|
|
14
|
+
* data.h TamaState::promptHint[44] -> 43 bytes
|
|
15
|
+
* data.h TamaState::promptTag[8] -> 7 bytes, ASCII
|
|
16
|
+
* data.h _LineBuf<1024> -> a longer line is truncated
|
|
17
|
+
* by the device and the
|
|
18
|
+
* truncated JSON fails to
|
|
19
|
+
* parse, so it is dropped
|
|
20
|
+
* ble_bridge.cpp RX_CAP = 2048 -> the BLE ring holds ~2 lines;
|
|
21
|
+
* flooding it drops bytes
|
|
22
|
+
*
|
|
23
|
+
* Everything this bridge sends goes through encodeLine(), which refuses to
|
|
24
|
+
* emit a line the device cannot parse.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
// Nordic UART Service (see REFERENCE.md "Transport").
|
|
28
|
+
export const NUS_SERVICE_UUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
|
|
29
|
+
export const NUS_RX_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"; // bridge -> device
|
|
30
|
+
export const NUS_TX_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"; // device -> bridge
|
|
31
|
+
|
|
32
|
+
/** Device line buffer is 1024 bytes incl. NUL; keep headroom for the LF. */
|
|
33
|
+
export const MAX_LINE_BYTES = 1000;
|
|
34
|
+
/** REFERENCE.md: turn events larger than this are dropped by the bridge. */
|
|
35
|
+
export const MAX_TURN_BYTES = 4096;
|
|
36
|
+
|
|
37
|
+
export const MAX_MSG_BYTES = 23;
|
|
38
|
+
/**
|
|
39
|
+
* The pane's depth: TRANSCRIPT_ROWS in board.h says how many lines the panel shows,
|
|
40
|
+
* and this says how many the bridge is willing to send. They are the same number by
|
|
41
|
+
* construction -- sending more would only mean the device drops them on the floor --
|
|
42
|
+
* and fourteen of them still fit the line budget with ordinary entries, which is
|
|
43
|
+
* what "a full pane of ordinary entries reaches the device whole" measures.
|
|
44
|
+
*/
|
|
45
|
+
export const MAX_ENTRIES = 14;
|
|
46
|
+
export const MAX_ENTRY_BYTES = 91;
|
|
47
|
+
export const MAX_PROMPT_ID_BYTES = 39;
|
|
48
|
+
export const MAX_PROMPT_TOOL_BYTES = 19;
|
|
49
|
+
export const MAX_PROMPT_HINT_BYTES = 43;
|
|
50
|
+
/**
|
|
51
|
+
* Which pi session is asking, shown beside "approve? 12s" on the approval line.
|
|
52
|
+
* Seven because that is what is left on a 240px panel once the timer is drawn,
|
|
53
|
+
* and it is the device's field (src/data.h promptTag[8]) that decides it.
|
|
54
|
+
*/
|
|
55
|
+
export const MAX_PROMPT_TAG_BYTES = 7;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The badge key on the wire. Fifteen because the device stores it in a fixed
|
|
59
|
+
* field (`char provider[16]` in src/data.h) and the last byte has to be free for
|
|
60
|
+
* the terminator the parser assumes.
|
|
61
|
+
*
|
|
62
|
+
* Truncating here rather than there is what makes a fallback square's colour
|
|
63
|
+
* stable: the firmware hashes the key it was sent, so if the device silently
|
|
64
|
+
* chopped a long gateway name, the same gateway configured twice could be drawn
|
|
65
|
+
* two colours by two builds of the bridge. Clamped in one place, hashed from what
|
|
66
|
+
* arrived, reproducible with `python3 tools/make_badges.py --check-hash <key>`.
|
|
67
|
+
*/
|
|
68
|
+
export const MAX_PROVIDER_BYTES = 15;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The oldest firmware release this bridge agrees to drive, as documented in
|
|
72
|
+
* REFERENCE.md's Compatibility section: the handshake is the first `status`
|
|
73
|
+
* ack after connect, and `version` is compared against this floor.
|
|
74
|
+
*
|
|
75
|
+
* 0.1.0 is the release that introduced `status.version` itself: older
|
|
76
|
+
* firmware omits the field, and an omitted version is an unknown version --
|
|
77
|
+
* warned about, never assumed compatible. Bump this only when a wire change
|
|
78
|
+
* makes driving an older panel actually unsafe or silently wrong; additive
|
|
79
|
+
* fields never raise the floor.
|
|
80
|
+
*/
|
|
81
|
+
export const MIN_FIRMWARE_VERSION = "0.1.0";
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Compares dotted `major.minor.patch` strings numerically, so "1.10.0" is
|
|
85
|
+
* newer than "1.9.0" -- a string compare would insist otherwise. Non-numeric
|
|
86
|
+
* or missing parts are not a version at all: null, which callers treat as
|
|
87
|
+
* unknown rather than zero.
|
|
88
|
+
*/
|
|
89
|
+
export function compareVersions(a: string, b: string): number | null {
|
|
90
|
+
const pa = a.split(".").map(Number);
|
|
91
|
+
const pb = b.split(".").map(Number);
|
|
92
|
+
if (pa.length !== 3 || pb.length !== 3 || [...pa, ...pb].some(Number.isNaN)) return null;
|
|
93
|
+
for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] < pb[i] ? -1 : 1;
|
|
94
|
+
return 0;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The provider ids the firmware has art for, byte for byte the list published
|
|
99
|
+
* as provider_badges.json by the pippi-m5stack repository's make_badges.py.
|
|
100
|
+
* tests/provider.test.ts fails the two lists apart against the vendored
|
|
101
|
+
* fixture, because a key the bridge invents and the device has never heard of
|
|
102
|
+
* is drawn as a hash square and reads as a bug in the logo rather than a gap
|
|
103
|
+
* in the roster.
|
|
104
|
+
*/
|
|
105
|
+
export const PROVIDER_BADGE_KEYS: readonly string[] = [
|
|
106
|
+
"anthropic",
|
|
107
|
+
"deepseek",
|
|
108
|
+
"google",
|
|
109
|
+
"huggingface",
|
|
110
|
+
"lmstudio",
|
|
111
|
+
"meta",
|
|
112
|
+
"minimax",
|
|
113
|
+
"mistral",
|
|
114
|
+
"moonshot",
|
|
115
|
+
"ollama",
|
|
116
|
+
"openai",
|
|
117
|
+
"qwen",
|
|
118
|
+
"sglang",
|
|
119
|
+
"strata",
|
|
120
|
+
"vllm",
|
|
121
|
+
"xai",
|
|
122
|
+
];
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Spellings that mean a provider on that list. The left-hand side is the spelling
|
|
126
|
+
* after the same lowercasing and punctuation strip providerBadgeKey() applies, so
|
|
127
|
+
* `openai-codex` arrives here as `openaicodex`.
|
|
128
|
+
*
|
|
129
|
+
* Every entry is a name pi or its user has been seen to report for somebody else:
|
|
130
|
+
* `moonshotai` is what pi's own model catalog calls Moonshot, and Kimi is what it
|
|
131
|
+
* sells under (docs/providers.md: "Kimi For Coding"); `openai-codex` appears in
|
|
132
|
+
* pi's distribution; `gemini` is Google's brand and `GEMINI_API_KEY` its variable;
|
|
133
|
+
* Qwen's two plan providers are both Qwen; `llama-server` is the binary a llama.cpp
|
|
134
|
+
* user starts. A gateway that is not here -- openrouter, groq, cerebras -- is a
|
|
135
|
+
* real answer and gets its own square, which is the truth: it is not Anthropic's
|
|
136
|
+
* account, it is somebody's proxy.
|
|
137
|
+
*/
|
|
138
|
+
const PROVIDER_BADGE_ALIASES: Readonly<Record<string, string>> = {
|
|
139
|
+
openaicodex: "openai",
|
|
140
|
+
gemini: "google",
|
|
141
|
+
googlevertexai: "google",
|
|
142
|
+
googlegemini: "google",
|
|
143
|
+
mistralai: "mistral",
|
|
144
|
+
moonshotai: "moonshot",
|
|
145
|
+
kimi: "moonshot",
|
|
146
|
+
kimiforcoding: "moonshot",
|
|
147
|
+
qwentokenplanteam: "qwen",
|
|
148
|
+
qwentokenplanindividual: "qwen",
|
|
149
|
+
hf: "huggingface",
|
|
150
|
+
huggingface: "huggingface",
|
|
151
|
+
lmstudioai: "lmstudio",
|
|
152
|
+
llamaserver: "llamacpp",
|
|
153
|
+
mlcllm: "mlc",
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The one key a badge is looked up by, from whatever the session's provider is
|
|
158
|
+
* actually called: lower case, no punctuation, alias resolved, clamped to the wire
|
|
159
|
+
* field. Returns undefined for nothing-to-draw, which is the same answer an empty
|
|
160
|
+
* string gives and is sent as no field at all.
|
|
161
|
+
*
|
|
162
|
+
* The strip is not cosmetic. Two windows on the same server spelled `llama-swap`
|
|
163
|
+
* and `llama_swap` have to be the same colour square, or the badge is a riddle
|
|
164
|
+
* about how the user typed a config file instead of a fact about the model.
|
|
165
|
+
*/
|
|
166
|
+
export function providerBadgeKey(provider: string | null | undefined): string | undefined {
|
|
167
|
+
if (!provider) return undefined;
|
|
168
|
+
const cleaned = provider.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
169
|
+
if (!cleaned) return undefined;
|
|
170
|
+
const key = PROVIDER_BADGE_ALIASES[cleaned] ?? cleaned;
|
|
171
|
+
return truncateBytes(key, MAX_PROVIDER_BYTES);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Snapshot the bridge pushes on every change and as a ~10s keepalive. */
|
|
175
|
+
export interface Snapshot {
|
|
176
|
+
total: number;
|
|
177
|
+
running: number;
|
|
178
|
+
waiting: number;
|
|
179
|
+
/** Drives the device's "celebrate" face; not in REFERENCE.md but the firmware reads it (pippi-m5stack src/data.h:96). */
|
|
180
|
+
completed?: boolean;
|
|
181
|
+
msg: string;
|
|
182
|
+
entries: string[];
|
|
183
|
+
tokens: number;
|
|
184
|
+
tokens_today: number;
|
|
185
|
+
/**
|
|
186
|
+
* Context window in use, 0-100 percent, rendered as the pet's "ctx" gauge.
|
|
187
|
+
* Omitted when pi cannot say: before a model is picked there is no window
|
|
188
|
+
* size to divide by, and usage reads unknown straight after a compaction.
|
|
189
|
+
* Absent is not the same as 0 — the firmware shows "n/a" rather than an
|
|
190
|
+
* empty bar, so a fresh session and an unreported one stay distinguishable.
|
|
191
|
+
*/
|
|
192
|
+
ctx?: number;
|
|
193
|
+
/**
|
|
194
|
+
* Generation speed, tokens per second, measured by the bridge:
|
|
195
|
+
* `prefill` is prompt tokens divided by time-to-first-token, `decode` is
|
|
196
|
+
* output tokens divided by streaming time. Both are rolling means over the
|
|
197
|
+
* last few responses (see PippiBridge.noteResponseSpeed). Omitted until a
|
|
198
|
+
* response has been timed, so the pet draws "n/a" rather than 0/s.
|
|
199
|
+
*/
|
|
200
|
+
prefill?: number;
|
|
201
|
+
decode?: number;
|
|
202
|
+
/**
|
|
203
|
+
* Which half of a response the model is in right now: `prefill` is reading
|
|
204
|
+
* the prompt (waiting for the first token), `decode` is writing the answer.
|
|
205
|
+
* The status LED breathes at two different rates for exactly this, so the
|
|
206
|
+
* person across the room can tell "still thinking" from "answering".
|
|
207
|
+
*
|
|
208
|
+
* Transient by nature, so a snapshot that omits it means "no phase", not
|
|
209
|
+
* "unchanged": the device clears its field on absent, the same rule the
|
|
210
|
+
* prompt uses. A phase the device remembers after the turn ended would keep
|
|
211
|
+
* the light breathing over a machine that has stopped working.
|
|
212
|
+
*/
|
|
213
|
+
phase?: Phase;
|
|
214
|
+
/**
|
|
215
|
+
* Provider allowance or balance, from the usage protocol on pi's event bus.
|
|
216
|
+
* Omitted when there is no such service in this session, which is the normal
|
|
217
|
+
* state of things and not an error: no service, no row.
|
|
218
|
+
*/
|
|
219
|
+
usage?: UsageInfo;
|
|
220
|
+
/**
|
|
221
|
+
* Who is answering: the badge key from providerBadgeKey(), the same list the
|
|
222
|
+
* firmware has art for. The pet is drawn on the left of the home screen and the
|
|
223
|
+
* provider's mark on the right, so a desk with three windows can see which one
|
|
224
|
+
* is Opus without leaning over.
|
|
225
|
+
*
|
|
226
|
+
* Absent means "no provider", not "unchanged", the rule `phase` and `prompt`
|
|
227
|
+
* document: a mark held on after the session moved to another provider would
|
|
228
|
+
* attribute a turn to the wrong company, which is the one thing the badge is
|
|
229
|
+
* there to get right. An id the firmware has no art for is not a reason to say
|
|
230
|
+
* nothing -- it draws a square coloured from a hash of the key and the key's
|
|
231
|
+
* initial, which is stable, distinctive, and honest about not being a logo.
|
|
232
|
+
*/
|
|
233
|
+
provider?: string;
|
|
234
|
+
prompt?: Prompt;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export type Phase = "prefill" | "decode";
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* What the other half of the desk costs, as the pet's usage rows.
|
|
241
|
+
*
|
|
242
|
+
* A list, because one account rarely has one counter: a Claude subscription has a
|
|
243
|
+
* five-hour window, a seven-day window, and a second seven-day window scoped to one
|
|
244
|
+
* model family, and a meter that quietly reduced those to a single percentage would
|
|
245
|
+
* be reporting something the provider never said. Each meter carries the tag it is
|
|
246
|
+
* drawn under, so a row reading `7d 41%` means that window and not the average of
|
|
247
|
+
* everything the account happens to track.
|
|
248
|
+
*
|
|
249
|
+
* Two kinds of meter, because buying model time is done in two currencies of idea:
|
|
250
|
+
*
|
|
251
|
+
* pct a ceiling with a window: cells that are full straight after a reset and
|
|
252
|
+
* drain as it is spent. `pct` is what is *left*, which is the opposite of
|
|
253
|
+
* the "ctx" gauge above it.
|
|
254
|
+
* money what is still there and what has gone, in minor units. Either half may
|
|
255
|
+
* be absent on its own, because an API key with no spending cap genuinely
|
|
256
|
+
* has a spend and no balance.
|
|
257
|
+
*
|
|
258
|
+
* Absent altogether is how "this session has no usage service" travels, and the
|
|
259
|
+
* device draws no rows for it — the rows are not there to be wrong about.
|
|
260
|
+
*/
|
|
261
|
+
export interface UsageMeter {
|
|
262
|
+
/** Drawn beside the bar, so a short tag is the whole label: "5h", "7d", "7d*". */
|
|
263
|
+
tag: string;
|
|
264
|
+
pct?: number;
|
|
265
|
+
left?: number;
|
|
266
|
+
used?: number;
|
|
267
|
+
cur?: string;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export interface UsageInfo {
|
|
271
|
+
/**
|
|
272
|
+
* Tightest first: the meter most likely to be the reason the next request fails
|
|
273
|
+
* belongs at the top, and a panel with room for two shows the two that matter.
|
|
274
|
+
*/
|
|
275
|
+
meters: UsageMeter[];
|
|
276
|
+
/**
|
|
277
|
+
* Below this percentage a bar is not merely low but alarming, and the device
|
|
278
|
+
* blinks it. Carried with the data rather than kept on the pet, because it is a
|
|
279
|
+
* judgement about the account ("I am nervous at 5% of my weekly window") and the
|
|
280
|
+
* settings screen is a dozen keypresses away from the desk where that is obvious.
|
|
281
|
+
* Absent means the default.
|
|
282
|
+
*/
|
|
283
|
+
low?: number;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** What counts as alarming when nobody has said. */
|
|
287
|
+
export const USAGE_LOW_DEFAULT = 5;
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Meters per report on the wire. Three is what the widest panel has room for and
|
|
291
|
+
* every provider seen so far stays under; the clamp exists so that a provider
|
|
292
|
+
* inventing a fourth window cannot decide the height of the stats screen by itself.
|
|
293
|
+
*/
|
|
294
|
+
export const MAX_USAGE_METERS = 3;
|
|
295
|
+
|
|
296
|
+
/** Tag length in bytes, because it is drawn in a fixed field next to the bar. */
|
|
297
|
+
export const MAX_USAGE_TAG_BYTES = 6;
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Money on the wire is integer minor units. The ceiling is $999,999.99 because
|
|
301
|
+
* the device holds it in a uint32, and an account that large is a conversation
|
|
302
|
+
* to have with the provider's account manager rather than a number to draw on a
|
|
303
|
+
* 240px panel; a bigger reading would be a provider reporting something the tool
|
|
304
|
+
* has not thought about.
|
|
305
|
+
*/
|
|
306
|
+
export const MAX_MONEY_MINOR = 99_999_999;
|
|
307
|
+
|
|
308
|
+
export interface Prompt {
|
|
309
|
+
id: string;
|
|
310
|
+
tool: string;
|
|
311
|
+
hint: string;
|
|
312
|
+
/**
|
|
313
|
+
* Label for the session that is asking, so a person with several pi windows
|
|
314
|
+
* open knows whose `rm` they are approving from across the room. Optional:
|
|
315
|
+
* a bridge that sends none leaves the approval line as it always looked.
|
|
316
|
+
*/
|
|
317
|
+
tag?: string;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** One-shot event for a finished turn (Anthropic-style content blocks). */
|
|
321
|
+
export interface TurnEvent {
|
|
322
|
+
evt: "turn";
|
|
323
|
+
role: "assistant";
|
|
324
|
+
content: unknown[];
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export interface DeviceAck {
|
|
328
|
+
ack: string;
|
|
329
|
+
ok?: boolean;
|
|
330
|
+
n?: number;
|
|
331
|
+
error?: string;
|
|
332
|
+
data?: Record<string, unknown>;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Device -> bridge permission decision (src/main.cpp BtnA/BtnB handlers). */
|
|
336
|
+
export interface PermissionDecision {
|
|
337
|
+
cmd: "permission";
|
|
338
|
+
id: string;
|
|
339
|
+
decision: "once" | "deny";
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export function byteLength(value: string): number {
|
|
343
|
+
return new TextEncoder().encode(value).length;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Truncate to at most `maxBytes` UTF-8 bytes, never splitting a code point.
|
|
348
|
+
* Adds "…" when anything was dropped, and the ellipsis is part of the budget.
|
|
349
|
+
*/
|
|
350
|
+
export function truncateBytes(value: string, maxBytes: number): string {
|
|
351
|
+
const encoder = new TextEncoder();
|
|
352
|
+
if (encoder.encode(value).length <= maxBytes) return value;
|
|
353
|
+
if (maxBytes <= 0) return "";
|
|
354
|
+
const ellipsis = "…";
|
|
355
|
+
const ellipsisBytes = encoder.encode(ellipsis).length;
|
|
356
|
+
if (maxBytes < ellipsisBytes) return "";
|
|
357
|
+
let out = "";
|
|
358
|
+
let bytes = 0;
|
|
359
|
+
const limit = maxBytes - ellipsisBytes;
|
|
360
|
+
for (const ch of value) {
|
|
361
|
+
const size = encoder.encode(ch).length;
|
|
362
|
+
if (bytes + size > limit) break;
|
|
363
|
+
out += ch;
|
|
364
|
+
bytes += size;
|
|
365
|
+
}
|
|
366
|
+
return out + ellipsis;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* A session tag as the panel can draw it: printable ASCII, at most `maxBytes` of
|
|
371
|
+
* them. Not truncateBytes -- that appends "…", three UTF-8 bytes the device font
|
|
372
|
+
* has no glyph for, and a tag is exactly the field that must never render as a
|
|
373
|
+
* hole. Whitespace joins with a hyphen rather than vanishing, because "two wor"
|
|
374
|
+
* still reads as two words while "twowo" reads as a typo. Non-ASCII is dropped
|
|
375
|
+
* rather than transliterated (café -> caf), which is also why character count and
|
|
376
|
+
* byte count agree here. Returns "" when nothing survives; the caller decides on a
|
|
377
|
+
* fallback.
|
|
378
|
+
*/
|
|
379
|
+
export function sanitizeTag(value: string, maxBytes = MAX_PROMPT_TAG_BYTES): string {
|
|
380
|
+
let out = "";
|
|
381
|
+
for (const char of value.trim().replace(/\s+/g, "-")) {
|
|
382
|
+
const code = char.codePointAt(0) ?? 0;
|
|
383
|
+
if (code < 0x21 || code > 0x7e) continue;
|
|
384
|
+
if (out.length + 1 > maxBytes) break;
|
|
385
|
+
out += char;
|
|
386
|
+
}
|
|
387
|
+
return out;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Collapse newlines/tabs and trim so a value fits on a 12px OLED line. */
|
|
391
|
+
export function oneLine(value: string): string {
|
|
392
|
+
return value.replace(/[\r\n\t]+/g, " ").replace(/\s{2,}/g, " ").trim();
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Tokens/second for the pet's speed rows: finite, positive, rounded. Zero and
|
|
397
|
+
* negative become undefined rather than 0, because "never measured" and "infinitely
|
|
398
|
+
* slow" must not render the same way. The ceiling is not a claim about hardware;
|
|
399
|
+
* it keeps a nonsense sample inside the field width the device reserves.
|
|
400
|
+
*/
|
|
401
|
+
function rateOrUndefined(value: number | undefined): number | undefined {
|
|
402
|
+
if (value === undefined || !Number.isFinite(value) || value <= 0) return undefined;
|
|
403
|
+
return Math.min(99_999, Math.round(value));
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Normalise a snapshot so every field respects a device budget. */
|
|
407
|
+
export function clampSnapshot(snapshot: Snapshot): Snapshot {
|
|
408
|
+
const clamped: Snapshot = {
|
|
409
|
+
total: Math.max(0, Math.trunc(snapshot.total)),
|
|
410
|
+
running: Math.max(0, Math.trunc(snapshot.running)),
|
|
411
|
+
waiting: Math.max(0, Math.trunc(snapshot.waiting)),
|
|
412
|
+
msg: truncateBytes(oneLine(snapshot.msg), MAX_MSG_BYTES),
|
|
413
|
+
entries: snapshot.entries
|
|
414
|
+
.slice(0, MAX_ENTRIES)
|
|
415
|
+
.map((entry) => truncateBytes(oneLine(entry), MAX_ENTRY_BYTES)),
|
|
416
|
+
tokens: Math.max(0, Math.trunc(snapshot.tokens)),
|
|
417
|
+
tokens_today: Math.max(0, Math.trunc(snapshot.tokens_today)),
|
|
418
|
+
};
|
|
419
|
+
if (snapshot.completed !== undefined) clamped.completed = snapshot.completed;
|
|
420
|
+
// Round and clamp: the gauge has ten cells and no use for a fraction, and a
|
|
421
|
+
// provider that over-reports must not push the firmware past full.
|
|
422
|
+
if (snapshot.ctx !== undefined && Number.isFinite(snapshot.ctx)) {
|
|
423
|
+
clamped.ctx = Math.max(0, Math.min(100, Math.round(snapshot.ctx)));
|
|
424
|
+
}
|
|
425
|
+
// Tokens/second as integers, and only when there is a rate to report: a key
|
|
426
|
+
// holding undefined would reach the pet as "present" and draw 0/s where the
|
|
427
|
+
// device wants to show "n/a". The ceiling is absurdly generous on purpose --
|
|
428
|
+
// it exists so a nonsense rate cannot blow the firmware's field width, not to
|
|
429
|
+
// describe real hardware.
|
|
430
|
+
const prefill = rateOrUndefined(snapshot.prefill);
|
|
431
|
+
if (prefill !== undefined) clamped.prefill = prefill;
|
|
432
|
+
const decode = rateOrUndefined(snapshot.decode);
|
|
433
|
+
if (decode !== undefined) clamped.decode = decode;
|
|
434
|
+
// Enumerated rather than passed through: the firmware switches on the string,
|
|
435
|
+
// so a value it has never heard of must not reach it at all. Omitting is also
|
|
436
|
+
// how "no phase" travels, which is why there is no else branch here.
|
|
437
|
+
if (snapshot.phase === "prefill" || snapshot.phase === "decode") {
|
|
438
|
+
clamped.phase = snapshot.phase;
|
|
439
|
+
}
|
|
440
|
+
const usage = snapshot.usage ? clampUsage(snapshot.usage) : undefined;
|
|
441
|
+
// An empty list and no usage at all are the same message, and it is "no rows":
|
|
442
|
+
// sending `{"meters":[]}` would have the firmware clear a row it was already not
|
|
443
|
+
// showing, at the cost of a field on every snapshot forever after.
|
|
444
|
+
if (usage) clamped.usage = usage;
|
|
445
|
+
// Same rule, one step lower: an empty provider is no provider, and the device
|
|
446
|
+
// clears its field on absent, so `"provider":""` would be a second way to spell
|
|
447
|
+
// the thing the absent case already spells.
|
|
448
|
+
if (snapshot.provider) {
|
|
449
|
+
clamped.provider = truncateBytes(oneLine(snapshot.provider), MAX_PROVIDER_BYTES);
|
|
450
|
+
}
|
|
451
|
+
if (snapshot.prompt) {
|
|
452
|
+
clamped.prompt = {
|
|
453
|
+
id: truncateBytes(snapshot.prompt.id, MAX_PROMPT_ID_BYTES),
|
|
454
|
+
tool: truncateBytes(oneLine(snapshot.prompt.tool), MAX_PROMPT_TOOL_BYTES),
|
|
455
|
+
hint: truncateBytes(oneLine(snapshot.prompt.hint), MAX_PROMPT_HINT_BYTES),
|
|
456
|
+
};
|
|
457
|
+
// Omit rather than send "": an empty tag and no tag should not be two
|
|
458
|
+
// different things on the wire, and the device clears its field on absent.
|
|
459
|
+
const tag = sanitizeTag(snapshot.prompt.tag ?? "");
|
|
460
|
+
if (tag) clamped.prompt.tag = tag;
|
|
461
|
+
}
|
|
462
|
+
return clamped;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* A tag that fits the field it is drawn in, in the alphabet that field can render.
|
|
467
|
+
*
|
|
468
|
+
* Not truncateBytes: that ends a shortened string with an ellipsis, and the tag is
|
|
469
|
+
* drawn in six pixels of the panel's ASCII glyph set, where the ellipsis is a
|
|
470
|
+
* different character than the one the sender had in mind. A tag should arrive
|
|
471
|
+
* already short (normalisation derives them from window lengths); this is the
|
|
472
|
+
* backstop for a provider that sends something else, and it must not make the string
|
|
473
|
+
* harder to read on its way past.
|
|
474
|
+
*/
|
|
475
|
+
function clampTag(tag: string): string {
|
|
476
|
+
const flat = oneLine(tag).replace(/[^ -~]/g, "");
|
|
477
|
+
return flat.slice(0, MAX_USAGE_TAG_BYTES);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* The usage row's fields, validated on the way out rather than trusted on the way
|
|
482
|
+
* in: the numbers come from a provider's HTTP response, reached through another
|
|
483
|
+
* extension, and the firmware has a uint32 and a fixed-width row waiting at the
|
|
484
|
+
* other end. A reading that cannot be drawn honestly is dropped, since a wrong
|
|
485
|
+
* "5% left" is worse than no bar at all.
|
|
486
|
+
*/
|
|
487
|
+
function clampUsage(usage: UsageInfo): UsageInfo | undefined {
|
|
488
|
+
const meters: UsageMeter[] = [];
|
|
489
|
+
for (const meter of usage.meters ?? []) {
|
|
490
|
+
// Built key by key so an unknown figure stays absent rather than arriving as an
|
|
491
|
+
// explicit null the firmware would have to distinguish from zero.
|
|
492
|
+
const out: UsageMeter = { tag: clampTag(meter.tag) };
|
|
493
|
+
if (meter.pct !== undefined && Number.isFinite(meter.pct)) {
|
|
494
|
+
// Round and clamp: the bar has ten cells, and a provider that over-reports
|
|
495
|
+
// must not push the firmware past full.
|
|
496
|
+
out.pct = Math.max(0, Math.min(100, Math.round(meter.pct)));
|
|
497
|
+
}
|
|
498
|
+
const money = (value: number | undefined): number | undefined =>
|
|
499
|
+
value === undefined || !Number.isFinite(value) || value < 0
|
|
500
|
+
? undefined
|
|
501
|
+
: Math.min(MAX_MONEY_MINOR, Math.round(value));
|
|
502
|
+
const left = money(meter.left);
|
|
503
|
+
const used = money(meter.used);
|
|
504
|
+
if (left !== undefined) out.left = left;
|
|
505
|
+
if (used !== undefined) out.used = used;
|
|
506
|
+
// A currency that is not three uppercase letters would be drawn as garbage next
|
|
507
|
+
// to a number, and a number with a garbage currency is a wrong number.
|
|
508
|
+
if (meter.cur && /^[A-Z]{3}$/.test(meter.cur)) out.cur = meter.cur;
|
|
509
|
+
// A meter with nothing to draw is not a row, and neither is one with nothing to
|
|
510
|
+
// call itself: several windows arriving as identical unlabelled bars is worse
|
|
511
|
+
// than the panel not showing usage at all, because it invites reading one as
|
|
512
|
+
// another. A provider that reports a window we cannot name reports a window we
|
|
513
|
+
// do not draw.
|
|
514
|
+
if (out.tag.length === 0) continue;
|
|
515
|
+
if (out.pct === undefined && left === undefined && used === undefined) continue;
|
|
516
|
+
meters.push(out);
|
|
517
|
+
if (meters.length >= MAX_USAGE_METERS) break;
|
|
518
|
+
}
|
|
519
|
+
if (meters.length === 0) return undefined;
|
|
520
|
+
// Only a deliberate threshold travels: a report whose low is the default is the
|
|
521
|
+
// same message as a report that says nothing, and the smaller wire is the one
|
|
522
|
+
// where a field's absence never means two things.
|
|
523
|
+
const low =
|
|
524
|
+
usage.low === undefined || !Number.isFinite(usage.low)
|
|
525
|
+
? undefined
|
|
526
|
+
: Math.max(0, Math.min(100, Math.round(usage.low)));
|
|
527
|
+
return low === undefined || low === USAGE_LOW_DEFAULT ? { meters } : { meters, low };
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Serialise a snapshot, dropping transcript entries from the tail until the
|
|
532
|
+
* line fits the device's 1024 byte line buffer. Entries are the only variable
|
|
533
|
+
* bulk in a snapshot, so this always converges.
|
|
534
|
+
*/
|
|
535
|
+
export function encodeSnapshot(snapshot: Snapshot): string {
|
|
536
|
+
let candidate = clampSnapshot(snapshot);
|
|
537
|
+
let line = JSON.stringify(candidate);
|
|
538
|
+
while (byteLength(line) > MAX_LINE_BYTES && candidate.entries.length > 0) {
|
|
539
|
+
candidate = { ...candidate, entries: candidate.entries.slice(0, -1) };
|
|
540
|
+
line = JSON.stringify(candidate);
|
|
541
|
+
}
|
|
542
|
+
return line;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Serialise a turn event, or null when it cannot be made to fit. */
|
|
546
|
+
export function encodeTurn(event: TurnEvent): string | null {
|
|
547
|
+
const full = JSON.stringify(event);
|
|
548
|
+
if (byteLength(full) > MAX_TURN_BYTES) return null;
|
|
549
|
+
let content = event.content;
|
|
550
|
+
let line = full;
|
|
551
|
+
while (byteLength(line) > MAX_LINE_BYTES && content.length > 0) {
|
|
552
|
+
// Prefer keeping the leading blocks: they carry the start of the reply.
|
|
553
|
+
content = content.slice(0, -1);
|
|
554
|
+
line = JSON.stringify({ ...event, content });
|
|
555
|
+
}
|
|
556
|
+
return byteLength(line) > MAX_LINE_BYTES ? null : line;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
export function encodeLine(value: unknown): string {
|
|
560
|
+
return JSON.stringify(value);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** Parse one device -> bridge line; returns null for anything not JSON. */
|
|
564
|
+
export function parseDeviceLine(line: string): Record<string, unknown> | null {
|
|
565
|
+
const trimmed = line.trim();
|
|
566
|
+
if (!trimmed.startsWith("{")) return null;
|
|
567
|
+
try {
|
|
568
|
+
const parsed = JSON.parse(trimmed);
|
|
569
|
+
return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : null;
|
|
570
|
+
} catch {
|
|
571
|
+
return null;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Time sync, sent once per connect: REFERENCE.md "One-shot on connect".
|
|
577
|
+
* The device computes local = epoch + offset, so offset is seconds *east* of
|
|
578
|
+
* UTC for the bridge's local zone (PST -> -25200).
|
|
579
|
+
*/
|
|
580
|
+
export function timeSync(now: Date = new Date()): { time: [number, number] } {
|
|
581
|
+
const epoch = Math.floor(now.getTime() / 1000);
|
|
582
|
+
// `|| 0` normalises -0, which JSON would serialise as 0 but would make
|
|
583
|
+
// strict equality tests in UTC environments fail.
|
|
584
|
+
const offset = (-Math.floor(now.getTimezoneOffset() * 60) || 0) as number;
|
|
585
|
+
return { time: [epoch, offset] };
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** Local midnight epoch for the daily token counter's reset boundary. */
|
|
589
|
+
export function localMidnightEpoch(now: Date = new Date()): number {
|
|
590
|
+
const start = new Date(now);
|
|
591
|
+
start.setHours(0, 0, 0, 0);
|
|
592
|
+
return Math.floor(start.getTime() / 1000);
|
|
593
|
+
}
|