@kvali/cli 0.7.1 → 0.7.2
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/kvali.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
-
import { writeFile } from "node:fs/promises";
|
|
4
|
+
import { lstat, writeFile } from "node:fs/promises";
|
|
5
5
|
import os3 from "node:os";
|
|
6
6
|
import path19 from "node:path";
|
|
7
7
|
import process2 from "node:process";
|
|
@@ -178,6 +178,8 @@ function dayKeyLocal(ms) {
|
|
|
178
178
|
|
|
179
179
|
// ../core/src/limits.ts
|
|
180
180
|
var KEEP_MS = 6 * 36e5;
|
|
181
|
+
var FUTURE_SLACK_MS = 5 * 6e4;
|
|
182
|
+
var MAX_SAMPLES = 720;
|
|
181
183
|
var PACE_MS = 60 * 6e4;
|
|
182
184
|
var MIN_SPAN_MS = 5 * 6e4;
|
|
183
185
|
var RESET_JITTER_MS = 5 * 6e4;
|
|
@@ -196,10 +198,15 @@ function runsOutAt(samples, latest, now) {
|
|
|
196
198
|
}
|
|
197
199
|
var LimitBook = class {
|
|
198
200
|
books = /* @__PURE__ */ new Map();
|
|
199
|
-
/**
|
|
200
|
-
|
|
201
|
+
/**
|
|
202
|
+
* Adds a reading taken at `at`. Older readings than the window's latest are ignored, and so is
|
|
203
|
+
* one from the future (a wrong clock or a broken file would otherwise hide every real one).
|
|
204
|
+
*/
|
|
205
|
+
add(reading, at, now) {
|
|
201
206
|
if (!Number.isFinite(reading.usedPercent) || !Number.isFinite(at)) return;
|
|
202
|
-
|
|
207
|
+
if (now !== void 0 && at > now + FUTURE_SLACK_MS) return;
|
|
208
|
+
if (typeof reading.label !== "string" || !reading.label || reading.label.length > 40) return;
|
|
209
|
+
const pct = Math.min(100, Math.max(0, reading.usedPercent));
|
|
203
210
|
let book = this.books.get(reading.label);
|
|
204
211
|
if (book) {
|
|
205
212
|
const sameWindow = book.latest.resetsAt === void 0 || reading.resetsAt === void 0 || Math.abs(book.latest.resetsAt - reading.resetsAt) <= RESET_JITTER_MS;
|
|
@@ -210,6 +217,7 @@ var LimitBook = class {
|
|
|
210
217
|
if (at >= book.latest.at - KEEP_MS && !book.samples.some((s) => s.at === at)) {
|
|
211
218
|
book.samples.push({ at, pct });
|
|
212
219
|
book.samples.sort((a, b) => a.at - b.at);
|
|
220
|
+
if (book.samples.length > MAX_SAMPLES) book.samples.splice(0, book.samples.length - MAX_SAMPLES);
|
|
213
221
|
}
|
|
214
222
|
return;
|
|
215
223
|
}
|
|
@@ -223,6 +231,7 @@ var LimitBook = class {
|
|
|
223
231
|
book.latest = { ...reading, usedPercent: pct, at };
|
|
224
232
|
const cutoff = at - KEEP_MS;
|
|
225
233
|
while (book.samples.length > 1 && book.samples[0].at < cutoff) book.samples.shift();
|
|
234
|
+
if (book.samples.length > MAX_SAMPLES) book.samples.splice(0, book.samples.length - MAX_SAMPLES);
|
|
226
235
|
}
|
|
227
236
|
get size() {
|
|
228
237
|
return this.books.size;
|
|
@@ -256,6 +265,89 @@ function claudeWindowLabel(kind) {
|
|
|
256
265
|
return { label: kind.replace(/_/g, " ") };
|
|
257
266
|
}
|
|
258
267
|
|
|
268
|
+
// ../core/src/util/text.ts
|
|
269
|
+
function firstLine(text, max = 80) {
|
|
270
|
+
const line = text.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
|
|
271
|
+
return truncate(line.replace(/\s+/g, " "), max);
|
|
272
|
+
}
|
|
273
|
+
function truncate(text, max) {
|
|
274
|
+
if (text.length <= max) return text;
|
|
275
|
+
return text.slice(0, Math.max(0, max - 1)).trimEnd() + "\u2026";
|
|
276
|
+
}
|
|
277
|
+
var INJECTED_TAGS = ["system-reminder", "local-command-stdout", "local-command-stderr", "command-message", "command-args"];
|
|
278
|
+
function removeTagged(text, tag, keep) {
|
|
279
|
+
const open = `<${tag}>`;
|
|
280
|
+
const close = `</${tag}>`;
|
|
281
|
+
let out = "";
|
|
282
|
+
let pos = 0;
|
|
283
|
+
for (; ; ) {
|
|
284
|
+
const a = text.indexOf(open, pos);
|
|
285
|
+
if (a === -1) break;
|
|
286
|
+
const b = text.indexOf(close, a + open.length);
|
|
287
|
+
if (b === -1) break;
|
|
288
|
+
out += text.slice(pos, a) + (keep ? text.slice(a + open.length, b) : "");
|
|
289
|
+
pos = b + close.length;
|
|
290
|
+
}
|
|
291
|
+
return out + text.slice(pos);
|
|
292
|
+
}
|
|
293
|
+
function stripInjectedTags(text) {
|
|
294
|
+
let out = text;
|
|
295
|
+
for (const tag of INJECTED_TAGS) out = removeTagged(out, tag, false);
|
|
296
|
+
return removeTagged(out, "command-name", true).trim();
|
|
297
|
+
}
|
|
298
|
+
function contentText(content) {
|
|
299
|
+
if (typeof content === "string") return content;
|
|
300
|
+
if (!Array.isArray(content)) return "";
|
|
301
|
+
const parts = [];
|
|
302
|
+
for (const part of content) {
|
|
303
|
+
if (typeof part === "string") parts.push(part);
|
|
304
|
+
else if (part && typeof part === "object") {
|
|
305
|
+
const p2 = part;
|
|
306
|
+
if (typeof p2.text === "string" && (p2.type === void 0 || p2.type === "text" || p2.type === "input_text" || p2.type === "output_text")) {
|
|
307
|
+
parts.push(p2.text);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return parts.join("\n");
|
|
312
|
+
}
|
|
313
|
+
function summarizeCommand(cmd, max = 80) {
|
|
314
|
+
let text;
|
|
315
|
+
if (typeof cmd === "string") text = cmd;
|
|
316
|
+
else if (Array.isArray(cmd)) {
|
|
317
|
+
const parts = cmd.filter((c) => typeof c === "string");
|
|
318
|
+
if (parts.length >= 3 && /(^|\/)(ba|z|fi)?sh$/.test(parts[0]) && /^-\w*c$/.test(parts[1])) text = parts.slice(2).join(" ");
|
|
319
|
+
else text = parts.join(" ");
|
|
320
|
+
}
|
|
321
|
+
if (!text) return void 0;
|
|
322
|
+
return truncate(text.replace(/\s+/g, " ").trim(), max);
|
|
323
|
+
}
|
|
324
|
+
function basename(p2) {
|
|
325
|
+
const parts = p2.split(/[\\/]/).filter(Boolean);
|
|
326
|
+
return parts[parts.length - 1] ?? p2;
|
|
327
|
+
}
|
|
328
|
+
function lookupTable(entries) {
|
|
329
|
+
return Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), entries));
|
|
330
|
+
}
|
|
331
|
+
var ESCAPES = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x1b[@-_]?/g;
|
|
332
|
+
var INVISIBLE = /[\x00-\x08\x0b-\x1f\x7f-\x9f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g;
|
|
333
|
+
function cleanText(text, max = 1e3) {
|
|
334
|
+
const t = text.replace(ESCAPES, "").replace(INVISIBLE, "");
|
|
335
|
+
return t.length > max ? truncate(t, max) : t;
|
|
336
|
+
}
|
|
337
|
+
function cleanFields(o, fields) {
|
|
338
|
+
let out;
|
|
339
|
+
for (const [k, max] of Object.entries(fields)) {
|
|
340
|
+
const v = o[k];
|
|
341
|
+
if (typeof v !== "string") continue;
|
|
342
|
+
const c = cleanText(v, max);
|
|
343
|
+
if (c !== v) {
|
|
344
|
+
out ??= { ...o };
|
|
345
|
+
out[k] = c;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return out ?? o;
|
|
349
|
+
}
|
|
350
|
+
|
|
259
351
|
// ../core/src/week.ts
|
|
260
352
|
var WEEK_DAYS = 7;
|
|
261
353
|
function localDay(ms) {
|
|
@@ -338,7 +430,7 @@ function weekShareText(w, opts = {}) {
|
|
|
338
430
|
|
|
339
431
|
Tracked with Kvali, an open-source progress bar for AI agents: ${KVALI_URL}`;
|
|
340
432
|
}
|
|
341
|
-
var esc = (t) => t.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
433
|
+
var esc = (t) => cleanText(t, 300).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
342
434
|
function weekSvg(w, opts = {}) {
|
|
343
435
|
const W = 1200;
|
|
344
436
|
const H = 630;
|
|
@@ -437,21 +529,58 @@ function isClaude46OrLater(key) {
|
|
|
437
529
|
const minor = Number(r[3] ?? 0);
|
|
438
530
|
return major > 4 || major === 4 && minor >= 6;
|
|
439
531
|
}
|
|
440
|
-
function
|
|
441
|
-
const
|
|
442
|
-
|
|
532
|
+
function globMatch(glob, text) {
|
|
533
|
+
const g = glob.toLowerCase();
|
|
534
|
+
const s = text.toLowerCase();
|
|
535
|
+
let gi = 0;
|
|
536
|
+
let si = 0;
|
|
537
|
+
let star = -1;
|
|
538
|
+
let mark = 0;
|
|
539
|
+
while (si < s.length) {
|
|
540
|
+
if (gi < g.length && (g[gi] === "?" || g[gi] === s[si])) {
|
|
541
|
+
gi += 1;
|
|
542
|
+
si += 1;
|
|
543
|
+
} else if (gi < g.length && g[gi] === "*") {
|
|
544
|
+
star = gi;
|
|
545
|
+
gi += 1;
|
|
546
|
+
mark = si;
|
|
547
|
+
} else if (star !== -1) {
|
|
548
|
+
gi = star + 1;
|
|
549
|
+
mark += 1;
|
|
550
|
+
si = mark;
|
|
551
|
+
} else return false;
|
|
552
|
+
}
|
|
553
|
+
while (gi < g.length && g[gi] === "*") gi += 1;
|
|
554
|
+
return gi === g.length;
|
|
555
|
+
}
|
|
556
|
+
var isPrice = (x) => typeof x === "number" && Number.isFinite(x) && x >= 0;
|
|
557
|
+
function customPrice(v, nested = false) {
|
|
558
|
+
if (!v || typeof v !== "object") return void 0;
|
|
559
|
+
const o = v;
|
|
560
|
+
if (!isPrice(o.input) || !isPrice(o.output)) return void 0;
|
|
561
|
+
const p2 = { input: o.input, output: o.output, cacheRead: isPrice(o.cacheRead) ? o.cacheRead : 0 };
|
|
562
|
+
if (isPrice(o.cacheWrite5m)) p2.cacheWrite5m = o.cacheWrite5m;
|
|
563
|
+
if (isPrice(o.cacheWrite1h)) p2.cacheWrite1h = o.cacheWrite1h;
|
|
564
|
+
if (isPrice(o.fastMultiplier)) p2.fastMultiplier = o.fastMultiplier;
|
|
565
|
+
if (!nested && o.longPrompt && typeof o.longPrompt === "object") {
|
|
566
|
+
const t = o.longPrompt.threshold;
|
|
567
|
+
const tier = customPrice(o.longPrompt, true);
|
|
568
|
+
if (tier && isPrice(t)) p2.longPrompt = { ...tier, threshold: t };
|
|
569
|
+
}
|
|
570
|
+
return p2;
|
|
443
571
|
}
|
|
444
572
|
var Pricing = class {
|
|
445
573
|
custom;
|
|
446
574
|
constructor(customPrices = {}) {
|
|
447
|
-
this.custom =
|
|
448
|
-
|
|
449
|
-
price
|
|
450
|
-
|
|
575
|
+
this.custom = [];
|
|
576
|
+
for (const [glob, v] of Object.entries(customPrices ?? {})) {
|
|
577
|
+
const price = customPrice(v);
|
|
578
|
+
if (price) this.custom.push({ glob, price });
|
|
579
|
+
}
|
|
451
580
|
}
|
|
452
581
|
find(model) {
|
|
453
582
|
if (!model) return void 0;
|
|
454
|
-
for (const c of this.custom) if (c.
|
|
583
|
+
for (const c of this.custom) if (globMatch(c.glob, model)) return { price: c.price, key: model };
|
|
455
584
|
const key = anthropicModelKey(model);
|
|
456
585
|
if (key && ANTHROPIC_PRICES[key]) return { price: ANTHROPIC_PRICES[key], key };
|
|
457
586
|
return void 0;
|
|
@@ -475,8 +604,11 @@ var Pricing = class {
|
|
|
475
604
|
// ../core/src/util/jsonl.ts
|
|
476
605
|
import { promises as fsp } from "node:fs";
|
|
477
606
|
var CHUNK_BYTES = 1 << 20;
|
|
607
|
+
var MAX_LINE_BYTES = 8 << 20;
|
|
478
608
|
var JsonlTail = class {
|
|
479
609
|
offset = 0;
|
|
610
|
+
/** Inside a line longer than MAX_LINE_BYTES: skipping to its end. */
|
|
611
|
+
skipping = false;
|
|
480
612
|
size = -1;
|
|
481
613
|
mtimeMs = -1;
|
|
482
614
|
ino;
|
|
@@ -505,6 +637,7 @@ var JsonlTail = class {
|
|
|
505
637
|
let reset = false;
|
|
506
638
|
if (st.size < this.offset || this.ino !== void 0 && st.ino !== this.ino) {
|
|
507
639
|
this.offset = 0;
|
|
640
|
+
this.skipping = false;
|
|
508
641
|
reset = true;
|
|
509
642
|
onReset?.();
|
|
510
643
|
}
|
|
@@ -514,19 +647,33 @@ var JsonlTail = class {
|
|
|
514
647
|
try {
|
|
515
648
|
const chunk = Buffer.allocUnsafe(CHUNK_BYTES);
|
|
516
649
|
let pos = this.offset;
|
|
517
|
-
let
|
|
650
|
+
let parts = [];
|
|
651
|
+
let partsLen = 0;
|
|
652
|
+
let skipping = this.skipping;
|
|
518
653
|
while (pos < st.size) {
|
|
519
654
|
const want = Math.min(chunk.length, st.size - pos);
|
|
520
655
|
const { bytesRead } = await fh.read(chunk, 0, want, pos);
|
|
521
656
|
if (bytesRead <= 0) break;
|
|
522
657
|
pos += bytesRead;
|
|
523
|
-
const buf =
|
|
658
|
+
const buf = chunk.subarray(0, bytesRead);
|
|
524
659
|
let start = 0;
|
|
525
660
|
let nl;
|
|
526
661
|
while ((nl = buf.indexOf(10, start)) !== -1) {
|
|
527
|
-
const line = buf.toString("utf8", start, nl).trim();
|
|
528
|
-
start = nl + 1;
|
|
529
662
|
lines += 1;
|
|
663
|
+
const piece = buf.subarray(start, nl);
|
|
664
|
+
start = nl + 1;
|
|
665
|
+
if (skipping) {
|
|
666
|
+
skipping = false;
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
if (partsLen + piece.length > MAX_LINE_BYTES) {
|
|
670
|
+
parts = [];
|
|
671
|
+
partsLen = 0;
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
const line = (partsLen ? Buffer.concat([...parts, piece]) : piece).toString("utf8").trim();
|
|
675
|
+
parts = [];
|
|
676
|
+
partsLen = 0;
|
|
530
677
|
if (!line) continue;
|
|
531
678
|
let record;
|
|
532
679
|
try {
|
|
@@ -534,11 +681,24 @@ var JsonlTail = class {
|
|
|
534
681
|
} catch {
|
|
535
682
|
continue;
|
|
536
683
|
}
|
|
537
|
-
|
|
684
|
+
try {
|
|
685
|
+
onRecord(record);
|
|
686
|
+
} catch {
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
if (!skipping && start < buf.length) {
|
|
690
|
+
if (partsLen + (buf.length - start) > MAX_LINE_BYTES) {
|
|
691
|
+
skipping = true;
|
|
692
|
+
parts = [];
|
|
693
|
+
partsLen = 0;
|
|
694
|
+
} else {
|
|
695
|
+
parts.push(Buffer.from(buf.subarray(start)));
|
|
696
|
+
partsLen += buf.length - start;
|
|
697
|
+
}
|
|
538
698
|
}
|
|
539
|
-
carry = Buffer.from(buf.subarray(start));
|
|
540
699
|
}
|
|
541
|
-
this.
|
|
700
|
+
this.skipping = skipping;
|
|
701
|
+
this.offset = pos - partsLen;
|
|
542
702
|
} finally {
|
|
543
703
|
await fh.close();
|
|
544
704
|
}
|
|
@@ -549,6 +709,21 @@ var JsonlTail = class {
|
|
|
549
709
|
};
|
|
550
710
|
|
|
551
711
|
// ../core/src/adapter.ts
|
|
712
|
+
var reported = /* @__PURE__ */ new Set();
|
|
713
|
+
async function isolated(ctx, what, fn) {
|
|
714
|
+
try {
|
|
715
|
+
return await fn();
|
|
716
|
+
} catch (err) {
|
|
717
|
+
const message = `${what}: ${err instanceof Error ? err.message : String(err)}`;
|
|
718
|
+
if (!reported.has(message)) {
|
|
719
|
+
if (reported.size >= 200) reported.clear();
|
|
720
|
+
reported.add(message);
|
|
721
|
+
ctx.log(message);
|
|
722
|
+
}
|
|
723
|
+
return void 0;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
var fileName = (p2) => p2.split(/[\\/]/).pop() ?? p2;
|
|
552
727
|
var JsonlSessionAdapter = class {
|
|
553
728
|
discoveryIntervalMs = 5e3;
|
|
554
729
|
tracked = /* @__PURE__ */ new Map();
|
|
@@ -571,14 +746,16 @@ var JsonlSessionAdapter = class {
|
|
|
571
746
|
}
|
|
572
747
|
const sessions = [];
|
|
573
748
|
for (const [p2, t] of this.tracked) {
|
|
574
|
-
const
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
749
|
+
const s = await isolated(ctx, `[${this.id}] ${fileName(p2)}`, async () => {
|
|
750
|
+
const res = await t.tail.read(
|
|
751
|
+
(record) => this.onRecord(t.state, record, ctx),
|
|
752
|
+
() => {
|
|
753
|
+
t.state = this.createState(p2);
|
|
754
|
+
}
|
|
755
|
+
);
|
|
756
|
+
await this.afterRead(t.state, ctx, res.changed);
|
|
757
|
+
return this.toSession(t.state, ctx);
|
|
758
|
+
});
|
|
582
759
|
if (s) sessions.push(s);
|
|
583
760
|
}
|
|
584
761
|
return sessions;
|
|
@@ -599,8 +776,22 @@ import path11 from "node:path";
|
|
|
599
776
|
import path2 from "node:path";
|
|
600
777
|
|
|
601
778
|
// ../core/src/util/checklist.ts
|
|
602
|
-
var ITEM_RE = /^(\
|
|
603
|
-
var
|
|
779
|
+
var ITEM_RE = /^([ \t]*)(?:[-*+]|\d{1,9}[.)])[ \t]+\[([ xX/\-~>!?])\][ \t]+(\S.*)$/;
|
|
780
|
+
var KEY_RE = /^[A-Za-z0-9_-]{1,40}$/;
|
|
781
|
+
var MAX_LINE = 2e3;
|
|
782
|
+
var MAX_TASKS = 500;
|
|
783
|
+
function heading(line) {
|
|
784
|
+
let level = 0;
|
|
785
|
+
while (level < line.length && line[level] === "#") level += 1;
|
|
786
|
+
if (level < 1 || level > 6) return void 0;
|
|
787
|
+
const rest = line.slice(level);
|
|
788
|
+
if (rest !== "" && rest[0] !== " " && rest[0] !== " ") return void 0;
|
|
789
|
+
let text = rest.trim();
|
|
790
|
+
let end2 = text.length;
|
|
791
|
+
while (end2 > 0 && text[end2 - 1] === "#") end2 -= 1;
|
|
792
|
+
if (end2 < text.length && (end2 === 0 || text[end2 - 1] === " " || text[end2 - 1] === " ")) text = text.slice(0, end2).trimEnd();
|
|
793
|
+
return text ? [level, text] : void 0;
|
|
794
|
+
}
|
|
604
795
|
var MARKER_STATUS = {
|
|
605
796
|
" ": "pending",
|
|
606
797
|
x: "completed",
|
|
@@ -613,14 +804,17 @@ var MARKER_STATUS = {
|
|
|
613
804
|
"?": "blocked"
|
|
614
805
|
};
|
|
615
806
|
function parseChecklist(markdown) {
|
|
616
|
-
const frontmatter =
|
|
617
|
-
let body = markdown.replace(
|
|
807
|
+
const frontmatter = /* @__PURE__ */ Object.create(null);
|
|
808
|
+
let body = markdown.replace(/^\ufeff/, "");
|
|
618
809
|
if (body.startsWith("---")) {
|
|
619
810
|
const end2 = body.indexOf("\n---", 3);
|
|
620
811
|
if (end2 !== -1) {
|
|
621
812
|
for (const line of body.slice(3, end2).split("\n")) {
|
|
622
|
-
const
|
|
623
|
-
if (
|
|
813
|
+
const colon = line.indexOf(":");
|
|
814
|
+
if (colon < 1) continue;
|
|
815
|
+
const key = line.slice(0, colon).trim();
|
|
816
|
+
if (!KEY_RE.test(key)) continue;
|
|
817
|
+
frontmatter[key.toLowerCase()] = line.slice(colon + 1, colon + 1 + MAX_LINE).trim().replace(/^["']|["']$/g, "");
|
|
624
818
|
}
|
|
625
819
|
body = body.slice(end2 + 4);
|
|
626
820
|
}
|
|
@@ -630,16 +824,17 @@ function parseChecklist(markdown) {
|
|
|
630
824
|
const tasks = [];
|
|
631
825
|
let inFence = false;
|
|
632
826
|
for (const raw of body.split("\n")) {
|
|
633
|
-
|
|
634
|
-
|
|
827
|
+
if (tasks.length >= MAX_TASKS) break;
|
|
828
|
+
const line = (raw.length > MAX_LINE ? raw.slice(0, MAX_LINE) : raw).replace(/\r$/, "");
|
|
829
|
+
if (/^[ \t]*(```|~~~)/.test(line)) {
|
|
635
830
|
inFence = !inFence;
|
|
636
831
|
continue;
|
|
637
832
|
}
|
|
638
833
|
if (inFence) continue;
|
|
639
|
-
const h =
|
|
834
|
+
const h = heading(line);
|
|
640
835
|
if (h) {
|
|
641
|
-
const text = h
|
|
642
|
-
if (
|
|
836
|
+
const [level, text] = h;
|
|
837
|
+
if (level === 1 && title === void 0) title = text;
|
|
643
838
|
else group = text;
|
|
644
839
|
continue;
|
|
645
840
|
}
|
|
@@ -648,7 +843,7 @@ function parseChecklist(markdown) {
|
|
|
648
843
|
const indent = m[1].replace(/\t/g, " ").length;
|
|
649
844
|
tasks.push({
|
|
650
845
|
id: String(tasks.length + 1),
|
|
651
|
-
title: m[3],
|
|
846
|
+
title: m[3].trimEnd(),
|
|
652
847
|
status: MARKER_STATUS[m[2]] ?? "pending",
|
|
653
848
|
depth: Math.floor(indent / 2),
|
|
654
849
|
group
|
|
@@ -719,49 +914,6 @@ function isWithin(child, parent) {
|
|
|
719
914
|
return rel2 === "" || !rel2.startsWith("..") && !path.isAbsolute(rel2);
|
|
720
915
|
}
|
|
721
916
|
|
|
722
|
-
// ../core/src/util/text.ts
|
|
723
|
-
function firstLine(text, max = 80) {
|
|
724
|
-
const line = text.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
|
|
725
|
-
return truncate(line.replace(/\s+/g, " "), max);
|
|
726
|
-
}
|
|
727
|
-
function truncate(text, max) {
|
|
728
|
-
if (text.length <= max) return text;
|
|
729
|
-
return text.slice(0, Math.max(0, max - 1)).trimEnd() + "\u2026";
|
|
730
|
-
}
|
|
731
|
-
function stripInjectedTags(text) {
|
|
732
|
-
return text.replace(/<(system-reminder|local-command-stdout|local-command-stderr|command-message|command-args)>[\s\S]*?<\/\1>/g, "").replace(/<command-name>([\s\S]*?)<\/command-name>/g, "$1").trim();
|
|
733
|
-
}
|
|
734
|
-
function contentText(content) {
|
|
735
|
-
if (typeof content === "string") return content;
|
|
736
|
-
if (!Array.isArray(content)) return "";
|
|
737
|
-
const parts = [];
|
|
738
|
-
for (const part of content) {
|
|
739
|
-
if (typeof part === "string") parts.push(part);
|
|
740
|
-
else if (part && typeof part === "object") {
|
|
741
|
-
const p2 = part;
|
|
742
|
-
if (typeof p2.text === "string" && (p2.type === void 0 || p2.type === "text" || p2.type === "input_text" || p2.type === "output_text")) {
|
|
743
|
-
parts.push(p2.text);
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
}
|
|
747
|
-
return parts.join("\n");
|
|
748
|
-
}
|
|
749
|
-
function summarizeCommand(cmd, max = 80) {
|
|
750
|
-
let text;
|
|
751
|
-
if (typeof cmd === "string") text = cmd;
|
|
752
|
-
else if (Array.isArray(cmd)) {
|
|
753
|
-
const parts = cmd.filter((c) => typeof c === "string");
|
|
754
|
-
if (parts.length >= 3 && /(^|\/)(ba|z|fi)?sh$/.test(parts[0]) && /^-\w*c$/.test(parts[1])) text = parts.slice(2).join(" ");
|
|
755
|
-
else text = parts.join(" ");
|
|
756
|
-
}
|
|
757
|
-
if (!text) return void 0;
|
|
758
|
-
return truncate(text.replace(/\s+/g, " ").trim(), max);
|
|
759
|
-
}
|
|
760
|
-
function basename(p2) {
|
|
761
|
-
const parts = p2.split(/[\\/]/).filter(Boolean);
|
|
762
|
-
return parts[parts.length - 1] ?? p2;
|
|
763
|
-
}
|
|
764
|
-
|
|
765
917
|
// ../core/src/util/task-timer.ts
|
|
766
918
|
var keyOf = (t) => t.title.trim().toLowerCase() || `#${t.id}`;
|
|
767
919
|
function median(xs) {
|
|
@@ -961,14 +1113,16 @@ var AntigravityAdapter = class {
|
|
|
961
1113
|
}
|
|
962
1114
|
const out = [];
|
|
963
1115
|
for (const st of this.tracked.values()) {
|
|
964
|
-
await st.
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
1116
|
+
const s = await isolated(ctx, `[antigravity] ${st.id}`, async () => {
|
|
1117
|
+
await st.tail.read(
|
|
1118
|
+
(rec) => this.onStep(st, rec, ctx),
|
|
1119
|
+
() => {
|
|
1120
|
+
Object.assign(st, this.blank(st.id, st.dir), { tail: st.tail });
|
|
1121
|
+
}
|
|
1122
|
+
);
|
|
1123
|
+
await this.readTask(st);
|
|
1124
|
+
return this.toSession(st, ctx);
|
|
1125
|
+
});
|
|
972
1126
|
if (s) out.push(s);
|
|
973
1127
|
}
|
|
974
1128
|
return out;
|
|
@@ -1101,7 +1255,7 @@ var AntigravityAdapter = class {
|
|
|
1101
1255
|
const meta = await readJsonSafe(path2.join(st.dir, "task.md.metadata.json"));
|
|
1102
1256
|
st.task = {
|
|
1103
1257
|
mtimeMs: s.mtimeMs,
|
|
1104
|
-
title: parsed?.title
|
|
1258
|
+
title: (parsed?.title !== void 0 ? withoutTrackerSuffix(parsed.title) : void 0) || void 0,
|
|
1105
1259
|
tasks: parsed?.tasks ?? [],
|
|
1106
1260
|
summary: typeof meta?.summary === "string" ? meta.summary : void 0
|
|
1107
1261
|
};
|
|
@@ -1173,6 +1327,12 @@ var AntigravityAdapter = class {
|
|
|
1173
1327
|
};
|
|
1174
1328
|
}
|
|
1175
1329
|
};
|
|
1330
|
+
function withoutTrackerSuffix(title) {
|
|
1331
|
+
const s = title.trim();
|
|
1332
|
+
if (!s.toLowerCase().endsWith("task tracker")) return s;
|
|
1333
|
+
const rest = s.slice(0, -"task tracker".length).trimEnd();
|
|
1334
|
+
return /[—–-]$/.test(rest) ? rest.slice(0, -1).trim() : s;
|
|
1335
|
+
}
|
|
1176
1336
|
|
|
1177
1337
|
// ../core/src/adapters/claude-code.ts
|
|
1178
1338
|
import path3 from "node:path";
|
|
@@ -1352,17 +1512,19 @@ var ClaudeCodeAdapter = class {
|
|
|
1352
1512
|
}
|
|
1353
1513
|
const out = [];
|
|
1354
1514
|
for (const entry of this.sessions.values()) {
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1515
|
+
await isolated(ctx, `[claude-code] ${path3.basename(entry.state.file)}`, async () => {
|
|
1516
|
+
const res = await entry.tail.read(
|
|
1517
|
+
(rec) => this.onRecord(entry.state, rec, ctx, false),
|
|
1518
|
+
() => {
|
|
1519
|
+
entry.state = this.createState(entry.state.file);
|
|
1520
|
+
}
|
|
1521
|
+
);
|
|
1522
|
+
await this.readSideFiles(entry.state, ctx, res.changed);
|
|
1523
|
+
});
|
|
1362
1524
|
}
|
|
1363
|
-
await this.readLegacyAgents(ctx);
|
|
1525
|
+
await isolated(ctx, "[claude-code] subagents", () => this.readLegacyAgents(ctx));
|
|
1364
1526
|
for (const entry of this.sessions.values()) {
|
|
1365
|
-
const s = this.toSession(entry.state, ctx);
|
|
1527
|
+
const s = await isolated(ctx, `[claude-code] ${path3.basename(entry.state.file)}`, () => this.toSession(entry.state, ctx));
|
|
1366
1528
|
if (s) out.push(s);
|
|
1367
1529
|
}
|
|
1368
1530
|
return out;
|
|
@@ -1761,7 +1923,7 @@ var ClaudeCodeAdapter = class {
|
|
|
1761
1923
|
else if (pst.mtimeMs !== st.pulse?.mtimeMs) {
|
|
1762
1924
|
const pulse = await readJsonSafe(pulseFile);
|
|
1763
1925
|
st.pulse = pulse && typeof pulse.at === "number" && typeof pulse.phase === "string" ? { ...pulse, mtimeMs: pst.mtimeMs } : void 0;
|
|
1764
|
-
if (st.pulse?.limits) this.addLimits(st.pulse.limits);
|
|
1926
|
+
if (st.pulse?.limits) this.addLimits(st.pulse.limits, ctx.now());
|
|
1765
1927
|
}
|
|
1766
1928
|
const now = ctx.now();
|
|
1767
1929
|
if (now - st.lastSubagentScan >= 5e3) {
|
|
@@ -1784,7 +1946,7 @@ var ClaudeCodeAdapter = class {
|
|
|
1784
1946
|
const windows = this.limitBook.windows(ctx.now());
|
|
1785
1947
|
return windows.length ? { agent: this.id, agentLabel: this.label, windows } : void 0;
|
|
1786
1948
|
}
|
|
1787
|
-
addLimits(l) {
|
|
1949
|
+
addLimits(l, now) {
|
|
1788
1950
|
if (typeof l.at !== "number" || !Array.isArray(l.windows)) return;
|
|
1789
1951
|
for (const w of l.windows) {
|
|
1790
1952
|
if (!w || typeof w.kind !== "string" || typeof w.percentUsed !== "number") continue;
|
|
@@ -1794,10 +1956,10 @@ var ClaudeCodeAdapter = class {
|
|
|
1794
1956
|
const series = l.samples?.[w.kind];
|
|
1795
1957
|
if (Array.isArray(series)) {
|
|
1796
1958
|
for (const pt of series) {
|
|
1797
|
-
if (Array.isArray(pt) && typeof pt[0] === "number" && typeof pt[1] === "number") this.limitBook.add({ label, usedPercent: pt[1], resetsAt, windowMinutes }, pt[0]);
|
|
1959
|
+
if (Array.isArray(pt) && typeof pt[0] === "number" && typeof pt[1] === "number") this.limitBook.add({ label, usedPercent: pt[1], resetsAt, windowMinutes }, pt[0], now);
|
|
1798
1960
|
}
|
|
1799
1961
|
}
|
|
1800
|
-
this.limitBook.add({ label, usedPercent: w.percentUsed, resetsAt, windowMinutes }, l.at);
|
|
1962
|
+
this.limitBook.add({ label, usedPercent: w.percentUsed, resetsAt, windowMinutes }, l.at, now);
|
|
1801
1963
|
}
|
|
1802
1964
|
}
|
|
1803
1965
|
/** Older Claude Code versions wrote subagents as top-level agent-*.jsonl files that reference the parent session. */
|
|
@@ -2003,7 +2165,7 @@ function editorUserDataDirs(home, env, platform = process.platform) {
|
|
|
2003
2165
|
}
|
|
2004
2166
|
|
|
2005
2167
|
// ../core/src/adapters/cline.ts
|
|
2006
|
-
var WAIT_ASKS = {
|
|
2168
|
+
var WAIT_ASKS = lookupTable({
|
|
2007
2169
|
followup: () => "Asked you a question",
|
|
2008
2170
|
plan_mode_respond: () => "Plan ready for your review",
|
|
2009
2171
|
act_mode_respond: () => "Waiting for your reply",
|
|
@@ -2017,7 +2179,7 @@ var WAIT_ASKS = {
|
|
|
2017
2179
|
summarize_task: () => "Wants to summarize the task",
|
|
2018
2180
|
report_bug: () => "Wants to report a bug",
|
|
2019
2181
|
auto_approval_max_req_reached: (_m, label) => `${label} reached its auto-approve limit`
|
|
2020
|
-
};
|
|
2182
|
+
});
|
|
2021
2183
|
var QUIET_SAYS = /* @__PURE__ */ new Set([
|
|
2022
2184
|
"checkpoint_created",
|
|
2023
2185
|
"checkpoint_saved",
|
|
@@ -2041,9 +2203,10 @@ function parseJson(text) {
|
|
|
2041
2203
|
}
|
|
2042
2204
|
}
|
|
2043
2205
|
function stripReqApp(cmd) {
|
|
2044
|
-
|
|
2206
|
+
const t = cmd.trimEnd();
|
|
2207
|
+
return t.endsWith("REQ_APP") ? t.slice(0, -"REQ_APP".length).trimEnd() : cmd;
|
|
2045
2208
|
}
|
|
2046
|
-
var TOOL_LABELS = {
|
|
2209
|
+
var TOOL_LABELS = lookupTable({
|
|
2047
2210
|
editedExistingFile: "Edit",
|
|
2048
2211
|
appliedDiff: "Edit",
|
|
2049
2212
|
insertContent: "Edit",
|
|
@@ -2069,7 +2232,7 @@ var TOOL_LABELS = {
|
|
|
2069
2232
|
imageGenerated: "Generate image",
|
|
2070
2233
|
runSlashCommand: "Slash command",
|
|
2071
2234
|
updateTodoList: "Update plan"
|
|
2072
|
-
};
|
|
2235
|
+
});
|
|
2073
2236
|
function toolActivity(m) {
|
|
2074
2237
|
const kind = m.type === "ask" ? m.ask : m.say;
|
|
2075
2238
|
const at = m.ts;
|
|
@@ -2323,9 +2486,10 @@ var ClineFamilyAdapter = class {
|
|
|
2323
2486
|
const out = [];
|
|
2324
2487
|
const byId = /* @__PURE__ */ new Map();
|
|
2325
2488
|
for (const t of this.tracked.values()) {
|
|
2326
|
-
await this.
|
|
2327
|
-
|
|
2328
|
-
|
|
2489
|
+
const s = await isolated(ctx, `[${this.id}] ${t.id}`, async () => {
|
|
2490
|
+
await this.refresh(t, ctx);
|
|
2491
|
+
return t.fold ? this.toSession(t, ctx) : void 0;
|
|
2492
|
+
});
|
|
2329
2493
|
if (s) {
|
|
2330
2494
|
out.push(s);
|
|
2331
2495
|
byId.set(t.id, s);
|
|
@@ -2584,7 +2748,7 @@ var RooCodeAdapter = class extends ClineFamilyAdapter {
|
|
|
2584
2748
|
return out;
|
|
2585
2749
|
}
|
|
2586
2750
|
};
|
|
2587
|
-
var SDK_TOOL_LABELS = {
|
|
2751
|
+
var SDK_TOOL_LABELS = lookupTable({
|
|
2588
2752
|
read_files: "Read",
|
|
2589
2753
|
search_codebase: "Search",
|
|
2590
2754
|
run_commands: "Shell",
|
|
@@ -2599,7 +2763,7 @@ var SDK_TOOL_LABELS = {
|
|
|
2599
2763
|
read_file: "Read",
|
|
2600
2764
|
write_to_file: "Write",
|
|
2601
2765
|
replace_in_file: "Edit"
|
|
2602
|
-
};
|
|
2766
|
+
});
|
|
2603
2767
|
function sdkActivity(block, at) {
|
|
2604
2768
|
const name = String(block.name ?? "tool");
|
|
2605
2769
|
const input = block.input && typeof block.input === "object" ? block.input : {};
|
|
@@ -2739,8 +2903,10 @@ var ClineSdkSessions = class {
|
|
|
2739
2903
|
}
|
|
2740
2904
|
const out = [];
|
|
2741
2905
|
for (const t of this.tracked.values()) {
|
|
2742
|
-
await
|
|
2743
|
-
|
|
2906
|
+
const s = await isolated(ctx, `[${label}] ${t.id}`, async () => {
|
|
2907
|
+
await this.refresh(t);
|
|
2908
|
+
return this.toSession(t, ctx, label);
|
|
2909
|
+
});
|
|
2744
2910
|
if (s) out.push(s);
|
|
2745
2911
|
}
|
|
2746
2912
|
return out;
|
|
@@ -3133,7 +3299,7 @@ var CodexAdapter = class extends JsonlSessionAdapter {
|
|
|
3133
3299
|
}
|
|
3134
3300
|
if (windows.length) {
|
|
3135
3301
|
st.rateLimits = windows;
|
|
3136
|
-
for (const w of windows) this.limitBook.add(w, ts);
|
|
3302
|
+
for (const w of windows) this.limitBook.add(w, ts, ctx.now());
|
|
3137
3303
|
}
|
|
3138
3304
|
}
|
|
3139
3305
|
}
|
|
@@ -3437,7 +3603,7 @@ function permissionLabel(r) {
|
|
|
3437
3603
|
}
|
|
3438
3604
|
}
|
|
3439
3605
|
function todoMarkdown(md) {
|
|
3440
|
-
return parseChecklist(md.replace(/^(\
|
|
3606
|
+
return parseChecklist(md.replace(/^([ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]*)\[[-~]\]/gm, "$1[/]")).tasks;
|
|
3441
3607
|
}
|
|
3442
3608
|
function dbStatus(s) {
|
|
3443
3609
|
return s === "done" ? "completed" : s === "in_progress" ? "in_progress" : s === "blocked" ? "blocked" : "pending";
|
|
@@ -4821,8 +4987,9 @@ var KiloCodeAdapter = class extends OpenCodeFamilyAdapter {
|
|
|
4821
4987
|
};
|
|
4822
4988
|
|
|
4823
4989
|
// ../core/src/adapters/progress-file.ts
|
|
4990
|
+
import { promises as fsp4 } from "node:fs";
|
|
4824
4991
|
import path10 from "node:path";
|
|
4825
|
-
var STATUS_WORDS = {
|
|
4992
|
+
var STATUS_WORDS = lookupTable({
|
|
4826
4993
|
working: "working",
|
|
4827
4994
|
running: "working",
|
|
4828
4995
|
in_progress: "working",
|
|
@@ -4835,7 +5002,16 @@ var STATUS_WORDS = {
|
|
|
4835
5002
|
paused: "idle",
|
|
4836
5003
|
error: "error",
|
|
4837
5004
|
failed: "error"
|
|
4838
|
-
};
|
|
5005
|
+
});
|
|
5006
|
+
var MAX_PROGRESS_FILES = 20;
|
|
5007
|
+
var MAX_LISTED = 500;
|
|
5008
|
+
async function realpathSafe(p2) {
|
|
5009
|
+
try {
|
|
5010
|
+
return await fsp4.realpath(p2);
|
|
5011
|
+
} catch {
|
|
5012
|
+
return void 0;
|
|
5013
|
+
}
|
|
5014
|
+
}
|
|
4839
5015
|
var ProgressFileAdapter = class {
|
|
4840
5016
|
id = "progress-file";
|
|
4841
5017
|
label = "Progress file";
|
|
@@ -4845,16 +5021,26 @@ var ProgressFileAdapter = class {
|
|
|
4845
5021
|
const files = [];
|
|
4846
5022
|
for (const root of ctx.workspaceRoots) {
|
|
4847
5023
|
const agentsDir = path10.join(root, ".agents");
|
|
4848
|
-
|
|
4849
|
-
for (const f of await listDir(path10.join(agentsDir, "progress"))) {
|
|
4850
|
-
if (f.isFile() && f.name.endsWith(".md"))
|
|
5024
|
+
const names = [path10.join(agentsDir, "progress.md")];
|
|
5025
|
+
for (const f of (await listDir(path10.join(agentsDir, "progress"))).slice(0, MAX_LISTED)) {
|
|
5026
|
+
if (f.isFile() && f.name.endsWith(".md")) names.push(path10.join(agentsDir, "progress", f.name));
|
|
5027
|
+
}
|
|
5028
|
+
const realRoot = await realpathSafe(root);
|
|
5029
|
+
if (!realRoot) continue;
|
|
5030
|
+
const found = [];
|
|
5031
|
+
for (const file of names) {
|
|
5032
|
+
const st = await statSafe(file);
|
|
5033
|
+
if (!st || !st.isFile()) continue;
|
|
5034
|
+
const real = await realpathSafe(file);
|
|
5035
|
+
if (!real || !pathWithin(real, realRoot)) continue;
|
|
5036
|
+
found.push({ file, root, st });
|
|
4851
5037
|
}
|
|
5038
|
+
found.sort((a, b) => b.st.mtimeMs - a.st.mtimeMs);
|
|
5039
|
+
files.push(...found.slice(0, MAX_PROGRESS_FILES));
|
|
4852
5040
|
}
|
|
4853
5041
|
const out = [];
|
|
4854
5042
|
const seen = /* @__PURE__ */ new Set();
|
|
4855
|
-
for (const { file, root } of files) {
|
|
4856
|
-
const st = await statSafe(file);
|
|
4857
|
-
if (!st || !st.isFile()) continue;
|
|
5043
|
+
for (const { file, root, st } of files) {
|
|
4858
5044
|
seen.add(file);
|
|
4859
5045
|
let entry = this.cache.get(file);
|
|
4860
5046
|
if (!entry || entry.mtimeMs !== st.mtimeMs) {
|
|
@@ -4929,16 +5115,43 @@ function createDefaultAdapters(opts = {}) {
|
|
|
4929
5115
|
];
|
|
4930
5116
|
}
|
|
4931
5117
|
var sameProject = (a, b) => !!a && !!b && (pathWithin(a, b) || pathWithin(b, a));
|
|
5118
|
+
function cleanSession(s) {
|
|
5119
|
+
const out = cleanFields(s, { title: 500, agentLabel: 60, model: 80, agentVersion: 40, statusDetail: 500 });
|
|
5120
|
+
const tasks = s.tasks.map((t) => cleanFields(t, { title: 500, activeTitle: 500, group: 200 }));
|
|
5121
|
+
const activity = s.activity && cleanFields(s.activity, { label: 200, detail: 500 });
|
|
5122
|
+
const recent = s.recent?.map((a) => cleanFields(a, { label: 200, detail: 500 }));
|
|
5123
|
+
const loop = s.loop && cleanFields(s.loop, { label: 200, detail: 500 });
|
|
5124
|
+
const trouble = s.trouble && cleanFields(s.trouble, { message: 500 });
|
|
5125
|
+
const pulse = s.pulse && cleanFields(s.pulse, { label: 200, detail: 500 });
|
|
5126
|
+
const rateLimits = s.rateLimits?.map((w) => cleanFields(w, { label: 40 }));
|
|
5127
|
+
const changed = out !== s || tasks.some((t, i) => t !== s.tasks[i]) || activity !== s.activity || recent !== void 0 && recent.some((a, i) => a !== s.recent[i]) || loop !== s.loop || trouble !== s.trouble || pulse !== s.pulse || rateLimits !== void 0 && rateLimits.some((w, i) => w !== s.rateLimits[i]);
|
|
5128
|
+
if (!changed) return s;
|
|
5129
|
+
return {
|
|
5130
|
+
...out,
|
|
5131
|
+
tasks,
|
|
5132
|
+
...activity && { activity },
|
|
5133
|
+
...recent && { recent },
|
|
5134
|
+
...loop && { loop },
|
|
5135
|
+
...trouble && { trouble },
|
|
5136
|
+
...pulse && { pulse },
|
|
5137
|
+
...rateLimits && { rateLimits }
|
|
5138
|
+
};
|
|
5139
|
+
}
|
|
5140
|
+
function cleanLimits(l) {
|
|
5141
|
+
const agentLabel = cleanText(l.agentLabel, 60);
|
|
5142
|
+
const windows = l.windows.map((w) => cleanFields(w, { label: 40 }));
|
|
5143
|
+
return agentLabel === l.agentLabel && windows.every((w, i) => w === l.windows[i]) ? l : { ...l, agentLabel, windows };
|
|
5144
|
+
}
|
|
4932
5145
|
function mergeProgressFiles(sessions) {
|
|
4933
5146
|
const native = sessions.filter((s) => s.agent !== "progress-file");
|
|
4934
5147
|
const out = [...native];
|
|
4935
5148
|
for (const pf of sessions) {
|
|
4936
5149
|
if (pf.agent !== "progress-file") continue;
|
|
4937
|
-
const label = pf.agentLabel.toLowerCase();
|
|
5150
|
+
const label = pf.agentLabel.trim().toLowerCase();
|
|
4938
5151
|
const match = native.filter((n) => {
|
|
4939
5152
|
const name = n.agentLabel.toLowerCase();
|
|
4940
5153
|
const short = name.split(" ")[0];
|
|
4941
|
-
return (label
|
|
5154
|
+
return (label === name || label === short) && sameProject(n.projectPath, pf.projectPath);
|
|
4942
5155
|
}).sort((a, b) => b.updatedAt - a.updatedAt)[0];
|
|
4943
5156
|
if (!match) {
|
|
4944
5157
|
out.push(pf);
|
|
@@ -4989,8 +5202,9 @@ var Engine = class {
|
|
|
4989
5202
|
workspaceRoots: opts.workspaceRoots ?? [],
|
|
4990
5203
|
pricing: opts.pricing ?? new Pricing(),
|
|
4991
5204
|
liveDir: opts.liveDir ?? defaultLiveDir(home),
|
|
4992
|
-
|
|
4993
|
-
|
|
5205
|
+
// Messages can quote a broken file (a parser's error does): keep its escapes out of a terminal.
|
|
5206
|
+
log: opts.log ? (m) => opts.log(cleanText(m, 2e3)) : () => {
|
|
5207
|
+
}
|
|
4994
5208
|
};
|
|
4995
5209
|
}
|
|
4996
5210
|
get snapshot() {
|
|
@@ -5033,7 +5247,11 @@ var Engine = class {
|
|
|
5033
5247
|
}
|
|
5034
5248
|
async loop() {
|
|
5035
5249
|
if (this.stopped) return;
|
|
5036
|
-
|
|
5250
|
+
try {
|
|
5251
|
+
await this.tick();
|
|
5252
|
+
} catch (err) {
|
|
5253
|
+
this.ctx.log(`tick failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
5254
|
+
}
|
|
5037
5255
|
if (this.stopped) return;
|
|
5038
5256
|
this.timer = setTimeout(() => void this.loop(), this.intervalMs);
|
|
5039
5257
|
}
|
|
@@ -5052,17 +5270,18 @@ var Engine = class {
|
|
|
5052
5270
|
const l = a.limits?.(this.ctx);
|
|
5053
5271
|
if (l?.windows.length) limits.push(l);
|
|
5054
5272
|
} catch (err) {
|
|
5055
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
5273
|
+
const message = cleanText(err instanceof Error ? err.message : String(err), 500);
|
|
5056
5274
|
errors.push({ agent: a.id, message });
|
|
5057
5275
|
this.ctx.log(`[${a.id}] ${message}`);
|
|
5058
5276
|
}
|
|
5059
5277
|
}
|
|
5060
|
-
const merged = mergeProgressFiles(sessions);
|
|
5278
|
+
const merged = mergeProgressFiles(sessions).map(cleanSession);
|
|
5279
|
+
const shown = limits.map(cleanLimits);
|
|
5061
5280
|
sortSessions(merged);
|
|
5062
|
-
const signature = JSON.stringify([merged, errors,
|
|
5281
|
+
const signature = JSON.stringify([merged, errors, shown]);
|
|
5063
5282
|
if (signature !== this.lastSignature) {
|
|
5064
5283
|
this.lastSignature = signature;
|
|
5065
|
-
this.current = { generatedAt: this.ctx.now(), sessions: merged, errors, ...
|
|
5284
|
+
this.current = { generatedAt: this.ctx.now(), sessions: merged, errors, ...shown.length ? { limits: shown } : {} };
|
|
5066
5285
|
for (const l of this.listeners) {
|
|
5067
5286
|
try {
|
|
5068
5287
|
l(this.current);
|
|
@@ -5079,9 +5298,46 @@ var Engine = class {
|
|
|
5079
5298
|
};
|
|
5080
5299
|
|
|
5081
5300
|
// ../core/src/hooks/hub.ts
|
|
5082
|
-
import { promises as
|
|
5301
|
+
import { promises as fsp6 } from "node:fs";
|
|
5083
5302
|
import http from "node:http";
|
|
5084
5303
|
import path12 from "node:path";
|
|
5304
|
+
|
|
5305
|
+
// ../core/src/util/files.ts
|
|
5306
|
+
import { randomBytes } from "node:crypto";
|
|
5307
|
+
import { promises as fsp5 } from "node:fs";
|
|
5308
|
+
async function writeFileSafely(file, text, mode) {
|
|
5309
|
+
let current;
|
|
5310
|
+
try {
|
|
5311
|
+
const st = await fsp5.lstat(file);
|
|
5312
|
+
current = { link: st.isSymbolicLink(), mode: st.mode & 511 };
|
|
5313
|
+
} catch {
|
|
5314
|
+
}
|
|
5315
|
+
if (current?.link) {
|
|
5316
|
+
await fsp5.writeFile(file, text);
|
|
5317
|
+
return;
|
|
5318
|
+
}
|
|
5319
|
+
const tmp = `${file}.kvali-${process.pid}-${randomBytes(4).toString("hex")}.tmp`;
|
|
5320
|
+
try {
|
|
5321
|
+
await fsp5.writeFile(tmp, text, { mode: mode ?? current?.mode ?? 420, flag: "wx" });
|
|
5322
|
+
if (current) await fsp5.chmod(tmp, mode ?? current.mode);
|
|
5323
|
+
await fsp5.rename(tmp, file);
|
|
5324
|
+
} catch (err) {
|
|
5325
|
+
await fsp5.rm(tmp, { force: true }).catch(() => void 0);
|
|
5326
|
+
throw err;
|
|
5327
|
+
}
|
|
5328
|
+
}
|
|
5329
|
+
function trimTrailingNewlines(text) {
|
|
5330
|
+
let end2 = text.length;
|
|
5331
|
+
while (end2 > 0 && (text[end2 - 1] === "\n" || text[end2 - 1] === "\r")) end2 -= 1;
|
|
5332
|
+
return text.slice(0, end2);
|
|
5333
|
+
}
|
|
5334
|
+
function trimLeadingNewlines(text) {
|
|
5335
|
+
let start = 0;
|
|
5336
|
+
while (start < text.length && (text[start] === "\n" || text[start] === "\r")) start += 1;
|
|
5337
|
+
return text.slice(start);
|
|
5338
|
+
}
|
|
5339
|
+
|
|
5340
|
+
// ../core/src/hooks/hub.ts
|
|
5085
5341
|
var DEFAULT_HOOK_PORT = 47821;
|
|
5086
5342
|
var MAX_BODY = 1 << 20;
|
|
5087
5343
|
var SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
|
|
@@ -5137,6 +5393,10 @@ var HookHub = class {
|
|
|
5137
5393
|
tryListen() {
|
|
5138
5394
|
if (this.disposed) return;
|
|
5139
5395
|
const server = http.createServer((req, res) => void this.handle(req, res));
|
|
5396
|
+
server.headersTimeout = 5e3;
|
|
5397
|
+
server.requestTimeout = 1e4;
|
|
5398
|
+
server.keepAliveTimeout = 2e3;
|
|
5399
|
+
server.maxConnections = 64;
|
|
5140
5400
|
server.on("error", (err) => {
|
|
5141
5401
|
server.close();
|
|
5142
5402
|
this.setHub(false);
|
|
@@ -5159,8 +5419,16 @@ var HookHub = class {
|
|
|
5159
5419
|
const port = this.server?.address()?.port ?? this.port;
|
|
5160
5420
|
return host === `127.0.0.1:${port}` || host === `localhost:${port}` || host === `[::1]:${port}`;
|
|
5161
5421
|
}
|
|
5422
|
+
/**
|
|
5423
|
+
* Browsers name the page a request comes from (`Origin`, `Sec-Fetch-Site`), even for requests a
|
|
5424
|
+
* page may send to another site without asking (a form post, `fetch` with `no-cors`). Hooks run
|
|
5425
|
+
* curl, which sends neither (nor does Node's `fetch`).
|
|
5426
|
+
*/
|
|
5427
|
+
fromBrowser(req) {
|
|
5428
|
+
return req.headers.origin !== void 0 || req.headers["sec-fetch-site"] !== void 0;
|
|
5429
|
+
}
|
|
5162
5430
|
async handle(req, res) {
|
|
5163
|
-
if (!this.localHost(req)) {
|
|
5431
|
+
if (!this.localHost(req) || this.fromBrowser(req)) {
|
|
5164
5432
|
res.writeHead(403).end();
|
|
5165
5433
|
return;
|
|
5166
5434
|
}
|
|
@@ -5171,8 +5439,8 @@ var HookHub = class {
|
|
|
5171
5439
|
return;
|
|
5172
5440
|
}
|
|
5173
5441
|
const m = /^\/v1\/events\/([a-z-]+)$/.exec(url);
|
|
5174
|
-
const type = String(req.headers["content-type"] ?? "");
|
|
5175
|
-
if (req.method !== "POST" || !m || !AGENTS.has(m[1]) ||
|
|
5442
|
+
const type = String(req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
|
|
5443
|
+
if (req.method !== "POST" || !m || !AGENTS.has(m[1]) || type !== "application/json") {
|
|
5176
5444
|
res.writeHead(404).end();
|
|
5177
5445
|
return;
|
|
5178
5446
|
}
|
|
@@ -5207,23 +5475,20 @@ var HookHub = class {
|
|
|
5207
5475
|
}
|
|
5208
5476
|
async store(agent, ev) {
|
|
5209
5477
|
const dir = path12.join(this.opts.liveDir, agent);
|
|
5210
|
-
await
|
|
5211
|
-
|
|
5212
|
-
const tmp = `${file}.${process.pid}.tmp`;
|
|
5213
|
-
await fsp4.writeFile(tmp, JSON.stringify(ev));
|
|
5214
|
-
await fsp4.rename(tmp, file);
|
|
5478
|
+
await fsp6.mkdir(dir, { recursive: true, mode: 448 });
|
|
5479
|
+
await writeFileSafely(path12.join(dir, `${ev.sessionId}.json`), JSON.stringify(ev), 384);
|
|
5215
5480
|
}
|
|
5216
5481
|
};
|
|
5217
5482
|
|
|
5218
5483
|
// ../core/src/hooks/claude-install.ts
|
|
5219
|
-
import { promises as
|
|
5484
|
+
import { promises as fsp8 } from "node:fs";
|
|
5220
5485
|
import os2 from "node:os";
|
|
5221
5486
|
import path14 from "node:path";
|
|
5222
5487
|
|
|
5223
5488
|
// ../core/src/hooks/claude-plugin.ts
|
|
5224
5489
|
import { execFile } from "node:child_process";
|
|
5225
5490
|
import { createHash } from "node:crypto";
|
|
5226
|
-
import { constants as fsc, promises as
|
|
5491
|
+
import { constants as fsc, promises as fsp7 } from "node:fs";
|
|
5227
5492
|
import path13 from "node:path";
|
|
5228
5493
|
var CLAUDE_PLUGIN_ID = "kvali@kvali";
|
|
5229
5494
|
var CLAUDE_MARKETPLACE = "kvali";
|
|
@@ -5233,7 +5498,7 @@ async function filesUnder(dir, base = dir) {
|
|
|
5233
5498
|
const out = [];
|
|
5234
5499
|
let entries;
|
|
5235
5500
|
try {
|
|
5236
|
-
entries = await
|
|
5501
|
+
entries = await fsp7.readdir(dir, { withFileTypes: true });
|
|
5237
5502
|
} catch {
|
|
5238
5503
|
return out;
|
|
5239
5504
|
}
|
|
@@ -5253,14 +5518,14 @@ async function pluginFingerprint(dir) {
|
|
|
5253
5518
|
for (const f of files) {
|
|
5254
5519
|
h.update(f.split(path13.sep).join("/"));
|
|
5255
5520
|
h.update("\0");
|
|
5256
|
-
h.update(await
|
|
5521
|
+
h.update(await fsp7.readFile(path13.join(dir, f)));
|
|
5257
5522
|
h.update("\0");
|
|
5258
5523
|
}
|
|
5259
5524
|
return h.digest("hex");
|
|
5260
5525
|
}
|
|
5261
5526
|
async function pluginVersion(dir) {
|
|
5262
5527
|
try {
|
|
5263
|
-
const v = JSON.parse(await
|
|
5528
|
+
const v = JSON.parse(await fsp7.readFile(path13.join(dir, ".claude-plugin", "plugin.json"), "utf8")).version;
|
|
5264
5529
|
return typeof v === "string" ? v : void 0;
|
|
5265
5530
|
} catch {
|
|
5266
5531
|
return void 0;
|
|
@@ -5280,11 +5545,11 @@ async function syncClaudePlugin(bundledDir, home) {
|
|
|
5280
5545
|
const [mine, theirs] = await Promise.all([pluginVersion(bundledDir), pluginVersion(target)]);
|
|
5281
5546
|
if (mine && theirs && compareVersions(mine, theirs) < 0) return false;
|
|
5282
5547
|
const next = `${target}.next`;
|
|
5283
|
-
await
|
|
5284
|
-
await
|
|
5285
|
-
await
|
|
5286
|
-
await
|
|
5287
|
-
await
|
|
5548
|
+
await fsp7.rm(next, { recursive: true, force: true });
|
|
5549
|
+
await fsp7.mkdir(path13.dirname(target), { recursive: true });
|
|
5550
|
+
await fsp7.cp(bundledDir, next, { recursive: true });
|
|
5551
|
+
await fsp7.rm(target, { recursive: true, force: true });
|
|
5552
|
+
await fsp7.rename(next, target);
|
|
5288
5553
|
return true;
|
|
5289
5554
|
}
|
|
5290
5555
|
async function claudeExtensionDirs(home) {
|
|
@@ -5295,7 +5560,7 @@ async function claudeExtensionDirs(home) {
|
|
|
5295
5560
|
for (const root of roots) {
|
|
5296
5561
|
let names = [];
|
|
5297
5562
|
try {
|
|
5298
|
-
names = await
|
|
5563
|
+
names = await fsp7.readdir(root);
|
|
5299
5564
|
} catch {
|
|
5300
5565
|
continue;
|
|
5301
5566
|
}
|
|
@@ -5316,7 +5581,7 @@ async function findClaudeBinary(opts) {
|
|
|
5316
5581
|
const bin = path13.join(d, "resources", "native-binary");
|
|
5317
5582
|
let inside = [];
|
|
5318
5583
|
try {
|
|
5319
|
-
inside = await
|
|
5584
|
+
inside = await fsp7.readdir(bin);
|
|
5320
5585
|
} catch {
|
|
5321
5586
|
continue;
|
|
5322
5587
|
}
|
|
@@ -5328,8 +5593,8 @@ async function findClaudeBinary(opts) {
|
|
|
5328
5593
|
if (!win) candidates.push("/opt/homebrew/bin/claude", "/usr/local/bin/claude");
|
|
5329
5594
|
for (const c of candidates) {
|
|
5330
5595
|
try {
|
|
5331
|
-
await
|
|
5332
|
-
if ((await
|
|
5596
|
+
await fsp7.access(c, win ? fsc.F_OK : fsc.X_OK);
|
|
5597
|
+
if ((await fsp7.stat(c)).isFile()) return c;
|
|
5333
5598
|
} catch {
|
|
5334
5599
|
}
|
|
5335
5600
|
}
|
|
@@ -5382,7 +5647,7 @@ async function installClaudePlugin(bin, dir, env) {
|
|
|
5382
5647
|
}
|
|
5383
5648
|
async function claudePluginEnabled(settingsFile) {
|
|
5384
5649
|
try {
|
|
5385
|
-
const s = JSON.parse(await
|
|
5650
|
+
const s = JSON.parse(await fsp7.readFile(settingsFile, "utf8"));
|
|
5386
5651
|
return s?.enabledPlugins?.[CLAUDE_PLUGIN_ID] === true;
|
|
5387
5652
|
} catch {
|
|
5388
5653
|
return false;
|
|
@@ -5390,15 +5655,15 @@ async function claudePluginEnabled(settingsFile) {
|
|
|
5390
5655
|
}
|
|
5391
5656
|
async function readKvaliState(home) {
|
|
5392
5657
|
try {
|
|
5393
|
-
return JSON.parse(await
|
|
5658
|
+
return JSON.parse(await fsp7.readFile(stateFile(home), "utf8")) ?? {};
|
|
5394
5659
|
} catch {
|
|
5395
5660
|
return {};
|
|
5396
5661
|
}
|
|
5397
5662
|
}
|
|
5398
5663
|
async function writeKvaliState(home, patch) {
|
|
5399
5664
|
const next = { ...await readKvaliState(home), ...patch };
|
|
5400
|
-
await
|
|
5401
|
-
await
|
|
5665
|
+
await fsp7.mkdir(path13.dirname(stateFile(home)), { recursive: true, mode: 448 });
|
|
5666
|
+
await writeFileSafely(stateFile(home), `${JSON.stringify(next, null, 2)}
|
|
5402
5667
|
`);
|
|
5403
5668
|
}
|
|
5404
5669
|
async function removeClaudePlugin(opts) {
|
|
@@ -5415,7 +5680,7 @@ async function removeClaudePlugin(opts) {
|
|
|
5415
5680
|
}
|
|
5416
5681
|
} else {
|
|
5417
5682
|
try {
|
|
5418
|
-
const raw = await
|
|
5683
|
+
const raw = await fsp7.readFile(opts.settingsFile, "utf8");
|
|
5419
5684
|
const s = JSON.parse(raw);
|
|
5420
5685
|
let changed = false;
|
|
5421
5686
|
if (s.enabledPlugins && CLAUDE_PLUGIN_ID in s.enabledPlugins) {
|
|
@@ -5427,12 +5692,12 @@ async function removeClaudePlugin(opts) {
|
|
|
5427
5692
|
delete s.extraKnownMarketplaces[CLAUDE_MARKETPLACE];
|
|
5428
5693
|
changed = true;
|
|
5429
5694
|
}
|
|
5430
|
-
if (changed) await
|
|
5695
|
+
if (changed) await fsp7.writeFile(opts.settingsFile, `${JSON.stringify(s, null, 2)}
|
|
5431
5696
|
`);
|
|
5432
5697
|
} catch {
|
|
5433
5698
|
}
|
|
5434
5699
|
}
|
|
5435
|
-
await
|
|
5700
|
+
await fsp7.rm(dir, { recursive: true, force: true });
|
|
5436
5701
|
await writeKvaliState(opts.home, { claudePlugin: false });
|
|
5437
5702
|
return true;
|
|
5438
5703
|
}
|
|
@@ -5460,7 +5725,7 @@ function hookEntry(spec, port) {
|
|
|
5460
5725
|
async function readSettings(file) {
|
|
5461
5726
|
let text;
|
|
5462
5727
|
try {
|
|
5463
|
-
text = await
|
|
5728
|
+
text = await fsp8.readFile(file, "utf8");
|
|
5464
5729
|
} catch (err) {
|
|
5465
5730
|
if (err.code === "ENOENT") return {};
|
|
5466
5731
|
throw err;
|
|
@@ -5517,13 +5782,13 @@ async function claudeHooksStatus(file = claudeSettingsPath(), port = DEFAULT_HOO
|
|
|
5517
5782
|
return current === CLAUDE_HOOKS.length && total === CLAUDE_HOOKS.length ? "installed" : "outdated";
|
|
5518
5783
|
}
|
|
5519
5784
|
async function writeWithBackup(file, before, settings) {
|
|
5520
|
-
await
|
|
5785
|
+
await fsp8.mkdir(path14.dirname(file), { recursive: true });
|
|
5521
5786
|
let backup;
|
|
5522
5787
|
if (before !== void 0) {
|
|
5523
5788
|
backup = `${file}.kvali-backup`;
|
|
5524
|
-
await
|
|
5789
|
+
await writeFileSafely(backup, before, 384);
|
|
5525
5790
|
}
|
|
5526
|
-
await
|
|
5791
|
+
await writeFileSafely(file, JSON.stringify(settings, null, 2) + "\n");
|
|
5527
5792
|
return backup;
|
|
5528
5793
|
}
|
|
5529
5794
|
function canonical(v) {
|
|
@@ -5533,7 +5798,7 @@ function canonical(v) {
|
|
|
5533
5798
|
);
|
|
5534
5799
|
}
|
|
5535
5800
|
async function installClaudeHooks(file = claudeSettingsPath(), port = DEFAULT_HOOK_PORT) {
|
|
5536
|
-
const before = await
|
|
5801
|
+
const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
|
|
5537
5802
|
const current = await readSettings(file);
|
|
5538
5803
|
const settings = withoutKvali(current);
|
|
5539
5804
|
settings.hooks = settings.hooks && typeof settings.hooks === "object" ? settings.hooks : {};
|
|
@@ -5549,7 +5814,7 @@ function envOf(settings) {
|
|
|
5549
5814
|
return settings.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : void 0;
|
|
5550
5815
|
}
|
|
5551
5816
|
async function enableClaudeTodoTools(file, home) {
|
|
5552
|
-
const before = await
|
|
5817
|
+
const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
|
|
5553
5818
|
const settings = await readSettings(file);
|
|
5554
5819
|
const env = envOf(settings);
|
|
5555
5820
|
if (env && CLAUDE_TODO_TOOLS_ENV in env) return { changed: false };
|
|
@@ -5560,7 +5825,7 @@ async function enableClaudeTodoTools(file, home) {
|
|
|
5560
5825
|
}
|
|
5561
5826
|
async function disableClaudeTodoTools(file, home) {
|
|
5562
5827
|
if (!(await readKvaliState(home)).claudeTodoTools) return { changed: false };
|
|
5563
|
-
const before = await
|
|
5828
|
+
const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
|
|
5564
5829
|
let changed = false;
|
|
5565
5830
|
if (before !== void 0) {
|
|
5566
5831
|
const settings = await readSettings(file);
|
|
@@ -5577,7 +5842,7 @@ async function disableClaudeTodoTools(file, home) {
|
|
|
5577
5842
|
return { changed };
|
|
5578
5843
|
}
|
|
5579
5844
|
async function uninstallClaudeHooks(file = claudeSettingsPath()) {
|
|
5580
|
-
const before = await
|
|
5845
|
+
const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
|
|
5581
5846
|
if (before === void 0) return { changed: false };
|
|
5582
5847
|
const settings = await readSettings(file);
|
|
5583
5848
|
const next = withoutKvali(settings);
|
|
@@ -5586,7 +5851,7 @@ async function uninstallClaudeHooks(file = claudeSettingsPath()) {
|
|
|
5586
5851
|
}
|
|
5587
5852
|
|
|
5588
5853
|
// ../core/src/protocol.ts
|
|
5589
|
-
import { promises as
|
|
5854
|
+
import { promises as fsp9 } from "node:fs";
|
|
5590
5855
|
import path15 from "node:path";
|
|
5591
5856
|
var PROGRESS_PROTOCOL_MARKER = "<!-- kvali:progress-protocol v2 -->";
|
|
5592
5857
|
function progressProtocolSnippet() {
|
|
@@ -5622,18 +5887,41 @@ For any task that takes more than two steps, create a task list with your built-
|
|
|
5622
5887
|
<!-- /kvali:plan-rule -->
|
|
5623
5888
|
`;
|
|
5624
5889
|
}
|
|
5890
|
+
function findBlock(text, name) {
|
|
5891
|
+
const open = new RegExp(`^<!-- kvali:${name} v\\d+ -->$`);
|
|
5892
|
+
const close = `<!-- /kvali:${name} -->`;
|
|
5893
|
+
let fence;
|
|
5894
|
+
let start;
|
|
5895
|
+
let pos = 0;
|
|
5896
|
+
for (const raw of text.split("\n")) {
|
|
5897
|
+
const at = pos;
|
|
5898
|
+
pos += raw.length + 1;
|
|
5899
|
+
const line = (raw.endsWith("\r") ? raw.slice(0, -1) : raw).trimEnd();
|
|
5900
|
+
const f = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
|
|
5901
|
+
if (f) {
|
|
5902
|
+
const mark = f[1];
|
|
5903
|
+
if (!fence) fence = { ch: mark[0], len: mark.length };
|
|
5904
|
+
else if (mark[0] === fence.ch && mark.length >= fence.len && f[2].trim() === "") fence = void 0;
|
|
5905
|
+
continue;
|
|
5906
|
+
}
|
|
5907
|
+
if (fence) continue;
|
|
5908
|
+
if (start === void 0) {
|
|
5909
|
+
if (open.test(line)) start = at;
|
|
5910
|
+
} else if (line === close) {
|
|
5911
|
+
return { start, end: at + close.length };
|
|
5912
|
+
}
|
|
5913
|
+
}
|
|
5914
|
+
return start === void 0 ? void 0 : { start };
|
|
5915
|
+
}
|
|
5625
5916
|
function withBlock(text, name, snippet) {
|
|
5626
5917
|
if (text === void 0 || text === "") return { text: snippet, result: text === void 0 ? "created" : "added" };
|
|
5627
|
-
const
|
|
5628
|
-
if (
|
|
5629
|
-
|
|
5630
|
-
const closeAt = text.indexOf(close, open.index);
|
|
5631
|
-
if (closeAt === -1) return { text, result: "exists" };
|
|
5632
|
-
const end2 = closeAt + close.length;
|
|
5918
|
+
const found = findBlock(text, name);
|
|
5919
|
+
if (found) {
|
|
5920
|
+
if (found.end === void 0) return { text, result: "exists" };
|
|
5633
5921
|
const crlf = text.includes("\r\n");
|
|
5634
5922
|
const block = snippet.trimEnd();
|
|
5635
|
-
if (text.slice(
|
|
5636
|
-
return { text: text.slice(0,
|
|
5923
|
+
if (text.slice(found.start, found.end).replace(/\r\n/g, "\n") === block) return { text, result: "exists" };
|
|
5924
|
+
return { text: text.slice(0, found.start) + (crlf ? block.replace(/\n/g, "\r\n") : block) + text.slice(found.end), result: "updated" };
|
|
5637
5925
|
}
|
|
5638
5926
|
const sep = text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
|
|
5639
5927
|
return { text: `${text}${sep}${snippet}`, result: "added" };
|
|
@@ -5648,30 +5936,36 @@ function globalInstructionFiles(home, env = {}) {
|
|
|
5648
5936
|
{ id: "gemini", agent: "Gemini CLI / Antigravity", dir: gemini, file: path15.join(gemini, "GEMINI.md") }
|
|
5649
5937
|
];
|
|
5650
5938
|
}
|
|
5651
|
-
|
|
5939
|
+
function withoutBlock(text, name) {
|
|
5940
|
+
const found = findBlock(text, name);
|
|
5941
|
+
if (!found || found.end === void 0) return void 0;
|
|
5942
|
+
const nl = text.includes("\r\n") ? "\r\n" : "\n";
|
|
5943
|
+
const before = trimTrailingNewlines(text.slice(0, found.start));
|
|
5944
|
+
const after = trimLeadingNewlines(text.slice(found.end));
|
|
5945
|
+
if (!before) return after;
|
|
5946
|
+
if (!after) return `${before}${nl}`;
|
|
5947
|
+
return `${before}${nl}${nl}${after}`;
|
|
5948
|
+
}
|
|
5652
5949
|
async function removeGlobalPlanRule(home, env = {}) {
|
|
5653
5950
|
const changed = [];
|
|
5654
5951
|
for (const target of globalInstructionFiles(home, env)) {
|
|
5655
5952
|
let text;
|
|
5656
5953
|
try {
|
|
5657
|
-
text = await
|
|
5954
|
+
text = await fsp9.readFile(target.file, "utf8");
|
|
5658
5955
|
} catch {
|
|
5659
5956
|
continue;
|
|
5660
5957
|
}
|
|
5661
|
-
const
|
|
5662
|
-
if (
|
|
5663
|
-
|
|
5664
|
-
|
|
5665
|
-
const next = (text.slice(0, start).replace(/\n+$/, "\n") + text.slice(end2).replace(/^\n+/, "")).replace(/^\n+$/, "");
|
|
5666
|
-
if (next.trim() === "") await fsp7.unlink(target.file);
|
|
5667
|
-
else await fsp7.writeFile(target.file, next);
|
|
5958
|
+
const next = withoutBlock(text, "plan-rule");
|
|
5959
|
+
if (next === void 0) continue;
|
|
5960
|
+
if (next.trim() === "") await fsp9.unlink(target.file);
|
|
5961
|
+
else await writeFileSafely(target.file, next);
|
|
5668
5962
|
changed.push(target.file);
|
|
5669
5963
|
}
|
|
5670
5964
|
return changed;
|
|
5671
5965
|
}
|
|
5672
5966
|
async function readOptional(file) {
|
|
5673
5967
|
try {
|
|
5674
|
-
return await
|
|
5968
|
+
return await fsp9.readFile(file, "utf8");
|
|
5675
5969
|
} catch {
|
|
5676
5970
|
return void 0;
|
|
5677
5971
|
}
|
|
@@ -5681,13 +5975,13 @@ async function addGlobalPlanRule(home, env = {}, only) {
|
|
|
5681
5975
|
for (const target of globalInstructionFiles(home, env)) {
|
|
5682
5976
|
if (only && !only.includes(target.id)) continue;
|
|
5683
5977
|
try {
|
|
5684
|
-
const st = await
|
|
5978
|
+
const st = await fsp9.stat(target.dir);
|
|
5685
5979
|
if (!st.isDirectory()) continue;
|
|
5686
5980
|
} catch {
|
|
5687
5981
|
continue;
|
|
5688
5982
|
}
|
|
5689
5983
|
const next = withBlock(await readOptional(target.file), "plan-rule", planRuleSnippet());
|
|
5690
|
-
if (next.result !== "exists") await
|
|
5984
|
+
if (next.result !== "exists") await writeFileSafely(target.file, next.text);
|
|
5691
5985
|
out.push({ agent: target.agent, file: target.file, result: next.result });
|
|
5692
5986
|
}
|
|
5693
5987
|
return out;
|
|
@@ -5696,7 +5990,7 @@ async function addProgressProtocol(root) {
|
|
|
5696
5990
|
const file = path15.join(root, "AGENTS.md");
|
|
5697
5991
|
const current = await readOptional(file);
|
|
5698
5992
|
const next = withBlock(current ?? "# AGENTS.md\n\n", "progress-protocol", progressProtocolSnippet());
|
|
5699
|
-
if (next.result !== "exists") await
|
|
5993
|
+
if (next.result !== "exists") await writeFileSafely(file, next.text);
|
|
5700
5994
|
return { file, result: current === void 0 ? "created" : next.result };
|
|
5701
5995
|
}
|
|
5702
5996
|
|
|
@@ -5719,11 +6013,11 @@ function claudeHookReply(ev, session, pluginRuns = false) {
|
|
|
5719
6013
|
}
|
|
5720
6014
|
|
|
5721
6015
|
// ../core/src/setup.ts
|
|
5722
|
-
import { promises as
|
|
6016
|
+
import { promises as fsp10 } from "node:fs";
|
|
5723
6017
|
import path17 from "node:path";
|
|
5724
6018
|
async function isDir(p2) {
|
|
5725
6019
|
try {
|
|
5726
|
-
return (await
|
|
6020
|
+
return (await fsp10.stat(p2)).isDirectory();
|
|
5727
6021
|
} catch {
|
|
5728
6022
|
return false;
|
|
5729
6023
|
}
|
|
@@ -5793,8 +6087,8 @@ async function removeSetup(home, env = {}, opts = {}) {
|
|
|
5793
6087
|
}
|
|
5794
6088
|
|
|
5795
6089
|
// ../core/src/phone.ts
|
|
5796
|
-
import { randomBytes } from "node:crypto";
|
|
5797
|
-
import { promises as
|
|
6090
|
+
import { randomBytes as randomBytes2, randomInt } from "node:crypto";
|
|
6091
|
+
import { promises as fsp11 } from "node:fs";
|
|
5798
6092
|
import path18 from "node:path";
|
|
5799
6093
|
var PHONE_EVENTS = ["needs-you", "done", "steps", "actions", "error", "stuck", "limits"];
|
|
5800
6094
|
var DEFAULT_PHONE_EVENTS = ["needs-you", "done", "error", "stuck", "steps", "limits"];
|
|
@@ -5843,7 +6137,7 @@ function normalizePhoneConfig(raw) {
|
|
|
5843
6137
|
}
|
|
5844
6138
|
async function readPhoneConfig(home) {
|
|
5845
6139
|
try {
|
|
5846
|
-
const all = JSON.parse(await
|
|
6140
|
+
const all = JSON.parse(await fsp11.readFile(kvaliConfigFile(home), "utf8"));
|
|
5847
6141
|
return normalizePhoneConfig(all?.phone);
|
|
5848
6142
|
} catch {
|
|
5849
6143
|
return void 0;
|
|
@@ -5853,7 +6147,7 @@ async function writePhoneConfig(home, cfg) {
|
|
|
5853
6147
|
const file = kvaliConfigFile(home);
|
|
5854
6148
|
let all = {};
|
|
5855
6149
|
try {
|
|
5856
|
-
const parsed = JSON.parse(await
|
|
6150
|
+
const parsed = JSON.parse(await fsp11.readFile(file, "utf8"));
|
|
5857
6151
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) all = parsed;
|
|
5858
6152
|
} catch {
|
|
5859
6153
|
}
|
|
@@ -5870,15 +6164,19 @@ async function writePhoneConfig(home, cfg) {
|
|
|
5870
6164
|
doneAfter: cfg.doneAfterSec ?? DEFAULT_DONE_AFTER_SEC
|
|
5871
6165
|
};
|
|
5872
6166
|
else delete all.phone;
|
|
5873
|
-
await
|
|
5874
|
-
await
|
|
5875
|
-
`,
|
|
5876
|
-
|
|
6167
|
+
await fsp11.mkdir(path18.dirname(file), { recursive: true, mode: 448 });
|
|
6168
|
+
await writeFileSafely(file, `${JSON.stringify(all, null, 2)}
|
|
6169
|
+
`, 384);
|
|
6170
|
+
}
|
|
6171
|
+
async function secureKvaliHome(home, create = false) {
|
|
6172
|
+
const dir = path18.dirname(kvaliConfigFile(home));
|
|
6173
|
+
if (create) await fsp11.mkdir(dir, { recursive: true, mode: 448 }).catch(() => void 0);
|
|
6174
|
+
await fsp11.chmod(dir, 448).catch(() => void 0);
|
|
5877
6175
|
}
|
|
5878
6176
|
function newTopic() {
|
|
5879
6177
|
const alphabet = "abcdefghijkmnpqrstuvwxyz23456789";
|
|
5880
6178
|
let s = "";
|
|
5881
|
-
for (const b of
|
|
6179
|
+
for (const b of randomBytes2(16)) s += alphabet[b % 32];
|
|
5882
6180
|
return `kvali-${s}`;
|
|
5883
6181
|
}
|
|
5884
6182
|
function newPhoneConfig(server = DEFAULT_NTFY_SERVER) {
|
|
@@ -6073,8 +6371,22 @@ async function telegramBot(token, fetchImpl = fetch) {
|
|
|
6073
6371
|
return { ok: false, error: unreachable(err, "api.telegram.org") };
|
|
6074
6372
|
}
|
|
6075
6373
|
}
|
|
6076
|
-
|
|
6374
|
+
function telegramPairCode() {
|
|
6375
|
+
return String(randomInt(1e5, 1e6));
|
|
6376
|
+
}
|
|
6377
|
+
function telegramStartLink(bot, code) {
|
|
6378
|
+
return `https://t.me/${encodeURIComponent(bot)}?start=${code}`;
|
|
6379
|
+
}
|
|
6380
|
+
function chatName(c) {
|
|
6381
|
+
const full = [c.first_name, c.last_name].filter((x) => typeof x === "string" && !!x).join(" ");
|
|
6382
|
+
const user = typeof c.username === "string" && c.username ? `@${c.username}` : void 0;
|
|
6383
|
+
const name = full && user ? `${full} (${user})` : full || user;
|
|
6384
|
+
return name ? cleanText(name, 80) : void 0;
|
|
6385
|
+
}
|
|
6386
|
+
async function telegramFindChat(token, code, waitMs = 12e4, fetchImpl = fetch, signal) {
|
|
6387
|
+
if (!/^\d{6}$/.test(code)) return void 0;
|
|
6077
6388
|
const until = Date.now() + waitMs;
|
|
6389
|
+
const hasCode = new RegExp(`(^|\\D)${code}(\\D|$)`);
|
|
6078
6390
|
let offset;
|
|
6079
6391
|
while (Date.now() < until && !signal?.aborted) {
|
|
6080
6392
|
const timeout = Math.max(1, Math.min(25, Math.round((until - Date.now()) / 1e3)));
|
|
@@ -6085,16 +6397,18 @@ async function telegramFindChat(token, waitMs = 12e4, fetchImpl = fetch, signal)
|
|
|
6085
6397
|
signal: AbortSignal.timeout((timeout + 10) * 1e3)
|
|
6086
6398
|
});
|
|
6087
6399
|
if (!res.ok) return void 0;
|
|
6088
|
-
|
|
6400
|
+
const result = (await res.json()).result;
|
|
6401
|
+
updates = Array.isArray(result) ? result.filter((u) => typeof u?.update_id === "number") : [];
|
|
6089
6402
|
} catch {
|
|
6090
6403
|
await new Promise((r) => setTimeout(r, 2e3));
|
|
6091
6404
|
continue;
|
|
6092
6405
|
}
|
|
6093
|
-
const
|
|
6406
|
+
const hit = updates.find((u) => u.message?.chat?.type === "private" && typeof u.message.chat.id === "number" && typeof u.message.text === "string" && hasCode.test(u.message.text));
|
|
6094
6407
|
if (updates.length) offset = updates[updates.length - 1].update_id + 1;
|
|
6095
|
-
if (
|
|
6408
|
+
if (hit) {
|
|
6096
6409
|
await fetchImpl(`https://api.telegram.org/bot${token}/getUpdates?timeout=0&offset=${offset}`, { signal: AbortSignal.timeout(1e4) }).catch(() => void 0);
|
|
6097
|
-
|
|
6410
|
+
const chat = hit.message.chat;
|
|
6411
|
+
return { id: String(chat.id), name: chatName(chat) };
|
|
6098
6412
|
}
|
|
6099
6413
|
if (Date.now() - askedAt < 1e3) await new Promise((r) => setTimeout(r, 1e3));
|
|
6100
6414
|
}
|
|
@@ -6124,8 +6438,34 @@ function clip(text, max) {
|
|
|
6124
6438
|
const one = text.replace(/\s+/g, " ").trim();
|
|
6125
6439
|
return one.length <= max ? one : `${one.slice(0, max - 1).trimEnd()}\u2026`;
|
|
6126
6440
|
}
|
|
6441
|
+
var APPROVAL_KINDS = lookupTable({
|
|
6442
|
+
run: "run a command",
|
|
6443
|
+
bash: "run a command",
|
|
6444
|
+
shell: "run a command",
|
|
6445
|
+
command: "run a command",
|
|
6446
|
+
powershell: "run a command",
|
|
6447
|
+
edit: "edit a file",
|
|
6448
|
+
write: "edit a file",
|
|
6449
|
+
patch: "edit a file",
|
|
6450
|
+
read: "read a file",
|
|
6451
|
+
fetch: "open a web page",
|
|
6452
|
+
webfetch: "open a web page"
|
|
6453
|
+
});
|
|
6454
|
+
function phoneStatus(detail) {
|
|
6455
|
+
if (detail === void 0) return void 0;
|
|
6456
|
+
const m = /^Needs approval:[ \t]*([A-Za-z][\w-]{0,40})?/.exec(detail);
|
|
6457
|
+
if (!m) return detail;
|
|
6458
|
+
const word = m[1];
|
|
6459
|
+
if (!word) return "Needs approval";
|
|
6460
|
+
return `Needs approval: ${APPROVAL_KINDS[word] ?? word}`;
|
|
6461
|
+
}
|
|
6462
|
+
function pushAgentLabel(s) {
|
|
6463
|
+
if (s.agent !== "progress-file") return s.agentLabel;
|
|
6464
|
+
const name = s.agentLabel.trim();
|
|
6465
|
+
return /^[\p{L}\p{N}][\p{L}\p{N} +_-]{0,23}$/u.test(name) && name.split(/\s+/).length <= 3 ? name : "An agent";
|
|
6466
|
+
}
|
|
6127
6467
|
function formatPush(kind, s, details, extra = {}) {
|
|
6128
|
-
const agent = s
|
|
6468
|
+
const agent = pushAgentLabel(s);
|
|
6129
6469
|
const where = details ? ` \xB7 ${projectName(s.projectPath)}` : "";
|
|
6130
6470
|
const p2 = progressOf(s.tasks);
|
|
6131
6471
|
const step = currentTask(s.tasks);
|
|
@@ -6139,7 +6479,8 @@ function formatPush(kind, s, details, extra = {}) {
|
|
|
6139
6479
|
return {
|
|
6140
6480
|
event: "needs-you",
|
|
6141
6481
|
title: `${agent} needs you${where}`,
|
|
6142
|
-
|
|
6482
|
+
// A progress file's note is a repository's words, not an agent's question: it stays on the computer.
|
|
6483
|
+
message: lines(details && s.agent !== "progress-file" ? clip(phoneStatus(s.statusDetail) ?? "Waiting for your answer", 200) : "Waiting for your answer", title, planLine),
|
|
6143
6484
|
priority: 4,
|
|
6144
6485
|
tags: ["bell"]
|
|
6145
6486
|
};
|
|
@@ -6185,7 +6526,7 @@ function formatPush(kind, s, details, extra = {}) {
|
|
|
6185
6526
|
}
|
|
6186
6527
|
case "loop": {
|
|
6187
6528
|
const l = s.loop;
|
|
6188
|
-
const what = l ? details ? `\u201C${clip(l.
|
|
6529
|
+
const what = l ? details ? `\u201C${clip(l.label, 80)}\u201D` : "The same action" : "An action";
|
|
6189
6530
|
const facts = l ? [`failed ${l.count} times in a row${l.sameError ? " with the same error" : ""}`, `for ${fmtDuration((extra.now ?? Date.now()) - l.since)}`, l.tokens ? `${fmtTokens(l.tokens)} tokens` : void 0] : ["keeps failing"];
|
|
6190
6531
|
return {
|
|
6191
6532
|
event: "stuck",
|
|
@@ -6445,7 +6786,7 @@ var PhoneNotifier = class {
|
|
|
6445
6786
|
const now = Date.now();
|
|
6446
6787
|
if (!force && now - this.checkedAt < 5e3) return;
|
|
6447
6788
|
this.checkedAt = now;
|
|
6448
|
-
const st = await
|
|
6789
|
+
const st = await fsp11.stat(kvaliConfigFile(this.opts.home)).catch(() => void 0);
|
|
6449
6790
|
const mtime = st?.mtimeMs ?? 0;
|
|
6450
6791
|
if (!force && mtime === this.mtime) return;
|
|
6451
6792
|
this.mtime = mtime;
|
|
@@ -8185,7 +8526,7 @@ function qrTerminal(text, color = true) {
|
|
|
8185
8526
|
}
|
|
8186
8527
|
|
|
8187
8528
|
// src/index.ts
|
|
8188
|
-
var VERSION = "0.7.
|
|
8529
|
+
var VERSION = "0.7.2";
|
|
8189
8530
|
function parse(argv) {
|
|
8190
8531
|
const opts = {
|
|
8191
8532
|
json: false,
|
|
@@ -8223,18 +8564,24 @@ function parse(argv) {
|
|
|
8223
8564
|
case "--here":
|
|
8224
8565
|
opts.project = process2.cwd();
|
|
8225
8566
|
break;
|
|
8226
|
-
case "--window":
|
|
8227
|
-
|
|
8567
|
+
case "--window": {
|
|
8568
|
+
const hours = Number(next());
|
|
8569
|
+
if (!Number.isFinite(hours) || hours <= 0 || hours > 24 * 365) fail("--window takes a number of hours, e.g. 24");
|
|
8570
|
+
opts.windowHours = hours;
|
|
8228
8571
|
break;
|
|
8572
|
+
}
|
|
8229
8573
|
case "--home":
|
|
8230
8574
|
opts.home = path19.resolve(next());
|
|
8231
8575
|
break;
|
|
8232
8576
|
case "--brain-dir":
|
|
8233
8577
|
opts.brainDirs.push(path19.resolve(next()));
|
|
8234
8578
|
break;
|
|
8235
|
-
case "--port":
|
|
8236
|
-
|
|
8579
|
+
case "--port": {
|
|
8580
|
+
const port = Number(next());
|
|
8581
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) fail("--port takes a port number from 1 to 65535");
|
|
8582
|
+
opts.port = port;
|
|
8237
8583
|
break;
|
|
8584
|
+
}
|
|
8238
8585
|
case "--no-hub":
|
|
8239
8586
|
opts.hub = false;
|
|
8240
8587
|
break;
|
|
@@ -8500,6 +8847,7 @@ async function week(opts, svgFile) {
|
|
|
8500
8847
|
);
|
|
8501
8848
|
if (svgFile !== void 0) {
|
|
8502
8849
|
const file = path19.resolve(svgFile || `kvali-week-${w.days[w.days.length - 1].day}.svg`);
|
|
8850
|
+
if ((await lstat(file).catch(() => void 0))?.isSymbolicLink()) fail(`${file} is a symbolic link; give the card another file name`);
|
|
8503
8851
|
await writeFile(file, weekSvg(w));
|
|
8504
8852
|
console.log(`
|
|
8505
8853
|
Card: ${file} ${c.gray("(1200\xD7630 SVG; open it in a browser to save as PNG)")}`);
|
|
@@ -8588,10 +8936,12 @@ async function phoneChannel(which, off, opts) {
|
|
|
8588
8936
|
const token = await askSecret(" Token: ");
|
|
8589
8937
|
const me = await telegramBot(token);
|
|
8590
8938
|
if (!me.ok) fail(`could not use this bot: ${me.error}`);
|
|
8591
|
-
|
|
8592
|
-
|
|
8593
|
-
|
|
8594
|
-
|
|
8939
|
+
const code = telegramPairCode();
|
|
8940
|
+
console.log(` 3. Open ${telegramStartLink(me.username, code)} and press Start, or send @${me.username} the code ${c.bold(code)}. Waiting up to 3 minutes\u2026`);
|
|
8941
|
+
const chat = await telegramFindChat(token, code, 18e4);
|
|
8942
|
+
if (!chat) fail(`the code did not reach @${me.username}; run \`kvali phone telegram\` again and send it while Kvali waits`);
|
|
8943
|
+
console.log(` Kvali will write to ${c.bold(chat.name ?? "this Telegram chat")} through @${me.username}.`);
|
|
8944
|
+
only = { telegram: { token, chatId: chat.id, bot: me.username } };
|
|
8595
8945
|
} else {
|
|
8596
8946
|
console.log([c.bold("Kvali \u2192 Discord"), "", " In Discord: Edit Channel \u2192 Integrations \u2192 Webhooks \u2192 New Webhook \u2192 Copy Webhook URL.", " Paste it here (it stays on this computer):"].join("\n"));
|
|
8597
8947
|
const webhook = await askSecret(" Webhook URL: ");
|
|
@@ -8663,6 +9013,7 @@ async function phone(sub, opts, arg) {
|
|
|
8663
9013
|
}
|
|
8664
9014
|
async function main() {
|
|
8665
9015
|
const { cmd, opts } = parse(process2.argv.slice(2));
|
|
9016
|
+
await secureKvaliHome(opts.home);
|
|
8666
9017
|
if (cmd[0] === "hooks") return hooks(cmd[1], opts);
|
|
8667
9018
|
if (cmd[0] === "setup") {
|
|
8668
9019
|
if (cmd[1] === "off") {
|