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