Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_net/lens/js/test/adapter/daimond_debugshare.js

53.0 KiB, 1 run

created by r1870400018:65606, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1/* daimond_debugshare.js -- GENERATED by make_adapter.mjs. Daimond's www/js/debugshare.js as it
2 * would stand after adopting fe2o3_net/lens/js/writer.js: its own app layer, cut from its own
3 * file by line range, over the extracted writer core in `__lensCore`.
4 *
5 * It is a classic script, evaluated by Daimond's own test harness exactly as the original is, so
6 * the core arrives as a global the preload supplies; in the page it would be an import.
7 */
8(function () {
9 'use strict';
10 var L = __lensCore;
11
12 'use strict';
13
14 // ── Keys, endpoint, and the transport caps (mirrored from the handler) ──
15 //
16 // These four match `gateway/src/handlers/debug_trace.rs` with a margin, so a
17 // post is never refused for size and a row is never clipped mid-payload:
18 // MAX_BODY 256 KiB -> we keep a post under 200 KiB
19 // MAX_ROWS 1000 -> we put at most 400 rows in a post
20 // MAX_DATA 400 -> we keep a base64 slice at 360 bytes
21 // MIN_INTERVAL_MS 2s -> we drain one post every 3s, ONE clock for every lane
22 var ENABLED_KEY = 'daimond-debugshare'; // the flag itself; '1' is on
23 var STAMP_KEY = 'daimond-debugshare-at'; // ms of the last LOCAL decision, for freshest-wins
24 var LEDGER_KEY = 'daimond-ledger'; // the cost ledger, read directly
25 var SIGNALS_KEY = 'daimond-signals'; // the per-Diamond / per-model signal index
26 var CROSS_KEY = 'daimond-debug-cross'; // our own diamond×model spend cross (while on)
27 var ENDPOINT = '/api/debug-trace';
28 var CLIENT_API = 2; // matches CLIENT_API in gateway.js / diag.js
29
30 var MAX_DATA_BYTES = 360;
31 var MAX_ROWS_POST = 400;
32 var MAX_BODY_BYTES = 200 * 1024;
33 // THE ONE DRAIN INTERVAL, shared by every lane. The gateway floor is 2 s
34 // (gateway/src/handlers/debug_trace.rs MIN_INTERVAL_MS); 3 s leaves margin for
35 // clock skew between the device and the handler. A device that meets an OLDER
36 // gateway -- one still refusing a second post inside ten seconds -- is not
37 // special-cased: its 429s double the gap through `gapMs`, so it degrades to
38 // the pace that gateway will take instead of spamming it.
39 var DRAIN_MS = 3000; // the minimum gap between ANY two posts, all lanes
40
41 var TELEMETRY_MS = 30000; // stream telemetry cadence while on
42 var RESNAP_MS = 300000; // periodic full re-snapshot (5 min)
43
44 var EVENT_KEY = 'daimond-debugshare-outbox'; // the durable outbox
45 var SEQ_KEY = 'daimond-debugshare-seq'; // the per-device sequence `n`
46 var BUILD_KEY = 'daimond-build-seen'; // breadcrumb.js's confirmed build id
47 var POST_AT_KEY = 'daimond-debugshare-lastpost'; // the post clock, so a reload keeps it
48 var BEAT_TICK_MS = 30000; // the beat timer's period ...
49 var BEAT_TURN_MS = 30000; // ... a beat this often while a turn runs ...
50 var BEAT_IDLE_MS = 300000; // ... and this often when nothing is running
51 // THE SCREEN, ADDED 2026-09-13. Every other event says what the ENGINE did; a
52 // phone driven by its own owner has no console to read and no way to be driven
53 // from Linux, so the beat/telemetry/console lanes above are silent about the one
54 // thing "full visibility" actually needs there: what the person is LOOKING AT.
55 // Checked on the SAME clock as the beat (see `beatTick`), so it costs no extra
56 // timer, but it posts its own `ev screen` row only when the picture actually
57 // CHANGED since the last one -- a device sitting on one screen for an hour must
58 // not repeat itself every thirty seconds -- with a floor that ships one anyway
59 // every `SCREEN_FLOOR_MS`, so a reader is never more than five minutes stale.
60 var SCREEN_FLOOR_MS = 300000; // ship one even unchanged, at least this often
61 var MAX_VIEW_CHARS = 24; // the view/thread kind
62 var MAX_SEAT_CHARS = 60; // the seat-line text, as rendered
63 var MAX_TILE_ROLE_CHARS = 16; // the last tile's role ("user", "assistant", ...)
64 var MAX_TILE_TEXT_CHARS = 80; // the last tile's text, head only
65 var MAX_DLG_CHARS = 48; // an open dialog/banner's kind + head
66 var MAX_MSG_CHARS = 200; // an `error` or `console` message, clipped
67 var MAX_SRC_CHARS = 60; // and where it came from
68 // A context drop of more than this fraction between two rounds of one turn is
69 // read as a fold, because the fold itself happens in Rust and emits nothing a
70 // JS caller can see (see `inferFold`). Such an event is marked `inferred:1`.
71 var FOLD_DROP = 0.30;
72 // A REAL fold (the engine's `compacted` event) within this window suppresses
73 // the inferred one, so a fold that IS reported is not also guessed at.
74 var FOLD_REAL_MS = 20000;
75
76 // A transcript embeds whole source-file reads and command outputs verbatim, so
77 // a snapshot was ~7 MB / 25k chunks and drained for ~12 min, starving telemetry
78 // behind it. The one lever is SIZE -- the handler's interval / 400-row / 360-byte
79 // caps mean we cannot post faster -- so a giant string is hard-capped to this
80 // many bytes with a "[+N bytes]" tail that keeps its size visible. The cap is
81 // generous enough to leave an ordinary readable message whole and only bites a
82 // giant tool payload. daimond.js has no `TOOL_ELISION_CAP` to reuse, so it
83 // lives here. Only the free-form arrays (transcripts, trail, diag) are elided;
84 // the structured state stays complete.
85 var ELISION_CAP = 2048;
86
87 // Windowing the transcripts, which is a SEPARATE lever from the per-payload
88 // elision above. Elision caps each STRING; it does nothing about turn COUNT, and
89 // an account with hundreds of turns still shipped every one -- a live trace saw a
90 // ~5.7 MB / ~15,900-chunk snapshot drain for ~7 minutes, and the small per-round
91 // telemetry the developer actually reads starved behind it. So the snapshot keeps
92 // only the MOST RECENT turns: each chat's last `MAX_MSGS_PER_CHAT`, and across all
93 // chats a total `TRANSCRIPT_BUDGET_BYTES` spent freshest-first. A row carries 360
94 // base64 bytes (= 270 raw), so a ~700 KiB transcript budget plus the small
95 // structured state lands the whole snapshot near the ~2,800-row / one-minute
96 // target. ONLY the transcript prose is windowed; every structured section (config,
97 // roster, presence, election, signals, ledger, tokenStats) and ALL telemetry stay
98 // complete and unwindowed -- the live numbers are never cut.
99 var MAX_MSGS_PER_CHAT = 40; // keep each chat's last N turns
100 var TRANSCRIPT_BUDGET_BYTES = 700 * 1024; // total cap across all chats' kept turns
101
102 // The snapshot no longer ships the whole raw cost ledger. Telemetry carries the
103 // per-model / per-Diamond AGGREGATES of it every tick (see aggregateLedger and
104 // signalBreakdown), so the raw ~400-entry array was pure duplicated bulk that
105 // pushed the snapshot past the one-minute drain target and starved the live
106 // numbers behind it. Only the most recent turns are kept, as a tail the operator
107 // can spot-check against the aggregates; the count dropped is recorded so the
108 // tail is read as a window, not a short ledger.
109 var SNAPSHOT_LEDGER_TAIL = 20; // raw ledger entries kept in a snapshot
110
111 // ── App state. What the writer owns (the outbox, the post clock, the console lane) is gone. ──
112 var enabled = read(ENABLED_KEY) === '1';
113 var provider = null; // registered by daimond.js: () -> (obj | Promise<obj>)
114 var statsFn = null; // registered by daimond.js: () -> live-stats obj (sync, cheap)
115 var screenFn = null; // registered by daimond.js: () -> {view,seat,role,text,dlg,comp,locked}
116 var crossIx = {}; // diamondId -> model -> {turns, usd}, filled while on
117 var telQueue = []; // priority lane: telemetry posts, each an array of rows
118 var snapQueue = []; // snapshot lane: drained only when telQueue is empty
119 var telTimer = null, snapTimer = null, beatTimer = null;
120 var lastBeatAt = 0;
121 var lastScreenAt = 0, lastScreenKey = null;
122 var lastCtx = {};
123 var lastRealFold = {};
124 var indicator = null;
125 var lastLedgerLen = 0, lastTrailLen = 0, lastDiagLen = 0;
126
127 function read(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }
128 function write(k, v) { try { localStorage.setItem(k, v); } catch (e) {} }
129 /// The same write, THROWING. `write` swallows, which is right for a flag nobody
130 /// misses -- and wrong for the outbox, whose whole point is durability: its quota
131 /// fallback was written against a function that cannot fail, so the fallback was
132 /// dead code and a full device simply stopped persisting the queue, silently.
133 function writeOrThrow(k, v) { localStorage.setItem(k, v); }
134
135 /// A plain positive-millisecond number, or 0. Bignum-safe -- a stamp that
136 /// round-tripped through the gateway can arrive as a bignum object with a
137 /// `toNumber`, like the presence stamps peer.js reads.
138 function ms(v) {
139 var n = (v && typeof v.toNumber === 'function') ? v.toNumber() : Number(v);
140 return (isFinite(n) && n > 0) ? n : 0;
141 }
142
143 /// Best-effort nudge to the sync engine, so a local flip is pushed to the
144 /// fleet promptly rather than only on the next debounce. Guarded on the global,
145 /// so a build without sync (or a test) pays only a property test.
146 function nudgeSync() {
147 try { if (window.DaimondSync && window.DaimondSync.nudge) window.DaimondSync.nudge(); }
148 catch (e) {}
149 }
150
151 // Restore the diamond×model cross from a previous session, so a device that was
152 // already sharing keeps its tally across a reload.
153 try { crossIx = JSON.parse(read(CROSS_KEY) || '{}') || {}; } catch (e) { crossIx = {}; }
154 function saveCross() { try { write(CROSS_KEY, JSON.stringify(crossIx)); } catch (e) {} }
155
156 /// Record one metered turn's spend against its (Diamond, model) pair -- the one
157 /// cross the ledger (which carries no Diamond) and the signal index (which holds
158 /// Diamond and model separately) cannot answer: which Diamond spent what on
159 /// which model. Called from daimond.js's `recordSpend`, and a no-op unless
160 /// sharing is on, so an off device pays only a guarded call and a flag test.
161 function noteCross(diamondId, model, usd) {
162 if (!enabled) return;
163 var id = diamondId || '(none)';
164 var m = model || '(unknown)';
165 var d = crossIx[id] || (crossIx[id] = {});
166 var r = d[m] || (d[m] = { turns: 0, usd: 0 });
167 r.turns += 1;
168 r.usd += usd || 0;
169 saveCross();
170 }
171
172 // ── Names, content shapes and the redactor: the core's, with Daimond's two parameters. ──
173 var SCRUB = L.createScrubber({
174 // The gateway's own session cookie. It is HttpOnly, so this app cannot read it, but a server
175 // log line pasted into a chat is not bound by that.
176 pairs: [{ k: 'cookie', g: 2, re: /(daimond_gw_sess=)([^;,\s"'\[\]]{4,})/g }],
177 // `body` is the archive's own snapshot FILENAME, which the entropy catch used to take.
178 idKeys: { holder: 1, self: 1, nominated: 1, body: 1 },
179 });
180 var REDACT = L.createRedactor();
181 var REDACT_CONFIG = L.createRedactor({ loose: true });
182 function scrubText(s, isId) { return SCRUB.text(s, isId); }
183 function scrubDeep(o) { return SCRUB.deep(o); }
184 function redact(o) { return REDACT.value(o); }
185 function redactConfig(o) { return REDACT_CONFIG.value(o); }
186 function fingerprint(v) { return L.fingerprint(v); }
187 function byteLen(s) { return L.byteLen(s); }
188 function str(o) { return JSON.stringify(o); }
189
190 /// A deep copy of `obj` with every string past `ELISION_CAP` bytes hard-capped
191 /// to its first `ELISION_CAP` characters plus a `…[+N bytes]` tail naming how
192 /// many bytes were dropped -- so the size stays visible and a giant file-read or
193 /// command output no longer bloats the bundle, while an ordinary readable
194 /// message (under the cap) passes through whole. Structure-preserving, so the
195 /// operator still sees the shape of a transcript; cycle-safe and depth-bounded,
196 /// like `redact()`, since the state it walks is arbitrary.
197 function elide(obj, seen, depth) {
198 seen = seen || [];
199 depth = depth || 0;
200 if (typeof obj === 'string') {
201 var bytes = byteLen(obj);
202 if (bytes <= ELISION_CAP) return obj;
203 // A string ABOUT TO BE CUT is scrubbed first, for the same reason `clip`
204 // does it: the 2 KiB boundary falls wherever it falls, and a key
205 // straddling it would reach the egress seam as a prefix too short for
206 // any rule to know. Only here, and not on every string: one that passes
207 // through whole is scrubbed at the seam anyway, and a transcript is
208 // thousands of strings the walk would otherwise search twice.
209 obj = scrubText(obj);
210 bytes = byteLen(obj);
211 if (bytes <= ELISION_CAP) return obj;
212 // Tool payloads are overwhelmingly ASCII, so a character slice at the cap
213 // is at or under the byte cap; the tail reports the exact bytes dropped.
214 var head = obj.slice(0, ELISION_CAP);
215 return head + '…[+' + (bytes - byteLen(head)) + ' bytes]';
216 }
217 if (obj == null || typeof obj !== 'object') return obj;
218 if (depth > 40 || seen.indexOf(obj) !== -1) return '[elided:cycle-or-deep]';
219 seen = seen.concat([obj]);
220 if (Array.isArray(obj)) {
221 return obj.map(function (v) { return elide(v, seen, depth + 1); });
222 }
223 var out = {};
224 Object.keys(obj).forEach(function (k) { out[k] = elide(obj[k], seen, depth + 1); });
225 return out;
226 }
227
228 /// The JSON byte length of one message, for the windowing budget. Never throws --
229 /// a message that will not serialise counts as zero, so it can never stall the walk.
230 function msgBytes(m) {
231 try { return byteLen(JSON.stringify(m) || ''); } catch (e) { return 0; }
232 }
233
234 /// Window transcripts down to a bounded, RECENT slice, so a snapshot of an account
235 /// with hundreds of turns drains in about a minute instead of starving the live
236 /// telemetry behind it. Two bounds, both keeping the NEWEST turns: each chat keeps
237 /// only its last `MAX_MSGS_PER_CHAT` messages (a transcript is append-only, so the
238 /// tail is the most recent turns), and across chats -- freshest `updatedAt` first --
239 /// messages are kept, newest of each chat first, until the running total reaches
240 /// `TRANSCRIPT_BUDGET_BYTES`, after which a chat keeps none. Each windowed chat
241 /// carries `droppedOlderTurns`, the count of messages cut, so the operator reads it
242 /// as a window rather than a short chat. Only the `messages` array is touched; every
243 /// other chat field is preserved. Returns a NEW array and does not mutate the input;
244 /// a non-array (e.g. `null`) is returned unchanged. Budget is measured on the RAW
245 /// message, before `elide` shrinks any giant payload, so the wire never exceeds it.
246 function windowTranscripts(chats) {
247 if (!Array.isArray(chats)) return chats;
248 // Freshest chats first, so the byte budget is spent on the most recent
249 // conversations; a stable tiebreak keeps equal/absent stamps in original order.
250 var order = chats.map(function (c, i) { return { c: c, i: i }; });
251 order.sort(function (a, b) {
252 var au = ms(a.c && a.c.updatedAt), bu = ms(b.c && b.c.updatedAt);
253 return (au !== bu) ? (bu - au) : (a.i - b.i);
254 });
255 var budget = TRANSCRIPT_BUDGET_BYTES;
256 var byIndex = {};
257 order.forEach(function (entry) {
258 var c = entry.c || {};
259 var msgs = Array.isArray(c.messages) ? c.messages : [];
260 var total = msgs.length;
261 // Per-chat tail cap first: at most the last N turns of THIS chat.
262 var tail = total > MAX_MSGS_PER_CHAT ? msgs.slice(total - MAX_MSGS_PER_CHAT) : msgs.slice();
263 // Then the cross-chat byte budget, still keeping the newest and dropping the
264 // oldest: walk the tail newest-first and stop when the next (older) turn will
265 // not fit, so a budget already spent by fresher chats leaves this one empty.
266 var out = [];
267 for (var j = tail.length - 1; j >= 0; j--) {
268 var b = msgBytes(tail[j]);
269 if (budget - b < 0) break;
270 budget -= b;
271 out.unshift(tail[j]);
272 }
273 var rec = {};
274 Object.keys(c).forEach(function (k) { if (k !== 'messages') rec[k] = c[k]; });
275 rec.messages = out;
276 var dropped = total - out.length;
277 if (dropped > 0) rec.droppedOlderTurns = dropped;
278 byIndex[entry.i] = rec;
279 });
280 // Restore the input's original order.
281 return chats.map(function (c, i) { return byIndex[i]; });
282 }
283 // ── Assembling a bundle ──────────────────────────────────────
284
285 /// The always-safe sources this module reads on its own, off public globals:
286 /// the cost ledger, the error/console trail, and the diagnostics ring. The
287 /// decrypted transcripts, roster, presence, election, config and token stats
288 /// come from the registered provider (daimond.js), which alone can see them.
289 function publicSources() {
290 var ledger = [];
291 try { ledger = JSON.parse(read(LEDGER_KEY) || '[]'); } catch (e) { ledger = []; }
292 var trail = [];
293 try { trail = (window.DaimondTrail && DaimondTrail.rows && DaimondTrail.rows()) || []; } catch (e) {}
294 var diag = [];
295 try { diag = (window.DaimondDiag && DaimondDiag.rows && DaimondDiag.rows()) || []; } catch (e) {}
296 // The per-Diamond / per-model signal index -- turns, spend and misses. Small
297 // and structured, so it travels whole and drives the live breakdowns.
298 var signals = null;
299 try { signals = JSON.parse(read(SIGNALS_KEY) || 'null'); } catch (e) { signals = null; }
300 return { ledger: ledger, trail: trail, diag: diag, signals: signals };
301 }
302
303 /// Assemble a full snapshot from a `sources` object and the provider's state.
304 /// Exposed for tests as `_assemble`. Redacts the whole result before returning,
305 /// so no caller can ever hold an un-redacted bundle.
306 function assemble(sources, state) {
307 sources = sources || {};
308 state = state || {};
309 // The raw cost ledger is NOT shipped whole any more: telemetry's per-model and
310 // per-Diamond aggregates already summarise it every tick, so a full ~400-entry
311 // copy in the snapshot was duplicated bulk that delayed the drain. Keep only the
312 // most recent tail for a spot-check, and record how many older entries were cut.
313 var fullLedger = sources.ledger || [];
314 var ledgerTail = fullLedger.length > SNAPSHOT_LEDGER_TAIL
315 ? fullLedger.slice(fullLedger.length - SNAPSHOT_LEDGER_TAIL)
316 : fullLedger;
317 var raw = {
318 v: 1,
319 kind: 'snapshot',
320 ts: Date.now(),
321 iso: new Date().toISOString(),
322 // From the provider (daimond.js) -- the decrypted, private-scope state.
323 // Only `transcripts` carries the giant verbatim tool outputs and the deep
324 // turn history, so it alone is WINDOWED (recent turns only, see
325 // windowTranscripts) and then elided; the rest is small, structured and
326 // travels COMPLETE.
327 config: redactConfig(state.config || null),
328 transcripts: elide(windowTranscripts(state.transcripts || null)),
329 roster: state.roster || null,
330 presence: state.presence || null,
331 election: state.election || null,
332 tokenStats: state.tokenStats || null,
333 // From this module's own public reads. The signal index is structured
334 // and complete; trail and diag are free-form logs, so their rows are
335 // elided against a stray giant string while their shape is kept. The
336 // ledger is a recent tail only -- telemetry carries its aggregates.
337 signals: sources.signals || null,
338 ledger: ledgerTail,
339 ledgerDropped: fullLedger.length - ledgerTail.length,
340 trail: elide(sources.trail || []),
341 diag: elide(sources.diag || []),
342 };
343 // Redact after eliding, so a secret-named field is a fingerprint regardless
344 // of what elision left of it. `config` was already run through
345 // `redactConfig` above, with the looser camelCase-aware match -- so put it
346 // back unchanged afterwards, or this general pass would redact an already-
347 // redacted `apiKey` a second time and turn its fingerprint into a
348 // fingerprint of a fingerprint.
349 var out = redact(raw);
350 out.config = raw.config;
351 return out;
352 }
353
354 /// Gather the full decrypted state: the provider's output plus this module's
355 /// public reads, assembled and redacted. Async because the provider may load
356 /// transcripts from IndexedDB.
357 function gatherSnapshot() {
358 return Promise.resolve(provider ? provider() : null).then(function (state) {
359 return assemble(publicSources(), state || {});
360 }, function () {
361 // A provider that throws must not stop the safe sources going out.
362 return assemble(publicSources(), {});
363 });
364 }
365
366 /// Fold the whole cost ledger into one row per model -- the discriminator the
367 /// developer reads every tick. `ledger` is the raw array this module reads off
368 /// `daimond-ledger`, entries shaped `{t,m,p,c,ca,u,r,e}`: `p` prompt tokens
369 /// (cumulative per turn), `c` completion, `ca` cached, `u` USD, `r` set when
370 /// the provider reported the cost. `cachedPct` is cache hit-rate on the prompt,
371 /// `maxPromptTurn` the largest single-turn prompt, `reportedPct` how much of the
372 /// spend the provider priced rather than this client guessing.
373 function aggregateLedger(ledger) {
374 var by = {}; // model id → accumulator
375 for (var i = 0; i < ledger.length; i++) {
376 var e = ledger[i];
377 if (!e) continue;
378 var m = e.m || '';
379 if (!by[m]) by[m] = { model: m, turns: 0, prompt: 0, completion: 0,
380 cached: 0, usd: 0, maxPromptTurn: 0, reported: 0 };
381 var a = by[m];
382 a.turns += 1;
383 a.prompt += e.p || 0;
384 a.completion += e.c || 0;
385 a.cached += e.ca || 0;
386 a.usd += e.u || 0;
387 if ((e.p || 0) > a.maxPromptTurn) a.maxPromptTurn = e.p || 0;
388 if (e.r) a.reported += 1;
389 }
390 return Object.keys(by).map(function (m) {
391 var a = by[m];
392 return {
393 model: a.model,
394 turns: a.turns,
395 prompt: a.prompt,
396 completion: a.completion,
397 cached: a.cached,
398 cachedPct: a.prompt ? 100 * a.cached / a.prompt : 0,
399 usd: a.usd,
400 maxPromptTurn: a.maxPromptTurn,
401 reportedPct: a.turns ? 100 * a.reported / a.turns : 0,
402 };
403 });
404 }
405
406 /// The per-Diamond and per-model breakdowns from the signal index -- turns,
407 /// spend and misses each. `ix.diamonds` answers "which Diamond spent what" over
408 /// all history; `ix.models` answers "which model cost what". Both are small
409 /// maps, so they go every tick. Returns empty arrays when there is no index.
410 function signalBreakdown(signals) {
411 var out = { diamonds: [], models: [] };
412 if (!signals || typeof signals !== 'object') return out;
413 var d = signals.diamonds || {};
414 Object.keys(d).forEach(function (id) {
415 var r = d[id] || {};
416 out.diamonds.push({ diamondId: id, turns: r.turns || 0, usd: r.usd || 0, missed: r.missed || 0 });
417 });
418 var m = signals.models || {};
419 Object.keys(m).forEach(function (model) {
420 var r = m[model] || {};
421 out.models.push({ model: model, turns: r.turns || 0, usd: r.usd || 0, missed: r.missed || 0 });
422 });
423 return out;
424 }
425
426 /// The diamond×model cross this module has accumulated while sharing was on --
427 /// `[{diamondId, model, turns, usd}]`, dearest first -- so the operator reads
428 /// which Diamond spent what on which model. Empty until turns are recorded.
429 function crossBreakdown() {
430 var out = [];
431 Object.keys(crossIx).forEach(function (id) {
432 var byModel = crossIx[id] || {};
433 Object.keys(byModel).forEach(function (model) {
434 var r = byModel[model] || {};
435 out.push({ diamondId: id, model: model, turns: r.turns || 0, usd: r.usd || 0 });
436 });
437 });
438 out.sort(function (a, b) { return b.usd - a.usd; });
439 return out;
440 }
441
442 /// The live numbers from daimond.js's stats seam, or null when none is
443 /// registered or it throws. Sync and cheap by contract -- no transcripts.
444 function liveStats() {
445 if (!statsFn) return null;
446 try {
447 var v = statsFn();
448 return (v && typeof v === 'object') ? v : null;
449 } catch (e) { return null; }
450 }
451
452 /// A lightweight telemetry object, sent EVERY tick: the ledger/trail/diag rows
453 /// that are new since the last tick, plus a `stats` block -- per-model ledger
454 /// aggregation and the live context/worker numbers -- that goes every time so
455 /// the developer sees the figures that matter even on a quiet tick. No
456 /// transcripts. Redacted like everything else. Returns null only when there is
457 /// genuinely nothing to say (no new rows and no stats seam).
458 function gatherTelemetry() {
459 var s = publicSources();
460 var ledDelta = s.ledger.slice(lastLedgerLen);
461 var trailNew = s.trail.slice(lastTrailLen);
462 var diagNew = s.diag.slice(lastDiagLen);
463 var sig = signalBreakdown(s.signals);
464 var stats = {
465 models: aggregateLedger(s.ledger), // per-model, from the cost ledger
466 diamonds: sig.diamonds, // per-Diamond, from the signal index
467 signalModels: sig.models, // per-model, from the signal index
468 cross: crossBreakdown(), // diamond×model, accumulated while on
469 live: liveStats(), // context/worker, from the stats seam
470 };
471 if (!ledDelta.length && !trailNew.length && !diagNew.length && !stats) return null;
472 lastLedgerLen = s.ledger.length;
473 lastTrailLen = s.trail.length;
474 lastDiagLen = s.diag.length;
475 return redact({
476 v: 1,
477 kind: 'telemetry',
478 ts: Date.now(),
479 iso: new Date().toISOString(),
480 ledger: ledDelta,
481 trail: trailNew,
482 diag: diagNew,
483 stats: stats,
484 });
485 }
486
487 // ── Chunking a bundle into debug-trace rows ──────────────────
488
489 /// UTF-8-safe base64 of a string (the JSON survives the handler's control-char
490 /// scrub and byte-boundary clip intact, which raw JSON would not guarantee).
491 function b64(str) {
492 try {
493 var bytes = new TextEncoder().encode(str);
494 var bin = '';
495 for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
496 return btoa(bin);
497 } catch (e) {
498 try { return btoa(unescape(encodeURIComponent(str))); } catch (e2) { return ''; }
499 }
500 }
501
502 /// Split an assembled bundle into an array of POSTS (each an array of rows the
503 /// `/api/debug-trace` handler accepts). A snapshot's rows are tagged
504 /// `ds <kind> <id> i/N` so the operator reassembles by concatenating `data` in
505 /// order and base64-decoding. Exposed for tests as `_chunk`.
506 function chunk(bundle) {
507 var json = '';
508 // THE EGRESS SEAM, half one. Nothing reaches the wire as a `ds` row except
509 // through here, so this is where the content rules meet a whole bundle --
510 // after which it is base64, and no later pass could read it.
511 try { json = JSON.stringify(scrubDeep(bundle)); }
512 catch (e) { json = '{"error":"stringify"}'; }
513 var payload = b64(json);
514 var id = (bundle && bundle.kind === 'telemetry' ? 't' : 's')
515 + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
516 var slices = [];
517 for (var i = 0; i < payload.length; i += MAX_DATA_BYTES) {
518 slices.push(payload.slice(i, i + MAX_DATA_BYTES));
519 }
520 if (!slices.length) slices.push('');
521 var n = slices.length;
522 var kind = (bundle && bundle.kind) || 'snapshot';
523 var rows = slices.map(function (data, idx) {
524 return {
525 ts: Date.now(),
526 tag: 'ds ' + kind + ' ' + id + ' ' + (idx + 1) + '/' + n,
527 data: data,
528 };
529 });
530 // Group rows into posts under both the row cap and the body cap.
531 var posts = [];
532 var cur = [], curBytes = 0;
533 rows.forEach(function (r) {
534 var rowBytes = r.tag.length + r.data.length + 48; // JSON overhead per row
535 if (cur.length >= MAX_ROWS_POST || (curBytes + rowBytes) > MAX_BODY_BYTES) {
536 if (cur.length) posts.push(cur);
537 cur = []; curBytes = 0;
538 }
539 cur.push(r); curBytes += rowBytes;
540 });
541 if (cur.length) posts.push(cur);
542 return posts;
543 }
544
545 /// THE THREE CAPABILITY FACTS a stuck device cannot otherwise be seen to be
546 /// missing: whether the tool surface exists at all, whether a workspace folder
547 /// is actually mounted, and whether this device may commit a chunk set. The
548 /// third is the one that matters most -- a device whose chunk index has not
549 /// merged refuses every commit, silently, and that state was invisible until
550 /// it cost a turn. `null` means the answer is not knowable yet (the core has
551 /// not loaded), which is a different thing from `false`.
552 function capabilities() {
553 var cap = { tools: false, folder: false, mayCommit: null };
554 try { cap.tools = !!window.DaimondTools; } catch (e) {}
555 try { cap.folder = !!(window.DaimondFiles && DaimondFiles.folder && DaimondFiles.folder()); } catch (e) {}
556 try {
557 if (window.DaimondCore && DaimondCore.syncMayCommitChunks) {
558 cap.mayCommit = !!DaimondCore.syncMayCommitChunks();
559 }
560 } catch (e) { /* the core is not up; `null` stands */ }
561 return cap;
562 }
563
564 /// A FOLD HAPPENS IN RUST and the JS side is told only when the engine emits
565 /// `compacted`; a fold the engine performs silently shows up here as nothing
566 /// but a context that got smaller. So a round whose `ctx` has dropped by more
567 /// than `FOLD_DROP` against the previous round of the same turn is reported as
568 /// a fold and MARKED `inferred:1`, which is the honest label for a fact that
569 /// was deduced rather than observed. A real fold reported within
570 /// `FOLD_REAL_MS` suppresses the guess, so the two never double up.
571 function inferFold(p) {
572 if (!p || typeof p !== 'object') return;
573 var id = String(p.turn || p.chat || '');
574 var ctx = Number(p.ctx) || 0;
575 if (!id || ctx <= 0) return;
576 var was = lastCtx[id] || 0;
577 lastCtx[id] = ctx;
578 if (was <= 0 || ctx >= was * (1 - FOLD_DROP)) return;
579 var real = lastRealFold[id] || 0;
580 if (real && (Date.now() - real) < FOLD_REAL_MS) return;
581 W.event('fold', { turn: id, before: was, after: ctx, trigger: 'est', inferred: 1 });
582 }
583
584 /// Record that the engine reported a REAL fold for this turn, so the inference
585 /// above stands down. Called beside the `fold` event in daimond.js.
586 function noteRealFold(id) {
587 try {
588 if (!id) return;
589 lastRealFold[String(id)] = Date.now();
590 lastCtx[String(id)] = 0; // the next round re-seeds the baseline
591 } catch (e) { W.fault(e); }
592 }
593
594 // ── The beat ───────────────────────────────────────────────
595
596 /// Where this device is, on a clock rather than on an event: build (in the
597 /// envelope), context against the window and the fold point, worker state,
598 /// credits when the gateway has said, and how deep the outbox is. Every 30 s
599 /// while a turn runs, every 5 min when nothing does -- one timer, with the
600 /// due time decided here, so a turn starting mid-interval is picked up within
601 /// one tick rather than after five minutes.
602 function beatTick() {
603 if (!enabled || !W.ok()) return;
604 var busy = false;
605 try { busy = !!(window.DaimondCore && DaimondCore.busy && DaimondCore.busy()); } catch (e) {}
606 var now = Date.now();
607 var due = busy ? BEAT_TURN_MS : BEAT_IDLE_MS;
608 if (lastBeatAt && (now - lastBeatAt) < (due - 500)) return;
609 lastBeatAt = now;
610 // Nothing held for dedupe should outlive a beat: a line logged once and
611 // never repeated would otherwise wait out its whole minute.
612 W.flushConsole(now, true);
613 var live = liveStats() || {};
614 var wk = live.workerState || null;
615 var credits = null;
616 try {
617 var gs = (window.DaimondGateway && DaimondGateway.state) ? DaimondGateway.state() : null;
618 if (gs && typeof gs.credits === 'number') credits = gs.credits;
619 } catch (e) { /* the gateway has not answered */ }
620 event('beat', {
621 ctx: live.contextActual || 0,
622 win: live.contextWindow || 0,
623 fold: live.foldAt || 0,
624 model: clip(live.activeModel || '', 48),
625 wk: wk ? (wk.active | 0) : 0,
626 wq: wk ? (wk.queued | 0) : 0,
627 busy: busy ? 1 : 0,
628 cr: (credits == null) ? undefined : credits,
629 ob: W.depth(),
630 // FEED HEALTH, which nothing else reports: how often the gateway has
631 // refused a post for rate (429), how often one failed for any other
632 // reason, and how many console lines the cap dropped since the last
633 // beat. A steady state that shows any of these is a bug in the pacing,
634 // which is exactly what these numbers are here to make visible.
635 throttled: W.health().throttled,
636 postFail: W.health().postFail,
637 cdrop: W.takeConsoleDropped(),
638 });
639 screenTick();
640 }
641
642 function deviceId() {
643 try { return (window.DaimondIdentity && DaimondIdentity.deviceId && DaimondIdentity.deviceId()) || ''; }
644 catch (e) { return ''; }
645 }
646
647 // ── The writer core, handed Daimond's seams ──
648 function buildRaw() {
649 try {
650 if (window.DaimondUpdater && DaimondUpdater.booted && DaimondUpdater.booted()) return DaimondUpdater.booted();
651 } catch (e) { /* the updater has not polled */ }
652 return read(BUILD_KEY) || '';
653 }
654 var W = L.createWriter({
655 host: { storage: localStorage, setTimeout: setTimeout, clearTimeout: clearTimeout, console: console,
656 now: function () { return Date.now(); }, document: typeof document !== 'undefined' ? document : null,
657 // Read at call time, so the test that swaps the tab's Error for one with no stack is seen.
658 get Error() { return Error; } },
659 keys: { outbox: EVENT_KEY, seq: SEQ_KEY, postAt: POST_AT_KEY },
660 device: deviceId,
661 build: buildRaw,
662 enabled: function () { return enabled; },
663 send: function (rows) {
664 return fetch(ENDPOINT, {
665 method: 'POST',
666 credentials: 'same-origin',
667 headers: { 'content-type': 'application/json', 'x-daimond-api': String(CLIENT_API) },
668 body: W.postBody(rows),
669 });
670 },
671 redact: REDACT,
672 scrub: SCRUB,
673 extra: function (kind) {
674 if (kind !== 'boot' && kind !== 'beat') return null;
675 var cap = capabilities();
676 return { tools: cap.tools, folder: cap.folder, mayCommit: cap.mayCommit };
677 },
678 lane: {
679 pending: function () { return telQueue.length > 0 || snapQueue.length > 0; },
680 next: function () { return telQueue.length ? telQueue.shift() : snapQueue.shift(); },
681 },
682 ownPath: ENDPOINT,
683 skipFrames: ['debugshare.js'],
684 after: function (kind, payload) { if (kind === 'round') inferFold(payload); },
685 onFault: function () { stopTimers(); },
686 caps: { gapMs: DRAIN_MS },
687 });
688 function clip(s, n) { return W.clip(s, n); }
689 function event(kind, payload) { return W.event(kind, payload); }
690 function fault(e) { W.fault(e); }
691 function noteFetchFail(p, s, l, e) { return W.noteFetchFail(p, s, l, e); }
692 function persistNow() { W.persistNow(); }
693 function noteError(m, w) { W.noteError(m, w); }
694 function noteConsole(lvl, args) { W.noteConsole(lvl, args); }
695 function flushConsole(t, force) { W.flushConsole(t, force); }
696 function looksSecret(m) { return L.looksSecret(m); }
697 function gapLeft() { return W.gapLeft(); }
698 function fit(o) { return W.fit(o); }
699 function eventBatch() { return W.eventBatch(); }
700
701 /// Enqueue a bundle's posts onto the telemetry lane when `priority` is true, else
702 /// the snapshot lane, and kick the drainer. A no-op when off.
703 function enqueue(posts, priority) {
704 if (!enabled || !posts || !posts.length) return;
705 var q = priority ? telQueue : snapQueue;
706 for (var i = 0; i < posts.length; i++) q.push(posts[i]);
707 W.drain();
708 }
709
710 /// Assemble and enqueue a full snapshot. A no-op when off, or once the feed
711 /// has faulted -- a feed that threw collects nothing more this session.
712 function snapshotNow() {
713 if (!enabled || !W.ok()) return Promise.resolve(false);
714 return gatherSnapshot().then(function (bundle) {
715 enqueue(chunk(bundle));
716 return true;
717 });
718 }
719
720 function telemetryTick() {
721 if (!enabled || !W.ok()) return;
722 var tel = gatherTelemetry();
723 if (tel) enqueue(chunk(tel), true); // priority lane -- ahead of any snapshot backlog
724 }
725
726 // ── The header indicator ─────────────────────────────────────
727 //
728 // A red, gently pulsing eye in the header's action group, shown the whole time
729 // the feature is on and gone the instant it is off. Its title/hover carries the
730 // plain warning. Theme-aware: the alert red is deliberately close in both
731 // themes (an alarm should not go quiet in the dark), but the glyph and ring
732 // adjust so it reads on either ground.
733
734 var INDICATOR_TITLE = 'Debug data sharing is ON — all your Daimond data is being '
735 + 'shared with the developer for debugging. Turn off in Settings.';
736
737 function ensureStyle() {
738 try {
739 if (document.getElementById('ds-style')) return;
740 var s = document.createElement('style');
741 s.id = 'ds-style';
742 s.textContent =
743 '.ds-indicator{display:inline-flex;align-items:center;justify-content:center;'
744 + 'width:34px;height:34px;margin:0 2px;border-radius:8px;cursor:pointer;'
745 + 'border:1px solid #ef4444;background:#fee2e2;color:#b91c1c;'
746 + 'animation:ds-pulse 1.6s ease-in-out infinite;}'
747 + '.ds-indicator:hover{background:#fecaca;}'
748 + '.ds-indicator .ic{width:20px;height:20px;stroke:currentColor;stroke-width:2;'
749 + 'fill:none;stroke-linecap:round;stroke-linejoin:round;}'
750 + '@keyframes ds-pulse{0%,100%{box-shadow:0 0 0 0 rgba(239,68,68,.55);}'
751 + '50%{box-shadow:0 0 0 5px rgba(239,68,68,0);}}'
752 + '@media (prefers-color-scheme:dark){'
753 + '.ds-indicator{background:#450a0a;color:#fca5a5;border-color:#f87171;}'
754 + '.ds-indicator:hover{background:#5b1010;}}'
755 + ':root[data-theme="dark"] .ds-indicator{background:#450a0a;color:#fca5a5;border-color:#f87171;}'
756 + ':root[data-theme="light"] .ds-indicator{background:#fee2e2;color:#b91c1c;border-color:#ef4444;}';
757 (document.head || document.body || document.documentElement).appendChild(s);
758 } catch (e) {}
759 }
760
761 function mountIndicator() {
762 try {
763 if (indicator || typeof document === 'undefined' || !document.querySelector) return;
764 ensureStyle();
765 var host = document.querySelector('.top-actions') || document.querySelector('.topbar');
766 if (!host) return;
767 var b = document.createElement('button');
768 b.type = 'button';
769 b.className = 'ds-indicator';
770 b.id = 'ds-indicator';
771 b.title = INDICATOR_TITLE;
772 b.setAttribute('aria-label', INDICATOR_TITLE);
773 // An eye with a dot -- "your data is being watched" -- in an alert frame.
774 b.innerHTML = '<svg class="ic" viewBox="0 0 24 24" aria-hidden="true">'
775 + '<path d="M1.5 12S5 5.5 12 5.5 22.5 12 22.5 12 19 18.5 12 18.5 1.5 12 1.5 12z"/>'
776 + '<circle cx="12" cy="12" r="3"/></svg>';
777 b.addEventListener('click', function () {
778 // Best-effort nudge toward Settings; harmless if nobody listens.
779 try { window.dispatchEvent(new CustomEvent('daimond:opensettings', { detail: { from: 'debugshare' } })); }
780 catch (e) {}
781 });
782 // First child, so it sits at the leading edge of the action group and is
783 // the first thing the eye meets.
784 if (host.firstChild) host.insertBefore(b, host.firstChild);
785 else host.appendChild(b);
786 indicator = b;
787 } catch (e) {}
788 }
789
790 function unmountIndicator() {
791 try { if (indicator && indicator.remove) indicator.remove(); } catch (e) {}
792 indicator = null;
793 }
794
795 // ── The switch ───────────────────────────────────────────────
796
797 function startTimers() {
798 stopTimers();
799 if (!W.ok()) return; // a faulted feed collects nothing more
800 try { telTimer = setInterval(telemetryTick, TELEMETRY_MS); } catch (e) {}
801 try { snapTimer = setInterval(function () { snapshotNow(); }, RESNAP_MS); } catch (e) {}
802 try { beatTimer = setInterval(function () { try { beatTick(); } catch (e2) { fault(e2); } }, BEAT_TICK_MS); } catch (e) {}
803 }
804 function stopTimers() {
805 try { if (telTimer) clearInterval(telTimer); } catch (e) {}
806 try { if (snapTimer) clearInterval(snapTimer); } catch (e) {}
807 try { if (beatTimer) clearInterval(beatTimer); } catch (e) {}
808 telTimer = null; snapTimer = null; beatTimer = null;
809 }
810
811 function isOn() { return enabled; }
812
813 /// Apply the on/off EFFECT without recording a decision or nudging sync. On:
814 /// show the indicator, start the timers, and post a full snapshot. Off: hide the
815 /// indicator, stop the timers, drop any queued posts, and reset the telemetry
816 /// cursors -- nothing more leaves the device. Idempotent and safe to call before
817 /// the DOM exists (the indicator is simply not mounted then, and mounts on the
818 /// next `on`). This is the shared body: `setEnabled` wraps it with a fresh stamp
819 /// for a LOCAL decision, and `adoptSync` calls it after writing the remote stamp
820 /// verbatim, so an adopted value never restamps and cannot ping-pong.
821 function applyState(v) {
822 enabled = !!v;
823 write(ENABLED_KEY, enabled ? '1' : '0');
824 try {
825 window.dispatchEvent(new CustomEvent('daimond:debugshare', { detail: { on: enabled } }));
826 } catch (e) {}
827 if (enabled) {
828 mountIndicator();
829 // Seed the telemetry cursors at the current tail, so the first telemetry
830 // tick sends only what happens AFTER toggle-on (the snapshot already
831 // carried the backlog).
832 var s = publicSources();
833 lastLedgerLen = s.ledger.length;
834 lastTrailLen = s.trail.length;
835 lastDiagLen = s.diag.length;
836 startTimers();
837 snapshotNow();
838 // NO IMMEDIATE BEAT. The snapshot that has just been queued carries the
839 // same state and more, and `boot` -- emitted by daimond.js at start and
840 // unlock -- is what says which build this device is on. The beat's job is
841 // the CLOCK: it says a quiet device is still there. So the first one is
842 // the timer's, not this.
843 lastBeatAt = 0;
844 lastScreenAt = 0;
845 lastScreenKey = null;
846 } else {
847 stopTimers();
848 telQueue = [];
849 snapQueue = [];
850 // The outbox, and what the console lane held, go with it: see `W.reset`.
851 W.reset();
852 unmountIndicator();
853 }
854 }
855
856 /// Turn the feature on or off from a LOCAL action (the Settings toggle). Stamps
857 /// the decision with the clock -- which is how this choice wins over an older one
858 /// on every linked device (see `adoptSync`) -- applies the effect, and nudges the
859 /// sync engine so the flag reaches the fleet without waiting for the next push.
860 function setEnabled(v) {
861 var on = !!v;
862 // Stamp BEFORE applying, so a snapshot the effect kicks off already carries the
863 // new decision when `collectSync` reads `syncSnapshot()`. Past the stamp it
864 // replaces, so turning it off on a device whose clock is behind the one that
865 // turned it on still wins (CLK-3).
866 write(STAMP_KEY, String(DaimondStamp.next(ms(read(STAMP_KEY)))));
867 applyState(on);
868 nudgeSync();
869 }
870
871 /// The flag as it rides the sync parcel: `{ on, at }`, or `null` when this device
872 /// has never touched the toggle. Verbatim -- no restamp -- so a value this device
873 /// already agrees with serialises to the same bytes and the push-skip still holds.
874 /// `null` (never touched) reads to the other side as "nothing to say", so a fresh
875 /// device cannot clear a fleet another device has just armed.
876 function syncSnapshot() {
877 var at = ms(read(STAMP_KEY));
878 if (!at) return null;
879 return { on: enabled, at: at };
880 }
881
882 /// Adopt a flag that arrived from another device: the fresher `at` wins, and at an
883 /// equal `at` OFF wins, on every device alike, so a tie never leaves collection
884 /// running anywhere. Written VERBATIM, so a record this device already holds moves
885 /// nothing and the next parcel is byte-identical. When the fresher value differs from what this
886 /// device shows, the effect is applied through `applyState` -- the indicator mounts
887 /// or unmounts and collection starts or stops -- so the eye and the collection match
888 /// the fleet. Only the boolean and its stamp are touched; no key or secret is read
889 /// or written here.
890 function adoptSync(rec) {
891 if (!rec || typeof rec !== 'object') return;
892 var at = ms(rec.at);
893 if (!at) return;
894 var on = !!rec.on;
895 var mineAt = ms(read(STAMP_KEY));
896 if (DaimondStamp.beats(at, on, mineAt, enabled, offFirst)) {
897 write(STAMP_KEY, String(at)); // verbatim: no restamp, so no ping-pong
898 if (on !== enabled) applyState(on);
899 }
900 }
901
902 /// The flag's rank for a tie: off above on.
903 function offFirst(on) { return on ? 0 : 1; }
904
905 /// Register the provider daimond.js supplies: a function returning (or
906 /// resolving to) the decrypted private-scope state. Called once at boot.
907 function registerProvider(fn) {
908 if (typeof fn === 'function') provider = fn;
909 }
910
911 /// Register the live-stats seam daimond.js supplies: a cheap, synchronous
912 /// function returning the current context/token/worker numbers (never
913 /// transcripts). Telemetry calls it every tick. Called once at boot, beside
914 /// `registerProvider`.
915 function registerStats(fn) {
916 if (typeof fn === 'function') statsFn = fn;
917 }
918
919 /// Register the screen seam daimond.js supplies: a cheap, synchronous function
920 /// returning what the person is actually LOOKING AT -- which view, the seat
921 /// line, the last tile's role and text head, an open dialog's kind, the
922 /// composer's length and the lock state. Called once at boot, beside the two
923 /// seams above; the fields this module cannot know on its own (window size,
924 /// tab visibility, the updater's state) are added in `gatherScreen`.
925 function registerScreen(fn) {
926 if (typeof fn === 'function') screenFn = fn;
927 }
928
929 /// The updater's state, in the one word a reader needs: `'none'` (nothing
930 /// pending), `'countdown'` (an automatic reload is due), `'manual'` or
931 /// `'manual:<why>'` (the watch has given up finding a safe moment, or a
932 /// controlling worker will not advance -- only a manual reload will move this
933 /// device; `<why>` is the LAST reason it was refused, when one was ever
934 /// recorded, see `heldWhy` in updater.js), `'held:<why>'` (a build is pending
935 /// but a named guard is holding the automatic path back right now -- see
936 /// `updater.js`'s `whyUnsafe`), or `'ready'` (safe and quiet, waiting only on
937 /// the next tick). `window.DaimondUpdater` absent -- an older build, or a
938 /// test -- reads as `'none'`.
939 ///
940 /// `manual` used to say nothing more, even once `heldWhy` had a reason on
941 /// file -- `gaveUp`/`stuck` short-circuited the `held` check below and the
942 /// lens saw a device stuck on manual with no way to tell why. Same reason
943 /// word either way now, since it is the SAME question -- what is stopping
944 /// this build -- read at a different moment.
945 function updaterState() {
946 try {
947 var U = window.DaimondUpdater;
948 if (!U || !(U.pending && U.pending())) return 'none';
949 if (U.countdown && U.countdown() > 0) return 'countdown';
950 if ((U.stuck && U.stuck()) || (U.gaveUp && U.gaveUp())) {
951 var manualWhy = (U.held && U.held()) || '';
952 return manualWhy ? 'manual:' + manualWhy : 'manual';
953 }
954 if (U.held) { var why = U.held(); if (why) return 'held:' + why; }
955 return 'ready';
956 } catch (e) { return 'none'; }
957 }
958
959 /// The screen picture, assembled from the registered seam plus the three
960 /// facts only this module can see: the viewport size, whether the tab is
961 /// visible, and the updater's own state. Every string is bounded here, so
962 /// `screenTick`'s change-detection compares an already-capped object and
963 /// `fit()` in `emit` is a safety net rather than the only thing keeping this
964 /// under the 360-byte cap. Never throws: a screen seam that is absent, or
965 /// that itself throws, yields the fields this module can still answer.
966 function gatherScreen() {
967 var s = null;
968 try { s = screenFn ? screenFn() : null; } catch (e) { s = null; }
969 s = (s && typeof s === 'object') ? s : {};
970 var role = clip(s.role || '', MAX_TILE_ROLE_CHARS);
971 var text = clip(s.text || '', MAX_TILE_TEXT_CHARS);
972 // One string, "role: text", which is what a reader wants on one line; an
973 // absent tile (a fresh chat, or no seam registered) is the empty string,
974 // not "': '".
975 var tile = text ? (role ? role + ': ' + text : text) : '';
976 var w = 0, h = 0, vis = '';
977 try { w = (window.innerWidth | 0) || 0; } catch (e) { /* no window */ }
978 try { h = (window.innerHeight | 0) || 0; } catch (e) { /* no window */ }
979 try { vis = (typeof document !== 'undefined' && document.visibilityState) || ''; }
980 catch (e) { /* no document */ }
981 return {
982 view: clip(s.view || '', MAX_VIEW_CHARS) || 'chat',
983 seat: clip(s.seat || '', MAX_SEAT_CHARS),
984 tile: tile,
985 dlg: clip(s.dlg || 'none', MAX_DLG_CHARS) || 'none',
986 comp: Number(s.comp) || 0,
987 locked: s.locked ? 1 : 0,
988 upd: updaterState(),
989 w: w,
990 h: h,
991 vis: vis,
992 };
993 }
994
995 /// Gather the screen and ship it as an `ev screen` row -- but only when its
996 /// picture has actually CHANGED since the last one shipped, or `SCREEN_FLOOR_MS`
997 /// has passed since it last did, whichever comes first. Called from `beatTick`,
998 /// so it is checked on the same clock as the beat (30 s busy, 5 min idle) without
999 /// a timer of its own; most ticks say nothing at all, which is the point -- a
1000 /// device sitting on one screen must not repeat itself every thirty seconds.
1001 function screenTick() {
1002 if (!enabled || !W.ok()) return;
1003 var s = gatherScreen();
1004 var key = '';
1005 try { key = str(s); } catch (e) { key = ''; }
1006 var now = Date.now();
1007 if (key === lastScreenKey && lastScreenAt && (now - lastScreenAt) < SCREEN_FLOOR_MS) return;
1008 lastScreenKey = key;
1009 lastScreenAt = now;
1010 event('screen', s);
1011 }
1012
1013 // If the switch was left on from a previous session, restore the indicator and
1014 // resume collection once the DOM is ready.
1015 function bootRestore() {
1016 if (!enabled) return;
1017 mountIndicator();
1018 var s = publicSources();
1019 lastLedgerLen = s.ledger.length;
1020 lastTrailLen = s.trail.length;
1021 lastDiagLen = s.diag.length;
1022 startTimers();
1023 // A boot snapshot lands the current state the moment the app is up.
1024 snapshotNow();
1025 // And whatever the LAST session could not deliver goes now, ahead of it: the
1026 // outbox is already loaded, and this is the moment it starts moving again.
1027 lastBeatAt = 0;
1028 W.drain();
1029 }
1030 try {
1031 if (typeof document !== 'undefined' && document.addEventListener) {
1032 if (document.readyState === 'loading') {
1033 document.addEventListener('DOMContentLoaded', bootRestore);
1034 } else {
1035 // Defer a tick so daimond.js has a chance to register its provider.
1036 setTimeout(bootRestore, 0);
1037 }
1038 }
1039 } catch (e) {}
1040
1041 // A switch flipped in one tab reaches the others of the SAME device, so turning
1042 // it off in one place stops collection everywhere on this machine. The sibling
1043 // tab that flipped it already stamped `STAMP_KEY` and nudged sync, so this one
1044 // only mirrors the EFFECT -- `applyState`, never `setEnabled` -- and does not
1045 // restamp. (Cross-DEVICE propagation is `syncSnapshot`/`adoptSync` on the parcel.)
1046 try {
1047 window.addEventListener('storage', function (e) {
1048 if (e && e.key === ENABLED_KEY) {
1049 var now = read(ENABLED_KEY) === '1';
1050 if (now !== enabled) applyState(now);
1051 }
1052 });
1053 } catch (e) {}
1054
1055 // ── Capture: errors, the console, and the page going away. All three are the core's. ──
1056 W.captureErrors(window);
1057 W.captureConsole(typeof console !== 'undefined' ? console : null);
1058 W.captureLifecycle(window, typeof document !== 'undefined' ? document : undefined);
1059
1060 window.DEBUG_SHARE = {
1061 isOn: isOn,
1062 setEnabled: setEnabled,
1063 // Cross-device flag sync, ridden on the existing parcel by daimond.js
1064 // (`collectSync` reads `syncSnapshot`, `applySync` calls `adoptSync`).
1065 syncSnapshot: syncSnapshot,
1066 adoptSync: adoptSync,
1067 registerProvider: registerProvider,
1068 registerStats: registerStats,
1069 registerScreen: registerScreen,
1070 noteCross: noteCross,
1071 snapshotNow: snapshotNow,
1072 // THE EVENT SEAM. One call, `DEBUG_SHARE.event(kind, payload)`, from every
1073 // call site in the app; a no-op when sharing is off and never a throw into
1074 // the caller. `noteFetchFail` is the gateway wrapper's shorthand for the
1075 // `fetch.fail` kind, and `noteRealFold` tells the fold inference to stand
1076 // down because the engine reported a fold itself.
1077 event: event,
1078 noteFetchFail: noteFetchFail,
1079 noteRealFold: noteRealFold,
1080 /// Is the feed still collecting? False once it has faulted, even while the
1081 /// share switch is on -- see `fault`.
1082 feedOk: function () { return !!W.ok(); },
1083 /// How many events are waiting to go out.
1084 outboxDepth: function () { return W.depth(); },
1085 // Exposed for the verifier: drive one telemetry tick without the 30 s timer.
1086 _telemetryTick: telemetryTick,
1087 // Exposed for the verifier (www/js/debugshare.test.mjs):
1088 _fingerprint: fingerprint,
1089 _redact: redact,
1090 // The content scrubber -- the shared block's two entry points.
1091 _scrubText: scrubText,
1092 _scrubDeep: scrubDeep,
1093 _elide: elide,
1094 _windowTranscripts: windowTranscripts,
1095 _byteLen: byteLen,
1096 _assemble: assemble,
1097 _chunk: chunk,
1098 _publicSources: publicSources,
1099 _gatherSnapshot: gatherSnapshot,
1100 _gatherTelemetry: gatherTelemetry,
1101 _aggregateLedger: aggregateLedger,
1102 _signalBreakdown: signalBreakdown,
1103 _crossBreakdown: crossBreakdown,
1104 _queueLen: function () { return telQueue.length + snapQueue.length; },
1105 // Exposed for the verifier: the event lane, its persistence, and the two
1106 // timed collectors, so the outage/reload/fault rules can be driven without
1107 // waiting out an interval.
1108 _outbox: function () { return W.outbox(); },
1109 _persistNow: persistNow,
1110 _beatTick: beatTick,
1111 _capabilities: capabilities,
1112 _gatherScreen: gatherScreen,
1113 _screenTick: screenTick,
1114 _updaterState: updaterState,
1115 // Simulate the five-minute floor having elapsed, without a real wait: the
1116 // change-detection compares against `lastScreenAt`, and this is the one
1117 // thing a test cannot otherwise move.
1118 _expireScreen: function () { lastScreenAt = 0; },
1119 _noteError: noteError,
1120 // The console lane, driven without waiting out a dedupe window.
1121 _noteConsole: function (lvl, args) { noteConsole(lvl, args || []); },
1122 _flushConsole: function (force) { flushConsole(Date.now(), force !== false); },
1123 _looksSecret: looksSecret,
1124 /// What the last beat would report: the 429s, the other post failures, and
1125 /// the console lines the cap dropped.
1126 _health: function () { return W.health(); },
1127 // Exposed for the verifier: whether a post may go NOW, per the clock this
1128 // instance booted with -- the property a reload used to lose.
1129 _gapLeft: gapLeft,
1130 _fit: fit,
1131 _eventBatch: eventBatch,
1132 _backoffMs: function (n) { return W.backoffMs(n); },
1133 _drain: function () { return W.drain(); },
1134 // Exposed for the verifier so it can assert lane ordering directly.
1135 _telQueueLen: function () { return telQueue.length; },
1136 _snapQueueLen: function () { return snapQueue.length; },
1137 };
1138})();