@kvali/cli 0.7.1 → 0.7.3

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";
@@ -80,7 +80,11 @@ function planEta(s, now) {
80
80
  const left = p2.total - p2.done;
81
81
  if (p2.total === 0 || left <= 0) return void 0;
82
82
  const spent = s.current ? Math.max(0, now - s.current.startedAt) : 0;
83
- return Math.max(0, typical - spent) + (left - 1) * typical;
83
+ return restOfPlan(typical, spent, left);
84
+ }
85
+ function restOfPlan(typical, spent, left) {
86
+ if (spent > 2 * typical) return void 0;
87
+ return Math.max(typical - spent, typical / 4) + (left - 1) * typical;
84
88
  }
85
89
  function fmtClock(ms) {
86
90
  return new Date(ms).toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit" });
@@ -178,6 +182,8 @@ function dayKeyLocal(ms) {
178
182
 
179
183
  // ../core/src/limits.ts
180
184
  var KEEP_MS = 6 * 36e5;
185
+ var FUTURE_SLACK_MS = 5 * 6e4;
186
+ var MAX_SAMPLES = 720;
181
187
  var PACE_MS = 60 * 6e4;
182
188
  var MIN_SPAN_MS = 5 * 6e4;
183
189
  var RESET_JITTER_MS = 5 * 6e4;
@@ -196,10 +202,15 @@ function runsOutAt(samples, latest, now) {
196
202
  }
197
203
  var LimitBook = class {
198
204
  books = /* @__PURE__ */ new Map();
199
- /** Adds a reading taken at `at`. Older readings than the window's latest are ignored. */
200
- add(reading, at) {
205
+ /**
206
+ * Adds a reading taken at `at`. Older readings than the window's latest are ignored, and so is
207
+ * one from the future (a wrong clock or a broken file would otherwise hide every real one).
208
+ */
209
+ add(reading, at, now) {
201
210
  if (!Number.isFinite(reading.usedPercent) || !Number.isFinite(at)) return;
202
- const pct = Math.max(0, reading.usedPercent);
211
+ if (now !== void 0 && at > now + FUTURE_SLACK_MS) return;
212
+ if (typeof reading.label !== "string" || !reading.label || reading.label.length > 40) return;
213
+ const pct = Math.min(100, Math.max(0, reading.usedPercent));
203
214
  let book = this.books.get(reading.label);
204
215
  if (book) {
205
216
  const sameWindow = book.latest.resetsAt === void 0 || reading.resetsAt === void 0 || Math.abs(book.latest.resetsAt - reading.resetsAt) <= RESET_JITTER_MS;
@@ -210,6 +221,7 @@ var LimitBook = class {
210
221
  if (at >= book.latest.at - KEEP_MS && !book.samples.some((s) => s.at === at)) {
211
222
  book.samples.push({ at, pct });
212
223
  book.samples.sort((a, b) => a.at - b.at);
224
+ if (book.samples.length > MAX_SAMPLES) book.samples.splice(0, book.samples.length - MAX_SAMPLES);
213
225
  }
214
226
  return;
215
227
  }
@@ -223,6 +235,7 @@ var LimitBook = class {
223
235
  book.latest = { ...reading, usedPercent: pct, at };
224
236
  const cutoff = at - KEEP_MS;
225
237
  while (book.samples.length > 1 && book.samples[0].at < cutoff) book.samples.shift();
238
+ if (book.samples.length > MAX_SAMPLES) book.samples.splice(0, book.samples.length - MAX_SAMPLES);
226
239
  }
227
240
  get size() {
228
241
  return this.books.size;
@@ -256,6 +269,89 @@ function claudeWindowLabel(kind) {
256
269
  return { label: kind.replace(/_/g, " ") };
257
270
  }
258
271
 
272
+ // ../core/src/util/text.ts
273
+ function firstLine(text, max = 80) {
274
+ const line = text.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
275
+ return truncate(line.replace(/\s+/g, " "), max);
276
+ }
277
+ function truncate(text, max) {
278
+ if (text.length <= max) return text;
279
+ return text.slice(0, Math.max(0, max - 1)).trimEnd() + "\u2026";
280
+ }
281
+ var INJECTED_TAGS = ["system-reminder", "local-command-stdout", "local-command-stderr", "command-message", "command-args"];
282
+ function removeTagged(text, tag, keep) {
283
+ const open = `<${tag}>`;
284
+ const close = `</${tag}>`;
285
+ let out = "";
286
+ let pos = 0;
287
+ for (; ; ) {
288
+ const a = text.indexOf(open, pos);
289
+ if (a === -1) break;
290
+ const b = text.indexOf(close, a + open.length);
291
+ if (b === -1) break;
292
+ out += text.slice(pos, a) + (keep ? text.slice(a + open.length, b) : "");
293
+ pos = b + close.length;
294
+ }
295
+ return out + text.slice(pos);
296
+ }
297
+ function stripInjectedTags(text) {
298
+ let out = text;
299
+ for (const tag of INJECTED_TAGS) out = removeTagged(out, tag, false);
300
+ return removeTagged(out, "command-name", true).trim();
301
+ }
302
+ function contentText(content) {
303
+ if (typeof content === "string") return content;
304
+ if (!Array.isArray(content)) return "";
305
+ const parts = [];
306
+ for (const part of content) {
307
+ if (typeof part === "string") parts.push(part);
308
+ else if (part && typeof part === "object") {
309
+ const p2 = part;
310
+ if (typeof p2.text === "string" && (p2.type === void 0 || p2.type === "text" || p2.type === "input_text" || p2.type === "output_text")) {
311
+ parts.push(p2.text);
312
+ }
313
+ }
314
+ }
315
+ return parts.join("\n");
316
+ }
317
+ function summarizeCommand(cmd, max = 80) {
318
+ let text;
319
+ if (typeof cmd === "string") text = cmd;
320
+ else if (Array.isArray(cmd)) {
321
+ const parts = cmd.filter((c) => typeof c === "string");
322
+ if (parts.length >= 3 && /(^|\/)(ba|z|fi)?sh$/.test(parts[0]) && /^-\w*c$/.test(parts[1])) text = parts.slice(2).join(" ");
323
+ else text = parts.join(" ");
324
+ }
325
+ if (!text) return void 0;
326
+ return truncate(text.replace(/\s+/g, " ").trim(), max);
327
+ }
328
+ function basename(p2) {
329
+ const parts = p2.split(/[\\/]/).filter(Boolean);
330
+ return parts[parts.length - 1] ?? p2;
331
+ }
332
+ function lookupTable(entries) {
333
+ return Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), entries));
334
+ }
335
+ var ESCAPES = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x1b[@-_]?/g;
336
+ var INVISIBLE = /[\x00-\x08\x0b-\x1f\x7f-\x9f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g;
337
+ function cleanText(text, max = 1e3) {
338
+ const t = text.replace(ESCAPES, "").replace(INVISIBLE, "");
339
+ return t.length > max ? truncate(t, max) : t;
340
+ }
341
+ function cleanFields(o, fields) {
342
+ let out;
343
+ for (const [k, max] of Object.entries(fields)) {
344
+ const v = o[k];
345
+ if (typeof v !== "string") continue;
346
+ const c = cleanText(v, max);
347
+ if (c !== v) {
348
+ out ??= { ...o };
349
+ out[k] = c;
350
+ }
351
+ }
352
+ return out ?? o;
353
+ }
354
+
259
355
  // ../core/src/week.ts
260
356
  var WEEK_DAYS = 7;
261
357
  function localDay(ms) {
@@ -338,7 +434,7 @@ function weekShareText(w, opts = {}) {
338
434
 
339
435
  Tracked with Kvali, an open-source progress bar for AI agents: ${KVALI_URL}`;
340
436
  }
341
- var esc = (t) => t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
437
+ var esc = (t) => cleanText(t, 300).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
342
438
  function weekSvg(w, opts = {}) {
343
439
  const W = 1200;
344
440
  const H = 630;
@@ -437,21 +533,58 @@ function isClaude46OrLater(key) {
437
533
  const minor = Number(r[3] ?? 0);
438
534
  return major > 4 || major === 4 && minor >= 6;
439
535
  }
440
- function globToRegExp(glob) {
441
- const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
442
- return new RegExp(`^${escaped}$`, "i");
536
+ function globMatch(glob, text) {
537
+ const g = glob.toLowerCase();
538
+ const s = text.toLowerCase();
539
+ let gi = 0;
540
+ let si = 0;
541
+ let star = -1;
542
+ let mark = 0;
543
+ while (si < s.length) {
544
+ if (gi < g.length && (g[gi] === "?" || g[gi] === s[si])) {
545
+ gi += 1;
546
+ si += 1;
547
+ } else if (gi < g.length && g[gi] === "*") {
548
+ star = gi;
549
+ gi += 1;
550
+ mark = si;
551
+ } else if (star !== -1) {
552
+ gi = star + 1;
553
+ mark += 1;
554
+ si = mark;
555
+ } else return false;
556
+ }
557
+ while (gi < g.length && g[gi] === "*") gi += 1;
558
+ return gi === g.length;
559
+ }
560
+ var isPrice = (x) => typeof x === "number" && Number.isFinite(x) && x >= 0;
561
+ function customPrice(v, nested = false) {
562
+ if (!v || typeof v !== "object") return void 0;
563
+ const o = v;
564
+ if (!isPrice(o.input) || !isPrice(o.output)) return void 0;
565
+ const p2 = { input: o.input, output: o.output, cacheRead: isPrice(o.cacheRead) ? o.cacheRead : 0 };
566
+ if (isPrice(o.cacheWrite5m)) p2.cacheWrite5m = o.cacheWrite5m;
567
+ if (isPrice(o.cacheWrite1h)) p2.cacheWrite1h = o.cacheWrite1h;
568
+ if (isPrice(o.fastMultiplier)) p2.fastMultiplier = o.fastMultiplier;
569
+ if (!nested && o.longPrompt && typeof o.longPrompt === "object") {
570
+ const t = o.longPrompt.threshold;
571
+ const tier = customPrice(o.longPrompt, true);
572
+ if (tier && isPrice(t)) p2.longPrompt = { ...tier, threshold: t };
573
+ }
574
+ return p2;
443
575
  }
444
576
  var Pricing = class {
445
577
  custom;
446
578
  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
- }));
579
+ this.custom = [];
580
+ for (const [glob, v] of Object.entries(customPrices ?? {})) {
581
+ const price = customPrice(v);
582
+ if (price) this.custom.push({ glob, price });
583
+ }
451
584
  }
452
585
  find(model) {
453
586
  if (!model) return void 0;
454
- for (const c of this.custom) if (c.re.test(model)) return { price: c.price, key: model };
587
+ for (const c of this.custom) if (globMatch(c.glob, model)) return { price: c.price, key: model };
455
588
  const key = anthropicModelKey(model);
456
589
  if (key && ANTHROPIC_PRICES[key]) return { price: ANTHROPIC_PRICES[key], key };
457
590
  return void 0;
@@ -475,8 +608,11 @@ var Pricing = class {
475
608
  // ../core/src/util/jsonl.ts
476
609
  import { promises as fsp } from "node:fs";
477
610
  var CHUNK_BYTES = 1 << 20;
611
+ var MAX_LINE_BYTES = 8 << 20;
478
612
  var JsonlTail = class {
479
613
  offset = 0;
614
+ /** Inside a line longer than MAX_LINE_BYTES: skipping to its end. */
615
+ skipping = false;
480
616
  size = -1;
481
617
  mtimeMs = -1;
482
618
  ino;
@@ -505,6 +641,7 @@ var JsonlTail = class {
505
641
  let reset = false;
506
642
  if (st.size < this.offset || this.ino !== void 0 && st.ino !== this.ino) {
507
643
  this.offset = 0;
644
+ this.skipping = false;
508
645
  reset = true;
509
646
  onReset?.();
510
647
  }
@@ -514,19 +651,33 @@ var JsonlTail = class {
514
651
  try {
515
652
  const chunk = Buffer.allocUnsafe(CHUNK_BYTES);
516
653
  let pos = this.offset;
517
- let carry = Buffer.alloc(0);
654
+ let parts = [];
655
+ let partsLen = 0;
656
+ let skipping = this.skipping;
518
657
  while (pos < st.size) {
519
658
  const want = Math.min(chunk.length, st.size - pos);
520
659
  const { bytesRead } = await fh.read(chunk, 0, want, pos);
521
660
  if (bytesRead <= 0) break;
522
661
  pos += bytesRead;
523
- const buf = carry.length ? Buffer.concat([carry, chunk.subarray(0, bytesRead)]) : chunk.subarray(0, bytesRead);
662
+ const buf = chunk.subarray(0, bytesRead);
524
663
  let start = 0;
525
664
  let nl;
526
665
  while ((nl = buf.indexOf(10, start)) !== -1) {
527
- const line = buf.toString("utf8", start, nl).trim();
528
- start = nl + 1;
529
666
  lines += 1;
667
+ const piece = buf.subarray(start, nl);
668
+ start = nl + 1;
669
+ if (skipping) {
670
+ skipping = false;
671
+ continue;
672
+ }
673
+ if (partsLen + piece.length > MAX_LINE_BYTES) {
674
+ parts = [];
675
+ partsLen = 0;
676
+ continue;
677
+ }
678
+ const line = (partsLen ? Buffer.concat([...parts, piece]) : piece).toString("utf8").trim();
679
+ parts = [];
680
+ partsLen = 0;
530
681
  if (!line) continue;
531
682
  let record;
532
683
  try {
@@ -534,11 +685,24 @@ var JsonlTail = class {
534
685
  } catch {
535
686
  continue;
536
687
  }
537
- onRecord(record);
688
+ try {
689
+ onRecord(record);
690
+ } catch {
691
+ }
692
+ }
693
+ if (!skipping && start < buf.length) {
694
+ if (partsLen + (buf.length - start) > MAX_LINE_BYTES) {
695
+ skipping = true;
696
+ parts = [];
697
+ partsLen = 0;
698
+ } else {
699
+ parts.push(Buffer.from(buf.subarray(start)));
700
+ partsLen += buf.length - start;
701
+ }
538
702
  }
539
- carry = Buffer.from(buf.subarray(start));
540
703
  }
541
- this.offset = pos - carry.length;
704
+ this.skipping = skipping;
705
+ this.offset = pos - partsLen;
542
706
  } finally {
543
707
  await fh.close();
544
708
  }
@@ -549,6 +713,21 @@ var JsonlTail = class {
549
713
  };
550
714
 
551
715
  // ../core/src/adapter.ts
716
+ var reported = /* @__PURE__ */ new Set();
717
+ async function isolated(ctx, what, fn) {
718
+ try {
719
+ return await fn();
720
+ } catch (err) {
721
+ const message = `${what}: ${err instanceof Error ? err.message : String(err)}`;
722
+ if (!reported.has(message)) {
723
+ if (reported.size >= 200) reported.clear();
724
+ reported.add(message);
725
+ ctx.log(message);
726
+ }
727
+ return void 0;
728
+ }
729
+ }
730
+ var fileName = (p2) => p2.split(/[\\/]/).pop() ?? p2;
552
731
  var JsonlSessionAdapter = class {
553
732
  discoveryIntervalMs = 5e3;
554
733
  tracked = /* @__PURE__ */ new Map();
@@ -571,14 +750,16 @@ var JsonlSessionAdapter = class {
571
750
  }
572
751
  const sessions = [];
573
752
  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);
753
+ const s = await isolated(ctx, `[${this.id}] ${fileName(p2)}`, async () => {
754
+ const res = await t.tail.read(
755
+ (record) => this.onRecord(t.state, record, ctx),
756
+ () => {
757
+ t.state = this.createState(p2);
758
+ }
759
+ );
760
+ await this.afterRead(t.state, ctx, res.changed);
761
+ return this.toSession(t.state, ctx);
762
+ });
582
763
  if (s) sessions.push(s);
583
764
  }
584
765
  return sessions;
@@ -599,8 +780,22 @@ import path11 from "node:path";
599
780
  import path2 from "node:path";
600
781
 
601
782
  // ../core/src/util/checklist.ts
602
- var ITEM_RE = /^(\s*)(?:[-*+]|\d+[.)])\s+\[([ xX/\-~>!?])\]\s+(.+?)\s*$/;
603
- var HEADING_RE = /^(#{1,6})\s+(.+?)\s*#*\s*$/;
783
+ var ITEM_RE = /^([ \t]*)(?:[-*+]|\d{1,9}[.)])[ \t]+\[([ xX/\-~>!?])\][ \t]+(\S.*)$/;
784
+ var KEY_RE = /^[A-Za-z0-9_-]{1,40}$/;
785
+ var MAX_LINE = 2e3;
786
+ var MAX_TASKS = 500;
787
+ function heading(line) {
788
+ let level = 0;
789
+ while (level < line.length && line[level] === "#") level += 1;
790
+ if (level < 1 || level > 6) return void 0;
791
+ const rest = line.slice(level);
792
+ if (rest !== "" && rest[0] !== " " && rest[0] !== " ") return void 0;
793
+ let text = rest.trim();
794
+ let end2 = text.length;
795
+ while (end2 > 0 && text[end2 - 1] === "#") end2 -= 1;
796
+ if (end2 < text.length && (end2 === 0 || text[end2 - 1] === " " || text[end2 - 1] === " ")) text = text.slice(0, end2).trimEnd();
797
+ return text ? [level, text] : void 0;
798
+ }
604
799
  var MARKER_STATUS = {
605
800
  " ": "pending",
606
801
  x: "completed",
@@ -613,14 +808,17 @@ var MARKER_STATUS = {
613
808
  "?": "blocked"
614
809
  };
615
810
  function parseChecklist(markdown) {
616
- const frontmatter = {};
617
- let body = markdown.replace(/^/, "");
811
+ const frontmatter = /* @__PURE__ */ Object.create(null);
812
+ let body = markdown.replace(/^\ufeff/, "");
618
813
  if (body.startsWith("---")) {
619
814
  const end2 = body.indexOf("\n---", 3);
620
815
  if (end2 !== -1) {
621
816
  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, "");
817
+ const colon = line.indexOf(":");
818
+ if (colon < 1) continue;
819
+ const key = line.slice(0, colon).trim();
820
+ if (!KEY_RE.test(key)) continue;
821
+ frontmatter[key.toLowerCase()] = line.slice(colon + 1, colon + 1 + MAX_LINE).trim().replace(/^["']|["']$/g, "");
624
822
  }
625
823
  body = body.slice(end2 + 4);
626
824
  }
@@ -630,16 +828,17 @@ function parseChecklist(markdown) {
630
828
  const tasks = [];
631
829
  let inFence = false;
632
830
  for (const raw of body.split("\n")) {
633
- const line = raw.replace(/\r$/, "");
634
- if (/^\s*(```|~~~)/.test(line)) {
831
+ if (tasks.length >= MAX_TASKS) break;
832
+ const line = (raw.length > MAX_LINE ? raw.slice(0, MAX_LINE) : raw).replace(/\r$/, "");
833
+ if (/^[ \t]*(```|~~~)/.test(line)) {
635
834
  inFence = !inFence;
636
835
  continue;
637
836
  }
638
837
  if (inFence) continue;
639
- const h = HEADING_RE.exec(line);
838
+ const h = heading(line);
640
839
  if (h) {
641
- const text = h[2].trim();
642
- if (h[1].length === 1 && title === void 0) title = text;
840
+ const [level, text] = h;
841
+ if (level === 1 && title === void 0) title = text;
643
842
  else group = text;
644
843
  continue;
645
844
  }
@@ -648,7 +847,7 @@ function parseChecklist(markdown) {
648
847
  const indent = m[1].replace(/\t/g, " ").length;
649
848
  tasks.push({
650
849
  id: String(tasks.length + 1),
651
- title: m[3],
850
+ title: m[3].trimEnd(),
652
851
  status: MARKER_STATUS[m[2]] ?? "pending",
653
852
  depth: Math.floor(indent / 2),
654
853
  group
@@ -719,49 +918,6 @@ function isWithin(child, parent) {
719
918
  return rel2 === "" || !rel2.startsWith("..") && !path.isAbsolute(rel2);
720
919
  }
721
920
 
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
921
  // ../core/src/util/task-timer.ts
766
922
  var keyOf = (t) => t.title.trim().toLowerCase() || `#${t.id}`;
767
923
  function median(xs) {
@@ -961,14 +1117,16 @@ var AntigravityAdapter = class {
961
1117
  }
962
1118
  const out = [];
963
1119
  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);
1120
+ const s = await isolated(ctx, `[antigravity] ${st.id}`, async () => {
1121
+ await st.tail.read(
1122
+ (rec) => this.onStep(st, rec, ctx),
1123
+ () => {
1124
+ Object.assign(st, this.blank(st.id, st.dir), { tail: st.tail });
1125
+ }
1126
+ );
1127
+ await this.readTask(st);
1128
+ return this.toSession(st, ctx);
1129
+ });
972
1130
  if (s) out.push(s);
973
1131
  }
974
1132
  return out;
@@ -1101,7 +1259,7 @@ var AntigravityAdapter = class {
1101
1259
  const meta = await readJsonSafe(path2.join(st.dir, "task.md.metadata.json"));
1102
1260
  st.task = {
1103
1261
  mtimeMs: s.mtimeMs,
1104
- title: parsed?.title?.replace(/\s*[—–-]\s*Task Tracker\s*$/i, "").trim() || void 0,
1262
+ title: (parsed?.title !== void 0 ? withoutTrackerSuffix(parsed.title) : void 0) || void 0,
1105
1263
  tasks: parsed?.tasks ?? [],
1106
1264
  summary: typeof meta?.summary === "string" ? meta.summary : void 0
1107
1265
  };
@@ -1173,6 +1331,12 @@ var AntigravityAdapter = class {
1173
1331
  };
1174
1332
  }
1175
1333
  };
1334
+ function withoutTrackerSuffix(title) {
1335
+ const s = title.trim();
1336
+ if (!s.toLowerCase().endsWith("task tracker")) return s;
1337
+ const rest = s.slice(0, -"task tracker".length).trimEnd();
1338
+ return /[—–-]$/.test(rest) ? rest.slice(0, -1).trim() : s;
1339
+ }
1176
1340
 
1177
1341
  // ../core/src/adapters/claude-code.ts
1178
1342
  import path3 from "node:path";
@@ -1352,17 +1516,19 @@ var ClaudeCodeAdapter = class {
1352
1516
  }
1353
1517
  const out = [];
1354
1518
  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);
1519
+ await isolated(ctx, `[claude-code] ${path3.basename(entry.state.file)}`, async () => {
1520
+ const res = await entry.tail.read(
1521
+ (rec) => this.onRecord(entry.state, rec, ctx, false),
1522
+ () => {
1523
+ entry.state = this.createState(entry.state.file);
1524
+ }
1525
+ );
1526
+ await this.readSideFiles(entry.state, ctx, res.changed);
1527
+ });
1362
1528
  }
1363
- await this.readLegacyAgents(ctx);
1529
+ await isolated(ctx, "[claude-code] subagents", () => this.readLegacyAgents(ctx));
1364
1530
  for (const entry of this.sessions.values()) {
1365
- const s = this.toSession(entry.state, ctx);
1531
+ const s = await isolated(ctx, `[claude-code] ${path3.basename(entry.state.file)}`, () => this.toSession(entry.state, ctx));
1366
1532
  if (s) out.push(s);
1367
1533
  }
1368
1534
  return out;
@@ -1430,6 +1596,8 @@ var ClaudeCodeAdapter = class {
1430
1596
  maxContext: 0,
1431
1597
  tasks: /* @__PURE__ */ new Map(),
1432
1598
  pendingCreates: /* @__PURE__ */ new Map(),
1599
+ foreignCreates: /* @__PURE__ */ new Set(),
1600
+ foreignTasks: /* @__PURE__ */ new Set(),
1433
1601
  open: /* @__PURE__ */ new Map(),
1434
1602
  phase: "idle",
1435
1603
  phaseAt: 0,
@@ -1450,7 +1618,18 @@ var ClaudeCodeAdapter = class {
1450
1618
  const o = rec;
1451
1619
  const ts = parseTime(o.timestamp);
1452
1620
  if (tokensOnly) {
1453
- if (o.type === "assistant" && o.message) this.countUsage(st, o, ts, ctx, false);
1621
+ if (o.type === "assistant" && o.message) {
1622
+ this.countUsage(st, o, ts, ctx, false);
1623
+ for (const b of Array.isArray(o.message.content) ? o.message.content : []) {
1624
+ if (b?.type === "tool_use" && b.name === "TaskCreate" && typeof b.id === "string") st.foreignCreates.add(b.id);
1625
+ }
1626
+ } else if (o.type === "user" && Array.isArray(o.message?.content) && st.foreignCreates.size) {
1627
+ for (const b of o.message.content) {
1628
+ if (b?.type !== "tool_result" || !st.foreignCreates.delete(b.tool_use_id)) continue;
1629
+ const id = o.toolUseResult?.task?.id ?? /Task #?(\w+) created/i.exec(contentText(b.content))?.[1];
1630
+ if (id !== void 0 && id !== null) st.foreignTasks.add(String(id));
1631
+ }
1632
+ }
1454
1633
  return;
1455
1634
  }
1456
1635
  if (ts !== void 0) {
@@ -1761,7 +1940,7 @@ var ClaudeCodeAdapter = class {
1761
1940
  else if (pst.mtimeMs !== st.pulse?.mtimeMs) {
1762
1941
  const pulse = await readJsonSafe(pulseFile);
1763
1942
  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);
1943
+ if (st.pulse?.limits) this.addLimits(st.pulse.limits, ctx.now());
1765
1944
  }
1766
1945
  const now = ctx.now();
1767
1946
  if (now - st.lastSubagentScan >= 5e3) {
@@ -1784,7 +1963,7 @@ var ClaudeCodeAdapter = class {
1784
1963
  const windows = this.limitBook.windows(ctx.now());
1785
1964
  return windows.length ? { agent: this.id, agentLabel: this.label, windows } : void 0;
1786
1965
  }
1787
- addLimits(l) {
1966
+ addLimits(l, now) {
1788
1967
  if (typeof l.at !== "number" || !Array.isArray(l.windows)) return;
1789
1968
  for (const w of l.windows) {
1790
1969
  if (!w || typeof w.kind !== "string" || typeof w.percentUsed !== "number") continue;
@@ -1794,10 +1973,10 @@ var ClaudeCodeAdapter = class {
1794
1973
  const series = l.samples?.[w.kind];
1795
1974
  if (Array.isArray(series)) {
1796
1975
  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]);
1976
+ 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
1977
  }
1799
1978
  }
1800
- this.limitBook.add({ label, usedPercent: w.percentUsed, resetsAt, windowMinutes }, l.at);
1979
+ this.limitBook.add({ label, usedPercent: w.percentUsed, resetsAt, windowMinutes }, l.at, now);
1801
1980
  }
1802
1981
  }
1803
1982
  /** Older Claude Code versions wrote subagents as top-level agent-*.jsonl files that reference the parent session. */
@@ -1815,7 +1994,8 @@ var ClaudeCodeAdapter = class {
1815
1994
  }
1816
1995
  }
1817
1996
  resolveTasks(st) {
1818
- if (st.taskDir && st.taskDir.tasks.length > 0) return st.taskDir.tasks;
1997
+ const own = st.taskDir?.tasks.filter((t) => !st.foreignTasks.has(t.id)) ?? [];
1998
+ if (own.length > 0) return own;
1819
1999
  if (st.tasks.size > 0) {
1820
2000
  return [...st.tasks.values()].sort((a, b) => Number(a.id) - Number(b.id) || a.id.localeCompare(b.id));
1821
2001
  }
@@ -2003,7 +2183,7 @@ function editorUserDataDirs(home, env, platform = process.platform) {
2003
2183
  }
2004
2184
 
2005
2185
  // ../core/src/adapters/cline.ts
2006
- var WAIT_ASKS = {
2186
+ var WAIT_ASKS = lookupTable({
2007
2187
  followup: () => "Asked you a question",
2008
2188
  plan_mode_respond: () => "Plan ready for your review",
2009
2189
  act_mode_respond: () => "Waiting for your reply",
@@ -2017,7 +2197,7 @@ var WAIT_ASKS = {
2017
2197
  summarize_task: () => "Wants to summarize the task",
2018
2198
  report_bug: () => "Wants to report a bug",
2019
2199
  auto_approval_max_req_reached: (_m, label) => `${label} reached its auto-approve limit`
2020
- };
2200
+ });
2021
2201
  var QUIET_SAYS = /* @__PURE__ */ new Set([
2022
2202
  "checkpoint_created",
2023
2203
  "checkpoint_saved",
@@ -2041,9 +2221,10 @@ function parseJson(text) {
2041
2221
  }
2042
2222
  }
2043
2223
  function stripReqApp(cmd) {
2044
- return cmd.replace(/\s*REQ_APP\s*$/, "");
2224
+ const t = cmd.trimEnd();
2225
+ return t.endsWith("REQ_APP") ? t.slice(0, -"REQ_APP".length).trimEnd() : cmd;
2045
2226
  }
2046
- var TOOL_LABELS = {
2227
+ var TOOL_LABELS = lookupTable({
2047
2228
  editedExistingFile: "Edit",
2048
2229
  appliedDiff: "Edit",
2049
2230
  insertContent: "Edit",
@@ -2069,7 +2250,7 @@ var TOOL_LABELS = {
2069
2250
  imageGenerated: "Generate image",
2070
2251
  runSlashCommand: "Slash command",
2071
2252
  updateTodoList: "Update plan"
2072
- };
2253
+ });
2073
2254
  function toolActivity(m) {
2074
2255
  const kind = m.type === "ask" ? m.ask : m.say;
2075
2256
  const at = m.ts;
@@ -2323,9 +2504,10 @@ var ClineFamilyAdapter = class {
2323
2504
  const out = [];
2324
2505
  const byId = /* @__PURE__ */ new Map();
2325
2506
  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);
2507
+ const s = await isolated(ctx, `[${this.id}] ${t.id}`, async () => {
2508
+ await this.refresh(t, ctx);
2509
+ return t.fold ? this.toSession(t, ctx) : void 0;
2510
+ });
2329
2511
  if (s) {
2330
2512
  out.push(s);
2331
2513
  byId.set(t.id, s);
@@ -2584,7 +2766,7 @@ var RooCodeAdapter = class extends ClineFamilyAdapter {
2584
2766
  return out;
2585
2767
  }
2586
2768
  };
2587
- var SDK_TOOL_LABELS = {
2769
+ var SDK_TOOL_LABELS = lookupTable({
2588
2770
  read_files: "Read",
2589
2771
  search_codebase: "Search",
2590
2772
  run_commands: "Shell",
@@ -2599,7 +2781,7 @@ var SDK_TOOL_LABELS = {
2599
2781
  read_file: "Read",
2600
2782
  write_to_file: "Write",
2601
2783
  replace_in_file: "Edit"
2602
- };
2784
+ });
2603
2785
  function sdkActivity(block, at) {
2604
2786
  const name = String(block.name ?? "tool");
2605
2787
  const input = block.input && typeof block.input === "object" ? block.input : {};
@@ -2739,8 +2921,10 @@ var ClineSdkSessions = class {
2739
2921
  }
2740
2922
  const out = [];
2741
2923
  for (const t of this.tracked.values()) {
2742
- await this.refresh(t);
2743
- const s = this.toSession(t, ctx, label);
2924
+ const s = await isolated(ctx, `[${label}] ${t.id}`, async () => {
2925
+ await this.refresh(t);
2926
+ return this.toSession(t, ctx, label);
2927
+ });
2744
2928
  if (s) out.push(s);
2745
2929
  }
2746
2930
  return out;
@@ -3133,7 +3317,7 @@ var CodexAdapter = class extends JsonlSessionAdapter {
3133
3317
  }
3134
3318
  if (windows.length) {
3135
3319
  st.rateLimits = windows;
3136
- for (const w of windows) this.limitBook.add(w, ts);
3320
+ for (const w of windows) this.limitBook.add(w, ts, ctx.now());
3137
3321
  }
3138
3322
  }
3139
3323
  }
@@ -3437,7 +3621,7 @@ function permissionLabel(r) {
3437
3621
  }
3438
3622
  }
3439
3623
  function todoMarkdown(md) {
3440
- return parseChecklist(md.replace(/^(\s*(?:[-*+]|\d+[.)])\s*)\[[-~]\]/gm, "$1[/]")).tasks;
3624
+ return parseChecklist(md.replace(/^([ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]*)\[[-~]\]/gm, "$1[/]")).tasks;
3441
3625
  }
3442
3626
  function dbStatus(s) {
3443
3627
  return s === "done" ? "completed" : s === "in_progress" ? "in_progress" : s === "blocked" ? "blocked" : "pending";
@@ -4821,8 +5005,9 @@ var KiloCodeAdapter = class extends OpenCodeFamilyAdapter {
4821
5005
  };
4822
5006
 
4823
5007
  // ../core/src/adapters/progress-file.ts
5008
+ import { promises as fsp4 } from "node:fs";
4824
5009
  import path10 from "node:path";
4825
- var STATUS_WORDS = {
5010
+ var STATUS_WORDS = lookupTable({
4826
5011
  working: "working",
4827
5012
  running: "working",
4828
5013
  in_progress: "working",
@@ -4835,7 +5020,16 @@ var STATUS_WORDS = {
4835
5020
  paused: "idle",
4836
5021
  error: "error",
4837
5022
  failed: "error"
4838
- };
5023
+ });
5024
+ var MAX_PROGRESS_FILES = 20;
5025
+ var MAX_LISTED = 500;
5026
+ async function realpathSafe(p2) {
5027
+ try {
5028
+ return await fsp4.realpath(p2);
5029
+ } catch {
5030
+ return void 0;
5031
+ }
5032
+ }
4839
5033
  var ProgressFileAdapter = class {
4840
5034
  id = "progress-file";
4841
5035
  label = "Progress file";
@@ -4845,16 +5039,26 @@ var ProgressFileAdapter = class {
4845
5039
  const files = [];
4846
5040
  for (const root of ctx.workspaceRoots) {
4847
5041
  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 });
5042
+ const names = [path10.join(agentsDir, "progress.md")];
5043
+ for (const f of (await listDir(path10.join(agentsDir, "progress"))).slice(0, MAX_LISTED)) {
5044
+ if (f.isFile() && f.name.endsWith(".md")) names.push(path10.join(agentsDir, "progress", f.name));
5045
+ }
5046
+ const realRoot = await realpathSafe(root);
5047
+ if (!realRoot) continue;
5048
+ const found = [];
5049
+ for (const file of names) {
5050
+ const st = await statSafe(file);
5051
+ if (!st || !st.isFile()) continue;
5052
+ const real = await realpathSafe(file);
5053
+ if (!real || !pathWithin(real, realRoot)) continue;
5054
+ found.push({ file, root, st });
4851
5055
  }
5056
+ found.sort((a, b) => b.st.mtimeMs - a.st.mtimeMs);
5057
+ files.push(...found.slice(0, MAX_PROGRESS_FILES));
4852
5058
  }
4853
5059
  const out = [];
4854
5060
  const seen = /* @__PURE__ */ new Set();
4855
- for (const { file, root } of files) {
4856
- const st = await statSafe(file);
4857
- if (!st || !st.isFile()) continue;
5061
+ for (const { file, root, st } of files) {
4858
5062
  seen.add(file);
4859
5063
  let entry = this.cache.get(file);
4860
5064
  if (!entry || entry.mtimeMs !== st.mtimeMs) {
@@ -4929,16 +5133,43 @@ function createDefaultAdapters(opts = {}) {
4929
5133
  ];
4930
5134
  }
4931
5135
  var sameProject = (a, b) => !!a && !!b && (pathWithin(a, b) || pathWithin(b, a));
5136
+ function cleanSession(s) {
5137
+ const out = cleanFields(s, { title: 500, agentLabel: 60, model: 80, agentVersion: 40, statusDetail: 500 });
5138
+ const tasks = s.tasks.map((t) => cleanFields(t, { title: 500, activeTitle: 500, group: 200 }));
5139
+ const activity = s.activity && cleanFields(s.activity, { label: 200, detail: 500 });
5140
+ const recent = s.recent?.map((a) => cleanFields(a, { label: 200, detail: 500 }));
5141
+ const loop = s.loop && cleanFields(s.loop, { label: 200, detail: 500 });
5142
+ const trouble = s.trouble && cleanFields(s.trouble, { message: 500 });
5143
+ const pulse = s.pulse && cleanFields(s.pulse, { label: 200, detail: 500 });
5144
+ const rateLimits = s.rateLimits?.map((w) => cleanFields(w, { label: 40 }));
5145
+ 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]);
5146
+ if (!changed) return s;
5147
+ return {
5148
+ ...out,
5149
+ tasks,
5150
+ ...activity && { activity },
5151
+ ...recent && { recent },
5152
+ ...loop && { loop },
5153
+ ...trouble && { trouble },
5154
+ ...pulse && { pulse },
5155
+ ...rateLimits && { rateLimits }
5156
+ };
5157
+ }
5158
+ function cleanLimits(l) {
5159
+ const agentLabel = cleanText(l.agentLabel, 60);
5160
+ const windows = l.windows.map((w) => cleanFields(w, { label: 40 }));
5161
+ return agentLabel === l.agentLabel && windows.every((w, i) => w === l.windows[i]) ? l : { ...l, agentLabel, windows };
5162
+ }
4932
5163
  function mergeProgressFiles(sessions) {
4933
5164
  const native = sessions.filter((s) => s.agent !== "progress-file");
4934
5165
  const out = [...native];
4935
5166
  for (const pf of sessions) {
4936
5167
  if (pf.agent !== "progress-file") continue;
4937
- const label = pf.agentLabel.toLowerCase();
5168
+ const label = pf.agentLabel.trim().toLowerCase();
4938
5169
  const match = native.filter((n) => {
4939
5170
  const name = n.agentLabel.toLowerCase();
4940
5171
  const short = name.split(" ")[0];
4941
- return (label.includes(short) || name.includes(label)) && sameProject(n.projectPath, pf.projectPath);
5172
+ return (label === name || label === short) && sameProject(n.projectPath, pf.projectPath);
4942
5173
  }).sort((a, b) => b.updatedAt - a.updatedAt)[0];
4943
5174
  if (!match) {
4944
5175
  out.push(pf);
@@ -4989,8 +5220,9 @@ var Engine = class {
4989
5220
  workspaceRoots: opts.workspaceRoots ?? [],
4990
5221
  pricing: opts.pricing ?? new Pricing(),
4991
5222
  liveDir: opts.liveDir ?? defaultLiveDir(home),
4992
- log: opts.log ?? (() => {
4993
- })
5223
+ // Messages can quote a broken file (a parser's error does): keep its escapes out of a terminal.
5224
+ log: opts.log ? (m) => opts.log(cleanText(m, 2e3)) : () => {
5225
+ }
4994
5226
  };
4995
5227
  }
4996
5228
  get snapshot() {
@@ -5033,7 +5265,11 @@ var Engine = class {
5033
5265
  }
5034
5266
  async loop() {
5035
5267
  if (this.stopped) return;
5036
- await this.tick();
5268
+ try {
5269
+ await this.tick();
5270
+ } catch (err) {
5271
+ this.ctx.log(`tick failed: ${err instanceof Error ? err.message : String(err)}`);
5272
+ }
5037
5273
  if (this.stopped) return;
5038
5274
  this.timer = setTimeout(() => void this.loop(), this.intervalMs);
5039
5275
  }
@@ -5052,17 +5288,18 @@ var Engine = class {
5052
5288
  const l = a.limits?.(this.ctx);
5053
5289
  if (l?.windows.length) limits.push(l);
5054
5290
  } catch (err) {
5055
- const message = err instanceof Error ? err.message : String(err);
5291
+ const message = cleanText(err instanceof Error ? err.message : String(err), 500);
5056
5292
  errors.push({ agent: a.id, message });
5057
5293
  this.ctx.log(`[${a.id}] ${message}`);
5058
5294
  }
5059
5295
  }
5060
- const merged = mergeProgressFiles(sessions);
5296
+ const merged = mergeProgressFiles(sessions).map(cleanSession);
5297
+ const shown = limits.map(cleanLimits);
5061
5298
  sortSessions(merged);
5062
- const signature = JSON.stringify([merged, errors, limits]);
5299
+ const signature = JSON.stringify([merged, errors, shown]);
5063
5300
  if (signature !== this.lastSignature) {
5064
5301
  this.lastSignature = signature;
5065
- this.current = { generatedAt: this.ctx.now(), sessions: merged, errors, ...limits.length ? { limits } : {} };
5302
+ this.current = { generatedAt: this.ctx.now(), sessions: merged, errors, ...shown.length ? { limits: shown } : {} };
5066
5303
  for (const l of this.listeners) {
5067
5304
  try {
5068
5305
  l(this.current);
@@ -5079,9 +5316,46 @@ var Engine = class {
5079
5316
  };
5080
5317
 
5081
5318
  // ../core/src/hooks/hub.ts
5082
- import { promises as fsp4 } from "node:fs";
5319
+ import { promises as fsp6 } from "node:fs";
5083
5320
  import http from "node:http";
5084
5321
  import path12 from "node:path";
5322
+
5323
+ // ../core/src/util/files.ts
5324
+ import { randomBytes } from "node:crypto";
5325
+ import { promises as fsp5 } from "node:fs";
5326
+ async function writeFileSafely(file, text, mode) {
5327
+ let current;
5328
+ try {
5329
+ const st = await fsp5.lstat(file);
5330
+ current = { link: st.isSymbolicLink(), mode: st.mode & 511 };
5331
+ } catch {
5332
+ }
5333
+ if (current?.link) {
5334
+ await fsp5.writeFile(file, text);
5335
+ return;
5336
+ }
5337
+ const tmp = `${file}.kvali-${process.pid}-${randomBytes(4).toString("hex")}.tmp`;
5338
+ try {
5339
+ await fsp5.writeFile(tmp, text, { mode: mode ?? current?.mode ?? 420, flag: "wx" });
5340
+ if (current) await fsp5.chmod(tmp, mode ?? current.mode);
5341
+ await fsp5.rename(tmp, file);
5342
+ } catch (err) {
5343
+ await fsp5.rm(tmp, { force: true }).catch(() => void 0);
5344
+ throw err;
5345
+ }
5346
+ }
5347
+ function trimTrailingNewlines(text) {
5348
+ let end2 = text.length;
5349
+ while (end2 > 0 && (text[end2 - 1] === "\n" || text[end2 - 1] === "\r")) end2 -= 1;
5350
+ return text.slice(0, end2);
5351
+ }
5352
+ function trimLeadingNewlines(text) {
5353
+ let start = 0;
5354
+ while (start < text.length && (text[start] === "\n" || text[start] === "\r")) start += 1;
5355
+ return text.slice(start);
5356
+ }
5357
+
5358
+ // ../core/src/hooks/hub.ts
5085
5359
  var DEFAULT_HOOK_PORT = 47821;
5086
5360
  var MAX_BODY = 1 << 20;
5087
5361
  var SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
@@ -5137,6 +5411,10 @@ var HookHub = class {
5137
5411
  tryListen() {
5138
5412
  if (this.disposed) return;
5139
5413
  const server = http.createServer((req, res) => void this.handle(req, res));
5414
+ server.headersTimeout = 5e3;
5415
+ server.requestTimeout = 1e4;
5416
+ server.keepAliveTimeout = 2e3;
5417
+ server.maxConnections = 64;
5140
5418
  server.on("error", (err) => {
5141
5419
  server.close();
5142
5420
  this.setHub(false);
@@ -5159,8 +5437,16 @@ var HookHub = class {
5159
5437
  const port = this.server?.address()?.port ?? this.port;
5160
5438
  return host === `127.0.0.1:${port}` || host === `localhost:${port}` || host === `[::1]:${port}`;
5161
5439
  }
5440
+ /**
5441
+ * Browsers name the page a request comes from (`Origin`, `Sec-Fetch-Site`), even for requests a
5442
+ * page may send to another site without asking (a form post, `fetch` with `no-cors`). Hooks run
5443
+ * curl, which sends neither (nor does Node's `fetch`).
5444
+ */
5445
+ fromBrowser(req) {
5446
+ return req.headers.origin !== void 0 || req.headers["sec-fetch-site"] !== void 0;
5447
+ }
5162
5448
  async handle(req, res) {
5163
- if (!this.localHost(req)) {
5449
+ if (!this.localHost(req) || this.fromBrowser(req)) {
5164
5450
  res.writeHead(403).end();
5165
5451
  return;
5166
5452
  }
@@ -5171,8 +5457,8 @@ var HookHub = class {
5171
5457
  return;
5172
5458
  }
5173
5459
  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")) {
5460
+ const type = String(req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
5461
+ if (req.method !== "POST" || !m || !AGENTS.has(m[1]) || type !== "application/json") {
5176
5462
  res.writeHead(404).end();
5177
5463
  return;
5178
5464
  }
@@ -5207,23 +5493,20 @@ var HookHub = class {
5207
5493
  }
5208
5494
  async store(agent, ev) {
5209
5495
  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);
5496
+ await fsp6.mkdir(dir, { recursive: true, mode: 448 });
5497
+ await writeFileSafely(path12.join(dir, `${ev.sessionId}.json`), JSON.stringify(ev), 384);
5215
5498
  }
5216
5499
  };
5217
5500
 
5218
5501
  // ../core/src/hooks/claude-install.ts
5219
- import { promises as fsp6 } from "node:fs";
5502
+ import { promises as fsp8 } from "node:fs";
5220
5503
  import os2 from "node:os";
5221
5504
  import path14 from "node:path";
5222
5505
 
5223
5506
  // ../core/src/hooks/claude-plugin.ts
5224
5507
  import { execFile } from "node:child_process";
5225
5508
  import { createHash } from "node:crypto";
5226
- import { constants as fsc, promises as fsp5 } from "node:fs";
5509
+ import { constants as fsc, promises as fsp7 } from "node:fs";
5227
5510
  import path13 from "node:path";
5228
5511
  var CLAUDE_PLUGIN_ID = "kvali@kvali";
5229
5512
  var CLAUDE_MARKETPLACE = "kvali";
@@ -5233,7 +5516,7 @@ async function filesUnder(dir, base = dir) {
5233
5516
  const out = [];
5234
5517
  let entries;
5235
5518
  try {
5236
- entries = await fsp5.readdir(dir, { withFileTypes: true });
5519
+ entries = await fsp7.readdir(dir, { withFileTypes: true });
5237
5520
  } catch {
5238
5521
  return out;
5239
5522
  }
@@ -5253,14 +5536,14 @@ async function pluginFingerprint(dir) {
5253
5536
  for (const f of files) {
5254
5537
  h.update(f.split(path13.sep).join("/"));
5255
5538
  h.update("\0");
5256
- h.update(await fsp5.readFile(path13.join(dir, f)));
5539
+ h.update(await fsp7.readFile(path13.join(dir, f)));
5257
5540
  h.update("\0");
5258
5541
  }
5259
5542
  return h.digest("hex");
5260
5543
  }
5261
5544
  async function pluginVersion(dir) {
5262
5545
  try {
5263
- const v = JSON.parse(await fsp5.readFile(path13.join(dir, ".claude-plugin", "plugin.json"), "utf8")).version;
5546
+ const v = JSON.parse(await fsp7.readFile(path13.join(dir, ".claude-plugin", "plugin.json"), "utf8")).version;
5264
5547
  return typeof v === "string" ? v : void 0;
5265
5548
  } catch {
5266
5549
  return void 0;
@@ -5280,11 +5563,11 @@ async function syncClaudePlugin(bundledDir, home) {
5280
5563
  const [mine, theirs] = await Promise.all([pluginVersion(bundledDir), pluginVersion(target)]);
5281
5564
  if (mine && theirs && compareVersions(mine, theirs) < 0) return false;
5282
5565
  const next = `${target}.next`;
5283
- await fsp5.rm(next, { recursive: true, force: true });
5284
- await fsp5.mkdir(path13.dirname(target), { recursive: true });
5285
- await fsp5.cp(bundledDir, next, { recursive: true });
5286
- await fsp5.rm(target, { recursive: true, force: true });
5287
- await fsp5.rename(next, target);
5566
+ await fsp7.rm(next, { recursive: true, force: true });
5567
+ await fsp7.mkdir(path13.dirname(target), { recursive: true });
5568
+ await fsp7.cp(bundledDir, next, { recursive: true });
5569
+ await fsp7.rm(target, { recursive: true, force: true });
5570
+ await fsp7.rename(next, target);
5288
5571
  return true;
5289
5572
  }
5290
5573
  async function claudeExtensionDirs(home) {
@@ -5295,7 +5578,7 @@ async function claudeExtensionDirs(home) {
5295
5578
  for (const root of roots) {
5296
5579
  let names = [];
5297
5580
  try {
5298
- names = await fsp5.readdir(root);
5581
+ names = await fsp7.readdir(root);
5299
5582
  } catch {
5300
5583
  continue;
5301
5584
  }
@@ -5316,7 +5599,7 @@ async function findClaudeBinary(opts) {
5316
5599
  const bin = path13.join(d, "resources", "native-binary");
5317
5600
  let inside = [];
5318
5601
  try {
5319
- inside = await fsp5.readdir(bin);
5602
+ inside = await fsp7.readdir(bin);
5320
5603
  } catch {
5321
5604
  continue;
5322
5605
  }
@@ -5328,8 +5611,8 @@ async function findClaudeBinary(opts) {
5328
5611
  if (!win) candidates.push("/opt/homebrew/bin/claude", "/usr/local/bin/claude");
5329
5612
  for (const c of candidates) {
5330
5613
  try {
5331
- await fsp5.access(c, win ? fsc.F_OK : fsc.X_OK);
5332
- if ((await fsp5.stat(c)).isFile()) return c;
5614
+ await fsp7.access(c, win ? fsc.F_OK : fsc.X_OK);
5615
+ if ((await fsp7.stat(c)).isFile()) return c;
5333
5616
  } catch {
5334
5617
  }
5335
5618
  }
@@ -5382,7 +5665,7 @@ async function installClaudePlugin(bin, dir, env) {
5382
5665
  }
5383
5666
  async function claudePluginEnabled(settingsFile) {
5384
5667
  try {
5385
- const s = JSON.parse(await fsp5.readFile(settingsFile, "utf8"));
5668
+ const s = JSON.parse(await fsp7.readFile(settingsFile, "utf8"));
5386
5669
  return s?.enabledPlugins?.[CLAUDE_PLUGIN_ID] === true;
5387
5670
  } catch {
5388
5671
  return false;
@@ -5390,15 +5673,15 @@ async function claudePluginEnabled(settingsFile) {
5390
5673
  }
5391
5674
  async function readKvaliState(home) {
5392
5675
  try {
5393
- return JSON.parse(await fsp5.readFile(stateFile(home), "utf8")) ?? {};
5676
+ return JSON.parse(await fsp7.readFile(stateFile(home), "utf8")) ?? {};
5394
5677
  } catch {
5395
5678
  return {};
5396
5679
  }
5397
5680
  }
5398
5681
  async function writeKvaliState(home, patch) {
5399
5682
  const next = { ...await readKvaliState(home), ...patch };
5400
- await fsp5.mkdir(path13.dirname(stateFile(home)), { recursive: true });
5401
- await fsp5.writeFile(stateFile(home), `${JSON.stringify(next, null, 2)}
5683
+ await fsp7.mkdir(path13.dirname(stateFile(home)), { recursive: true, mode: 448 });
5684
+ await writeFileSafely(stateFile(home), `${JSON.stringify(next, null, 2)}
5402
5685
  `);
5403
5686
  }
5404
5687
  async function removeClaudePlugin(opts) {
@@ -5415,7 +5698,7 @@ async function removeClaudePlugin(opts) {
5415
5698
  }
5416
5699
  } else {
5417
5700
  try {
5418
- const raw = await fsp5.readFile(opts.settingsFile, "utf8");
5701
+ const raw = await fsp7.readFile(opts.settingsFile, "utf8");
5419
5702
  const s = JSON.parse(raw);
5420
5703
  let changed = false;
5421
5704
  if (s.enabledPlugins && CLAUDE_PLUGIN_ID in s.enabledPlugins) {
@@ -5427,12 +5710,12 @@ async function removeClaudePlugin(opts) {
5427
5710
  delete s.extraKnownMarketplaces[CLAUDE_MARKETPLACE];
5428
5711
  changed = true;
5429
5712
  }
5430
- if (changed) await fsp5.writeFile(opts.settingsFile, `${JSON.stringify(s, null, 2)}
5713
+ if (changed) await fsp7.writeFile(opts.settingsFile, `${JSON.stringify(s, null, 2)}
5431
5714
  `);
5432
5715
  } catch {
5433
5716
  }
5434
5717
  }
5435
- await fsp5.rm(dir, { recursive: true, force: true });
5718
+ await fsp7.rm(dir, { recursive: true, force: true });
5436
5719
  await writeKvaliState(opts.home, { claudePlugin: false });
5437
5720
  return true;
5438
5721
  }
@@ -5460,7 +5743,7 @@ function hookEntry(spec, port) {
5460
5743
  async function readSettings(file) {
5461
5744
  let text;
5462
5745
  try {
5463
- text = await fsp6.readFile(file, "utf8");
5746
+ text = await fsp8.readFile(file, "utf8");
5464
5747
  } catch (err) {
5465
5748
  if (err.code === "ENOENT") return {};
5466
5749
  throw err;
@@ -5517,13 +5800,13 @@ async function claudeHooksStatus(file = claudeSettingsPath(), port = DEFAULT_HOO
5517
5800
  return current === CLAUDE_HOOKS.length && total === CLAUDE_HOOKS.length ? "installed" : "outdated";
5518
5801
  }
5519
5802
  async function writeWithBackup(file, before, settings) {
5520
- await fsp6.mkdir(path14.dirname(file), { recursive: true });
5803
+ await fsp8.mkdir(path14.dirname(file), { recursive: true });
5521
5804
  let backup;
5522
5805
  if (before !== void 0) {
5523
5806
  backup = `${file}.kvali-backup`;
5524
- await fsp6.writeFile(backup, before);
5807
+ await writeFileSafely(backup, before, 384);
5525
5808
  }
5526
- await fsp6.writeFile(file, JSON.stringify(settings, null, 2) + "\n");
5809
+ await writeFileSafely(file, JSON.stringify(settings, null, 2) + "\n");
5527
5810
  return backup;
5528
5811
  }
5529
5812
  function canonical(v) {
@@ -5533,7 +5816,7 @@ function canonical(v) {
5533
5816
  );
5534
5817
  }
5535
5818
  async function installClaudeHooks(file = claudeSettingsPath(), port = DEFAULT_HOOK_PORT) {
5536
- const before = await fsp6.readFile(file, "utf8").catch(() => void 0);
5819
+ const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
5537
5820
  const current = await readSettings(file);
5538
5821
  const settings = withoutKvali(current);
5539
5822
  settings.hooks = settings.hooks && typeof settings.hooks === "object" ? settings.hooks : {};
@@ -5549,7 +5832,7 @@ function envOf(settings) {
5549
5832
  return settings.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : void 0;
5550
5833
  }
5551
5834
  async function enableClaudeTodoTools(file, home) {
5552
- const before = await fsp6.readFile(file, "utf8").catch(() => void 0);
5835
+ const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
5553
5836
  const settings = await readSettings(file);
5554
5837
  const env = envOf(settings);
5555
5838
  if (env && CLAUDE_TODO_TOOLS_ENV in env) return { changed: false };
@@ -5560,7 +5843,7 @@ async function enableClaudeTodoTools(file, home) {
5560
5843
  }
5561
5844
  async function disableClaudeTodoTools(file, home) {
5562
5845
  if (!(await readKvaliState(home)).claudeTodoTools) return { changed: false };
5563
- const before = await fsp6.readFile(file, "utf8").catch(() => void 0);
5846
+ const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
5564
5847
  let changed = false;
5565
5848
  if (before !== void 0) {
5566
5849
  const settings = await readSettings(file);
@@ -5577,7 +5860,7 @@ async function disableClaudeTodoTools(file, home) {
5577
5860
  return { changed };
5578
5861
  }
5579
5862
  async function uninstallClaudeHooks(file = claudeSettingsPath()) {
5580
- const before = await fsp6.readFile(file, "utf8").catch(() => void 0);
5863
+ const before = await fsp8.readFile(file, "utf8").catch(() => void 0);
5581
5864
  if (before === void 0) return { changed: false };
5582
5865
  const settings = await readSettings(file);
5583
5866
  const next = withoutKvali(settings);
@@ -5586,7 +5869,7 @@ async function uninstallClaudeHooks(file = claudeSettingsPath()) {
5586
5869
  }
5587
5870
 
5588
5871
  // ../core/src/protocol.ts
5589
- import { promises as fsp7 } from "node:fs";
5872
+ import { promises as fsp9 } from "node:fs";
5590
5873
  import path15 from "node:path";
5591
5874
  var PROGRESS_PROTOCOL_MARKER = "<!-- kvali:progress-protocol v2 -->";
5592
5875
  function progressProtocolSnippet() {
@@ -5622,18 +5905,41 @@ For any task that takes more than two steps, create a task list with your built-
5622
5905
  <!-- /kvali:plan-rule -->
5623
5906
  `;
5624
5907
  }
5908
+ function findBlock(text, name) {
5909
+ const open = new RegExp(`^<!-- kvali:${name} v\\d+ -->$`);
5910
+ const close = `<!-- /kvali:${name} -->`;
5911
+ let fence;
5912
+ let start;
5913
+ let pos = 0;
5914
+ for (const raw of text.split("\n")) {
5915
+ const at = pos;
5916
+ pos += raw.length + 1;
5917
+ const line = (raw.endsWith("\r") ? raw.slice(0, -1) : raw).trimEnd();
5918
+ const f = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
5919
+ if (f) {
5920
+ const mark = f[1];
5921
+ if (!fence) fence = { ch: mark[0], len: mark.length };
5922
+ else if (mark[0] === fence.ch && mark.length >= fence.len && f[2].trim() === "") fence = void 0;
5923
+ continue;
5924
+ }
5925
+ if (fence) continue;
5926
+ if (start === void 0) {
5927
+ if (open.test(line)) start = at;
5928
+ } else if (line === close) {
5929
+ return { start, end: at + close.length };
5930
+ }
5931
+ }
5932
+ return start === void 0 ? void 0 : { start };
5933
+ }
5625
5934
  function withBlock(text, name, snippet) {
5626
5935
  if (text === void 0 || text === "") return { text: snippet, result: text === void 0 ? "created" : "added" };
5627
- const open = new RegExp(`<!-- kvali:${name} v\\d+ -->`).exec(text);
5628
- if (open) {
5629
- const close = `<!-- /kvali:${name} -->`;
5630
- const closeAt = text.indexOf(close, open.index);
5631
- if (closeAt === -1) return { text, result: "exists" };
5632
- const end2 = closeAt + close.length;
5936
+ const found = findBlock(text, name);
5937
+ if (found) {
5938
+ if (found.end === void 0) return { text, result: "exists" };
5633
5939
  const crlf = text.includes("\r\n");
5634
5940
  const block = snippet.trimEnd();
5635
- if (text.slice(open.index, end2).replace(/\r\n/g, "\n") === block) return { text, result: "exists" };
5636
- return { text: text.slice(0, open.index) + (crlf ? block.replace(/\n/g, "\r\n") : block) + text.slice(end2), result: "updated" };
5941
+ if (text.slice(found.start, found.end).replace(/\r\n/g, "\n") === block) return { text, result: "exists" };
5942
+ return { text: text.slice(0, found.start) + (crlf ? block.replace(/\n/g, "\r\n") : block) + text.slice(found.end), result: "updated" };
5637
5943
  }
5638
5944
  const sep = text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
5639
5945
  return { text: `${text}${sep}${snippet}`, result: "added" };
@@ -5648,30 +5954,36 @@ function globalInstructionFiles(home, env = {}) {
5648
5954
  { id: "gemini", agent: "Gemini CLI / Antigravity", dir: gemini, file: path15.join(gemini, "GEMINI.md") }
5649
5955
  ];
5650
5956
  }
5651
- var PLAN_RULE_END = "<!-- /kvali:plan-rule -->";
5957
+ function withoutBlock(text, name) {
5958
+ const found = findBlock(text, name);
5959
+ if (!found || found.end === void 0) return void 0;
5960
+ const nl = text.includes("\r\n") ? "\r\n" : "\n";
5961
+ const before = trimTrailingNewlines(text.slice(0, found.start));
5962
+ const after = trimLeadingNewlines(text.slice(found.end));
5963
+ if (!before) return after;
5964
+ if (!after) return `${before}${nl}`;
5965
+ return `${before}${nl}${nl}${after}`;
5966
+ }
5652
5967
  async function removeGlobalPlanRule(home, env = {}) {
5653
5968
  const changed = [];
5654
5969
  for (const target of globalInstructionFiles(home, env)) {
5655
5970
  let text;
5656
5971
  try {
5657
- text = await fsp7.readFile(target.file, "utf8");
5972
+ text = await fsp9.readFile(target.file, "utf8");
5658
5973
  } catch {
5659
5974
  continue;
5660
5975
  }
5661
- const start = text.search(/<!-- kvali:plan-rule v\d+ -->/);
5662
- if (start === -1) continue;
5663
- const endAt = text.indexOf(PLAN_RULE_END, start);
5664
- const end2 = endAt === -1 ? text.length : endAt + PLAN_RULE_END.length;
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);
5976
+ const next = withoutBlock(text, "plan-rule");
5977
+ if (next === void 0) continue;
5978
+ if (next.trim() === "") await fsp9.unlink(target.file);
5979
+ else await writeFileSafely(target.file, next);
5668
5980
  changed.push(target.file);
5669
5981
  }
5670
5982
  return changed;
5671
5983
  }
5672
5984
  async function readOptional(file) {
5673
5985
  try {
5674
- return await fsp7.readFile(file, "utf8");
5986
+ return await fsp9.readFile(file, "utf8");
5675
5987
  } catch {
5676
5988
  return void 0;
5677
5989
  }
@@ -5681,13 +5993,13 @@ async function addGlobalPlanRule(home, env = {}, only) {
5681
5993
  for (const target of globalInstructionFiles(home, env)) {
5682
5994
  if (only && !only.includes(target.id)) continue;
5683
5995
  try {
5684
- const st = await fsp7.stat(target.dir);
5996
+ const st = await fsp9.stat(target.dir);
5685
5997
  if (!st.isDirectory()) continue;
5686
5998
  } catch {
5687
5999
  continue;
5688
6000
  }
5689
6001
  const next = withBlock(await readOptional(target.file), "plan-rule", planRuleSnippet());
5690
- if (next.result !== "exists") await fsp7.writeFile(target.file, next.text);
6002
+ if (next.result !== "exists") await writeFileSafely(target.file, next.text);
5691
6003
  out.push({ agent: target.agent, file: target.file, result: next.result });
5692
6004
  }
5693
6005
  return out;
@@ -5696,7 +6008,7 @@ async function addProgressProtocol(root) {
5696
6008
  const file = path15.join(root, "AGENTS.md");
5697
6009
  const current = await readOptional(file);
5698
6010
  const next = withBlock(current ?? "# AGENTS.md\n\n", "progress-protocol", progressProtocolSnippet());
5699
- if (next.result !== "exists") await fsp7.writeFile(file, next.text);
6011
+ if (next.result !== "exists") await writeFileSafely(file, next.text);
5700
6012
  return { file, result: current === void 0 ? "created" : next.result };
5701
6013
  }
5702
6014
 
@@ -5719,11 +6031,11 @@ function claudeHookReply(ev, session, pluginRuns = false) {
5719
6031
  }
5720
6032
 
5721
6033
  // ../core/src/setup.ts
5722
- import { promises as fsp8 } from "node:fs";
6034
+ import { promises as fsp10 } from "node:fs";
5723
6035
  import path17 from "node:path";
5724
6036
  async function isDir(p2) {
5725
6037
  try {
5726
- return (await fsp8.stat(p2)).isDirectory();
6038
+ return (await fsp10.stat(p2)).isDirectory();
5727
6039
  } catch {
5728
6040
  return false;
5729
6041
  }
@@ -5793,8 +6105,8 @@ async function removeSetup(home, env = {}, opts = {}) {
5793
6105
  }
5794
6106
 
5795
6107
  // ../core/src/phone.ts
5796
- import { randomBytes } from "node:crypto";
5797
- import { promises as fsp9 } from "node:fs";
6108
+ import { randomBytes as randomBytes2, randomInt } from "node:crypto";
6109
+ import { promises as fsp11 } from "node:fs";
5798
6110
  import path18 from "node:path";
5799
6111
  var PHONE_EVENTS = ["needs-you", "done", "steps", "actions", "error", "stuck", "limits"];
5800
6112
  var DEFAULT_PHONE_EVENTS = ["needs-you", "done", "error", "stuck", "steps", "limits"];
@@ -5843,7 +6155,7 @@ function normalizePhoneConfig(raw) {
5843
6155
  }
5844
6156
  async function readPhoneConfig(home) {
5845
6157
  try {
5846
- const all = JSON.parse(await fsp9.readFile(kvaliConfigFile(home), "utf8"));
6158
+ const all = JSON.parse(await fsp11.readFile(kvaliConfigFile(home), "utf8"));
5847
6159
  return normalizePhoneConfig(all?.phone);
5848
6160
  } catch {
5849
6161
  return void 0;
@@ -5853,7 +6165,7 @@ async function writePhoneConfig(home, cfg) {
5853
6165
  const file = kvaliConfigFile(home);
5854
6166
  let all = {};
5855
6167
  try {
5856
- const parsed = JSON.parse(await fsp9.readFile(file, "utf8"));
6168
+ const parsed = JSON.parse(await fsp11.readFile(file, "utf8"));
5857
6169
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) all = parsed;
5858
6170
  } catch {
5859
6171
  }
@@ -5870,15 +6182,19 @@ async function writePhoneConfig(home, cfg) {
5870
6182
  doneAfter: cfg.doneAfterSec ?? DEFAULT_DONE_AFTER_SEC
5871
6183
  };
5872
6184
  else delete all.phone;
5873
- await fsp9.mkdir(path18.dirname(file), { recursive: true });
5874
- await fsp9.writeFile(file, `${JSON.stringify(all, null, 2)}
5875
- `, { mode: 384 });
5876
- await fsp9.chmod(file, 384).catch(() => void 0);
6185
+ await fsp11.mkdir(path18.dirname(file), { recursive: true, mode: 448 });
6186
+ await writeFileSafely(file, `${JSON.stringify(all, null, 2)}
6187
+ `, 384);
6188
+ }
6189
+ async function secureKvaliHome(home, create = false) {
6190
+ const dir = path18.dirname(kvaliConfigFile(home));
6191
+ if (create) await fsp11.mkdir(dir, { recursive: true, mode: 448 }).catch(() => void 0);
6192
+ await fsp11.chmod(dir, 448).catch(() => void 0);
5877
6193
  }
5878
6194
  function newTopic() {
5879
6195
  const alphabet = "abcdefghijkmnpqrstuvwxyz23456789";
5880
6196
  let s = "";
5881
- for (const b of randomBytes(16)) s += alphabet[b % 32];
6197
+ for (const b of randomBytes2(16)) s += alphabet[b % 32];
5882
6198
  return `kvali-${s}`;
5883
6199
  }
5884
6200
  function newPhoneConfig(server = DEFAULT_NTFY_SERVER) {
@@ -6073,8 +6389,22 @@ async function telegramBot(token, fetchImpl = fetch) {
6073
6389
  return { ok: false, error: unreachable(err, "api.telegram.org") };
6074
6390
  }
6075
6391
  }
6076
- async function telegramFindChat(token, waitMs = 12e4, fetchImpl = fetch, signal) {
6392
+ function telegramPairCode() {
6393
+ return String(randomInt(1e5, 1e6));
6394
+ }
6395
+ function telegramStartLink(bot, code) {
6396
+ return `https://t.me/${encodeURIComponent(bot)}?start=${code}`;
6397
+ }
6398
+ function chatName(c) {
6399
+ const full = [c.first_name, c.last_name].filter((x) => typeof x === "string" && !!x).join(" ");
6400
+ const user = typeof c.username === "string" && c.username ? `@${c.username}` : void 0;
6401
+ const name = full && user ? `${full} (${user})` : full || user;
6402
+ return name ? cleanText(name, 80) : void 0;
6403
+ }
6404
+ async function telegramFindChat(token, code, waitMs = 12e4, fetchImpl = fetch, signal) {
6405
+ if (!/^\d{6}$/.test(code)) return void 0;
6077
6406
  const until = Date.now() + waitMs;
6407
+ const hasCode = new RegExp(`(^|\\D)${code}(\\D|$)`);
6078
6408
  let offset;
6079
6409
  while (Date.now() < until && !signal?.aborted) {
6080
6410
  const timeout = Math.max(1, Math.min(25, Math.round((until - Date.now()) / 1e3)));
@@ -6085,16 +6415,18 @@ async function telegramFindChat(token, waitMs = 12e4, fetchImpl = fetch, signal)
6085
6415
  signal: AbortSignal.timeout((timeout + 10) * 1e3)
6086
6416
  });
6087
6417
  if (!res.ok) return void 0;
6088
- updates = (await res.json()).result ?? [];
6418
+ const result = (await res.json()).result;
6419
+ updates = Array.isArray(result) ? result.filter((u) => typeof u?.update_id === "number") : [];
6089
6420
  } catch {
6090
6421
  await new Promise((r) => setTimeout(r, 2e3));
6091
6422
  continue;
6092
6423
  }
6093
- const chat = [...updates].reverse().find((u) => u.message?.chat?.type === "private" && typeof u.message.chat.id === "number")?.message?.chat?.id;
6424
+ 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
6425
  if (updates.length) offset = updates[updates.length - 1].update_id + 1;
6095
- if (chat !== void 0) {
6426
+ if (hit) {
6096
6427
  await fetchImpl(`https://api.telegram.org/bot${token}/getUpdates?timeout=0&offset=${offset}`, { signal: AbortSignal.timeout(1e4) }).catch(() => void 0);
6097
- return String(chat);
6428
+ const chat = hit.message.chat;
6429
+ return { id: String(chat.id), name: chatName(chat) };
6098
6430
  }
6099
6431
  if (Date.now() - askedAt < 1e3) await new Promise((r) => setTimeout(r, 1e3));
6100
6432
  }
@@ -6124,8 +6456,34 @@ function clip(text, max) {
6124
6456
  const one = text.replace(/\s+/g, " ").trim();
6125
6457
  return one.length <= max ? one : `${one.slice(0, max - 1).trimEnd()}\u2026`;
6126
6458
  }
6459
+ var APPROVAL_KINDS = lookupTable({
6460
+ run: "run a command",
6461
+ bash: "run a command",
6462
+ shell: "run a command",
6463
+ command: "run a command",
6464
+ powershell: "run a command",
6465
+ edit: "edit a file",
6466
+ write: "edit a file",
6467
+ patch: "edit a file",
6468
+ read: "read a file",
6469
+ fetch: "open a web page",
6470
+ webfetch: "open a web page"
6471
+ });
6472
+ function phoneStatus(detail) {
6473
+ if (detail === void 0) return void 0;
6474
+ const m = /^Needs approval:[ \t]*([A-Za-z][\w-]{0,40})?/.exec(detail);
6475
+ if (!m) return detail;
6476
+ const word = m[1];
6477
+ if (!word) return "Needs approval";
6478
+ return `Needs approval: ${APPROVAL_KINDS[word] ?? word}`;
6479
+ }
6480
+ function pushAgentLabel(s) {
6481
+ if (s.agent !== "progress-file") return s.agentLabel;
6482
+ const name = s.agentLabel.trim();
6483
+ return /^[\p{L}\p{N}][\p{L}\p{N} +_-]{0,23}$/u.test(name) && name.split(/\s+/).length <= 3 ? name : "An agent";
6484
+ }
6127
6485
  function formatPush(kind, s, details, extra = {}) {
6128
- const agent = s.agentLabel;
6486
+ const agent = pushAgentLabel(s);
6129
6487
  const where = details ? ` \xB7 ${projectName(s.projectPath)}` : "";
6130
6488
  const p2 = progressOf(s.tasks);
6131
6489
  const step = currentTask(s.tasks);
@@ -6139,7 +6497,8 @@ function formatPush(kind, s, details, extra = {}) {
6139
6497
  return {
6140
6498
  event: "needs-you",
6141
6499
  title: `${agent} needs you${where}`,
6142
- message: lines(details ? clip(s.statusDetail ?? "Waiting for your answer", 200) : "Waiting for your answer", title, planLine),
6500
+ // A progress file's note is a repository's words, not an agent's question: it stays on the computer.
6501
+ message: lines(details && s.agent !== "progress-file" ? clip(phoneStatus(s.statusDetail) ?? "Waiting for your answer", 200) : "Waiting for your answer", title, planLine),
6143
6502
  priority: 4,
6144
6503
  tags: ["bell"]
6145
6504
  };
@@ -6185,7 +6544,7 @@ function formatPush(kind, s, details, extra = {}) {
6185
6544
  }
6186
6545
  case "loop": {
6187
6546
  const l = s.loop;
6188
- const what = l ? details ? `\u201C${clip(l.detail ?? l.label, 80)}\u201D` : "The same action" : "An action";
6547
+ const what = l ? details ? `\u201C${clip(l.label, 80)}\u201D` : "The same action" : "An action";
6189
6548
  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
6549
  return {
6191
6550
  event: "stuck",
@@ -6445,7 +6804,7 @@ var PhoneNotifier = class {
6445
6804
  const now = Date.now();
6446
6805
  if (!force && now - this.checkedAt < 5e3) return;
6447
6806
  this.checkedAt = now;
6448
- const st = await fsp9.stat(kvaliConfigFile(this.opts.home)).catch(() => void 0);
6807
+ const st = await fsp11.stat(kvaliConfigFile(this.opts.home)).catch(() => void 0);
6449
6808
  const mtime = st?.mtimeMs ?? 0;
6450
6809
  if (!force && mtime === this.mtime) return;
6451
6810
  this.mtime = mtime;
@@ -8185,7 +8544,7 @@ function qrTerminal(text, color = true) {
8185
8544
  }
8186
8545
 
8187
8546
  // src/index.ts
8188
- var VERSION = "0.7.1";
8547
+ var VERSION = "0.7.3";
8189
8548
  function parse(argv) {
8190
8549
  const opts = {
8191
8550
  json: false,
@@ -8223,18 +8582,24 @@ function parse(argv) {
8223
8582
  case "--here":
8224
8583
  opts.project = process2.cwd();
8225
8584
  break;
8226
- case "--window":
8227
- opts.windowHours = Number(next());
8585
+ case "--window": {
8586
+ const hours = Number(next());
8587
+ if (!Number.isFinite(hours) || hours <= 0 || hours > 24 * 365) fail("--window takes a number of hours, e.g. 24");
8588
+ opts.windowHours = hours;
8228
8589
  break;
8590
+ }
8229
8591
  case "--home":
8230
8592
  opts.home = path19.resolve(next());
8231
8593
  break;
8232
8594
  case "--brain-dir":
8233
8595
  opts.brainDirs.push(path19.resolve(next()));
8234
8596
  break;
8235
- case "--port":
8236
- opts.port = Number(next());
8597
+ case "--port": {
8598
+ const port = Number(next());
8599
+ if (!Number.isInteger(port) || port < 1 || port > 65535) fail("--port takes a port number from 1 to 65535");
8600
+ opts.port = port;
8237
8601
  break;
8602
+ }
8238
8603
  case "--no-hub":
8239
8604
  opts.hub = false;
8240
8605
  break;
@@ -8500,6 +8865,7 @@ async function week(opts, svgFile) {
8500
8865
  );
8501
8866
  if (svgFile !== void 0) {
8502
8867
  const file = path19.resolve(svgFile || `kvali-week-${w.days[w.days.length - 1].day}.svg`);
8868
+ if ((await lstat(file).catch(() => void 0))?.isSymbolicLink()) fail(`${file} is a symbolic link; give the card another file name`);
8503
8869
  await writeFile(file, weekSvg(w));
8504
8870
  console.log(`
8505
8871
  Card: ${file} ${c.gray("(1200\xD7630 SVG; open it in a browser to save as PNG)")}`);
@@ -8588,10 +8954,12 @@ async function phoneChannel(which, off, opts) {
8588
8954
  const token = await askSecret(" Token: ");
8589
8955
  const me = await telegramBot(token);
8590
8956
  if (!me.ok) fail(`could not use this bot: ${me.error}`);
8591
- console.log(` 3. Now send any message to @${me.username} (https://t.me/${me.username}). Waiting up to 3 minutes\u2026`);
8592
- const chatId = await telegramFindChat(token, 18e4);
8593
- if (!chatId) fail(`no message reached @${me.username}; run \`kvali phone telegram\` again and write to the bot while Kvali waits`);
8594
- only = { telegram: { token, chatId, bot: me.username } };
8957
+ const code = telegramPairCode();
8958
+ 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`);
8959
+ const chat = await telegramFindChat(token, code, 18e4);
8960
+ if (!chat) fail(`the code did not reach @${me.username}; run \`kvali phone telegram\` again and send it while Kvali waits`);
8961
+ console.log(` Kvali will write to ${c.bold(chat.name ?? "this Telegram chat")} through @${me.username}.`);
8962
+ only = { telegram: { token, chatId: chat.id, bot: me.username } };
8595
8963
  } else {
8596
8964
  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
8965
  const webhook = await askSecret(" Webhook URL: ");
@@ -8663,6 +9031,7 @@ async function phone(sub, opts, arg) {
8663
9031
  }
8664
9032
  async function main() {
8665
9033
  const { cmd, opts } = parse(process2.argv.slice(2));
9034
+ await secureKvaliHome(opts.home);
8666
9035
  if (cmd[0] === "hooks") return hooks(cmd[1], opts);
8667
9036
  if (cmd[0] === "setup") {
8668
9037
  if (cmd[1] === "off") {