@hginsights/hgi 0.1.1 → 0.2.0

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/bin.js CHANGED
@@ -98,7 +98,8 @@ var EXIT = {
98
98
  NETWORK: 9,
99
99
  WRONG_VERB: 10,
100
100
  FORBIDDEN: 11,
101
- LOCAL_STATE: 12
101
+ LOCAL_STATE: 12,
102
+ BUDGET: 13
102
103
  };
103
104
  var ERROR_EXIT = {
104
105
  internal_error: EXIT.INTERNAL,
@@ -108,6 +109,11 @@ var ERROR_EXIT = {
108
109
  login_expired: EXIT.LOGIN,
109
110
  rate_limited: EXIT.RATE_LIMITED,
110
111
  credit_limit_exceeded: EXIT.CREDIT,
112
+ user_credit_limit_exceeded: EXIT.CREDIT,
113
+ governance_unavailable: EXIT.UNREACHABLE,
114
+ tool_not_enabled_for_team: EXIT.FORBIDDEN,
115
+ phoenix_account_required: EXIT.LOGIN,
116
+ budget_exceeded: EXIT.BUDGET,
111
117
  server_unreachable: EXIT.UNREACHABLE,
112
118
  oauth_error: EXIT.OAUTH,
113
119
  network_proxy_tls: EXIT.NETWORK,
@@ -269,7 +275,7 @@ function classifyNetworkError(err, context = "the server", viaProxy) {
269
275
  }
270
276
 
271
277
  // src/config.ts
272
- var VERSION = true ? "0.1.1" : "0.0.0-dev";
278
+ var VERSION = true ? "0.2.0" : "0.0.0-dev";
273
279
  var DEFAULT_BASE_URL = "https://phoenix.hginsights.com";
274
280
  var MCP_PATH = "/api/ai/mcp";
275
281
  var SCOPE = "mcp:read mcp:tools offline_access";
@@ -364,10 +370,12 @@ function workspaceRoot() {
364
370
  if (top === home || top === path.parse(top).root) return null;
365
371
  return top;
366
372
  }
367
- function guardOverride(dir, label) {
373
+ function guardOverride(dir, label, opts = {}) {
368
374
  const resolved = realpathDeep(dir);
369
375
  const root = workspaceRoot();
370
- if (root && (isInside(resolved, root) || isInsideByInode(resolved, root))) {
376
+ const lexical = opts.lexical ? path.resolve(dir) : null;
377
+ const inside = (p) => isInside(p, root) || isInsideByInode(p, root);
378
+ if (root && (inside(resolved) || lexical !== null && inside(lexical))) {
371
379
  throw new HgiError("invalid_input", `${label} must not be inside a workspace (${root}).`, {
372
380
  hint: "Credentials and caches never live in a project directory; choose a path outside it.",
373
381
  details: { reason: "workspace_guard" }
@@ -380,6 +388,9 @@ function configDir(env = process.env) {
380
388
  if (env.XDG_CONFIG_HOME) return guardOverride(path.join(env.XDG_CONFIG_HOME, "hgi"), "XDG_CONFIG_HOME");
381
389
  return path.join(os.homedir(), ".config", "hgi");
382
390
  }
391
+ function guardLedgerOverride(file) {
392
+ return guardOverride(file, "HGI_LEDGER", { lexical: true });
393
+ }
383
394
  function cacheDir(env = process.env) {
384
395
  if (env.HGI_CACHE_DIR) return guardOverride(env.HGI_CACHE_DIR, "HGI_CACHE_DIR");
385
396
  if (env.XDG_CACHE_HOME) return guardOverride(path.join(env.XDG_CACHE_HOME, "hgi"), "XDG_CACHE_HOME");
@@ -735,8 +746,11 @@ async function getUserinfo(meta, doFetch, onUnauthorized) {
735
746
  }
736
747
 
737
748
  // src/auth/credentials-store.ts
738
- import fs2 from "fs";
749
+ import fs3 from "fs";
739
750
  import path2 from "path";
751
+
752
+ // src/file-lock.ts
753
+ import fs2 from "fs";
740
754
  import lockfile from "proper-lockfile";
741
755
 
742
756
  // src/auth/pkce.ts
@@ -753,6 +767,100 @@ function safeEqual(a, b) {
753
767
  return left.length === right.length && timingSafeEqual(left, right);
754
768
  }
755
769
 
770
+ // src/file-lock.ts
771
+ var DEFAULT_TIMING = { stale: 3e4, update: 5e3 };
772
+ function stampOwner(ownerPath, nonce, label) {
773
+ let fd;
774
+ try {
775
+ fd = fs2.openSync(
776
+ ownerPath,
777
+ fs2.constants.O_CREAT | fs2.constants.O_WRONLY | fs2.constants.O_TRUNC | fs2.constants.O_NOFOLLOW | fs2.constants.O_NONBLOCK,
778
+ 384
779
+ );
780
+ if (!fs2.fstatSync(fd).isFile()) throw new Error("not a regular file");
781
+ fs2.writeFileSync(fd, nonce);
782
+ } catch (err) {
783
+ throw new HgiError("local_state_error", `Could not stamp the ${label} lock (${ownerPath}): ${err.code ?? err.message}.`, {
784
+ hint: `Remove ${ownerPath} if it is not a regular file, then retry.`,
785
+ details: { kind: "lock_timeout" },
786
+ cause: err
787
+ });
788
+ } finally {
789
+ if (fd !== void 0) fs2.closeSync(fd);
790
+ }
791
+ }
792
+ function readOwner(ownerPath) {
793
+ let fd;
794
+ try {
795
+ fd = fs2.openSync(ownerPath, fs2.constants.O_RDONLY | fs2.constants.O_NOFOLLOW | fs2.constants.O_NONBLOCK);
796
+ if (!fs2.fstatSync(fd).isFile()) return null;
797
+ return fs2.readFileSync(fd, "utf8");
798
+ } catch {
799
+ return null;
800
+ } finally {
801
+ if (fd !== void 0) fs2.closeSync(fd);
802
+ }
803
+ }
804
+ async function withFileLock(file, opts, fn) {
805
+ let compromised;
806
+ let release;
807
+ try {
808
+ release = await lockfile.lock(file, {
809
+ ...DEFAULT_TIMING,
810
+ ...opts.timing ?? {},
811
+ realpath: false,
812
+ retries: { ...opts.retries },
813
+ onCompromised: (err) => {
814
+ compromised = err;
815
+ debug("lock compromised", err);
816
+ }
817
+ });
818
+ } catch (err) {
819
+ if (err.code === "ELOCKED") {
820
+ throw new HgiError("local_state_error", "Timed out waiting for another hgi process to finish.", {
821
+ hint: `If no other hgi is running, remove ${file}.lock and retry.`,
822
+ details: { kind: "lock_timeout" },
823
+ cause: err
824
+ });
825
+ }
826
+ throw new HgiError("local_state_error", `Could not take the ${opts.label} lock: ${err.code ?? "error"}.`, {
827
+ details: { kind: "lock_timeout" },
828
+ cause: err
829
+ });
830
+ }
831
+ const ownerPath = `${file}.lock-owner`;
832
+ const nonce = randomUrlSafe(12);
833
+ const lost = (cause) => new HgiError("local_state_error", `The ${opts.label} lock was lost while hgi was working (the process stalled for too long).`, {
834
+ hint: "Another hgi process may have taken over. Re-run your command.",
835
+ details: { kind: "lock_compromised" },
836
+ cause
837
+ });
838
+ const handle = {
839
+ assertHeld() {
840
+ if (compromised !== void 0) throw lost(compromised);
841
+ if (readOwner(ownerPath) !== nonce) throw lost(new Error("lock owner changed"));
842
+ }
843
+ };
844
+ let stamped = false;
845
+ try {
846
+ stampOwner(ownerPath, nonce, opts.label);
847
+ stamped = true;
848
+ return await fn(handle);
849
+ } finally {
850
+ if (!stamped) {
851
+ await release().catch((err) => debug("lock release failed", err));
852
+ } else if (readOwner(ownerPath) === nonce) {
853
+ try {
854
+ fs2.unlinkSync(ownerPath);
855
+ } catch {
856
+ }
857
+ await release().catch((err) => debug("lock release failed", err));
858
+ } else if (compromised === void 0) {
859
+ debug("lock ownership changed; not releasing the successor's lock");
860
+ }
861
+ }
862
+ }
863
+
756
864
  // src/auth/credentials-store.ts
757
865
  function unsafe(reason, file) {
758
866
  return new HgiError("local_state_error", `Credentials path is unsafe (${reason}): ${file}`, {
@@ -770,7 +878,7 @@ function isCredentials(value) {
770
878
  function ensureDir(dir) {
771
879
  let st = null;
772
880
  try {
773
- st = fs2.lstatSync(dir);
881
+ st = fs3.lstatSync(dir);
774
882
  } catch {
775
883
  st = null;
776
884
  }
@@ -779,15 +887,15 @@ function ensureDir(dir) {
779
887
  if (!st.isDirectory()) throw unsafe("not_a_directory", dir);
780
888
  if ((st.mode & 63) !== 0) {
781
889
  try {
782
- fs2.chmodSync(dir, 448);
890
+ fs3.chmodSync(dir, 448);
783
891
  } catch {
784
892
  }
785
893
  }
786
894
  return;
787
895
  }
788
896
  try {
789
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
790
- fs2.chmodSync(dir, 448);
897
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
898
+ fs3.chmodSync(dir, 448);
791
899
  } catch (err) {
792
900
  throw new HgiError("local_state_error", `Cannot create ${dir}: ${err.code ?? "error"}.`, {
793
901
  details: { kind: "write_failed" },
@@ -799,7 +907,7 @@ function preflightWritable(file) {
799
907
  ensureDir(path2.dirname(file));
800
908
  let st = null;
801
909
  try {
802
- st = fs2.lstatSync(file);
910
+ st = fs3.lstatSync(file);
803
911
  } catch {
804
912
  st = null;
805
913
  }
@@ -809,7 +917,7 @@ function preflightWritable(file) {
809
917
  function inspectCredentials(file) {
810
918
  let fd;
811
919
  try {
812
- fd = fs2.openSync(file, fs2.constants.O_RDONLY | fs2.constants.O_NOFOLLOW);
920
+ fd = fs3.openSync(file, fs3.constants.O_RDONLY | fs3.constants.O_NOFOLLOW);
813
921
  } catch (err) {
814
922
  const code = err.code;
815
923
  if (code === "ENOENT") return { status: "missing" };
@@ -820,11 +928,11 @@ function inspectCredentials(file) {
820
928
  });
821
929
  }
822
930
  try {
823
- const st = fs2.fstatSync(fd);
931
+ const st = fs3.fstatSync(fd);
824
932
  if (!st.isFile()) throw unsafe("not_regular_file", file);
825
933
  let parsed;
826
934
  try {
827
- parsed = JSON.parse(fs2.readFileSync(fd, "utf8"));
935
+ parsed = JSON.parse(fs3.readFileSync(fd, "utf8"));
828
936
  } catch {
829
937
  return { status: "corrupt" };
830
938
  }
@@ -834,7 +942,7 @@ function inspectCredentials(file) {
834
942
  if ((st.mode & 63) !== 0) return { status: "bad_mode", creds: parsed };
835
943
  return { status: "ok", creds: parsed };
836
944
  } finally {
837
- fs2.closeSync(fd);
945
+ fs3.closeSync(fd);
838
946
  }
839
947
  }
840
948
  function readCredentials(file) {
@@ -861,28 +969,28 @@ function writePrivateFile(file, content, hooks = {}) {
861
969
  const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
862
970
  let fd;
863
971
  try {
864
- fd = fs2.openSync(
972
+ fd = fs3.openSync(
865
973
  tmp,
866
- fs2.constants.O_CREAT | fs2.constants.O_EXCL | fs2.constants.O_WRONLY | fs2.constants.O_NOFOLLOW,
974
+ fs3.constants.O_CREAT | fs3.constants.O_EXCL | fs3.constants.O_WRONLY | fs3.constants.O_NOFOLLOW,
867
975
  384
868
976
  );
869
- fs2.writeFileSync(fd, content);
870
- fs2.fsyncSync(fd);
871
- fs2.closeSync(fd);
977
+ fs3.writeFileSync(fd, content);
978
+ fs3.fsyncSync(fd);
979
+ fs3.closeSync(fd);
872
980
  fd = void 0;
873
981
  hooks.afterTemp?.();
874
982
  preflightWritable(file);
875
983
  hooks.beforeRename?.();
876
- fs2.renameSync(tmp, file);
984
+ fs3.renameSync(tmp, file);
877
985
  } catch (err) {
878
986
  if (fd !== void 0) {
879
987
  try {
880
- fs2.closeSync(fd);
988
+ fs3.closeSync(fd);
881
989
  } catch {
882
990
  }
883
991
  }
884
992
  try {
885
- fs2.unlinkSync(tmp);
993
+ fs3.unlinkSync(tmp);
886
994
  } catch {
887
995
  }
888
996
  if (err instanceof HgiError) throw err;
@@ -900,115 +1008,28 @@ function writeCredentials(file, creds, hooks = {}) {
900
1008
  }
901
1009
  function deleteCredentials(file) {
902
1010
  try {
903
- fs2.unlinkSync(file);
1011
+ fs3.unlinkSync(file);
904
1012
  } catch (err) {
905
1013
  if (err.code !== "ENOENT") throw err;
906
1014
  }
907
1015
  }
908
- var LOCK_OPTIONS = {
909
- stale: 3e4,
910
- update: 5e3,
911
- realpath: false,
912
- retries: { retries: 60, factor: 1.4, minTimeout: 100, maxTimeout: 1500, randomize: true }
913
- };
914
- function stampOwner(ownerPath, nonce) {
915
- let fd;
916
- try {
917
- fd = fs2.openSync(
918
- ownerPath,
919
- fs2.constants.O_CREAT | fs2.constants.O_WRONLY | fs2.constants.O_TRUNC | fs2.constants.O_NOFOLLOW | fs2.constants.O_NONBLOCK,
920
- 384
921
- );
922
- if (!fs2.fstatSync(fd).isFile()) throw new Error("not a regular file");
923
- fs2.writeFileSync(fd, nonce);
924
- } catch (err) {
925
- throw new HgiError("local_state_error", `Could not stamp the credentials lock (${ownerPath}): ${err.code ?? err.message}.`, {
926
- hint: `Remove ${ownerPath} if it is not a regular file, then retry.`,
927
- details: { kind: "lock_timeout" },
928
- cause: err
929
- });
930
- } finally {
931
- if (fd !== void 0) fs2.closeSync(fd);
932
- }
933
- }
934
- function readOwner(ownerPath) {
935
- let fd;
936
- try {
937
- fd = fs2.openSync(ownerPath, fs2.constants.O_RDONLY | fs2.constants.O_NOFOLLOW | fs2.constants.O_NONBLOCK);
938
- if (!fs2.fstatSync(fd).isFile()) return null;
939
- return fs2.readFileSync(fd, "utf8");
940
- } catch {
941
- return null;
942
- } finally {
943
- if (fd !== void 0) fs2.closeSync(fd);
944
- }
945
- }
946
- async function withLock(file, fn, timing) {
1016
+ var LOCK_RETRIES = { retries: 60, factor: 1.4, minTimeout: 100, maxTimeout: 1500, randomize: true };
1017
+ async function withLock(file, fn, timing, label = "credentials") {
947
1018
  ensureDir(path2.dirname(file));
948
- let compromised;
949
- let release;
950
- try {
951
- release = await lockfile.lock(file, {
952
- ...LOCK_OPTIONS,
953
- ...timing ?? {},
954
- retries: { ...LOCK_OPTIONS.retries },
955
- onCompromised: (err) => {
956
- compromised = err;
957
- debug("lock compromised", err);
1019
+ return withFileLock(file, { label, retries: LOCK_RETRIES, timing }, (lock) => {
1020
+ const held = {
1021
+ assertHeld: () => lock.assertHeld(),
1022
+ write(creds, hooks) {
1023
+ lock.assertHeld();
1024
+ writeCredentials(file, creds, { afterTemp: hooks?.afterTemp, beforeRename: () => lock.assertHeld() });
1025
+ },
1026
+ remove() {
1027
+ lock.assertHeld();
1028
+ deleteCredentials(file);
958
1029
  }
959
- });
960
- } catch (err) {
961
- if (err.code === "ELOCKED") {
962
- throw new HgiError("local_state_error", "Timed out waiting for another hgi process to finish.", {
963
- hint: `If no other hgi is running, remove ${file}.lock and retry.`,
964
- details: { kind: "lock_timeout" },
965
- cause: err
966
- });
967
- }
968
- throw new HgiError("local_state_error", `Could not take the credentials lock: ${err.code ?? "error"}.`, {
969
- details: { kind: "lock_timeout" },
970
- cause: err
971
- });
972
- }
973
- const ownerPath = `${file}.lock-owner`;
974
- const nonce = randomUrlSafe(12);
975
- const lost = (cause) => new HgiError("local_state_error", "The credentials lock was lost while hgi was working (the process stalled for too long).", {
976
- hint: "Another hgi process may have taken over. Re-run your command.",
977
- details: { kind: "lock_compromised" },
978
- cause
1030
+ };
1031
+ return fn(held);
979
1032
  });
980
- const held = {
981
- assertHeld() {
982
- if (compromised !== void 0) throw lost(compromised);
983
- if (readOwner(ownerPath) !== nonce) throw lost(new Error("lock owner changed"));
984
- },
985
- write(creds, hooks) {
986
- held.assertHeld();
987
- writeCredentials(file, creds, { afterTemp: hooks?.afterTemp, beforeRename: () => held.assertHeld() });
988
- },
989
- remove() {
990
- held.assertHeld();
991
- deleteCredentials(file);
992
- }
993
- };
994
- let stamped = false;
995
- try {
996
- stampOwner(ownerPath, nonce);
997
- stamped = true;
998
- return await fn(held);
999
- } finally {
1000
- if (!stamped) {
1001
- await release().catch((err) => debug("lock release failed", err));
1002
- } else if (readOwner(ownerPath) === nonce) {
1003
- try {
1004
- fs2.unlinkSync(ownerPath);
1005
- } catch {
1006
- }
1007
- await release().catch((err) => debug("lock release failed", err));
1008
- } else if (compromised === void 0) {
1009
- debug("lock ownership changed; not releasing the successor's lock");
1010
- }
1011
- }
1012
1033
  }
1013
1034
 
1014
1035
  // src/auth/login.ts
@@ -1073,6 +1094,28 @@ function parsePastedCallback(input, expected, used) {
1073
1094
 
1074
1095
  // src/auth/loopback.ts
1075
1096
  import http from "http";
1097
+
1098
+ // src/auth/recovery.ts
1099
+ function steps(base, browser) {
1100
+ const host = new URL(base).host;
1101
+ return `open a private window (or clear ${browser}'s cookies for ${host}), sign in at ${base} first`;
1102
+ }
1103
+ function browserFlowLines(base, url) {
1104
+ return [
1105
+ "Opening your browser to sign in. If it does not open, or the page shows an error,",
1106
+ "open this URL in a browser on this computer; sign-in still finishes here:",
1107
+ ` ${url}`,
1108
+ `If the page shows 403 Forbidden: ${steps(base, "this browser")}, then open the URL above in that same window.`
1109
+ ];
1110
+ }
1111
+ function noBrowserForbiddenLine(base) {
1112
+ return `If the page shows 403 Forbidden, in the browser you open it in: ${steps(base, "that browser")}, then open the URL above in that same window.`;
1113
+ }
1114
+ function loginTimeoutHint(base) {
1115
+ return `If the sign-in page showed 403 Forbidden: ${steps(base, "that browser")}, then run \`hgi auth login\` again and open the URL it prints in that same window. On a remote machine, use \`--no-browser\`.`;
1116
+ }
1117
+
1118
+ // src/auth/loopback.ts
1076
1119
  var PAGE = (title, body) => `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head><body style="font-family:system-ui;max-width:32rem;margin:4rem auto;line-height:1.5"><h1>${title}</h1><p>${body}</p></body></html>`;
1077
1120
  async function startLoopback(opts) {
1078
1121
  let settle;
@@ -1109,7 +1152,7 @@ async function startLoopback(opts) {
1109
1152
  done = true;
1110
1153
  settle.reject(
1111
1154
  new HgiError("oauth_error", "Timed out waiting for the browser sign-in to finish.", {
1112
- hint: "Run `hgi auth login` again, or use `--no-browser` on a remote machine.",
1155
+ hint: loginTimeoutHint(opts.base),
1113
1156
  details: { reason: "login_timeout" }
1114
1157
  })
1115
1158
  );
@@ -1294,15 +1337,15 @@ async function login(opts) {
1294
1337
  say2("Open this URL in a browser on any machine and approve access:");
1295
1338
  say2(` ${url}`);
1296
1339
  say2("After approving, the browser will fail to load a http://localhost page. Copy that full URL from the address bar.");
1340
+ say2(noBrowserForbiddenLine(base));
1297
1341
  const pasted = await readPastedLine("Paste the callback URL: ");
1298
1342
  code = parsePastedCallback(pasted, { redirectUri, state }, { value: false });
1299
1343
  } else {
1300
- const loop = await startLoopback({ state, timeoutMs: LOGIN_TIMEOUT_MS });
1344
+ const loop = await startLoopback({ state, timeoutMs: LOGIN_TIMEOUT_MS, base });
1301
1345
  try {
1302
1346
  redirectUri = loop.redirectUri;
1303
1347
  const url = buildAuthorizeUrl(meta, base, { redirectUri, state, challenge });
1304
- say2("Opening your browser to sign in. If it does not open, visit:");
1305
- say2(` ${url}`);
1348
+ for (const line of browserFlowLines(base, url)) say2(line);
1306
1349
  openBrowser(url);
1307
1350
  code = await loop.waitForCode();
1308
1351
  } finally {
@@ -1574,7 +1617,7 @@ function formatValue(value, format, opts) {
1574
1617
  }
1575
1618
 
1576
1619
  // src/output/out-file.ts
1577
- import fs3 from "fs";
1620
+ import fs4 from "fs";
1578
1621
  import path3 from "path";
1579
1622
  function refuse(message, reason, hint) {
1580
1623
  return new HgiError("invalid_input", message, { hint, details: { reason } });
@@ -1596,13 +1639,13 @@ function protectedInodes(protectedDirs2) {
1596
1639
  for (const dir of protectedDirs2) {
1597
1640
  let entries = [];
1598
1641
  try {
1599
- entries = fs3.readdirSync(dir);
1642
+ entries = fs4.readdirSync(dir);
1600
1643
  } catch {
1601
1644
  continue;
1602
1645
  }
1603
1646
  for (const name of entries) {
1604
1647
  try {
1605
- const st = fs3.statSync(path3.join(dir, name));
1648
+ const st = fs4.statSync(path3.join(dir, name));
1606
1649
  if (st.isFile()) stats.push(st);
1607
1650
  } catch {
1608
1651
  }
@@ -1610,24 +1653,24 @@ function protectedInodes(protectedDirs2) {
1610
1653
  }
1611
1654
  return stats;
1612
1655
  }
1613
- function readInputFile(file, protectedDirs2, hooks = {}) {
1614
- const real = assertNotProtected(file, protectedDirs2, "--input @file");
1656
+ function readInputFile(file, protectedDirs2, hooks = {}, what = "--input @file") {
1657
+ const real = assertNotProtected(file, protectedDirs2, what);
1615
1658
  let fd;
1616
1659
  try {
1617
1660
  hooks.beforeOpen?.();
1618
- fd = fs3.openSync(real, fs3.constants.O_RDONLY | fs3.constants.O_NOFOLLOW);
1619
- const st = fs3.fstatSync(fd);
1661
+ fd = fs4.openSync(real, fs4.constants.O_RDONLY | fs4.constants.O_NOFOLLOW);
1662
+ const st = fs4.fstatSync(fd);
1620
1663
  if (!st.isFile()) throw refuse(`${file} is not a regular file.`, "not_regular_file");
1621
1664
  if (protectedInodes(protectedDirs2).some((other) => sameInode(st, other))) {
1622
1665
  throw refuse("That file is one of hgi's credential or cache files.", "protected_path");
1623
1666
  }
1624
1667
  hooks.afterCheck?.();
1625
- return fs3.readFileSync(fd, "utf8");
1668
+ return fs4.readFileSync(fd, "utf8");
1626
1669
  } catch (err) {
1627
1670
  if (err instanceof HgiError) throw err;
1628
1671
  throw refuse(`Cannot read input file ${file}: ${err.code ?? "error"}.`, "input_unreadable");
1629
1672
  } finally {
1630
- if (fd !== void 0) fs3.closeSync(fd);
1673
+ if (fd !== void 0) fs4.closeSync(fd);
1631
1674
  }
1632
1675
  }
1633
1676
  function preflightOutFile(target, opts) {
@@ -1638,14 +1681,14 @@ function preflightOutFile(target, opts) {
1638
1681
  const dest = path3.join(dir, path3.basename(target));
1639
1682
  assertNotProtected(dest, opts.protectedDirs, "--out");
1640
1683
  try {
1641
- if (!fs3.statSync(dir).isDirectory()) throw new Error("not a directory");
1642
- fs3.accessSync(dir, fs3.constants.W_OK | fs3.constants.X_OK);
1684
+ if (!fs4.statSync(dir).isDirectory()) throw new Error("not a directory");
1685
+ fs4.accessSync(dir, fs4.constants.W_OK | fs4.constants.X_OK);
1643
1686
  } catch {
1644
1687
  throw refuse(`Cannot write to ${dir}: it does not exist or is not writable.`, "out_dir_unwritable", "Create the directory first, or choose another --out path.");
1645
1688
  }
1646
1689
  let existing = null;
1647
1690
  try {
1648
- existing = fs3.lstatSync(dest);
1691
+ existing = fs4.lstatSync(dest);
1649
1692
  } catch {
1650
1693
  existing = null;
1651
1694
  }
@@ -1660,17 +1703,17 @@ function preflightOutFile(target, opts) {
1660
1703
  }
1661
1704
  function writeOutFile(target, data, opts) {
1662
1705
  const { dest, existing } = preflightOutFile(target, opts);
1663
- const flags = fs3.constants.O_CREAT | fs3.constants.O_EXCL | fs3.constants.O_WRONLY | fs3.constants.O_NOFOLLOW;
1706
+ const flags = fs4.constants.O_CREAT | fs4.constants.O_EXCL | fs4.constants.O_WRONLY | fs4.constants.O_NOFOLLOW;
1664
1707
  const tmp = existing ? `${dest}.hgi-${process.pid}-${Date.now()}.tmp` : dest;
1665
1708
  try {
1666
- const fd = fs3.openSync(tmp, flags, 438);
1709
+ const fd = fs4.openSync(tmp, flags, 438);
1667
1710
  try {
1668
- fs3.writeFileSync(fd, data);
1669
- fs3.fsyncSync(fd);
1711
+ fs4.writeFileSync(fd, data);
1712
+ fs4.fsyncSync(fd);
1670
1713
  } finally {
1671
- fs3.closeSync(fd);
1714
+ fs4.closeSync(fd);
1672
1715
  }
1673
- if (existing) fs3.renameSync(tmp, dest);
1716
+ if (existing) fs4.renameSync(tmp, dest);
1674
1717
  } catch (err) {
1675
1718
  if (err.code === "EEXIST" && !existing) {
1676
1719
  throw refuse(`${dest} already exists.`, "out_exists", "Choose a new path, or pass --force to `hgi run`.");
@@ -1717,7 +1760,11 @@ function preflightOutput(opts) {
1717
1760
  async function emit(value, opts = {}) {
1718
1761
  const isTty = Boolean(process.stdout.isTTY);
1719
1762
  const format = opts.format ? parseFormat(opts.format) : defaultFormat(isTty);
1720
- let text = formatValue(applySelect(value, opts.select), format, { pretty: isTty });
1763
+ await emitText(formatValue(applySelect(value, opts.select), format, { pretty: isTty }), format, opts);
1764
+ }
1765
+ async function emitText(formatted, format, opts = {}) {
1766
+ const isTty = Boolean(process.stdout.isTTY);
1767
+ let text = formatted;
1721
1768
  if (isTty && !opts.out) {
1722
1769
  if (format === "table" || format === "csv" || format === "yaml") text = sanitizeForTerminal(text);
1723
1770
  else if (format === "json" || format === "jsonl") text = escapeJsonForTerminal(text);
@@ -1791,38 +1838,257 @@ function registerAuthCommands(program) {
1791
1838
  });
1792
1839
  }
1793
1840
 
1794
- // src/commands/invoke.ts
1795
- import { Option } from "commander";
1796
-
1797
- // src/mcp/cache.ts
1798
- import fs4 from "fs";
1799
- import path4 from "path";
1841
+ // src/budget.ts
1800
1842
  import { createHash as createHash2 } from "crypto";
1801
- var TOOLS_CACHE_TTL_MS = 15 * 6e4;
1802
- function toolsCachePath(base, orgSlug, userId) {
1803
- const userHash = createHash2("sha256").update(userId).digest("hex").slice(0, 12);
1804
- const org = orgSlug.replace(/[^a-z0-9_-]/gi, "_");
1805
- return path4.join(cacheDir(), `tools-${hostSlug(base)}-${org}-${userHash}.json`);
1843
+ import fs5 from "fs";
1844
+ import path4 from "path";
1845
+ var PRUNE_AFTER_MS = 7 * 24 * 60 * 60 * 1e3;
1846
+ function resolveBudgetId(env = process.env) {
1847
+ const id = env.HGI_BUDGET_ID;
1848
+ return id ? id : String(process.ppid);
1849
+ }
1850
+ function parseMaxCredits(raw, source) {
1851
+ const value = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
1852
+ if (!Number.isSafeInteger(value)) {
1853
+ throw new HgiError("invalid_input", `${source} must be a non-negative whole number of credits, not "${raw}".`, {
1854
+ hint: "For example --max-credits 50. 0 refuses every call.",
1855
+ details: { reason: "max_credits" }
1856
+ });
1857
+ }
1858
+ return value;
1806
1859
  }
1807
- function readToolsCache(file, now = Date.now()) {
1860
+ function resolveMaxCredits(flag, env = process.env) {
1861
+ if (flag !== void 0) return parseMaxCredits(flag, "--max-credits");
1862
+ const fromEnv = env.HGI_MAX_CREDITS;
1863
+ if (fromEnv) return parseMaxCredits(fromEnv, "HGI_MAX_CREDITS");
1864
+ return null;
1865
+ }
1866
+ function budgetsDir(env = process.env) {
1867
+ return path4.join(configDir(env), "budgets");
1868
+ }
1869
+ function budgetPath(id, env = process.env) {
1870
+ const name = createHash2("sha256").update(id).digest("hex").slice(0, 16);
1871
+ return path4.join(budgetsDir(env), `${name}.json`);
1872
+ }
1873
+ function budgetError(kind, message, hint, cause) {
1874
+ return new HgiError("local_state_error", message, { hint, details: { kind }, cause });
1875
+ }
1876
+ var CORRUPT_HINT = "Run `hgi budget reset` to start the count over, or delete the file.";
1877
+ function assertDirsSafe(env, kind) {
1878
+ for (const dir of [configDir(env), budgetsDir(env)]) {
1879
+ let st;
1880
+ try {
1881
+ st = fs5.lstatSync(dir);
1882
+ } catch {
1883
+ continue;
1884
+ }
1885
+ if (st.isSymbolicLink() || !st.isDirectory()) {
1886
+ throw budgetError(
1887
+ kind,
1888
+ `Budget directory is unsafe (${st.isSymbolicLink() ? "symlink" : "not a directory"}): ${dir}`,
1889
+ "Remove or fix it yourself; hgi will not follow symlinks."
1890
+ );
1891
+ }
1892
+ }
1893
+ }
1894
+ async function withBudgetLock(file, kind, fn) {
1895
+ const dir = path4.dirname(file);
1896
+ ensureDir(dir);
1808
1897
  try {
1809
- const parsed = JSON.parse(fs4.readFileSync(file, "utf8"));
1810
- if (!Array.isArray(parsed.tools) || typeof parsed.fetched_at !== "number") return null;
1811
- if (now - parsed.fetched_at > TOOLS_CACHE_TTL_MS) return null;
1898
+ fs5.accessSync(dir, fs5.constants.W_OK | fs5.constants.X_OK);
1899
+ } catch (err) {
1900
+ throw budgetError(kind, `Cannot write to the budget directory ${dir}: ${err.code ?? "error"}.`, `Make ${dir} writable (chmod 700), then retry.`, err);
1901
+ }
1902
+ return withLock(file, fn, void 0, "budget");
1903
+ }
1904
+ function isCount(value) {
1905
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
1906
+ }
1907
+ function isState(value, id) {
1908
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1909
+ const b = value;
1910
+ return b.schema === 1 && b.budget_id === id && isCount(b.spent) && isCount(b.calls) && Number.isSafeInteger(b.calls) && isCount(b.unknown_cost_calls) && Number.isSafeInteger(b.unknown_cost_calls) && b.unknown_cost_calls <= b.calls && (b.max === null || isCount(b.max) && Number.isSafeInteger(b.max)) && typeof b.updated_at === "string" && !Number.isNaN(Date.parse(b.updated_at));
1911
+ }
1912
+ function emptyState(id, now) {
1913
+ return { schema: 1, budget_id: id, spent: 0, calls: 0, unknown_cost_calls: 0, max: null, updated_at: new Date(now).toISOString() };
1914
+ }
1915
+ function readFile(file, id) {
1916
+ let fd;
1917
+ try {
1918
+ fd = fs5.openSync(file, fs5.constants.O_RDONLY | fs5.constants.O_NOFOLLOW);
1919
+ } catch (err) {
1920
+ const code = err.code;
1921
+ if (code === "ENOENT") return null;
1922
+ throw budgetError(
1923
+ "budget_corrupt",
1924
+ code === "ELOOP" ? `Budget file is a symlink: ${file}` : `Cannot read budget file ${file}: ${code ?? "error"}.`,
1925
+ code === "ELOOP" ? "Remove it yourself; hgi will not follow symlinks." : CORRUPT_HINT,
1926
+ err
1927
+ );
1928
+ }
1929
+ try {
1930
+ if (!fs5.fstatSync(fd).isFile()) throw budgetError("budget_corrupt", `Budget path is not a regular file: ${file}`, "Remove it yourself.");
1931
+ let parsed;
1932
+ try {
1933
+ parsed = JSON.parse(fs5.readFileSync(fd, "utf8"));
1934
+ } catch (err) {
1935
+ throw budgetError("budget_corrupt", `Budget file is corrupt: ${file}`, CORRUPT_HINT, err);
1936
+ }
1937
+ if (!isState(parsed, id)) throw budgetError("budget_corrupt", `Budget file is corrupt: ${file}`, CORRUPT_HINT);
1812
1938
  return parsed;
1939
+ } finally {
1940
+ fs5.closeSync(fd);
1941
+ }
1942
+ }
1943
+ function readBudget(id, env = process.env, now = Date.now()) {
1944
+ assertDirsSafe(env, "budget_corrupt");
1945
+ return readFile(budgetPath(id, env), id) ?? emptyState(id, now);
1946
+ }
1947
+ function writeState(lock, file, state) {
1948
+ lock.assertHeld();
1949
+ writePrivateFile(file, `${JSON.stringify(state)}
1950
+ `, { beforeRename: () => lock.assertHeld() });
1951
+ }
1952
+ function pruneBudgets(dir, now = Date.now()) {
1953
+ let names;
1954
+ try {
1955
+ names = fs5.readdirSync(dir);
1813
1956
  } catch {
1814
- return null;
1957
+ return;
1958
+ }
1959
+ for (const name of names) {
1960
+ if (!name.endsWith(".json")) continue;
1961
+ const file = path4.join(dir, name);
1962
+ try {
1963
+ const st = fs5.lstatSync(file);
1964
+ if (st.isFile() && now - st.mtimeMs > PRUNE_AFTER_MS) fs5.unlinkSync(file);
1965
+ } catch (err) {
1966
+ debug("budget prune skipped", name, err);
1967
+ }
1815
1968
  }
1816
1969
  }
1817
- function writeToolsCache(file, cache) {
1970
+ async function checkBudget(id, max, env = process.env) {
1971
+ assertDirsSafe(env, "budget_corrupt");
1972
+ const file = budgetPath(id, env);
1973
+ const state = await withBudgetLock(file, "budget_corrupt", async () => readFile(file, id) ?? emptyState(id, Date.now()));
1974
+ if (state.spent >= max) {
1975
+ throw new HgiError("budget_exceeded", `This run's credit cap is reached: ${state.spent} of ${max} credits spent (budget ${id}).`, {
1976
+ hint: "Nothing was sent. Raise --max-credits or HGI_MAX_CREDITS, or start the count over with `hgi budget reset`.",
1977
+ details: { spent: state.spent, max, budget_id: id }
1978
+ });
1979
+ }
1980
+ return state;
1981
+ }
1982
+ async function recordSpend(id, max, cost, env = process.env, now = Date.now()) {
1818
1983
  try {
1819
- writePrivateFile(file, JSON.stringify(cache));
1984
+ assertDirsSafe(env, "budget_write_failed");
1985
+ const file = budgetPath(id, env);
1986
+ const next = await withBudgetLock(file, "budget_write_failed", async (lock) => {
1987
+ const prev = readFile(file, id) ?? emptyState(id, now);
1988
+ const known = cost !== null && Number.isFinite(cost) && cost >= 0;
1989
+ const state = {
1990
+ schema: 1,
1991
+ budget_id: id,
1992
+ spent: prev.spent + (known ? cost : 0),
1993
+ calls: prev.calls + 1,
1994
+ unknown_cost_calls: prev.unknown_cost_calls + (known ? 0 : 1),
1995
+ max,
1996
+ updated_at: new Date(now).toISOString()
1997
+ };
1998
+ if (!isState(state, id)) throw new Error("the new total is not a valid count (the reported cost overflowed it).");
1999
+ writeState(lock, file, state);
2000
+ return state;
2001
+ });
2002
+ pruneBudgets(path4.dirname(file), now);
2003
+ return next;
1820
2004
  } catch (err) {
1821
- debug("could not write tools cache", err);
2005
+ const cause = err instanceof Error ? err.message : String(err);
2006
+ throw budgetError("budget_write_failed", `Could not record this call's spend: ${cause}`, CORRUPT_HINT, err);
1822
2007
  }
1823
2008
  }
2009
+ async function resetBudget(id, env = process.env, now = Date.now()) {
2010
+ assertDirsSafe(env, "budget_write_failed");
2011
+ const file = budgetPath(id, env);
2012
+ const next = await withBudgetLock(file, "budget_write_failed", async (lock) => {
2013
+ let max = null;
2014
+ try {
2015
+ max = readFile(file, id)?.max ?? null;
2016
+ } catch (err) {
2017
+ if (!(err instanceof HgiError && err.details?.kind === "budget_corrupt")) throw err;
2018
+ }
2019
+ const state = { ...emptyState(id, now), max };
2020
+ try {
2021
+ writeState(lock, file, state);
2022
+ } catch (err) {
2023
+ if (err instanceof HgiError && err.details?.kind === "lock_compromised") throw err;
2024
+ throw budgetError("budget_write_failed", `Could not reset ${file}: ${err instanceof Error ? err.message : String(err)}`, "Remove the file yourself, then retry.", err);
2025
+ }
2026
+ return state;
2027
+ });
2028
+ pruneBudgets(path4.dirname(file), now);
2029
+ return next;
2030
+ }
1824
2031
 
1825
- // src/mcp/session.ts
2032
+ // src/commands/budget.ts
2033
+ function budgetStatus(state, activeMax) {
2034
+ const max = activeMax ?? state.max;
2035
+ return {
2036
+ budget_id: state.budget_id,
2037
+ spent: state.spent,
2038
+ max,
2039
+ remaining: max === null ? null : Math.max(0, max - state.spent),
2040
+ calls: state.calls,
2041
+ unknown_cost_calls: state.unknown_cost_calls
2042
+ };
2043
+ }
2044
+ function registerBudgetCommands(program) {
2045
+ const budget = program.command("budget").description("See or reset what this run has spent against --max-credits (local only; sends nothing)");
2046
+ budget.command("status").description("Print the current budget: {budget_id, spent, max, remaining, calls, unknown_cost_calls}").option("--max-credits <n>", "report against this cap (default: $HGI_MAX_CREDITS, else the last cap used)").option("-f, --format <format>", "json|jsonl|csv|yaml|table").option("--select <fields>", "keep only these comma-separated fields").option("--out <file>", "write to a new file instead of stdout").action(async (opts) => {
2047
+ preflightOutput({ format: opts.format, select: opts.select, out: opts.out });
2048
+ const max = resolveMaxCredits(opts.maxCredits);
2049
+ const state = readBudget(resolveBudgetId());
2050
+ await emit(budgetStatus(state, max), { format: opts.format, select: opts.select, out: opts.out });
2051
+ });
2052
+ budget.command("reset").description("Set this budget's spent, calls and unknown_cost_calls to 0, then print its status").option("-f, --format <format>", "json|jsonl|csv|yaml|table").action(async (opts) => {
2053
+ preflightOutput({ format: opts.format });
2054
+ const max = resolveMaxCredits(void 0);
2055
+ const state = await resetBudget(resolveBudgetId());
2056
+ await emit(budgetStatus(state, max), { format: opts.format });
2057
+ });
2058
+ }
2059
+
2060
+ // src/commands/invoke.ts
2061
+ import { Option } from "commander";
2062
+
2063
+ // src/mcp/cache.ts
2064
+ import fs6 from "fs";
2065
+ import path5 from "path";
2066
+ import { createHash as createHash3 } from "crypto";
2067
+ var TOOLS_CACHE_TTL_MS = 15 * 6e4;
2068
+ function toolsCachePath(base, orgSlug, userId) {
2069
+ const userHash = createHash3("sha256").update(userId).digest("hex").slice(0, 12);
2070
+ const org = orgSlug.replace(/[^a-z0-9_-]/gi, "_");
2071
+ return path5.join(cacheDir(), `tools-${hostSlug(base)}-${org}-${userHash}.json`);
2072
+ }
2073
+ function readToolsCache(file, now = Date.now()) {
2074
+ try {
2075
+ const parsed = JSON.parse(fs6.readFileSync(file, "utf8"));
2076
+ if (!Array.isArray(parsed.tools) || typeof parsed.fetched_at !== "number") return null;
2077
+ if (now - parsed.fetched_at > TOOLS_CACHE_TTL_MS) return null;
2078
+ return parsed;
2079
+ } catch {
2080
+ return null;
2081
+ }
2082
+ }
2083
+ function writeToolsCache(file, cache) {
2084
+ try {
2085
+ writePrivateFile(file, JSON.stringify(cache));
2086
+ } catch (err) {
2087
+ debug("could not write tools cache", err);
2088
+ }
2089
+ }
2090
+
2091
+ // src/mcp/session.ts
1826
2092
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
1827
2093
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
1828
2094
  import {
@@ -1834,9 +2100,22 @@ import {
1834
2100
 
1835
2101
  // src/mcp/transport-fetch.ts
1836
2102
  var RETRY_BUDGET_MS = 6e4;
2103
+ var RETRIES_BUDGET_MS = 6e5;
1837
2104
  var MAX_RATE_RETRIES = 3;
1838
2105
  var MAX_TRANSIENT_RETRIES = 2;
1839
2106
  var PRE_DISPATCH_CODES = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"]);
2107
+ function retryLimits(opts) {
2108
+ const configured = opts.retries !== void 0 || opts.retryBudgetMs !== void 0;
2109
+ const budgetMs = opts.retryBudgetMs ?? (opts.retries !== void 0 ? RETRIES_BUDGET_MS : RETRY_BUDGET_MS);
2110
+ if (opts.retries !== void 0) {
2111
+ return { rate: opts.retries, shed: opts.retries, transient: opts.retries, shared: false, budgetMs, configured };
2112
+ }
2113
+ return { rate: MAX_RATE_RETRIES, shed: MAX_RATE_RETRIES, transient: MAX_TRANSIENT_RETRIES, shared: true, budgetMs, configured };
2114
+ }
2115
+ function maxHttpSends(limits) {
2116
+ const retries = (limits.shared ? limits.rate : limits.rate + limits.shed) + limits.transient;
2117
+ return 2 * (1 + retries);
2118
+ }
1840
2119
  function rpcMethod(init) {
1841
2120
  const body = init?.body;
1842
2121
  if (typeof body !== "string") return void 0;
@@ -1862,6 +2141,7 @@ function createTransportFetch(authed, state, opts) {
1862
2141
  const wait = opts.sleepFn ?? sleep;
1863
2142
  const now = opts.now ?? Date.now;
1864
2143
  const random = opts.random ?? Math.random;
2144
+ const limits = retryLimits(opts);
1865
2145
  return async (url, rawInit) => {
1866
2146
  const init = rawInit ?? {};
1867
2147
  const method = (init.method ?? "GET").toUpperCase();
@@ -1870,34 +2150,43 @@ function createTransportFetch(authed, state, opts) {
1870
2150
  const signal = init.signal;
1871
2151
  const started = now();
1872
2152
  let rateAttempts = 0;
2153
+ let shedAttempts = 0;
1873
2154
  let transientAttempts = 0;
2155
+ let sends = 0;
2156
+ const remaining = () => limits.budgetMs - (now() - started);
2157
+ const transientFits = () => !limits.configured || 500 * (transientAttempts + 1) <= remaining();
2158
+ const retryWait = async (code, attempt, max, ms) => {
2159
+ opts.onRetry?.({ attempt, max, code, wait_seconds: Math.round(ms / 100) / 10 });
2160
+ await wait(ms, signal);
2161
+ };
1874
2162
  for (; ; ) {
1875
2163
  if (signal?.aborted) throw signal.reason;
1876
2164
  let res;
1877
2165
  try {
1878
- if (isToolsCall) state.toolsCallWritten = true;
2166
+ if (isToolsCall) {
2167
+ state.toolsCallWritten = true;
2168
+ state.toolsCallSends += 1;
2169
+ }
2170
+ sends += 1;
1879
2171
  res = await authed(String(url), init, { redirectKind: "mcp", context: "the MCP server", timeoutMs: opts.timeoutMs });
1880
2172
  } catch (err) {
1881
2173
  if (!(err instanceof HgiError) || err.code !== "server_unreachable") throw err;
1882
2174
  const cause = networkErrorCode(err.cause) ?? err.details?.cause;
2175
+ const preDispatch = Boolean(cause && PRE_DISPATCH_CODES.has(cause));
2176
+ if ((!isToolsCall || preDispatch) && transientAttempts < limits.transient && transientFits()) {
2177
+ transientAttempts += 1;
2178
+ await retryWait("not_established", transientAttempts, limits.transient, 500 * transientAttempts);
2179
+ continue;
2180
+ }
2181
+ const attempts = preDispatch || transientAttempts > 0 ? { attempts: sends } : {};
1883
2182
  if (isToolsCall) {
1884
- if (cause && PRE_DISPATCH_CODES.has(cause) && transientAttempts < MAX_TRANSIENT_RETRIES) {
1885
- transientAttempts += 1;
1886
- await wait(500 * transientAttempts, signal);
1887
- continue;
1888
- }
1889
2183
  throw new HgiError("server_unreachable", err.message, {
1890
2184
  hint: "The call may or may not have run. Check state before re-running.",
1891
- details: { ...err.details, outcome_unknown: true },
2185
+ details: { ...err.details, outcome_unknown: true, ...attempts },
1892
2186
  cause: err.cause
1893
2187
  });
1894
2188
  }
1895
- if (transientAttempts < MAX_TRANSIENT_RETRIES) {
1896
- transientAttempts += 1;
1897
- await wait(500 * transientAttempts, signal);
1898
- continue;
1899
- }
1900
- throw err;
2189
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, attempts: sends }, cause: err.cause });
1901
2190
  }
1902
2191
  const headerVersion = res.headers.get("x-mcp-version");
1903
2192
  if (headerVersion) state.mcpVersion = headerVersion;
@@ -1905,17 +2194,17 @@ function createTransportFetch(authed, state, opts) {
1905
2194
  if (res.status === 429) {
1906
2195
  const header = parseRetryAfter(res.headers.get("retry-after"));
1907
2196
  await res.body?.cancel().catch(() => void 0);
1908
- const delaySec = header ?? Math.min(2 ** (rateAttempts + 1), 30) + random();
1909
- const remaining = RETRY_BUDGET_MS - (now() - started);
1910
- if (rateAttempts >= MAX_RATE_RETRIES || delaySec * 1e3 > remaining) {
2197
+ const used = limits.shared ? rateAttempts + shedAttempts : rateAttempts;
2198
+ const delaySec = header ?? Math.min(2 ** (used + 1), 30) + random();
2199
+ if (used >= limits.rate || delaySec * 1e3 > remaining()) {
1911
2200
  throw new HgiError("rate_limited", "The organization is being rate limited by the server.", {
1912
2201
  hint: "Wait and retry; the limit is shared by every hgi process in your organization.",
1913
- details: { retry_after_seconds: header ?? Math.ceil(delaySec) }
2202
+ details: { retry_after_seconds: header ?? Math.ceil(delaySec), attempts: sends }
1914
2203
  });
1915
2204
  }
1916
2205
  rateAttempts += 1;
1917
2206
  debug("429, waiting", delaySec);
1918
- await wait(delaySec * 1e3 + random() * 250, signal);
2207
+ await retryWait("rate_limited", used + 1, limits.rate, delaySec * 1e3 + random() * 250);
1919
2208
  continue;
1920
2209
  }
1921
2210
  if (res.status === 403) {
@@ -1929,15 +2218,15 @@ function createTransportFetch(authed, state, opts) {
1929
2218
  const shed = await isShed(res);
1930
2219
  if (shed) {
1931
2220
  const header = parseRetryAfter(res.headers.get("retry-after")) ?? 1;
1932
- const remaining = RETRY_BUDGET_MS - (now() - started);
1933
- if (rateAttempts >= MAX_RATE_RETRIES || header * 1e3 > remaining) {
2221
+ const used = limits.shared ? rateAttempts + shedAttempts : shedAttempts;
2222
+ if (used >= limits.shed || header * 1e3 > remaining()) {
1934
2223
  throw new HgiError("server_unreachable", "The server is shedding load (503).", {
1935
2224
  hint: "Nothing was run; retrying is safe.",
1936
- details: { status: 503, outcome_unknown: false, retry_after_seconds: header }
2225
+ details: { status: 503, outcome_unknown: false, retry_after_seconds: header, attempts: sends }
1937
2226
  });
1938
2227
  }
1939
- rateAttempts += 1;
1940
- await wait(header * 1e3 + random() * 250, signal);
2228
+ shedAttempts += 1;
2229
+ await retryWait("load_shed", used + 1, limits.shed, header * 1e3 + random() * 250);
1941
2230
  continue;
1942
2231
  }
1943
2232
  if (isToolsCall) {
@@ -1946,14 +2235,14 @@ function createTransportFetch(authed, state, opts) {
1946
2235
  details: { status: res.status, outcome_unknown: true }
1947
2236
  });
1948
2237
  }
1949
- if ([502, 503, 504].includes(res.status) && transientAttempts < MAX_TRANSIENT_RETRIES) {
2238
+ if ([502, 503, 504].includes(res.status) && transientAttempts < limits.transient && transientFits()) {
1950
2239
  transientAttempts += 1;
1951
- await wait(500 * transientAttempts, signal);
2240
+ await retryWait("not_established", transientAttempts, limits.transient, 500 * transientAttempts);
1952
2241
  continue;
1953
2242
  }
1954
2243
  throw new HgiError("server_unreachable", `The server returned HTTP ${res.status}.`, {
1955
2244
  hint: "Retry in a moment.",
1956
- details: { status: res.status }
2245
+ details: { status: res.status, ...[502, 503, 504].includes(res.status) ? { attempts: sends } : {} }
1957
2246
  });
1958
2247
  }
1959
2248
  return res;
@@ -2020,20 +2309,25 @@ function mapMcpErrorInner(err, state) {
2020
2309
  }
2021
2310
  return toHgiError(err);
2022
2311
  }
2312
+ function sdkTimeoutMs(timeoutMs, retry = {}) {
2313
+ const limits = retryLimits(retry);
2314
+ const sends = maxHttpSends(limits);
2315
+ return timeoutMs * sends + limits.budgetMs + 250 * sends + 5e3;
2316
+ }
2023
2317
  async function openSession(ctx, opts) {
2024
- const state = { mcpVersion: null, toolsCallWritten: false };
2318
+ const state = { mcpVersion: null, toolsCallWritten: false, toolsCallSends: 0 };
2025
2319
  const transport = new StreamableHTTPClientTransport(new URL(mcpUrl(ctx.base)), {
2026
- fetch: createTransportFetch(ctx.authedFetch, state, { timeoutMs: opts.timeoutMs })
2320
+ fetch: createTransportFetch(ctx.authedFetch, state, { timeoutMs: opts.timeoutMs, ...opts.retry })
2027
2321
  });
2028
2322
  const client = new Client({ name: "hgi", version: VERSION }, { capabilities: {} });
2323
+ const requestOptions = { timeout: sdkTimeoutMs(opts.timeoutMs, opts.retry) };
2029
2324
  try {
2030
- await client.connect(transport);
2325
+ await client.connect(transport, requestOptions);
2031
2326
  } catch (err) {
2032
2327
  await transport.close().catch(() => void 0);
2033
2328
  throw mapMcpError(err, state);
2034
2329
  }
2035
2330
  const info = client.getServerVersion();
2036
- const requestOptions = { timeout: opts.timeoutMs };
2037
2331
  return {
2038
2332
  state,
2039
2333
  serverInfo: info ? { name: info.name, version: info.version } : null,
@@ -2171,6 +2465,293 @@ function registerToolsCommands(program) {
2171
2465
  });
2172
2466
  }
2173
2467
 
2468
+ // src/ledger.ts
2469
+ import fs7 from "fs";
2470
+ import path6 from "path";
2471
+ var LEDGER_FILE = "ledger.jsonl";
2472
+ var LEDGER_LOCK_RETRIES = { retries: 9, factor: 1.5, minTimeout: 70, maxTimeout: 700, randomize: true };
2473
+ function ledgerPath(env = process.env) {
2474
+ const raw = env.HGI_LEDGER;
2475
+ if (raw === "off") return null;
2476
+ if (raw) return guardLedgerOverride(raw);
2477
+ return path6.join(configDir(env), LEDGER_FILE);
2478
+ }
2479
+ function budgetId(env = process.env) {
2480
+ return env.HGI_BUDGET_ID ? env.HGI_BUDGET_ID : null;
2481
+ }
2482
+ var LABEL = /^[A-Za-z0-9._:/-]{1,64}$/;
2483
+ function parseLabel(raw) {
2484
+ if (raw === void 0) return null;
2485
+ if (LABEL.test(raw)) return raw;
2486
+ throw new HgiError("invalid_input", "--label must be 1 to 64 characters from A-Z a-z 0-9 . _ : / -", {
2487
+ hint: "For example: --label resolve or --label enrich/pass-2. Nothing was sent.",
2488
+ details: { reason: "bad_label" }
2489
+ });
2490
+ }
2491
+ var MCP_VERSION = /^[A-Za-z0-9._-]{1,32}$/;
2492
+ function sanitizeMcpVersion(value) {
2493
+ return typeof value === "string" && MCP_VERSION.test(value) && redact(value) === value ? value : null;
2494
+ }
2495
+ function redactOrNull(value) {
2496
+ return value === null ? null : redact(value);
2497
+ }
2498
+ function serializeRecord(r) {
2499
+ const line = {
2500
+ v: 1,
2501
+ ts: redact(r.ts),
2502
+ host: redact(r.host),
2503
+ verb: r.verb,
2504
+ tool: redact(r.tool),
2505
+ label: redactOrNull(r.label),
2506
+ credit_cost: typeof r.credit_cost === "number" && Number.isFinite(r.credit_cost) ? r.credit_cost : null,
2507
+ budget_id: redactOrNull(r.budget_id),
2508
+ mcp_version: sanitizeMcpVersion(r.mcp_version),
2509
+ status: r.status
2510
+ };
2511
+ return `${JSON.stringify(line)}
2512
+ `;
2513
+ }
2514
+ function errnoOf(err) {
2515
+ const code = err?.code;
2516
+ return typeof code === "string" ? code : void 0;
2517
+ }
2518
+ function reasonOf(err) {
2519
+ if (err instanceof HgiError) {
2520
+ const kind = err.details?.kind;
2521
+ if (kind === "lock_timeout" || kind === "lock_compromised") return kind;
2522
+ const reason = err.details?.reason;
2523
+ if (typeof reason === "string") return reason;
2524
+ return errnoOf(err.cause) ?? (typeof kind === "string" ? kind : "write_failed");
2525
+ }
2526
+ return errnoOf(err) ?? "write_failed";
2527
+ }
2528
+ function writeLine(file, buf, lock) {
2529
+ let fd;
2530
+ try {
2531
+ fd = fs7.openSync(
2532
+ file,
2533
+ fs7.constants.O_WRONLY | fs7.constants.O_APPEND | fs7.constants.O_CREAT | fs7.constants.O_NOFOLLOW | fs7.constants.O_NONBLOCK,
2534
+ 384
2535
+ );
2536
+ const st = fs7.fstatSync(fd);
2537
+ if (!st.isFile()) return "not_regular_file";
2538
+ if ((st.mode & 511) !== 384) {
2539
+ try {
2540
+ fs7.fchmodSync(fd, 384);
2541
+ } catch {
2542
+ return "mode";
2543
+ }
2544
+ }
2545
+ lock.assertHeld();
2546
+ const written = fs7.writeSync(fd, buf);
2547
+ return written === buf.length ? null : "short_write";
2548
+ } catch (err) {
2549
+ return errnoOf(err) === "ELOOP" ? "symlink" : reasonOf(err);
2550
+ } finally {
2551
+ if (fd !== void 0) {
2552
+ try {
2553
+ fs7.closeSync(fd);
2554
+ } catch {
2555
+ }
2556
+ }
2557
+ }
2558
+ }
2559
+ async function appendLedger(file, record) {
2560
+ try {
2561
+ const buf = Buffer.from(serializeRecord(record), "utf8");
2562
+ ensureDir(path6.dirname(file));
2563
+ let st = null;
2564
+ try {
2565
+ st = fs7.lstatSync(file);
2566
+ } catch {
2567
+ st = null;
2568
+ }
2569
+ if (st?.isSymbolicLink()) return "symlink";
2570
+ if (st && !st.isFile()) return "not_regular_file";
2571
+ return await withFileLock(file, { label: "ledger", retries: LEDGER_LOCK_RETRIES }, async (lock) => writeLine(file, buf, lock));
2572
+ } catch (err) {
2573
+ return reasonOf(err);
2574
+ }
2575
+ }
2576
+ function stderrIsJson() {
2577
+ return !process.stderr.isTTY || process.argv.includes("--json-errors");
2578
+ }
2579
+ async function recordCall(file, record) {
2580
+ if (file === null) return;
2581
+ const reason = await appendLedger(file, record);
2582
+ if (reason === null) return;
2583
+ const safe = reason.replace(/[^A-Za-z0-9_]/g, "_");
2584
+ process.stderr.write(
2585
+ stderrIsJson() ? `${JSON.stringify({ warning: "ledger_not_updated", reason: safe })}
2586
+ ` : `hgi: warning: credit ledger not updated: ${safe}
2587
+ `
2588
+ );
2589
+ }
2590
+ function ledgerUnsafe(reason, file) {
2591
+ return new HgiError("local_state_error", `Credit ledger path is unsafe (${reason}): ${file}`, {
2592
+ hint: "Remove or fix it yourself; hgi will not follow symlinks or read non-regular files. Deleting the ledger only resets local history.",
2593
+ details: { kind: "ledger_unsafe", reason }
2594
+ });
2595
+ }
2596
+ function readFailed(code, file, cause) {
2597
+ return new HgiError("local_state_error", `Cannot read the credit ledger ${file}: ${code}.`, {
2598
+ hint: "Check its permissions. Deleting the ledger only resets local history.",
2599
+ details: { kind: "read_failed", reason: code },
2600
+ cause
2601
+ });
2602
+ }
2603
+ var isStringOrNull = (v) => v === null || typeof v === "string";
2604
+ function parseLine(line) {
2605
+ let value;
2606
+ try {
2607
+ value = JSON.parse(line);
2608
+ } catch {
2609
+ return null;
2610
+ }
2611
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
2612
+ const r = value;
2613
+ const cost = r.credit_cost;
2614
+ const ok = r.v === 1 && typeof r.ts === "string" && Number.isFinite(Date.parse(r.ts)) && typeof r.host === "string" && (r.verb === "call" || r.verb === "run") && typeof r.tool === "string" && isStringOrNull(r.label) && (cost === null || typeof cost === "number" && Number.isFinite(cost)) && isStringOrNull(r.budget_id) && (r.mcp_version === null || sanitizeMcpVersion(r.mcp_version) !== null) && (r.status === "ok" || r.status === "tool_error");
2615
+ if (!ok) return null;
2616
+ return {
2617
+ v: 1,
2618
+ ts: r.ts,
2619
+ host: r.host,
2620
+ verb: r.verb,
2621
+ tool: r.tool,
2622
+ label: r.label,
2623
+ credit_cost: cost,
2624
+ budget_id: r.budget_id,
2625
+ mcp_version: r.mcp_version,
2626
+ status: r.status
2627
+ };
2628
+ }
2629
+ function readLedger(file) {
2630
+ let fd;
2631
+ try {
2632
+ fd = fs7.openSync(file, fs7.constants.O_RDONLY | fs7.constants.O_NOFOLLOW | fs7.constants.O_NONBLOCK);
2633
+ } catch (err) {
2634
+ const code = errnoOf(err) ?? "error";
2635
+ if (code === "ENOENT") return { status: "missing" };
2636
+ if (code === "ELOOP") throw ledgerUnsafe("symlink", file);
2637
+ throw readFailed(code, file, err);
2638
+ }
2639
+ let text;
2640
+ try {
2641
+ if (!fs7.fstatSync(fd).isFile()) throw ledgerUnsafe("not_regular_file", file);
2642
+ text = fs7.readFileSync(fd, "utf8");
2643
+ } catch (err) {
2644
+ if (err instanceof HgiError) throw err;
2645
+ throw readFailed(errnoOf(err) ?? "error", file, err);
2646
+ } finally {
2647
+ fs7.closeSync(fd);
2648
+ }
2649
+ const rows = [];
2650
+ let malformed = 0;
2651
+ for (const line of text.split("\n")) {
2652
+ if (line.trim() === "") continue;
2653
+ const row = parseLine(line);
2654
+ if (row) rows.push(row);
2655
+ else malformed += 1;
2656
+ }
2657
+ return { status: "ok", rows, malformed };
2658
+ }
2659
+ function badSince(raw) {
2660
+ return new HgiError("invalid_input", `--since "${raw}" is not a date, a datetime, "today" or a duration.`, {
2661
+ hint: "Use 2026-11-01, 2026-11-01T09:00 (local time unless a zone is given), today, 24h or 7d.",
2662
+ details: { reason: "bad_since" }
2663
+ });
2664
+ }
2665
+ var DURATION = /^(\d+)([hd])$/;
2666
+ var DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
2667
+ var DATETIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?$/;
2668
+ function validDate(y, m, d) {
2669
+ const probe = new Date(Date.UTC(y, m - 1, d));
2670
+ return probe.getUTCFullYear() === y && probe.getUTCMonth() === m - 1 && probe.getUTCDate() === d;
2671
+ }
2672
+ function parseSince(raw, now = Date.now()) {
2673
+ const dur = DURATION.exec(raw);
2674
+ if (dur) {
2675
+ const n = Number(dur[1]);
2676
+ if (!Number.isSafeInteger(n) || n < 1) throw badSince(raw);
2677
+ return now - n * (dur[2] === "h" ? 36e5 : 864e5);
2678
+ }
2679
+ if (raw === "today") {
2680
+ const d = new Date(now);
2681
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
2682
+ }
2683
+ const date = DATE.exec(raw);
2684
+ if (date) {
2685
+ const [y, m, d] = [Number(date[1]), Number(date[2]), Number(date[3])];
2686
+ if (!validDate(y, m, d)) throw badSince(raw);
2687
+ return new Date(y, m - 1, d).getTime();
2688
+ }
2689
+ const dt = DATETIME.exec(raw);
2690
+ if (dt) {
2691
+ const [y, mo, d, h, mi] = [Number(dt[1]), Number(dt[2]), Number(dt[3]), Number(dt[4]), Number(dt[5])];
2692
+ const s = dt[6] === void 0 ? 0 : Number(dt[6]);
2693
+ const ms = dt[7] === void 0 ? 0 : Number(dt[7].padEnd(3, "0"));
2694
+ if (!validDate(y, mo, d) || h > 23 || mi > 59 || s > 59) throw badSince(raw);
2695
+ const zone = dt[8];
2696
+ if (zone === void 0) return new Date(y, mo - 1, d, h, mi, s, ms).getTime();
2697
+ const utc = Date.UTC(y, mo - 1, d, h, mi, s, ms);
2698
+ if (zone === "Z") return utc;
2699
+ const [zh, zm] = [Number(zone.slice(1, 3)), Number(zone.slice(4, 6))];
2700
+ if (zh > 23 || zm > 59) throw badSince(raw);
2701
+ const offset = (zh * 60 + zm) * 6e4 * (zone.startsWith("-") ? -1 : 1);
2702
+ return utc - offset;
2703
+ }
2704
+ throw badSince(raw);
2705
+ }
2706
+ var BY_VALUES = ["tool", "label", "day", "call"];
2707
+ function parseBy(raw) {
2708
+ if (BY_VALUES.includes(raw)) return raw;
2709
+ throw new HgiError("invalid_input", `--by "${raw}" is not one of: ${BY_VALUES.join(", ")}.`, {
2710
+ details: { reason: "bad_by" }
2711
+ });
2712
+ }
2713
+ function filterRows(rows, host, sinceMs) {
2714
+ return rows.map((row) => ({ row, t: Date.parse(row.ts) })).filter(({ row, t }) => row.host === host && (sinceMs === null || t >= sinceMs)).sort((a, b) => a.t - b.t).map(({ row }) => row);
2715
+ }
2716
+ function localDay(ts) {
2717
+ const d = new Date(ts);
2718
+ const pad = (n) => String(n).padStart(2, "0");
2719
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
2720
+ }
2721
+ function compareKeys(a, b) {
2722
+ if (a === b) return 0;
2723
+ if (a === null) return 1;
2724
+ if (b === null) return -1;
2725
+ return a < b ? -1 : 1;
2726
+ }
2727
+ function summarize2(rows, by) {
2728
+ const groups = /* @__PURE__ */ new Map();
2729
+ for (const row of rows) {
2730
+ const key = by === "tool" ? row.tool : by === "label" ? row.label : localDay(row.ts);
2731
+ let g = groups.get(key);
2732
+ if (!g) {
2733
+ g = { key, calls: 0, credits: 0, zero_cost_calls: 0, unknown_cost_calls: 0 };
2734
+ groups.set(key, g);
2735
+ }
2736
+ g.calls += 1;
2737
+ if (row.credit_cost === null) g.unknown_cost_calls += 1;
2738
+ else {
2739
+ g.credits += row.credit_cost;
2740
+ if (row.credit_cost === 0) g.zero_cost_calls += 1;
2741
+ }
2742
+ }
2743
+ const list = [...groups.values()];
2744
+ if (by === "day") list.sort((a, b) => compareKeys(a.key, b.key));
2745
+ else list.sort((a, b) => b.credits - a.credits || compareKeys(a.key, b.key));
2746
+ return list.map((g) => ({
2747
+ [by]: g.key,
2748
+ calls: g.calls,
2749
+ credits: g.credits,
2750
+ zero_cost_calls: g.zero_cost_calls,
2751
+ unknown_cost_calls: g.unknown_cost_calls
2752
+ }));
2753
+ }
2754
+
2174
2755
  // src/mcp/result.ts
2175
2756
  var MAX_ERROR_TEXT = 2e3;
2176
2757
  function textOf(result) {
@@ -2195,17 +2776,44 @@ function creditCostOf(result) {
2195
2776
  const cost = result._meta?.creditCost;
2196
2777
  return typeof cost === "number" && Number.isFinite(cost) ? cost : null;
2197
2778
  }
2779
+ var REFUSALS = {
2780
+ credit_limit_exceeded: {
2781
+ code: "credit_limit_exceeded",
2782
+ hint: "Your organization has used its credit allowance. Contact your admin; retrying will not help."
2783
+ },
2784
+ user_credit_limit_exceeded: {
2785
+ code: "user_credit_limit_exceeded",
2786
+ hint: "Your personal credit budget is used up. Ask an admin to raise it, or wait for the next billing period; retrying will not help."
2787
+ },
2788
+ governance_unavailable: {
2789
+ code: "governance_unavailable",
2790
+ hint: "The server could not check your budget, so nothing ran. Retry shortly.",
2791
+ details: { retryable: true, outcome_unknown: false }
2792
+ },
2793
+ tool_not_enabled_for_team: {
2794
+ code: "tool_not_enabled_for_team",
2795
+ hint: "This tool is not enabled for your team. Ask an admin to enable it."
2796
+ },
2797
+ phoenix_account_required: {
2798
+ code: "phoenix_account_required",
2799
+ hint: "This identity has no Phoenix account. Sign up for one, or sign in with `hgi auth login` as an account that has one."
2800
+ }
2801
+ };
2802
+ function serverErrorCodeOf(result) {
2803
+ const code = result._meta?.errorCode;
2804
+ return typeof code === "string" ? code : void 0;
2805
+ }
2198
2806
  function interpretResult(result, toolName) {
2199
2807
  if (result.isError) {
2200
2808
  const text = redact(textOf(result)).slice(0, MAX_ERROR_TEXT) || "The tool reported an error.";
2201
- const code = result._meta?.errorCode;
2202
- if (code === "credit_limit_exceeded") {
2203
- throw new HgiError("credit_limit_exceeded", text, {
2204
- hint: "Your organization has used its credit allowance. Contact your admin; retrying will not help.",
2205
- details: { tool: toolName }
2206
- });
2809
+ const serverCode = serverErrorCodeOf(result);
2810
+ const details = { tool: toolName };
2811
+ if (serverCode !== void 0) details.server_error_code = serverCode;
2812
+ const refusal = serverCode !== void 0 && Object.hasOwn(REFUSALS, serverCode) ? REFUSALS[serverCode] : void 0;
2813
+ if (refusal) {
2814
+ throw new HgiError(refusal.code, text, { hint: refusal.hint, details: { ...details, ...refusal.details } });
2207
2815
  }
2208
- throw new HgiError("tool_error", text, { details: { tool: toolName } });
2816
+ throw new HgiError("tool_error", text, { details });
2209
2817
  }
2210
2818
  return { value: extractValue(result), creditCost: creditCostOf(result) };
2211
2819
  }
@@ -2241,7 +2849,949 @@ function assertValidInput(tool, input) {
2241
2849
  });
2242
2850
  }
2243
2851
 
2852
+ // src/batch/ids.ts
2853
+ function stripBom(text) {
2854
+ return text.charCodeAt(0) === 65279 ? text.slice(1) : text;
2855
+ }
2856
+ function parseIdLines(text) {
2857
+ const out = [];
2858
+ stripBom(text).split("\n").forEach((raw, i) => {
2859
+ const value = raw.trim();
2860
+ if (value === "" || value.startsWith("#")) return;
2861
+ out.push({ text: value, line: i + 1 });
2862
+ });
2863
+ return out;
2864
+ }
2865
+ function parseCsv(text) {
2866
+ const src = stripBom(text);
2867
+ const records = [];
2868
+ let record = [];
2869
+ let cell = "";
2870
+ let quoted = false;
2871
+ let atCellStart = true;
2872
+ for (let i = 0; i < src.length; i += 1) {
2873
+ const ch = src[i];
2874
+ if (quoted) {
2875
+ if (ch === '"' && src[i + 1] === '"') {
2876
+ cell += '"';
2877
+ i += 1;
2878
+ } else if (ch === '"') {
2879
+ quoted = false;
2880
+ } else {
2881
+ cell += ch;
2882
+ }
2883
+ continue;
2884
+ }
2885
+ if (ch === '"' && atCellStart) {
2886
+ quoted = true;
2887
+ atCellStart = false;
2888
+ } else if (ch === ",") {
2889
+ record.push(cell);
2890
+ cell = "";
2891
+ atCellStart = true;
2892
+ } else if (ch === "\n" || ch === "\r" && src[i + 1] === "\n") {
2893
+ if (ch === "\r") i += 1;
2894
+ record.push(cell);
2895
+ records.push(record);
2896
+ record = [];
2897
+ cell = "";
2898
+ atCellStart = true;
2899
+ } else {
2900
+ cell += ch;
2901
+ atCellStart = false;
2902
+ }
2903
+ }
2904
+ if (quoted) {
2905
+ throw new HgiError("invalid_input", "The --ids CSV file has a quoted field that is never closed.", {
2906
+ details: { reason: "bad_csv" }
2907
+ });
2908
+ }
2909
+ if (cell !== "" || record.length > 0) {
2910
+ record.push(cell);
2911
+ records.push(record);
2912
+ }
2913
+ return records;
2914
+ }
2915
+ function parseCsvColumn(text, column) {
2916
+ const [header, ...rows] = parseCsv(text);
2917
+ const names = (header ?? []).map((h) => h.trim());
2918
+ const index = names.indexOf(column.trim());
2919
+ if (index < 0) {
2920
+ throw new HgiError("invalid_input", `The --ids CSV file has no column "${column}".`, {
2921
+ hint: names.length ? `Its columns are: ${names.slice(0, 20).join(", ")}.` : "The file has no header row.",
2922
+ details: { reason: "unknown_column", column, columns: names.slice(0, 50) }
2923
+ });
2924
+ }
2925
+ const out = [];
2926
+ rows.forEach((row, i) => {
2927
+ const value = (row[index] ?? "").trim();
2928
+ if (value !== "") out.push({ text: value, line: i + 2 });
2929
+ });
2930
+ return out;
2931
+ }
2932
+ function classify(text) {
2933
+ return text.includes(".") ? "domain" : "id";
2934
+ }
2935
+ function normalizeId(text) {
2936
+ const lower = text.trim().toLowerCase();
2937
+ const stripped = lower.replace(/^0+/, "");
2938
+ return stripped === "" && lower !== "" ? "0" : stripped;
2939
+ }
2940
+ function normalizeDomain(text) {
2941
+ let s = text.trim().toLowerCase();
2942
+ s = s.replace(/^[a-z][a-z0-9+.-]*:\/\//, "");
2943
+ const cut = s.search(/[/?#]/);
2944
+ if (cut >= 0) s = s.slice(0, cut);
2945
+ if (s.startsWith("www.")) s = s.slice(4);
2946
+ return s;
2947
+ }
2948
+ function normalize(kind, text) {
2949
+ return kind === "id" ? normalizeId(text) : normalizeDomain(text);
2950
+ }
2951
+
2952
+ // src/mcp/schema-shape.ts
2953
+ function isRecord(value) {
2954
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2955
+ }
2956
+ function hasType(schema, type) {
2957
+ return schema.type === type || Array.isArray(schema.type) && schema.type.includes(type);
2958
+ }
2959
+ function isArrayOfObjects(schema) {
2960
+ if (!isRecord(schema) || !hasType(schema, "array")) return false;
2961
+ const items = schema.items;
2962
+ return isRecord(items) && (hasType(items, "object") || isRecord(items.properties));
2963
+ }
2964
+ function propertiesOf(schema) {
2965
+ return isRecord(schema) && isRecord(schema.properties) ? schema.properties : {};
2966
+ }
2967
+
2968
+ // src/batch/plan.ts
2969
+ var DEFAULT_BATCH_SIZE = 25;
2970
+ var FIELD_FOR = { id: "hg_ids", domain: "domains" };
2971
+ var ID_MATCH_KEYS = ["company_id", "requested_hg_id", "organization_id"];
2972
+ var DOMAIN_MATCH_KEY = "company_domain";
2973
+ function batchFields(tool) {
2974
+ const props = isRecord(tool.inputSchema.properties) ? tool.inputSchema.properties : {};
2975
+ const fields = {};
2976
+ for (const kind of ["id", "domain"]) {
2977
+ const name = FIELD_FOR[kind];
2978
+ const schema = props[name];
2979
+ if (!isRecord(schema) || !hasType(schema, "array")) continue;
2980
+ if (!("maxItems" in schema)) {
2981
+ fields[kind] = { field: name, max: DEFAULT_BATCH_SIZE };
2982
+ continue;
2983
+ }
2984
+ const declared = schema.maxItems;
2985
+ const usable = typeof declared === "number" && Number.isInteger(declared) && declared >= 1;
2986
+ fields[kind] = usable ? { field: name, max: declared } : { field: name, max: null, declaredMax: declared };
2987
+ }
2988
+ return fields;
2989
+ }
2990
+ function entriesKey(tool) {
2991
+ const candidates = Object.entries(propertiesOf(tool.outputSchema)).filter(([, schema]) => isArrayOfObjects(schema));
2992
+ return candidates.length === 1 ? candidates[0][0] : "companies";
2993
+ }
2994
+ function buildBatches(input, fields, batchSize) {
2995
+ const uniques = /* @__PURE__ */ new Map();
2996
+ const lines = [];
2997
+ input.forEach((line, position) => {
2998
+ const kind = classify(line.text);
2999
+ const field = fields[kind];
3000
+ if (!field) {
3001
+ const has = Object.values(fields).map((f) => f.field);
3002
+ throw new HgiError("invalid_input", `Line ${line.line} is ${kind === "domain" ? "a domain" : "an HG id"}, but this tool has no "${FIELD_FOR[kind]}" field.`, {
3003
+ hint: has.length ? `This tool takes: ${has.join(", ")}. Nothing was sent.` : "This tool takes neither hg_ids nor domains. Nothing was sent.",
3004
+ details: { reason: "unsupported_kind", kind, line: line.line, fields: has }
3005
+ });
3006
+ }
3007
+ const norm = normalize(kind, line.text);
3008
+ const key = `${kind}:${norm}`;
3009
+ let unique = uniques.get(key);
3010
+ if (!unique) {
3011
+ unique = { kind, text: line.text, norm, first: position };
3012
+ uniques.set(key, unique);
3013
+ }
3014
+ lines.push({ text: line.text, unique });
3015
+ });
3016
+ const chunks = [];
3017
+ for (const kind of ["id", "domain"]) {
3018
+ const field = fields[kind];
3019
+ const ofKind = [...uniques.values()].filter((u) => u.kind === kind);
3020
+ if (!field || ofKind.length === 0) continue;
3021
+ const max = usableMax(field);
3022
+ if (batchSize !== void 0 && batchSize > max) {
3023
+ throw new HgiError("invalid_input", `--batch-size ${batchSize} is above the tool's limit of ${max} for "${field.field}".`, {
3024
+ hint: "--batch-size can only lower the batch size. Nothing was sent.",
3025
+ details: { reason: "bad_batch_size", field: field.field, max }
3026
+ });
3027
+ }
3028
+ const size = batchSize ?? max;
3029
+ for (let i = 0; i < ofKind.length; i += size) {
3030
+ chunks.push({ kind, field: field.field, items: ofKind.slice(i, i + size) });
3031
+ }
3032
+ }
3033
+ const firstOf = (b) => b.items[0].first;
3034
+ chunks.sort((a, b) => firstOf(a) - firstOf(b));
3035
+ return { batches: chunks, lines };
3036
+ }
3037
+ function usableMax(field) {
3038
+ if (field.max !== null) return field.max;
3039
+ throw new HgiError("invalid_input", `The tool declares an unusable maxItems for "${field.field}", so --ids cannot batch it.`, {
3040
+ hint: "Nothing was sent. Call the tool with --input instead.",
3041
+ details: { reason: "unusable_max_items", field: field.field, max_items: field.declaredMax ?? null }
3042
+ });
3043
+ }
3044
+ function keyText(value) {
3045
+ if (typeof value === "string") return value;
3046
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
3047
+ return null;
3048
+ }
3049
+ function matchEntries(kind, value, key) {
3050
+ if (!isRecord(value) || !Array.isArray(value[key])) return null;
3051
+ const index = /* @__PURE__ */ new Map();
3052
+ for (const entry of value[key]) {
3053
+ if (!isRecord(entry)) continue;
3054
+ let raw = null;
3055
+ if (kind === "id") {
3056
+ for (const k of ID_MATCH_KEYS) {
3057
+ raw = keyText(entry[k]);
3058
+ if (raw !== null) break;
3059
+ }
3060
+ } else {
3061
+ raw = keyText(entry[DOMAIN_MATCH_KEY]);
3062
+ }
3063
+ if (raw === null) continue;
3064
+ const norm = normalize(kind, raw);
3065
+ if (!index.has(norm)) index.set(norm, entry);
3066
+ }
3067
+ return index;
3068
+ }
3069
+
3070
+ // src/commands/io.ts
3071
+ async function readStdin() {
3072
+ const chunks = [];
3073
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
3074
+ return Buffer.concat(chunks).toString("utf8");
3075
+ }
3076
+ function stderrWantsJson() {
3077
+ return !process.stderr.isTTY || process.argv.includes("--json-errors");
3078
+ }
3079
+ function reportCredit(cost) {
3080
+ process.stderr.write(stderrWantsJson() ? `${JSON.stringify({ credit_cost: cost })}
3081
+ ` : `credit_cost: ${cost ?? "unknown"}
3082
+ `);
3083
+ }
3084
+ function roundWait(ms) {
3085
+ return Math.round(ms / 100) / 10;
3086
+ }
3087
+ function reportRetry(e) {
3088
+ const event = { attempt: e.attempt, max: e.max, code: e.code, wait_seconds: e.wait_seconds };
3089
+ process.stderr.write(
3090
+ stderrWantsJson() ? `${JSON.stringify({ retry: event })}
3091
+ ` : `hgi: retry ${event.attempt}/${event.max}: ${event.code}, waiting ${event.wait_seconds}s
3092
+ `
3093
+ );
3094
+ }
3095
+
3096
+ // src/commands/retry.ts
3097
+ var GOVERNANCE_MAX_WAIT_SECONDS = 30;
3098
+ function isGovernanceUnavailable(result) {
3099
+ return result.isError === true && result._meta?.errorCode === "governance_unavailable";
3100
+ }
3101
+ async function sendWithRetry(session, name, args, opts) {
3102
+ const sleep2 = opts.sleep ?? sleep;
3103
+ const now = opts.now ?? Date.now;
3104
+ const random = opts.random ?? Math.random;
3105
+ const sendsBefore = session.state.toolsCallSends;
3106
+ const started = now();
3107
+ for (let attempt = 1; ; attempt += 1) {
3108
+ const result = await session.callTool(name, args);
3109
+ const budgetFailure = await opts.record(result);
3110
+ const outcome = () => ({ result, attempts: session.state.toolsCallSends - sendsBefore, budgetFailure });
3111
+ if (budgetFailure || attempt > opts.retries || !isGovernanceUnavailable(result)) return outcome();
3112
+ const waitMs = random() * Math.min(2 ** attempt, GOVERNANCE_MAX_WAIT_SECONDS) * 1e3;
3113
+ if (waitMs > opts.budgetMs - (now() - started)) return outcome();
3114
+ opts.report({ attempt, max: opts.retries, code: "governance_unavailable", wait_seconds: roundWait(waitMs) });
3115
+ await sleep2(waitMs);
3116
+ await opts.beforeResend?.();
3117
+ }
3118
+ }
3119
+
3120
+ // src/commands/batch.ts
3121
+ function usage(message, reason, hint, extra = {}) {
3122
+ return new HgiError("invalid_input", message, { hint, details: { reason, ...extra } });
3123
+ }
3124
+ function preflightBatchFlags(flags) {
3125
+ if (flags.ids === void 0) {
3126
+ if (flags.idsColumn !== void 0) throw usage("--ids-column needs --ids.", "ids_column_without_ids");
3127
+ if (flags.batchSize !== void 0) throw usage("--batch-size needs --ids.", "batch_size_without_ids");
3128
+ return void 0;
3129
+ }
3130
+ if (flags.ids !== "-" && !flags.ids.startsWith("@")) {
3131
+ throw usage("--ids takes @file or - (stdin).", "bad_ids_source", `Did you mean --ids @${flags.ids}?`);
3132
+ }
3133
+ if (flags.ids === "-" && flags.input === "-") {
3134
+ throw usage("--ids - and --input - cannot both read stdin.", "stdin_conflict", "Pass one of them as @file.");
3135
+ }
3136
+ if (flags.batchSize === void 0) return void 0;
3137
+ const raw = flags.batchSize.trim();
3138
+ const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
3139
+ if (!Number.isSafeInteger(n) || n < 1) {
3140
+ throw usage(`--batch-size must be a whole number of at least 1, not "${flags.batchSize}".`, "bad_batch_size");
3141
+ }
3142
+ return n;
3143
+ }
3144
+ async function readIds(flags, input) {
3145
+ for (const field of ["hg_ids", "domains"]) {
3146
+ if (field in input) {
3147
+ throw usage(`--ids builds "${field}" itself; remove it from --input.`, "ids_conflict", void 0, { field });
3148
+ }
3149
+ }
3150
+ const text = flags.ids === "-" ? await readStdin() : readInputFile(flags.ids.slice(1), protectedDirs(), {}, "--ids @file");
3151
+ const lines = flags.idsColumn !== void 0 ? parseCsvColumn(text, flags.idsColumn) : parseIdLines(text);
3152
+ if (lines.length === 0) {
3153
+ throw usage("--ids holds no HG ids or domains (only blank lines or # comments).", "no_ids");
3154
+ }
3155
+ return lines;
3156
+ }
3157
+ function argsFor(input, batch) {
3158
+ return { ...input, [batch.field]: batch.items.map((u) => u.text) };
3159
+ }
3160
+ function stdoutIsTty() {
3161
+ return Boolean(process.stdout.isTTY);
3162
+ }
3163
+ function render2(rows, format) {
3164
+ if (format === "jsonl") return rows.map((r) => `${JSON.stringify(r)}
3165
+ `).join("");
3166
+ return formatValue(rows, format, { pretty: stdoutIsTty() });
3167
+ }
3168
+ var Run = class {
3169
+ constructor(plan, format, streaming) {
3170
+ this.plan = plan;
3171
+ this.format = format;
3172
+ this.streaming = streaming;
3173
+ }
3174
+ plan;
3175
+ format;
3176
+ streaming;
3177
+ outcomes = /* @__PURE__ */ new Map();
3178
+ rows = [];
3179
+ rowErrors = 0;
3180
+ cursor = 0;
3181
+ callsMade = 0;
3182
+ /** `tools/call` re-sends across all batch calls (transport retries and governance re-sends). */
3183
+ retries = 0;
3184
+ callsWithoutCost = 0;
3185
+ creditSum = 0;
3186
+ failedBatches = 0;
3187
+ /** Emits every row, in input order, whose batch has returned. */
3188
+ async flush(select) {
3189
+ while (this.cursor < this.plan.lines.length) {
3190
+ const line = this.plan.lines[this.cursor];
3191
+ const outcome = this.outcomes.get(line.unique);
3192
+ if (!outcome) return;
3193
+ const row = "result" in outcome ? { input: line.text, result: applySelect(outcome.result, select) } : { input: line.text, error: outcome.error };
3194
+ if ("error" in row) this.rowErrors += 1;
3195
+ this.rows.push(row);
3196
+ this.cursor += 1;
3197
+ if (this.streaming) {
3198
+ const text = `${JSON.stringify(row)}
3199
+ `;
3200
+ await writeStream(process.stdout, stdoutIsTty() ? escapeJsonForTerminal(text) : text);
3201
+ }
3202
+ }
3203
+ }
3204
+ addCost(result) {
3205
+ const cost = result ? creditCostOf(result) : null;
3206
+ if (cost === null) this.callsWithoutCost += 1;
3207
+ else this.creditSum += cost;
3208
+ }
3209
+ creditCost() {
3210
+ return this.callsMade > this.callsWithoutCost ? this.creditSum : null;
3211
+ }
3212
+ failBatch(batch, error) {
3213
+ this.failedBatches += 1;
3214
+ for (const u of batch.items) this.outcomes.set(u, { error });
3215
+ }
3216
+ };
3217
+ function rowError(code, message) {
3218
+ return { code, message: redact(message) };
3219
+ }
3220
+ async function callBatch(run, session, tool, input, batch, key, opts) {
3221
+ const { budget } = opts;
3222
+ run.callsMade += 1;
3223
+ let result;
3224
+ let budgetFailure = null;
3225
+ const sendsBefore = session.state.toolsCallSends;
3226
+ const governanceRetries = opts.governance?.retries ?? 0;
3227
+ let attempts = 1;
3228
+ try {
3229
+ ({ result, budgetFailure, attempts } = await sendWithRetry(session, tool.name, argsFor(input, batch), {
3230
+ retries: governanceRetries,
3231
+ budgetMs: opts.governance?.budgetMs ?? 0,
3232
+ // Every attempt that came back: one ledger row, and its spend under a run cap.
3233
+ record: async (r) => {
3234
+ await opts.onResult?.(r);
3235
+ if (!budget) return null;
3236
+ try {
3237
+ await recordSpend(budget.id, budget.max, creditCostOf(r));
3238
+ return null;
3239
+ } catch (err) {
3240
+ return toHgiError(err);
3241
+ }
3242
+ },
3243
+ beforeResend: budget ? () => checkBatchBudget(budget, run) : void 0,
3244
+ report: reportRetry
3245
+ }));
3246
+ run.addCost(result);
3247
+ const outcome = interpretResult(result, tool.name);
3248
+ const index = matchEntries(batch.kind, outcome.value, key);
3249
+ if (!index) {
3250
+ run.failBatch(batch, rowError("unexpected_response", `The response has no "${key}" array to match inputs against.`));
3251
+ return budgetFailure;
3252
+ }
3253
+ for (const u of batch.items) {
3254
+ const entry = index.get(u.norm);
3255
+ run.outcomes.set(u, entry ? { result: entry } : { error: rowError("not_found", `No ${u.kind === "id" ? "company for this HG id" : "company for this domain"} in the response.`) });
3256
+ }
3257
+ } catch (raw) {
3258
+ if (!result) run.addCost(void 0);
3259
+ const err = toHgiError(raw);
3260
+ if (err.code !== "tool_error" || err.details?.outcome_unknown === true) {
3261
+ const retried = governanceRetries > 0 && err.code === "governance_unavailable";
3262
+ if (budgetFailure || retried) {
3263
+ const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
3264
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, ...extra }, cause: err });
3265
+ }
3266
+ throw err;
3267
+ }
3268
+ run.failBatch(batch, rowError(err.code, err.message));
3269
+ } finally {
3270
+ run.retries += Math.max(0, session.state.toolsCallSends - sendsBefore - 1);
3271
+ }
3272
+ return budgetFailure;
3273
+ }
3274
+ async function checkBatchBudget(budget, run) {
3275
+ try {
3276
+ await checkBudget(budget.id, budget.max);
3277
+ } catch (raw) {
3278
+ const err = toHgiError(raw);
3279
+ if (err.code !== "budget_exceeded") throw err;
3280
+ throw new HgiError(err.code, err.message, {
3281
+ hint: `${run.callsMade} batch call(s) already ran and their rows were printed; nothing more was sent. Keep those rows, raise --max-credits or run \`hgi budget reset\`, then resume from the rest.`,
3282
+ details: err.details,
3283
+ cause: err
3284
+ });
3285
+ }
3286
+ }
3287
+ function printMeta(run) {
3288
+ process.stderr.write(
3289
+ `${JSON.stringify({
3290
+ calls: run.callsMade,
3291
+ retries: run.retries,
3292
+ rows: run.rows.length,
3293
+ row_errors: run.rowErrors,
3294
+ credit_cost: run.creditCost(),
3295
+ calls_without_cost: run.callsWithoutCost
3296
+ })}
3297
+ `
3298
+ );
3299
+ }
3300
+ async function writeBuffered(run, opts) {
3301
+ if (run.streaming) return {};
3302
+ const text = render2(run.rows, run.format);
3303
+ if (!opts.out) {
3304
+ await emitText(text, run.format);
3305
+ return {};
3306
+ }
3307
+ try {
3308
+ await emitText(text, run.format, { out: opts.out });
3309
+ return {};
3310
+ } catch (err) {
3311
+ const outError = toHgiError(err);
3312
+ const note2 = `hgi: could not write ${opts.out} (${String(outError.details?.reason ?? outError.code)}); the rows were printed to stdout instead.`;
3313
+ process.stderr.write(`${sanitizeForTerminal(redact(note2))}
3314
+ `);
3315
+ try {
3316
+ await emitText(text, run.format);
3317
+ } catch {
3318
+ }
3319
+ return { outError };
3320
+ }
3321
+ }
3322
+ function withProgress(details, run, extra = {}) {
3323
+ return { ...details, rows_emitted: run.rows.length, calls_made: run.callsMade, ...extra };
3324
+ }
3325
+ async function runBatch(session, tool, input, lines, opts) {
3326
+ const plan = buildBatches(lines, batchFields(tool), opts.batchSize);
3327
+ if (opts.validate) {
3328
+ plan.batches.forEach((batch, i) => {
3329
+ try {
3330
+ assertValidInput(tool, argsFor(input, batch));
3331
+ } catch (err) {
3332
+ const e = toHgiError(err);
3333
+ throw new HgiError(e.code, `Batch ${i + 1} of ${plan.batches.length}: ${e.message}`, {
3334
+ hint: `${e.hint ?? ""} Nothing was sent.`.trim(),
3335
+ details: { ...e.details, batch: i + 1 }
3336
+ });
3337
+ }
3338
+ });
3339
+ }
3340
+ const format = opts.format ? parseFormat(opts.format) : "jsonl";
3341
+ const run = new Run(plan, format, format === "jsonl" && !opts.out);
3342
+ const key = entriesKey(tool);
3343
+ try {
3344
+ for (const [i, batch] of plan.batches.entries()) {
3345
+ if (opts.budget && i > 0) await checkBatchBudget(opts.budget, run);
3346
+ if (process.stderr.isTTY) process.stderr.write(`hgi: batch ${i + 1}/${plan.batches.length}
3347
+ `);
3348
+ const budgetFailure = await callBatch(run, session, tool, input, batch, key, opts);
3349
+ await run.flush(opts.select);
3350
+ if (budgetFailure) {
3351
+ throw new HgiError("local_state_error", `The batch call ran, but ${budgetFailure.message.replace(/^Could not/, "hgi could not")}`, {
3352
+ hint: "Every call so far already ran and was billed, and its rows were printed. Do NOT re-run them. Check the budget with `hgi budget status`.",
3353
+ details: { kind: "budget_write_failed", tool_ran: true },
3354
+ cause: budgetFailure
3355
+ });
3356
+ }
3357
+ }
3358
+ } catch (raw) {
3359
+ const err = toHgiError(raw);
3360
+ let outFailed = false;
3361
+ try {
3362
+ outFailed = (await writeBuffered(run, opts)).outError !== void 0;
3363
+ } catch {
3364
+ }
3365
+ reportCredit(run.creditCost());
3366
+ if (opts.meta) printMeta(run);
3367
+ throw new HgiError(err.code, err.message, {
3368
+ hint: err.hint,
3369
+ details: withProgress(err.details, run, outFailed ? { out_write_failed: true } : {}),
3370
+ cause: err
3371
+ });
3372
+ }
3373
+ let outError;
3374
+ try {
3375
+ ({ outError } = await writeBuffered(run, opts));
3376
+ } finally {
3377
+ reportCredit(run.creditCost());
3378
+ if (opts.meta) printMeta(run);
3379
+ }
3380
+ if (outError) {
3381
+ throw new HgiError("local_state_error", `The batch ran, but its rows could not be written to ${opts.out}: ${outError.message}`, {
3382
+ hint: "Every call already ran and was billed; the rows were printed to stdout instead. Do NOT re-run it.",
3383
+ details: { kind: "write_failed", reason: outError.details?.reason ?? outError.code, tool_ran: true, ...withProgress(void 0, run) },
3384
+ cause: outError
3385
+ });
3386
+ }
3387
+ if (run.failedBatches > 0) {
3388
+ throw new HgiError("tool_error", `${run.failedBatches} of ${plan.batches.length} batch calls failed; their rows carry the error.`, {
3389
+ hint: "Every other row was printed. Re-run only the inputs whose rows have an error.",
3390
+ details: withProgress({ failed_batches: run.failedBatches }, run)
3391
+ });
3392
+ }
3393
+ }
3394
+
3395
+ // src/mcp/paging.ts
3396
+ var NAMED_TOTALS = ["total", "total_count", "totalCount"];
3397
+ var PAGE_SIZE_KEYS = ["limit", "max_results"];
3398
+ function isNumeric(schema) {
3399
+ return isRecord(schema) && (hasType(schema, "integer") || hasType(schema, "number"));
3400
+ }
3401
+ function isPositiveInt(value) {
3402
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
3403
+ }
3404
+ function totalKeyOf(props, rowsKey) {
3405
+ for (const key of NAMED_TOTALS) {
3406
+ if (Object.hasOwn(props, key) && isNumeric(props[key])) return key;
3407
+ }
3408
+ const candidates = Object.keys(props).filter(
3409
+ (key) => key.startsWith("total_") && isNumeric(props[key]) && key.split("_").includes(rowsKey)
3410
+ );
3411
+ return candidates.length === 1 ? candidates[0] : void 0;
3412
+ }
3413
+ function pageObjectSpec(schema) {
3414
+ const props = propertiesOf(schema);
3415
+ const arrays = Object.keys(props).filter((key) => isArrayOfObjects(props[key]));
3416
+ if (arrays.length !== 1) return null;
3417
+ const rowsKey = arrays[0];
3418
+ const hasMoreKey = Object.hasOwn(props, "has_more") ? "has_more" : Object.hasOwn(props, "hasMore") ? "hasMore" : void 0;
3419
+ const totalKey = totalKeyOf(props, rowsKey);
3420
+ if (hasMoreKey === void 0 && totalKey === void 0) return null;
3421
+ return { rowsKey, ...hasMoreKey ? { hasMoreKey } : {}, ...totalKey ? { totalKey } : {} };
3422
+ }
3423
+ function pageSizeOfSchema(inputProps) {
3424
+ const declared = PAGE_SIZE_KEYS.filter((key2) => Object.hasOwn(inputProps, key2));
3425
+ if (declared.length !== 1) return {};
3426
+ const key = declared[0];
3427
+ const schema = inputProps[key];
3428
+ const fallback = isRecord(schema) ? schema.default : void 0;
3429
+ return { pageSizeKey: key, ...isPositiveInt(fallback) ? { pageSizeDefault: fallback } : {} };
3430
+ }
3431
+ function pagingSpec(tool) {
3432
+ const inputProps = propertiesOf(tool.inputSchema);
3433
+ const offset = inputProps.offset;
3434
+ if (!isRecord(offset) || !hasType(offset, "integer")) return null;
3435
+ if (!isRecord(tool.outputSchema)) return null;
3436
+ const size = pageSizeOfSchema(inputProps);
3437
+ const top = pageObjectSpec(tool.outputSchema);
3438
+ if (top) return { kind: "top", ...top, ...size };
3439
+ const outputProps = propertiesOf(tool.outputSchema);
3440
+ const itemSpecs = Object.keys(outputProps).filter((key) => isArrayOfObjects(outputProps[key])).map((key) => ({ key, spec: pageObjectSpec(outputProps[key].items) })).filter((c) => c.spec !== null);
3441
+ if (itemSpecs.length !== 1) return null;
3442
+ const only = itemSpecs[0];
3443
+ return { kind: "items", itemsKey: only.key, ...only.spec, ...size };
3444
+ }
3445
+ function pageSizeOf(spec, input) {
3446
+ if (spec.pageSizeKey === void 0) return void 0;
3447
+ const sent = input[spec.pageSizeKey];
3448
+ if (isPositiveInt(sent)) return sent;
3449
+ return spec.pageSizeDefault;
3450
+ }
3451
+ function stopReason(state, pageSize, maxPages) {
3452
+ if (state.hasMore === false) return "done";
3453
+ if (state.pageRows === 0) return "done";
3454
+ if (pageSize !== void 0 && state.pageRows < pageSize) return "done";
3455
+ if (typeof state.total === "number" && Number.isFinite(state.total) && state.collected >= state.total) return "done";
3456
+ if (state.pages >= maxPages) return "max_pages";
3457
+ return null;
3458
+ }
3459
+
3460
+ // src/commands/paging.ts
3461
+ var DEFAULT_MAX_PAGES = 10;
3462
+ function usage2(message, reason, extra = {}) {
3463
+ return new HgiError("invalid_input", message, { hint: "Nothing was sent.", details: { reason, ...extra } });
3464
+ }
3465
+ function preflightPaging(flags, input) {
3466
+ if (!flags.allPages) {
3467
+ if (flags.maxPages !== void 0) throw usage2("--max-pages needs --all-pages.", "max_pages_without_all_pages");
3468
+ return null;
3469
+ }
3470
+ let maxPages = DEFAULT_MAX_PAGES;
3471
+ if (flags.maxPages !== void 0) {
3472
+ const raw = flags.maxPages.trim();
3473
+ const n = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
3474
+ if (!Number.isSafeInteger(n) || n < 1) throw usage2(`--max-pages must be a whole number of at least 1, not "${flags.maxPages}".`, "bad_max_pages");
3475
+ maxPages = n;
3476
+ }
3477
+ if (flags.ids !== void 0) throw usage2("--all-pages cannot be combined with --ids yet.", "all_pages_with_ids");
3478
+ if (Object.hasOwn(input, "offset")) throw usage2('--all-pages sets "offset" itself; remove it from --input.', "offset_with_all_pages");
3479
+ return maxPages;
3480
+ }
3481
+ function assertPageable(tool) {
3482
+ const spec = pagingSpec(tool);
3483
+ if (spec) return spec;
3484
+ throw new HgiError("invalid_input", `${tool.name} cannot be paged safely with --all-pages.`, {
3485
+ hint: 'Its schema has no integer "offset" input, or its output has no single rows array with has_more or a total. Nothing was sent. Page it yourself with --input.',
3486
+ details: { reason: "not_pageable", tool: tool.name }
3487
+ });
3488
+ }
3489
+ var StopPaging = class extends Error {
3490
+ constructor(error) {
3491
+ super(error.message);
3492
+ this.error = error;
3493
+ }
3494
+ error;
3495
+ /** The merged result up to the stop, set by the loop that caught it. */
3496
+ merged;
3497
+ };
3498
+ function unexpected(tool, what) {
3499
+ return new HgiError("tool_error", `A later page of ${tool.name} came back without ${what}; paging stopped.`, {
3500
+ details: { reason: "unexpected_response", tool: tool.name }
3501
+ });
3502
+ }
3503
+ var Pager = class {
3504
+ constructor(ctx) {
3505
+ this.ctx = ctx;
3506
+ this.pageSize = pageSizeOf(ctx.spec, ctx.input);
3507
+ }
3508
+ ctx;
3509
+ acc = { callsMade: 0, retries: 0, callsWithoutCost: 0, creditSum: 0 };
3510
+ pageSize;
3511
+ /**
3512
+ * Sends one page. Page 1 was checked against the run cap before the session opened. A page whose spend could
3513
+ * not be recorded is returned with `budgetFailure`, so its rows are kept before paging stops.
3514
+ */
3515
+ async fetch(args, first) {
3516
+ const { session, tool, budget } = this.ctx;
3517
+ if (!first && budget) await checkBudget(budget.id, budget.max);
3518
+ if (!first && this.ctx.validate) assertValidInput(tool, args);
3519
+ this.acc.callsMade += 1;
3520
+ const sendsBefore = session.state.toolsCallSends;
3521
+ const governanceRetries = this.ctx.governance?.retries ?? 0;
3522
+ let sent;
3523
+ try {
3524
+ sent = await sendWithRetry(session, tool.name, args, {
3525
+ retries: governanceRetries,
3526
+ budgetMs: this.ctx.governance?.budgetMs ?? 0,
3527
+ // Every attempt that came back: one ledger row, and its spend under a run cap.
3528
+ record: async (r) => {
3529
+ await this.ctx.onResult?.(r);
3530
+ if (!budget) return null;
3531
+ try {
3532
+ await recordSpend(budget.id, budget.max, creditCostOf(r));
3533
+ return null;
3534
+ } catch (err) {
3535
+ return toHgiError(err);
3536
+ }
3537
+ },
3538
+ beforeResend: budget ? async () => void await checkBudget(budget.id, budget.max) : void 0,
3539
+ report: reportRetry
3540
+ });
3541
+ } catch (err) {
3542
+ this.acc.callsWithoutCost += 1;
3543
+ throw err;
3544
+ } finally {
3545
+ this.acc.retries += Math.max(0, session.state.toolsCallSends - sendsBefore - 1);
3546
+ }
3547
+ const { result, attempts, budgetFailure } = sent;
3548
+ const cost = creditCostOf(result);
3549
+ if (cost === null) this.acc.callsWithoutCost += 1;
3550
+ else this.acc.creditSum += cost;
3551
+ try {
3552
+ return { value: interpretResult(result, tool.name).value, budgetFailure };
3553
+ } catch (err) {
3554
+ const retried = governanceRetries > 0 && err instanceof HgiError && err.code === "governance_unavailable";
3555
+ if ((budgetFailure || retried) && err instanceof HgiError) {
3556
+ const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
3557
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, ...extra }, cause: err });
3558
+ }
3559
+ throw err;
3560
+ }
3561
+ }
3562
+ /** A follow-up page: any failure stops paging. */
3563
+ async fetchLater(args) {
3564
+ try {
3565
+ return await this.fetch(args, false);
3566
+ } catch (err) {
3567
+ throw new StopPaging(toHgiError(err));
3568
+ }
3569
+ }
3570
+ track(entry) {
3571
+ const rows = entry[this.ctx.spec.rowsKey];
3572
+ const t = { entry, rows: Array.isArray(rows) ? [...rows] : null, pages: 0, done: false };
3573
+ this.settle(t, Array.isArray(rows) ? rows.length : 0);
3574
+ return t;
3575
+ }
3576
+ /** Applies the stop rule after a page with `pageRows` rows. */
3577
+ settle(t, pageRows) {
3578
+ t.pages += 1;
3579
+ const { hasMoreKey, totalKey } = this.ctx.spec;
3580
+ const reason = stopReason(
3581
+ {
3582
+ pageRows,
3583
+ collected: t.rows?.length ?? 0,
3584
+ pages: t.pages,
3585
+ hasMore: hasMoreKey ? t.entry[hasMoreKey] : void 0,
3586
+ total: totalKey ? t.entry[totalKey] : void 0
3587
+ },
3588
+ this.pageSize,
3589
+ this.ctx.maxPages
3590
+ );
3591
+ if (reason === null) return;
3592
+ t.done = true;
3593
+ if (reason === "max_pages") t.reason = "max_pages";
3594
+ }
3595
+ /** Adds a follow-up page object's rows to its tracker. */
3596
+ append(t, entry) {
3597
+ const rows = entry[this.ctx.spec.rowsKey];
3598
+ if (!Array.isArray(rows)) throw new StopPaging(unexpected(this.ctx.tool, `a "${this.ctx.spec.rowsKey}" array`));
3599
+ t.entry = entry;
3600
+ t.rows = [...t.rows ?? [], ...rows];
3601
+ this.settle(t, rows.length);
3602
+ }
3603
+ merged(t) {
3604
+ return {
3605
+ ...t.entry,
3606
+ ...t.rows === null ? {} : { [this.ctx.spec.rowsKey]: t.rows },
3607
+ pages_fetched: t.pages,
3608
+ ...t.reason === void 0 ? {} : { truncated: true, truncated_reason: t.reason }
3609
+ };
3610
+ }
3611
+ creditCost() {
3612
+ return this.acc.callsMade > this.acc.callsWithoutCost ? this.acc.creditSum : null;
3613
+ }
3614
+ };
3615
+ function companyInputs(input) {
3616
+ const out = [];
3617
+ for (const [field, kind] of [["hg_ids", "id"], ["domains", "domain"]]) {
3618
+ const values = input[field];
3619
+ if (!Array.isArray(values)) continue;
3620
+ for (const text of values) {
3621
+ if (typeof text === "string") out.push({ field, kind, text, norm: kind === "id" ? normalizeId(text) : normalizeDomain(text) });
3622
+ }
3623
+ }
3624
+ return out;
3625
+ }
3626
+ function entryKey(entry, kind) {
3627
+ if (kind === "domain") {
3628
+ const raw = keyText(entry[DOMAIN_MATCH_KEY]);
3629
+ return raw === null ? null : normalizeDomain(raw);
3630
+ }
3631
+ for (const key of ID_MATCH_KEYS) {
3632
+ const raw = keyText(entry[key]);
3633
+ if (raw !== null) return normalizeId(raw);
3634
+ }
3635
+ return null;
3636
+ }
3637
+ function matches(entry, input) {
3638
+ return entryKey(entry, input.kind) === input.norm;
3639
+ }
3640
+ function withoutCompanies(input) {
3641
+ const rest = { ...input };
3642
+ delete rest.hg_ids;
3643
+ delete rest.domains;
3644
+ return rest;
3645
+ }
3646
+ function planFollowUps(trackers, input) {
3647
+ const live = trackers.filter((t) => t !== null);
3648
+ const inputs = companyInputs(input);
3649
+ if (inputs.length < 2) {
3650
+ const named = inputs[0];
3651
+ for (const t of live) {
3652
+ if (t.done) continue;
3653
+ if (trackers.length === 1 && (named === void 0 || matches(t.entry, named))) {
3654
+ t.follow = "same";
3655
+ if (named) t.expect = { kind: named.kind, norm: named.norm };
3656
+ } else {
3657
+ Object.assign(t, { done: true, reason: "unmatched" });
3658
+ }
3659
+ }
3660
+ return;
3661
+ }
3662
+ const matchedBy = /* @__PURE__ */ new Map();
3663
+ const candidates = live.map((t) => inputs.map((inp, i) => matches(t.entry, inp) ? i : -1).filter((i) => i >= 0));
3664
+ for (const list of candidates) for (const i of list) matchedBy.set(i, (matchedBy.get(i) ?? 0) + 1);
3665
+ live.forEach((t, k) => {
3666
+ if (t.done) return;
3667
+ const list = candidates[k];
3668
+ const only = list.length === 1 ? list[0] : -1;
3669
+ if (only >= 0 && matchedBy.get(only) === 1) {
3670
+ const inp = inputs[only];
3671
+ t.follow = { field: inp.field, text: inp.text, kind: inp.kind, norm: inp.norm };
3672
+ } else {
3673
+ Object.assign(t, { done: true, reason: "unmatched" });
3674
+ }
3675
+ });
3676
+ }
3677
+ async function pageTop(p, ctx, first) {
3678
+ if (!isRecord(first)) return first;
3679
+ const t = p.track(first);
3680
+ try {
3681
+ while (!t.done) {
3682
+ const page = await p.fetchLater({ ...ctx.input, offset: t.rows?.length ?? 0 });
3683
+ if (!isRecord(page.value)) throw new StopPaging(unexpected(ctx.tool, "a result object"));
3684
+ p.append(t, page.value);
3685
+ if (page.budgetFailure) throw new StopPaging(page.budgetFailure);
3686
+ }
3687
+ } catch (err) {
3688
+ if (!(err instanceof StopPaging)) throw err;
3689
+ if (!t.done) Object.assign(t, { done: true, reason: err.error.code });
3690
+ err.merged = p.merged(t);
3691
+ throw err;
3692
+ }
3693
+ return p.merged(t);
3694
+ }
3695
+ async function pageItems(p, ctx, first) {
3696
+ const itemsKey = ctx.spec.itemsKey;
3697
+ if (!isRecord(first) || !Array.isArray(first[itemsKey])) return first;
3698
+ const entries = first[itemsKey];
3699
+ const trackers = entries.map((e) => isRecord(e) ? p.track(e) : null);
3700
+ planFollowUps(trackers, ctx.input);
3701
+ const merge = () => ({ ...first, [itemsKey]: entries.map((e, i) => trackers[i] ? p.merged(trackers[i]) : e) });
3702
+ try {
3703
+ for (const t of trackers) {
3704
+ while (t && !t.done) {
3705
+ const follow = t.follow;
3706
+ const args = follow === "same" ? { ...ctx.input, offset: t.rows?.length ?? 0 } : { ...withoutCompanies(ctx.input), [follow.field]: [follow.text], offset: t.rows?.length ?? 0 };
3707
+ const page = await p.fetchLater(args);
3708
+ if (!isRecord(page.value) || !Array.isArray(page.value[itemsKey])) {
3709
+ throw new StopPaging(unexpected(ctx.tool, `a "${itemsKey}" array`));
3710
+ }
3711
+ const list = page.value[itemsKey];
3712
+ const only = list.length === 1 && isRecord(list[0]) ? list[0] : null;
3713
+ const want = follow === "same" ? t.expect : follow;
3714
+ if (only === null || want !== void 0 && !matches(only, want)) {
3715
+ Object.assign(t, { done: true, reason: "unmatched" });
3716
+ } else {
3717
+ p.append(t, only);
3718
+ }
3719
+ if (page.budgetFailure) throw new StopPaging(page.budgetFailure);
3720
+ }
3721
+ }
3722
+ } catch (err) {
3723
+ if (!(err instanceof StopPaging)) throw err;
3724
+ for (const t of trackers) if (t && !t.done) Object.assign(t, { done: true, reason: err.error.code });
3725
+ err.merged = merge();
3726
+ throw err;
3727
+ }
3728
+ return merge();
3729
+ }
3730
+ async function runAllPages(ctx) {
3731
+ const p = new Pager(ctx);
3732
+ const first = await p.fetch(ctx.input, true);
3733
+ const outcome = (value, failure) => ({
3734
+ value,
3735
+ callsMade: p.acc.callsMade,
3736
+ retries: p.acc.retries,
3737
+ callsWithoutCost: p.acc.callsWithoutCost,
3738
+ creditCost: p.creditCost(),
3739
+ ...failure ? { failure } : {}
3740
+ });
3741
+ if (first.budgetFailure) {
3742
+ return { ...outcome(first.value, first.budgetFailure), pageOneBudgetFailure: true };
3743
+ }
3744
+ try {
3745
+ return outcome(ctx.spec.kind === "top" ? await pageTop(p, ctx, first.value) : await pageItems(p, ctx, first.value));
3746
+ } catch (err) {
3747
+ if (err instanceof StopPaging) return outcome(err.merged, err.error);
3748
+ throw err;
3749
+ }
3750
+ }
3751
+
3752
+ // src/commands/retry-options.ts
3753
+ var MAX_RETRIES = 20;
3754
+ var MAX_RETRY_BUDGET_SECONDS = 3600;
3755
+ function parseRetries(raw, source) {
3756
+ const trimmed = raw.trim();
3757
+ const value = /^\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN;
3758
+ if (!Number.isSafeInteger(value) || value > MAX_RETRIES) {
3759
+ throw new HgiError("invalid_input", `${source} must be a whole number from 0 to ${MAX_RETRIES}.`, {
3760
+ hint: "For example --retries 6. 0 turns every retry off.",
3761
+ details: { reason: "bad_retries" }
3762
+ });
3763
+ }
3764
+ return value;
3765
+ }
3766
+ function parseRetryBudget(raw, source) {
3767
+ const trimmed = raw.trim();
3768
+ const seconds = trimmed === "" ? Number.NaN : Number(trimmed);
3769
+ if (!Number.isFinite(seconds) || seconds <= 0 || seconds > MAX_RETRY_BUDGET_SECONDS) {
3770
+ throw new HgiError("invalid_input", `${source} must be a positive number of seconds, at most ${MAX_RETRY_BUDGET_SECONDS}.`, {
3771
+ hint: "For example --retry-budget 600.",
3772
+ details: { reason: "bad_retry_budget" }
3773
+ });
3774
+ }
3775
+ return seconds * 1e3;
3776
+ }
3777
+ function resolveRetryOptions(flags, env = process.env) {
3778
+ let retries = null;
3779
+ if (flags.retries !== void 0) retries = parseRetries(flags.retries, "--retries");
3780
+ else if (env.HGI_RETRIES) retries = parseRetries(env.HGI_RETRIES, "HGI_RETRIES");
3781
+ let retryBudgetMs = null;
3782
+ if (flags.retryBudget !== void 0) retryBudgetMs = parseRetryBudget(flags.retryBudget, "--retry-budget");
3783
+ else if (env.HGI_RETRY_BUDGET) retryBudgetMs = parseRetryBudget(env.HGI_RETRY_BUDGET, "HGI_RETRY_BUDGET");
3784
+ return { retries, retryBudgetMs };
3785
+ }
3786
+
2244
3787
  // src/commands/invoke.ts
3788
+ function transportRetryOptions(r) {
3789
+ return {
3790
+ ...r.retries !== null ? { retries: r.retries } : {},
3791
+ ...r.retryBudgetMs !== null ? { retryBudgetMs: r.retryBudgetMs } : {},
3792
+ onRetry: reportRetry
3793
+ };
3794
+ }
2245
3795
  function parseTimeoutMs(raw) {
2246
3796
  const seconds = Number(raw);
2247
3797
  if (!Number.isFinite(seconds) || seconds <= 0) {
@@ -2251,11 +3801,6 @@ function parseTimeoutMs(raw) {
2251
3801
  }
2252
3802
  return seconds * 1e3;
2253
3803
  }
2254
- async function readStdin() {
2255
- const chunks = [];
2256
- for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
2257
- return Buffer.concat(chunks).toString("utf8");
2258
- }
2259
3804
  async function readInput(raw) {
2260
3805
  if (raw === void 0) return {};
2261
3806
  let text = raw;
@@ -2279,12 +3824,6 @@ function suggest(name, tools) {
2279
3824
  const needle = name.toLowerCase();
2280
3825
  return tools.map((t) => t.name).filter((n) => n.toLowerCase().includes(needle) || needle.includes(n.toLowerCase())).slice(0, 5);
2281
3826
  }
2282
- function reportCredit(cost) {
2283
- const json = !process.stderr.isTTY || process.argv.includes("--json-errors");
2284
- process.stderr.write(json ? `${JSON.stringify({ credit_cost: cost })}
2285
- ` : `credit_cost: ${cost ?? "unknown"}
2286
- `);
2287
- }
2288
3827
  function assertVerb(requested, tool) {
2289
3828
  const expected = verbFor(tool);
2290
3829
  if (requested === expected) return;
@@ -2294,13 +3833,114 @@ function assertVerb(requested, tool) {
2294
3833
  details: { tool: tool.name, expected_verb: expected, requested_verb: requested }
2295
3834
  });
2296
3835
  }
3836
+ async function failAfterBudgetWrite(cause, value, opts, creditCost, extraDetails = {}) {
3837
+ try {
3838
+ await emit(value, { format: opts.format });
3839
+ } catch {
3840
+ } finally {
3841
+ reportCredit(creditCost);
3842
+ }
3843
+ throw new HgiError("local_state_error", `The tool ran, but ${cause.message.replace(/^Could not/, "hgi could not")}`, {
3844
+ hint: "The tool already ran and was billed; its result was printed to stdout. Do NOT re-run it. Check the budget with `hgi budget status`.",
3845
+ details: { kind: "budget_write_failed", tool_ran: true, ...extraDetails },
3846
+ cause
3847
+ });
3848
+ }
3849
+ async function emitResult(value, verb, opts, creditCost) {
3850
+ try {
3851
+ await emit(value, { format: opts.format, out: opts.out, force: opts.force, allowForce: verb === "run" });
3852
+ } catch (err) {
3853
+ if (!opts.out) throw err;
3854
+ const cause = toHgiError(err);
3855
+ try {
3856
+ await emit(value, { format: opts.format });
3857
+ } catch {
3858
+ }
3859
+ throw new HgiError("local_state_error", `The tool ran, but its result could not be written to ${opts.out}: ${cause.message}`, {
3860
+ hint: "The tool already ran and was billed; its result was printed to stdout instead. Do NOT re-run it.",
3861
+ details: { kind: "write_failed", reason: cause.details?.reason ?? cause.code, tool_ran: true },
3862
+ cause: err
3863
+ });
3864
+ } finally {
3865
+ reportCredit(creditCost);
3866
+ }
3867
+ }
3868
+ async function runPaged(ctx, verb, opts, mcpVersion) {
3869
+ const paged = await runAllPages(ctx);
3870
+ if (paged.pageOneBudgetFailure && paged.failure) {
3871
+ const one = applySelect(paged.value, opts.select);
3872
+ const value2 = opts.meta ? { result: one, credit_cost: paged.creditCost, mcp_version: mcpVersion() } : one;
3873
+ await failAfterBudgetWrite(paged.failure, value2, opts, paged.creditCost);
3874
+ }
3875
+ const selected = applySelect(paged.value, opts.select);
3876
+ const value = opts.meta ? {
3877
+ result: selected,
3878
+ credit_cost: paged.creditCost,
3879
+ mcp_version: mcpVersion(),
3880
+ pages_fetched: paged.callsMade,
3881
+ retries: paged.retries,
3882
+ calls_without_cost: paged.callsWithoutCost
3883
+ } : selected;
3884
+ const failure = paged.failure;
3885
+ if (!failure) {
3886
+ await emitResult(value, verb, opts, paged.creditCost);
3887
+ return;
3888
+ }
3889
+ const partial = { partial_result: true, pages_fetched: paged.callsMade };
3890
+ if (failure.code === "local_state_error" && failure.details?.kind === "budget_write_failed") {
3891
+ await failAfterBudgetWrite(failure, value, opts, paged.creditCost, partial);
3892
+ }
3893
+ let outFailed = false;
3894
+ try {
3895
+ await emit(value, { format: opts.format, out: opts.out, force: opts.force, allowForce: verb === "run" });
3896
+ } catch {
3897
+ if (opts.out) {
3898
+ outFailed = true;
3899
+ try {
3900
+ await emit(value, { format: opts.format });
3901
+ } catch {
3902
+ }
3903
+ }
3904
+ } finally {
3905
+ reportCredit(paged.creditCost);
3906
+ }
3907
+ const resultWent = outFailed || !opts.out ? "stdout" : opts.out;
3908
+ throw new HgiError(failure.code, failure.message, {
3909
+ hint: `${failure.hint ? `${failure.hint} ` : ""}The pages fetched so far were written to ${resultWent}, with the unfinished parts marked truncated. Do NOT re-run the pages already fetched; they were billed.`,
3910
+ details: { ...failure.details, ...partial, ...outFailed ? { out_write_failed: true } : {} },
3911
+ cause: failure
3912
+ });
3913
+ }
2297
3914
  async function runInvoke(verb, toolName, opts, cmd) {
3915
+ const batchSize = preflightBatchFlags(opts);
2298
3916
  const input = await readInput(opts.input);
3917
+ const maxPages = verb === "call" ? preflightPaging(opts, input) : null;
2299
3918
  preflightOutput({ format: opts.format, select: opts.select, out: opts.out, force: opts.force, allowForce: verb === "run" });
2300
3919
  const timeoutMs = parseTimeoutMs(opts.timeout);
3920
+ const retryOptions = resolveRetryOptions({ retries: opts.retries, retryBudget: opts.retryBudget });
3921
+ const transportRetry = transportRetryOptions(retryOptions);
3922
+ const governance = { retries: verb === "call" ? retryOptions.retries ?? 0 : 0, budgetMs: retryLimits(transportRetry).budgetMs };
3923
+ const label = parseLabel(opts.label);
3924
+ const ledger = ledgerPath();
3925
+ const ids = opts.ids === void 0 ? void 0 : await readIds({ ...opts, ids: opts.ids }, input);
3926
+ const maxCredits = verb === "call" ? resolveMaxCredits(opts.maxCredits) : null;
3927
+ const budgetId2 = maxCredits === null ? null : resolveBudgetId();
3928
+ if (budgetId2 !== null && maxCredits !== null) await checkBudget(budgetId2, maxCredits);
2301
3929
  const ctx = buildContext(cmd);
2302
3930
  const creds = ctx.tokens.loadCredentials();
2303
- const session = await openSession(ctx, { timeoutMs });
3931
+ const session = await openSession(ctx, { timeoutMs, retry: transportRetry });
3932
+ const recordUsage = (result) => recordCall(ledger, {
3933
+ v: 1,
3934
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
3935
+ host: new URL(ctx.base).host,
3936
+ verb,
3937
+ tool: toolName,
3938
+ label,
3939
+ credit_cost: creditCostOf(result),
3940
+ budget_id: budgetId(),
3941
+ mcp_version: session.state.mcpVersion,
3942
+ status: result.isError ? "tool_error" : "ok"
3943
+ });
2304
3944
  try {
2305
3945
  const tools = await session.listTools();
2306
3946
  writeToolsCache(toolsCachePath(...mcpCacheKey(ctx.base, creds)), {
@@ -2318,33 +3958,74 @@ async function runInvoke(verb, toolName, opts, cmd) {
2318
3958
  });
2319
3959
  }
2320
3960
  assertVerb(verb, tool);
2321
- if (opts.validate) assertValidInput(tool, input);
2322
- const result = await session.callTool(toolName, input);
2323
- const outcome = interpretResult(result, toolName);
2324
- const selected = applySelect(outcome.value, opts.select);
2325
- const value = opts.meta ? { result: selected, credit_cost: outcome.creditCost, mcp_version: session.state.mcpVersion } : selected;
2326
- try {
2327
- await emit(value, {
3961
+ if (ids) {
3962
+ await runBatch(session, tool, input, ids, {
3963
+ batchSize,
2328
3964
  format: opts.format,
3965
+ select: opts.select,
2329
3966
  out: opts.out,
2330
- force: opts.force,
2331
- allowForce: verb === "run"
3967
+ meta: opts.meta,
3968
+ validate: opts.validate,
3969
+ budget: budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : void 0,
3970
+ onResult: recordUsage,
3971
+ governance
2332
3972
  });
3973
+ return;
3974
+ }
3975
+ if (maxPages !== null) {
3976
+ const spec = assertPageable(tool);
3977
+ if (opts.validate) assertValidInput(tool, input);
3978
+ await runPaged(
3979
+ {
3980
+ session,
3981
+ tool,
3982
+ input,
3983
+ spec,
3984
+ maxPages,
3985
+ validate: opts.validate,
3986
+ budget: budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : void 0,
3987
+ onResult: recordUsage,
3988
+ governance
3989
+ },
3990
+ verb,
3991
+ opts,
3992
+ () => session.state.mcpVersion
3993
+ );
3994
+ return;
3995
+ }
3996
+ if (opts.validate) assertValidInput(tool, input);
3997
+ const capped = budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : null;
3998
+ const { result, attempts, budgetFailure } = await sendWithRetry(session, toolName, input, {
3999
+ ...governance,
4000
+ // Every attempt that came back: one ledger row, and its spend under a run cap.
4001
+ record: async (r) => {
4002
+ await recordUsage(r);
4003
+ if (!capped) return null;
4004
+ try {
4005
+ await recordSpend(capped.id, capped.max, creditCostOf(r));
4006
+ return null;
4007
+ } catch (err) {
4008
+ return toHgiError(err);
4009
+ }
4010
+ },
4011
+ beforeResend: capped ? async () => void await checkBudget(capped.id, capped.max) : void 0,
4012
+ report: reportRetry
4013
+ });
4014
+ let outcome;
4015
+ try {
4016
+ outcome = interpretResult(result, toolName);
2333
4017
  } catch (err) {
2334
- if (!opts.out) throw err;
2335
- const cause = toHgiError(err);
2336
- try {
2337
- await emit(value, { format: opts.format });
2338
- } catch {
4018
+ const retried = governance.retries > 0 && err instanceof HgiError && err.code === "governance_unavailable";
4019
+ if ((budgetFailure || retried) && err instanceof HgiError) {
4020
+ const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
4021
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, ...extra }, cause: err });
2339
4022
  }
2340
- throw new HgiError("local_state_error", `The tool ran, but its result could not be written to ${opts.out}: ${cause.message}`, {
2341
- hint: "The tool already ran and was billed; its result was printed to stdout instead. Do NOT re-run it.",
2342
- details: { kind: "write_failed", reason: cause.details?.reason ?? cause.code, tool_ran: true },
2343
- cause: err
2344
- });
2345
- } finally {
2346
- reportCredit(outcome.creditCost);
4023
+ throw err;
2347
4024
  }
4025
+ const selected = applySelect(outcome.value, opts.select);
4026
+ const value = opts.meta ? { result: selected, credit_cost: outcome.creditCost, mcp_version: session.state.mcpVersion, attempts } : selected;
4027
+ if (budgetFailure) await failAfterBudgetWrite(budgetFailure, value, opts, outcome.creditCost);
4028
+ await emitResult(value, verb, opts, outcome.creditCost);
2348
4029
  } finally {
2349
4030
  await session.close();
2350
4031
  }
@@ -2355,33 +4036,69 @@ function registerInvokeCommands(program) {
2355
4036
  run: "Run a tool that changes state or starts work. Fails for read-only tools."
2356
4037
  };
2357
4038
  for (const verb of ["call", "run"]) {
2358
- program.command(`${verb} <tool>`).description(describeVerb[verb]).option("--input <json>", "tool arguments as a JSON object; @file or - reads a file or stdin").option("-f, --format <format>", "json|jsonl|csv|yaml|table").option("--select <fields>", "keep only these comma-separated fields (dotted paths allowed)").option("--out <file>", "write the result to a new file instead of stdout").option("--force", verb === "run" ? "overwrite an existing --out file" : "not available on call").option("--meta", "print {result, credit_cost, mcp_version} instead of the bare result").option("--timeout <seconds>", "per-request timeout", "120").addOption(new Option("--no-validate", "skip client-side schema validation (let the server judge the input)").hideHelp()).action((tool, opts, cmd) => runInvoke(verb, tool, opts, cmd));
4039
+ const cmd = program.command(`${verb} <tool>`).description(describeVerb[verb]).option("--input <json>", "tool arguments as a JSON object; @file or - reads a file or stdin").option("-f, --format <format>", "json|jsonl|csv|yaml|table").option("--select <fields>", "keep only these comma-separated fields (dotted paths allowed)").option("--out <file>", "write the result to a new file instead of stdout").option("--force", verb === "run" ? "overwrite an existing --out file" : "not available on call").option("--meta", `print {result, credit_cost, mcp_version, attempts} instead of the bare result${verb === "call" ? " (with --all-pages: pages_fetched and retries instead of attempts)" : ""}`).option("--label <label>", "tag this call in the local credit ledger (see `hgi usage --by label`)").option("--timeout <seconds>", "per-request timeout (each attempt; retry waits are extra)", "120").option("--retries <n>", "retry rate limits and outages up to n times each, 0-20; 0 turns every retry off (also $HGI_RETRIES)").option("--retry-budget <seconds>", "most seconds one request may spend waiting between retries, at most 3600 (also $HGI_RETRY_BUDGET; default 600 with retries, else 60)").addOption(new Option("--no-validate", "skip client-side schema validation (let the server judge the input)").hideHelp());
4040
+ if (verb === "call") {
4041
+ cmd.option("--ids <source>", "batch over HG ids or domains, one per line: @file or - (stdin); prints one row per line").option("--ids-column <name>", "with --ids, read the file as CSV with a header row and take ids from this column").option("--batch-size <n>", "with --ids, send fewer ids per call than the tool's limit").option("--max-credits <n>", "stop this run once it has spent n credits (also $HGI_MAX_CREDITS; the flag wins)").option(
4042
+ "--all-pages",
4043
+ "fetch every page of an offset-paged tool and print one merged result; each extra page is a separate, billed call (batch tools: one call per company)"
4044
+ ).option("--max-pages <n>", "with --all-pages, fetch at most n pages per page object, page 1 included (default 10)").addHelpText(
4045
+ "after",
4046
+ [
4047
+ "",
4048
+ "Run cap (client-side, on top of the server limits):",
4049
+ " --max-credits <n> / HGI_MAX_CREDITS refuse the call, sending nothing (exit 13), once this run has spent n credits",
4050
+ " HGI_BUDGET_ID the run to count against (default: the parent process id, so one shell or script)",
4051
+ " `hgi budget status` shows the spend; `hgi budget reset` starts it over.",
4052
+ " With --ids, every batch call is checked and counted.",
4053
+ "",
4054
+ "Paging (--all-pages):",
4055
+ ' Only tools whose schemas show an integer "offset" input and a rows array with has_more or a total.',
4056
+ " Pages are fetched one at a time. Each extra page is a separate, billed call; for batch tools",
4057
+ " (hg_ids/domains), follow-ups go one call per company. Paging stops on has_more: false, an empty or",
4058
+ " short page, the total reached, or --max-pages (default 10). A stopped-early part says",
4059
+ " truncated: true and truncated_reason. A later-page failure prints the pages so far, then exits",
4060
+ " with that failure's code and details.partial_result: true. The run cap is checked before every page."
4061
+ ].join("\n")
4062
+ );
4063
+ }
4064
+ cmd.addHelpText(
4065
+ "after",
4066
+ [
4067
+ "",
4068
+ "Retries (only failures before the tool runs; never a call that may have run):",
4069
+ " hgi retries a 429, the server shedding load (503) and a connection that was never established, and prints",
4070
+ " one line on stderr before each wait. --retries n allows n of each; --retry-budget caps the waiting per request.",
4071
+ verb === "call" ? " With --retries, `hgi call` also re-sends a governance_unavailable refusal (the server could not check the budget)." : " `hgi run` never re-sends governance_unavailable: it exits 7 with retryable: true and you decide.",
4072
+ " The flags win over HGI_RETRIES / HGI_RETRY_BUDGET."
4073
+ ].join("\n")
4074
+ );
4075
+ cmd.action((tool, opts, c) => runInvoke(verb, tool, opts, c));
2359
4076
  }
2360
4077
  }
2361
4078
 
2362
4079
  // src/commands/skill.ts
2363
- import fs5 from "fs";
4080
+ import fs8 from "fs";
2364
4081
  import os2 from "os";
2365
- import path5 from "path";
4082
+ import path7 from "path";
2366
4083
 
2367
4084
  // src/generated/skill-md.ts
2368
- var SKILL_MD = '---\nname: hgi\ndescription: Look up company, contact, technology, intent and spend data from the HG Insights MCP server with the `hgi` command-line client. Use when the user asks about a company\'s tech stack, firmographics, intent signals, contacts, or wants to run an HG Insights agent, and `hgi` is installed.\n---\n\n# hgi: the HG Insights command-line client\n\n`hgi` is a thin client for the HG Insights MCP server. It signs in once through the user\'s browser, then exposes every tool the server offers to the signed-in user.\n\n## Rules\n\n1. **List tools first.** Run `hgi tools list --json` before your first call in a session. The list depends on the user, their organization and the server version, so never assume a tool exists and never reuse a tool list from memory. Each tool is marked `call` or `run`, and `required` shows the mandatory input fields.\n2. **Use `hgi call <tool> --input \'<json>\'` for lookups.** It only runs tools the server marks read-only. It is safe to run without asking.\n3. **Use `hgi run <tool> --input \'<json>\'` only with the user\'s approval.** It runs tools that change state or start work (for example starting an agent run, uploading an artifact by URL, or starting a customer-data discovery). It also runs tools that do not declare themselves read-only. Ask the user, say what the tool will do, then run it.\n4. **Report the credit cost after every call.** The cost is printed on stderr (`credit_cost: N`, or `{"credit_cost":N}` when stderr is not a terminal). `unknown` or `null` means the server did not report one. Tell the user what the call cost; credits are billed to their organization.\n5. **Never read, print or copy the credentials file** under `~/.config/hgi/`, and do not put tokens in commands. If `hgi` says the login is missing or expired, ask the user to run `hgi auth login` themselves. It opens their browser.\n6. **Using the wrong verb fails safely.** `hgi call` on a state-changing tool, or `hgi run` on a read-only tool, exits 10, names the right verb, and sends nothing.\n\n## Recommended permissions (Claude Code)\n\nAllow lookups, ask for everything that can change state. Put this in your user settings (`~/.claude/settings.json`) or a trusted project\'s `.claude/settings.json` (headless runs ignore the settings file of a directory that was never trusted):\n\n```json\n{\n "permissions": {\n "allow": ["Bash(hgi call *)", "Bash(hgi tools list *)", "Bash(hgi auth whoami)"],\n "ask": ["Bash(hgi run *)"]\n }\n}\n```\n\n## Usage\n\n```bash\nhgi tools list --json # what can I call?\nhgi call company_enrich --input \'{"domain":"acme.com"}\' # lookup, JSON on stdout\nhgi call search_companies --input \'{"query":"saas"}\' --select name,domain -f csv\nhgi call <tool> --input \'{"limit":100}\' --out result.json # big result to a new file\nhgi run <tool> --input \'{...}\' # only after the user approves\n```\n\n- `--input` takes a JSON object. `@file.json` reads a file and `-` reads stdin.\n- Output is JSON when piped and a table on a terminal. Use `-f json|jsonl|csv|yaml|table`.\n- `--select a,b.c` keeps only those fields (dotted paths work through arrays). Prefer it, or `--out <new file>`, for large results; results are never truncated.\n- `--meta` prints `{ "result": ..., "credit_cost": ..., "mcp_version": ... }` on stdout.\n\n## Exit codes\n\n**If an error from `hgi run` has `details.outcome_unknown: true`, whatever its exit code (1, 7 or 9), the work may already have started and been billed. Check state first; never just retry.**\n\n| Code | Meaning | What to do |\n|---|---|---|\n| 0 | success | |\n| 1 | internal error in hgi | report it; check state before re-running a `run` (see `outcome_unknown`) |\n| 2 | invalid input or usage | fix the input; the JSON error lists the problem fields |\n| 3 | the tool reported an error | read the message; do not blindly retry |\n| 4 | not signed in, or login expired | ask the user to run `hgi auth login` |\n| 5 | rate limited | wait `retry_after_seconds` from the error, then retry |\n| 6 | out of credits | stop; tell the user. Retrying will not help |\n| 7 | server unreachable | retry later. If `outcome_unknown` is `true`, check state before re-running a `run` |\n| 8 | OAuth or sign-in failure | ask the user to run `hgi auth login` again |\n| 9 | proxy or TLS problem | the error names the cause (see `NODE_EXTRA_CA_CERTS`, `HTTPS_PROXY`). After a `run`, check `outcome_unknown` before retrying |\n| 10 | wrong verb | use the verb the error names |\n| 11 | forbidden | the account or organization lacks access |\n| 12 | local credential or file problem | follow the hint. If `details.tool_ran` is `true`, the tool already ran and its result is on stdout: do not re-run it |\n\nErrors are JSON on stderr when it is not a terminal: `{"schema":1,"error":{"code","exit_code","message","hint","details"}}`.\n';
4085
+ var SKILL_MD = '---\nname: hgi\ndescription: Look up company, contact, technology, intent and spend data from the HG Insights MCP server with the `hgi` command-line client. Use when the user asks about a company\'s tech stack, firmographics, intent signals, contacts, or wants to run an HG Insights agent, and `hgi` is installed.\n---\n\n# hgi: the HG Insights command-line client\n\n`hgi` is a thin client for the HG Insights MCP server. It signs in once through the user\'s browser, then exposes every tool the server offers to the signed-in user.\n\n## Rules\n\n1. **List tools first.** Run `hgi tools list --json` before your first call in a session. The list depends on the user, their organization and the server version, so never assume a tool exists and never reuse a tool list from memory. Each tool is marked `call` or `run`, and `required` shows the mandatory input fields.\n2. **Use `hgi call <tool> --input \'<json>\'` for lookups.** It only runs tools the server marks read-only. It is safe to run without asking.\n3. **Use `hgi run <tool> --input \'<json>\'` only with the user\'s approval.** It runs tools that change state or start work (for example starting an agent run, uploading an artifact by URL, or starting a customer-data discovery). It also runs tools that do not declare themselves read-only. Ask the user, say what the tool will do, then run it.\n4. **Report the credit cost after every call.** The cost is printed on stderr (`credit_cost: N`, or `{"credit_cost":N}` when stderr is not a terminal). `unknown` or `null` means the server did not report one. Tell the user what the call cost; credits are billed to their organization.\n5. **Never read, print or copy the credentials file** under `~/.config/hgi/`, and do not put tokens in commands. If `hgi` says the login is missing or expired, ask the user to run `hgi auth login` themselves. It opens their browser.\n6. **Using the wrong verb fails safely.** `hgi call` on a state-changing tool, or `hgi run` on a read-only tool, exits 10, names the right verb, and sends nothing.\n7. **Show a plan before working through a list.** When the work needs more than one batch (see `## Recipes`), first run one sample batch and report its `credit_cost`. Then show the plan: the calls, the number of batches, and the total estimated by extrapolating from the sample. **Wait for the user\'s go-ahead** before running the rest. Estimate only from the reported `credit_cost`, never from a price list; a figure from a past run may appear only as an example, labelled "observed".\n\n## Recommended permissions (Claude Code)\n\nAllow lookups, ask for everything that can change state. Put this in your user settings (`~/.claude/settings.json`) or a trusted project\'s `.claude/settings.json` (headless runs ignore the settings file of a directory that was never trusted):\n\n```json\n{\n "permissions": {\n "allow": ["Bash(hgi call *)", "Bash(hgi tools list *)", "Bash(hgi auth whoami)"],\n "ask": ["Bash(hgi run *)"]\n }\n}\n```\n\n## Usage\n\n```bash\nhgi tools list --json # what can I call?\nhgi call company_enrich --input \'{"domain":"acme.com"}\' # lookup, JSON on stdout\nhgi call search_companies --input \'{"query":"saas"}\' --select name,domain -f csv\nhgi call <tool> --input \'{"limit":100}\' --out result.json # big result to a new file\nhgi call <tool> --ids @hg_ids.txt --input \'{...}\' # a whole list: one JSONL row per line\nhgi call <tool> --all-pages --input \'{...}\' # every page of an offset-paged tool, merged\nhgi run <tool> --input \'{...}\' # only after the user approves\n```\n\n- `--input` takes a JSON object. `@file.json` reads a file and `-` reads stdin.\n- Output is JSON when piped and a table on a terminal. Use `-f json|jsonl|csv|yaml|table`.\n- `--select a,b.c` keeps only those fields (dotted paths work through arrays). Prefer it, or `--out <new file>`, for large results; results are never truncated.\n- `--meta` prints `{ "result": ..., "credit_cost": ..., "mcp_version": ... }` on stdout.\n- `--label <stage>` on `call`/`run` tags the call in the local credit ledger (1 to 64 of `A-Z a-z 0-9 . _ : / -`).\n- `hgi usage [--since today|24h|7d|2026-11-01] [--by tool|label|day|call]` shows the credits `hgi` spent on this machine (local only, no sign-in, not the organization\'s bill). `credits` excludes calls with unknown cost (`unknown_cost_calls`); `zero_cost_calls` are cache hits or free tools.\n- A `{"warning":"ledger_not_updated",...}` line on stderr means the call still succeeded; do not re-run it.\n- For more than one company, use `--ids @file` (one HG id or domain per line; `--ids -` for stdin; `--ids-column <name>` for a CSV; `--batch-size <n>` to send fewer per call than the tool\'s limit) instead of looping. hgi batches by the tool\'s limit, sends batches one at a time, and prints `{"input", "result"}` or `{"input", "error"}` rows as JSONL in input order. Exit 3 means a batch failed (its rows carry the error, the rest are fine); any other non-zero exit stopped the run, and `details.rows_emitted` / `calls_made` say how far it got: keep the rows already printed and resume from there.\n\n### Paging (`--all-pages`)\n\nFor every row of an offset-paged tool, use `hgi call <tool> --all-pages` instead of an `offset` loop. hgi pages only tools whose schemas show it is safe (an integer `offset` input and a rows array with `has_more` or a total); anything else is refused with exit 2 `not_pageable`, nothing sent. Don\'t pass `offset` yourself.\n\n- **Each extra page is a separate, billed call.** For batch tools (`hg_ids`/`domains`), follow-ups go one call per unfinished company.\n- It stops on `has_more: false`, an empty or short page, or the total reached, never on `has_more: true` alone (the server can say `true` after the last row). `--max-pages <n>` caps pages per page object (default 10, page 1 included).\n- The result keeps the server\'s shape. Each page object (the result, or each `companies[]` entry) gets `pages_fetched`; one cut short says `truncated: true` and `truncated_reason`: `max_pages`, `unmatched` (a batch entry hgi could not tie to one input, so it never guesses) or the code of the call that failed. Report truncated parts as incomplete.\n- One credit line at the end with the sum. `--meta` adds `pages_fetched` (pages requested), `retries` (re-sends) and `calls_without_cost`.\n- Not with `--ids` (exit 2 `all_pages_with_ids`): page one company list at a time.\n\n## Recipes\n\nThese recipes name tools as examples. Before each one:\n\n- **Confirm the tools.** Check every tool a recipe names in `hgi tools list --json`. If one is missing, skip that step and tell the user which tool is unavailable; never substitute a guess.\n- **Take the batch size from the schema.** Read `maxItems` on `hg_ids` or `domains`, and the maximum of `limit`, `max_results` and `offset`, in the tool\'s `input_schema`. Don\'t hard-code them.\n- **Keep batches stable.** The server caches identical inputs for 30 days (7 for search), and a cached call costs nothing (observed). Sort ids and keep the same batches, so a re-run is free. Changing one id in a batch makes the whole batch a new input.\n- **Missing is not zero.** No installs, no intent, or a company left out of a batch response means unknown, not zero. Record it as unknown; don\'t score the account down.\n- **Show a plan first** for more than one batch (Rule 7).\n- Batching is manual for now: sorted id batches, as below. Paging is `--all-pages` where the tool allows it (`not_pageable` otherwise).\n\n### Match an account list\n\n**Tools:** `search_companies`, `company_firmographic`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_firmographic`\'s `input_schema`.\n**Order:**\n\n1. `search_companies` per account: the name, the HQ country and a revenue floor (USD), `limit` small. It returns only `hg_id`, `name`, `domain`, `domain_normalized`.\n2. Collect the candidate `hg_id`s, sort them, and confirm them with `company_firmographic` in batches of `hg_ids`: name, `country_code`, `employees_total`, `revenue_total`, `company_level`.\n3. Keep the row whose country and size fit. Don\'t roll up to the global HQ or corporate parent blindly: HG lists Legrand Lebanon as Legrand\'s global HQ, and the French state as EDF\'s parent. Use `company_level` and the parent fields only after a sanity check.\n\n```bash\nhgi call search_companies --input \'{"company_identifiers":{"name":"Accor"},"firmographics":{"country_codes":[{"ids":["FR"],"inclusion_method":"ANY_PRESENT"}],"revenue":{"min":1000000000}},"limit":5}\'\nhgi call company_firmographic --input \'{"hg_ids":["<id1>","<id2>"]}\' --select companies.company_id,companies.firmographics.name,companies.firmographics.country_code,companies.firmographics.company_level\n```\n\n### Score fit and propensity\n\n**Tools:** `company_technographic`, `company_intent`, `list_intent_topics`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_technographic`\'s `input_schema`, and the maximum of `max_results` and `offset`. `company_intent` takes one company per call.\n**Order:**\n\n1. **Fit:** `company_technographic` on a batch of `hg_ids`, filtered (`vendor_names`, `product_names` or `category_ids`) so pages stay small, with `--all-pages` (above). It pages each company on its own and stops on a short page or `total_installs_count`, not on `has_more` alone (it can be wrong at page boundaries). A company with `truncated: true` is partial: say so, and narrow the filter rather than raising `--max-pages`.\n2. **Topics:** resolve curated topic names to ids with `list_intent_topics`.\n3. **Intent:** `company_intent` on the company\'s web domain (`company_domain`), not only its HQ id: intent is observed on web domains. In one run, Accor had 0 topics on its HQ id and 18 on `accor.com` (observed; counts change over time). Check `company.id` and `company.name` in the response: a domain can resolve to a subsidiary.\n4. **Baseline:** large companies are active on about 70% of the ~20,000-topic catalogue (observed), so a raw topic count measures size, not interest. Compare the curated topics (`topic_ids`) with the company\'s own unfiltered summary. A summary with `topic_ids` counts only those topics. `fields:["summary"]` without a topic filter rejects `granularity` (422). When you request `fields:["topics"]`, pass `granularity:"global"`: the default is one row per state, which counts a topic several times.\n\n```bash\n# every install per company, paged safely; max_results up to the schema\'s maximum keeps the call count down\nhgi call company_technographic --all-pages --max-pages 5 \\\n --input \'{"hg_ids":["<id1>","<id2>"],"vendor_names":["<vendor>"],"max_results":<schema maximum>}\' -f json > tech.json\n# exit 0 with truncated companies = capped; non-zero with details.partial_result = stopped early, tech.json still holds what was paid for\nhgi call company_intent --input \'{"company_domain":"accor.com"}\'\nhgi call company_intent --input \'{"company_domain":"accor.com","fields":["summary"],"topic_ids":["<topic id>"]}\'\n```\n\n### Size wallet from spend\n\n**Tools:** `company_spend`, `get_product_category`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_spend`\'s `input_schema`, and the maximum of `max_results`.\n**Order:**\n\n1. Use the `hg_id`s from the matching recipe, sorted.\n2. To size one area, resolve its category ids first with `get_product_category`, as `company_spend`\'s description says. Don\'t pass guessed `category_names`: a name that matches nothing returns 0 rows without an error.\n3. One `company_spend` call per batch of `hg_ids`, with `category_ids` set in that same call, not filtered afterwards.\n4. `company_spend` is not pageable with `--all-pages` (its per-company spend has no rows array). Page with `max_results` and `offset` by hand only when `all_count` exceeds the rows returned; stop on a short page or once `all_count` is reached, never on a has-more flag alone.\n5. Rows are per country, and categories form a tree through `category_parent_id` (Total IT \u2192 Total External IT \u2192 Software, \u2026). Sum across countries, never a parent with its children.\n\n```bash\nhgi call company_spend --input \'{"hg_ids":["<id1>","<id2>"],"category_ids":["<category id>"]}\' --select companies.company_id,companies.spend.all\n```\n\n## Data semantics\n\nVerified with one live call per tool. "Scope" is what a call returns by default.\n\n| Tool | Default scope | Nullable fields (what null means) |\n|---|---|---|\n| `search_companies` | global: all countries unless `country_codes` filters the HQ country | no field came back null in the verification call; treat a missing field as unknown |\n| `company_firmographic` | country: one record per entity, in its own `country_code` | `corporate_parent_id`, `corporate_parent_name`, `parent_id`, `domestic_parent_id`, `domestic_parent_name`: none (no parent above it); `fortune_500_rank`, `forbes_2000_rank`: unknown |\n| `company_technographic` | global: default rows have `country_code: null`; `granularity` or `country_codes` give per-country rows | `country_code`: a global or unattributed row, not missing data; `product_category_level4_name`, `product_category_level5_name`: none (the category tree is shallower) |\n| `company_intent` | global: `summary` only, for the resolved entity across all geographies; with `fields:["topics"]`, one row per state unless `granularity:"global"` | no field came back null in the verification call; treat a missing field as unknown |\n| `company_spend` | country: every row has a `country_code` | no field came back null in the verification call; treat a missing field as unknown |\n\nNot null, but easy to misread:\n\n- A batch response leaves out companies it didn\'t match. A left-out company is unknown, not zero.\n- `company_domain` is `""` when you query by `hg_ids`.\n- `company_intent` on a domain answers for whichever company the domain resolves to: `accor.com` resolved to an Accor subsidiary in Australia, not the group HQ.\n\n**HG ids** are hex strings, normally 32 characters and uppercase in responses. An id can come back with its leading zero dropped, as 31 characters: seen on a spend `category_id`, and on company ids (observed). The `hg_ids` inputs accept 31 or 32 characters. Upper-case ids and left-pad them to 32 with `0` before comparing or joining.\n\n## Exit codes\n\n**If an error from `hgi run` has `details.outcome_unknown: true`, whatever its exit code (1, 7 or 9), the work may already have started and been billed. Check state first; never just retry.**\n\n| Code | Meaning | What to do |\n|---|---|---|\n| 0 | success | |\n| 1 | internal error in hgi | report it; check state before re-running a `run` (see `outcome_unknown`) |\n| 2 | invalid input or usage | fix the input; the JSON error lists the problem fields |\n| 3 | the tool reported an error | read the message; do not blindly retry |\n| 4 | not signed in, or login expired | ask the user to run `hgi auth login` |\n| 4 `phoenix_account_required` | the signed-in identity has no Phoenix account | stop; tell the user to sign up, or to sign in with `hgi auth login` as an account that has one |\n| 5 | rate limited (after hgi\'s own retries) | wait `retry_after_seconds` from the error, then retry. For a long batch of lookups, pass `--retries 6` instead of writing your own retry loop |\n| 6 | out of credits: `credit_limit_exceeded` (the organization) or `user_credit_limit_exceeded` (the user\'s personal budget) | stop; tell the user which one, and to ask an admin. Retrying will not help |\n| 7 | server unreachable | retry later. If `outcome_unknown` is `true`, check state before re-running a `run` |\n| 7 `governance_unavailable` | the server could not check the budget; nothing ran (`retryable: true`) | wait a little, then retry once. `hgi call --retries <n>` retries it itself; `hgi run` never does |\n| 8 | OAuth or sign-in failure | ask the user to run `hgi auth login` again |\n| 9 | proxy or TLS problem | the error names the cause (see `NODE_EXTRA_CA_CERTS`, `HTTPS_PROXY`). After a `run`, check `outcome_unknown` before retrying |\n| 10 | wrong verb | use the verb the error names |\n| 11 | forbidden, or `tool_not_enabled_for_team` | the account, organization or team lacks access to this tool; stop and tell the user to ask an admin |\n| 12 | local credential or file problem | follow the hint. If `details.tool_ran` is `true`, the tool already ran and its result is on stdout: do not re-run it |\n| any, with `details.partial_result: true` | `--all-pages` stopped on a later page; the pages fetched so far are on stdout (or `--out`), unfinished parts marked `truncated` | keep them, they were billed; then act on the code as its own row says. Don\'t re-fetch pages you already have |\n| 13 `budget_exceeded` | the run spent its `--max-credits` cap; nothing more was sent (with `--ids`, keep the rows already printed) | stop; tell the user what was spent (`details.spent` of `details.max`). Only the user raises the cap or runs `hgi budget reset` |\n\nErrors are JSON on stderr when it is not a terminal: `{"schema":1,"error":{"code","exit_code","message","hint","details"}}`. Branch on `error.code`, not on the message.\n\n## Run cap\n\nWhen the user gives a credit limit for a task, pass it as `hgi call --max-credits <n>` (or set `HGI_MAX_CREDITS`). It counts every `hgi call` in one budget; `hgi run` is not counted. **Run `export HGI_BUDGET_ID=<something unique to the task>` once first:** agent harnesses usually start a fresh shell per command, and the default budget (the parent process) would then give every call its own empty budget. The cap is client-side, on top of the server\'s limits, and can overshoot by the calls running at the same time. `hgi budget status` shows what the task has spent.\n';
2369
4086
 
2370
4087
  // src/commands/skill.ts
2371
4088
  function defaultSkillsDir() {
2372
- const claude = process.env.CLAUDE_CONFIG_DIR ?? path5.join(os2.homedir(), ".claude");
2373
- return path5.join(claude, "skills");
4089
+ const claude = process.env.CLAUDE_CONFIG_DIR ?? path7.join(os2.homedir(), ".claude");
4090
+ return path7.join(claude, "skills");
2374
4091
  }
2375
4092
  function refuse2(message, reason) {
2376
4093
  return new HgiError("invalid_input", message, { details: { reason } });
2377
4094
  }
2378
4095
  function installSkill(opts) {
2379
- const skillsDir = path5.resolve(opts.dir ?? defaultSkillsDir());
2380
- const targetDir = path5.join(skillsDir, "hgi");
2381
- const target = path5.join(targetDir, "SKILL.md");
4096
+ const skillsDir = path7.resolve(opts.dir ?? defaultSkillsDir());
4097
+ const targetDir = path7.join(skillsDir, "hgi");
4098
+ const target = path7.join(targetDir, "SKILL.md");
2382
4099
  for (const guarded of [skillsDir, targetDir]) {
2383
4100
  try {
2384
- const st = fs5.lstatSync(guarded);
4101
+ const st = fs8.lstatSync(guarded);
2385
4102
  if (st.isSymbolicLink()) throw refuse2(`Refusing to install through the symlink ${guarded}.`, "symlink");
2386
4103
  if (!st.isDirectory()) throw refuse2(`${guarded} is not a directory.`, "not_a_directory");
2387
4104
  } catch (err) {
@@ -2389,24 +4106,24 @@ function installSkill(opts) {
2389
4106
  if (err.code !== "ENOENT") throw err;
2390
4107
  }
2391
4108
  }
2392
- fs5.mkdirSync(targetDir, { recursive: true });
4109
+ fs8.mkdirSync(targetDir, { recursive: true });
2393
4110
  let existing = null;
2394
4111
  try {
2395
- existing = fs5.lstatSync(target);
4112
+ existing = fs8.lstatSync(target);
2396
4113
  } catch {
2397
4114
  existing = null;
2398
4115
  }
2399
4116
  if (existing) {
2400
4117
  if (existing.isSymbolicLink() || !existing.isFile()) throw refuse2(`${target} is not a regular file.`, "not_regular_file");
2401
- if (fs5.readFileSync(target, "utf8") === SKILL_MD) return { path: target, result: "unchanged" };
4118
+ if (fs8.readFileSync(target, "utf8") === SKILL_MD) return { path: target, result: "unchanged" };
2402
4119
  if (!opts.force) {
2403
4120
  throw refuse2(`${target} already exists and differs.`, "exists");
2404
4121
  }
2405
- fs5.unlinkSync(target);
2406
- fs5.writeFileSync(target, SKILL_MD, { flag: "wx", mode: 420 });
4122
+ fs8.unlinkSync(target);
4123
+ fs8.writeFileSync(target, SKILL_MD, { flag: "wx", mode: 420 });
2407
4124
  return { path: target, result: "replaced" };
2408
4125
  }
2409
- fs5.writeFileSync(target, SKILL_MD, { flag: "wx", mode: 420 });
4126
+ fs8.writeFileSync(target, SKILL_MD, { flag: "wx", mode: 420 });
2410
4127
  return { path: target, result: "installed" };
2411
4128
  }
2412
4129
  function registerSkillCommands(program) {
@@ -2416,6 +4133,58 @@ function registerSkillCommands(program) {
2416
4133
  });
2417
4134
  }
2418
4135
 
4136
+ // src/commands/usage.ts
4137
+ var LOCAL_ONLY_NOTICE = "Local to this machine: calls made by hgi here, not your organization's bill.";
4138
+ var ZERO_COST_CELL = "0 (server cache or free tool)";
4139
+ var TABLE_FOOTNOTE = [
4140
+ "zero_cost_calls: calls the server reported as costing 0 credits (a server-side cache hit or a free tool).",
4141
+ "unknown_cost_calls: calls whose cost the server did not report; they are not counted in credits."
4142
+ ].join("\n");
4143
+ function forTable(rows) {
4144
+ return rows.map((row) => {
4145
+ const out = { ...row };
4146
+ if (out.credit_cost === 0) out.credit_cost = ZERO_COST_CELL;
4147
+ if (out.credits === 0 && typeof out.zero_cost_calls === "number" && out.zero_cost_calls > 0) out.credits = ZERO_COST_CELL;
4148
+ if ("label" in out && out.label === null) out.label = "(none)";
4149
+ return out;
4150
+ });
4151
+ }
4152
+ function note(text) {
4153
+ process.stderr.write(`${text}
4154
+ `);
4155
+ }
4156
+ function registerUsageCommands(program) {
4157
+ program.command("usage").description("Summarize the credits hgi spent on this machine (local ledger; not your organization's bill)").option("--since <when>", 'only calls since a date, datetime, "today", or a duration such as 24h or 7d').option("--by <key>", "tool|label|day|call (call lists the ledger rows themselves)", "tool").option("-f, --format <format>", "json|jsonl|csv|yaml|table").option("--select <fields>", "keep only these comma-separated fields").option("--out <file>", "write to a new file instead of stdout").action(async (opts, cmd) => {
4158
+ const by = parseBy(opts.by);
4159
+ const since = opts.since === void 0 ? null : parseSince(opts.since);
4160
+ preflightOutput({ format: opts.format, select: opts.select, out: opts.out });
4161
+ const globals = cmd.optsWithGlobals();
4162
+ setDebug(Boolean(globals.debug) || process.env.HGI_DEBUG === "1");
4163
+ const host = new URL(resolveBaseUrl(globals.baseUrl ?? process.env.HGI_BASE_URL)).host;
4164
+ const file = ledgerPath();
4165
+ const format = opts.format ? parseFormat(opts.format) : defaultFormat(Boolean(process.stdout.isTTY));
4166
+ note(LOCAL_ONLY_NOTICE);
4167
+ let rows = [];
4168
+ if (file === null) {
4169
+ note("hgi: the credit ledger is disabled (HGI_LEDGER=off); nothing is recorded on this machine.");
4170
+ } else {
4171
+ const read = readLedger(file);
4172
+ if (read.status === "missing") {
4173
+ note("hgi: nothing has been recorded on this machine yet.");
4174
+ } else {
4175
+ if (read.malformed > 0) {
4176
+ note(`hgi: warning: skipped ${read.malformed} malformed ledger line${read.malformed === 1 ? "" : "s"}.`);
4177
+ }
4178
+ if (read.rows.length === 0 && read.malformed === 0) note("hgi: nothing has been recorded on this machine yet.");
4179
+ rows = filterRows(read.rows, host, since);
4180
+ }
4181
+ }
4182
+ const value = by === "call" ? rows.map((r) => ({ ...r })) : summarize2(rows, by);
4183
+ await emit(format === "table" ? forTable(value) : value, { format, select: opts.select, out: opts.out });
4184
+ if (format === "table") note(TABLE_FOOTNOTE);
4185
+ });
4186
+ }
4187
+
2419
4188
  // src/cli.ts
2420
4189
  function buildProgram() {
2421
4190
  const program = new Command();
@@ -2423,6 +4192,8 @@ function buildProgram() {
2423
4192
  registerAuthCommands(program);
2424
4193
  registerToolsCommands(program);
2425
4194
  registerInvokeCommands(program);
4195
+ registerUsageCommands(program);
4196
+ registerBudgetCommands(program);
2426
4197
  registerSkillCommands(program);
2427
4198
  return program;
2428
4199
  }