@cloop/runner 0.3.18 → 0.3.22

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.
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ sanitizeLabel,
3
4
  stripControl
4
5
  } from "./chunk-VK6GV757.js";
5
6
  import {
@@ -107,16 +108,16 @@ var SECRETS = [
107
108
  [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g, "[redacted]"]
108
109
  ];
109
110
  var OPAQUE = /[A-Za-z0-9_+=-]{32,}/g;
110
- function redactSecrets(text2) {
111
- let out = text2;
111
+ function redactSecrets(text3) {
112
+ let out = text3;
112
113
  for (const [pattern, replacement] of SECRETS) out = out.replace(pattern, replacement);
113
114
  return out.replace(
114
115
  OPAQUE,
115
116
  (run2) => /^[0-9a-f-]+$/i.test(run2) || !/\d/.test(run2) || !/[A-Za-z]/.test(run2) ? run2 : "[redacted]"
116
117
  );
117
118
  }
118
- function logText(text2) {
119
- const flat = redactSecrets(stripControl(text2).replace(/\s+/g, " ").trim());
119
+ function logText(text3) {
120
+ const flat = redactSecrets(stripControl(text3).replace(/\s+/g, " ").trim());
120
121
  return flat.length > RUN_LOG_LINE_MAX ? `${flat.slice(0, RUN_LOG_LINE_MAX - 1)}\u2026` : flat;
121
122
  }
122
123
  function logLineFor(item) {
@@ -129,16 +130,18 @@ function logLineFor(item) {
129
130
  }
130
131
  case "ask":
131
132
  return `? ${item.summary}`;
133
+ case "session":
134
+ return item.notReady ? `! Not connected at start: ${item.notReady.join(", ")}` : null;
132
135
  case "result":
133
136
  return item.ok ? `= Result: ${item.text ?? "done"}` : `= Error: ${item.text ?? "no text"}`;
134
137
  default:
135
138
  return null;
136
139
  }
137
140
  }
138
- function appendRunLog(dir, workId, text2, { now = Date.now(), maxBytes = RUN_LOG_MAX_BYTES } = {}) {
141
+ function appendRunLog(dir, workId, text3, { now = Date.now(), maxBytes = RUN_LOG_MAX_BYTES } = {}) {
139
142
  const path = runLogPath(dir, workId);
140
143
  if (!path) return;
141
- const line = `${stamp(now)} ${logText(text2)}
144
+ const line = `${stamp(now)} ${logText(text3)}
142
145
  `;
143
146
  mkdirSync(dir, { recursive: true, mode: 448 });
144
147
  const size = sizeOf(path);
@@ -332,6 +335,174 @@ function whichAll(bin) {
332
335
  }
333
336
  }
334
337
 
338
+ // src/t3.ts
339
+ var T3_SCOPE = "orchestration:read orchestration:operate diagnostics:read";
340
+ var REQUIRED_SCOPES = ["orchestration:read", "orchestration:operate"];
341
+ var MIN_PROTOCOL = 2;
342
+ async function readEnvironment(t3Url, fetchFn = fetch) {
343
+ const res = await fetchFn(`${t3Url}/.well-known/t3/environment`);
344
+ if (!res.ok) throw new Error(`T3 environment ${res.status} at ${t3Url}`);
345
+ return await res.json();
346
+ }
347
+ async function exchangePairing(t3Url, credential, label, fetchFn = fetch) {
348
+ const form = new URLSearchParams({
349
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
350
+ subject_token: credential,
351
+ subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap",
352
+ requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
353
+ scope: T3_SCOPE,
354
+ client_label: label,
355
+ client_device_type: "bot"
356
+ });
357
+ const res = await fetchFn(`${t3Url}/oauth/token`, { method: "POST", body: form });
358
+ if (!res.ok) throw new T3HttpError("token exchange", res.status);
359
+ const token = await res.json();
360
+ if (!REQUIRED_SCOPES.every((s) => hasScope(token.scope, s)) || scopes(token.scope).some((s) => !hasScope(T3_SCOPE, s)))
361
+ throw new Error(`T3 granted scope "${token.scope}", wanted "${T3_SCOPE}"`);
362
+ return token;
363
+ }
364
+ var scopes = (s) => s.split(/\s+/).filter(Boolean);
365
+ var hasScope = (scope, name) => scopes(scope ?? "").includes(name);
366
+ var T3HttpError = class extends Error {
367
+ constructor(path, status) {
368
+ super(`T3 ${path} ${status}`);
369
+ this.status = status;
370
+ this.name = "T3HttpError";
371
+ }
372
+ status;
373
+ };
374
+ var T3Client = class {
375
+ constructor(t3Url, token, fetchFn = fetch) {
376
+ this.t3Url = t3Url;
377
+ this.token = token;
378
+ this.fetchFn = fetchFn;
379
+ }
380
+ t3Url;
381
+ token;
382
+ fetchFn;
383
+ async http(path, headers = {}) {
384
+ const res = await this.fetchFn(`${this.t3Url}${path}`, {
385
+ headers: { authorization: `Bearer ${this.token}`, ...headers }
386
+ });
387
+ if (!res.ok) throw new T3HttpError(path, res.status);
388
+ return await res.json();
389
+ }
390
+ async openSocket() {
391
+ const ticket = await this.fetchFn(`${this.t3Url}/api/auth/websocket-ticket`, {
392
+ method: "POST",
393
+ headers: { authorization: `Bearer ${this.token}` }
394
+ });
395
+ if (!ticket.ok) throw new T3HttpError("/api/auth/websocket-ticket", ticket.status);
396
+ const { ticket: wsTicket } = await ticket.json();
397
+ const { WebSocket } = await import("ws");
398
+ const url = `${this.t3Url.replace(/^http/, "ws")}/ws?wsTicket=${encodeURIComponent(wsTicket)}&orchestrationProtocol=2&clientSurface=web&clientAppVersion=cloop-box`;
399
+ return new WebSocket(url);
400
+ }
401
+ /** One request over a fresh /ws socket. The daemon makes a few calls a minute, so a socket per call is simpler than keeping one alive. */
402
+ async rpc(tag, payload) {
403
+ const ws = await this.openSocket();
404
+ return new Promise((resolve, reject) => {
405
+ let settled = false;
406
+ const finish = (fn) => {
407
+ if (settled) return;
408
+ settled = true;
409
+ clearTimeout(timer);
410
+ fn();
411
+ try {
412
+ ws.close();
413
+ } catch {
414
+ }
415
+ };
416
+ const timer = setTimeout(
417
+ () => finish(() => reject(new Error(`T3 rpc ${tag} timed out`))),
418
+ 15e3
419
+ );
420
+ ws.on(
421
+ "error",
422
+ (err) => finish(() => reject(err instanceof Error ? err : new Error(String(err))))
423
+ );
424
+ ws.on(
425
+ "close",
426
+ () => finish(() => reject(new Error(`T3 rpc ${tag}: socket closed before a reply`)))
427
+ );
428
+ ws.on("open", () => {
429
+ ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
430
+ });
431
+ ws.on("message", (data) => {
432
+ for (const msg of parseFrames(data)) {
433
+ if (msg._tag !== "Exit" || String(msg.requestId) !== "1") continue;
434
+ const exit = msg.exit;
435
+ if (exit._tag === "Success") finish(() => resolve(exit.value));
436
+ else {
437
+ finish(
438
+ () => reject(
439
+ new Error(`T3 rpc ${tag} failed: ${JSON.stringify(exit.cause).slice(0, 300)}`)
440
+ )
441
+ );
442
+ }
443
+ }
444
+ });
445
+ });
446
+ }
447
+ /**
448
+ * A streaming request, such as `orchestration.subscribeThread`, on its own
449
+ * socket. Every item is acked, as Effect RPC requires. `done` resolves with
450
+ * the reason the stream ended and never rejects; `close` interrupts it.
451
+ */
452
+ async stream(tag, payload, onItem) {
453
+ const ws = await this.openSocket();
454
+ let resolveDone = () => {
455
+ };
456
+ const done = new Promise((r) => {
457
+ resolveDone = r;
458
+ });
459
+ const end = (reason) => {
460
+ resolveDone(reason);
461
+ try {
462
+ ws.close();
463
+ } catch {
464
+ }
465
+ };
466
+ ws.on("error", (err) => end(`error: ${err instanceof Error ? err.message : String(err)}`));
467
+ ws.on("close", () => end("closed"));
468
+ ws.on("open", () => {
469
+ ws.send(JSON.stringify({ _tag: "Request", id: 1, tag, payload, headers: [] }));
470
+ });
471
+ ws.on("message", (data) => {
472
+ for (const msg of parseFrames(data)) {
473
+ if (String(msg.requestId) !== "1") continue;
474
+ if (msg._tag === "Chunk") {
475
+ ws.send(JSON.stringify({ _tag: "Ack", requestId: msg.requestId }));
476
+ for (const value of msg.values) onItem(value);
477
+ } else if (msg._tag === "Exit") {
478
+ const exit = msg.exit;
479
+ end(
480
+ exit._tag === "Success" ? "exit" : `failed: ${JSON.stringify(exit.cause).slice(0, 300)}`
481
+ );
482
+ }
483
+ }
484
+ });
485
+ return {
486
+ done,
487
+ close: () => {
488
+ try {
489
+ ws.send(JSON.stringify({ _tag: "Interrupt", requestId: "1" }));
490
+ } catch {
491
+ }
492
+ end("closed by client");
493
+ }
494
+ };
495
+ }
496
+ };
497
+ function parseFrames(data) {
498
+ try {
499
+ const raw = JSON.parse(String(data));
500
+ return Array.isArray(raw) ? raw : [raw];
501
+ } catch {
502
+ return [];
503
+ }
504
+ }
505
+
335
506
  // src/drivers/t3.ts
336
507
  import { execFile, execFileSync as execFileSync3 } from "child_process";
337
508
  import { randomUUID } from "crypto";
@@ -358,8 +529,8 @@ var https = (v) => {
358
529
  };
359
530
  var PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
360
531
  var prNumber = (url) => Number(url.slice(url.lastIndexOf("/") + 1));
361
- function prUrlIn(text2) {
362
- const urls = text2?.match(PR_URL) ?? [];
532
+ function prUrlIn(text3) {
533
+ const urls = text3?.match(PR_URL) ?? [];
363
534
  return urls.reduce(
364
535
  (newest, url) => newest && prNumber(newest) >= prNumber(url) ? newest : url,
365
536
  null
@@ -484,8 +655,8 @@ function isProgressSentence(value) {
484
655
  }
485
656
  var PROGRESS_MS = 3e4;
486
657
  var RUN_TEXT_MAX = 4e3;
487
- function nextProgress(clock, text2, now, ms = PROGRESS_MS, force = false) {
488
- const summary = (parseRunResult(text2)?.summary ?? text2.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, RUN_TEXT_MAX);
658
+ function nextProgress(clock, text3, now, ms = PROGRESS_MS, force = false) {
659
+ const summary = (parseRunResult(text3)?.summary ?? text3.split("```cloop-result")[0] ?? "").replace(/\s+/g, " ").trim().slice(0, RUN_TEXT_MAX);
489
660
  if (!isProgressSentence(summary)) return null;
490
661
  if (!force && now - clock.lastProgressAt < ms) return null;
491
662
  clock.lastProgressAt = now;
@@ -526,6 +697,309 @@ function handoverPrompt(prompt, from) {
526
697
  ${from} started this work and stopped at its usage limit. Its changes, if any, are in this checkout. Read \`git status\` and \`git log\` first, and carry on from there.`;
527
698
  }
528
699
 
700
+ // src/drivers/usage.ts
701
+ import { createHash } from "crypto";
702
+ var TOKEN_SCOPE = "agent session logs on this machine";
703
+ var MISSING_DIAGNOSTICS = {
704
+ status: "missing_permission",
705
+ hint: "This runner's T3 pairing cannot read token usage. Run `cloop connect` on that machine; if it asks for a pairing link, make one with the diagnostics permission."
706
+ };
707
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
708
+ var count = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
709
+ var text2 = (v) => typeof v === "string" && v.length > 0;
710
+ var DAY = /^\d{4}-\d{2}-\d{2}$/;
711
+ function safeMessage(v) {
712
+ if (!text2(v)) return void 0;
713
+ return sanitizeLabel(v.replace(/(?:[A-Za-z]:)?[\\/][^\s'"]+/g, "<path>"), 200);
714
+ }
715
+ var KINDS = /* @__PURE__ */ new Set(["session", "weekly", "monthly", "other"]);
716
+ function quotaWindow(id, kind, label, usedPercent, resetsAt, windowMinutes) {
717
+ if (!count(usedPercent) || usedPercent > 100) return null;
718
+ return {
719
+ id: sanitizeLabel(id, 60),
720
+ kind,
721
+ label: sanitizeLabel(label, 80),
722
+ usedPercent,
723
+ resetsAt,
724
+ windowMinutes: count(windowMinutes) ? windowMinutes : null
725
+ };
726
+ }
727
+ function isoTime(v) {
728
+ const ms = typeof v === "number" && Number.isFinite(v) && v > 0 ? v < 1e12 ? v * 1e3 : v : text2(v) ? Date.parse(v) : Number.NaN;
729
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
730
+ }
731
+ var KIND_LABEL = { session: "Session", weekly: "Weekly", monthly: "Monthly", other: "Limit" };
732
+ var KIND_MINUTES = { session: 300, weekly: 10080, monthly: null, other: null };
733
+ function kindOf(minutes) {
734
+ if (minutes === 300) return "session";
735
+ if (minutes === 10080) return "weekly";
736
+ if (count(minutes) && minutes >= 40320 && minutes <= 44640) return "monthly";
737
+ return "other";
738
+ }
739
+ var capped = (v) => typeof v === "number" ? Math.min(v, 100) : v;
740
+ function quotaFromT3(raw) {
741
+ if (raw === void 0 || raw === null) return { status: "not_reported" };
742
+ if (!isObject(raw)) return { status: "malformed" };
743
+ const checkedAt = text2(raw.checkedAt) ? raw.checkedAt : null;
744
+ if (raw.unavailable !== void 0) {
745
+ const u = raw.unavailable;
746
+ if (!isObject(u) || u.reason !== "unsupported" && u.reason !== "probeFailed")
747
+ return { status: "malformed" };
748
+ const message = safeMessage(u.message);
749
+ return {
750
+ status: u.reason === "unsupported" ? "unsupported" : "probe_failed",
751
+ checkedAt,
752
+ ...message ? { message } : {}
753
+ };
754
+ }
755
+ if (!checkedAt || !Array.isArray(raw.windows) || raw.windows.length === 0)
756
+ return { status: "malformed" };
757
+ const windows = [];
758
+ for (const w of raw.windows) {
759
+ const window = isObject(w) && text2(w.id) && KINDS.has(w.kind) && text2(w.label) ? quotaWindow(
760
+ w.id,
761
+ w.kind,
762
+ w.label,
763
+ w.usedPercent,
764
+ text2(w.resetsAt) ? w.resetsAt : null,
765
+ w.windowDurationMins
766
+ ) : null;
767
+ if (!window) return { status: "malformed" };
768
+ windows.push(window);
769
+ }
770
+ const credits = raw.resetCredits;
771
+ return {
772
+ status: "ok",
773
+ checkedAt,
774
+ windows,
775
+ ...isObject(credits) && count(credits.availableCount) ? {
776
+ resetCredits: {
777
+ available: credits.availableCount,
778
+ nextExpiresAt: text2(credits.nextExpiresAt) ? credits.nextExpiresAt : null
779
+ }
780
+ } : {}
781
+ };
782
+ }
783
+ function quotaFromCodex(answer, checkedAt) {
784
+ if (!isObject(answer)) return { status: "malformed" };
785
+ if (answer.error !== void 0) {
786
+ const message = safeMessage(isObject(answer.error) ? answer.error.message : void 0);
787
+ return {
788
+ status: /chatgpt authentication required/i.test(message ?? "") ? "unsupported" : "probe_failed",
789
+ checkedAt,
790
+ ...message ? { message } : {}
791
+ };
792
+ }
793
+ const r = answer.result;
794
+ if (!isObject(r)) return { status: "malformed" };
795
+ const byId = isObject(r.rateLimitsByLimitId) ? Object.values(r.rateLimitsByLimitId) : [];
796
+ const limits = byId.length > 0 ? byId : [r.rateLimits];
797
+ const windows = [];
798
+ for (const limit of limits) {
799
+ if (!isObject(limit)) return { status: "malformed" };
800
+ const id = text2(limit.limitId) ? limit.limitId : "codex";
801
+ const name = text2(limit.limitName) ? limit.limitName : id;
802
+ for (const slot of ["primary", "secondary"]) {
803
+ const w = limit[slot];
804
+ if (w === null || w === void 0) continue;
805
+ if (!isObject(w)) return { status: "malformed" };
806
+ const kind = kindOf(w.windowDurationMins);
807
+ const label = kind === "other" && count(w.windowDurationMins) ? `${Math.round(w.windowDurationMins / 60)}-hour` : KIND_LABEL[kind];
808
+ const window = quotaWindow(
809
+ `${id}_${slot}`,
810
+ kind,
811
+ id === "codex" ? label : `${label} \xB7 ${name}`,
812
+ capped(w.usedPercent),
813
+ isoTime(w.resetsAt),
814
+ w.windowDurationMins
815
+ );
816
+ if (!window) return { status: "malformed" };
817
+ windows.push(window);
818
+ }
819
+ }
820
+ if (windows.length === 0)
821
+ return { status: "unsupported", checkedAt, message: "Codex reported no limit windows." };
822
+ const credits = isObject(r.rateLimitResetCredits) ? r.rateLimitResetCredits : null;
823
+ const expiries = (Array.isArray(credits?.credits) ? credits.credits : []).filter((c) => isObject(c) && (c.status === void 0 || c.status === "available")).map((c) => isoTime(c.expiresAt)).filter((t) => t !== null).sort();
824
+ return {
825
+ status: "ok",
826
+ checkedAt,
827
+ windows,
828
+ ...credits && count(credits.availableCount) ? { resetCredits: { available: credits.availableCount, nextExpiresAt: expiries[0] ?? null } } : {}
829
+ };
830
+ }
831
+ function quotaFromClaude(response, checkedAt) {
832
+ if (!isObject(response)) return { status: "malformed" };
833
+ if (response.subtype === "error") {
834
+ const message = safeMessage(response.error);
835
+ return { status: "probe_failed", checkedAt, ...message ? { message } : {} };
836
+ }
837
+ const r = response.response;
838
+ if (!isObject(r)) return { status: "malformed" };
839
+ if (r.rate_limits_available === false)
840
+ return { status: "unsupported", checkedAt, message: "This Claude login has no limit windows." };
841
+ const limits = r.rate_limits;
842
+ if (r.rate_limits_available !== true || !isObject(limits)) return { status: "malformed" };
843
+ const windows = [];
844
+ for (const [id, kind] of [
845
+ ["five_hour", "session"],
846
+ ["seven_day", "weekly"]
847
+ ]) {
848
+ const w = limits[id];
849
+ if (w === null || w === void 0) continue;
850
+ const window = isObject(w) ? quotaWindow(
851
+ id,
852
+ kind,
853
+ KIND_LABEL[kind],
854
+ capped(w.utilization),
855
+ isoTime(w.resets_at),
856
+ KIND_MINUTES[kind]
857
+ ) : null;
858
+ if (!window) return { status: "malformed" };
859
+ windows.push(window);
860
+ }
861
+ for (const l of Array.isArray(limits.limits) ? limits.limits : []) {
862
+ const scope = isObject(l) && isObject(l.scope) ? l.scope : null;
863
+ const model = isObject(scope?.model) ? scope.model.display_name : void 0;
864
+ if (!isObject(l) || !text2(model)) continue;
865
+ const kind = l.group === "session" || l.group === "weekly" ? l.group : "other";
866
+ const window = quotaWindow(
867
+ `${kind}_${model.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`,
868
+ kind,
869
+ `${KIND_LABEL[kind]} \xB7 ${model}`,
870
+ capped(l.percent),
871
+ isoTime(l.resets_at),
872
+ KIND_MINUTES[kind]
873
+ );
874
+ if (!window) return { status: "malformed" };
875
+ windows.push(window);
876
+ }
877
+ if (windows.length === 0)
878
+ return { status: "unsupported", checkedAt, message: "Claude Code reported no limit windows." };
879
+ return { status: "ok", checkedAt, windows };
880
+ }
881
+ var TOKEN_DAYS = 7;
882
+ var TOKEN_TTL_MS = 10 * 6e4;
883
+ var GOOD = /* @__PURE__ */ new Set(["ok", "partial"]);
884
+ var FAILED = /* @__PURE__ */ new Set(["unavailable", "probe_failed"]);
885
+ var BackgroundReading = class {
886
+ constructor(opts) {
887
+ this.opts = opts;
888
+ }
889
+ opts;
890
+ value = null;
891
+ at = 0;
892
+ isReading = false;
893
+ get() {
894
+ const now = this.opts.now ?? Date.now;
895
+ if (!this.isReading && (!this.value || now() - this.at > this.opts.ttlMs)) {
896
+ this.isReading = true;
897
+ void this.opts.read().then(
898
+ (next) => {
899
+ if (!(FAILED.has(next.status) && this.value && GOOD.has(this.value.status)))
900
+ this.value = next;
901
+ },
902
+ () => {
903
+ }
904
+ ).finally(() => {
905
+ this.at = now();
906
+ this.isReading = false;
907
+ });
908
+ }
909
+ return this.value ?? { status: "pending" };
910
+ }
911
+ };
912
+ function utcWindow(now, days) {
913
+ const day = (ms) => new Date(ms).toISOString().slice(0, 10);
914
+ return { sinceDay: day(now - (days - 1) * 864e5), untilDay: day(now) };
915
+ }
916
+ function addTokens(days, day, provider, t) {
917
+ const key = `${day} ${provider}`;
918
+ const row = days.get(key) ?? {
919
+ day,
920
+ provider: sanitizeLabel(provider, 40),
921
+ total_tokens: 0,
922
+ uncached_input_tokens: 0,
923
+ cached_input_tokens: 0,
924
+ cache_creation_tokens: 0,
925
+ output_tokens: 0,
926
+ reasoning_tokens: 0,
927
+ records: 0
928
+ };
929
+ row.uncached_input_tokens += t.uncached;
930
+ row.cached_input_tokens += t.cached;
931
+ row.cache_creation_tokens += t.creation;
932
+ row.output_tokens += t.output;
933
+ row.reasoning_tokens += t.reasoning;
934
+ row.total_tokens += t.uncached + t.cached + t.creation + t.output;
935
+ row.records += t.records;
936
+ days.set(key, row);
937
+ }
938
+ function sortedDays(days) {
939
+ return [...days.values()].sort(
940
+ (a, b) => b.day.localeCompare(a.day) || a.provider.localeCompare(b.provider)
941
+ );
942
+ }
943
+ function sourceKey(parts) {
944
+ return createHash("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 12);
945
+ }
946
+ var SOURCE_STATUS = /* @__PURE__ */ new Set(["ok", "missing", "partial", "failed"]);
947
+ function tokenUsageFromSummary(raw, window) {
948
+ if (!isObject(raw) || !Array.isArray(raw.buckets) || !Array.isArray(raw.sources))
949
+ return { status: "malformed" };
950
+ const days = /* @__PURE__ */ new Map();
951
+ let malformed = 0;
952
+ for (const b of raw.buckets) {
953
+ const t = isObject(b) ? b.totals : void 0;
954
+ if (!isObject(b) || !isObject(t) || !text2(b.day) || !DAY.test(b.day) || !text2(b.provider) || !count(b.records) || !count(t.uncachedInputTokens) || !count(t.cachedInputTokens) || !count(t.cacheCreationTokens) || !count(t.outputTokens) || !count(t.reasoningTokens)) {
955
+ malformed++;
956
+ continue;
957
+ }
958
+ addTokens(days, b.day, b.provider, {
959
+ uncached: t.uncachedInputTokens,
960
+ cached: t.cachedInputTokens,
961
+ creation: t.cacheCreationTokens,
962
+ output: t.outputTokens,
963
+ reasoning: t.reasoningTokens,
964
+ records: b.records
965
+ });
966
+ }
967
+ const sources = [];
968
+ for (const s of raw.sources) {
969
+ const f = isObject(s) ? s.fingerprint : void 0;
970
+ if (!isObject(s) || !isObject(f) || !text2(f.provider) || !SOURCE_STATUS.has(s.status)) {
971
+ malformed++;
972
+ continue;
973
+ }
974
+ const message = safeMessage(s.message);
975
+ sources.push({
976
+ source_key: sourceKey([f.hostId, f.provider, f.resolvedHomePath, f.volumeId]),
977
+ provider: sanitizeLabel(f.provider, 40),
978
+ status: s.status,
979
+ scanned_files: count(s.scannedFiles) ? s.scannedFiles : 0,
980
+ skipped_files: count(s.skippedFiles) ? s.skippedFiles : 0,
981
+ malformed_records: count(s.malformedRecords) ? s.malformedRecords : 0,
982
+ ...message ? { message } : {}
983
+ });
984
+ }
985
+ const partial = malformed > 0 || sources.some((s) => s.status === "partial" || s.status === "failed");
986
+ return {
987
+ status: partial ? "partial" : "ok",
988
+ scope: TOKEN_SCOPE,
989
+ window: { since_day: window.sinceDay, until_day: window.untilDay, time_zone: "UTC" },
990
+ read_at: text2(raw.readAt) ? raw.readAt : null,
991
+ by_day: sortedDays(days),
992
+ sources,
993
+ ...malformed ? { malformed_rows: malformed } : {}
994
+ };
995
+ }
996
+ function isPermissionError(err) {
997
+ if (err?.status === 403) return true;
998
+ return /diagnostics:read|missing required (scope|permission)|insufficient_scope/i.test(
999
+ err instanceof Error ? err.message : String(err)
1000
+ );
1001
+ }
1002
+
529
1003
  // src/drivers/t3.ts
530
1004
  function isUnsettled(t) {
531
1005
  return !t.settledAt && !t.archivedAt && !isChild(t);
@@ -602,14 +1076,14 @@ function outcomeOf(p) {
602
1076
  const run2 = latestRun(p.runs ?? []);
603
1077
  const status = run2?.status ?? "pending";
604
1078
  const settled = TERMINAL_RUN.has(status) || Boolean(p.thread.settledAt);
605
- const text2 = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
606
- const { result, dropped } = readRunResult(text2);
1079
+ const text3 = (p.messages ?? []).filter((m) => m.role === "assistant" && m.text).at(-1)?.text?.trim();
1080
+ const { result, dropped } = readRunResult(text3);
607
1081
  return {
608
1082
  status,
609
1083
  settled,
610
1084
  kind: settled ? status === "completed" || !run2 ? "settled" : "failed" : null,
611
- pr_url: resultPrUrl(text2),
612
- last_assistant_text: text2 ? text2.slice(0, RUN_TEXT_MAX) : null,
1085
+ pr_url: resultPrUrl(text3),
1086
+ last_assistant_text: text3 ? text3.slice(0, RUN_TEXT_MAX) : null,
613
1087
  ...result ? { result } : {},
614
1088
  ...dropped.outputs || dropped.checks ? { dropped } : {}
615
1089
  };
@@ -645,8 +1119,7 @@ function pickProject(projects, repository) {
645
1119
  }
646
1120
  var SHELL_HEADERS = { "x-t3-orchestration-protocol": "2" };
647
1121
  function boxCapabilities(scope) {
648
- const scopes = (scope ?? "").split(/\s+/).filter(Boolean);
649
- return scopes.includes("orchestration:operate") ? ["view", "start", "steer"] : ["view"];
1122
+ return hasScope(scope, "orchestration:operate") ? ["view", "start", "steer"] : ["view"];
650
1123
  }
651
1124
  function threadView(t) {
652
1125
  return {
@@ -772,7 +1245,8 @@ var T3Driver = class {
772
1245
  ready: p.status === "ready",
773
1246
  signedIn: p.auth?.status === "authenticated",
774
1247
  account: p.auth?.label ?? null,
775
- defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null
1248
+ defaultModel: p.models?.find((m) => m.isDefault)?.slug ?? null,
1249
+ quota: quotaFromT3(p.usageLimits)
776
1250
  })),
777
1251
  clients: sessions?.filter((s) => s.client?.deviceType !== "bot").map((s) => ({
778
1252
  label: s.client?.label ?? "unknown",
@@ -785,9 +1259,38 @@ var T3Driver = class {
785
1259
  running: unsettled.filter((t) => t.status === "running").length,
786
1260
  settled: threads.length - unsettled.length,
787
1261
  cloop: unsettled.filter((t) => (t.title ?? "").startsWith(CLOOP_THREAD_PREFIX)).length
788
- }
1262
+ },
1263
+ token_usage: this.tokenUsage()
789
1264
  };
790
1265
  }
1266
+ usage = new BackgroundReading({
1267
+ ttlMs: TOKEN_TTL_MS,
1268
+ read: () => this.readTokenUsage(),
1269
+ now: () => (this.deps.now ?? Date.now)()
1270
+ });
1271
+ /**
1272
+ * Token counts from `server.getUsageSummary`, from the cache: T3 reads the
1273
+ * agent logs on disk for it, so status never waits. It needs
1274
+ * `diagnostics:read`, which an older pairing lacks.
1275
+ */
1276
+ tokenUsage() {
1277
+ const scope = this.deps.scope?.();
1278
+ if (scope !== void 0 && !hasScope(scope, "diagnostics:read")) return MISSING_DIAGNOSTICS;
1279
+ return this.usage.get();
1280
+ }
1281
+ async readTokenUsage() {
1282
+ const window = utcWindow((this.deps.now ?? Date.now)(), TOKEN_DAYS);
1283
+ try {
1284
+ const raw = await this.t3.rpc("server.getUsageSummary", {
1285
+ ...window,
1286
+ timeZone: "UTC"
1287
+ });
1288
+ return tokenUsageFromSummary(raw, window);
1289
+ } catch (err) {
1290
+ this.log(`usage summary failed: ${err?.message}`);
1291
+ return isPermissionError(err) ? MISSING_DIAGNOSTICS : { status: "unavailable", reason: "T3 did not answer the usage read" };
1292
+ }
1293
+ }
791
1294
  async listThreads({
792
1295
  scope,
793
1296
  limit
@@ -1577,9 +2080,9 @@ var LocalDriver = class {
1577
2080
  this.deps.log?.(line);
1578
2081
  }
1579
2082
  /** One line in the run's own log, for `cloop watch`. A full disk must not stop the run. */
1580
- note(r, text2) {
2083
+ note(r, text3) {
1581
2084
  try {
1582
- appendRunLog(this.logDir, r.work_id, text2, { now: this.now() });
2085
+ appendRunLog(this.logDir, r.work_id, text3, { now: this.now() });
1583
2086
  } catch (err) {
1584
2087
  if (this.logFailed) return;
1585
2088
  this.logFailed = true;
@@ -1591,15 +2094,20 @@ var LocalDriver = class {
1591
2094
  }
1592
2095
  /** Probes the harnesses now, so the first status after the daemon starts answers at once. */
1593
2096
  warmHarnesses() {
1594
- void this.harnessCheck.refresh();
2097
+ void this.harnessCheck.refresh().then(() => this.status()).catch((err) => this.log(`usage warm failed: ${err?.message}`));
1595
2098
  }
1596
2099
  async status() {
1597
2100
  const { harnesses, checkedAt, probing } = await this.harnessCheck.read();
1598
2101
  const all = [...this.runs.values()];
1599
2102
  const unsettled = all.filter((r) => !r.end);
2103
+ const usage = this.deps.usage;
1600
2104
  return {
1601
2105
  box: { label: this.deps.label ?? hostname(), driver: this.name },
1602
- harnesses,
2106
+ harnesses: usage ? harnesses.map((h) => ({
2107
+ ...h,
2108
+ // A signed-out harness has no account to ask.
2109
+ quota: h.signedIn ? usage.quota(h.id) : { status: "not_reported" }
2110
+ })) : harnesses,
1603
2111
  harnesses_checked_at: checkedAt,
1604
2112
  ...probing ? { probing: true } : {},
1605
2113
  clients: null,
@@ -1609,7 +2117,8 @@ var LocalDriver = class {
1609
2117
  running: unsettled.filter((r) => this.lives.has(r.work_id)).length,
1610
2118
  settled: all.length - unsettled.length,
1611
2119
  cloop: unsettled.length
1612
- }
2120
+ },
2121
+ ...usage ? { token_usage: usage.tokenUsage() } : {}
1613
2122
  };
1614
2123
  }
1615
2124
  async listThreads({
@@ -1892,7 +2401,7 @@ ${a.text}` : a.text;
1892
2401
  const child = spawn(command.file, command.args, {
1893
2402
  cwd: r.repo,
1894
2403
  stdio: ["pipe", "pipe", "pipe"],
1895
- env: process.env,
2404
+ env: { ...dialect.env, ...process.env },
1896
2405
  ...command.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
1897
2406
  });
1898
2407
  const live = {
@@ -1986,12 +2495,12 @@ ${RESULT_INSTRUCTION}`));
1986
2495
  return;
1987
2496
  }
1988
2497
  if (code === 0 && live.result?.ok) {
1989
- const text2 = live.result.text?.trim() || r.last_text;
1990
- const { result, dropped } = readRunResult(text2);
2498
+ const text3 = live.result.text?.trim() || r.last_text;
2499
+ const { result, dropped } = readRunResult(text3);
1991
2500
  const lost = droppedLine(dropped, r.work_id);
1992
2501
  if (lost) this.log(lost);
1993
- const { pr, note } = await this.outcome(r, text2);
1994
- const summary = [r.switched, note, text2].filter(Boolean).join(" ").replace(/\s+/g, " ");
2502
+ const { pr, note } = await this.outcome(r, text3);
2503
+ const summary = [r.switched, note, text3].filter(Boolean).join(" ").replace(/\s+/g, " ");
1995
2504
  await this.end(r, {
1996
2505
  kind: "settled",
1997
2506
  ...result ? { result } : {},
@@ -2122,8 +2631,8 @@ ${RESULT_INSTRUCTION}`));
2122
2631
  * started produced nothing, and the branch's PR belongs to someone else's
2123
2632
  * work. A run that committed without pushing says so.
2124
2633
  */
2125
- async outcome(r, text2) {
2126
- const named = resultPrUrl(text2);
2634
+ async outcome(r, text3) {
2635
+ const named = resultPrUrl(text3);
2127
2636
  if (named) return { pr: named };
2128
2637
  if (!r.head_at_launch) return { pr: null };
2129
2638
  const head = await this.repo.head(r.repo);
@@ -2251,11 +2760,27 @@ export {
2251
2760
  quoteWindowsArg,
2252
2761
  windowsExecutable,
2253
2762
  windowsPowerShellEnv,
2763
+ HARNESS_STALE_MS,
2254
2764
  defaultT3BinSources,
2255
2765
  t3Candidates,
2256
2766
  pickT3Bin,
2257
2767
  t3BaseDirArgs,
2258
2768
  runT3,
2769
+ MIN_PROTOCOL,
2770
+ readEnvironment,
2771
+ exchangePairing,
2772
+ T3HttpError,
2773
+ T3Client,
2774
+ TOKEN_SCOPE,
2775
+ quotaFromCodex,
2776
+ quotaFromClaude,
2777
+ TOKEN_DAYS,
2778
+ TOKEN_TTL_MS,
2779
+ BackgroundReading,
2780
+ utcWindow,
2781
+ addTokens,
2782
+ sortedDays,
2783
+ sourceKey,
2259
2784
  T3Driver,
2260
2785
  takeoverSummary,
2261
2786
  runHarness,