veoflow 0.1.1 → 0.1.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/veo.mjs CHANGED
@@ -26,9 +26,9 @@ var __commonJS = (cb, mod) => function __require2() {
26
26
  throw mod = 0, e;
27
27
  }
28
28
  };
29
- var __export = (target, all2) => {
29
+ var __export = (target2, all2) => {
30
30
  for (var name in all2)
31
- __defProp(target, name, { get: all2[name], enumerable: true });
31
+ __defProp(target2, name, { get: all2[name], enumerable: true });
32
32
  };
33
33
  var __copyProps = (to, from, except, desc) => {
34
34
  if (from && typeof from === "object" || typeof from === "function") {
@@ -38,12 +38,12 @@ var __copyProps = (to, from, except, desc) => {
38
38
  }
39
39
  return to;
40
40
  };
41
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
41
+ var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
42
42
  // If the importer is in node compatibility mode or this is not an ESM
43
43
  // file that has been converted to a CommonJS file using a Babel-
44
44
  // compatible transform (i.e. "__esModule" has not been set), then set
45
45
  // "default" to the CommonJS "module.exports" for node compatibility.
46
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
46
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
47
47
  mod
48
48
  ));
49
49
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
@@ -154,6 +154,10 @@ function classify(path) {
154
154
  return "typescript";
155
155
  case "tsx":
156
156
  return "tsx";
157
+ case "vue":
158
+ return "vue";
159
+ case "svelte":
160
+ return "svelte";
157
161
  case "py":
158
162
  return "python";
159
163
  case "go":
@@ -164,6 +168,12 @@ function classify(path) {
164
168
  return null;
165
169
  }
166
170
  }
171
+ function unsupportedLanguage(path) {
172
+ const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
173
+ if (name.endsWith(".component.html")) return "Angular template";
174
+ const dot = name.lastIndexOf(".");
175
+ return dot > 0 ? UNSUPPORTED[name.slice(dot + 1)] ?? null : null;
176
+ }
167
177
  function languageSkip(path, language) {
168
178
  if (/\.d\.[mc]?ts$/i.test(path)) return "declaration-file";
169
179
  return ANALYZED_LANGUAGES.has(language) ? null : "language-not-analyzed";
@@ -180,11 +190,52 @@ function decodeUtf8(bytes) {
180
190
  return null;
181
191
  }
182
192
  }
183
- var ANALYZED_LANGUAGES, utf8;
193
+ var ANALYZED_LANGUAGES, UNSUPPORTED, utf8;
184
194
  var init_classify = __esm({
185
195
  "packages/planner/src/classify.ts"() {
186
196
  "use strict";
187
- ANALYZED_LANGUAGES = /* @__PURE__ */ new Set(["javascript", "jsx", "typescript", "tsx"]);
197
+ ANALYZED_LANGUAGES = /* @__PURE__ */ new Set([
198
+ "javascript",
199
+ "jsx",
200
+ "typescript",
201
+ "tsx",
202
+ "vue",
203
+ "svelte",
204
+ "angular-template"
205
+ ]);
206
+ UNSUPPORTED = {
207
+ java: "Java",
208
+ kt: "Kotlin",
209
+ kts: "Kotlin",
210
+ scala: "Scala",
211
+ groovy: "Groovy",
212
+ cs: "C#",
213
+ vb: "Visual Basic",
214
+ php: "PHP",
215
+ rb: "Ruby",
216
+ swift: "Swift",
217
+ m: "Objective-C or MATLAB",
218
+ mm: "Objective-C++",
219
+ c: "C",
220
+ h: "C/C++ header",
221
+ cc: "C++",
222
+ cpp: "C++",
223
+ cxx: "C++",
224
+ hpp: "C/C++ header",
225
+ hh: "C/C++ header",
226
+ hxx: "C/C++ header",
227
+ dart: "Dart",
228
+ ex: "Elixir",
229
+ exs: "Elixir",
230
+ erl: "Erlang",
231
+ clj: "Clojure",
232
+ cljs: "ClojureScript",
233
+ cljc: "Clojure",
234
+ hs: "Haskell",
235
+ lua: "Lua",
236
+ pl: "Perl",
237
+ astro: "Astro"
238
+ };
188
239
  utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
189
240
  }
190
241
  });
@@ -476,8 +527,55 @@ function planSource(source, options = {}) {
476
527
  }
477
528
  if (!plan.files.some((f) => ANALYZED_LANGUAGES.has(f.language)))
478
529
  plan.notices.push("No JavaScript or TypeScript files were found.");
530
+ const unsupported = unsupportedNotice(plan.unsupported);
531
+ if (unsupported) plan.notices.push(unsupported);
479
532
  return plan;
480
533
  }
