@kvali/cli 0.7.0 → 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
- /** Adds a reading taken at `at`. Older readings than the window's latest are ignored. */
200
- add(reading, at) {
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
- const pct = Math.max(0, reading.usedPercent);
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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
433
+ var esc = (t) => cleanText(t, 300).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
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 globToRegExp(glob) {
441
- const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
442
- return new RegExp(`^${escaped}$`, "i");
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 = Object.entries(customPrices).filter(([, v]) => v && typeof v.input === "number" && typeof v.output === "number").map(([k, v]) => ({
448
- re: globToRegExp(k),
449
- price: { cacheRead: 0, ...v }
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.re.test(model)) return { price: c.price, key: model };
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 carry = Buffer.alloc(0);
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 = carry.length ? Buffer.concat([carry, chunk.subarray(0, bytesRead)]) : chunk.subarray(0, bytesRead);
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
- onRecord(record);
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.offset = pos - carry.length;
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 res = await t.tail.read(
575
- (record) => this.onRecord(t.state, record, ctx),
576
- () => {
577
- t.state = this.createState(p2);
578
- }
579
- );
580
- await this.afterRead(t.state, ctx, res.changed);
581
- const s = this.toSession(t.state, ctx);
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 = /^(\s*)(?:[-*+]|\d+[.)])\s+\[([ xX/\-~>!?])\]\s+(.+?)\s*$/;
603
- var HEADING_RE = /^(#{1,6})\s+(.+?)\s*#*\s*$/;
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 m = /^\s*([A-Za-z0-9_-]+)\s*:\s*(.*?)\s*$/.exec(line);
623
- if (m) frontmatter[m[1].toLowerCase()] = m[2].replace(/^["']|["']$/g, "");
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
- const line = raw.replace(/\r$/, "");
634
- if (/^\s*(```|~~~)/.test(line)) {
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 = HEADING_RE.exec(line);
834
+ const h = heading(line);
640
835
  if (h) {
641
- const text = h[2].trim();
642
- if (h[1].length === 1 && title === void 0) title = text;
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.tail.read(
965
- (rec) => this.onStep(st, rec, ctx),
966
- () => {
967
- Object.assign(st, this.blank(st.id, st.dir), { tail: st.tail });
968
- }
969
- );
970
- await this.readTask(st);
971
- const s = this.toSession(st, ctx);
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?.replace(/\s*[—–-]\s*Task Tracker\s*$/i, "").trim() || void 0,
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
- const res = await entry.tail.read(
1356
- (rec) => this.onRecord(entry.state, rec, ctx, false),
1357
- () => {
1358
- entry.state = this.createState(entry.state.file);
1359
- }
1360
- );
1361
- await this.readSideFiles(entry.state, ctx, res.changed);
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
- return cmd.replace(/\s*REQ_APP\s*$/, "");
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.refresh(t, ctx);
2327
- if (!t.fold) continue;
2328
- const s = this.toSession(t, ctx);
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 this.refresh(t);
2743
- const s = this.toSession(t, ctx, label);
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(/^(\s*(?:[-*+]|\d+[.)])\s*)\[[-~]\]/gm, "$1[/]")).tasks;
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
- files.push({ file: path10.join(agentsDir, "progress.md"), root });
4849
- for (const f of await listDir(path10.join(agentsDir, "progress"))) {
4850
- if (f.isFile() && f.name.endsWith(".md")) files.push({ file: path10.join(agentsDir, "progress", f.name), root });
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.includes(short) || name.includes(label)) && sameProject(n.projectPath, pf.projectPath);
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
- log: opts.log ?? (() => {
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
- await this.tick();
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, limits]);
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, ...limits.length ? { limits } : {} };
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 fsp4 } from "node:fs";
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]) || !type.includes("application/json")) {
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,316 +5475,78 @@ var HookHub = class {
5207
5475
  }
5208
5476
  async store(agent, ev) {
5209
5477
  const dir = path12.join(this.opts.liveDir, agent);
5210
- await fsp4.mkdir(dir, { recursive: true });
5211
- const file = path12.join(dir, `${ev.sessionId}.json`);
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 fsp5 } from "node:fs";
5484
+ import { promises as fsp8 } from "node:fs";
5220
5485
  import os2 from "node:os";
5486
+ import path14 from "node:path";
5487
+
5488
+ // ../core/src/hooks/claude-plugin.ts
5489
+ import { execFile } from "node:child_process";
5490
+ import { createHash } from "node:crypto";
5491
+ import { constants as fsc, promises as fsp7 } from "node:fs";
5221
5492
  import path13 from "node:path";
5222
- var CLAUDE_HOOKS = [
5223
- { event: "UserPromptSubmit", sync: true },
5224
- { event: "Notification", sync: false },
5225
- { event: "Stop", sync: false },
5226
- { event: "SessionEnd", sync: false }
5227
- ];
5228
- var CLAUDE_HOOK_EVENTS = CLAUDE_HOOKS.map((h) => h.event);
5229
- var MARKER = "/v1/events/claude-code";
5230
- function claudeSettingsPath(home = os2.homedir(), env = process.env) {
5231
- const dir = env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim() || path13.join(home, ".claude");
5232
- return path13.join(dir, "settings.json");
5233
- }
5234
- function claudeHookCommand(port = DEFAULT_HOOK_PORT, sync = false) {
5235
- const url = `http://127.0.0.1:${port}${MARKER}`;
5236
- return sync ? `curl -s --noproxy '*' -m 1 --connect-timeout 0.3 -H 'Content-Type: application/json' --data-binary @- ${url} || true` : `curl -s --noproxy '*' -m 2 -o /dev/null -H 'Content-Type: application/json' --data-binary @- ${url} || true`;
5237
- }
5238
- function hookEntry(spec, port) {
5239
- return spec.sync ? { type: "command", command: claudeHookCommand(port, true), timeout: 3 } : { type: "command", command: claudeHookCommand(port, false), async: true, timeout: 5 };
5240
- }
5241
- async function readSettings(file) {
5242
- let text;
5493
+ var CLAUDE_PLUGIN_ID = "kvali@kvali";
5494
+ var CLAUDE_MARKETPLACE = "kvali";
5495
+ var kvaliPluginDir = (home) => path13.join(home, ".kvali", "claude-plugin");
5496
+ var stateFile = (home) => path13.join(home, ".kvali", "state.json");
5497
+ async function filesUnder(dir, base = dir) {
5498
+ const out = [];
5499
+ let entries;
5243
5500
  try {
5244
- text = await fsp5.readFile(file, "utf8");
5245
- } catch (err) {
5246
- if (err.code === "ENOENT") return {};
5247
- throw err;
5501
+ entries = await fsp7.readdir(dir, { withFileTypes: true });
5502
+ } catch {
5503
+ return out;
5248
5504
  }
5249
- if (!text.trim()) return {};
5250
- try {
5251
- const v = JSON.parse(text);
5252
- if (!v || typeof v !== "object" || Array.isArray(v)) throw new Error("not an object");
5253
- return v;
5254
- } catch (err) {
5255
- throw new Error(`${file} is not valid JSON (${err.message}). Fix it first; Kvali will not overwrite it.`);
5505
+ for (const e of entries) {
5506
+ const full = path13.join(dir, e.name);
5507
+ if (e.isDirectory()) {
5508
+ if (path13.relative(base, full) === path13.join(".claude-plugin", "types")) continue;
5509
+ out.push(...await filesUnder(full, base));
5510
+ } else if (e.isFile()) out.push(path13.relative(base, full));
5256
5511
  }
5512
+ return out.sort();
5257
5513
  }
5258
- function isKvaliGroup(group) {
5259
- return Array.isArray(group?.hooks) && group.hooks.some((h) => typeof h?.command === "string" && h.command.includes(MARKER));
5260
- }
5261
- function withoutKvali(settings) {
5262
- const next = { ...settings };
5263
- if (!next.hooks || typeof next.hooks !== "object") return next;
5264
- const hooks2 = {};
5265
- for (const [event, groups] of Object.entries(next.hooks)) {
5266
- if (!Array.isArray(groups)) {
5267
- hooks2[event] = groups;
5268
- continue;
5269
- }
5270
- const kept = groups.filter((g) => !isKvaliGroup(g));
5271
- if (kept.length) hooks2[event] = kept;
5514
+ async function pluginFingerprint(dir) {
5515
+ const files = await filesUnder(dir);
5516
+ if (!files.length) return void 0;
5517
+ const h = createHash("sha256");
5518
+ for (const f of files) {
5519
+ h.update(f.split(path13.sep).join("/"));
5520
+ h.update("\0");
5521
+ h.update(await fsp7.readFile(path13.join(dir, f)));
5522
+ h.update("\0");
5272
5523
  }
5273
- if (Object.keys(hooks2).length) next.hooks = hooks2;
5274
- else delete next.hooks;
5275
- return next;
5524
+ return h.digest("hex");
5276
5525
  }
5277
- async function claudeHooksStatus(file = claudeSettingsPath(), port = DEFAULT_HOOK_PORT) {
5278
- let settings;
5526
+ async function pluginVersion(dir) {
5279
5527
  try {
5280
- settings = await readSettings(file);
5281
- } catch {
5282
- return "not-installed";
5283
- }
5284
- let found = 0;
5285
- let current = 0;
5286
- let total = 0;
5287
- for (const groups of Object.values(settings.hooks ?? {})) if (Array.isArray(groups)) total += groups.filter(isKvaliGroup).length;
5288
- for (const spec of CLAUDE_HOOKS) {
5289
- const groups = settings.hooks?.[spec.event];
5290
- if (!Array.isArray(groups)) continue;
5291
- const g = groups.find(isKvaliGroup);
5292
- if (!g) continue;
5293
- found += 1;
5294
- const want = hookEntry(spec, port);
5295
- if (g.hooks.some((h) => h.command === want.command && h.async === true === (want.async === true))) current += 1;
5296
- }
5297
- if (found === 0 && total === 0) return "not-installed";
5298
- return current === CLAUDE_HOOKS.length && total === CLAUDE_HOOKS.length ? "installed" : "outdated";
5299
- }
5300
- async function writeWithBackup(file, before, settings) {
5301
- await fsp5.mkdir(path13.dirname(file), { recursive: true });
5302
- let backup;
5303
- if (before !== void 0) {
5304
- backup = `${file}.kvali-backup`;
5305
- await fsp5.writeFile(backup, before);
5306
- }
5307
- await fsp5.writeFile(file, JSON.stringify(settings, null, 2) + "\n");
5308
- return backup;
5309
- }
5310
- function canonical(v) {
5311
- return JSON.stringify(
5312
- v,
5313
- (_k, x) => x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, x[k]])) : x
5314
- );
5315
- }
5316
- async function installClaudeHooks(file = claudeSettingsPath(), port = DEFAULT_HOOK_PORT) {
5317
- const before = await fsp5.readFile(file, "utf8").catch(() => void 0);
5318
- const current = await readSettings(file);
5319
- const settings = withoutKvali(current);
5320
- settings.hooks = settings.hooks && typeof settings.hooks === "object" ? settings.hooks : {};
5321
- for (const spec of CLAUDE_HOOKS) {
5322
- const groups = Array.isArray(settings.hooks[spec.event]) ? settings.hooks[spec.event] : [];
5323
- settings.hooks[spec.event] = [...groups, { hooks: [hookEntry(spec, port)] }];
5324
- }
5325
- if (before !== void 0 && canonical(settings) === canonical(current)) return { changed: false };
5326
- return { backup: await writeWithBackup(file, before, settings), changed: true };
5327
- }
5328
- async function uninstallClaudeHooks(file = claudeSettingsPath()) {
5329
- const before = await fsp5.readFile(file, "utf8").catch(() => void 0);
5330
- if (before === void 0) return { changed: false };
5331
- const settings = await readSettings(file);
5332
- const next = withoutKvali(settings);
5333
- if (JSON.stringify(next) === JSON.stringify(settings)) return { changed: false };
5334
- return { backup: await writeWithBackup(file, before, next), changed: true };
5335
- }
5336
-
5337
- // ../core/src/protocol.ts
5338
- import { promises as fsp6 } from "node:fs";
5339
- import path14 from "node:path";
5340
- var PROGRESS_PROTOCOL_MARKER = "<!-- kvali:progress-protocol v2 -->";
5341
- function progressProtocolSnippet() {
5342
- return `${PROGRESS_PROTOCOL_MARKER}
5343
- ## Progress reporting
5344
-
5345
- For any task that takes more than two steps, keep your plan visible so the user can follow progress without asking:
5346
-
5347
- - If you have a built-in plan or todo tool (Claude Code Tasks/TodoWrite, Codex \`update_plan\`, Gemini CLI \`write_todos\`, Antigravity \`task.md\`), create the plan with it before you start, update it as you go, and do not create \`.agents/progress.md\`.
5348
- - Only agents without such a tool maintain \`.agents/progress.md\`, in this format:
5349
-
5350
- \`\`\`md
5351
- ---
5352
- agent: <your name, e.g. Cursor>
5353
- status: working # working | waiting | done | error
5354
- ---
5355
- # <short task title>
5356
- - [x] a finished step
5357
- - [/] the step you are working on now
5358
- - [ ] a next step
5359
- \`\`\`
5360
-
5361
- - Keep exactly one step marked \`[/]\`. Update the file right after each step, set \`status: waiting\` when you need input from the user, and \`status: done\` when everything is finished.
5362
- <!-- /kvali:progress-protocol -->
5363
- `;
5364
- }
5365
- var PLAN_RULE_MARKER = "<!-- kvali:plan-rule v2 -->";
5366
- function planRuleSnippet() {
5367
- return `${PLAN_RULE_MARKER}
5368
- ## Keep a visible plan
5369
-
5370
- For any task that takes more than two steps, create a task list with your built-in plan tool before you start (Claude Code: TaskCreate/TaskUpdate or TodoWrite, whichever it has, loaded with ToolSearch when not in your tool list; Codex: update_plan; Gemini CLI: write_todos; Antigravity: task.md), keep exactly one item in progress, and mark each item done as soon as it is finished. The user follows your progress from this list.
5371
- <!-- /kvali:plan-rule -->
5372
- `;
5373
- }
5374
- function withBlock(text, name, snippet) {
5375
- if (text === void 0 || text === "") return { text: snippet, result: text === void 0 ? "created" : "added" };
5376
- const open = new RegExp(`<!-- kvali:${name} v\\d+ -->`).exec(text);
5377
- if (open) {
5378
- const close = `<!-- /kvali:${name} -->`;
5379
- const closeAt = text.indexOf(close, open.index);
5380
- if (closeAt === -1) return { text, result: "exists" };
5381
- const end2 = closeAt + close.length;
5382
- const crlf = text.includes("\r\n");
5383
- const block = snippet.trimEnd();
5384
- if (text.slice(open.index, end2).replace(/\r\n/g, "\n") === block) return { text, result: "exists" };
5385
- return { text: text.slice(0, open.index) + (crlf ? block.replace(/\n/g, "\r\n") : block) + text.slice(end2), result: "updated" };
5386
- }
5387
- const sep = text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
5388
- return { text: `${text}${sep}${snippet}`, result: "added" };
5389
- }
5390
- function globalInstructionFiles(home, env = {}) {
5391
- const claude = env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim() || path14.join(home, ".claude");
5392
- const codex = env.CODEX_HOME || path14.join(home, ".codex");
5393
- const gemini = path14.join(home, ".gemini");
5394
- return [
5395
- { id: "claude-code", agent: "Claude Code", dir: claude, file: path14.join(claude, "CLAUDE.md") },
5396
- { id: "codex", agent: "Codex", dir: codex, file: path14.join(codex, "AGENTS.md") },
5397
- { id: "gemini", agent: "Gemini CLI / Antigravity", dir: gemini, file: path14.join(gemini, "GEMINI.md") }
5398
- ];
5399
- }
5400
- var PLAN_RULE_END = "<!-- /kvali:plan-rule -->";
5401
- async function removeGlobalPlanRule(home, env = {}) {
5402
- const changed = [];
5403
- for (const target of globalInstructionFiles(home, env)) {
5404
- let text;
5405
- try {
5406
- text = await fsp6.readFile(target.file, "utf8");
5407
- } catch {
5408
- continue;
5409
- }
5410
- const start = text.search(/<!-- kvali:plan-rule v\d+ -->/);
5411
- if (start === -1) continue;
5412
- const endAt = text.indexOf(PLAN_RULE_END, start);
5413
- const end2 = endAt === -1 ? text.length : endAt + PLAN_RULE_END.length;
5414
- const next = (text.slice(0, start).replace(/\n+$/, "\n") + text.slice(end2).replace(/^\n+/, "")).replace(/^\n+$/, "");
5415
- if (next.trim() === "") await fsp6.unlink(target.file);
5416
- else await fsp6.writeFile(target.file, next);
5417
- changed.push(target.file);
5418
- }
5419
- return changed;
5420
- }
5421
- async function readOptional(file) {
5422
- try {
5423
- return await fsp6.readFile(file, "utf8");
5528
+ const v = JSON.parse(await fsp7.readFile(path13.join(dir, ".claude-plugin", "plugin.json"), "utf8")).version;
5529
+ return typeof v === "string" ? v : void 0;
5424
5530
  } catch {
5425
5531
  return void 0;
5426
5532
  }
5427
5533
  }
5428
- async function addGlobalPlanRule(home, env = {}, only) {
5429
- const out = [];
5430
- for (const target of globalInstructionFiles(home, env)) {
5431
- if (only && !only.includes(target.id)) continue;
5432
- try {
5433
- const st = await fsp6.stat(target.dir);
5434
- if (!st.isDirectory()) continue;
5435
- } catch {
5436
- continue;
5437
- }
5438
- const next = withBlock(await readOptional(target.file), "plan-rule", planRuleSnippet());
5439
- if (next.result !== "exists") await fsp6.writeFile(target.file, next.text);
5440
- out.push({ agent: target.agent, file: target.file, result: next.result });
5441
- }
5442
- return out;
5443
- }
5444
- async function addProgressProtocol(root) {
5445
- const file = path14.join(root, "AGENTS.md");
5446
- const current = await readOptional(file);
5447
- const next = withBlock(current ?? "# AGENTS.md\n\n", "progress-protocol", progressProtocolSnippet());
5448
- if (next.result !== "exists") await fsp6.writeFile(file, next.text);
5449
- return { file, result: current === void 0 ? "created" : next.result };
5450
- }
5451
-
5452
- // ../core/src/hooks/replies.ts
5453
- import { existsSync as existsSync2 } from "node:fs";
5454
- import path15 from "node:path";
5455
- var CLAUDE_PLAN_CONTEXT = "Progress tracking (Kvali): if this request takes more than two steps, start by creating a task list with TaskCreate or TodoWrite, whichever you have (if neither is in your tool list, load one with ToolSearch first), keep exactly one task in_progress, and mark each task completed as soon as it is done. The user follows your progress from that list, so keep it current.";
5456
- function pluginRunsIn(liveDir, sessionId) {
5457
- if (!/^[A-Za-z0-9-]{8,80}$/.test(sessionId)) return false;
5458
- return existsSync2(path15.join(liveDir, "claude-code", `${sessionId}.mod.json`));
5459
- }
5460
- function claudeHookReply(ev, session, pluginRuns = false) {
5461
- if (ev.event !== "UserPromptSubmit") return void 0;
5462
- if (pluginRuns) return void 0;
5463
- if (session) {
5464
- const p2 = progressOf(session.tasks);
5465
- if (p2.total > 0 && p2.done < p2.total) return void 0;
5466
- }
5467
- return { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: CLAUDE_PLAN_CONTEXT } };
5468
- }
5469
-
5470
- // ../core/src/setup.ts
5471
- import { promises as fsp8 } from "node:fs";
5472
- import path17 from "node:path";
5473
-
5474
- // ../core/src/hooks/claude-plugin.ts
5475
- import { execFile } from "node:child_process";
5476
- import { createHash } from "node:crypto";
5477
- import { constants as fsc, promises as fsp7 } from "node:fs";
5478
- import path16 from "node:path";
5479
- var CLAUDE_PLUGIN_ID = "kvali@kvali";
5480
- var CLAUDE_MARKETPLACE = "kvali";
5481
- var kvaliPluginDir = (home) => path16.join(home, ".kvali", "claude-plugin");
5482
- var stateFile = (home) => path16.join(home, ".kvali", "state.json");
5483
- async function filesUnder(dir, base = dir) {
5484
- const out = [];
5485
- let entries;
5486
- try {
5487
- entries = await fsp7.readdir(dir, { withFileTypes: true });
5488
- } catch {
5489
- return out;
5490
- }
5491
- for (const e of entries) {
5492
- const full = path16.join(dir, e.name);
5493
- if (e.isDirectory()) {
5494
- if (path16.relative(base, full) === path16.join(".claude-plugin", "types")) continue;
5495
- out.push(...await filesUnder(full, base));
5496
- } else if (e.isFile()) out.push(path16.relative(base, full));
5497
- }
5498
- return out.sort();
5499
- }
5500
- async function pluginFingerprint(dir) {
5501
- const files = await filesUnder(dir);
5502
- if (!files.length) return void 0;
5503
- const h = createHash("sha256");
5504
- for (const f of files) {
5505
- h.update(f.split(path16.sep).join("/"));
5506
- h.update("\0");
5507
- h.update(await fsp7.readFile(path16.join(dir, f)));
5508
- h.update("\0");
5509
- }
5510
- return h.digest("hex");
5534
+ function compareVersions(a, b) {
5535
+ const parts = (v) => v.split(/[.+-]/).slice(0, 3).map((n) => Number.parseInt(n, 10) || 0);
5536
+ const [x, y] = [parts(a), parts(b)];
5537
+ for (let i = 0; i < 3; i += 1) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) - (y[i] ?? 0);
5538
+ return 0;
5511
5539
  }
5512
5540
  async function syncClaudePlugin(bundledDir, home) {
5513
5541
  const target = kvaliPluginDir(home);
5514
5542
  const [want, have] = await Promise.all([pluginFingerprint(bundledDir), pluginFingerprint(target)]);
5515
5543
  if (!want) throw new Error(`the Claude Code plugin is missing from ${bundledDir}`);
5516
5544
  if (want === have) return false;
5545
+ const [mine, theirs] = await Promise.all([pluginVersion(bundledDir), pluginVersion(target)]);
5546
+ if (mine && theirs && compareVersions(mine, theirs) < 0) return false;
5517
5547
  const next = `${target}.next`;
5518
5548
  await fsp7.rm(next, { recursive: true, force: true });
5519
- await fsp7.mkdir(path16.dirname(target), { recursive: true });
5549
+ await fsp7.mkdir(path13.dirname(target), { recursive: true });
5520
5550
  await fsp7.cp(bundledDir, next, { recursive: true });
5521
5551
  await fsp7.rm(target, { recursive: true, force: true });
5522
5552
  await fsp7.rename(next, target);
@@ -5524,7 +5554,7 @@ async function syncClaudePlugin(bundledDir, home) {
5524
5554
  }
5525
5555
  async function claudeExtensionDirs(home) {
5526
5556
  const roots = [".vscode", ".vscode-insiders", ".vscode-oss", ".cursor", ".windsurf", ".antigravity", ".antigravity-ide", ".kiro"].map(
5527
- (d) => path16.join(home, d, "extensions")
5557
+ (d) => path13.join(home, d, "extensions")
5528
5558
  );
5529
5559
  const found = [];
5530
5560
  for (const root of roots) {
@@ -5534,9 +5564,9 @@ async function claudeExtensionDirs(home) {
5534
5564
  } catch {
5535
5565
  continue;
5536
5566
  }
5537
- for (const n of names) if (n.toLowerCase().startsWith("anthropic.claude-code-")) found.push(path16.join(root, n));
5567
+ for (const n of names) if (n.toLowerCase().startsWith("anthropic.claude-code-")) found.push(path13.join(root, n));
5538
5568
  }
5539
- const ver = (p2) => (/-(\d+)\.(\d+)\.(\d+)/.exec(path16.basename(p2)) ?? []).slice(1).map(Number);
5569
+ const ver = (p2) => (/-(\d+)\.(\d+)\.(\d+)/.exec(path13.basename(p2)) ?? []).slice(1).map(Number);
5540
5570
  return found.sort((a, b) => {
5541
5571
  const [x, y] = [ver(a), ver(b)];
5542
5572
  for (let i = 0; i < 3; i += 1) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (y[i] ?? 0) - (x[i] ?? 0);
@@ -5548,7 +5578,7 @@ async function findClaudeBinary(opts) {
5548
5578
  const names = win ? ["claude.exe", "claude.cmd"] : ["claude"];
5549
5579
  const candidates = [];
5550
5580
  for (const d of opts.extensionDirs ?? []) {
5551
- const bin = path16.join(d, "resources", "native-binary");
5581
+ const bin = path13.join(d, "resources", "native-binary");
5552
5582
  let inside = [];
5553
5583
  try {
5554
5584
  inside = await fsp7.readdir(bin);
@@ -5556,10 +5586,10 @@ async function findClaudeBinary(opts) {
5556
5586
  continue;
5557
5587
  }
5558
5588
  const ranked = inside.filter((n) => /^claude([-.].*)?$/i.test(n) && !/\.(json|md|txt|map)$/i.test(n)).sort((x, y) => x.length - y.length);
5559
- for (const n of ranked) candidates.push(path16.join(bin, n));
5589
+ for (const n of ranked) candidates.push(path13.join(bin, n));
5560
5590
  }
5561
- for (const dir of (opts.env?.PATH ?? opts.env?.Path ?? "").split(path16.delimiter)) if (dir) for (const n of names) candidates.push(path16.join(dir, n));
5562
- candidates.push(path16.join(opts.home, ".claude", "local", names[0]), path16.join(opts.home, ".local", "bin", names[0]));
5591
+ for (const dir of (opts.env?.PATH ?? opts.env?.Path ?? "").split(path13.delimiter)) if (dir) for (const n of names) candidates.push(path13.join(dir, n));
5592
+ candidates.push(path13.join(opts.home, ".claude", "local", names[0]), path13.join(opts.home, ".local", "bin", names[0]));
5563
5593
  if (!win) candidates.push("/opt/homebrew/bin/claude", "/usr/local/bin/claude");
5564
5594
  for (const c of candidates) {
5565
5595
  try {
@@ -5632,8 +5662,8 @@ async function readKvaliState(home) {
5632
5662
  }
5633
5663
  async function writeKvaliState(home, patch) {
5634
5664
  const next = { ...await readKvaliState(home), ...patch };
5635
- await fsp7.mkdir(path16.dirname(stateFile(home)), { recursive: true });
5636
- await fsp7.writeFile(stateFile(home), `${JSON.stringify(next, null, 2)}
5665
+ await fsp7.mkdir(path13.dirname(stateFile(home)), { recursive: true, mode: 448 });
5666
+ await writeFileSafely(stateFile(home), `${JSON.stringify(next, null, 2)}
5637
5667
  `);
5638
5668
  }
5639
5669
  async function removeClaudePlugin(opts) {
@@ -5645,7 +5675,7 @@ async function removeClaudePlugin(opts) {
5645
5675
  const list = await runClaude(opts.bin, ["plugin", "marketplace", "list", "--json"], opts.env);
5646
5676
  try {
5647
5677
  const mk = JSON.parse(list.out.slice(list.out.indexOf("["))).find((m) => m.name === CLAUDE_MARKETPLACE);
5648
- if (mk && mk.path && path16.resolve(mk.path) === path16.resolve(dir)) await runClaude(opts.bin, ["plugin", "marketplace", "remove", CLAUDE_MARKETPLACE], opts.env);
5678
+ if (mk && mk.path && path13.resolve(mk.path) === path13.resolve(dir)) await runClaude(opts.bin, ["plugin", "marketplace", "remove", CLAUDE_MARKETPLACE], opts.env);
5649
5679
  } catch {
5650
5680
  }
5651
5681
  } else {
@@ -5658,7 +5688,7 @@ async function removeClaudePlugin(opts) {
5658
5688
  changed = true;
5659
5689
  }
5660
5690
  const mk = s.extraKnownMarketplaces?.[CLAUDE_MARKETPLACE];
5661
- if (mk?.source?.path && path16.resolve(mk.source.path) === path16.resolve(dir)) {
5691
+ if (mk?.source?.path && path13.resolve(mk.source.path) === path13.resolve(dir)) {
5662
5692
  delete s.extraKnownMarketplaces[CLAUDE_MARKETPLACE];
5663
5693
  changed = true;
5664
5694
  }
@@ -5672,10 +5702,322 @@ async function removeClaudePlugin(opts) {
5672
5702
  return true;
5673
5703
  }
5674
5704
 
5705
+ // ../core/src/hooks/claude-install.ts
5706
+ var CLAUDE_HOOKS = [
5707
+ { event: "UserPromptSubmit", sync: true },
5708
+ { event: "Notification", sync: false },
5709
+ { event: "Stop", sync: false },
5710
+ { event: "SessionEnd", sync: false }
5711
+ ];
5712
+ var CLAUDE_HOOK_EVENTS = CLAUDE_HOOKS.map((h) => h.event);
5713
+ var MARKER = "/v1/events/claude-code";
5714
+ function claudeSettingsPath(home = os2.homedir(), env = process.env) {
5715
+ const dir = env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim() || path14.join(home, ".claude");
5716
+ return path14.join(dir, "settings.json");
5717
+ }
5718
+ function claudeHookCommand(port = DEFAULT_HOOK_PORT, sync = false) {
5719
+ const url = `http://127.0.0.1:${port}${MARKER}`;
5720
+ return sync ? `curl -s --noproxy '*' -m 1 --connect-timeout 0.3 -H 'Content-Type: application/json' --data-binary @- ${url} || true` : `curl -s --noproxy '*' -m 2 -o /dev/null -H 'Content-Type: application/json' --data-binary @- ${url} || true`;
5721
+ }
5722
+ function hookEntry(spec, port) {
5723
+ return spec.sync ? { type: "command", command: claudeHookCommand(port, true), timeout: 3 } : { type: "command", command: claudeHookCommand(port, false), async: true, timeout: 5 };
5724
+ }
5725
+ async function readSettings(file) {
5726
+ let text;
5727
+ try {
5728
+ text = await fsp8.readFile(file, "utf8");
5729
+ } catch (err) {
5730
+ if (err.code === "ENOENT") return {};
5731
+ throw err;
5732
+ }
5733
+ if (!text.trim()) return {};
5734
+ try {
5735
+ const v = JSON.parse(text);
5736
+ if (!v || typeof v !== "object" || Array.isArray(v)) throw new Error("not an object");
5737
+ return v;
5738
+ } catch (err) {
5739
+ throw new Error(`${file} is not valid JSON (${err.message}). Fix it first; Kvali will not overwrite it.`);
5740
+ }
5741
+ }
5742
+ function isKvaliGroup(group) {
5743
+ return Array.isArray(group?.hooks) && group.hooks.some((h) => typeof h?.command === "string" && h.command.includes(MARKER));
5744
+ }
5745
+ function withoutKvali(settings) {
5746
+ const next = { ...settings };
5747
+ if (!next.hooks || typeof next.hooks !== "object") return next;
5748
+ const hooks2 = {};
5749
+ for (const [event, groups] of Object.entries(next.hooks)) {
5750
+ if (!Array.isArray(groups)) {
5751
+ hooks2[event] = groups;
5752
+ continue;
5753
+ }
5754
+ const kept = groups.filter((g) => !isKvaliGroup(g));
5755
+ if (kept.length) hooks2[event] = kept;
5756
+ }
5757
+ if (Object.keys(hooks2).length) next.hooks = hooks2;
5758
+ else delete next.hooks;
5759
+ return next;
5760
+ }
5761
+ async function claudeHooksStatus(file = claudeSettingsPath(), port = DEFAULT_HOOK_PORT) {
5762
+ let settings;
5763
+ try {
5764
+ settings = await readSettings(file);
5765
+ } catch {
5766
+ return "not-installed";
5767
+ }
5768
+ let found = 0;
5769
+ let current = 0;
5770
+ let total = 0;
5771
+ for (const groups of Object.values(settings.hooks ?? {})) if (Array.isArray(groups)) total += groups.filter(isKvaliGroup).length;
5772
+ for (const spec of CLAUDE_HOOKS) {
5773
+ const groups = settings.hooks?.[spec.event];
5774
+ if (!Array.isArray(groups)) continue;
5775
+ const g = groups.find(isKvaliGroup);
5776
+ if (!g) continue;
5777
+ found += 1;
5778
+ const want = hookEntry(spec, port);
5779
+ if (g.hooks.some((h) => h.command === want.command && h.async === true === (want.async === true))) current += 1;
5780
+ }
5781
+ if (found === 0 && total === 0) return "not-installed";
5782
+ return current === CLAUDE_HOOKS.length && total === CLAUDE_HOOKS.length ? "installed" : "outdated";
5783
+ }
5784
+ async function writeWithBackup(file, before, settings) {
5785
+ await fsp8.mkdir(path14.dirname(file), { recursive: true });
5786
+ let backup;
5787
+ if (before !== void 0) {
5788
+ backup = `${file}.kvali-backup`;
5789
+ await writeFileSafely(backup, before, 384);
5790
+ }
5791
+ await writeFileSafely(file, JSON.stringify(settings, null, 2) + "\n");
5792
+ return backup;
5793
+ }
5794
+ function canonical(v) {
5795
+ return JSON.stringify(
5796
+ v,
5797
+ (_k, x) => x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, x[k]])) : x
5798
+ );
5799
+ }
5800
+ async function installClaudeHooks(file = claudeSettingsPath(), port = DEFAULT_HOOK_PORT) {
5801
+ const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
5802
+ const current = await readSettings(file);
5803
+ const settings = withoutKvali(current);
5804
+ settings.hooks = settings.hooks && typeof settings.hooks === "object" ? settings.hooks : {};
5805
+ for (const spec of CLAUDE_HOOKS) {
5806
+ const groups = Array.isArray(settings.hooks[spec.event]) ? settings.hooks[spec.event] : [];
5807
+ settings.hooks[spec.event] = [...groups, { hooks: [hookEntry(spec, port)] }];
5808
+ }
5809
+ if (before !== void 0 && canonical(settings) === canonical(current)) return { changed: false };
5810
+ return { backup: await writeWithBackup(file, before, settings), changed: true };
5811
+ }
5812
+ var CLAUDE_TODO_TOOLS_ENV = "CLAUDE_CODE_ENABLE_TODO_TOOLS";
5813
+ function envOf(settings) {
5814
+ return settings.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : void 0;
5815
+ }
5816
+ async function enableClaudeTodoTools(file, home) {
5817
+ const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
5818
+ const settings = await readSettings(file);
5819
+ const env = envOf(settings);
5820
+ if (env && CLAUDE_TODO_TOOLS_ENV in env) return { changed: false };
5821
+ settings.env = { ...env ?? {}, [CLAUDE_TODO_TOOLS_ENV]: "1" };
5822
+ await writeWithBackup(file, before, settings);
5823
+ await writeKvaliState(home, { claudeTodoTools: true });
5824
+ return { changed: true };
5825
+ }
5826
+ async function disableClaudeTodoTools(file, home) {
5827
+ if (!(await readKvaliState(home)).claudeTodoTools) return { changed: false };
5828
+ const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
5829
+ let changed = false;
5830
+ if (before !== void 0) {
5831
+ const settings = await readSettings(file);
5832
+ const env = envOf(settings);
5833
+ if (env?.[CLAUDE_TODO_TOOLS_ENV] === "1") {
5834
+ const { [CLAUDE_TODO_TOOLS_ENV]: _gone, ...rest } = env;
5835
+ if (Object.keys(rest).length) settings.env = rest;
5836
+ else delete settings.env;
5837
+ await writeWithBackup(file, before, settings);
5838
+ changed = true;
5839
+ }
5840
+ }
5841
+ await writeKvaliState(home, { claudeTodoTools: false });
5842
+ return { changed };
5843
+ }
5844
+ async function uninstallClaudeHooks(file = claudeSettingsPath()) {
5845
+ const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
5846
+ if (before === void 0) return { changed: false };
5847
+ const settings = await readSettings(file);
5848
+ const next = withoutKvali(settings);
5849
+ if (JSON.stringify(next) === JSON.stringify(settings)) return { changed: false };
5850
+ return { backup: await writeWithBackup(file, before, next), changed: true };
5851
+ }
5852
+
5853
+ // ../core/src/protocol.ts
5854
+ import { promises as fsp9 } from "node:fs";
5855
+ import path15 from "node:path";
5856
+ var PROGRESS_PROTOCOL_MARKER = "<!-- kvali:progress-protocol v2 -->";
5857
+ function progressProtocolSnippet() {
5858
+ return `${PROGRESS_PROTOCOL_MARKER}
5859
+ ## Progress reporting
5860
+
5861
+ For any task that takes more than two steps, keep your plan visible so the user can follow progress without asking:
5862
+
5863
+ - If you have a built-in plan or todo tool (Claude Code Tasks/TodoWrite, Codex \`update_plan\`, Gemini CLI \`write_todos\`, Antigravity \`task.md\`), create the plan with it before you start, update it as you go, and do not create \`.agents/progress.md\`.
5864
+ - Only agents without such a tool maintain \`.agents/progress.md\`, in this format:
5865
+
5866
+ \`\`\`md
5867
+ ---
5868
+ agent: <your name, e.g. Cursor>
5869
+ status: working # working | waiting | done | error
5870
+ ---
5871
+ # <short task title>
5872
+ - [x] a finished step
5873
+ - [/] the step you are working on now
5874
+ - [ ] a next step
5875
+ \`\`\`
5876
+
5877
+ - Keep exactly one step marked \`[/]\`. Update the file right after each step, set \`status: waiting\` when you need input from the user, and \`status: done\` when everything is finished.
5878
+ <!-- /kvali:progress-protocol -->
5879
+ `;
5880
+ }
5881
+ var PLAN_RULE_MARKER = "<!-- kvali:plan-rule v2 -->";
5882
+ function planRuleSnippet() {
5883
+ return `${PLAN_RULE_MARKER}
5884
+ ## Keep a visible plan
5885
+
5886
+ For any task that takes more than two steps, create a task list with your built-in plan tool before you start (Claude Code: TaskCreate/TaskUpdate or TodoWrite, whichever it has, loaded with ToolSearch when not in your tool list; Codex: update_plan; Gemini CLI: write_todos; Antigravity: task.md), keep exactly one item in progress, and mark each item done as soon as it is finished. The user follows your progress from this list.
5887
+ <!-- /kvali:plan-rule -->
5888
+ `;
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
+ }
5916
+ function withBlock(text, name, snippet) {
5917
+ if (text === void 0 || text === "") return { text: snippet, result: text === void 0 ? "created" : "added" };
5918
+ const found = findBlock(text, name);
5919
+ if (found) {
5920
+ if (found.end === void 0) return { text, result: "exists" };
5921
+ const crlf = text.includes("\r\n");
5922
+ const block = snippet.trimEnd();
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" };
5925
+ }
5926
+ const sep = text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
5927
+ return { text: `${text}${sep}${snippet}`, result: "added" };
5928
+ }
5929
+ function globalInstructionFiles(home, env = {}) {
5930
+ const claude = env.CLAUDE_CONFIG_DIR?.split(",")[0]?.trim() || path15.join(home, ".claude");
5931
+ const codex = env.CODEX_HOME || path15.join(home, ".codex");
5932
+ const gemini = path15.join(home, ".gemini");
5933
+ return [
5934
+ { id: "claude-code", agent: "Claude Code", dir: claude, file: path15.join(claude, "CLAUDE.md") },
5935
+ { id: "codex", agent: "Codex", dir: codex, file: path15.join(codex, "AGENTS.md") },
5936
+ { id: "gemini", agent: "Gemini CLI / Antigravity", dir: gemini, file: path15.join(gemini, "GEMINI.md") }
5937
+ ];
5938
+ }
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
+ }
5949
+ async function removeGlobalPlanRule(home, env = {}) {
5950
+ const changed = [];
5951
+ for (const target of globalInstructionFiles(home, env)) {
5952
+ let text;
5953
+ try {
5954
+ text = await fsp9.readFile(target.file, "utf8");
5955
+ } catch {
5956
+ continue;
5957
+ }
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);
5962
+ changed.push(target.file);
5963
+ }
5964
+ return changed;
5965
+ }
5966
+ async function readOptional(file) {
5967
+ try {
5968
+ return await fsp9.readFile(file, "utf8");
5969
+ } catch {
5970
+ return void 0;
5971
+ }
5972
+ }
5973
+ async function addGlobalPlanRule(home, env = {}, only) {
5974
+ const out = [];
5975
+ for (const target of globalInstructionFiles(home, env)) {
5976
+ if (only && !only.includes(target.id)) continue;
5977
+ try {
5978
+ const st = await fsp9.stat(target.dir);
5979
+ if (!st.isDirectory()) continue;
5980
+ } catch {
5981
+ continue;
5982
+ }
5983
+ const next = withBlock(await readOptional(target.file), "plan-rule", planRuleSnippet());
5984
+ if (next.result !== "exists") await writeFileSafely(target.file, next.text);
5985
+ out.push({ agent: target.agent, file: target.file, result: next.result });
5986
+ }
5987
+ return out;
5988
+ }
5989
+ async function addProgressProtocol(root) {
5990
+ const file = path15.join(root, "AGENTS.md");
5991
+ const current = await readOptional(file);
5992
+ const next = withBlock(current ?? "# AGENTS.md\n\n", "progress-protocol", progressProtocolSnippet());
5993
+ if (next.result !== "exists") await writeFileSafely(file, next.text);
5994
+ return { file, result: current === void 0 ? "created" : next.result };
5995
+ }
5996
+
5997
+ // ../core/src/hooks/replies.ts
5998
+ import { existsSync as existsSync2 } from "node:fs";
5999
+ import path16 from "node:path";
6000
+ var CLAUDE_PLAN_CONTEXT = "Progress tracking (Kvali): if this request takes more than two steps, start by creating a task list with TaskCreate or TodoWrite, whichever you have (if neither is in your tool list, look for them once with ToolSearch, and go on without a list if they are not there), keep exactly one task in_progress, and mark each task completed as soon as it is done. The user follows your progress from that list, so keep it current.";
6001
+ function pluginRunsIn(liveDir, sessionId) {
6002
+ if (!/^[A-Za-z0-9-]{8,80}$/.test(sessionId)) return false;
6003
+ return existsSync2(path16.join(liveDir, "claude-code", `${sessionId}.mod.json`));
6004
+ }
6005
+ function claudeHookReply(ev, session, pluginRuns = false) {
6006
+ if (ev.event !== "UserPromptSubmit") return void 0;
6007
+ if (pluginRuns) return void 0;
6008
+ if (session) {
6009
+ const p2 = progressOf(session.tasks);
6010
+ if (p2.total > 0 && p2.done < p2.total) return void 0;
6011
+ }
6012
+ return { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: CLAUDE_PLAN_CONTEXT } };
6013
+ }
6014
+
5675
6015
  // ../core/src/setup.ts
6016
+ import { promises as fsp10 } from "node:fs";
6017
+ import path17 from "node:path";
5676
6018
  async function isDir(p2) {
5677
6019
  try {
5678
- return (await fsp8.stat(p2)).isDirectory();
6020
+ return (await fsp10.stat(p2)).isDirectory();
5679
6021
  } catch {
5680
6022
  return false;
5681
6023
  }
@@ -5693,7 +6035,7 @@ async function detectAgents(home, env = {}) {
5693
6035
  }
5694
6036
  function setupChanges(d) {
5695
6037
  const out = [];
5696
- if (d.claude) out.push("Claude Code: the Kvali plugin (live progress pane, exact status, alerts, automatic plans), added with Claude Code's own plugin command");
6038
+ if (d.claude) out.push("Claude Code: the Kvali plugin (live progress pane, exact status, alerts, automatic plans), added with Claude Code's own plugin command, and its task-list tools turned on in ~/.claude/settings.json (current Claude models do not get them unless asked)");
5697
6039
  if (d.codex) out.push("Codex: a planning rule in ~/.codex/AGENTS.md");
5698
6040
  if (d.gemini) out.push(`${d.antigravity ? "Antigravity / Gemini CLI" : "Gemini CLI"}: a planning rule in ~/.gemini/GEMINI.md`);
5699
6041
  return out;
@@ -5726,6 +6068,8 @@ async function applySetup(home, env = {}, port = DEFAULT_HOOK_PORT, d, opts = {}
5726
6068
  result.claude = "hooks";
5727
6069
  result.claudeNote = plugin.note;
5728
6070
  }
6071
+ if (opts.autoPlan === false) await disableClaudeTodoTools(settings, home);
6072
+ else await enableClaudeTodoTools(settings, home);
5729
6073
  }
5730
6074
  const only = [];
5731
6075
  if (agents.codex) only.push("codex");
@@ -5738,12 +6082,13 @@ async function removeSetup(home, env = {}, opts = {}) {
5738
6082
  const bin = await findClaudeBinary({ home, env, extensionDirs: [...opts.claudeExtensionDirs ?? [], ...await claudeExtensionDirs(home)] }).catch(() => void 0);
5739
6083
  await removeClaudePlugin({ home, env, settingsFile: settings, bin }).catch(() => void 0);
5740
6084
  await uninstallClaudeHooks(settings).catch(() => void 0);
6085
+ await disableClaudeTodoTools(settings, home).catch(() => void 0);
5741
6086
  await removeGlobalPlanRule(home, env).catch(() => void 0);
5742
6087
  }
5743
6088
 
5744
6089
  // ../core/src/phone.ts
5745
- import { randomBytes } from "node:crypto";
5746
- import { promises as fsp9 } from "node:fs";
6090
+ import { randomBytes as randomBytes2, randomInt } from "node:crypto";
6091
+ import { promises as fsp11 } from "node:fs";
5747
6092
  import path18 from "node:path";
5748
6093
  var PHONE_EVENTS = ["needs-you", "done", "steps", "actions", "error", "stuck", "limits"];
5749
6094
  var DEFAULT_PHONE_EVENTS = ["needs-you", "done", "error", "stuck", "steps", "limits"];
@@ -5792,7 +6137,7 @@ function normalizePhoneConfig(raw) {
5792
6137
  }
5793
6138
  async function readPhoneConfig(home) {
5794
6139
  try {
5795
- const all = JSON.parse(await fsp9.readFile(kvaliConfigFile(home), "utf8"));
6140
+ const all = JSON.parse(await fsp11.readFile(kvaliConfigFile(home), "utf8"));
5796
6141
  return normalizePhoneConfig(all?.phone);
5797
6142
  } catch {
5798
6143
  return void 0;
@@ -5802,7 +6147,7 @@ async function writePhoneConfig(home, cfg) {
5802
6147
  const file = kvaliConfigFile(home);
5803
6148
  let all = {};
5804
6149
  try {
5805
- const parsed = JSON.parse(await fsp9.readFile(file, "utf8"));
6150
+ const parsed = JSON.parse(await fsp11.readFile(file, "utf8"));
5806
6151
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) all = parsed;
5807
6152
  } catch {
5808
6153
  }
@@ -5819,15 +6164,19 @@ async function writePhoneConfig(home, cfg) {
5819
6164
  doneAfter: cfg.doneAfterSec ?? DEFAULT_DONE_AFTER_SEC
5820
6165
  };
5821
6166
  else delete all.phone;
5822
- await fsp9.mkdir(path18.dirname(file), { recursive: true });
5823
- await fsp9.writeFile(file, `${JSON.stringify(all, null, 2)}
5824
- `, { mode: 384 });
5825
- await fsp9.chmod(file, 384).catch(() => void 0);
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);
5826
6175
  }
5827
6176
  function newTopic() {
5828
6177
  const alphabet = "abcdefghijkmnpqrstuvwxyz23456789";
5829
6178
  let s = "";
5830
- for (const b of randomBytes(16)) s += alphabet[b % 32];
6179
+ for (const b of randomBytes2(16)) s += alphabet[b % 32];
5831
6180
  return `kvali-${s}`;
5832
6181
  }
5833
6182
  function newPhoneConfig(server = DEFAULT_NTFY_SERVER) {
@@ -6022,8 +6371,22 @@ async function telegramBot(token, fetchImpl = fetch) {
6022
6371
  return { ok: false, error: unreachable(err, "api.telegram.org") };
6023
6372
  }
6024
6373
  }
6025
- async function telegramFindChat(token, waitMs = 12e4, fetchImpl = fetch, signal) {
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;
6026
6388
  const until = Date.now() + waitMs;
6389
+ const hasCode = new RegExp(`(^|\\D)${code}(\\D|$)`);
6027
6390
  let offset;
6028
6391
  while (Date.now() < until && !signal?.aborted) {
6029
6392
  const timeout = Math.max(1, Math.min(25, Math.round((until - Date.now()) / 1e3)));
@@ -6034,16 +6397,18 @@ async function telegramFindChat(token, waitMs = 12e4, fetchImpl = fetch, signal)
6034
6397
  signal: AbortSignal.timeout((timeout + 10) * 1e3)
6035
6398
  });
6036
6399
  if (!res.ok) return void 0;
6037
- updates = (await res.json()).result ?? [];
6400
+ const result = (await res.json()).result;
6401
+ updates = Array.isArray(result) ? result.filter((u) => typeof u?.update_id === "number") : [];
6038
6402
  } catch {
6039
6403
  await new Promise((r) => setTimeout(r, 2e3));
6040
6404
  continue;
6041
6405
  }
6042
- const chat = [...updates].reverse().find((u) => u.message?.chat?.type === "private" && typeof u.message.chat.id === "number")?.message?.chat?.id;
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));
6043
6407
  if (updates.length) offset = updates[updates.length - 1].update_id + 1;
6044
- if (chat !== void 0) {
6408
+ if (hit) {
6045
6409
  await fetchImpl(`https://api.telegram.org/bot${token}/getUpdates?timeout=0&offset=${offset}`, { signal: AbortSignal.timeout(1e4) }).catch(() => void 0);
6046
- return String(chat);
6410
+ const chat = hit.message.chat;
6411
+ return { id: String(chat.id), name: chatName(chat) };
6047
6412
  }
6048
6413
  if (Date.now() - askedAt < 1e3) await new Promise((r) => setTimeout(r, 1e3));
6049
6414
  }
@@ -6073,8 +6438,34 @@ function clip(text, max) {
6073
6438
  const one = text.replace(/\s+/g, " ").trim();
6074
6439
  return one.length <= max ? one : `${one.slice(0, max - 1).trimEnd()}\u2026`;
6075
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
+ }
6076
6467
  function formatPush(kind, s, details, extra = {}) {
6077
- const agent = s.agentLabel;
6468
+ const agent = pushAgentLabel(s);
6078
6469
  const where = details ? ` \xB7 ${projectName(s.projectPath)}` : "";
6079
6470
  const p2 = progressOf(s.tasks);
6080
6471
  const step = currentTask(s.tasks);
@@ -6088,7 +6479,8 @@ function formatPush(kind, s, details, extra = {}) {
6088
6479
  return {
6089
6480
  event: "needs-you",
6090
6481
  title: `${agent} needs you${where}`,
6091
- message: lines(details ? clip(s.statusDetail ?? "Waiting for your answer", 200) : "Waiting for your answer", title, planLine),
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),
6092
6484
  priority: 4,
6093
6485
  tags: ["bell"]
6094
6486
  };
@@ -6134,7 +6526,7 @@ function formatPush(kind, s, details, extra = {}) {
6134
6526
  }
6135
6527
  case "loop": {
6136
6528
  const l = s.loop;
6137
- const what = l ? details ? `\u201C${clip(l.detail ?? l.label, 80)}\u201D` : "The same action" : "An action";
6529
+ const what = l ? details ? `\u201C${clip(l.label, 80)}\u201D` : "The same action" : "An action";
6138
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"];
6139
6531
  return {
6140
6532
  event: "stuck",
@@ -6394,7 +6786,7 @@ var PhoneNotifier = class {
6394
6786
  const now = Date.now();
6395
6787
  if (!force && now - this.checkedAt < 5e3) return;
6396
6788
  this.checkedAt = now;
6397
- const st = await fsp9.stat(kvaliConfigFile(this.opts.home)).catch(() => void 0);
6789
+ const st = await fsp11.stat(kvaliConfigFile(this.opts.home)).catch(() => void 0);
6398
6790
  const mtime = st?.mtimeMs ?? 0;
6399
6791
  if (!force && mtime === this.mtime) return;
6400
6792
  this.mtime = mtime;
@@ -8134,7 +8526,7 @@ function qrTerminal(text, color = true) {
8134
8526
  }
8135
8527
 
8136
8528
  // src/index.ts
8137
- var VERSION = "0.7.0";
8529
+ var VERSION = "0.7.2";
8138
8530
  function parse(argv) {
8139
8531
  const opts = {
8140
8532
  json: false,
@@ -8172,18 +8564,24 @@ function parse(argv) {
8172
8564
  case "--here":
8173
8565
  opts.project = process2.cwd();
8174
8566
  break;
8175
- case "--window":
8176
- opts.windowHours = Number(next());
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;
8177
8571
  break;
8572
+ }
8178
8573
  case "--home":
8179
8574
  opts.home = path19.resolve(next());
8180
8575
  break;
8181
8576
  case "--brain-dir":
8182
8577
  opts.brainDirs.push(path19.resolve(next()));
8183
8578
  break;
8184
- case "--port":
8185
- opts.port = Number(next());
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;
8186
8583
  break;
8584
+ }
8187
8585
  case "--no-hub":
8188
8586
  opts.hub = false;
8189
8587
  break;
@@ -8449,6 +8847,7 @@ async function week(opts, svgFile) {
8449
8847
  );
8450
8848
  if (svgFile !== void 0) {
8451
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`);
8452
8851
  await writeFile(file, weekSvg(w));
8453
8852
  console.log(`
8454
8853
  Card: ${file} ${c.gray("(1200\xD7630 SVG; open it in a browser to save as PNG)")}`);
@@ -8537,10 +8936,12 @@ async function phoneChannel(which, off, opts) {
8537
8936
  const token = await askSecret(" Token: ");
8538
8937
  const me = await telegramBot(token);
8539
8938
  if (!me.ok) fail(`could not use this bot: ${me.error}`);
8540
- console.log(` 3. Now send any message to @${me.username} (https://t.me/${me.username}). Waiting up to 3 minutes\u2026`);
8541
- const chatId = await telegramFindChat(token, 18e4);
8542
- if (!chatId) fail(`no message reached @${me.username}; run \`kvali phone telegram\` again and write to the bot while Kvali waits`);
8543
- only = { telegram: { token, chatId, bot: me.username } };
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 } };
8544
8945
  } else {
8545
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"));
8546
8947
  const webhook = await askSecret(" Webhook URL: ");
@@ -8612,6 +9013,7 @@ async function phone(sub, opts, arg) {
8612
9013
  }
8613
9014
  async function main() {
8614
9015
  const { cmd, opts } = parse(process2.argv.slice(2));
9016
+ await secureKvaliHome(opts.home);
8615
9017
  if (cmd[0] === "hooks") return hooks(cmd[1], opts);
8616
9018
  if (cmd[0] === "setup") {
8617
9019
  if (cmd[1] === "off") {