534
+ function manifestDir(rel) {
535
+ return rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";
536
+ }
537
+ function dependsOnAngular(text) {
538
+ try {
539
+ const json2 = JSON.parse(text.replace(/^\uFEFF/, ""));
540
+ return ["dependencies", "devDependencies", "peerDependencies"].some(
541
+ (k) => json2[k]?.["@angular/core"] !== void 0
542
+ );
543
+ } catch {
544
+ return false;
545
+ }
546
+ }
547
+ function angularTemplates(htmls, manifests) {
548
+ const angular = new Map([...manifests].map(([dir, text]) => [dir, dependsOnAngular(text)]));
549
+ const root = angular.get("") ?? false;
550
+ const out = /* @__PURE__ */ new Set();
551
+ for (const rel of htmls) {
552
+ let dir = manifestDir(rel);
553
+ let nearest = false;
554
+ for (; ; ) {
555
+ if (angular.has(dir)) {
556
+ nearest = angular.get(dir);
557
+ break;
558
+ }
559
+ if (dir === "") break;
560
+ dir = manifestDir(dir);
561
+ }
562
+ if (nearest || root) out.add(rel);
563
+ }
564
+ return out;
565
+ }
566
+ function unsupportedNotice(unsupported) {
567
+ if (!unsupported.length) return null;
568
+ const files = (n) => `${n.toLocaleString("en-US")} ${n === 1 ? "file" : "files"}`;
569
+ const parts = unsupported.slice(0, 3).map((u) => `${u.files.toLocaleString("en-US")} ${u.language} ${u.files === 1 ? "file" : "files"}`);
570
+ const rest = unsupported.slice(3);
571
+ if (rest.length)
572
+ parts.push(
573
+ `${files(rest.reduce((n, u) => n + u.files, 0))} in ${rest.length} other ${rest.length === 1 ? "language" : "languages"}`
574
+ );
575
+ const list = parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
576
+ const total = unsupported.reduce((n, u) => n + u.files, 0);
577
+ return `${list} ${total === 1 ? "is" : "are"} not analyzed: veoflow does not read ${unsupported.length === 1 ? "this language" : "these languages"} yet.`;
578
+ }
481
579
  function planGit(source, top, prefix, head, branch, filter, maxFileBytes) {
482
580
  const changes = workTreeChanges(top, prefix);
483
581
  const plan = {
@@ -490,9 +588,13 @@ function planGit(source, top, prefix, head, branch, filter, maxFileBytes) {
490
588
  files: [],
491
589
  unpinned: [],
492
590
  skipped: [],
591
+ unsupported: [],
493
592
  notices: []
494
593
  };
495
594
  const candidates = [];
595
+ const unsupported = new UnsupportedCounter();
596
+ const htmls = [];
597
+ const manifests = [];
496
598
  let entries = 0;
497
599
  const collect = (repoDir, commit, treePrefix, relBase, sub) => {
498
600
  for (const entry of lsTree(repoDir, commit, treePrefix)) {
@@ -509,17 +611,52 @@ function planGit(source, top, prefix, head, branch, filter, maxFileBytes) {
509
611
  collect(dir, entry.sha, "", rel, entry.sha);
510
612
  continue;
511
613
  }
614
+ if (entry.type === "blob" && entry.mode !== "120000" && (rel === "package.json" || rel.endsWith("/package.json")))
615
+ manifests.push({ rel, sha: entry.sha, repoDir });
512
616
  if (entry.type !== "blob" || !filter.matches(rel)) continue;
513
617
  const language = classify(rel);
514
618
  if (entry.mode === "120000") {
515
- if (language) plan.skipped.push({ path: rel, reason: "symlink" });
619
+ if (language || rel.toLowerCase().endsWith(".html"))
620
+ plan.skipped.push({ path: rel, reason: "symlink" });
516
621
  continue;
517
622
  }
518
623
  if (language)
519
624
  candidates.push({ rel, sha: entry.sha, language, repoDir, ...sub ? { commit: sub } : {} });
625
+ else if (rel.toLowerCase().endsWith(".html"))
626
+ htmls.push({
627
+ rel,
628
+ sha: entry.sha,
629
+ language: "angular-template",
630
+ repoDir,
631
+ ...sub ? { commit: sub } : {}
632
+ });
633
+ else unsupported.add(rel);
520
634
  }
521
635
  };
522
636
  collect(top, head, prefix, "");
637
+ if (htmls.length > 0) {
638
+ const texts = /* @__PURE__ */ new Map();
639
+ const byRepoDir = /* @__PURE__ */ new Map();
640
+ for (const m of manifests) byRepoDir.set(m.repoDir, [...byRepoDir.get(m.repoDir) ?? [], m]);
641
+ for (const [repoDir, list] of byRepoDir) {
642
+ const shas = list.map((m) => m.sha);
643
+ const sizes = new Map([...blobSizes(repoDir, shas)].filter(([, n]) => n <= maxFileBytes));
644
+ const blobs = readBlobs(repoDir, shas, sizes);
645
+ for (const m of list) {
646
+ const blob = blobs.get(m.sha);
647
+ if (blob) texts.set(manifestDir(m.rel), blob.toString("utf8"));
648
+ }
649
+ }
650
+ const angular = angularTemplates(
651
+ htmls.map((h) => h.rel),
652
+ texts
653
+ );
654
+ for (const h of htmls) {
655
+ if (angular.has(h.rel)) candidates.push(h);
656
+ else unsupported.add(h.rel);
657
+ }
658
+ }
659
+ plan.unsupported = unsupported.list();
523
660
  if (entries === 0 && prefix)
524
661
  plan.notices.push(
525
662
  `${prefix} is not in the last commit (it may be untracked or ignored), so there was nothing to analyze.`
@@ -600,12 +737,16 @@ function planPlain(source, filter, maxFileBytes) {
600
737
  files: [],
601
738
  unpinned: [],
602
739
  skipped: [],
740
+ unsupported: [],
603
741
  notices: []
604
742
  };
605
743
  const rootReal = realpathSync(source.root);
606
744
  const within = (real) => real === rootReal || real.startsWith(rootReal + sep);
607
745
  const toRel = (abs) => relative(source.root, abs).split(sep).join("/");
608
746
  const inputs = [];
747
+ const unsupported = new UnsupportedCounter();
748
+ const htmls = [];
749
+ const manifests = /* @__PURE__ */ new Map();
609
750
  const walk = (dir, dirReal) => {
610
751
  let names;
611
752
  try {
@@ -642,9 +783,20 @@ function planPlain(source, filter, maxFileBytes) {
642
783
  walk(abs, join2(dirReal, name));
643
784
  continue;
644
785
  }
786
+ if (st.isFile() && name === "package.json" && st.size <= maxFileBytes) {
787
+ try {
788
+ manifests.set(manifestDir(rel), readFileSync(abs, "utf8"));
789
+ } catch {
790
+ }
791
+ }
645
792
  if (!st.isFile() || !filter.matches(rel)) continue;
646
793
  const language = classify(rel);
794
+ if (!language && rel.toLowerCase().endsWith(".html")) {
795
+ htmls.push({ abs, rel, size: st.size });
796
+ continue;
797
+ }
647
798
  if (!language) {
799
+ unsupported.add(rel);
648
800
  if (RESOLVER_INPUT.test(rel) && st.size <= maxFileBytes) {
649
801
  try {
650
802
  inputs.push({ path: rel, hash: sha256(readFileSync(abs)) });
@@ -674,6 +826,43 @@ function planPlain(source, filter, maxFileBytes) {
674
826
  }
675
827
  };
676
828
  walk(source.root, rootReal);
829
+ const angular = angularTemplates(
830
+ htmls.map((h) => h.rel),
831
+ manifests
832
+ );
833
+ for (const h of htmls) {
834
+ if (!angular.has(h.rel)) {
835
+ unsupported.add(h.rel);
836
+ continue;
837
+ }
838
+ if (h.size > maxFileBytes) {
839
+ let hash2 = "";
840
+ try {
841
+ hash2 = sha256File(h.abs);
842
+ } catch {
843
+ }
844
+ plan.files.push({
845
+ path: h.rel,
846
+ language: "angular-template",
847
+ size: h.size,
848
+ contentHash: hash2,
849
+ skip: "too-large"
850
+ });
851
+ continue;
852
+ }
853
+ try {
854
+ plan.files.push(fileFromBytes(h.rel, "angular-template", readFileSync(h.abs), maxFileBytes));
855
+ } catch {
856
+ plan.files.push({
857
+ path: h.rel,
858
+ language: "angular-template",
859
+ size: h.size,
860
+ contentHash: "",
861
+ skip: "unreadable"
862
+ });
863
+ }
864
+ }
865
+ plan.unsupported = unsupported.list();
677
866
  plan.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
678
867
  const lines = [
679
868
  ...plan.files.map((f) => `${f.path}\0${f.contentHash}
@@ -684,7 +873,7 @@ function planPlain(source, filter, maxFileBytes) {
684
873
  plan.revision = `sha256:${sha256(lines.join(""))}`;
685
874
  return plan;
686
875
  }
687
- var DEFAULT_MAX_FILE_BYTES, RESOLVER_INPUT;
876
+ var DEFAULT_MAX_FILE_BYTES, RESOLVER_INPUT, UnsupportedCounter;
688
877
  var init_plan = __esm({
689
878
  "packages/planner/src/plan.ts"() {
690
879
  "use strict";
@@ -694,6 +883,16 @@ var init_plan = __esm({
694
883
  init_glob();
695
884
  DEFAULT_MAX_FILE_BYTES = 10 * 1024 * 1024;
696
885
  RESOLVER_INPUT = /\.(json|jsonc|lock|ya?ml|toml|mod|sum)$|(^|\/)(\.npmrc|\.nvmrc|\.babelrc)$/i;
886
+ UnsupportedCounter = class {
887
+ counts = /* @__PURE__ */ new Map();
888
+ add(path) {
889
+ const language = unsupportedLanguage(path);
890
+ if (language) this.counts.set(language, (this.counts.get(language) ?? 0) + 1);
891
+ }
892
+ list() {
893
+ return [...this.counts].map(([language, files]) => ({ language, files })).sort((a, b) => b.files - a.files || (a.language < b.language ? -1 : 1));
894
+ }
895
+ };
697
896
  }
698
897
  });
699
898
 
@@ -757,7 +956,10 @@ function indexColumns(fact) {
757
956
  case "Function":
758
957
  return { file: fact.file, src: null, dst: null };
759
958
  case "CALLS":
959
+ case "CALLS_CROSS_FILE":
760
960
  return { file: fact.evidence.file, src: fact.from, dst: fact.to };
961
+ case "DeclaredTemplate":
962
+ return { file: fact.file, src: null, dst: null };
761
963
  case "UnresolvedCallSite":
762
964
  return { file: fact.file, src: fact.enclosingFn, dst: null };
763
965
  case "Finding":
@@ -775,7 +977,7 @@ function sourceOf(fileId) {
775
977
  }
776
978
  function factSource(fact) {
777
979
  if (fact.type === "File") return fact.source;
778
- if (fact.type === "CALLS") return sourceOf(fact.evidence.file);
980
+ if (fact.type === "CALLS" || fact.type === "CALLS_CROSS_FILE") return sourceOf(fact.evidence.file);
779
981
  return sourceOf(fact.evidence ? fact.evidence.file : fact.file);
780
982
  }
781
983
  function processAlive(pid) {
@@ -891,10 +1093,40 @@ CREATE TABLE IF NOT EXISTS lock (
891
1093
  return this.rows("file = :file", { file: file2 });
892
1094
  }
893
1095
  callsFrom(fnId) {
894
- return this.rows("type = 'CALLS' AND src = :id", { id: fnId });
1096
+ return this.rows("type IN ('CALLS', 'CALLS_CROSS_FILE') AND src = :id", { id: fnId });
895
1097
  }
896
1098
  callsTo(fnId) {
897
- return this.rows("type = 'CALLS' AND dst = :id", { id: fnId });
1099
+ return this.rows("type IN ('CALLS', 'CALLS_CROSS_FILE') AND dst = :id", { id: fnId });
1100
+ }
1101
+ /** How many facts of a type each file holds (functions or calls per file, for the file list). */
1102
+ countByFile(type) {
1103
+ const rows = this.db.prepare(
1104
+ `SELECT file, COUNT(*) AS n FROM facts WHERE ${VISIBLE} AND type = :type AND file IS NOT NULL GROUP BY file`
1105
+ ).all({ type, run: this.run });
1106
+ return new Map(rows.map((r) => [r.file, r.n]));
1107
+ }
1108
+ /**
1109
+ * CALLS grouped by one end: for each function, how many calls and how many
1110
+ * distinct functions at the other end. Limited to `ids` when given.
1111
+ */
1112
+ callCounts(end, ids2) {
1113
+ const other = end === "src" ? "dst" : "src";
1114
+ const out = /* @__PURE__ */ new Map();
1115
+ const query = (where, params) => this.db.prepare(
1116
+ `SELECT ${end} AS k, COUNT(*) AS calls, COUNT(DISTINCT ${other}) AS functions FROM facts WHERE ${VISIBLE} AND type IN ('CALLS', 'CALLS_CROSS_FILE')${where} GROUP BY ${end}`
1117
+ ).all({ ...params, run: this.run });
1118
+ if (!ids2) {
1119
+ for (const r of query("", {})) out.set(r.k, { calls: r.calls, functions: r.functions });
1120
+ return out;
1121
+ }
1122
+ for (let i = 0; i < ids2.length; i += 500) {
1123
+ const batch = ids2.slice(i, i + 500);
1124
+ const params = Object.fromEntries(batch.map((id, j) => [`p${j}`, id]));
1125
+ const list = batch.map((_, j) => `:p${j}`).join(",");
1126
+ for (const r of query(` AND ${end} IN (${list})`, params))
1127
+ out.set(r.k, { calls: r.calls, functions: r.functions });
1128
+ }
1129
+ return out;
898
1130
  }
899
1131
  count(type) {
900
1132
  const sql = `SELECT COUNT(*) AS n FROM facts WHERE ${VISIBLE}${type ? " AND type = :type" : ""}`;
@@ -952,13 +1184,13 @@ CREATE TABLE IF NOT EXISTS lock (
952
1184
  * (the graph "as of" that run, design §5.3 A5).
953
1185
  */
954
1186
  reader(run) {
955
- const target = run ?? this.currentRun();
956
- if (target === null) return new GraphReader(this.db, 0);
957
- const info = this.runInfo(target);
958
- if (!info) throw new Error(`run ${target} does not exist`);
1187
+ const target2 = run ?? this.currentRun();
1188
+ if (target2 === null) return new GraphReader(this.db, 0);
1189
+ const info = this.runInfo(target2);
1190
+ if (!info) throw new Error(`run ${target2} does not exist`);
959
1191
  if (info.status !== "committed")
960
- throw new Error(`run ${target} is ${info.status}; only committed runs can be read`);
961
- return new GraphReader(this.db, target);
1192
+ throw new Error(`run ${target2} is ${info.status}; only committed runs can be read`);
1193
+ return new GraphReader(this.db, target2);
962
1194
  }
963
1195
  runs() {
964
1196
  return this.db.prepare("SELECT * FROM runs ORDER BY run_id").all().map(toRunInfo);
@@ -1093,11 +1325,11 @@ CREATE TABLE IF NOT EXISTS lock (
1093
1325
  * the stage's scopes that it did not re-emit. Scopes belong to a stage: the
1094
1326
  * sweep only closes facts this stage wrote in those scopes.
1095
1327
  */
1096
- writeStage(stage, write) {
1328
+ writeStage(stage, write2) {
1097
1329
  this.assertOpen();
1098
1330
  const startedAt = now();
1099
- const scopes = new Set(write.scopes);
1100
- for (const { scope, fact } of write.facts) {
1331
+ const scopes = new Set(write2.scopes);
1332
+ for (const { scope, fact } of write2.facts) {
1101
1333
  if (!scopes.has(scope))
1102
1334
  throw new Error(`fact ${fact.id} has scope ${scope}, which the stage did not declare`);
1103
1335
  }
@@ -1128,7 +1360,7 @@ CREATE TABLE IF NOT EXISTS lock (
1128
1360
  `INSERT INTO facts (id, type, stage, scope, rev, file, src, dst, hash, payload, from_run, to_run)
1129
1361
  VALUES (:id, :type, :stage, :scope, :rev, :file, :src, :dst, :hash, :payload, :run, NULL)`
1130
1362
  );
1131
- for (const { scope, fact } of write.facts) {
1363
+ for (const { scope, fact } of write2.facts) {
1132
1364
  if (emitted.has(fact.id)) throw new Error(`fact ${fact.id} written twice in stage ${stage}`);
1133
1365
  emitted.add(fact.id);
1134
1366
  const rev = revisionOf(fact);
@@ -1588,6 +1820,7 @@ function sourcesOf(plans) {
1588
1820
  kind: p.kind,
1589
1821
  ...p.kind === "git" ? { dirty: p.dirty } : {},
1590
1822
  ...p.unpinned.length ? { unpinned: p.unpinned } : {},
1823
+ ...p.unsupported.length ? { unsupported: p.unsupported } : {},
1591
1824
  ...p.notices.length ? { notices: p.notices } : {}
1592
1825
  }));
1593
1826
  }
@@ -1642,14 +1875,14 @@ async function runNow(request) {
1642
1875
  current = stage.name;
1643
1876
  run.startStage(stage.name);
1644
1877
  const started = Date.now();
1645
- const write = await stage.run({
1878
+ const write2 = await stage.run({
1646
1879
  projectId,
1647
1880
  runId: run.runId,
1648
1881
  plans,
1649
1882
  view: run.view(),
1650
1883
  evidence: request.evidence
1651
1884
  });
1652
- const info = run.writeStage(stage.name, write);
1885
+ const info = run.writeStage(stage.name, write2);
1653
1886
  emit({
1654
1887
  type: "stage.completed",
1655
1888
  projectId,
@@ -1740,7 +1973,7 @@ var PROTOCOL_VERSION;
1740
1973
  var init_protocol = __esm({
1741
1974
  "protocol/index.ts"() {
1742
1975
  "use strict";
1743
- PROTOCOL_VERSION = "1.0.0";
1976
+ PROTOCOL_VERSION = "1.1.0";
1744
1977
  }
1745
1978
  });
1746
1979
 
@@ -1850,6 +2083,20 @@ function factsForFile(sourceId, file2, result2) {
1850
2083
  };
1851
2084
  facts.push(site);
1852
2085
  }
2086
+ for (const t of result2.templates) {
2087
+ facts.push({
2088
+ type: "DeclaredTemplate",
2089
+ id: `template|${fileId}|${t.component}`,
2090
+ file: fileId,
2091
+ component: t.component,
2092
+ specifier: t.specifier,
2093
+ methods: t.methods,
2094
+ signals: t.signals,
2095
+ fields: t.fields,
2096
+ inherits: t.inherits,
2097
+ evidence: evidence(t.span)
2098
+ });
2099
+ }
1853
2100
  for (const [d, ordinal] of withOrdinals(
1854
2101
  result2.diagnostics.filter((d2) => d2.severity !== "info"),
1855
2102
  (d2) => d2.code
@@ -1930,19 +2177,208 @@ var init_readback = __esm({
1930
2177
  }
1931
2178
  });
1932
2179
 
2180
+ // packages/stages/src/template-link.ts
2181
+ import { execFileSync as execFileSync2 } from "node:child_process";
2182
+ import { existsSync as existsSync5 } from "node:fs";
2183
+ import { join as join6, posix, relative as relative2, sep as sep3 } from "node:path";
2184
+ function runTemplateLink(ctx) {
2185
+ const view = ctx.view;
2186
+ const files = view.facts("File");
2187
+ const fileById = new Map(files.map((f) => [f.id, f]));
2188
+ const scopes = /* @__PURE__ */ new Set();
2189
+ const facts = [];
2190
+ const push = (scope, fact) => {
2191
+ scopes.add(scope);
2192
+ facts.push({ scope, fact });
2193
+ };
2194
+ for (const e of view.facts("CALLS_CROSS_FILE"))
2195
+ if (e.via === "template-link") scopes.add(scopeOf(`${e.evidence.file}|${e.component}`));
2196
+ for (const u of view.facts("UnresolvedCallSite"))
2197
+ if (u.component) scopes.add(scopeOf(`${u.file}|${u.component}`));
2198
+ for (const f of view.facts("Finding"))
2199
+ if (f.id.startsWith(`${TEMPLATE_LINK}|`)) scopes.add(scopeOf(f.component ?? f.file));
2200
+ const roots = ctx.plans.map((p) => ({
2201
+ source: p.sourceId,
2202
+ root: p.root,
2203
+ kind: p.kind,
2204
+ revision: p.revision
2205
+ }));
2206
+ const exists = (r, rel) => {
2207
+ if (r.kind !== "git") return existsSync5(join6(r.root, ...rel.split("/")));
2208
+ try {
2209
+ execFileSync2("git", ["-C", r.root, "cat-file", "-e", `${r.revision}:./${rel}`], { stdio: "ignore" });
2210
+ return true;
2211
+ } catch {
2212
+ return false;
2213
+ }
2214
+ };
2215
+ const resolveTarget = (d) => {
2216
+ if (d.specifier === null) return { kind: "computed" };
2217
+ const owner = fileById.get(d.file);
2218
+ if (!owner) return { kind: "not-found" };
2219
+ const ownerRoot = roots.find((r) => r.source === owner.source);
2220
+ const rel = d.specifier.startsWith("/") ? posix.normalize(d.specifier.slice(1)) : posix.normalize(posix.join(posix.dirname(owner.path), d.specifier));
2221
+ if (!rel.startsWith("../") && rel !== "..") {
2222
+ const file2 = fileById.get(ids.file(owner.source, rel));
2223
+ if (file2)
2224
+ return file2.language === "angular-template" ? { kind: "file", file: file2 } : { kind: "not-analyzed" };
2225
+ return { kind: ownerRoot && exists(ownerRoot, rel) ? "not-analyzed" : "not-found" };
2226
+ }
2227
+ if (ownerRoot) {
2228
+ const abs = join6(ownerRoot.root, ...owner.path.split("/").slice(0, -1), ...d.specifier.split("/"));
2229
+ for (const r of roots) {
2230
+ const inside = relative2(r.root, abs);
2231
+ if (inside && !inside.startsWith("..") && !inside.startsWith(sep3) && !/^[a-zA-Z]:/.test(inside)) {
2232
+ const inRel = inside.split(sep3).join("/");
2233
+ const file2 = fileById.get(ids.file(r.source, inRel));
2234
+ if (file2)
2235
+ return file2.language === "angular-template" ? { kind: "file", file: file2 } : { kind: "not-analyzed" };
2236
+ return { kind: exists(r, inRel) ? "not-analyzed" : "not-found" };
2237
+ }
2238
+ }
2239
+ }
2240
+ return { kind: "pending" };
2241
+ };
2242
+ const owners = /* @__PURE__ */ new Map();
2243
+ for (const d of view.facts("DeclaredTemplate")) {
2244
+ const key = componentKey(d);
2245
+ scopes.add(scopeOf(key));
2246
+ const target2 = resolveTarget(d);
2247
+ if (target2.kind === "file") {
2248
+ const list = owners.get(target2.file.id) ?? [];
2249
+ list.push(d);
2250
+ owners.set(target2.file.id, list);
2251
+ continue;
2252
+ }
2253
+ const kind = `template-${target2.kind === "computed" ? "url-computed" : target2.kind}`;
2254
+ const message2 = {
2255
+ computed: `${d.component}'s templateUrl is computed, so its template can't be linked`,
2256
+ "not-found": `${d.component} declares ${d.specifier}, which does not exist in the source`,
2257
+ pending: `${d.component} declares ${d.specifier}, which is outside every source of this project; it links when that source is added`,
2258
+ "not-analyzed": `${d.component} declares ${d.specifier}, which exists but was not analyzed as an Angular template`
2259
+ }[target2.kind];
2260
+ const finding = {
2261
+ type: "Finding",
2262
+ id: `${TEMPLATE_LINK}|${kind}|${key}`,
2263
+ kind,
2264
+ file: d.file,
2265
+ message: message2,
2266
+ evidence: d.evidence,
2267
+ severity: target2.kind === "pending" ? "info" : "warning",
2268
+ component: key
2269
+ };
2270
+ push(scopeOf(key), finding);
2271
+ }
2272
+ for (const template of files.filter((f) => f.language === "angular-template")) {
2273
+ const declaring = owners.get(template.id) ?? [];
2274
+ if (declaring.length === 0) {
2275
+ const finding = {
2276
+ type: "Finding",
2277
+ id: `${TEMPLATE_LINK}|template-owner-unknown|${template.id}`,
2278
+ kind: "template-owner-unknown",
2279
+ file: template.id,
2280
+ message: "No component declares this template, so its calls are not part of a component",
2281
+ evidence: null,
2282
+ severity: "info"
2283
+ };
2284
+ push(scopeOf(template.id), finding);
2285
+ continue;
2286
+ }
2287
+ const bindings = view.inFile(template.id).flatMap(
2288
+ (f) => f.type === "UnresolvedCallSite" && f.reason === "template-binding" && !f.component ? [f] : []
2289
+ ).sort((a, b) => a.evidence.span.start.offset - b.evidence.span.start.offset);
2290
+ const from = ids.fn(template.source, template.path, "<template>");
2291
+ const evidence = (u) => ({ ...u.evidence, commit: template.commit ?? "" });
2292
+ for (const d of declaring) {
2293
+ const key = componentKey(d);
2294
+ const scope = scopeOf(`${template.id}|${key}`);
2295
+ scopes.add(scope);
2296
+ const owner = fileById.get(d.file);
2297
+ const ordinals = /* @__PURE__ */ new Map();
2298
+ for (const u of bindings) {
2299
+ const [root, ...path] = u.expression.replace(/[\s()!]/g, "").replace(/\?\./g, ".").replace(/^this\./, "").split(".");
2300
+ const method = path.length === 0 ? d.methods.find((m) => m.name === root) : void 0;
2301
+ if (method) {
2302
+ const to = ids.fn(owner.source, owner.path, method.qualifiedName);
2303
+ const n = ordinals.get(to) ?? 0;
2304
+ ordinals.set(to, n + 1);
2305
+ const edge = {
2306
+ type: "CALLS_CROSS_FILE",
2307
+ id: `${ids.edge("CALLS_CROSS_FILE", from, to, n)}|${key}`,
2308
+ from,
2309
+ to,
2310
+ form: "plain",
2311
+ resolution: "static-exact",
2312
+ confidence: 1,
2313
+ evidence: evidence(u),
2314
+ via: "template-link",
2315
+ component: key
2316
+ };
2317
+ push(scope, edge);
2318
+ continue;
2319
+ }
2320
+ const known = [...d.methods.map((m) => m.name), ...d.signals, ...d.fields].includes(root);
2321
+ const [reason, status] = path.length === 0 && d.signals.includes(root) ? ["runtime-global", "external"] : known ? ["dynamic-dispatch", "open"] : d.inherits ? ["template-reference", "awaiting-link"] : ["dynamic-dispatch", "open"];
2322
+ const record2 = {
2323
+ ...u,
2324
+ id: `${u.id}|${key}`,
2325
+ reason,
2326
+ status,
2327
+ importSpecifier: null,
2328
+ importedName: null,
2329
+ component: key,
2330
+ evidence: evidence(u)
2331
+ };
2332
+ push(scope, record2);
2333
+ }
2334
+ }
2335
+ }
2336
+ return { scopes: [...scopes], facts };
2337
+ }
2338
+ var TEMPLATE_LINK, scopeOf, componentKey, templateLink;
2339
+ var init_template_link = __esm({
2340
+ "packages/stages/src/template-link.ts"() {
2341
+ "use strict";
2342
+ init_src();
2343
+ TEMPLATE_LINK = "template-link";
2344
+ scopeOf = (key) => `${TEMPLATE_LINK}:${key}`;
2345
+ componentKey = (d) => `${d.file}#${d.component}`;
2346
+ templateLink = { name: TEMPLATE_LINK, run: runTemplateLink };
2347
+ }
2348
+ });
2349
+
1933
2350
  // packages/stages/src/index.ts
1934
2351
  var init_src5 = __esm({
1935
2352
  "packages/stages/src/index.ts"() {
1936
2353
  "use strict";
1937
2354
  init_stage1();
1938
2355
  init_readback();
2356
+ init_template_link();
1939
2357
  }
1940
2358
  });
1941
2359
 
1942
2360
  // packages/query/src/engine.ts
1943
2361
  import { EventEmitter } from "node:events";
1944
2362
  import { basename as basename2, resolve as resolve2 } from "node:path";
1945
- var sleep2, slug2, Engine;
2363
+ function visibleSites(facts, reader) {
2364
+ const sites = facts.flatMap((f) => f.type === "UnresolvedCallSite" ? [f] : []);
2365
+ const linked = /* @__PURE__ */ new Set();
2366
+ for (const f of facts) {
2367
+ if (f.type === "UnresolvedCallSite" && f.component) linked.add(f.file);
2368
+ if (f.type === "CALLS_CROSS_FILE") linked.add(f.evidence.file);
2369
+ }
2370
+ if (reader) for (const e of reader.facts("CALLS_CROSS_FILE")) linked.add(e.evidence.file);
2371
+ return sites.filter((s) => !(s.reason === "template-binding" && !s.component && linked.has(s.file)));
2372
+ }
2373
+ function checkLimit(limit, fallback, max) {
2374
+ if (limit === void 0) return fallback;
2375
+ if (!Number.isInteger(limit) || limit < 1)
2376
+ throw new VeoError("invalid-arguments", `limit must be a positive integer (got ${String(limit)})`, {
2377
+ fields: ["limit"]
2378
+ });
2379
+ return Math.min(limit, max);
2380
+ }
2381
+ var GROUP_BY, SEARCH_LIMIT, SEARCH_MAX, AGGREGATE_MAX, OUTLINE_MAX, byCodePoint, sleep2, slug2, Engine;
1946
2382
  var init_engine = __esm({
1947
2383
  "packages/query/src/engine.ts"() {
1948
2384
  "use strict";
@@ -1950,6 +2386,17 @@ var init_engine = __esm({
1950
2386
  init_src3();
1951
2387
  init_src5();
1952
2388
  init_src2();
2389
+ GROUP_BY = {
2390
+ File: ["status", "language", "source", "folder"],
2391
+ Function: ["file", "kind", "exported"],
2392
+ UnresolvedCallSite: ["reason", "status", "file"],
2393
+ CALLS: ["to", "from", "form", "resolution"]
2394
+ };
2395
+ SEARCH_LIMIT = 20;
2396
+ SEARCH_MAX = 100;
2397
+ AGGREGATE_MAX = 50;
2398
+ OUTLINE_MAX = 500;
2399
+ byCodePoint = (a, b) => a < b ? -1 : a > b ? 1 : 0;
1953
2400
  sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
1954
2401
  slug2 = (s) => s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-.]+|-+$/g, "").slice(0, 48) || "source";
1955
2402
  Engine = class {
@@ -2073,7 +2520,7 @@ var init_engine = __esm({
2073
2520
  store,
2074
2521
  evidence,
2075
2522
  sources,
2076
- stages: [stage1],
2523
+ stages: [stage1, templateLink],
2077
2524
  onEvent: (e) => {
2078
2525
  if (e.type === "run.started") onStarted?.(e.runId);
2079
2526
  this.events.emit("event", e);
@@ -2125,6 +2572,19 @@ var init_engine = __esm({
2125
2572
  const reader = this.reader(project2);
2126
2573
  return { ...this.meta(project2, reader), files: reader.facts("File") };
2127
2574
  }
2575
+ /** Functions and calls per file, for the file list (not an MCP tool: a UI aid). */
2576
+ fileCounts(args, cwd) {
2577
+ const project2 = this.resolveProject(args, cwd);
2578
+ const reader = this.reader(project2);
2579
+ const functions = reader.countByFile("Function");
2580
+ const calls = reader.countByFile("CALLS");
2581
+ for (const [file2, n] of reader.countByFile("CALLS_CROSS_FILE"))
2582
+ calls.set(file2, (calls.get(file2) ?? 0) + n);
2583
+ const counts = {};
2584
+ for (const f of reader.facts("File"))
2585
+ counts[f.id] = { functions: functions.get(f.id) ?? 0, calls: calls.get(f.id) ?? 0 };
2586
+ return { ...this.meta(project2, reader), counts };
2587
+ }
2128
2588
  /** A file's functions, the calls among them, its unresolved sites and findings. */
2129
2589
  fileGraph(args, cwd) {
2130
2590
  const project2 = this.resolveProject(args, cwd);
@@ -2135,14 +2595,25 @@ var init_engine = __esm({
2135
2595
  const facts = reader.inFile(file2.id);
2136
2596
  const fns = facts.flatMap((f) => f.type === "Function" ? [f] : []);
2137
2597
  const byId = new Map(fns.map((f) => [f.id, f]));
2598
+ const pathOf = (fileId) => reader.fact(fileId)?.path ?? "";
2599
+ const across = (e, otherId) => {
2600
+ const other = reader.fact(otherId);
2601
+ return this.callView(e, other, other ? pathOf(other.file) : "", otherId);
2602
+ };
2603
+ const incoming = fns.flatMap(
2604
+ (fn) => reader.callsTo(fn.id).filter((e) => e.type === "CALLS_CROSS_FILE" && e.evidence.file !== file2.id)
2605
+ );
2138
2606
  return {
2139
2607
  ...this.meta(project2, reader),
2140
2608
  file: file2,
2141
2609
  functions: fns.map((f) => this.functionView(f, file2.path)),
2142
- calls: facts.flatMap(
2143
- (f) => f.type === "CALLS" ? [this.callView(f, byId.get(f.to), file2.path, f.to)] : []
2144
- ),
2145
- unresolved: facts.flatMap((f) => f.type === "UnresolvedCallSite" ? [f] : []),
2610
+ calls: [
2611
+ ...facts.flatMap(
2612
+ (f) => f.type === "CALLS" ? [this.callView(f, byId.get(f.to), file2.path, f.to)] : f.type === "CALLS_CROSS_FILE" ? [across(f, f.to)] : []
2613
+ ),
2614
+ ...incoming.map((e) => across(e, e.from))
2615
+ ],
2616
+ unresolved: visibleSites(facts),
2146
2617
  findings: facts.filter((f) => f.type === "Finding")
2147
2618
  };
2148
2619
  }
@@ -2167,10 +2638,16 @@ var init_engine = __esm({
2167
2638
  id: edge.id,
2168
2639
  from: edge.from,
2169
2640
  to: edge.to,
2170
- function: { id: otherId, qualifiedName: other?.qualifiedName ?? otherId, path },
2641
+ function: {
2642
+ id: otherId,
2643
+ qualifiedName: other?.qualifiedName ?? otherId,
2644
+ path,
2645
+ ...other ? { line: other.evidence.span.start.line } : {}
2646
+ },
2171
2647
  form: edge.form,
2172
2648
  resolution: edge.resolution,
2173
- evidence: edge.evidence
2649
+ evidence: edge.evidence,
2650
+ ...edge.type === "CALLS_CROSS_FILE" ? { crossFile: true } : {}
2174
2651
  };
2175
2652
  }
2176
2653
  /** One function, by id or by qualified name (optionally within a file path). */
@@ -2227,13 +2704,230 @@ var init_engine = __esm({
2227
2704
  });
2228
2705
  return { ...this.meta(project2, reader), function: fn.id, direction, calls };
2229
2706
  }
2707
+ /**
2708
+ * Find functions or files by name (generic graph tool `search_nodes`, design
2709
+ * §12 A3, limited to R1's labels). Ranked: exact name, then name prefix, then
2710
+ * a match anywhere in the qualified name or path; ties by path then id, in
2711
+ * code-point order so every machine returns the same page.
2712
+ */
2713
+ searchNodes(args, cwd) {
2714
+ const project2 = this.resolveProject(args, cwd);
2715
+ const reader = this.reader(project2);
2716
+ if (args.label !== "Function" && args.label !== "File")
2717
+ throw new VeoError(
2718
+ "invalid-arguments",
2719
+ `search_nodes supports Function and File (got ${String(args.label)})`,
2720
+ { fields: ["label"] }
2721
+ );
2722
+ if (args.filters?.status !== void 0 && args.label !== "File")
2723
+ throw new VeoError("invalid-arguments", "filters.status applies to File only", { fields: ["filters"] });
2724
+ const limit = checkLimit(args.limit, SEARCH_LIMIT, SEARCH_MAX);
2725
+ const text = (args.text ?? "").trim().toLowerCase();
2726
+ const prefix = args.filters?.path;
2727
+ const files = reader.facts("File");
2728
+ const pathOf = new Map(files.map((f) => [f.id, f.path]));
2729
+ const rank = (name, short, path) => {
2730
+ if (!text) return 3;
2731
+ const n = name.toLowerCase();
2732
+ const s = short.toLowerCase();
2733
+ if (s === text || n === text) return 0;
2734
+ if (s.startsWith(text) || n.startsWith(text)) return 1;
2735
+ if (n.includes(text)) return 2;
2736
+ if (path.toLowerCase().includes(text)) return 3;
2737
+ return -1;
2738
+ };
2739
+ const scored = [];
2740
+ if (args.label === "File") {
2741
+ for (const f of files) {
2742
+ if (prefix && !f.path.startsWith(prefix)) continue;
2743
+ if (args.filters?.status && f.status !== args.filters.status) continue;
2744
+ const score = rank(f.path, f.path.slice(f.path.lastIndexOf("/") + 1), f.path);
2745
+ if (score >= 0) scored.push({ score, path: f.path, id: f.id });
2746
+ }
2747
+ } else {
2748
+ for (const fn of reader.facts("Function")) {
2749
+ const path = pathOf.get(fn.file) ?? "";
2750
+ if (prefix && !path.startsWith(prefix)) continue;
2751
+ const score = rank(fn.qualifiedName, fn.name, path);
2752
+ if (score >= 0) scored.push({ score, path, id: fn.id });
2753
+ }
2754
+ }
2755
+ scored.sort((a, b) => a.score - b.score || byCodePoint(a.path, b.path) || byCodePoint(a.id, b.id));
2756
+ const page = scored.slice(0, limit);
2757
+ let results;
2758
+ if (args.label === "File") {
2759
+ const byId = new Map(files.map((f) => [f.id, f]));
2760
+ results = page.map(({ id }) => {
2761
+ const f = byId.get(id);
2762
+ return {
2763
+ label: "File",
2764
+ id,
2765
+ name: f.path,
2766
+ path: f.path,
2767
+ status: f.status,
2768
+ functions: reader.facts("Function", id).length
2769
+ };
2770
+ });
2771
+ } else {
2772
+ const ids2 = page.map((p) => p.id);
2773
+ const incoming = reader.callCounts("dst", ids2);
2774
+ const outgoing = reader.callCounts("src", ids2);
2775
+ results = page.map(({ id, path }) => {
2776
+ const fn = reader.fact(id);
2777
+ return {
2778
+ label: "Function",
2779
+ id,
2780
+ name: fn.qualifiedName,
2781
+ path,
2782
+ callers: incoming.get(id)?.functions ?? 0,
2783
+ callees: outgoing.get(id)?.functions ?? 0,
2784
+ callsIn: incoming.get(id)?.calls ?? 0,
2785
+ callsOut: outgoing.get(id)?.calls ?? 0,
2786
+ evidence: fn.evidence
2787
+ };
2788
+ });
2789
+ }
2790
+ return {
2791
+ ...this.meta(project2, reader),
2792
+ label: args.label,
2793
+ text: args.text ?? "",
2794
+ total: scored.length,
2795
+ truncated: scored.length > limit,
2796
+ results
2797
+ };
2798
+ }
2799
+ /**
2800
+ * Counts grouped by a property (generic graph tool `aggregate`, design §12
2801
+ * A3, limited to R1's labels). Sorted by count, then key in code-point
2802
+ * order; at most 50 groups. `filters.open` limits unresolved call sites to
2803
+ * open questions (design A6); `filters.path` to files under a path prefix.
2804
+ */
2805
+ aggregate(args, cwd) {
2806
+ const project2 = this.resolveProject(args, cwd);
2807
+ const reader = this.reader(project2);
2808
+ if (!Object.hasOwn(GROUP_BY, args.label))
2809
+ throw new VeoError("invalid-arguments", `aggregate supports ${Object.keys(GROUP_BY).join(", ")}`, {
2810
+ fields: ["label"]
2811
+ });
2812
+ const allowed = GROUP_BY[args.label];
2813
+ if (!allowed.includes(args.groupBy))
2814
+ throw new VeoError("invalid-arguments", `${args.label} can be grouped by ${allowed.join(", ")}`, {
2815
+ fields: ["groupBy"]
2816
+ });
2817
+ const open2 = args.filters?.open;
2818
+ if (open2 !== void 0 && args.label !== "UnresolvedCallSite")
2819
+ throw new VeoError("invalid-arguments", "filters.open applies to UnresolvedCallSite only", {
2820
+ fields: ["filters"]
2821
+ });
2822
+ const limit = checkLimit(args.limit, AGGREGATE_MAX, AGGREGATE_MAX);
2823
+ const prefix = args.filters?.path;
2824
+ const files = reader.facts("File");
2825
+ const pathOf = new Map(files.map((f) => [f.id, f.path]));
2826
+ const inPath = (fileId) => !prefix || (pathOf.get(fileId) ?? "").startsWith(prefix);
2827
+ const counts = /* @__PURE__ */ new Map();
2828
+ const add = (key) => counts.set(key, (counts.get(key) ?? 0) + 1);
2829
+ let named;
2830
+ const fnName = (key) => reader.fact(key)?.qualifiedName;
2831
+ if (args.label === "File") {
2832
+ for (const f of files) {
2833
+ if (prefix && !f.path.startsWith(prefix)) continue;
2834
+ const folder = f.path.includes("/") ? f.path.slice(0, f.path.lastIndexOf("/")) : ".";
2835
+ const value = { status: f.status, language: f.language ?? "none", source: f.source, folder }[args.groupBy];
2836
+ add(String(value));
2837
+ }
2838
+ } else if (args.label === "Function") {
2839
+ for (const fn of reader.facts("Function")) {
2840
+ if (!inPath(fn.file)) continue;
2841
+ add(String({ file: fn.file, kind: fn.kind, exported: fn.exported }[args.groupBy]));
2842
+ }
2843
+ if (args.groupBy === "file") named = (key) => pathOf.get(key);
2844
+ } else if (args.label === "UnresolvedCallSite") {
2845
+ for (const site of visibleSites(reader.facts("UnresolvedCallSite"), reader)) {
2846
+ if (!inPath(site.file)) continue;
2847
+ if (open2 && !isOpenQuestion(site)) continue;
2848
+ add(String({ reason: site.reason, status: site.status, file: site.file }[args.groupBy]));
2849
+ }
2850
+ if (args.groupBy === "file") named = (key) => pathOf.get(key);
2851
+ } else if ((args.groupBy === "to" || args.groupBy === "from") && !prefix) {
2852
+ for (const [key, c] of reader.callCounts(args.groupBy === "to" ? "dst" : "src"))
2853
+ counts.set(key, c.calls);
2854
+ named = fnName;
2855
+ } else {
2856
+ const fileOf = new Map(reader.facts("Function").map((f) => [f.id, f.file]));
2857
+ for (const call of [...reader.facts("CALLS"), ...reader.facts("CALLS_CROSS_FILE")]) {
2858
+ const owner = fileOf.get(call.from);
2859
+ if (prefix && (!owner || !inPath(owner))) continue;
2860
+ add(
2861
+ String(
2862
+ { to: call.to, from: call.from, form: call.form, resolution: call.resolution }[args.groupBy]
2863
+ )
2864
+ );
2865
+ }
2866
+ if (args.groupBy === "to" || args.groupBy === "from") named = fnName;
2867
+ }
2868
+ const sorted = [...counts].sort(([ka, a], [kb, b]) => b - a || byCodePoint(ka, kb));
2869
+ let total = 0;
2870
+ for (const [, n] of sorted) total += n;
2871
+ return {
2872
+ ...this.meta(project2, reader),
2873
+ label: args.label,
2874
+ groupBy: args.groupBy,
2875
+ total,
2876
+ groupCount: sorted.length,
2877
+ truncated: sorted.length > limit,
2878
+ groups: sorted.slice(0, limit).map(([key, count]) => {
2879
+ const name = named?.(key);
2880
+ return name === void 0 ? { key, count } : { key, count, name };
2881
+ })
2882
+ };
2883
+ }
2884
+ /**
2885
+ * A file's functions in source order, each with its callers and callees
2886
+ * (distinct functions), call counts and unresolved sites, plus the file's
2887
+ * totals (design §12, A9). At most 500 functions.
2888
+ */
2889
+ fileOutline(args, cwd) {
2890
+ const project2 = this.resolveProject(args, cwd);
2891
+ const reader = this.reader(project2);
2892
+ const file2 = reader.fact(args.file);
2893
+ if (!file2 || file2.type !== "File")
2894
+ throw new VeoError("not-found", `no file ${args.file}`, { kind: "file", id: args.file });
2895
+ const facts = reader.inFile(file2.id);
2896
+ const fns = facts.flatMap((f) => f.type === "Function" ? [f] : []).sort(
2897
+ (a, b) => a.evidence.span.start.line - b.evidence.span.start.line || a.evidence.span.start.column - b.evidence.span.start.column || byCodePoint(a.id, b.id)
2898
+ );
2899
+ const shown = fns.slice(0, OUTLINE_MAX);
2900
+ const ids2 = shown.map((f) => f.id);
2901
+ const incoming = reader.callCounts("dst", ids2);
2902
+ const outgoing = reader.callCounts("src", ids2);
2903
+ const sites = visibleSites(facts);
2904
+ const unresolvedIn = /* @__PURE__ */ new Map();
2905
+ for (const s of sites) unresolvedIn.set(s.enclosingFn, (unresolvedIn.get(s.enclosingFn) ?? 0) + 1);
2906
+ return {
2907
+ ...this.meta(project2, reader),
2908
+ file: file2,
2909
+ functions: shown.map((f) => ({
2910
+ ...this.functionView(f, file2.path),
2911
+ callers: incoming.get(f.id)?.functions ?? 0,
2912
+ callees: outgoing.get(f.id)?.functions ?? 0,
2913
+ callsIn: incoming.get(f.id)?.calls ?? 0,
2914
+ callsOut: outgoing.get(f.id)?.calls ?? 0,
2915
+ unresolved: unresolvedIn.get(f.id) ?? 0
2916
+ })),
2917
+ total: fns.length,
2918
+ truncated: fns.length > OUTLINE_MAX,
2919
+ calls: facts.filter((f) => f.type === "CALLS" || f.type === "CALLS_CROSS_FILE").length,
2920
+ unresolved: sites.length,
2921
+ open: sites.filter(isOpenQuestion).length
2922
+ };
2923
+ }
2230
2924
  /** Unresolved call sites: open questions only, unless `includeAll` (design A6). */
2231
2925
  listUnresolvedSites(args, cwd) {
2232
2926
  const project2 = this.resolveProject(args, cwd);
2233
2927
  const reader = this.reader(project2);
2234
2928
  if (args.file && reader.fact(args.file)?.type !== "File")
2235
2929
  throw new VeoError("not-found", `no file ${args.file}`, { kind: "file", id: args.file });
2236
- const all2 = args.file ? reader.inFile(args.file).flatMap((f) => f.type === "UnresolvedCallSite" ? [f] : []) : reader.facts("UnresolvedCallSite");
2930
+ const all2 = args.file ? visibleSites(reader.inFile(args.file)) : visibleSites(reader.facts("UnresolvedCallSite"), reader);
2237
2931
  return { ...this.meta(project2, reader), sites: args.includeAll ? all2 : all2.filter(isOpenQuestion) };
2238
2932
  }
2239
2933
  /** The analyzed text around an evidence span (exactly what was analyzed). */
@@ -2273,7 +2967,7 @@ var init_view = __esm({
2273
2967
  file: null,
2274
2968
  selection: null,
2275
2969
  panel: "evidence",
2276
- showUnresolved: true
2970
+ showUnresolved: false
2277
2971
  };
2278
2972
  str = (field, optional2 = false) => (a) => optional2 && a[field] === void 0 || typeof a[field] === "string" && a[field].length > 0 ? [] : [field];
2279
2973
  oneOf = (field, values) => (a) => values.includes(a[field]) ? [] : [field];
@@ -2300,7 +2994,9 @@ var init_view = __esm({
2300
2994
  ...s,
2301
2995
  file: a.file ?? s.file,
2302
2996
  selection: { kind: a.kind, id: a.id },
2303
- panel: "evidence"
2997
+ panel: "evidence",
2998
+ // An unresolved site is only drawn when sites are shown.
2999
+ showUnresolved: a.kind === "site" ? true : s.showUnresolved
2304
3000
  })
2305
3001
  },
2306
3002
  clearSelection: {
@@ -2310,9 +3006,9 @@ var init_view = __esm({
2310
3006
  apply: (s) => ({ ...s, selection: null })
2311
3007
  },
2312
3008
  showPanel: {
2313
- description: "Show the evidence panel or the open-questions list",
3009
+ description: "Show the evidence panel, the open-questions list or the last answer",
2314
3010
  control: { kind: "tab", testId: "show-panel" },
2315
- check: oneOf("panel", ["evidence", "questions"]),
3011
+ check: oneOf("panel", ["evidence", "questions", "answer"]),
2316
3012
  apply: (s, a) => ({ ...s, panel: a.panel })
2317
3013
  },
2318
3014
  toggleUnresolved: {
@@ -2332,6 +3028,16 @@ var init_view = __esm({
2332
3028
  description: "Analyze the project again",
2333
3029
  control: { kind: "button", testId: "reanalyze" },
2334
3030
  check: none
3031
+ },
3032
+ ask: {
3033
+ description: "Ask a question about the analyzed code (built-in questions offline; anything with a model)",
3034
+ control: { kind: "button", testId: "ask", shortcut: "Mod+K" },
3035
+ check: str("question")
3036
+ },
3037
+ openSettings: {
3038
+ description: "Set the model provider: base URL, API key and model name",
3039
+ control: { kind: "button", testId: "settings" },
3040
+ check: none
2335
3041
  }
2336
3042
  };
2337
3043
  }
@@ -3358,8 +4064,8 @@ var init_types = __esm({
3358
4064
  description
3359
4065
  });
3360
4066
  }
3361
- pipe(target) {
3362
- return ZodPipeline.create(this, target);
4067
+ pipe(target2) {
4068
+ return ZodPipeline.create(this, target2);
3363
4069
  }
3364
4070
  readonly() {
3365
4071
  return ZodReadonly.create(this);
@@ -6459,8 +7165,8 @@ function defineLazy(object3, key, getter) {
6459
7165
  function objectClone(obj) {
6460
7166
  return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
6461
7167
  }
6462
- function assignProp(target, prop, value) {
6463
- Object.defineProperty(target, prop, {
7168
+ function assignProp(target2, prop, value) {
7169
+ Object.defineProperty(target2, prop, {
6464
7170
  value,
6465
7171
  writable: true,
6466
7172
  enumerable: true,
@@ -6474,8 +7180,8 @@ function rawShape(def) {
6474
7180
  function sourceShape(schema) {
6475
7181
  return rawShape(schema._zod.def) ?? schema._zod.def.shape;
6476
7182
  }
6477
- function deferProp(target, key, getter) {
6478
- Object.defineProperty(target, key, {
7183
+ function deferProp(target2, key, getter) {
7184
+ Object.defineProperty(target2, key, {
6479
7185
  get() {
6480
7186
  const value = getter();
6481
7187
  assignProp(this, key, value);
@@ -6485,36 +7191,36 @@ function deferProp(target, key, getter) {
6485
7191
  configurable: true
6486
7192
  });
6487
7193
  }
6488
- function putProp(target, key, value) {
6489
- if (key in target)
6490
- assignProp(target, key, value);
7194
+ function putProp(target2, key, value) {
7195
+ if (key in target2)
7196
+ assignProp(target2, key, value);
6491
7197
  else
6492
- target[key] = value;
7198
+ target2[key] = value;
6493
7199
  }
6494
- function mirrorShape(target, source, keys, wrap) {
7200
+ function mirrorShape(target2, source, keys, wrap) {
6495
7201
  const raw = sourceShape(source);
6496
7202
  for (const key of keys) {
6497
7203
  const desc = Object.getOwnPropertyDescriptor(raw, key);
6498
7204
  if (!desc.enumerable)
6499
7205
  continue;
6500
7206
  if (desc.get) {
6501
- deferProp(target, key, () => {
7207
+ deferProp(target2, key, () => {
6502
7208
  const value = source._zod.def.shape[key];
6503
7209
  return wrap ? wrap(value, key) : value;
6504
7210
  });
6505
7211
  } else
6506
- putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);
7212
+ putProp(target2, key, wrap ? wrap(desc.value, key) : desc.value);
6507
7213
  }
6508
7214
  }
6509
- function mirrorProps(target, source) {
7215
+ function mirrorProps(target2, source) {
6510
7216
  for (const key of Reflect.ownKeys(source)) {
6511
7217
  const desc = Object.getOwnPropertyDescriptor(source, key);
6512
7218
  if (!desc.enumerable)
6513
7219
  continue;
6514
7220
  if (desc.get)
6515
- deferProp(target, key, () => source[key]);
7221
+ deferProp(target2, key, () => source[key]);
6516
7222
  else
6517
- putProp(target, key, desc.value);
7223
+ putProp(target2, key, desc.value);
6518
7224
  }
6519
7225
  }
6520
7226
  function mergeDefs(...defs) {
@@ -6623,35 +7329,35 @@ function normalizeParams(_params) {
6623
7329
  return params;
6624
7330
  }
6625
7331
  function createTransparentProxy(getter) {
6626
- let target;
7332
+ let target2;
6627
7333
  return new Proxy({}, {
6628
7334
  get(_, prop, receiver) {
6629
- target ?? (target = getter());
6630
- return Reflect.get(target, prop, receiver);
7335
+ target2 ?? (target2 = getter());
7336
+ return Reflect.get(target2, prop, receiver);
6631
7337
  },
6632
7338
  set(_, prop, value, receiver) {
6633
- target ?? (target = getter());
6634
- return Reflect.set(target, prop, value, receiver);
7339
+ target2 ?? (target2 = getter());
7340
+ return Reflect.set(target2, prop, value, receiver);
6635
7341
  },
6636
7342
  has(_, prop) {
6637
- target ?? (target = getter());
6638
- return Reflect.has(target, prop);
7343
+ target2 ?? (target2 = getter());
7344
+ return Reflect.has(target2, prop);
6639
7345
  },
6640
7346
  deleteProperty(_, prop) {
6641
- target ?? (target = getter());
6642
- return Reflect.deleteProperty(target, prop);
7347
+ target2 ?? (target2 = getter());
7348
+ return Reflect.deleteProperty(target2, prop);
6643
7349
  },
6644
7350
  ownKeys(_) {
6645
- target ?? (target = getter());
6646
- return Reflect.ownKeys(target);
7351
+ target2 ?? (target2 = getter());
7352
+ return Reflect.ownKeys(target2);
6647
7353
  },
6648
7354
  getOwnPropertyDescriptor(_, prop) {
6649
- target ?? (target = getter());
6650
- return Reflect.getOwnPropertyDescriptor(target, prop);
7355
+ target2 ?? (target2 = getter());
7356
+ return Reflect.getOwnPropertyDescriptor(target2, prop);
6651
7357
  },
6652
7358
  defineProperty(_, prop, descriptor) {
6653
- target ?? (target = getter());
6654
- return Reflect.defineProperty(target, prop, descriptor);
7359
+ target2 ?? (target2 = getter());
7360
+ return Reflect.defineProperty(target2, prop, descriptor);
6655
7361
  }
6656
7362
  });
6657
7363
  }
@@ -7206,10 +7912,10 @@ function $constructor(name, initializer3, proto, params) {
7206
7912
  let up = own2;
7207
7913
  while (up && up !== ctorProto)
7208
7914
  up = Object.getPrototypeOf(up);
7209
- const target = up ?? own2;
7210
- if (!initialized.has(target)) {
7211
- initialized.add(target);
7212
- members(target, protoMembers);
7915
+ const target2 = up ?? own2;
7916
+ if (!initialized.has(target2)) {
7917
+ initialized.add(target2);
7918
+ members(target2, protoMembers);
7213
7919
  }
7214
7920
  }
7215
7921
  const proto2 = _.prototype;
@@ -15888,11 +16594,11 @@ var init_nl = __esm({
15888
16594
  case "too_small": {
15889
16595
  const adj = issue2.inclusive ? ">=" : ">";
15890
16596
  const sizing = getSizing(issue2.origin);
15891
- const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein";
16597
+ const shortName2 = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein";
15892
16598
  if (sizing) {
15893
- return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
16599
+ return `Te ${shortName2}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
15894
16600
  }
15895
- return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
16601
+ return `Te ${shortName2}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
15896
16602
  }
15897
16603
  case "invalid_format": {
15898
16604
  const _issue = issue2;
@@ -16662,8 +17368,8 @@ var init_pt = __esm({
16662
17368
  case "not_multiple_of":
16663
17369
  return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;
16664
17370
  case "unrecognized_keys": {
16665
- const plural2 = issue2.keys.length > 1 ? "s" : "";
16666
- return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`;
17371
+ const plural3 = issue2.keys.length > 1 ? "s" : "";
17372
+ return `Chave${plural3} inv\xE1lida${plural3}: ${joinValues(issue2.keys, ", ")}`;
16667
17373
  }
16668
17374
  case "invalid_key":
16669
17375
  return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`;
@@ -16813,8 +17519,8 @@ var init_pt_BR = __esm({
16813
17519
  case "not_multiple_of":
16814
17520
  return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;
16815
17521
  case "unrecognized_keys": {
16816
- const plural2 = issue2.keys.length > 1 ? "s" : "";
16817
- return `Chave${plural2} inv\xE1lida${plural2}: ${joinValues(issue2.keys, ", ")}`;
17522
+ const plural3 = issue2.keys.length > 1 ? "s" : "";
17523
+ return `Chave${plural3} inv\xE1lida${plural3}: ${joinValues(issue2.keys, ", ")}`;
16818
17524
  }
16819
17525
  case "invalid_key":
16820
17526
  return `Entrada inv\xE1lida n${translateOriginWithArticle(issue2.origin, "definite")}`;
@@ -19193,8 +19899,8 @@ function withParser(schema, parser) {
19193
19899
  installCompiledUserMethods(clone2, schema, parser);
19194
19900
  return clone2;
19195
19901
  }
19196
- function installCompiledUserMethods(target, source, parser) {
19197
- const targetAny = target;
19902
+ function installCompiledUserMethods(target2, source, parser) {
19903
+ const targetAny = target2;
19198
19904
  const sourceAny = source;
19199
19905
  if (typeof sourceAny.safeParse === "function") {
19200
19906
  const originalSafeParse = sourceAny.safeParse;
@@ -21824,26 +22530,26 @@ var init_api = __esm({
21824
22530
  });
21825
22531
 
21826
22532
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/to-json-schema.js
21827
- function assignProps(target, ...sources) {
22533
+ function assignProps(target2, ...sources) {
21828
22534
  for (const source of sources) {
21829
22535
  for (const key of Reflect.ownKeys(source)) {
21830
22536
  if (Object.prototype.propertyIsEnumerable.call(source, key)) {
21831
- assignProp(target, key, source[key]);
22537
+ assignProp(target2, key, source[key]);
21832
22538
  }
21833
22539
  }
21834
22540
  }
21835
- return target;
22541
+ return target2;
21836
22542
  }
21837
22543
  function initializeContext(params) {
21838
- let target = params?.target ?? "draft-2020-12";
21839
- if (target === "draft-4")
21840
- target = "draft-04";
21841
- if (target === "draft-7")
21842
- target = "draft-07";
22544
+ let target2 = params?.target ?? "draft-2020-12";
22545
+ if (target2 === "draft-4")
22546
+ target2 = "draft-04";
22547
+ if (target2 === "draft-7")
22548
+ target2 = "draft-07";
21843
22549
  return {
21844
22550
  processors: params.processors ?? {},
21845
22551
  metadataRegistry: params?.metadata ?? globalRegistry,
21846
- target,
22552
+ target: target2,
21847
22553
  unrepresentable: params?.unrepresentable ?? "throw",
21848
22554
  override: params?.override ?? (() => {
21849
22555
  }),
@@ -22351,8 +23057,8 @@ var init_to_json_schema = __esm({
22351
23057
  return finalize(ctx, schema);
22352
23058
  };
22353
23059
  createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
22354
- const { libraryOptions, target } = params ?? {};
22355
- const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
23060
+ const { libraryOptions, target: target2 } = params ?? {};
23061
+ const ctx = initializeContext({ ...libraryOptions ?? {}, target: target2, io, processors });
22356
23062
  processSchema(schema, ctx);
22357
23063
  extractDefs(ctx, schema);
22358
23064
  return finalize(ctx, schema);
@@ -24870,8 +25576,8 @@ var init_schemas3 = __esm({
24870
25576
  catch(params) {
24871
25577
  return _catch2(this, params);
24872
25578
  },
24873
- pipe(target) {
24874
- return pipe(this, target);
25579
+ pipe(target2) {
25580
+ return pipe(this, target2);
24875
25581
  },
24876
25582
  readonly() {
24877
25583
  return readonly(this);
@@ -33290,8 +33996,8 @@ var require_resolve = __commonJS({
33290
33996
  }
33291
33997
  return count;
33292
33998
  }
33293
- function getFullPath(resolver, id = "", normalize) {
33294
- if (normalize !== false)
33999
+ function getFullPath(resolver, id = "", normalize2) {
34000
+ if (normalize2 !== false)
33295
34001
  id = normalizeId(id);
33296
34002
  const p = resolver.parse(id);
33297
34003
  return _getFullPath(resolver, p);
@@ -34886,7 +35592,7 @@ var require_fast_uri = __commonJS({
34886
35592
  }
34887
35593
  return decodedScheme;
34888
35594
  }
34889
- function normalize(uri, options) {
35595
+ function normalize2(uri, options) {
34890
35596
  if (typeof uri === "string") {
34891
35597
  uri = /** @type {T} */
34892
35598
  normalizeString(uri, options);
@@ -34929,58 +35635,58 @@ var require_fast_uri = __commonJS({
34929
35635
  schemelessOptions.skipEscape = true;
34930
35636
  return serialize(resolved, schemelessOptions);
34931
35637
  }
34932
- function resolveComponent(base, relative2, options, skipNormalization) {
34933
- const target = {};
35638
+ function resolveComponent(base, relative3, options, skipNormalization) {
35639
+ const target2 = {};
34934
35640
  if (!skipNormalization) {
34935
35641
  base = parse4(serialize(base, options), options);
34936
- relative2 = parse4(serialize(relative2, options), options);
35642
+ relative3 = parse4(serialize(relative3, options), options);
34937
35643
  }
34938
35644
  options = options || {};
34939
- if (!options.tolerant && relative2.scheme) {
34940
- target.scheme = relative2.scheme;
34941
- target.userinfo = relative2.userinfo;
34942
- target.host = relative2.host;
34943
- target.port = relative2.port;
34944
- target.path = removeDotSegments(relative2.path || "");
34945
- target.query = relative2.query;
35645
+ if (!options.tolerant && relative3.scheme) {
35646
+ target2.scheme = relative3.scheme;
35647
+ target2.userinfo = relative3.userinfo;
35648
+ target2.host = relative3.host;
35649
+ target2.port = relative3.port;
35650
+ target2.path = removeDotSegments(relative3.path || "");
35651
+ target2.query = relative3.query;
34946
35652
  } else {
34947
- if (relative2.userinfo !== void 0 || relative2.host !== void 0 || relative2.port !== void 0) {
34948
- target.userinfo = relative2.userinfo;
34949
- target.host = relative2.host;
34950
- target.port = relative2.port;
34951
- target.path = removeDotSegments(relative2.path || "");
34952
- target.query = relative2.query;
35653
+ if (relative3.userinfo !== void 0 || relative3.host !== void 0 || relative3.port !== void 0) {
35654
+ target2.userinfo = relative3.userinfo;
35655
+ target2.host = relative3.host;
35656
+ target2.port = relative3.port;
35657
+ target2.path = removeDotSegments(relative3.path || "");
35658
+ target2.query = relative3.query;
34953
35659
  } else {
34954
- if (!relative2.path) {
34955
- target.path = base.path;
34956
- if (relative2.query !== void 0) {
34957
- target.query = relative2.query;
35660
+ if (!relative3.path) {
35661
+ target2.path = base.path;
35662
+ if (relative3.query !== void 0) {
35663
+ target2.query = relative3.query;
34958
35664
  } else {
34959
- target.query = base.query;
35665
+ target2.query = base.query;
34960
35666
  }
34961
35667
  } else {
34962
- if (relative2.path[0] === "/") {
34963
- target.path = removeDotSegments(relative2.path);
35668
+ if (relative3.path[0] === "/") {
35669
+ target2.path = removeDotSegments(relative3.path);
34964
35670
  } else {
34965
35671
  if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
34966
- target.path = "/" + relative2.path;
35672
+ target2.path = "/" + relative3.path;
34967
35673
  } else if (!base.path) {
34968
- target.path = relative2.path;
35674
+ target2.path = relative3.path;
34969
35675
  } else {
34970
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative2.path;
35676
+ target2.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path;
34971
35677
  }
34972
- target.path = removeDotSegments(target.path);
35678
+ target2.path = removeDotSegments(target2.path);
34973
35679
  }
34974
- target.query = relative2.query;
35680
+ target2.query = relative3.query;
34975
35681
  }
34976
- target.userinfo = base.userinfo;
34977
- target.host = base.host;
34978
- target.port = base.port;
35682
+ target2.userinfo = base.userinfo;
35683
+ target2.host = base.host;
35684
+ target2.port = base.port;
34979
35685
  }
34980
- target.scheme = base.scheme;
35686
+ target2.scheme = base.scheme;
34981
35687
  }
34982
- target.fragment = relative2.fragment;
34983
- return target;
35688
+ target2.fragment = relative3.fragment;
35689
+ return target2;
34984
35690
  }
34985
35691
  function equal(uriA, uriB, options) {
34986
35692
  const normalizedA = normalizeComparableURI(uriA, options);
@@ -35264,7 +35970,7 @@ var require_fast_uri = __commonJS({
35264
35970
  }
35265
35971
  var fastUri = {
35266
35972
  SCHEMES,
35267
- normalize,
35973
+ normalize: normalize2,
35268
35974
  resolve: resolve5,
35269
35975
  resolveComponent,
35270
35976
  equal,
@@ -35646,12 +36352,12 @@ var require_core = __commonJS({
35646
36352
  return this;
35647
36353
  }
35648
36354
  keywordMetaschema.call(this, def);
35649
- const definition = {
36355
+ const definition2 = {
35650
36356
  ...def,
35651
36357
  type: (0, dataType_1.getJSONTypes)(def.type),
35652
36358
  schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
35653
36359
  };
35654
- (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
36360
+ (0, util_1.eachItem)(keyword, definition2.type.length === 0 ? (k) => addRule.call(this, k, definition2) : (k) => definition2.type.forEach((t) => addRule.call(this, k, definition2, t)));
35655
36361
  return this;
35656
36362
  }
35657
36363
  getKeyword(keyword) {
@@ -35844,9 +36550,9 @@ var require_core = __commonJS({
35844
36550
  throw new Error('$data keyword must have "code" or "validate" function');
35845
36551
  }
35846
36552
  }
35847
- function addRule(keyword, definition, dataType) {
36553
+ function addRule(keyword, definition2, dataType) {
35848
36554
  var _a3;
35849
- const post = definition === null || definition === void 0 ? void 0 : definition.post;
36555
+ const post = definition2 === null || definition2 === void 0 ? void 0 : definition2.post;
35850
36556
  if (dataType && post)
35851
36557
  throw new Error('keyword with "post" flag cannot have "type"');
35852
36558
  const { RULES } = this;
@@ -35856,22 +36562,22 @@ var require_core = __commonJS({
35856
36562
  RULES.rules.push(ruleGroup);
35857
36563
  }
35858
36564
  RULES.keywords[keyword] = true;
35859
- if (!definition)
36565
+ if (!definition2)
35860
36566
  return;
35861
36567
  const rule = {
35862
36568
  keyword,
35863
36569
  definition: {
35864
- ...definition,
35865
- type: (0, dataType_1.getJSONTypes)(definition.type),
35866
- schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
36570
+ ...definition2,
36571
+ type: (0, dataType_1.getJSONTypes)(definition2.type),
36572
+ schemaType: (0, dataType_1.getJSONTypes)(definition2.schemaType)
35867
36573
  }
35868
36574
  };
35869
- if (definition.before)
35870
- addBeforeRule.call(this, ruleGroup, rule, definition.before);
36575
+ if (definition2.before)
36576
+ addBeforeRule.call(this, ruleGroup, rule, definition2.before);
35871
36577
  else
35872
36578
  ruleGroup.rules.push(rule);
35873
36579
  RULES.all[keyword] = rule;
35874
- (_a3 = definition.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd));
36580
+ (_a3 = definition2.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd));
35875
36581
  }
35876
36582
  function addBeforeRule(ruleGroup, rule, before) {
35877
36583
  const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
@@ -39213,24 +39919,24 @@ var init_mcp = __esm({
39213
39919
  }
39214
39920
  });
39215
39921
  this.server.setRequestHandler(ListToolsRequestSchema, () => ({
39216
- tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => {
39922
+ tools: Object.entries(this._registeredTools).filter(([, tool2]) => tool2.enabled).map(([name, tool2]) => {
39217
39923
  const toolDefinition = {
39218
39924
  name,
39219
- title: tool.title,
39220
- description: tool.description,
39925
+ title: tool2.title,
39926
+ description: tool2.description,
39221
39927
  inputSchema: (() => {
39222
- const obj = normalizeObjectSchema(tool.inputSchema);
39928
+ const obj = normalizeObjectSchema(tool2.inputSchema);
39223
39929
  return obj ? toJsonSchemaCompat(obj, {
39224
39930
  strictUnions: true,
39225
39931
  pipeStrategy: "input"
39226
39932
  }) : EMPTY_OBJECT_JSON_SCHEMA;
39227
39933
  })(),
39228
- annotations: tool.annotations,
39229
- execution: tool.execution,
39230
- _meta: tool._meta
39934
+ annotations: tool2.annotations,
39935
+ execution: tool2.execution,
39936
+ _meta: tool2._meta
39231
39937
  };
39232
- if (tool.outputSchema) {
39233
- const obj = normalizeObjectSchema(tool.outputSchema);
39938
+ if (tool2.outputSchema) {
39939
+ const obj = normalizeObjectSchema(tool2.outputSchema);
39234
39940
  if (obj) {
39235
39941
  toolDefinition.outputSchema = toJsonSchemaCompat(obj, {
39236
39942
  strictUnions: true,
@@ -39243,16 +39949,16 @@ var init_mcp = __esm({
39243
39949
  }));
39244
39950
  this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
39245
39951
  try {
39246
- const tool = this._registeredTools[request.params.name];
39247
- if (!tool) {
39952
+ const tool2 = this._registeredTools[request.params.name];
39953
+ if (!tool2) {
39248
39954
  throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
39249
39955
  }
39250
- if (!tool.enabled) {
39956
+ if (!tool2.enabled) {
39251
39957
  throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
39252
39958
  }
39253
39959
  const isTaskRequest = !!request.params.task;
39254
- const taskSupport = tool.execution?.taskSupport;
39255
- const isTaskHandler = "createTask" in tool.handler;
39960
+ const taskSupport = tool2.execution?.taskSupport;
39961
+ const isTaskHandler = "createTask" in tool2.handler;
39256
39962
  if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) {
39257
39963
  throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);
39258
39964
  }
@@ -39260,14 +39966,14 @@ var init_mcp = __esm({
39260
39966
  throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);
39261
39967
  }
39262
39968
  if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) {
39263
- return await this.handleAutomaticTaskPolling(tool, request, extra);
39969
+ return await this.handleAutomaticTaskPolling(tool2, request, extra);
39264
39970
  }
39265
- const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
39266
- const result2 = await this.executeToolHandler(tool, args, extra);
39971
+ const args = await this.validateToolInput(tool2, request.params.arguments, request.params.name);
39972
+ const result2 = await this.executeToolHandler(tool2, args, extra);
39267
39973
  if (isTaskRequest) {
39268
39974
  return result2;
39269
39975
  }
39270
- await this.validateToolOutput(tool, result2, request.params.name);
39976
+ await this.validateToolOutput(tool2, result2, request.params.name);
39271
39977
  return result2;
39272
39978
  } catch (error62) {
39273
39979
  if (error62 instanceof McpError) {
@@ -39300,12 +40006,12 @@ var init_mcp = __esm({
39300
40006
  /**
39301
40007
  * Validates tool input arguments against the tool's input schema.
39302
40008
  */
39303
- async validateToolInput(tool, args, toolName) {
39304
- if (!tool.inputSchema) {
40009
+ async validateToolInput(tool2, args, toolName) {
40010
+ if (!tool2.inputSchema) {
39305
40011
  return void 0;
39306
40012
  }
39307
- const inputObj = normalizeObjectSchema(tool.inputSchema);
39308
- const schemaToParse = inputObj ?? tool.inputSchema;
40013
+ const inputObj = normalizeObjectSchema(tool2.inputSchema);
40014
+ const schemaToParse = inputObj ?? tool2.inputSchema;
39309
40015
  const parseResult = await safeParseAsync2(schemaToParse, args);
39310
40016
  if (!parseResult.success) {
39311
40017
  const error62 = "error" in parseResult ? parseResult.error : "Unknown error";
@@ -39317,8 +40023,8 @@ var init_mcp = __esm({
39317
40023
  /**
39318
40024
  * Validates tool output against the tool's output schema.
39319
40025
  */
39320
- async validateToolOutput(tool, result2, toolName) {
39321
- if (!tool.outputSchema) {
40026
+ async validateToolOutput(tool2, result2, toolName) {
40027
+ if (!tool2.outputSchema) {
39322
40028
  return;
39323
40029
  }
39324
40030
  if (!("content" in result2)) {
@@ -39330,7 +40036,7 @@ var init_mcp = __esm({
39330
40036
  if (!result2.structuredContent) {
39331
40037
  throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
39332
40038
  }
39333
- const outputObj = normalizeObjectSchema(tool.outputSchema);
40039
+ const outputObj = normalizeObjectSchema(tool2.outputSchema);
39334
40040
  const parseResult = await safeParseAsync2(outputObj, result2.structuredContent);
39335
40041
  if (!parseResult.success) {
39336
40042
  const error62 = "error" in parseResult ? parseResult.error : "Unknown error";
@@ -39341,15 +40047,15 @@ var init_mcp = __esm({
39341
40047
  /**
39342
40048
  * Executes a tool handler (either regular or task-based).
39343
40049
  */
39344
- async executeToolHandler(tool, args, extra) {
39345
- const handler = tool.handler;
40050
+ async executeToolHandler(tool2, args, extra) {
40051
+ const handler = tool2.handler;
39346
40052
  const isTaskHandler = "createTask" in handler;
39347
40053
  if (isTaskHandler) {
39348
40054
  if (!extra.taskStore) {
39349
40055
  throw new Error("No task store provided.");
39350
40056
  }
39351
40057
  const taskExtra = { ...extra, taskStore: extra.taskStore };
39352
- if (tool.inputSchema) {
40058
+ if (tool2.inputSchema) {
39353
40059
  const typedHandler = handler;
39354
40060
  return await Promise.resolve(typedHandler.createTask(args, taskExtra));
39355
40061
  } else {
@@ -39357,7 +40063,7 @@ var init_mcp = __esm({
39357
40063
  return await Promise.resolve(typedHandler.createTask(taskExtra));
39358
40064
  }
39359
40065
  }
39360
- if (tool.inputSchema) {
40066
+ if (tool2.inputSchema) {
39361
40067
  const typedHandler = handler;
39362
40068
  return await Promise.resolve(typedHandler(args, extra));
39363
40069
  } else {
@@ -39368,12 +40074,12 @@ var init_mcp = __esm({
39368
40074
  /**
39369
40075
  * Handles automatic task polling for tools with taskSupport 'optional'.
39370
40076
  */
39371
- async handleAutomaticTaskPolling(tool, request, extra) {
40077
+ async handleAutomaticTaskPolling(tool2, request, extra) {
39372
40078
  if (!extra.taskStore) {
39373
40079
  throw new Error("No task store provided for task-capable tool.");
39374
40080
  }
39375
- const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
39376
- const handler = tool.handler;
40081
+ const args = await this.validateToolInput(tool2, request.params.arguments, request.params.name);
40082
+ const handler = tool2.handler;
39377
40083
  const taskExtra = { ...extra, taskStore: extra.taskStore };
39378
40084
  const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : (
39379
40085
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -40011,8 +40717,8 @@ function errorJson(e) {
40011
40717
  return { code: "internal", message: e instanceof Error ? e.message.split("\n")[0] : String(e) };
40012
40718
  }
40013
40719
  async function callTool(engine, name, args, cwd) {
40014
- const tool = TOOLS[name];
40015
- return await tool.call(engine, args, cwd);
40720
+ const tool2 = TOOLS[name];
40721
+ return await tool2.call(engine, args, cwd);
40016
40722
  }
40017
40723
  function result(value, isError = false) {
40018
40724
  return {
@@ -40022,22 +40728,22 @@ function result(value, isError = false) {
40022
40728
  }
40023
40729
  function createMcpServer(engine, options = {}) {
40024
40730
  const server = new McpServer({ name: "veoflow", version: options.version ?? "0.0.0" });
40025
- for (const [name, tool] of Object.entries(TOOLS)) {
40731
+ for (const [name, tool2] of Object.entries(TOOLS)) {
40026
40732
  server.registerTool(
40027
40733
  name,
40028
- { description: tool.description, inputSchema: external_exports.strictObject(tool.input) },
40734
+ { description: tool2.description, inputSchema: external_exports.strictObject(tool2.input) },
40029
40735
  (() => result({ code: "internal", message: "unreachable" }, true))
40030
40736
  );
40031
40737
  }
40032
40738
  server.server.setRequestHandler(CallToolRequestSchema, async (request) => {
40033
40739
  const name = request.params.name;
40034
- const tool = Object.hasOwn(TOOLS, name) ? TOOLS[name] : void 0;
40035
- if (!tool)
40740
+ const tool2 = Object.hasOwn(TOOLS, name) ? TOOLS[name] : void 0;
40741
+ if (!tool2)
40036
40742
  return result(
40037
40743
  { code: "not-found", message: `no tool ${name}`, details: { kind: "tool", id: name } },
40038
40744
  true
40039
40745
  );
40040
- const parsed = external_exports.object(tool.input).strict().safeParse(request.params.arguments ?? {});
40746
+ const parsed = external_exports.object(tool2.input).strict().safeParse(request.params.arguments ?? {});
40041
40747
  if (!parsed.success) {
40042
40748
  const fields = [
40043
40749
  ...new Set(
@@ -40159,6 +40865,42 @@ var init_server3 = __esm({
40159
40865
  includeAll: external_exports.boolean().optional()
40160
40866
  },
40161
40867
  call: (e, a, cwd) => e.listUnresolvedSites(a, cwd)
40868
+ },
40869
+ search_nodes: {
40870
+ description: "Find functions or files by name (generic graph tool). Ranked: exact name, then prefix, then anywhere in the qualified name or path. Functions come with callers and callees (distinct functions) and callsIn/callsOut (calls). At most 100 results (default 20); `total` and `truncated` say how many matched.",
40871
+ input: {
40872
+ project,
40873
+ label: external_exports.enum(["Function", "File"]),
40874
+ text: external_exports.string().optional().describe("Name or part of a name or path; omitted lists everything"),
40875
+ filters: external_exports.object({
40876
+ path: external_exports.string().min(1).optional().describe("Only results whose file path starts with this prefix"),
40877
+ status: external_exports.enum(["analyzed", "degraded", "not_analyzed"]).optional().describe("Files only")
40878
+ }).optional(),
40879
+ limit: external_exports.number().int().positive().optional()
40880
+ },
40881
+ call: (e, a, cwd) => e.searchNodes(a, cwd)
40882
+ },
40883
+ aggregate: {
40884
+ description: "Counts grouped by a property (generic graph tool): File by status|language|source|folder; Function by file|kind|exported; UnresolvedCallSite by reason|status|file (filters.open: true for open questions only); CALLS by to|from|form|resolution (CALLS by 'to' gives the most-called functions, Function by 'file' the largest files). Sorted by count; at most 50 groups (limit lowers it).",
40885
+ input: {
40886
+ project,
40887
+ label: external_exports.enum(["File", "Function", "UnresolvedCallSite", "CALLS"]),
40888
+ groupBy: external_exports.string().min(1),
40889
+ filters: external_exports.object({
40890
+ path: external_exports.string().min(1).optional().describe("Only facts in files whose path starts with this prefix"),
40891
+ open: external_exports.boolean().optional().describe("UnresolvedCallSite only: open questions only")
40892
+ }).optional(),
40893
+ limit: external_exports.number().int().positive().optional()
40894
+ },
40895
+ call: (e, a, cwd) => e.aggregate(a, cwd)
40896
+ },
40897
+ file_outline: {
40898
+ description: "A file's functions in source order, each with its callers and callees (distinct functions), calls in and out, and unresolved call sites, plus the file's totals. At most 500 functions.",
40899
+ input: {
40900
+ project,
40901
+ file: external_exports.string().min(1).describe("A file id, as returned by search_nodes or listed files")
40902
+ },
40903
+ call: (e, a, cwd) => e.fileOutline(a, cwd)
40162
40904
  }
40163
40905
  };
40164
40906
  }
@@ -44125,7 +44867,7 @@ var require_parseTokenList = __commonJS({
44125
44867
  // node_modules/.pnpm/depd@2.0.0/node_modules/depd/index.js
44126
44868
  var require_depd = __commonJS({
44127
44869
  "node_modules/.pnpm/depd@2.0.0/node_modules/depd/index.js"(exports, module) {
44128
- var relative2 = __require("path").relative;
44870
+ var relative3 = __require("path").relative;
44129
44871
  module.exports = depd;
44130
44872
  var basePath = process.cwd();
44131
44873
  function containsNamespace(str3, namespace) {
@@ -44317,7 +45059,7 @@ var require_depd = __commonJS({
44317
45059
  return formatted;
44318
45060
  }
44319
45061
  function formatLocation(callSite) {
44320
- return relative2(basePath, callSite[0]) + ":" + callSite[1] + ":" + callSite[2];
45062
+ return relative3(basePath, callSite[0]) + ":" + callSite[1] + ":" + callSite[2];
44321
45063
  }
44322
45064
  function getStack() {
44323
45065
  var limit = Error.stackTraceLimit;
@@ -44850,10 +45592,10 @@ var require_send = __commonJS({
44850
45592
  var { parseTokenList } = require_parseTokenList();
44851
45593
  var { createHttpError } = require_createHttpError();
44852
45594
  var extname = path.extname;
44853
- var join8 = path.join;
44854
- var normalize = path.normalize;
45595
+ var join10 = path.join;
45596
+ var normalize2 = path.normalize;
44855
45597
  var resolve5 = path.resolve;
44856
- var sep3 = path.sep;
45598
+ var sep4 = path.sep;
44857
45599
  var Readable = stream.Readable;
44858
45600
  var BYTES_RANGE_REGEXP = /^ *bytes=/;
44859
45601
  var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1e3;
@@ -44930,20 +45672,20 @@ var require_send = __commonJS({
44930
45672
  let parts;
44931
45673
  if (root !== null) {
44932
45674
  if (path2) {
44933
- path2 = normalize("." + sep3 + path2);
45675
+ path2 = normalize2("." + sep4 + path2);
44934
45676
  }
44935
45677
  if (UP_PATH_REGEXP.test(path2)) {
44936
45678
  debug('malicious path "%s"', path2);
44937
45679
  return { statusCode: 403 };
44938
45680
  }
44939
- parts = path2.split(sep3);
44940
- path2 = normalize(join8(root, path2));
45681
+ parts = path2.split(sep4);
45682
+ path2 = normalize2(join10(root, path2));
44941
45683
  } else {
44942
45684
  if (UP_PATH_REGEXP.test(path2)) {
44943
45685
  debug('malicious path "%s"', path2);
44944
45686
  return { statusCode: 403 };
44945
45687
  }
44946
- parts = normalize(path2).split(sep3);
45688
+ parts = normalize2(path2).split(sep4);
44947
45689
  path2 = resolve5(path2);
44948
45690
  }
44949
45691
  return { path: path2, parts };
@@ -45220,7 +45962,7 @@ var require_send = __commonJS({
45220
45962
  let err;
45221
45963
  for (let i = 0; i < options.index.length; i++) {
45222
45964
  const index = options.index[i];
45223
- const p = join8(path2, index);
45965
+ const p = join10(path2, index);
45224
45966
  const { error: error62, stat } = await tryStat(p);
45225
45967
  if (error62) {
45226
45968
  err = error62;
@@ -45236,7 +45978,7 @@ var require_send = __commonJS({
45236
45978
  }
45237
45979
  async function sendFile(request, path2, options) {
45238
45980
  const { error: error62, stat } = await tryStat(path2);
45239
- if (error62 && error62.code === "ENOENT" && !extname(path2) && path2[path2.length - 1] !== sep3) {
45981
+ if (error62 && error62.code === "ENOENT" && !extname(path2) && path2[path2.length - 1] !== sep4) {
45240
45982
  let err = error62;
45241
45983
  for (let i = 0; i < options.extensions.length; i++) {
45242
45984
  const extension = options.extensions[i];
@@ -46195,8 +46937,8 @@ var require_dirList = __commonJS({
46195
46937
  FST_STATIC_MULTIROOT_LIST_CONFLICT
46196
46938
  } = require_errors2();
46197
46939
  var fastqConcurrency = Math.max(1, os.cpus().length - 1);
46198
- function isPathInsideRoot(root, target) {
46199
- const relativePath = path.relative(root, target);
46940
+ function isPathInsideRoot(root, target2) {
46941
+ const relativePath = path.relative(root, target2);
46200
46942
  return relativePath === "" || relativePath !== ".." && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath);
46201
46943
  }
46202
46944
  var dirList = {
@@ -46391,7 +47133,7 @@ var require_static = __commonJS({
46391
47133
  "use strict";
46392
47134
  var path = __require("node:path");
46393
47135
  var { fileURLToPath: fileURLToPath3 } = __require("node:url");
46394
- var { statSync: statSync4 } = __require("node:fs");
47136
+ var { statSync: statSync5 } = __require("node:fs");
46395
47137
  var { readdir, stat } = __require("node:fs/promises");
46396
47138
  var { basename: basename4 } = __require("node:path");
46397
47139
  var { glob } = require_index_min();
@@ -46568,8 +47310,8 @@ var require_static = __commonJS({
46568
47310
  }
46569
47311
  }
46570
47312
  }
46571
- for (const [dirname6, rootPath] of indexDirs.entries()) {
46572
- const pathname = dirname6 + (dirname6.endsWith("/") ? "" : "/");
47313
+ for (const [dirname7, rootPath] of indexDirs.entries()) {
47314
+ const pathname = dirname7 + (dirname7.endsWith("/") ? "" : "/");
46573
47315
  const file2 = "/" + pathname.replace(prefix, "");
46574
47316
  setUpHeadAndGet(routeOpts, pathname, file2, rootPath);
46575
47317
  if (opts.redirect === true) {
@@ -46835,7 +47577,7 @@ var require_static = __commonJS({
46835
47577
  }
46836
47578
  let pathStat;
46837
47579
  try {
46838
- pathStat = statSync4(rootPath);
47580
+ pathStat = statSync5(rootPath);
46839
47581
  } catch (e) {
46840
47582
  if (e.code === "ENOENT") {
46841
47583
  !suppressWarning && fastify.log.warn(`"root" path "${rootPath}" must exist`);
@@ -46939,7 +47681,7 @@ var require_static = __commonJS({
46939
47681
  return indexFiles.find((filename) => {
46940
47682
  const p = path.join(root, pathname, filename);
46941
47683
  try {
46942
- const stats = statSync4(p);
47684
+ const stats = statSync5(p);
46943
47685
  return !stats.isDirectory();
46944
47686
  } catch {
46945
47687
  return false;
@@ -47115,17 +47857,17 @@ var require_buffer_util = __commonJS({
47115
47857
  function concat(list, totalLength) {
47116
47858
  if (list.length === 0) return EMPTY_BUFFER;
47117
47859
  if (list.length === 1) return list[0];
47118
- const target = Buffer.allocUnsafe(totalLength);
47860
+ const target2 = Buffer.allocUnsafe(totalLength);
47119
47861
  let offset = 0;
47120
47862
  for (let i = 0; i < list.length; i++) {
47121
47863
  const buf = list[i];
47122
- target.set(buf, offset);
47864
+ target2.set(buf, offset);
47123
47865
  offset += buf.length;
47124
47866
  }
47125
47867
  if (offset < totalLength) {
47126
- return new FastBuffer(target.buffer, target.byteOffset, offset);
47868
+ return new FastBuffer(target2.buffer, target2.byteOffset, offset);
47127
47869
  }
47128
- return target;
47870
+ return target2;
47129
47871
  }
47130
47872
  function _mask(source, mask, output2, offset, length) {
47131
47873
  for (let i = 0; i < length; i++) {
@@ -48549,29 +49291,29 @@ var require_sender = __commonJS({
48549
49291
  offset += 2;
48550
49292
  payloadLength = 126;
48551
49293
  }
48552
- const target = Buffer.allocUnsafe(merge2 ? dataLength + offset : offset);
48553
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
48554
- if (options.rsv1) target[0] |= 64;
48555
- target[1] = payloadLength;
49294
+ const target2 = Buffer.allocUnsafe(merge2 ? dataLength + offset : offset);
49295
+ target2[0] = options.fin ? options.opcode | 128 : options.opcode;
49296
+ if (options.rsv1) target2[0] |= 64;
49297
+ target2[1] = payloadLength;
48556
49298
  if (payloadLength === 126) {
48557
- target.writeUInt16BE(dataLength, 2);
49299
+ target2.writeUInt16BE(dataLength, 2);
48558
49300
  } else if (payloadLength === 127) {
48559
- target[2] = target[3] = 0;
48560
- target.writeUIntBE(dataLength, 4, 6);
48561
- }
48562
- if (!options.mask) return [target, data];
48563
- target[1] |= 128;
48564
- target[offset - 4] = mask[0];
48565
- target[offset - 3] = mask[1];
48566
- target[offset - 2] = mask[2];
48567
- target[offset - 1] = mask[3];
48568
- if (skipMasking) return [target, data];
49301
+ target2[2] = target2[3] = 0;
49302
+ target2.writeUIntBE(dataLength, 4, 6);
49303
+ }
49304
+ if (!options.mask) return [target2, data];
49305
+ target2[1] |= 128;
49306
+ target2[offset - 4] = mask[0];
49307
+ target2[offset - 3] = mask[1];
49308
+ target2[offset - 2] = mask[2];
49309
+ target2[offset - 1] = mask[3];
49310
+ if (skipMasking) return [target2, data];
48569
49311
  if (merge2) {
48570
- applyMask(data, mask, target, offset, dataLength);
48571
- return [target];
49312
+ applyMask(data, mask, target2, offset, dataLength);
49313
+ return [target2];
48572
49314
  }
48573
49315
  applyMask(data, mask, data, 0, dataLength);
48574
- return [target, data];
49316
+ return [target2, data];
48575
49317
  }
48576
49318
  /**
48577
49319
  * Sends a close message to the other peer.
@@ -50812,16 +51554,16 @@ var require_buffer_list = __commonJS({
50812
51554
  }
50813
51555
  return keys;
50814
51556
  }
50815
- function _objectSpread(target) {
51557
+ function _objectSpread(target2) {
50816
51558
  for (var i = 1; i < arguments.length; i++) {
50817
51559
  var source = null != arguments[i] ? arguments[i] : {};
50818
51560
  i % 2 ? ownKeys(Object(source), true).forEach(function(key) {
50819
- _defineProperty(target, key, source[key]);
50820
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
50821
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
51561
+ _defineProperty(target2, key, source[key]);
51562
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target2, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
51563
+ Object.defineProperty(target2, key, Object.getOwnPropertyDescriptor(source, key));
50822
51564
  });
50823
51565
  }
50824
- return target;
51566
+ return target2;
50825
51567
  }
50826
51568
  function _defineProperty(obj, key, value) {
50827
51569
  key = _toPropertyKey(key);
@@ -50837,13 +51579,13 @@ var require_buffer_list = __commonJS({
50837
51579
  throw new TypeError("Cannot call a class as a function");
50838
51580
  }
50839
51581
  }
50840
- function _defineProperties(target, props) {
51582
+ function _defineProperties(target2, props) {
50841
51583
  for (var i = 0; i < props.length; i++) {
50842
51584
  var descriptor = props[i];
50843
51585
  descriptor.enumerable = descriptor.enumerable || false;
50844
51586
  descriptor.configurable = true;
50845
51587
  if ("value" in descriptor) descriptor.writable = true;
50846
- Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
51588
+ Object.defineProperty(target2, _toPropertyKey(descriptor.key), descriptor);
50847
51589
  }
50848
51590
  }
50849
51591
  function _createClass(Constructor, protoProps, staticProps) {
@@ -50871,8 +51613,8 @@ var require_buffer_list = __commonJS({
50871
51613
  var _require2 = __require("util");
50872
51614
  var inspect = _require2.inspect;
50873
51615
  var custom2 = inspect && inspect.custom || "inspect";
50874
- function copyBuffer(src, target, offset) {
50875
- Buffer2.prototype.copy.call(src, target, offset);
51616
+ function copyBuffer(src, target2, offset) {
51617
+ Buffer2.prototype.copy.call(src, target2, offset);
50876
51618
  }
50877
51619
  module.exports = /* @__PURE__ */ (function() {
50878
51620
  function BufferList() {
@@ -50922,7 +51664,7 @@ var require_buffer_list = __commonJS({
50922
51664
  }
50923
51665
  }, {
50924
51666
  key: "join",
50925
- value: function join8(s) {
51667
+ value: function join10(s) {
50926
51668
  if (this.length === 0) return "";
50927
51669
  var p = this.head;
50928
51670
  var ret = "" + p.data;
@@ -52436,16 +53178,16 @@ var require_from = __commonJS({
52436
53178
  }
52437
53179
  return keys;
52438
53180
  }
52439
- function _objectSpread(target) {
53181
+ function _objectSpread(target2) {
52440
53182
  for (var i = 1; i < arguments.length; i++) {
52441
53183
  var source = null != arguments[i] ? arguments[i] : {};
52442
53184
  i % 2 ? ownKeys(Object(source), true).forEach(function(key) {
52443
- _defineProperty(target, key, source[key]);
52444
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
52445
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
53185
+ _defineProperty(target2, key, source[key]);
53186
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target2, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
53187
+ Object.defineProperty(target2, key, Object.getOwnPropertyDescriptor(source, key));
52446
53188
  });
52447
53189
  }
52448
- return target;
53190
+ return target2;
52449
53191
  }
52450
53192
  function _defineProperty(obj, key, value) {
52451
53193
  key = _toPropertyKey(key);
@@ -60778,8 +61520,8 @@ var require_atomic_sleep = __commonJS({
60778
61520
  }
60779
61521
  throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");
60780
61522
  }
60781
- const target = Date.now() + Number(ms);
60782
- while (target > Date.now()) {
61523
+ const target2 = Date.now() + Number(ms);
61524
+ while (target2 > Date.now()) {
60783
61525
  }
60784
61526
  };
60785
61527
  module.exports = sleep3;
@@ -60906,7 +61648,7 @@ var require_sonic_boom = __commonJS({
60906
61648
  fsWrite = () => fs.write(this.fd, this._writingBuf, this.release);
60907
61649
  } else if (contentMode === void 0 || contentMode === kContentModeUtf8) {
60908
61650
  this._writingBuf = "";
60909
- this.write = write;
61651
+ this.write = write2;
60910
61652
  this.flush = flush;
60911
61653
  this.flushSync = flushSync;
60912
61654
  this._actualWrite = actualWrite;
@@ -61039,7 +61781,7 @@ var require_sonic_boom = __commonJS({
61039
61781
  }
61040
61782
  return Buffer.concat(bufs, len);
61041
61783
  }
61042
- function write(data) {
61784
+ function write2(data) {
61043
61785
  if (this.destroyed) {
61044
61786
  throw new Error("SonicBoom destroyed");
61045
61787
  }
@@ -61605,7 +62347,7 @@ var require_thread_stream = __commonJS({
61605
62347
  var { version: version3 } = require_package();
61606
62348
  var { EventEmitter: EventEmitter2 } = __require("events");
61607
62349
  var { Worker } = __require("worker_threads");
61608
- var { join: join8 } = __require("path");
62350
+ var { join: join10 } = __require("path");
61609
62351
  var { pathToFileURL } = __require("url");
61610
62352
  var { wait } = require_wait();
61611
62353
  var {
@@ -61656,7 +62398,7 @@ var require_thread_stream = __commonJS({
61656
62398
  function createWorker(stream, opts) {
61657
62399
  const { filename, workerData } = opts;
61658
62400
  const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {};
61659
- const toExecute = bundlerOverrides["thread-stream-worker"] || join8(__dirname, "lib", "worker.js");
62401
+ const toExecute = bundlerOverrides["thread-stream-worker"] || join10(__dirname, "lib", "worker.js");
61660
62402
  const worker = new Worker(toExecute, {
61661
62403
  ...opts.workerOpts,
61662
62404
  name: opts.workerOpts?.name || "thread-stream",
@@ -61700,7 +62442,7 @@ var require_thread_stream = __commonJS({
61700
62442
  }
61701
62443
  return;
61702
62444
  }
61703
- write(stream, leftover, noop);
62445
+ write2(stream, leftover, noop);
61704
62446
  continue;
61705
62447
  }
61706
62448
  if (leftover === 0) {
@@ -62004,7 +62746,7 @@ var require_thread_stream = __commonJS({
62004
62746
  });
62005
62747
  }
62006
62748
  }
62007
- function write(stream, maxBytes, cb) {
62749
+ function write2(stream, maxBytes, cb) {
62008
62750
  const current = Atomics.load(stream[kImpl].state, WRITE_INDEX);
62009
62751
  let offset = current;
62010
62752
  let remaining = maxBytes;
@@ -62089,7 +62831,7 @@ var require_thread_stream = __commonJS({
62089
62831
  } else if (leftover < 0) {
62090
62832
  throw new Error("overwritten");
62091
62833
  }
62092
- write(stream, leftover, cb);
62834
+ write2(stream, leftover, cb);
62093
62835
  }
62094
62836
  }
62095
62837
  function flushSync(stream) {
@@ -62122,9 +62864,9 @@ var require_transport = __commonJS({
62122
62864
  "node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/transport.js"(exports, module) {
62123
62865
  "use strict";
62124
62866
  var { createRequire: createRequire3 } = __require("module");
62125
- var { existsSync: existsSync7 } = __require("node:fs");
62867
+ var { existsSync: existsSync9 } = __require("node:fs");
62126
62868
  var getCallers = require_caller();
62127
- var { join: join8, isAbsolute, sep: sep3 } = __require("node:path");
62869
+ var { join: join10, isAbsolute: isAbsolute2, sep: sep4 } = __require("node:path");
62128
62870
  var { fileURLToPath: fileURLToPath3 } = __require("node:url");
62129
62871
  var sleep3 = require_atomic_sleep();
62130
62872
  var onExit = require_on_exit_leak_free();
@@ -62196,7 +62938,7 @@ var require_transport = __commonJS({
62196
62938
  return false;
62197
62939
  }
62198
62940
  }
62199
- return isAbsolute(path) && !existsSync7(path);
62941
+ return isAbsolute2(path) && !existsSync9(path);
62200
62942
  }
62201
62943
  function stripQuotes(value) {
62202
62944
  const first = value[0];
@@ -62270,14 +63012,14 @@ var require_transport = __commonJS({
62270
63012
  const options = {
62271
63013
  ...fullOptions.options
62272
63014
  };
62273
- const callers = typeof caller === "string" ? [caller] : caller;
63015
+ const callers2 = typeof caller === "string" ? [caller] : caller;
62274
63016
  const bundlerOverrides = typeof globalThis === "object" && Object.prototype.hasOwnProperty.call(globalThis, "__bundlerPathsOverrides") && globalThis.__bundlerPathsOverrides && typeof globalThis.__bundlerPathsOverrides === "object" ? globalThis.__bundlerPathsOverrides : /* @__PURE__ */ Object.create(null);
62275
- let target = fullOptions.target;
62276
- if (target && targets) {
63017
+ let target2 = fullOptions.target;
63018
+ if (target2 && targets) {
62277
63019
  throw new Error("only one of target or targets can be specified");
62278
63020
  }
62279
63021
  if (targets) {
62280
- target = bundlerOverrides["pino-worker"] || join8(__dirname, "worker.js");
63022
+ target2 = bundlerOverrides["pino-worker"] || join10(__dirname, "worker.js");
62281
63023
  options.targets = targets.filter((dest) => dest.target).map((dest) => {
62282
63024
  return {
62283
63025
  ...dest,
@@ -62295,7 +63037,7 @@ var require_transport = __commonJS({
62295
63037
  });
62296
63038
  });
62297
63039
  } else if (pipeline) {
62298
- target = bundlerOverrides["pino-worker"] || join8(__dirname, "worker.js");
63040
+ target2 = bundlerOverrides["pino-worker"] || join10(__dirname, "worker.js");
62299
63041
  options.pipelines = [pipeline.map((dest) => {
62300
63042
  return {
62301
63043
  ...dest,
@@ -62310,20 +63052,20 @@ var require_transport = __commonJS({
62310
63052
  options.dedupe = dedupe;
62311
63053
  }
62312
63054
  options.pinoWillSendConfig = true;
62313
- const name = targets || pipeline ? "pino.transport" : target;
62314
- return buildStream(fixTarget(target), options, worker, sync, name);
63055
+ const name = targets || pipeline ? "pino.transport" : target2;
63056
+ return buildStream(fixTarget(target2), options, worker, sync, name);
62315
63057
  function fixTarget(origin) {
62316
63058
  origin = bundlerOverrides[origin] || origin;
62317
- if (isAbsolute(origin) || origin.indexOf("file://") === 0) {
63059
+ if (isAbsolute2(origin) || origin.indexOf("file://") === 0) {
62318
63060
  return origin;
62319
63061
  }
62320
63062
  if (origin === "pino/file") {
62321
- return join8(__dirname, "..", "file.js");
63063
+ return join10(__dirname, "..", "file.js");
62322
63064
  }
62323
63065
  let fixTarget2;
62324
- for (const filePath of callers) {
63066
+ for (const filePath of callers2) {
62325
63067
  try {
62326
- const context = filePath === "node:repl" ? process.cwd() + sep3 : filePath;
63068
+ const context = filePath === "node:repl" ? process.cwd() + sep4 : filePath;
62327
63069
  fixTarget2 = createRequire3(context).resolve(origin);
62328
63070
  break;
62329
63071
  } catch (err) {
@@ -62972,7 +63714,7 @@ var require_proto = __commonJS({
62972
63714
  return "Pino";
62973
63715
  },
62974
63716
  [lsCacheSym]: initialLsCache,
62975
- [writeSym]: write,
63717
+ [writeSym]: write2,
62976
63718
  [asJsonSym]: asJson,
62977
63719
  [getLevelSym]: getLevel,
62978
63720
  [setLevelSym]: setLevel
@@ -63075,7 +63817,7 @@ var require_proto = __commonJS({
63075
63817
  function defaultMixinMergeStrategy(mergeObject, mixinObject) {
63076
63818
  return Object.assign(mixinObject, mergeObject);
63077
63819
  }
63078
- function write(_obj, msg, num) {
63820
+ function write2(_obj, msg, num) {
63079
63821
  const t = this[timeSym]();
63080
63822
  const mixin = this[mixinSym];
63081
63823
  const errorKey = this[errorKeySym];
@@ -63298,7 +64040,7 @@ var require_safe_stable_stringify = __commonJS({
63298
64040
  return circularValue;
63299
64041
  }
63300
64042
  let res = "";
63301
- let join8 = ",";
64043
+ let join10 = ",";
63302
64044
  const originalIndentation = indentation;
63303
64045
  if (Array.isArray(value)) {
63304
64046
  if (value.length === 0) {
@@ -63312,7 +64054,7 @@ var require_safe_stable_stringify = __commonJS({
63312
64054
  indentation += spacer;
63313
64055
  res += `
63314
64056
  ${indentation}`;
63315
- join8 = `,
64057
+ join10 = `,
63316
64058
  ${indentation}`;
63317
64059
  }
63318
64060
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
@@ -63320,13 +64062,13 @@ ${indentation}`;
63320
64062
  for (; i < maximumValuesToStringify - 1; i++) {
63321
64063
  const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
63322
64064
  res += tmp2 !== void 0 ? tmp2 : "null";
63323
- res += join8;
64065
+ res += join10;
63324
64066
  }
63325
64067
  const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
63326
64068
  res += tmp !== void 0 ? tmp : "null";
63327
64069
  if (value.length - 1 > maximumBreadth) {
63328
64070
  const removedKeys = value.length - maximumBreadth - 1;
63329
- res += `${join8}"... ${getItemCount(removedKeys)} not stringified"`;
64071
+ res += `${join10}"... ${getItemCount(removedKeys)} not stringified"`;
63330
64072
  }
63331
64073
  if (spacer !== "") {
63332
64074
  res += `
@@ -63347,7 +64089,7 @@ ${originalIndentation}`;
63347
64089
  let separator = "";
63348
64090
  if (spacer !== "") {
63349
64091
  indentation += spacer;
63350
- join8 = `,
64092
+ join10 = `,
63351
64093
  ${indentation}`;
63352
64094
  whitespace = " ";
63353
64095
  }
@@ -63361,13 +64103,13 @@ ${indentation}`;
63361
64103
  const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation);
63362
64104
  if (tmp !== void 0) {
63363
64105
  res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
63364
- separator = join8;
64106
+ separator = join10;
63365
64107
  }
63366
64108
  }
63367
64109
  if (keyLength > maximumBreadth) {
63368
64110
  const removedKeys = keyLength - maximumBreadth;
63369
64111
  res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
63370
- separator = join8;
64112
+ separator = join10;
63371
64113
  }
63372
64114
  if (spacer !== "" && separator.length > 1) {
63373
64115
  res = `
@@ -63408,7 +64150,7 @@ ${originalIndentation}`;
63408
64150
  }
63409
64151
  const originalIndentation = indentation;
63410
64152
  let res = "";
63411
- let join8 = ",";
64153
+ let join10 = ",";
63412
64154
  if (Array.isArray(value)) {
63413
64155
  if (value.length === 0) {
63414
64156
  return "[]";
@@ -63421,7 +64163,7 @@ ${originalIndentation}`;
63421
64163
  indentation += spacer;
63422
64164
  res += `
63423
64165
  ${indentation}`;
63424
- join8 = `,
64166
+ join10 = `,
63425
64167
  ${indentation}`;
63426
64168
  }
63427
64169
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
@@ -63429,13 +64171,13 @@ ${indentation}`;
63429
64171
  for (; i < maximumValuesToStringify - 1; i++) {
63430
64172
  const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
63431
64173
  res += tmp2 !== void 0 ? tmp2 : "null";
63432
- res += join8;
64174
+ res += join10;
63433
64175
  }
63434
64176
  const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
63435
64177
  res += tmp !== void 0 ? tmp : "null";
63436
64178
  if (value.length - 1 > maximumBreadth) {
63437
64179
  const removedKeys = value.length - maximumBreadth - 1;
63438
- res += `${join8}"... ${getItemCount(removedKeys)} not stringified"`;
64180
+ res += `${join10}"... ${getItemCount(removedKeys)} not stringified"`;
63439
64181
  }
63440
64182
  if (spacer !== "") {
63441
64183
  res += `
@@ -63448,7 +64190,7 @@ ${originalIndentation}`;
63448
64190
  let whitespace = "";
63449
64191
  if (spacer !== "") {
63450
64192
  indentation += spacer;
63451
- join8 = `,
64193
+ join10 = `,
63452
64194
  ${indentation}`;
63453
64195
  whitespace = " ";
63454
64196
  }
@@ -63457,7 +64199,7 @@ ${indentation}`;
63457
64199
  const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation);
63458
64200
  if (tmp !== void 0) {
63459
64201
  res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
63460
- separator = join8;
64202
+ separator = join10;
63461
64203
  }
63462
64204
  }
63463
64205
  if (spacer !== "" && separator.length > 1) {
@@ -63515,20 +64257,20 @@ ${originalIndentation}`;
63515
64257
  indentation += spacer;
63516
64258
  let res2 = `
63517
64259
  ${indentation}`;
63518
- const join9 = `,
64260
+ const join11 = `,
63519
64261
  ${indentation}`;
63520
64262
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
63521
64263
  let i = 0;
63522
64264
  for (; i < maximumValuesToStringify - 1; i++) {
63523
64265
  const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation);
63524
64266
  res2 += tmp2 !== void 0 ? tmp2 : "null";
63525
- res2 += join9;
64267
+ res2 += join11;
63526
64268
  }
63527
64269
  const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
63528
64270
  res2 += tmp !== void 0 ? tmp : "null";
63529
64271
  if (value.length - 1 > maximumBreadth) {
63530
64272
  const removedKeys = value.length - maximumBreadth - 1;
63531
- res2 += `${join9}"... ${getItemCount(removedKeys)} not stringified"`;
64273
+ res2 += `${join11}"... ${getItemCount(removedKeys)} not stringified"`;
63532
64274
  }
63533
64275
  res2 += `
63534
64276
  ${originalIndentation}`;
@@ -63544,16 +64286,16 @@ ${originalIndentation}`;
63544
64286
  return '"[Object]"';
63545
64287
  }
63546
64288
  indentation += spacer;
63547
- const join8 = `,
64289
+ const join10 = `,
63548
64290
  ${indentation}`;
63549
64291
  let res = "";
63550
64292
  let separator = "";
63551
64293
  let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
63552
64294
  if (isTypedArrayWithEntries(value)) {
63553
- res += stringifyTypedArray(value, join8, maximumBreadth);
64295
+ res += stringifyTypedArray(value, join10, maximumBreadth);
63554
64296
  keys = keys.slice(value.length);
63555
64297
  maximumPropertiesToStringify -= value.length;
63556
- separator = join8;
64298
+ separator = join10;
63557
64299
  }
63558
64300
  if (deterministic) {
63559
64301
  keys = sort(keys, comparator);
@@ -63564,13 +64306,13 @@ ${indentation}`;
63564
64306
  const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation);
63565
64307
  if (tmp !== void 0) {
63566
64308
  res += `${separator}${strEscape(key2)}: ${tmp}`;
63567
- separator = join8;
64309
+ separator = join10;
63568
64310
  }
63569
64311
  }
63570
64312
  if (keyLength > maximumBreadth) {
63571
64313
  const removedKeys = keyLength - maximumBreadth;
63572
64314
  res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
63573
- separator = join8;
64315
+ separator = join10;
63574
64316
  }
63575
64317
  if (separator !== "") {
63576
64318
  res = `
@@ -63736,7 +64478,7 @@ var require_multistream = __commonJS({
63736
64478
  });
63737
64479
  }
63738
64480
  const res = {
63739
- write,
64481
+ write: write2,
63740
64482
  add,
63741
64483
  remove,
63742
64484
  emit,
@@ -63756,7 +64498,7 @@ var require_multistream = __commonJS({
63756
64498
  }
63757
64499
  streamsArray = null;
63758
64500
  return res;
63759
- function write(data) {
64501
+ function write2(data) {
63760
64502
  let dest;
63761
64503
  const level = this.lastLevel;
63762
64504
  const { streams } = this;
@@ -63858,7 +64600,7 @@ var require_multistream = __commonJS({
63858
64600
  };
63859
64601
  }
63860
64602
  return {
63861
- write,
64603
+ write: write2,
63862
64604
  add,
63863
64605
  remove,
63864
64606
  minLevel: level,
@@ -63971,11 +64713,11 @@ var require_pino = __commonJS({
63971
64713
  depthLimit: 5,
63972
64714
  edgeLimit: 100
63973
64715
  };
63974
- var normalize = createArgsNormalizer(defaultOptions2);
64716
+ var normalize2 = createArgsNormalizer(defaultOptions2);
63975
64717
  var serializers = Object.assign(/* @__PURE__ */ Object.create(null), stdSerializers);
63976
64718
  function pino(...args) {
63977
64719
  const instance = {};
63978
- const { opts, stream } = normalize(instance, caller(), ...args);
64720
+ const { opts, stream } = normalize2(instance, caller(), ...args);
63979
64721
  if (opts.level && typeof opts.level === "string" && DEFAULT_LEVELS[opts.level.toLowerCase()] !== void 0) opts.level = opts.level.toLowerCase();
63980
64722
  const {
63981
64723
  redact,
@@ -70411,7 +71153,7 @@ var require_fast_uri2 = __commonJS({
70411
71153
  }
70412
71154
  return decodedScheme;
70413
71155
  }
70414
- function normalize(uri, options) {
71156
+ function normalize2(uri, options) {
70415
71157
  if (typeof uri === "string") {
70416
71158
  uri = /** @type {T} */
70417
71159
  normalizeString(uri, options);
@@ -70454,64 +71196,64 @@ var require_fast_uri2 = __commonJS({
70454
71196
  schemelessOptions.skipEscape = true;
70455
71197
  return serialize(resolved, schemelessOptions);
70456
71198
  }
70457
- function copyHost(target, source) {
70458
- target.host = source.host;
71199
+ function copyHost(target2, source) {
71200
+ target2.host = source.host;
70459
71201
  if (source.ipv6Zone !== void 0) {
70460
- target.ipv6Zone = source.ipv6Zone;
71202
+ target2.ipv6Zone = source.ipv6Zone;
70461
71203
  }
70462
71204
  }
70463
- function resolveComponent(base, relative2, options, skipNormalization) {
70464
- const target = {};
71205
+ function resolveComponent(base, relative3, options, skipNormalization) {
71206
+ const target2 = {};
70465
71207
  if (!skipNormalization) {
70466
71208
  base = parse4(serialize(base, options), options);
70467
- relative2 = parse4(serialize(relative2, options), options);
71209
+ relative3 = parse4(serialize(relative3, options), options);
70468
71210
  }
70469
71211
  options = options || {};
70470
- if (!options.tolerant && relative2.scheme) {
70471
- target.scheme = relative2.scheme;
70472
- target.userinfo = relative2.userinfo;
70473
- copyHost(target, relative2);
70474
- target.port = relative2.port;
70475
- target.path = removeDotSegments(relative2.path || "");
70476
- target.query = relative2.query;
71212
+ if (!options.tolerant && relative3.scheme) {
71213
+ target2.scheme = relative3.scheme;
71214
+ target2.userinfo = relative3.userinfo;
71215
+ copyHost(target2, relative3);
71216
+ target2.port = relative3.port;
71217
+ target2.path = removeDotSegments(relative3.path || "");
71218
+ target2.query = relative3.query;
70477
71219
  } else {
70478
- if (relative2.userinfo !== void 0 || relative2.host !== void 0 || relative2.port !== void 0) {
70479
- target.userinfo = relative2.userinfo;
70480
- copyHost(target, relative2);
70481
- target.port = relative2.port;
70482
- target.path = removeDotSegments(relative2.path || "");
70483
- target.query = relative2.query;
71220
+ if (relative3.userinfo !== void 0 || relative3.host !== void 0 || relative3.port !== void 0) {
71221
+ target2.userinfo = relative3.userinfo;
71222
+ copyHost(target2, relative3);
71223
+ target2.port = relative3.port;
71224
+ target2.path = removeDotSegments(relative3.path || "");
71225
+ target2.query = relative3.query;
70484
71226
  } else {
70485
- if (!relative2.path) {
70486
- target.path = base.path;
70487
- if (relative2.query !== void 0) {
70488
- target.query = relative2.query;
71227
+ if (!relative3.path) {
71228
+ target2.path = base.path;
71229
+ if (relative3.query !== void 0) {
71230
+ target2.query = relative3.query;
70489
71231
  } else {
70490
- target.query = base.query;
71232
+ target2.query = base.query;
70491
71233
  }
70492
71234
  } else {
70493
- if (relative2.path[0] === "/") {
70494
- target.path = removeDotSegments(relative2.path);
71235
+ if (relative3.path[0] === "/") {
71236
+ target2.path = removeDotSegments(relative3.path);
70495
71237
  } else {
70496
71238
  if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
70497
- target.path = "/" + relative2.path;
71239
+ target2.path = "/" + relative3.path;
70498
71240
  } else if (!base.path) {
70499
- target.path = relative2.path;
71241
+ target2.path = relative3.path;
70500
71242
  } else {
70501
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative2.path;
71243
+ target2.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path;
70502
71244
  }
70503
- target.path = removeDotSegments(target.path);
71245
+ target2.path = removeDotSegments(target2.path);
70504
71246
  }
70505
- target.query = relative2.query;
71247
+ target2.query = relative3.query;
70506
71248
  }
70507
- target.userinfo = base.userinfo;
70508
- copyHost(target, base);
70509
- target.port = base.port;
71249
+ target2.userinfo = base.userinfo;
71250
+ copyHost(target2, base);
71251
+ target2.port = base.port;
70510
71252
  }
70511
- target.scheme = base.scheme;
71253
+ target2.scheme = base.scheme;
70512
71254
  }
70513
- target.fragment = relative2.fragment;
70514
- return target;
71255
+ target2.fragment = relative3.fragment;
71256
+ return target2;
70515
71257
  }
70516
71258
  function equal(uriA, uriB, options) {
70517
71259
  const normalizedA = normalizeComparableURI(uriA, options);
@@ -70804,7 +71546,7 @@ var require_fast_uri2 = __commonJS({
70804
71546
  }
70805
71547
  var fastUri = {
70806
71548
  SCHEMES,
70807
- normalize,
71549
+ normalize: normalize2,
70808
71550
  resolve: resolve5,
70809
71551
  resolveComponent,
70810
71552
  equal,
@@ -80933,8 +81675,8 @@ var require_response = __commonJS({
80933
81675
  function Response(req, onEnd, reject) {
80934
81676
  http.ServerResponse.call(this, req);
80935
81677
  if (req._lightMyRequest?.payloadAsStream) {
80936
- const read = this.emit.bind(this, "drain");
80937
- this._lightMyRequest = { headers: null, trailers: {}, stream: new Readable({ read }) };
81678
+ const read2 = this.emit.bind(this, "drain");
81679
+ this._lightMyRequest = { headers: null, trailers: {}, stream: new Readable({ read: read2 }) };
80938
81680
  const signal = req._lightMyRequest.signal;
80939
81681
  if (signal) {
80940
81682
  addAbortSignal(signal, this._lightMyRequest.stream);
@@ -82938,9 +83680,1154 @@ ${body}`);
82938
83680
  }
82939
83681
  });
82940
83682
 
83683
+ // packages/agents/src/types.ts
83684
+ var init_types3 = __esm({
83685
+ "packages/agents/src/types.ts"() {
83686
+ "use strict";
83687
+ }
83688
+ });
83689
+
83690
+ // packages/agents/src/config.ts
83691
+ import { chmodSync, existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync3, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
83692
+ import { dirname as dirname4, join as join7 } from "node:path";
83693
+ function read(home) {
83694
+ const path = configPath(home);
83695
+ if (!existsSync6(path)) return {};
83696
+ try {
83697
+ return JSON.parse(readFileSync3(path, "utf8"));
83698
+ } catch {
83699
+ throw new VeoError("invalid-arguments", `${path} is not valid JSON; fix or delete it`);
83700
+ }
83701
+ }
83702
+ function write(home, config2) {
83703
+ const path = configPath(home);
83704
+ mkdirSync4(dirname4(path), { recursive: true });
83705
+ const tmp = `${path}.tmp`;
83706
+ rmSync2(tmp, { force: true });
83707
+ writeFileSync2(tmp, JSON.stringify(config2, null, 2) + "\n", { mode: 384, flag: "wx" });
83708
+ chmodSync(tmp, 384);
83709
+ renameSync3(tmp, path);
83710
+ }
83711
+ function loadSettings(home, env = process.env) {
83712
+ const m = read(home).model ?? {};
83713
+ const str3 = (v) => typeof v === "string" ? v.trim() : "";
83714
+ const fromFile = str3(m.apiKey) || null;
83715
+ const fromEnv = env.OPENROUTER_API_KEY?.trim() || null;
83716
+ return {
83717
+ baseUrl: str3(m.baseUrl) || DEFAULT_BASE_URL,
83718
+ model: str3(m.model) || DEFAULT_MODEL,
83719
+ apiKey: fromFile ?? fromEnv,
83720
+ keySource: fromFile ? "config" : fromEnv ? "env" : null
83721
+ };
83722
+ }
83723
+ function publicSettings(s) {
83724
+ return {
83725
+ baseUrl: s.baseUrl,
83726
+ model: s.model,
83727
+ apiKeySet: s.apiKey !== null,
83728
+ // A hint only for keys long enough that four characters reveal nothing useful.
83729
+ apiKeyHint: s.apiKey && s.apiKey.length >= 12 ? s.apiKey.slice(-4) : null,
83730
+ keySource: s.keySource,
83731
+ configured: s.apiKey !== null
83732
+ };
83733
+ }
83734
+ function saveSettings(home, update, env = process.env) {
83735
+ const config2 = read(home);
83736
+ const m = { ...config2.model ?? {} };
83737
+ if (update.baseUrl !== void 0) {
83738
+ const url2 = update.baseUrl.trim();
83739
+ if (url2 && !/^https?:\/\/[^\s]+$/.test(url2))
83740
+ throw new VeoError("invalid-arguments", `base URL must start with http:// or https:// (got "${url2}")`, {
83741
+ fields: ["baseUrl"]
83742
+ });
83743
+ if (url2) m.baseUrl = url2.replace(/\/+$/, "");
83744
+ else delete m.baseUrl;
83745
+ }
83746
+ if (update.model !== void 0) {
83747
+ const model = update.model.trim();
83748
+ if (model) m.model = model;
83749
+ else delete m.model;
83750
+ }
83751
+ if (update.apiKey === null) delete m.apiKey;
83752
+ else if (update.apiKey !== void 0 && update.apiKey.trim()) m.apiKey = update.apiKey.trim();
83753
+ write(home, { ...config2, model: m });
83754
+ return loadSettings(home, env);
83755
+ }
83756
+ var DEFAULT_BASE_URL, DEFAULT_MODEL, configPath;
83757
+ var init_config = __esm({
83758
+ "packages/agents/src/config.ts"() {
83759
+ "use strict";
83760
+ init_src();
83761
+ DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
83762
+ DEFAULT_MODEL = "anthropic/claude-sonnet-5.5";
83763
+ configPath = (home) => join7(home, "config.json");
83764
+ }
83765
+ });
83766
+
83767
+ // packages/agents/src/grammar.ts
83768
+ function tool(ctx, name, args, run) {
83769
+ ctx.calls.push({ tool: name, args });
83770
+ return run();
83771
+ }
83772
+ function say(qualifiedName) {
83773
+ if (!qualifiedName.includes("<")) return qualifiedName;
83774
+ return qualifiedName.split(/\.(?![^<]*>)/).map((part) => {
83775
+ const m = /^<([a-z]+)(?::([^>]*))?>(?:#\d+)?$/.exec(part);
83776
+ if (!m) return part;
83777
+ if (m[1] === "callback") return `${m[2] ?? "anonymous"} callback`;
83778
+ if (m[1] === "module") return "top level";
83779
+ if (m[1] === "iife") return "immediately invoked function";
83780
+ return `${m[1]} function`;
83781
+ }).join(" \u203A ");
83782
+ }
83783
+ function parseTarget(raw) {
83784
+ let text = raw.trim().replace(/[?.!]+$/, "");
83785
+ let path;
83786
+ const inFile = /^(.+?)\s+(?:in|from)\s+([\w@./-]+\.[A-Za-z0-9]+)$/.exec(text);
83787
+ if (inFile) {
83788
+ text = inFile[1];
83789
+ path = inFile[2];
83790
+ }
83791
+ const name = text.replace(/^(?:the\s+)?(?:function|method|class)\s+/i, "").replace(/[`'"]/g, "").replace(/\(\)$/, "").trim();
83792
+ return path ? { name, path } : { name };
83793
+ }
83794
+ function resolveFunction(ctx, raw) {
83795
+ const { name, path } = parseTarget(raw);
83796
+ const filters = path ? { path } : void 0;
83797
+ const args = { label: "Function", text: name, ...filters ? { filters } : {}, limit: 20 };
83798
+ const r = tool(
83799
+ ctx,
83800
+ "search_nodes",
83801
+ args,
83802
+ () => ctx.engine.searchNodes({
83803
+ project: ctx.project,
83804
+ label: "Function",
83805
+ text: name,
83806
+ limit: 20,
83807
+ ...filters ? { filters } : {}
83808
+ })
83809
+ );
83810
+ const lower = name.toLowerCase();
83811
+ const exact = r.results.filter(
83812
+ (h) => h.name.toLowerCase() === lower || h.name.toLowerCase().split(".").pop() === lower
83813
+ );
83814
+ const here = ctx.file ? exact.filter((h) => h.id.startsWith(`${ctx.file}:`)) : [];
83815
+ const full = exact.filter((h) => h.name.toLowerCase() === lower);
83816
+ const pick2 = here.length === 1 ? here : full.length > 0 ? full : exact;
83817
+ if (pick2.length === 1) return { kind: "one", hit: pick2[0], name };
83818
+ if (pick2.length > 1) return { kind: "many", hits: pick2, total: pick2.length, name };
83819
+ return { kind: "none", near: r.results.slice(0, 8), name };
83820
+ }
83821
+ function resolveFile(ctx, raw) {
83822
+ const name = raw.trim().replace(/[?.!`'"]+$/g, "").replace(/^[`'"]|^(?:the\s+)?file\s+/gi, "");
83823
+ const r = tool(
83824
+ ctx,
83825
+ "search_nodes",
83826
+ { label: "File", text: name, limit: 20 },
83827
+ () => ctx.engine.searchNodes({ project: ctx.project, label: "File", text: name, limit: 20 })
83828
+ );
83829
+ const lower = name.toLowerCase();
83830
+ const exact = r.results.filter(
83831
+ (h) => h.path.toLowerCase() === lower || h.path.toLowerCase().endsWith(`/${lower}`)
83832
+ );
83833
+ if (exact.length === 1) return { kind: "one", hit: exact[0] };
83834
+ if (exact.length > 1) return { kind: "many", hits: exact, name };
83835
+ if (r.results.length === 1) return { kind: "one", hit: r.results[0] };
83836
+ return { kind: r.results.length ? "many" : "none", hits: r.results.slice(0, 10), name };
83837
+ }
83838
+ function unresolvedName(ctx, r, verb) {
83839
+ if (r.kind === "none" && r.near.length === 0 && ctx.fallThrough) return null;
83840
+ if (r.kind === "many")
83841
+ return {
83842
+ summary: `"${r.name}" matches ${plural2(r.hits.length, "function")}; which one did you mean?`,
83843
+ results: r.hits.map(fnItem),
83844
+ suggestions: r.hits.slice(0, 3).map((h) => `${verb} ${h.name} in ${h.path}`)
83845
+ };
83846
+ return {
83847
+ summary: `No function named "${r.name}" in the last analysis.`,
83848
+ results: r.near.map(fnItem),
83849
+ ...r.near.length ? { note: "Functions with similar names are listed." } : {}
83850
+ };
83851
+ }
83852
+ function normalize(question) {
83853
+ return question.trim().replace(/\s+/g, " ").replace(/^(?:please\s+|can you\s+|could you\s+)?(?:tell me\s+|show me\s+(?=the\s+))?/i, "").replace(/[?!.\s]+$/, "");
83854
+ }
83855
+ function answerWithGrammar(engine, project2, question, options = {}) {
83856
+ const text = normalize(question);
83857
+ for (const intent of INTENTS)
83858
+ for (const pattern of intent.patterns) {
83859
+ const m = text.match(new RegExp(pattern.source, `${pattern.flags.replace("i", "")}i`));
83860
+ if (!m) continue;
83861
+ const ctx = {
83862
+ engine,
83863
+ project: project2,
83864
+ calls: [],
83865
+ fallThrough: options.fallThrough ?? false,
83866
+ ...options.file ? { file: options.file } : {}
83867
+ };
83868
+ const body = intent.handle(ctx, m, question);
83869
+ if (body === null) return null;
83870
+ return { question, via: "grammar", intent: intent.name, toolCalls: ctx.calls, ...body };
83871
+ }
83872
+ return null;
83873
+ }
83874
+ var IN_FILE_NOTE, target, plural2, fnItem, fileItem, callers, callees, definition, fileFunctions, fileQuestions, TOP, largestFiles, mostCalled, questionsByReason, filesByQuestions, overview, REASONS, STATUS_WORDS, LANGUAGE_WORDS, INTENTS, EXAMPLES, HELP_SUMMARY;
83875
+ var init_grammar = __esm({
83876
+ "packages/agents/src/grammar.ts"() {
83877
+ "use strict";
83878
+ IN_FILE_NOTE = "Calls are linked within each file for now; calls from other files are not shown yet.";
83879
+ target = (m) => m[2] ? `${m[1]} in ${m[2]}` : m[1];
83880
+ plural2 = (n, one, many = `${one}s`) => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
83881
+ fnItem = (h) => ({
83882
+ kind: "function",
83883
+ id: h.id,
83884
+ label: h.name,
83885
+ detail: `${h.path}:${h.evidence?.span.start.line ?? "?"} \xB7 ${plural2(h.callers ?? 0, "caller")} \xB7 ${plural2(h.callees ?? 0, "callee")}`,
83886
+ file: h.id.slice(0, h.id.lastIndexOf(":")),
83887
+ path: h.path,
83888
+ ...h.evidence ? { line: h.evidence.span.start.line } : {}
83889
+ });
83890
+ fileItem = (h) => ({
83891
+ kind: "file",
83892
+ id: h.id,
83893
+ label: h.path,
83894
+ detail: `${plural2(h.functions ?? 0, "function")}${h.status && h.status !== "analyzed" ? ` \xB7 ${h.status}` : ""}`,
83895
+ file: h.id,
83896
+ path: h.path
83897
+ });
83898
+ callers = (ctx, m) => {
83899
+ const r = resolveFunction(ctx, target(m));
83900
+ if (r.kind !== "one") return unresolvedName(ctx, r, "who calls");
83901
+ const out = tool(
83902
+ ctx,
83903
+ "list_calls",
83904
+ { function: r.hit.id, direction: "in" },
83905
+ () => ctx.engine.listCalls({ project: ctx.project, function: r.hit.id, direction: "in" })
83906
+ );
83907
+ const fns = new Set(out.calls.map((c) => c.function.id));
83908
+ return {
83909
+ summary: out.calls.length === 0 ? `No calls to ${say(r.hit.name)} were found.` : `${say(r.hit.name)} is called ${plural2(out.calls.length, "time")} by ${plural2(fns.size, "function")}.`,
83910
+ // The caveat matters most when nothing in the file calls it.
83911
+ ...out.calls.length === 0 ? { note: IN_FILE_NOTE } : {},
83912
+ results: [
83913
+ fnItem(r.hit),
83914
+ ...out.calls.map((c) => ({
83915
+ kind: "call",
83916
+ id: c.id,
83917
+ // The caller; the row's kind already says it is a call to the function asked about.
83918
+ label: c.function.qualifiedName,
83919
+ ...c.function.line !== void 0 ? { fnLine: c.function.line } : {},
83920
+ detail: `${c.function.path}:${c.evidence.span.start.line}`,
83921
+ file: c.evidence.file,
83922
+ path: c.function.path,
83923
+ line: c.evidence.span.start.line
83924
+ }))
83925
+ ],
83926
+ suggestions: [`what does ${r.hit.name} call`]
83927
+ };
83928
+ };
83929
+ callees = (ctx, m) => {
83930
+ const r = resolveFunction(ctx, target(m));
83931
+ if (r.kind !== "one") return unresolvedName(ctx, r, "what does");
83932
+ const out = tool(
83933
+ ctx,
83934
+ "list_calls",
83935
+ { function: r.hit.id, direction: "out" },
83936
+ () => ctx.engine.listCalls({ project: ctx.project, function: r.hit.id, direction: "out" })
83937
+ );
83938
+ const file2 = r.hit.id.slice(0, r.hit.id.lastIndexOf(":"));
83939
+ const sites = tool(
83940
+ ctx,
83941
+ "list_unresolved_sites",
83942
+ { file: file2, includeAll: true },
83943
+ () => ctx.engine.listUnresolvedSites({ project: ctx.project, file: file2, includeAll: true })
83944
+ ).sites.filter((s) => s.enclosingFn === r.hit.id);
83945
+ return {
83946
+ summary: `${say(r.hit.name)} makes ${plural2(out.calls.length, "resolved call")}${sites.length ? ` and ${plural2(sites.length, "unresolved call site")}` : ""}.`,
83947
+ // The caveat matters most when nothing in the file calls it.
83948
+ ...out.calls.length === 0 ? { note: IN_FILE_NOTE } : {},
83949
+ results: [
83950
+ fnItem(r.hit),
83951
+ ...out.calls.map((c) => ({
83952
+ kind: "call",
83953
+ id: c.id,
83954
+ label: c.function.qualifiedName,
83955
+ ...c.function.line !== void 0 ? { fnLine: c.function.line } : {},
83956
+ detail: `${r.hit.path}:${c.evidence.span.start.line}`,
83957
+ file: c.evidence.file,
83958
+ path: r.hit.path,
83959
+ line: c.evidence.span.start.line
83960
+ })),
83961
+ ...sites.map((s) => ({
83962
+ kind: "site",
83963
+ id: s.id,
83964
+ label: `? ${s.expression}`,
83965
+ detail: `${r.hit.path}:${s.evidence.span.start.line} \xB7 ${REASONS[s.reason] ?? s.reason}`,
83966
+ file: s.file,
83967
+ path: r.hit.path,
83968
+ line: s.evidence.span.start.line
83969
+ }))
83970
+ ],
83971
+ suggestions: [`who calls ${r.hit.name}`]
83972
+ };
83973
+ };
83974
+ definition = (ctx, m) => {
83975
+ const r = resolveFunction(ctx, target(m));
83976
+ if (r.kind === "one")
83977
+ return {
83978
+ summary: `${say(r.hit.name)} is defined at ${r.hit.path}:${r.hit.evidence?.span.start.line ?? "?"}.`,
83979
+ results: [fnItem(r.hit)],
83980
+ suggestions: [`who calls ${r.hit.name}`, `what does ${r.hit.name} call`]
83981
+ };
83982
+ if (r.kind === "many")
83983
+ return {
83984
+ summary: `"${r.name}" is defined in ${plural2(r.hits.length, "place")}.`,
83985
+ results: r.hits.map(fnItem)
83986
+ };
83987
+ const f = resolveFile(ctx, m[1]);
83988
+ if (f.kind === "one")
83989
+ return {
83990
+ summary: `${f.hit.path} is a file with ${plural2(f.hit.functions ?? 0, "function")}.`,
83991
+ results: [fileItem(f.hit)]
83992
+ };
83993
+ return unresolvedName(ctx, r, "where is");
83994
+ };
83995
+ fileFunctions = (ctx, m) => {
83996
+ const f = resolveFile(ctx, m[1]);
83997
+ if (f.kind === "none" && ctx.fallThrough) return null;
83998
+ if (f.kind !== "one")
83999
+ return {
84000
+ summary: f.kind === "many" ? `"${f.name}" matches ${plural2(f.hits.length, "file")}; which one?` : `No file matching "${f.name}".`,
84001
+ results: f.hits.map(fileItem)
84002
+ };
84003
+ const o = tool(
84004
+ ctx,
84005
+ "file_outline",
84006
+ { file: f.hit.id },
84007
+ () => ctx.engine.fileOutline({ project: ctx.project, file: f.hit.id })
84008
+ );
84009
+ return {
84010
+ summary: `${f.hit.path} defines ${plural2(o.functions.length, "function")} with ${plural2(o.calls, "call")} between them and ${plural2(o.open, "open question")}.`,
84011
+ results: [
84012
+ fileItem(f.hit),
84013
+ ...o.functions.map((fn) => ({
84014
+ kind: "function",
84015
+ id: fn.id,
84016
+ label: fn.qualifiedName,
84017
+ detail: `line ${fn.evidence.span.start.line} \xB7 ${plural2(fn.callers, "caller")} \xB7 ${plural2(fn.callees, "callee")}${fn.unresolved ? ` \xB7 ${fn.unresolved} unresolved` : ""}`,
84018
+ file: f.hit.id,
84019
+ path: f.hit.path,
84020
+ line: fn.evidence.span.start.line
84021
+ }))
84022
+ ],
84023
+ suggestions: [`open questions in ${f.hit.path}`]
84024
+ };
84025
+ };
84026
+ fileQuestions = (ctx, m) => {
84027
+ const f = resolveFile(ctx, m[1]);
84028
+ if (f.kind === "none" && ctx.fallThrough) return null;
84029
+ if (f.kind !== "one")
84030
+ return {
84031
+ summary: f.kind === "many" ? `"${f.name}" matches ${plural2(f.hits.length, "file")}; which one?` : `No file matching "${f.name}".`,
84032
+ results: f.hits.map(fileItem)
84033
+ };
84034
+ const sites = tool(
84035
+ ctx,
84036
+ "list_unresolved_sites",
84037
+ { file: f.hit.id },
84038
+ () => ctx.engine.listUnresolvedSites({ project: ctx.project, file: f.hit.id })
84039
+ ).sites;
84040
+ return {
84041
+ summary: `${f.hit.path} has ${plural2(sites.length, "open question")} (call sites that could not be resolved, such as dynamic dispatch).`,
84042
+ results: sites.map((s) => ({
84043
+ kind: "site",
84044
+ id: s.id,
84045
+ label: `? ${s.expression}`,
84046
+ detail: `line ${s.evidence.span.start.line} \xB7 ${REASONS[s.reason] ?? s.reason}`,
84047
+ file: s.file,
84048
+ path: f.hit.path,
84049
+ line: s.evidence.span.start.line
84050
+ }))
84051
+ };
84052
+ };
84053
+ TOP = 10;
84054
+ largestFiles = (ctx) => {
84055
+ const r = tool(
84056
+ ctx,
84057
+ "aggregate",
84058
+ { label: "Function", groupBy: "file" },
84059
+ () => ctx.engine.aggregate({ project: ctx.project, label: "Function", groupBy: "file" })
84060
+ );
84061
+ const top = r.groups.slice(0, TOP);
84062
+ return {
84063
+ summary: top.length ? `The largest file is ${top[0].name ?? top[0].key} with ${plural2(top[0].count, "function")}.` : "No functions have been analyzed yet.",
84064
+ results: top.map((g) => ({
84065
+ kind: "file",
84066
+ id: g.key,
84067
+ label: g.name ?? g.key,
84068
+ detail: plural2(g.count, "function"),
84069
+ file: g.key,
84070
+ path: g.name ?? g.key,
84071
+ count: g.count
84072
+ }))
84073
+ };
84074
+ };
84075
+ mostCalled = (ctx) => {
84076
+ const r = tool(
84077
+ ctx,
84078
+ "aggregate",
84079
+ { label: "CALLS", groupBy: "to" },
84080
+ () => ctx.engine.aggregate({ project: ctx.project, label: "CALLS", groupBy: "to" })
84081
+ );
84082
+ const top = r.groups.slice(0, TOP);
84083
+ return {
84084
+ summary: top.length ? `The most-called function is ${say(top[0].name ?? top[0].key)} (${plural2(top[0].count, "call")}).` : "No calls have been found yet.",
84085
+ note: IN_FILE_NOTE,
84086
+ results: top.map((g) => {
84087
+ const file2 = g.key.slice(0, g.key.lastIndexOf(":"));
84088
+ return {
84089
+ kind: "function",
84090
+ id: g.key,
84091
+ label: g.name ?? g.key,
84092
+ detail: `${plural2(g.count, "call")} \xB7 ${file2.slice(file2.indexOf(":") + 1)}`,
84093
+ file: file2,
84094
+ path: file2.slice(file2.indexOf(":") + 1),
84095
+ count: g.count
84096
+ };
84097
+ })
84098
+ };
84099
+ };
84100
+ questionsByReason = (ctx) => {
84101
+ const r = tool(
84102
+ ctx,
84103
+ "aggregate",
84104
+ { label: "UnresolvedCallSite", groupBy: "reason", filters: { open: true } },
84105
+ () => ctx.engine.aggregate({
84106
+ project: ctx.project,
84107
+ label: "UnresolvedCallSite",
84108
+ groupBy: "reason",
84109
+ filters: { open: true }
84110
+ })
84111
+ );
84112
+ return {
84113
+ summary: `${plural2(r.total, "open question")}: call sites that could not be resolved, by reason.`,
84114
+ results: r.groups.map((g) => ({
84115
+ kind: "group",
84116
+ id: g.key,
84117
+ label: g.key,
84118
+ detail: plural2(g.count, "site"),
84119
+ count: g.count
84120
+ })),
84121
+ suggestions: ["files with the most open questions"]
84122
+ };
84123
+ };
84124
+ filesByQuestions = (ctx) => {
84125
+ const r = tool(
84126
+ ctx,
84127
+ "aggregate",
84128
+ { label: "UnresolvedCallSite", groupBy: "file", filters: { open: true } },
84129
+ () => ctx.engine.aggregate({
84130
+ project: ctx.project,
84131
+ label: "UnresolvedCallSite",
84132
+ groupBy: "file",
84133
+ filters: { open: true }
84134
+ })
84135
+ );
84136
+ const top = r.groups.slice(0, TOP);
84137
+ return {
84138
+ summary: top.length ? `${top[0].name ?? top[0].key} has the most open questions (${top[0].count}).` : "There are no open questions.",
84139
+ results: top.map((g) => ({
84140
+ kind: "file",
84141
+ id: g.key,
84142
+ label: g.name ?? g.key,
84143
+ detail: plural2(g.count, "open question"),
84144
+ file: g.key,
84145
+ path: g.name ?? g.key,
84146
+ count: g.count
84147
+ }))
84148
+ };
84149
+ };
84150
+ overview = (ctx) => {
84151
+ const files = tool(
84152
+ ctx,
84153
+ "aggregate",
84154
+ { label: "File", groupBy: "status" },
84155
+ () => ctx.engine.aggregate({ project: ctx.project, label: "File", groupBy: "status" })
84156
+ );
84157
+ const langs = tool(
84158
+ ctx,
84159
+ "aggregate",
84160
+ { label: "File", groupBy: "language" },
84161
+ () => ctx.engine.aggregate({ project: ctx.project, label: "File", groupBy: "language" })
84162
+ );
84163
+ const fns = tool(
84164
+ ctx,
84165
+ "aggregate",
84166
+ { label: "Function", groupBy: "kind" },
84167
+ () => ctx.engine.aggregate({ project: ctx.project, label: "Function", groupBy: "kind" })
84168
+ );
84169
+ const calls = tool(
84170
+ ctx,
84171
+ "aggregate",
84172
+ { label: "CALLS", groupBy: "resolution" },
84173
+ () => ctx.engine.aggregate({ project: ctx.project, label: "CALLS", groupBy: "resolution" })
84174
+ );
84175
+ const open2 = tool(
84176
+ ctx,
84177
+ "aggregate",
84178
+ { label: "UnresolvedCallSite", groupBy: "reason", filters: { open: true } },
84179
+ () => ctx.engine.aggregate({
84180
+ project: ctx.project,
84181
+ label: "UnresolvedCallSite",
84182
+ groupBy: "reason",
84183
+ filters: { open: true }
84184
+ })
84185
+ );
84186
+ const group = (id, label, count) => ({
84187
+ kind: "group",
84188
+ id,
84189
+ label,
84190
+ count
84191
+ });
84192
+ const n = (x) => x.toLocaleString("en-US");
84193
+ return {
84194
+ summary: `${plural2(files.total, "file")}, ${plural2(fns.total, "function")}, ${plural2(calls.total, "call")} and ${plural2(open2.total, "open question")}.`,
84195
+ results: [
84196
+ ...files.groups.map(
84197
+ (g) => group(
84198
+ `files:${g.key}`,
84199
+ `${n(g.count)} ${g.count === 1 ? "file" : "files"} ${STATUS_WORDS[g.key] ?? g.key}`,
84200
+ g.count
84201
+ )
84202
+ ),
84203
+ ...langs.groups.map(
84204
+ (g) => group(
84205
+ `language:${g.key}`,
84206
+ `${n(g.count)} ${LANGUAGE_WORDS[g.key] ?? g.key} ${g.count === 1 ? "file" : "files"}`,
84207
+ g.count
84208
+ )
84209
+ ),
84210
+ ...open2.groups.map(
84211
+ (g) => group(
84212
+ `open:${g.key}`,
84213
+ `${n(g.count)} open ${g.count === 1 ? "question" : "questions"}: ${g.key.replace(/-/g, " ")}`,
84214
+ g.count
84215
+ )
84216
+ )
84217
+ ],
84218
+ suggestions: ["largest files", "most called functions", "open questions by reason"]
84219
+ };
84220
+ };
84221
+ REASONS = {
84222
+ "dynamic-dispatch": "type unknown",
84223
+ reflection: "reflection",
84224
+ "imported-symbol": "imported",
84225
+ "runtime-global": "built-in"
84226
+ };
84227
+ STATUS_WORDS = {
84228
+ analyzed: "analyzed",
84229
+ degraded: "partly analyzed",
84230
+ not_analyzed: "not analyzed"
84231
+ };
84232
+ LANGUAGE_WORDS = {
84233
+ typescript: "TypeScript",
84234
+ tsx: "TSX",
84235
+ javascript: "JavaScript",
84236
+ jsx: "JSX",
84237
+ python: "Python",
84238
+ go: "Go",
84239
+ rust: "Rust",
84240
+ none: "other"
84241
+ };
84242
+ INTENTS = [
84243
+ {
84244
+ name: "help",
84245
+ patterns: [/^(?:help|\?|what can (?:i|you) (?:ask|do)|what questions can i ask)$/],
84246
+ handle: () => ({ summary: HELP_SUMMARY, results: [], suggestions: EXAMPLES })
84247
+ },
84248
+ {
84249
+ name: "callers",
84250
+ patterns: [
84251
+ /^(?:who|what|which functions?)\s+(?:calls|uses|invokes)\s+(.+)$/,
84252
+ /^(?:show\s+|list\s+)?(?:the\s+)?callers\s+(?:of|for|to)\s+(.+)$/,
84253
+ /^where\s+is\s+(.+?)\s+(?:called|used|invoked)\s+(?:in|from)\s+([\w@./-]+\.[a-z0-9]+)$/,
84254
+ /^where\s+is\s+(.+?)\s+(?:called|used|invoked)(?:\s+from)?$/
84255
+ ],
84256
+ handle: callers
84257
+ },
84258
+ {
84259
+ name: "callees",
84260
+ patterns: [
84261
+ /^what\s+does\s+(.+?)\s+(?:call|invoke|use)$/,
84262
+ /^(?:show\s+|list\s+)?(?:the\s+)?(?:callees|calls)\s+(?:of|from|made by|in)\s+(.+)$/,
84263
+ /^(?:which|what)\s+functions\s+does\s+(.+?)\s+call$/
84264
+ ],
84265
+ handle: callees
84266
+ },
84267
+ {
84268
+ name: "open-questions-in-file",
84269
+ patterns: [/^(?:open questions|unresolved(?:\s+calls|\s+call\s+sites)?)\s+(?:in|for)\s+(.+)$/],
84270
+ handle: fileQuestions
84271
+ },
84272
+ {
84273
+ name: "files-by-open-questions",
84274
+ patterns: [
84275
+ /^(?:which\s+)?files?\s+(?:with|have)\s+(?:the\s+)?most\s+(?:open\s+questions|unresolved(?:\s+calls|\s+call\s+sites)?)$/
84276
+ ],
84277
+ handle: filesByQuestions
84278
+ },
84279
+ {
84280
+ name: "open-questions",
84281
+ patterns: [
84282
+ /^(?:open questions|unresolved(?:\s+calls|\s+call\s+sites)?)(?:\s+by\s+reason)?$/,
84283
+ /what\s+(?:could(?:n'?t| not)|can'?t|cannot)\s+(?:be\s+)?resolve/
84284
+ ],
84285
+ handle: questionsByReason
84286
+ },
84287
+ {
84288
+ name: "largest-files",
84289
+ patterns: [
84290
+ /^(?:(?:what|which)\s+are\s+)?(?:the\s+)?(?:largest|biggest)\s+files?$/,
84291
+ /^(?:which\s+)?files?\s+(?:with|have)\s+(?:the\s+)?most\s+functions$/
84292
+ ],
84293
+ handle: largestFiles
84294
+ },
84295
+ {
84296
+ name: "most-called",
84297
+ patterns: [
84298
+ /^(?:(?:what|which)\s+are\s+)?(?:the\s+)?most[-\s]?(?:called|used)(?:\s+functions)?$/,
84299
+ /^(?:the\s+)?hot\s?spots?$/,
84300
+ /^(?:which|what)\s+functions?\s+(?:is|are)\s+called\s+the\s+most$/
84301
+ ],
84302
+ handle: mostCalled
84303
+ },
84304
+ {
84305
+ name: "file-functions",
84306
+ patterns: [
84307
+ /^(?:what|which)\s+functions\s+(?:are\s+)?(?:in|defined in)\s+(.+)$/,
84308
+ /^(?:outline|functions)\s+(?:of|in)\s+(.+)$/,
84309
+ /^what(?:'s| is)\s+in\s+(.+)$/
84310
+ ],
84311
+ handle: fileFunctions
84312
+ },
84313
+ {
84314
+ name: "overview",
84315
+ patterns: [
84316
+ /^(?:stats|statistics|summary|overview|project (?:stats|summary|overview))$/,
84317
+ /^how\s+(?:big|large)\s+is\s+(?:this|the)\s+(?:project|code(?:base)?|repo(?:sitory)?)$/,
84318
+ /^how\s+many\s+(?:files|functions|calls)(?:\s+(?:are\s+there|does\s+(?:it|this\s+project)\s+have))?(?:\s+in\s+(?:this|the)\s+(?:project|code(?:base)?|repo(?:sitory)?))?$/
84319
+ ],
84320
+ handle: overview
84321
+ },
84322
+ {
84323
+ name: "definition",
84324
+ patterns: [
84325
+ /^where\s+is\s+(.+?)\s+(?:defined|declared|implemented)\s+in\s+([\w@./-]+\.[a-z0-9]+)$/,
84326
+ /^where\s+is\s+(.+?)\s+(?:defined|declared|implemented)$/,
84327
+ /^(?:find|show|go to|open|locate)\s+(?:me\s+)?(.+)$/,
84328
+ /^where\s+is\s+(.+)$/
84329
+ ],
84330
+ handle: definition
84331
+ }
84332
+ ];
84333
+ EXAMPLES = [
84334
+ "overview",
84335
+ "largest files",
84336
+ "most called functions",
84337
+ "open questions by reason",
84338
+ "who calls <function>",
84339
+ "what does <function> call",
84340
+ "where is <function> defined",
84341
+ "functions in <file>",
84342
+ "open questions in <file>"
84343
+ ];
84344
+ HELP_SUMMARY = "Without a model, Ask understands these questions; with a model configured in Settings, it answers anything about the analyzed code.";
84345
+ }
84346
+ });
84347
+
84348
+ // packages/agents/src/chat.ts
84349
+ function toolDefinitions() {
84350
+ return CHAT_TOOLS.map((name) => {
84351
+ const { project: _project, ...input2 } = TOOLS[name].input;
84352
+ return {
84353
+ type: "function",
84354
+ function: {
84355
+ name,
84356
+ description: TOOLS[name].description,
84357
+ parameters: external_exports.toJSONSchema(external_exports.object(input2))
84358
+ }
84359
+ };
84360
+ });
84361
+ }
84362
+ function systemPrompt(project2) {
84363
+ return [
84364
+ "You answer questions about a codebase using veoflow's knowledge graph of it.",
84365
+ `The project is "${project2}". What the graph holds today: files; functions (with qualified names such as Cart.addItem); calls between functions resolved within each file; and unresolved call sites (dynamic dispatch, imported symbols waiting for cross-file linking, runtime globals).`,
84366
+ "Calls across files are not linked yet, so a function can have callers in other files that the graph does not show; say so when it matters.",
84367
+ "Always look things up with the tools before answering, even when the question seems general; never guess or rely on memory. Start with search_nodes to find functions or files by name, then use list_calls, file_outline, get_function, list_unresolved_sites or aggregate.",
84368
+ 'Some names are generated for anonymous functions, such as authRoutes.<callback:post>#5. In your answer describe them in words with their location ("the post callback in authRoutes at src/routes/auth.ts:519") rather than repeating the generated name.',
84369
+ "Cite locations exactly as path:line from tool results (for example src/cart.ts:42).",
84370
+ "Answer briefly: one or two sentences, then a short list if it helps. If the graph cannot answer the question, say what is missing."
84371
+ ].join("\n");
84372
+ }
84373
+ async function complete(settings, body, fetchImpl) {
84374
+ let response;
84375
+ try {
84376
+ response = await fetchImpl(`${settings.baseUrl}/chat/completions`, {
84377
+ method: "POST",
84378
+ headers: {
84379
+ "content-type": "application/json",
84380
+ authorization: `Bearer ${settings.apiKey ?? ""}`,
84381
+ // OpenRouter's optional attribution headers.
84382
+ "x-title": "veoflow",
84383
+ "http-referer": "https://github.com/mudit70/veoapp"
84384
+ },
84385
+ body: JSON.stringify({ model: settings.model, temperature: 0, ...body }),
84386
+ signal: AbortSignal.timeout(TIMEOUT_MS)
84387
+ });
84388
+ } catch (e) {
84389
+ const name = e.name;
84390
+ throw new ModelError(
84391
+ name === "TimeoutError" ? "model-timeout" : "model-unreachable",
84392
+ name === "TimeoutError" ? `The model did not answer within ${TIMEOUT_MS / 1e3} seconds. Try again, or choose a faster model.` : `Couldn't reach ${settings.baseUrl}. Check the base URL and that the server is running.`
84393
+ );
84394
+ }
84395
+ const text = await response.text();
84396
+ let json2 = {};
84397
+ try {
84398
+ json2 = JSON.parse(text);
84399
+ } catch {
84400
+ }
84401
+ if (!response.ok) {
84402
+ const detail = json2.error?.message ?? text.slice(0, 200);
84403
+ const code = response.status === 401 || response.status === 403 ? "model-auth" : response.status === 429 ? "model-rate-limit" : response.status === 404 ? "model-not-found" : "model-error";
84404
+ const hint = code === "model-auth" ? "The provider refused the API key. Check the API key in Settings." : code === "model-rate-limit" ? "The provider is rate limiting requests. Try again in a moment." : code === "model-not-found" ? `The model "${settings.model}" was not found. Check the model name in Settings.` : `The provider returned an error (${response.status}).`;
84405
+ throw new ModelError(code, detail ? `${hint} (${detail.slice(0, 160)})` : hint);
84406
+ }
84407
+ const message2 = json2.choices?.[0]?.message;
84408
+ if (!message2)
84409
+ throw new ModelError("model-error", `unexpected response from the provider: ${text.slice(0, 200)}`);
84410
+ return message2;
84411
+ }
84412
+ function harvest(tool2, result2, items, locations) {
84413
+ const r = result2;
84414
+ const add = (item) => {
84415
+ if (items.size < MAX_ITEMS && !items.has(`${item.kind}:${item.id}`))
84416
+ items.set(`${item.kind}:${item.id}`, item);
84417
+ };
84418
+ const prove = (path, span, item) => {
84419
+ if (!path || !span) return;
84420
+ const list = locations.get(path) ?? [];
84421
+ list.push({ a: span.start.line, b: span.end.line, ...item ? { item } : {} });
84422
+ locations.set(path, list);
84423
+ };
84424
+ const fileOf = (id) => id.slice(0, id.lastIndexOf(":"));
84425
+ const fn = (f) => {
84426
+ const item = {
84427
+ kind: "function",
84428
+ id: f.id,
84429
+ label: f.qualifiedName ?? f.name ?? f.id,
84430
+ file: fileOf(f.id),
84431
+ path: f.path,
84432
+ ...f.evidence ? { line: f.evidence.span.start.line, detail: `${f.path}:${f.evidence.span.start.line}` } : {}
84433
+ };
84434
+ prove(f.path, f.evidence?.span, item);
84435
+ add(item);
84436
+ };
84437
+ if (tool2 === "search_nodes")
84438
+ for (const h of r.results ?? []) {
84439
+ if (h.label === "Function") fn(h);
84440
+ else add({ kind: "file", id: h.id, label: h.path, file: h.id, path: h.path });
84441
+ }
84442
+ else if (tool2 === "get_function") fn(r.function);
84443
+ else if (tool2 === "file_outline") {
84444
+ const file2 = r.file;
84445
+ add({ kind: "file", id: file2.id, label: file2.path, file: file2.id, path: file2.path });
84446
+ for (const f of r.functions ?? []) fn(f);
84447
+ } else if (tool2 === "list_calls")
84448
+ for (const c of r.calls ?? []) {
84449
+ const path = c.evidence.file.slice(c.evidence.file.indexOf(":") + 1);
84450
+ const item = {
84451
+ kind: "call",
84452
+ id: c.id,
84453
+ label: c.function.qualifiedName,
84454
+ detail: `${r.direction === "in" ? "calls it" : "called"} \xB7 ${path}:${c.evidence.span.start.line}`,
84455
+ file: c.evidence.file,
84456
+ path,
84457
+ line: c.evidence.span.start.line
84458
+ };
84459
+ prove(path, c.evidence.span, item);
84460
+ add(item);
84461
+ }
84462
+ else if (tool2 === "list_unresolved_sites")
84463
+ for (const s of r.sites ?? []) {
84464
+ const path = s.file.slice(s.file.indexOf(":") + 1);
84465
+ const item = {
84466
+ kind: "site",
84467
+ id: s.id,
84468
+ label: `? ${s.expression}`,
84469
+ detail: `${path}:${s.evidence.span.start.line} \xB7 ${s.reason}`,
84470
+ file: s.file,
84471
+ path,
84472
+ line: s.evidence.span.start.line
84473
+ };
84474
+ prove(path, s.evidence.span, item);
84475
+ add(item);
84476
+ }
84477
+ }
84478
+ function checkCitations(prose, locations) {
84479
+ const out = [];
84480
+ const seen = /* @__PURE__ */ new Set();
84481
+ for (const m of prose.matchAll(CITATION)) {
84482
+ const [text, path, line] = [m[0], m[1], Number(m[2])];
84483
+ if (seen.has(text)) continue;
84484
+ seen.add(text);
84485
+ let best = null;
84486
+ for (const [known, spans] of locations)
84487
+ if (known === path || known.endsWith(`/${path}`)) {
84488
+ for (const s of spans)
84489
+ if (line >= s.a && line <= s.b) {
84490
+ const better = !best || s.item && !best.item || Boolean(s.item) === Boolean(best.item) && s.b - s.a < best.b - best.a;
84491
+ if (better) best = s;
84492
+ }
84493
+ }
84494
+ out.push({ text, path, line, verified: best !== null, ...best?.item ? { target: best.item } : {} });
84495
+ }
84496
+ return out;
84497
+ }
84498
+ function shortName(item) {
84499
+ const label = item.label.replace(/^\? /, "");
84500
+ if (item.kind === "file") return label.slice(label.lastIndexOf("/") + 1);
84501
+ const last = label.split(".").pop() ?? "";
84502
+ return /^[A-Za-z_$][\w$]{3,}$/.test(last) ? last : null;
84503
+ }
84504
+ function splitMentioned(prose, citations, items) {
84505
+ const at = /* @__PURE__ */ new Map();
84506
+ for (const c of citations)
84507
+ if (c.target) {
84508
+ const key = `${c.target.kind}:${c.target.id}`;
84509
+ const i = prose.indexOf(c.text);
84510
+ if (!at.has(key) || i < at.get(key)) at.set(key, i);
84511
+ }
84512
+ const token = (name) => new RegExp(`(?<![\\w$.])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w$]|\\.[\\w$])`);
84513
+ for (const item of items) {
84514
+ const key = `${item.kind}:${item.id}`;
84515
+ const label = item.label.replace(/^\? /, "");
84516
+ for (const name of [label.includes("<") ? null : label, shortName(item)]) {
84517
+ if (!name) continue;
84518
+ const m = token(name).exec(prose);
84519
+ if (m && (!at.has(key) || m.index < at.get(key))) at.set(key, m.index);
84520
+ }
84521
+ }
84522
+ const byKey = new Map(items.map((i) => [`${i.kind}:${i.id}`, i]));
84523
+ for (const c of citations) if (c.target) byKey.set(`${c.target.kind}:${c.target.id}`, c.target);
84524
+ const mentioned = [...at].sort(([, a], [, b]) => a - b).map(([key]) => byKey.get(key)).filter(Boolean);
84525
+ const keys = new Set(mentioned.map((i) => `${i.kind}:${i.id}`));
84526
+ return { mentioned, lookups: items.filter((i) => !keys.has(`${i.kind}:${i.id}`)) };
84527
+ }
84528
+ async function answerWithModel(engine, project2, question, settings, fetchImpl = fetch) {
84529
+ const calls = [];
84530
+ const items = /* @__PURE__ */ new Map();
84531
+ const locations = /* @__PURE__ */ new Map();
84532
+ const messages = [
84533
+ { role: "system", content: systemPrompt(project2) },
84534
+ { role: "user", content: question }
84535
+ ];
84536
+ const tools = toolDefinitions();
84537
+ const allowed = new Set(CHAT_TOOLS);
84538
+ let prose;
84539
+ let truncated;
84540
+ const base = { question, via: "model", model: settings.model };
84541
+ let refused = false;
84542
+ const runTool = async (name, args) => {
84543
+ if (calls.length >= TOOL_BUDGET) {
84544
+ refused = true;
84545
+ return JSON.stringify({ error: { code: "budget", message: "tool budget used up" } });
84546
+ }
84547
+ if (!allowed.has(name)) {
84548
+ calls.push({ tool: name, args, error: "not an allowed read tool" });
84549
+ return JSON.stringify({
84550
+ error: {
84551
+ code: "not-allowed",
84552
+ message: `${name} is not available; use one of ${CHAT_TOOLS.join(", ")}`
84553
+ }
84554
+ });
84555
+ }
84556
+ const { project: _ignored, ...rest } = args;
84557
+ const { project: _p, ...input2 } = TOOLS[name].input;
84558
+ const parsed = external_exports.object(input2).strict().safeParse(rest);
84559
+ if (!parsed.success) {
84560
+ const message2 = parsed.error.issues.map((i) => `${i.path.join(".") || "arguments"}: ${i.message}`).join("; ");
84561
+ calls.push({ tool: name, args: rest, error: message2 });
84562
+ return JSON.stringify({ error: { code: "invalid-arguments", message: message2 } });
84563
+ }
84564
+ let result2;
84565
+ try {
84566
+ result2 = await callTool(engine, name, { ...rest, project: project2 });
84567
+ } catch (e) {
84568
+ const err = errorJson(e);
84569
+ calls.push({ tool: name, args: rest, error: err.message });
84570
+ return JSON.stringify({ error: err });
84571
+ }
84572
+ calls.push({ tool: name, args: rest });
84573
+ harvest(name, result2, items, locations);
84574
+ return JSON.stringify(result2);
84575
+ };
84576
+ try {
84577
+ for (let round = 0; ; round++) {
84578
+ if (round >= MAX_ROUNDS || calls.length >= TOOL_BUDGET) {
84579
+ messages.push({
84580
+ role: "user",
84581
+ content: "The tool budget is used up. Answer now with what the tools returned, and say what you could not check."
84582
+ });
84583
+ const last = await complete(settings, { messages, tools, tool_choice: "none" }, fetchImpl);
84584
+ prose = last.content ?? "";
84585
+ if (last.tool_calls?.length || refused)
84586
+ truncated = { reason: `stopped after ${TOOL_BUDGET} tool calls (the budget)` };
84587
+ break;
84588
+ }
84589
+ const message2 = await complete(settings, { messages, tools, tool_choice: "auto" }, fetchImpl);
84590
+ messages.push({
84591
+ role: "assistant",
84592
+ content: message2.content ?? null,
84593
+ ...message2.tool_calls ? { tool_calls: message2.tool_calls } : {}
84594
+ });
84595
+ if (!message2.tool_calls?.length) {
84596
+ prose = message2.content ?? "";
84597
+ break;
84598
+ }
84599
+ for (const call of message2.tool_calls) {
84600
+ let args = {};
84601
+ try {
84602
+ const parsed = JSON.parse(call.function.arguments || "{}");
84603
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
84604
+ args = parsed;
84605
+ } catch {
84606
+ }
84607
+ let content = await runTool(call.function.name, args);
84608
+ if (content.length > RESULT_CHARS)
84609
+ content = `${content.slice(0, RESULT_CHARS)}\u2026 (cut; ask a narrower question)`;
84610
+ messages.push({ role: "tool", tool_call_id: call.id, content });
84611
+ }
84612
+ if (refused) truncated = { reason: `stopped after ${TOOL_BUDGET} tool calls (the budget)` };
84613
+ }
84614
+ } catch (e) {
84615
+ const err = e instanceof ModelError ? { code: e.code, message: e.message } : { code: "model-error", message: String(e.message ?? e) };
84616
+ return {
84617
+ ...base,
84618
+ summary: `The model could not answer: ${err.message}`,
84619
+ results: [...items.values()],
84620
+ toolCalls: calls,
84621
+ error: err
84622
+ };
84623
+ }
84624
+ const citations = checkCitations(prose, locations);
84625
+ const unverified = citations.filter((c) => !c.verified).length;
84626
+ const { mentioned, lookups } = splitMentioned(prose, citations, [...items.values()]);
84627
+ return {
84628
+ ...base,
84629
+ summary: calls.length === 0 ? `Answered by ${settings.model} without looking anything up in the graph, so this is general knowledge, not your code. Rephrase the question around a function or file name to get an answer from the graph.` : `Answered by ${settings.model} using ${calls.length} tool ${calls.length === 1 ? "call" : "calls"}${unverified ? `; ${unverified} cited ${unverified === 1 ? "location was" : "locations were"} not returned by any tool` : ""}.`,
84630
+ // Flag, never fabricate: an answer no tool backed is marked as such.
84631
+ ...calls.length === 0 ? { ungrounded: true } : {},
84632
+ // What the answer is about first; the rest of the lookups apart.
84633
+ results: mentioned,
84634
+ lookups,
84635
+ prose,
84636
+ citations,
84637
+ ...truncated ? { truncated } : {},
84638
+ toolCalls: calls
84639
+ };
84640
+ }
84641
+ async function testConnection(settings, fetchImpl = fetch) {
84642
+ if (!settings.apiKey)
84643
+ return { ok: false, toolCalls: false, model: settings.model, message: "No API key is set." };
84644
+ try {
84645
+ const message2 = await complete(
84646
+ settings,
84647
+ {
84648
+ max_tokens: 50,
84649
+ messages: [{ role: "user", content: "Call the ping tool." }],
84650
+ tools: [
84651
+ {
84652
+ type: "function",
84653
+ function: {
84654
+ name: "ping",
84655
+ description: "Answers pong.",
84656
+ parameters: { type: "object", properties: {} }
84657
+ }
84658
+ }
84659
+ ],
84660
+ tool_choice: { type: "function", function: { name: "ping" } }
84661
+ },
84662
+ fetchImpl
84663
+ );
84664
+ const toolCalls = Boolean(message2.tool_calls?.length);
84665
+ return {
84666
+ ok: true,
84667
+ toolCalls,
84668
+ model: settings.model,
84669
+ message: toolCalls ? `Connected to ${settings.model}; it can call tools.` : `Connected to ${settings.model}, but it did not call a tool. Ask needs a model that supports tool calls; until then only the built-in questions work.`
84670
+ };
84671
+ } catch (e) {
84672
+ return {
84673
+ ok: false,
84674
+ toolCalls: false,
84675
+ model: settings.model,
84676
+ message: e instanceof ModelError ? e.message : String(e.message ?? e)
84677
+ };
84678
+ }
84679
+ }
84680
+ var CHAT_TOOLS, TOOL_BUDGET, MAX_ROUNDS, RESULT_CHARS, MAX_ITEMS, TIMEOUT_MS, ModelError, CITATION;
84681
+ var init_chat = __esm({
84682
+ "packages/agents/src/chat.ts"() {
84683
+ "use strict";
84684
+ init_zod();
84685
+ init_src7();
84686
+ CHAT_TOOLS = [
84687
+ "search_nodes",
84688
+ "aggregate",
84689
+ "file_outline",
84690
+ "get_function",
84691
+ "list_calls",
84692
+ "list_unresolved_sites",
84693
+ "run_status"
84694
+ ];
84695
+ TOOL_BUDGET = 8;
84696
+ MAX_ROUNDS = 10;
84697
+ RESULT_CHARS = 12e3;
84698
+ MAX_ITEMS = 40;
84699
+ TIMEOUT_MS = 9e4;
84700
+ ModelError = class extends Error {
84701
+ constructor(code, message2) {
84702
+ super(message2);
84703
+ this.code = code;
84704
+ }
84705
+ code;
84706
+ };
84707
+ CITATION = /(?<![\w/:.@-])(?:[\w.-]+:(?=[\w@./-]+\.[A-Za-z]))?(?:\.\/)?((?:[\w@.-]+\/)*[\w@-][\w@.-]*\.[A-Za-z][A-Za-z0-9]*):(\d+)(?::\d+)?(?![\w/])/g;
84708
+ }
84709
+ });
84710
+
84711
+ // packages/agents/src/ask.ts
84712
+ async function ask(engine, home, project2, question, options = {}) {
84713
+ const text = question.trim();
84714
+ const mode = options.mode ?? "auto";
84715
+ if (!text)
84716
+ return {
84717
+ question,
84718
+ via: "help",
84719
+ summary: HELP_SUMMARY,
84720
+ results: [],
84721
+ toolCalls: [],
84722
+ suggestions: suggest(engine, project2)
84723
+ };
84724
+ const settings = loadSettings(home, options.env);
84725
+ const modelReady = mode !== "grammar" && settings.apiKey !== null;
84726
+ if (mode !== "model") {
84727
+ const answer = answerWithGrammar(engine, project2, text, {
84728
+ fallThrough: modelReady,
84729
+ ...options.file ? { file: options.file } : {}
84730
+ });
84731
+ if (answer) return answer;
84732
+ }
84733
+ if (mode !== "grammar" && settings.apiKey)
84734
+ return answerWithModel(engine, project2, text, settings, options.fetch);
84735
+ return {
84736
+ question,
84737
+ via: "help",
84738
+ summary: mode === "grammar" || settings.apiKey ? `That isn't one of the built-in questions. ${HELP_SUMMARY}` : "That isn't one of the built-in questions, and no model is configured. Add an OpenRouter key and model in Settings to ask anything, or try one of these.",
84739
+ results: [],
84740
+ toolCalls: [],
84741
+ // A few starters and the question shapes; the full list is in the Ask bar.
84742
+ suggestions: [...suggest(engine, project2).slice(0, 3), ...EXAMPLES.filter((e) => e.includes("<"))]
84743
+ };
84744
+ }
84745
+ function suggest(engine, project2) {
84746
+ const out = ["overview"];
84747
+ try {
84748
+ const called = engine.aggregate({ project: project2, label: "CALLS", groupBy: "to", limit: 10 }).groups.find((g) => sourceFile(g.key.slice(g.key.indexOf(":") + 1)) && !(g.name ?? "<").includes("<"));
84749
+ if (called?.name) out.push(`who calls ${called.name}`);
84750
+ const largest = engine.aggregate({ project: project2, label: "Function", groupBy: "file" }).groups.find((g) => sourceFile(g.name));
84751
+ if (largest?.name) out.push(`functions in ${largest.name}`);
84752
+ const questions = engine.aggregate({ project: project2, label: "UnresolvedCallSite", groupBy: "file", filters: { open: true } }).groups.find((g) => sourceFile(g.name));
84753
+ if (questions?.name) out.push(`open questions in ${questions.name}`);
84754
+ } catch {
84755
+ }
84756
+ out.push("largest files", "most called functions");
84757
+ return [...new Set(out)];
84758
+ }
84759
+ var TEST_PATH, sourceFile;
84760
+ var init_ask = __esm({
84761
+ "packages/agents/src/ask.ts"() {
84762
+ "use strict";
84763
+ init_chat();
84764
+ init_config();
84765
+ init_grammar();
84766
+ TEST_PATH = /(^|\/)(__tests__|__mocks__|tests?|e2e|specs?|fixtures?)\/|\.(test|spec|e2e|stories)\.[a-z0-9]+$/i;
84767
+ sourceFile = (path) => path !== void 0 && !TEST_PATH.test(path);
84768
+ }
84769
+ });
84770
+
84771
+ // packages/agents/src/view.ts
84772
+ function viewCommands(item) {
84773
+ if (!item.file) return [];
84774
+ if (item.kind === "file") return [{ name: "openFile", args: { file: item.file } }];
84775
+ if (item.kind === "function" || item.kind === "call" || item.kind === "site")
84776
+ return [
84777
+ { name: "openFile", args: { file: item.file } },
84778
+ { name: "select", args: { kind: item.kind, id: item.id, file: item.file } }
84779
+ ];
84780
+ return [];
84781
+ }
84782
+ var init_view2 = __esm({
84783
+ "packages/agents/src/view.ts"() {
84784
+ "use strict";
84785
+ }
84786
+ });
84787
+
84788
+ // packages/agents/src/index.ts
84789
+ var src_exports2 = {};
84790
+ __export(src_exports2, {
84791
+ CHAT_TOOLS: () => CHAT_TOOLS,
84792
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
84793
+ DEFAULT_MODEL: () => DEFAULT_MODEL,
84794
+ EXAMPLES: () => EXAMPLES,
84795
+ HELP_SUMMARY: () => HELP_SUMMARY,
84796
+ INTENTS: () => INTENTS,
84797
+ IN_FILE_NOTE: () => IN_FILE_NOTE,
84798
+ TOOL_BUDGET: () => TOOL_BUDGET,
84799
+ answerWithGrammar: () => answerWithGrammar,
84800
+ answerWithModel: () => answerWithModel,
84801
+ ask: () => ask,
84802
+ checkCitations: () => checkCitations,
84803
+ configPath: () => configPath,
84804
+ loadSettings: () => loadSettings,
84805
+ normalize: () => normalize,
84806
+ publicSettings: () => publicSettings,
84807
+ saveSettings: () => saveSettings,
84808
+ say: () => say,
84809
+ splitMentioned: () => splitMentioned,
84810
+ suggest: () => suggest,
84811
+ systemPrompt: () => systemPrompt,
84812
+ testConnection: () => testConnection,
84813
+ toolDefinitions: () => toolDefinitions,
84814
+ viewCommands: () => viewCommands
84815
+ });
84816
+ var init_src8 = __esm({
84817
+ "packages/agents/src/index.ts"() {
84818
+ "use strict";
84819
+ init_types3();
84820
+ init_config();
84821
+ init_grammar();
84822
+ init_chat();
84823
+ init_ask();
84824
+ init_view2();
84825
+ }
84826
+ });
84827
+
82941
84828
  // packages/server/src/server.ts
82942
- import { existsSync as existsSync5 } from "node:fs";
82943
- import { dirname as dirname4, join as join6, resolve as resolve3 } from "node:path";
84829
+ import { existsSync as existsSync7, statSync as statSync3 } from "node:fs";
84830
+ import { dirname as dirname5, isAbsolute, join as join8, resolve as resolve3 } from "node:path";
82944
84831
  import { fileURLToPath } from "node:url";
82945
84832
  function hostName(host) {
82946
84833
  return host.startsWith("[") ? host.slice(0, host.indexOf("]") + 1) : host.replace(/:\d+$/, "");
@@ -82987,8 +84874,11 @@ async function createServer(engine, options = {}) {
82987
84874
  app.get("/api/projects", async () => engine.listProjects());
82988
84875
  app.post(
82989
84876
  "/api/projects",
82990
- { schema: { body: { type: "object", required: ["name"], properties: { name: str2 } } } },
82991
- async (req, reply) => reply.status(201).send(engine.createProject(req.body))
84877
+ { schema: { body: { type: "object", required: ["name"], properties: { name: str2, root: str2 } } } },
84878
+ async (req, reply) => {
84879
+ if (req.body.root !== void 0) checkFolder(req.body.root);
84880
+ return reply.status(201).send(engine.createProject({ name: req.body.name }));
84881
+ }
82992
84882
  );
82993
84883
  app.get(
82994
84884
  "/api/projects/:project/sources",
@@ -83008,7 +84898,10 @@ async function createServer(engine, options = {}) {
83008
84898
  }
83009
84899
  }
83010
84900
  },
83011
- async (req, reply) => reply.status(201).send(engine.addSource({ ...req.body, ...req.params }))
84901
+ async (req, reply) => {
84902
+ checkFolder(req.body.root);
84903
+ return reply.status(201).send(engine.addSource({ ...req.body, ...req.params }));
84904
+ }
83012
84905
  );
83013
84906
  app.post(
83014
84907
  "/api/projects/:project/runs",
@@ -83033,6 +84926,11 @@ async function createServer(engine, options = {}) {
83033
84926
  },
83034
84927
  async (req) => engine.listRuns({ ...req.params, ...req.query.limit ? { limit: Number(req.query.limit) } : {} })
83035
84928
  );
84929
+ app.get(
84930
+ "/api/projects/:project/file-counts",
84931
+ { schema: { params: projectParams } },
84932
+ async (req) => engine.fileCounts(req.params)
84933
+ );
83036
84934
  app.get(
83037
84935
  "/api/projects/:project/files",
83038
84936
  { schema: { params: projectParams } },
@@ -83089,6 +84987,167 @@ async function createServer(engine, options = {}) {
83089
84987
  includeAll: req.query.includeAll === "true"
83090
84988
  })
83091
84989
  );
84990
+ app.post(
84991
+ "/api/projects/:project/ask",
84992
+ {
84993
+ schema: {
84994
+ params: projectParams,
84995
+ body: {
84996
+ type: "object",
84997
+ required: ["question"],
84998
+ additionalProperties: false,
84999
+ properties: {
85000
+ question: { type: "string", maxLength: 2e3 },
85001
+ mode: { type: "string", enum: ["auto", "model", "grammar"] },
85002
+ file: { type: "string", maxLength: 1e3 }
85003
+ }
85004
+ }
85005
+ }
85006
+ },
85007
+ async (req) => {
85008
+ const project2 = engine.resolveProject(req.params).id;
85009
+ const mode = isLocal(req) ? req.body.mode : "grammar";
85010
+ return ask(engine, engine.catalog.home, project2, req.body.question, {
85011
+ ...mode ? { mode } : {},
85012
+ ...req.body.file ? { file: req.body.file } : {}
85013
+ });
85014
+ }
85015
+ );
85016
+ app.get(
85017
+ "/api/projects/:project/suggestions",
85018
+ { schema: { params: projectParams } },
85019
+ async (req) => ({ suggestions: suggest(engine, engine.resolveProject(req.params).id) })
85020
+ );
85021
+ app.get("/api/settings", async () => ({ model: publicSettings(loadSettings(engine.catalog.home)) }));
85022
+ app.put(
85023
+ "/api/settings",
85024
+ {
85025
+ schema: {
85026
+ body: {
85027
+ type: "object",
85028
+ additionalProperties: false,
85029
+ properties: {
85030
+ baseUrl: { type: "string", maxLength: 500 },
85031
+ model: { type: "string", maxLength: 200 },
85032
+ apiKey: { type: ["string", "null"], maxLength: 500 }
85033
+ }
85034
+ }
85035
+ }
85036
+ },
85037
+ async (req) => {
85038
+ localOnly(req);
85039
+ return { model: publicSettings(saveSettings(engine.catalog.home, req.body)) };
85040
+ }
85041
+ );
85042
+ app.post(
85043
+ "/api/settings/test",
85044
+ {
85045
+ schema: {
85046
+ body: {
85047
+ type: "object",
85048
+ additionalProperties: false,
85049
+ properties: {
85050
+ baseUrl: { type: "string", maxLength: 500 },
85051
+ model: { type: "string", maxLength: 200 },
85052
+ apiKey: { type: "string", maxLength: 500 }
85053
+ }
85054
+ }
85055
+ }
85056
+ },
85057
+ async (req) => {
85058
+ localOnly(req);
85059
+ const stored = loadSettings(engine.catalog.home);
85060
+ const body = req.body ?? {};
85061
+ const baseUrl = body.baseUrl?.trim().replace(/\/+$/, "") || stored.baseUrl;
85062
+ if (!/^https?:\/\/\S+$/.test(baseUrl))
85063
+ return {
85064
+ ok: false,
85065
+ toolCalls: false,
85066
+ model: stored.model,
85067
+ message: "The base URL must start with http:// or https://."
85068
+ };
85069
+ return testConnection({
85070
+ ...stored,
85071
+ baseUrl,
85072
+ model: body.model?.trim() || stored.model,
85073
+ apiKey: body.apiKey?.trim() || stored.apiKey
85074
+ });
85075
+ }
85076
+ );
85077
+ app.get(
85078
+ "/api/projects/:project/search",
85079
+ {
85080
+ schema: {
85081
+ params: projectParams,
85082
+ querystring: {
85083
+ type: "object",
85084
+ required: ["label"],
85085
+ properties: {
85086
+ label: { type: "string", enum: ["Function", "File"] },
85087
+ text: { type: "string" },
85088
+ path: str2,
85089
+ status: { type: "string", enum: ["analyzed", "degraded", "not_analyzed"] },
85090
+ limit: { type: "string", pattern: "^[1-9][0-9]*$" }
85091
+ }
85092
+ }
85093
+ }
85094
+ },
85095
+ async (req) => {
85096
+ const { label, text, path, status, limit } = req.query;
85097
+ const filters = {
85098
+ ...path ? { path } : {},
85099
+ ...status ? { status } : {}
85100
+ };
85101
+ return engine.searchNodes({
85102
+ ...req.params,
85103
+ label,
85104
+ ...text !== void 0 ? { text } : {},
85105
+ ...Object.keys(filters).length ? { filters } : {},
85106
+ ...limit ? { limit: Number(limit) } : {}
85107
+ });
85108
+ }
85109
+ );
85110
+ app.get(
85111
+ "/api/projects/:project/aggregate",
85112
+ {
85113
+ schema: {
85114
+ params: projectParams,
85115
+ querystring: {
85116
+ type: "object",
85117
+ required: ["label", "groupBy"],
85118
+ properties: {
85119
+ label: { type: "string", enum: ["File", "Function", "UnresolvedCallSite", "CALLS"] },
85120
+ groupBy: str2,
85121
+ open: { type: "string", enum: ["true", "false"] },
85122
+ path: str2,
85123
+ limit: { type: "string", pattern: "^[1-9][0-9]*$" }
85124
+ }
85125
+ }
85126
+ }
85127
+ },
85128
+ async (req) => engine.aggregate({
85129
+ ...req.params,
85130
+ label: req.query.label,
85131
+ groupBy: req.query.groupBy,
85132
+ ...req.query.open !== void 0 || req.query.path ? {
85133
+ filters: {
85134
+ ...req.query.open !== void 0 ? { open: req.query.open === "true" } : {},
85135
+ ...req.query.path ? { path: req.query.path } : {}
85136
+ }
85137
+ } : {},
85138
+ ...req.query.limit ? { limit: Number(req.query.limit) } : {}
85139
+ })
85140
+ );
85141
+ app.get(
85142
+ "/api/projects/:project/file-outline",
85143
+ {
85144
+ schema: {
85145
+ params: projectParams,
85146
+ querystring: { type: "object", required: ["file"], properties: { file: str2 } }
85147
+ }
85148
+ },
85149
+ async (req) => engine.fileOutline({ ...req.params, file: req.query.file })
85150
+ );
83092
85151
  app.post(
83093
85152
  "/api/projects/:project/snippet",
83094
85153
  {
@@ -83112,7 +85171,7 @@ async function createServer(engine, options = {}) {
83112
85171
  async (req) => engine.snippet({ ...req.params, ...req.body })
83113
85172
  );
83114
85173
  const webRoot = options.webRoot === void 0 ? defaultWebRoot : options.webRoot;
83115
- const hasUi = webRoot !== null && existsSync5(join6(webRoot, "index.html"));
85174
+ const hasUi = webRoot !== null && existsSync7(join8(webRoot, "index.html"));
83116
85175
  if (hasUi) await app.register(import_static.default, { root: webRoot });
83117
85176
  app.setNotFoundHandler((req, reply) => {
83118
85177
  if (req.url.startsWith("/api/") || !hasUi)
@@ -83138,6 +85197,31 @@ async function listen(engine, options = {}) {
83138
85197
  }
83139
85198
  };
83140
85199
  }
85200
+ function checkFolder(root) {
85201
+ if (!isAbsolute(root))
85202
+ throw new VeoError(
85203
+ "invalid-arguments",
85204
+ `Enter an absolute path (for example /Users/you/app), not "${root}"`,
85205
+ {
85206
+ fields: ["root"]
85207
+ }
85208
+ );
85209
+ let dir;
85210
+ try {
85211
+ dir = statSync3(root).isDirectory();
85212
+ } catch {
85213
+ dir = false;
85214
+ }
85215
+ if (!dir) throw new VeoError("source-not-found", `${root} is not a folder`, { root });
85216
+ }
85217
+ function localOnly(req) {
85218
+ if (!isLocal(req))
85219
+ throw new VeoError("forbidden", "settings can only be changed from the machine running veoflow");
85220
+ }
85221
+ function isLocal(req) {
85222
+ const ip = req.socket.remoteAddress ?? "";
85223
+ return ip === "::1" || /^(?:::ffff:)?127\./.test(ip);
85224
+ }
83141
85225
  var import_static, import_websocket, import_fastify, STATUS, defaultWebRoot, LOOPBACK, str2, strings, position, projectParams;
83142
85226
  var init_server4 = __esm({
83143
85227
  "packages/server/src/server.ts"() {
@@ -83146,6 +85230,7 @@ var init_server4 = __esm({
83146
85230
  import_websocket = __toESM(require_websocket2(), 1);
83147
85231
  import_fastify = __toESM(require_fastify(), 1);
83148
85232
  init_src();
85233
+ init_src8();
83149
85234
  STATUS = {
83150
85235
  "not-found": 404,
83151
85236
  "source-not-found": 404,
@@ -83158,7 +85243,7 @@ var init_server4 = __esm({
83158
85243
  ambiguous: 409,
83159
85244
  locked: 409
83160
85245
  };
83161
- defaultWebRoot = process.env.VEO_WEB_ROOT ?? resolve3(dirname4(fileURLToPath(import.meta.url)), "../../web/dist");
85246
+ defaultWebRoot = process.env.VEO_WEB_ROOT ?? resolve3(dirname5(fileURLToPath(import.meta.url)), "../../web/dist");
83162
85247
  LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
83163
85248
  str2 = { type: "string", minLength: 1 };
83164
85249
  strings = { type: "array", items: { type: "string" } };
@@ -83172,13 +85257,13 @@ var init_server4 = __esm({
83172
85257
  });
83173
85258
 
83174
85259
  // packages/server/src/index.ts
83175
- var src_exports2 = {};
83176
- __export(src_exports2, {
85260
+ var src_exports3 = {};
85261
+ __export(src_exports3, {
83177
85262
  createServer: () => createServer,
83178
85263
  listen: () => listen,
83179
85264
  urlHost: () => urlHost
83180
85265
  });
83181
- var init_src8 = __esm({
85266
+ var init_src9 = __esm({
83182
85267
  "packages/server/src/index.ts"() {
83183
85268
  "use strict";
83184
85269
  init_server4();
@@ -83189,8 +85274,8 @@ var init_src8 = __esm({
83189
85274
  init_src();
83190
85275
  init_src6();
83191
85276
  import { spawn } from "node:child_process";
83192
- import { existsSync as existsSync6, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
83193
- import { basename as basename3, dirname as dirname5, join as join7, resolve as resolve4 } from "node:path";
85277
+ import { existsSync as existsSync8, readFileSync as readFileSync4, statSync as statSync4 } from "node:fs";
85278
+ import { basename as basename3, dirname as dirname6, join as join9, resolve as resolve4 } from "node:path";
83194
85279
  import { fileURLToPath as fileURLToPath2 } from "node:url";
83195
85280
  import { parseArgs } from "node:util";
83196
85281
  var USAGE = `veoflow \u2014 a knowledge graph of your code (also runs as \`veo\`)
@@ -83203,6 +85288,11 @@ Usage:
83203
85288
  veoflow serve [--port 7420] [--host 127.0.0.1] [--no-open]
83204
85289
  serve the UI and API
83205
85290
  veoflow mcp serve the MCP tools over stdio
85291
+ veoflow ask "<question>" [--project <id>] [--mode auto|grammar|model]
85292
+ ask about the analyzed code
85293
+ veoflow config [get [<key>] | set <key> <value> | test]
85294
+ model settings: model.baseUrl, model.name, model.apiKey
85295
+ ("set model.apiKey -" reads the key from stdin)
83206
85296
  veoflow projects list projects
83207
85297
  veoflow help | --version`;
83208
85298
  var UsageError = class extends Error {
@@ -83210,7 +85300,7 @@ var UsageError = class extends Error {
83210
85300
  function version2() {
83211
85301
  if (process.env.VEO_VERSION) return process.env.VEO_VERSION;
83212
85302
  const pkg = JSON.parse(
83213
- readFileSync3(join7(dirname5(fileURLToPath2(import.meta.url)), "../package.json"), "utf8")
85303
+ readFileSync4(join9(dirname6(fileURLToPath2(import.meta.url)), "../package.json"), "utf8")
83214
85304
  );
83215
85305
  return pkg.version;
83216
85306
  }
@@ -83314,7 +85404,7 @@ async function main(argv, io) {
83314
85404
  });
83315
85405
  if (positionals.length !== 1) throw new UsageError("usage: veoflow add <dir> [--project <id>]");
83316
85406
  const root = resolve4(io.cwd, positionals[0]);
83317
- if (!existsSync6(root) || !statSync3(root).isDirectory())
85407
+ if (!existsSync8(root) || !statSync4(root).isDirectory())
83318
85408
  throw new VeoError("source-not-found", `${root} is not a directory`);
83319
85409
  let project2 = values.project ?? engine.catalog.resolveProjectForCwd(io.cwd)?.id;
83320
85410
  if (!project2) {
@@ -83349,7 +85439,7 @@ async function main(argv, io) {
83349
85439
  const port = values.port === void 0 ? 7420 : Number(values.port);
83350
85440
  if (!Number.isInteger(port) || port < 0 || port > 65535)
83351
85441
  throw new UsageError(`invalid --port ${values.port}`);
83352
- const { listen: listen2 } = await Promise.resolve().then(() => (init_src8(), src_exports2));
85442
+ const { listen: listen2 } = await Promise.resolve().then(() => (init_src9(), src_exports3));
83353
85443
  let started;
83354
85444
  try {
83355
85445
  started = await listen2(engine, { port, ...values.host ? { host: values.host } : {} });
@@ -83370,6 +85460,91 @@ async function main(argv, io) {
83370
85460
  }, started.url);
83371
85461
  return 0;
83372
85462
  }
85463
+ case "ask": {
85464
+ const { values, positionals } = parseArgs({
85465
+ args: rest,
85466
+ strict: true,
85467
+ allowPositionals: true,
85468
+ options: { project: { type: "string" }, mode: { type: "string" }, json: { type: "boolean" } }
85469
+ });
85470
+ if (positionals.length === 0)
85471
+ throw new UsageError('usage: veoflow ask "<question>" [--project <id>]');
85472
+ const mode = values.mode ?? "auto";
85473
+ if (mode !== "auto" && mode !== "grammar" && mode !== "model")
85474
+ throw new UsageError(`invalid --mode ${mode} (auto, grammar or model)`);
85475
+ const { ask: ask2 } = await Promise.resolve().then(() => (init_src8(), src_exports2));
85476
+ const project2 = pickProject(engine, values.project, io.cwd);
85477
+ const answer = await ask2(engine, engine.catalog.home, project2, positionals.join(" "), { mode });
85478
+ if (values.json) {
85479
+ io.out(JSON.stringify(answer, null, 2));
85480
+ return answer.error ? 1 : 0;
85481
+ }
85482
+ io.out(answer.summary);
85483
+ if (answer.note) io.out(`note: ${answer.note}`);
85484
+ if (answer.prose) io.out(`
85485
+ ${plain(answer.prose)}`);
85486
+ for (const c of answer.citations ?? [])
85487
+ if (!c.verified) io.out(`unverified: ${c.text} was not returned by any tool`);
85488
+ if (answer.results.length) io.out("");
85489
+ for (const r of answer.results.slice(0, 25))
85490
+ io.out(` ${r.label}${r.detail ? ` (${r.detail})` : ""}`);
85491
+ if (answer.results.length > 25) io.out(` \u2026 ${answer.results.length - 25} more`);
85492
+ if (answer.truncated) io.out(`truncated: ${answer.truncated.reason}`);
85493
+ if (answer.suggestions?.length) io.out(`
85494
+ try: ${answer.suggestions.join(" \xB7 ")}`);
85495
+ return answer.error || mode === "model" && answer.via !== "model" ? 1 : 0;
85496
+ }
85497
+ case "config": {
85498
+ const [action = "get", key, value] = rest;
85499
+ const { loadSettings: loadSettings2, publicSettings: publicSettings2, saveSettings: saveSettings2, testConnection: testConnection2 } = await Promise.resolve().then(() => (init_src8(), src_exports2));
85500
+ const home = engine.catalog.home;
85501
+ const keys = {
85502
+ "model.baseUrl": "baseUrl",
85503
+ "model.name": "model",
85504
+ "model.apiKey": "apiKey"
85505
+ };
85506
+ const show = () => {
85507
+ const p = publicSettings2(loadSettings2(home));
85508
+ return {
85509
+ "model.baseUrl": p.baseUrl,
85510
+ "model.name": p.model,
85511
+ "model.apiKey": p.apiKeySet ? `set (\u2026${p.apiKeyHint}, from ${p.keySource})` : "not set"
85512
+ };
85513
+ };
85514
+ if (action === "get") {
85515
+ const all2 = show();
85516
+ if (key && !(key in all2))
85517
+ throw new UsageError(`unknown key ${key} (${Object.keys(keys).join(", ")})`);
85518
+ for (const [k, v] of Object.entries(all2)) if (!key || k === key) io.out(key ? v : `${k} = ${v}`);
85519
+ return 0;
85520
+ }
85521
+ if (action === "set") {
85522
+ if (!key || !(key in keys) || value === void 0)
85523
+ throw new UsageError(`usage: veoflow config set <${Object.keys(keys).join("|")}> <value>`);
85524
+ const field = keys[key];
85525
+ let v = value;
85526
+ if (field === "apiKey" && value === "-") {
85527
+ if (process.stdin.isTTY)
85528
+ throw new UsageError(
85529
+ "pipe the key in, so it never shows on screen: pbpaste | veoflow config set model.apiKey -"
85530
+ );
85531
+ v = readFileSync4(0, "utf8").trim();
85532
+ if (!v)
85533
+ throw new UsageError(
85534
+ "no key on stdin; to remove the stored key: veoflow config set model.apiKey ''"
85535
+ );
85536
+ }
85537
+ saveSettings2(home, { [field]: field === "apiKey" && v === "" ? null : v });
85538
+ io.out(`${key} = ${show()[key]}`);
85539
+ return 0;
85540
+ }
85541
+ if (action === "test") {
85542
+ const r = await testConnection2(loadSettings2(home));
85543
+ (r.ok && r.toolCalls ? io.out : io.err)(r.message);
85544
+ return r.ok ? 0 : 1;
85545
+ }
85546
+ throw new UsageError("usage: veoflow config [get [<key>] | set <key> <value> | test]");
85547
+ }
83373
85548
  default:
83374
85549
  throw new UsageError(`unknown command ${command}
83375
85550
 
@@ -83390,6 +85565,9 @@ ${USAGE}`);
83390
85565
  if (!keepOpen) engine.close();
83391
85566
  }
83392
85567
  }
85568
+ function plain(text) {
85569
+ return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "");
85570
+ }
83393
85571
  export {
83394
85572
  main
83395
85573
  };