@hginsights/hgi 0.1.0 → 0.2.0-rc.1
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/README.md +51 -2
- package/dist/bin.js +1385 -202
- package/docs/exit-codes.md +55 -8
- package/docs/output-formats.md +38 -0
- package/docs/releasing.md +4 -1
- package/docs/security.md +14 -2
- package/npm-shrinkwrap.json +870 -314
- package/package.json +2 -2
- package/skills/hgi/SKILL.md +106 -3
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.
|
|
278
|
+
var VERSION = true ? "0.2.0-rc.1" : "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
|
-
|
|
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
|
|
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 =
|
|
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
|
-
|
|
890
|
+
fs3.chmodSync(dir, 448);
|
|
783
891
|
} catch {
|
|
784
892
|
}
|
|
785
893
|
}
|
|
786
894
|
return;
|
|
787
895
|
}
|
|
788
896
|
try {
|
|
789
|
-
|
|
790
|
-
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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(
|
|
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
|
-
|
|
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 =
|
|
972
|
+
fd = fs3.openSync(
|
|
865
973
|
tmp,
|
|
866
|
-
|
|
974
|
+
fs3.constants.O_CREAT | fs3.constants.O_EXCL | fs3.constants.O_WRONLY | fs3.constants.O_NOFOLLOW,
|
|
867
975
|
384
|
|
868
976
|
);
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
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
|
-
|
|
984
|
+
fs3.renameSync(tmp, file);
|
|
877
985
|
} catch (err) {
|
|
878
986
|
if (fd !== void 0) {
|
|
879
987
|
try {
|
|
880
|
-
|
|
988
|
+
fs3.closeSync(fd);
|
|
881
989
|
} catch {
|
|
882
990
|
}
|
|
883
991
|
}
|
|
884
992
|
try {
|
|
885
|
-
|
|
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
|
-
|
|
1011
|
+
fs3.unlinkSync(file);
|
|
904
1012
|
} catch (err) {
|
|
905
1013
|
if (err.code !== "ENOENT") throw err;
|
|
906
1014
|
}
|
|
907
1015
|
}
|
|
908
|
-
var
|
|
909
|
-
|
|
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
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
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
|
|
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 =
|
|
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 =
|
|
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,
|
|
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 =
|
|
1619
|
-
const st =
|
|
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
|
|
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)
|
|
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 (!
|
|
1642
|
-
|
|
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 =
|
|
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 =
|
|
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 =
|
|
1709
|
+
const fd = fs4.openSync(tmp, flags, 438);
|
|
1667
1710
|
try {
|
|
1668
|
-
|
|
1669
|
-
|
|
1711
|
+
fs4.writeFileSync(fd, data);
|
|
1712
|
+
fs4.fsyncSync(fd);
|
|
1670
1713
|
} finally {
|
|
1671
|
-
|
|
1714
|
+
fs4.closeSync(fd);
|
|
1672
1715
|
}
|
|
1673
|
-
if (existing)
|
|
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
|
-
|
|
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/
|
|
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
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
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
|
|
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
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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/
|
|
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 {
|
|
@@ -2171,6 +2437,293 @@ function registerToolsCommands(program) {
|
|
|
2171
2437
|
});
|
|
2172
2438
|
}
|
|
2173
2439
|
|
|
2440
|
+
// src/ledger.ts
|
|
2441
|
+
import fs7 from "fs";
|
|
2442
|
+
import path6 from "path";
|
|
2443
|
+
var LEDGER_FILE = "ledger.jsonl";
|
|
2444
|
+
var LEDGER_LOCK_RETRIES = { retries: 9, factor: 1.5, minTimeout: 70, maxTimeout: 700, randomize: true };
|
|
2445
|
+
function ledgerPath(env = process.env) {
|
|
2446
|
+
const raw = env.HGI_LEDGER;
|
|
2447
|
+
if (raw === "off") return null;
|
|
2448
|
+
if (raw) return guardLedgerOverride(raw);
|
|
2449
|
+
return path6.join(configDir(env), LEDGER_FILE);
|
|
2450
|
+
}
|
|
2451
|
+
function budgetId(env = process.env) {
|
|
2452
|
+
return env.HGI_BUDGET_ID ? env.HGI_BUDGET_ID : null;
|
|
2453
|
+
}
|
|
2454
|
+
var LABEL = /^[A-Za-z0-9._:/-]{1,64}$/;
|
|
2455
|
+
function parseLabel(raw) {
|
|
2456
|
+
if (raw === void 0) return null;
|
|
2457
|
+
if (LABEL.test(raw)) return raw;
|
|
2458
|
+
throw new HgiError("invalid_input", "--label must be 1 to 64 characters from A-Z a-z 0-9 . _ : / -", {
|
|
2459
|
+
hint: "For example: --label resolve or --label enrich/pass-2. Nothing was sent.",
|
|
2460
|
+
details: { reason: "bad_label" }
|
|
2461
|
+
});
|
|
2462
|
+
}
|
|
2463
|
+
var MCP_VERSION = /^[A-Za-z0-9._-]{1,32}$/;
|
|
2464
|
+
function sanitizeMcpVersion(value) {
|
|
2465
|
+
return typeof value === "string" && MCP_VERSION.test(value) && redact(value) === value ? value : null;
|
|
2466
|
+
}
|
|
2467
|
+
function redactOrNull(value) {
|
|
2468
|
+
return value === null ? null : redact(value);
|
|
2469
|
+
}
|
|
2470
|
+
function serializeRecord(r) {
|
|
2471
|
+
const line = {
|
|
2472
|
+
v: 1,
|
|
2473
|
+
ts: redact(r.ts),
|
|
2474
|
+
host: redact(r.host),
|
|
2475
|
+
verb: r.verb,
|
|
2476
|
+
tool: redact(r.tool),
|
|
2477
|
+
label: redactOrNull(r.label),
|
|
2478
|
+
credit_cost: typeof r.credit_cost === "number" && Number.isFinite(r.credit_cost) ? r.credit_cost : null,
|
|
2479
|
+
budget_id: redactOrNull(r.budget_id),
|
|
2480
|
+
mcp_version: sanitizeMcpVersion(r.mcp_version),
|
|
2481
|
+
status: r.status
|
|
2482
|
+
};
|
|
2483
|
+
return `${JSON.stringify(line)}
|
|
2484
|
+
`;
|
|
2485
|
+
}
|
|
2486
|
+
function errnoOf(err) {
|
|
2487
|
+
const code = err?.code;
|
|
2488
|
+
return typeof code === "string" ? code : void 0;
|
|
2489
|
+
}
|
|
2490
|
+
function reasonOf(err) {
|
|
2491
|
+
if (err instanceof HgiError) {
|
|
2492
|
+
const kind = err.details?.kind;
|
|
2493
|
+
if (kind === "lock_timeout" || kind === "lock_compromised") return kind;
|
|
2494
|
+
const reason = err.details?.reason;
|
|
2495
|
+
if (typeof reason === "string") return reason;
|
|
2496
|
+
return errnoOf(err.cause) ?? (typeof kind === "string" ? kind : "write_failed");
|
|
2497
|
+
}
|
|
2498
|
+
return errnoOf(err) ?? "write_failed";
|
|
2499
|
+
}
|
|
2500
|
+
function writeLine(file, buf, lock) {
|
|
2501
|
+
let fd;
|
|
2502
|
+
try {
|
|
2503
|
+
fd = fs7.openSync(
|
|
2504
|
+
file,
|
|
2505
|
+
fs7.constants.O_WRONLY | fs7.constants.O_APPEND | fs7.constants.O_CREAT | fs7.constants.O_NOFOLLOW | fs7.constants.O_NONBLOCK,
|
|
2506
|
+
384
|
|
2507
|
+
);
|
|
2508
|
+
const st = fs7.fstatSync(fd);
|
|
2509
|
+
if (!st.isFile()) return "not_regular_file";
|
|
2510
|
+
if ((st.mode & 511) !== 384) {
|
|
2511
|
+
try {
|
|
2512
|
+
fs7.fchmodSync(fd, 384);
|
|
2513
|
+
} catch {
|
|
2514
|
+
return "mode";
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
lock.assertHeld();
|
|
2518
|
+
const written = fs7.writeSync(fd, buf);
|
|
2519
|
+
return written === buf.length ? null : "short_write";
|
|
2520
|
+
} catch (err) {
|
|
2521
|
+
return errnoOf(err) === "ELOOP" ? "symlink" : reasonOf(err);
|
|
2522
|
+
} finally {
|
|
2523
|
+
if (fd !== void 0) {
|
|
2524
|
+
try {
|
|
2525
|
+
fs7.closeSync(fd);
|
|
2526
|
+
} catch {
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
}
|
|
2531
|
+
async function appendLedger(file, record) {
|
|
2532
|
+
try {
|
|
2533
|
+
const buf = Buffer.from(serializeRecord(record), "utf8");
|
|
2534
|
+
ensureDir(path6.dirname(file));
|
|
2535
|
+
let st = null;
|
|
2536
|
+
try {
|
|
2537
|
+
st = fs7.lstatSync(file);
|
|
2538
|
+
} catch {
|
|
2539
|
+
st = null;
|
|
2540
|
+
}
|
|
2541
|
+
if (st?.isSymbolicLink()) return "symlink";
|
|
2542
|
+
if (st && !st.isFile()) return "not_regular_file";
|
|
2543
|
+
return await withFileLock(file, { label: "ledger", retries: LEDGER_LOCK_RETRIES }, async (lock) => writeLine(file, buf, lock));
|
|
2544
|
+
} catch (err) {
|
|
2545
|
+
return reasonOf(err);
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
function stderrIsJson() {
|
|
2549
|
+
return !process.stderr.isTTY || process.argv.includes("--json-errors");
|
|
2550
|
+
}
|
|
2551
|
+
async function recordCall(file, record) {
|
|
2552
|
+
if (file === null) return;
|
|
2553
|
+
const reason = await appendLedger(file, record);
|
|
2554
|
+
if (reason === null) return;
|
|
2555
|
+
const safe = reason.replace(/[^A-Za-z0-9_]/g, "_");
|
|
2556
|
+
process.stderr.write(
|
|
2557
|
+
stderrIsJson() ? `${JSON.stringify({ warning: "ledger_not_updated", reason: safe })}
|
|
2558
|
+
` : `hgi: warning: credit ledger not updated: ${safe}
|
|
2559
|
+
`
|
|
2560
|
+
);
|
|
2561
|
+
}
|
|
2562
|
+
function ledgerUnsafe(reason, file) {
|
|
2563
|
+
return new HgiError("local_state_error", `Credit ledger path is unsafe (${reason}): ${file}`, {
|
|
2564
|
+
hint: "Remove or fix it yourself; hgi will not follow symlinks or read non-regular files. Deleting the ledger only resets local history.",
|
|
2565
|
+
details: { kind: "ledger_unsafe", reason }
|
|
2566
|
+
});
|
|
2567
|
+
}
|
|
2568
|
+
function readFailed(code, file, cause) {
|
|
2569
|
+
return new HgiError("local_state_error", `Cannot read the credit ledger ${file}: ${code}.`, {
|
|
2570
|
+
hint: "Check its permissions. Deleting the ledger only resets local history.",
|
|
2571
|
+
details: { kind: "read_failed", reason: code },
|
|
2572
|
+
cause
|
|
2573
|
+
});
|
|
2574
|
+
}
|
|
2575
|
+
var isStringOrNull = (v) => v === null || typeof v === "string";
|
|
2576
|
+
function parseLine(line) {
|
|
2577
|
+
let value;
|
|
2578
|
+
try {
|
|
2579
|
+
value = JSON.parse(line);
|
|
2580
|
+
} catch {
|
|
2581
|
+
return null;
|
|
2582
|
+
}
|
|
2583
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
2584
|
+
const r = value;
|
|
2585
|
+
const cost = r.credit_cost;
|
|
2586
|
+
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");
|
|
2587
|
+
if (!ok) return null;
|
|
2588
|
+
return {
|
|
2589
|
+
v: 1,
|
|
2590
|
+
ts: r.ts,
|
|
2591
|
+
host: r.host,
|
|
2592
|
+
verb: r.verb,
|
|
2593
|
+
tool: r.tool,
|
|
2594
|
+
label: r.label,
|
|
2595
|
+
credit_cost: cost,
|
|
2596
|
+
budget_id: r.budget_id,
|
|
2597
|
+
mcp_version: r.mcp_version,
|
|
2598
|
+
status: r.status
|
|
2599
|
+
};
|
|
2600
|
+
}
|
|
2601
|
+
function readLedger(file) {
|
|
2602
|
+
let fd;
|
|
2603
|
+
try {
|
|
2604
|
+
fd = fs7.openSync(file, fs7.constants.O_RDONLY | fs7.constants.O_NOFOLLOW | fs7.constants.O_NONBLOCK);
|
|
2605
|
+
} catch (err) {
|
|
2606
|
+
const code = errnoOf(err) ?? "error";
|
|
2607
|
+
if (code === "ENOENT") return { status: "missing" };
|
|
2608
|
+
if (code === "ELOOP") throw ledgerUnsafe("symlink", file);
|
|
2609
|
+
throw readFailed(code, file, err);
|
|
2610
|
+
}
|
|
2611
|
+
let text;
|
|
2612
|
+
try {
|
|
2613
|
+
if (!fs7.fstatSync(fd).isFile()) throw ledgerUnsafe("not_regular_file", file);
|
|
2614
|
+
text = fs7.readFileSync(fd, "utf8");
|
|
2615
|
+
} catch (err) {
|
|
2616
|
+
if (err instanceof HgiError) throw err;
|
|
2617
|
+
throw readFailed(errnoOf(err) ?? "error", file, err);
|
|
2618
|
+
} finally {
|
|
2619
|
+
fs7.closeSync(fd);
|
|
2620
|
+
}
|
|
2621
|
+
const rows = [];
|
|
2622
|
+
let malformed = 0;
|
|
2623
|
+
for (const line of text.split("\n")) {
|
|
2624
|
+
if (line.trim() === "") continue;
|
|
2625
|
+
const row = parseLine(line);
|
|
2626
|
+
if (row) rows.push(row);
|
|
2627
|
+
else malformed += 1;
|
|
2628
|
+
}
|
|
2629
|
+
return { status: "ok", rows, malformed };
|
|
2630
|
+
}
|
|
2631
|
+
function badSince(raw) {
|
|
2632
|
+
return new HgiError("invalid_input", `--since "${raw}" is not a date, a datetime, "today" or a duration.`, {
|
|
2633
|
+
hint: "Use 2026-11-01, 2026-11-01T09:00 (local time unless a zone is given), today, 24h or 7d.",
|
|
2634
|
+
details: { reason: "bad_since" }
|
|
2635
|
+
});
|
|
2636
|
+
}
|
|
2637
|
+
var DURATION = /^(\d+)([hd])$/;
|
|
2638
|
+
var DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
2639
|
+
var DATETIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?$/;
|
|
2640
|
+
function validDate(y, m, d) {
|
|
2641
|
+
const probe = new Date(Date.UTC(y, m - 1, d));
|
|
2642
|
+
return probe.getUTCFullYear() === y && probe.getUTCMonth() === m - 1 && probe.getUTCDate() === d;
|
|
2643
|
+
}
|
|
2644
|
+
function parseSince(raw, now = Date.now()) {
|
|
2645
|
+
const dur = DURATION.exec(raw);
|
|
2646
|
+
if (dur) {
|
|
2647
|
+
const n = Number(dur[1]);
|
|
2648
|
+
if (!Number.isSafeInteger(n) || n < 1) throw badSince(raw);
|
|
2649
|
+
return now - n * (dur[2] === "h" ? 36e5 : 864e5);
|
|
2650
|
+
}
|
|
2651
|
+
if (raw === "today") {
|
|
2652
|
+
const d = new Date(now);
|
|
2653
|
+
return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
|
2654
|
+
}
|
|
2655
|
+
const date = DATE.exec(raw);
|
|
2656
|
+
if (date) {
|
|
2657
|
+
const [y, m, d] = [Number(date[1]), Number(date[2]), Number(date[3])];
|
|
2658
|
+
if (!validDate(y, m, d)) throw badSince(raw);
|
|
2659
|
+
return new Date(y, m - 1, d).getTime();
|
|
2660
|
+
}
|
|
2661
|
+
const dt = DATETIME.exec(raw);
|
|
2662
|
+
if (dt) {
|
|
2663
|
+
const [y, mo, d, h, mi] = [Number(dt[1]), Number(dt[2]), Number(dt[3]), Number(dt[4]), Number(dt[5])];
|
|
2664
|
+
const s = dt[6] === void 0 ? 0 : Number(dt[6]);
|
|
2665
|
+
const ms = dt[7] === void 0 ? 0 : Number(dt[7].padEnd(3, "0"));
|
|
2666
|
+
if (!validDate(y, mo, d) || h > 23 || mi > 59 || s > 59) throw badSince(raw);
|
|
2667
|
+
const zone = dt[8];
|
|
2668
|
+
if (zone === void 0) return new Date(y, mo - 1, d, h, mi, s, ms).getTime();
|
|
2669
|
+
const utc = Date.UTC(y, mo - 1, d, h, mi, s, ms);
|
|
2670
|
+
if (zone === "Z") return utc;
|
|
2671
|
+
const [zh, zm] = [Number(zone.slice(1, 3)), Number(zone.slice(4, 6))];
|
|
2672
|
+
if (zh > 23 || zm > 59) throw badSince(raw);
|
|
2673
|
+
const offset = (zh * 60 + zm) * 6e4 * (zone.startsWith("-") ? -1 : 1);
|
|
2674
|
+
return utc - offset;
|
|
2675
|
+
}
|
|
2676
|
+
throw badSince(raw);
|
|
2677
|
+
}
|
|
2678
|
+
var BY_VALUES = ["tool", "label", "day", "call"];
|
|
2679
|
+
function parseBy(raw) {
|
|
2680
|
+
if (BY_VALUES.includes(raw)) return raw;
|
|
2681
|
+
throw new HgiError("invalid_input", `--by "${raw}" is not one of: ${BY_VALUES.join(", ")}.`, {
|
|
2682
|
+
details: { reason: "bad_by" }
|
|
2683
|
+
});
|
|
2684
|
+
}
|
|
2685
|
+
function filterRows(rows, host, sinceMs) {
|
|
2686
|
+
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);
|
|
2687
|
+
}
|
|
2688
|
+
function localDay(ts) {
|
|
2689
|
+
const d = new Date(ts);
|
|
2690
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
2691
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
2692
|
+
}
|
|
2693
|
+
function compareKeys(a, b) {
|
|
2694
|
+
if (a === b) return 0;
|
|
2695
|
+
if (a === null) return 1;
|
|
2696
|
+
if (b === null) return -1;
|
|
2697
|
+
return a < b ? -1 : 1;
|
|
2698
|
+
}
|
|
2699
|
+
function summarize2(rows, by) {
|
|
2700
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2701
|
+
for (const row of rows) {
|
|
2702
|
+
const key = by === "tool" ? row.tool : by === "label" ? row.label : localDay(row.ts);
|
|
2703
|
+
let g = groups.get(key);
|
|
2704
|
+
if (!g) {
|
|
2705
|
+
g = { key, calls: 0, credits: 0, zero_cost_calls: 0, unknown_cost_calls: 0 };
|
|
2706
|
+
groups.set(key, g);
|
|
2707
|
+
}
|
|
2708
|
+
g.calls += 1;
|
|
2709
|
+
if (row.credit_cost === null) g.unknown_cost_calls += 1;
|
|
2710
|
+
else {
|
|
2711
|
+
g.credits += row.credit_cost;
|
|
2712
|
+
if (row.credit_cost === 0) g.zero_cost_calls += 1;
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
const list = [...groups.values()];
|
|
2716
|
+
if (by === "day") list.sort((a, b) => compareKeys(a.key, b.key));
|
|
2717
|
+
else list.sort((a, b) => b.credits - a.credits || compareKeys(a.key, b.key));
|
|
2718
|
+
return list.map((g) => ({
|
|
2719
|
+
[by]: g.key,
|
|
2720
|
+
calls: g.calls,
|
|
2721
|
+
credits: g.credits,
|
|
2722
|
+
zero_cost_calls: g.zero_cost_calls,
|
|
2723
|
+
unknown_cost_calls: g.unknown_cost_calls
|
|
2724
|
+
}));
|
|
2725
|
+
}
|
|
2726
|
+
|
|
2174
2727
|
// src/mcp/result.ts
|
|
2175
2728
|
var MAX_ERROR_TEXT = 2e3;
|
|
2176
2729
|
function textOf(result) {
|
|
@@ -2195,17 +2748,44 @@ function creditCostOf(result) {
|
|
|
2195
2748
|
const cost = result._meta?.creditCost;
|
|
2196
2749
|
return typeof cost === "number" && Number.isFinite(cost) ? cost : null;
|
|
2197
2750
|
}
|
|
2751
|
+
var REFUSALS = {
|
|
2752
|
+
credit_limit_exceeded: {
|
|
2753
|
+
code: "credit_limit_exceeded",
|
|
2754
|
+
hint: "Your organization has used its credit allowance. Contact your admin; retrying will not help."
|
|
2755
|
+
},
|
|
2756
|
+
user_credit_limit_exceeded: {
|
|
2757
|
+
code: "user_credit_limit_exceeded",
|
|
2758
|
+
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."
|
|
2759
|
+
},
|
|
2760
|
+
governance_unavailable: {
|
|
2761
|
+
code: "governance_unavailable",
|
|
2762
|
+
hint: "The server could not check your budget, so nothing ran. Retry shortly.",
|
|
2763
|
+
details: { retryable: true, outcome_unknown: false }
|
|
2764
|
+
},
|
|
2765
|
+
tool_not_enabled_for_team: {
|
|
2766
|
+
code: "tool_not_enabled_for_team",
|
|
2767
|
+
hint: "This tool is not enabled for your team. Ask an admin to enable it."
|
|
2768
|
+
},
|
|
2769
|
+
phoenix_account_required: {
|
|
2770
|
+
code: "phoenix_account_required",
|
|
2771
|
+
hint: "This identity has no Phoenix account. Sign up for one, or sign in with `hgi auth login` as an account that has one."
|
|
2772
|
+
}
|
|
2773
|
+
};
|
|
2774
|
+
function serverErrorCodeOf(result) {
|
|
2775
|
+
const code = result._meta?.errorCode;
|
|
2776
|
+
return typeof code === "string" ? code : void 0;
|
|
2777
|
+
}
|
|
2198
2778
|
function interpretResult(result, toolName) {
|
|
2199
2779
|
if (result.isError) {
|
|
2200
2780
|
const text = redact(textOf(result)).slice(0, MAX_ERROR_TEXT) || "The tool reported an error.";
|
|
2201
|
-
const
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
});
|
|
2781
|
+
const serverCode = serverErrorCodeOf(result);
|
|
2782
|
+
const details = { tool: toolName };
|
|
2783
|
+
if (serverCode !== void 0) details.server_error_code = serverCode;
|
|
2784
|
+
const refusal = serverCode !== void 0 && Object.hasOwn(REFUSALS, serverCode) ? REFUSALS[serverCode] : void 0;
|
|
2785
|
+
if (refusal) {
|
|
2786
|
+
throw new HgiError(refusal.code, text, { hint: refusal.hint, details: { ...details, ...refusal.details } });
|
|
2207
2787
|
}
|
|
2208
|
-
throw new HgiError("tool_error", text, { details
|
|
2788
|
+
throw new HgiError("tool_error", text, { details });
|
|
2209
2789
|
}
|
|
2210
2790
|
return { value: extractValue(result), creditCost: creditCostOf(result) };
|
|
2211
2791
|
}
|
|
@@ -2241,6 +2821,489 @@ function assertValidInput(tool, input) {
|
|
|
2241
2821
|
});
|
|
2242
2822
|
}
|
|
2243
2823
|
|
|
2824
|
+
// src/batch/ids.ts
|
|
2825
|
+
function stripBom(text) {
|
|
2826
|
+
return text.charCodeAt(0) === 65279 ? text.slice(1) : text;
|
|
2827
|
+
}
|
|
2828
|
+
function parseIdLines(text) {
|
|
2829
|
+
const out = [];
|
|
2830
|
+
stripBom(text).split("\n").forEach((raw, i) => {
|
|
2831
|
+
const value = raw.trim();
|
|
2832
|
+
if (value === "" || value.startsWith("#")) return;
|
|
2833
|
+
out.push({ text: value, line: i + 1 });
|
|
2834
|
+
});
|
|
2835
|
+
return out;
|
|
2836
|
+
}
|
|
2837
|
+
function parseCsv(text) {
|
|
2838
|
+
const src = stripBom(text);
|
|
2839
|
+
const records = [];
|
|
2840
|
+
let record = [];
|
|
2841
|
+
let cell = "";
|
|
2842
|
+
let quoted = false;
|
|
2843
|
+
let atCellStart = true;
|
|
2844
|
+
for (let i = 0; i < src.length; i += 1) {
|
|
2845
|
+
const ch = src[i];
|
|
2846
|
+
if (quoted) {
|
|
2847
|
+
if (ch === '"' && src[i + 1] === '"') {
|
|
2848
|
+
cell += '"';
|
|
2849
|
+
i += 1;
|
|
2850
|
+
} else if (ch === '"') {
|
|
2851
|
+
quoted = false;
|
|
2852
|
+
} else {
|
|
2853
|
+
cell += ch;
|
|
2854
|
+
}
|
|
2855
|
+
continue;
|
|
2856
|
+
}
|
|
2857
|
+
if (ch === '"' && atCellStart) {
|
|
2858
|
+
quoted = true;
|
|
2859
|
+
atCellStart = false;
|
|
2860
|
+
} else if (ch === ",") {
|
|
2861
|
+
record.push(cell);
|
|
2862
|
+
cell = "";
|
|
2863
|
+
atCellStart = true;
|
|
2864
|
+
} else if (ch === "\n" || ch === "\r" && src[i + 1] === "\n") {
|
|
2865
|
+
if (ch === "\r") i += 1;
|
|
2866
|
+
record.push(cell);
|
|
2867
|
+
records.push(record);
|
|
2868
|
+
record = [];
|
|
2869
|
+
cell = "";
|
|
2870
|
+
atCellStart = true;
|
|
2871
|
+
} else {
|
|
2872
|
+
cell += ch;
|
|
2873
|
+
atCellStart = false;
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
if (quoted) {
|
|
2877
|
+
throw new HgiError("invalid_input", "The --ids CSV file has a quoted field that is never closed.", {
|
|
2878
|
+
details: { reason: "bad_csv" }
|
|
2879
|
+
});
|
|
2880
|
+
}
|
|
2881
|
+
if (cell !== "" || record.length > 0) {
|
|
2882
|
+
record.push(cell);
|
|
2883
|
+
records.push(record);
|
|
2884
|
+
}
|
|
2885
|
+
return records;
|
|
2886
|
+
}
|
|
2887
|
+
function parseCsvColumn(text, column) {
|
|
2888
|
+
const [header, ...rows] = parseCsv(text);
|
|
2889
|
+
const names = (header ?? []).map((h) => h.trim());
|
|
2890
|
+
const index = names.indexOf(column.trim());
|
|
2891
|
+
if (index < 0) {
|
|
2892
|
+
throw new HgiError("invalid_input", `The --ids CSV file has no column "${column}".`, {
|
|
2893
|
+
hint: names.length ? `Its columns are: ${names.slice(0, 20).join(", ")}.` : "The file has no header row.",
|
|
2894
|
+
details: { reason: "unknown_column", column, columns: names.slice(0, 50) }
|
|
2895
|
+
});
|
|
2896
|
+
}
|
|
2897
|
+
const out = [];
|
|
2898
|
+
rows.forEach((row, i) => {
|
|
2899
|
+
const value = (row[index] ?? "").trim();
|
|
2900
|
+
if (value !== "") out.push({ text: value, line: i + 2 });
|
|
2901
|
+
});
|
|
2902
|
+
return out;
|
|
2903
|
+
}
|
|
2904
|
+
function classify(text) {
|
|
2905
|
+
return text.includes(".") ? "domain" : "id";
|
|
2906
|
+
}
|
|
2907
|
+
function normalizeId(text) {
|
|
2908
|
+
const lower = text.trim().toLowerCase();
|
|
2909
|
+
const stripped = lower.replace(/^0+/, "");
|
|
2910
|
+
return stripped === "" && lower !== "" ? "0" : stripped;
|
|
2911
|
+
}
|
|
2912
|
+
function normalizeDomain(text) {
|
|
2913
|
+
let s = text.trim().toLowerCase();
|
|
2914
|
+
s = s.replace(/^[a-z][a-z0-9+.-]*:\/\//, "");
|
|
2915
|
+
const cut = s.search(/[/?#]/);
|
|
2916
|
+
if (cut >= 0) s = s.slice(0, cut);
|
|
2917
|
+
if (s.startsWith("www.")) s = s.slice(4);
|
|
2918
|
+
return s;
|
|
2919
|
+
}
|
|
2920
|
+
function normalize(kind, text) {
|
|
2921
|
+
return kind === "id" ? normalizeId(text) : normalizeDomain(text);
|
|
2922
|
+
}
|
|
2923
|
+
|
|
2924
|
+
// src/batch/plan.ts
|
|
2925
|
+
var DEFAULT_BATCH_SIZE = 25;
|
|
2926
|
+
var FIELD_FOR = { id: "hg_ids", domain: "domains" };
|
|
2927
|
+
var ID_MATCH_KEYS = ["company_id", "requested_hg_id", "organization_id"];
|
|
2928
|
+
var DOMAIN_MATCH_KEY = "company_domain";
|
|
2929
|
+
function isRecord(value) {
|
|
2930
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2931
|
+
}
|
|
2932
|
+
function hasType(schema, type) {
|
|
2933
|
+
return schema.type === type || Array.isArray(schema.type) && schema.type.includes(type);
|
|
2934
|
+
}
|
|
2935
|
+
function batchFields(tool) {
|
|
2936
|
+
const props = isRecord(tool.inputSchema.properties) ? tool.inputSchema.properties : {};
|
|
2937
|
+
const fields = {};
|
|
2938
|
+
for (const kind of ["id", "domain"]) {
|
|
2939
|
+
const name = FIELD_FOR[kind];
|
|
2940
|
+
const schema = props[name];
|
|
2941
|
+
if (!isRecord(schema) || !hasType(schema, "array")) continue;
|
|
2942
|
+
if (!("maxItems" in schema)) {
|
|
2943
|
+
fields[kind] = { field: name, max: DEFAULT_BATCH_SIZE };
|
|
2944
|
+
continue;
|
|
2945
|
+
}
|
|
2946
|
+
const declared = schema.maxItems;
|
|
2947
|
+
const usable = typeof declared === "number" && Number.isInteger(declared) && declared >= 1;
|
|
2948
|
+
fields[kind] = usable ? { field: name, max: declared } : { field: name, max: null, declaredMax: declared };
|
|
2949
|
+
}
|
|
2950
|
+
return fields;
|
|
2951
|
+
}
|
|
2952
|
+
function entriesKey(tool) {
|
|
2953
|
+
const props = isRecord(tool.outputSchema?.properties) ? tool.outputSchema.properties : {};
|
|
2954
|
+
const candidates = Object.entries(props).filter(([, schema]) => {
|
|
2955
|
+
if (!isRecord(schema) || !hasType(schema, "array")) return false;
|
|
2956
|
+
const items = schema.items;
|
|
2957
|
+
return isRecord(items) && (hasType(items, "object") || isRecord(items.properties));
|
|
2958
|
+
});
|
|
2959
|
+
return candidates.length === 1 ? candidates[0][0] : "companies";
|
|
2960
|
+
}
|
|
2961
|
+
function buildBatches(input, fields, batchSize) {
|
|
2962
|
+
const uniques = /* @__PURE__ */ new Map();
|
|
2963
|
+
const lines = [];
|
|
2964
|
+
input.forEach((line, position) => {
|
|
2965
|
+
const kind = classify(line.text);
|
|
2966
|
+
const field = fields[kind];
|
|
2967
|
+
if (!field) {
|
|
2968
|
+
const has = Object.values(fields).map((f) => f.field);
|
|
2969
|
+
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.`, {
|
|
2970
|
+
hint: has.length ? `This tool takes: ${has.join(", ")}. Nothing was sent.` : "This tool takes neither hg_ids nor domains. Nothing was sent.",
|
|
2971
|
+
details: { reason: "unsupported_kind", kind, line: line.line, fields: has }
|
|
2972
|
+
});
|
|
2973
|
+
}
|
|
2974
|
+
const norm = normalize(kind, line.text);
|
|
2975
|
+
const key = `${kind}:${norm}`;
|
|
2976
|
+
let unique = uniques.get(key);
|
|
2977
|
+
if (!unique) {
|
|
2978
|
+
unique = { kind, text: line.text, norm, first: position };
|
|
2979
|
+
uniques.set(key, unique);
|
|
2980
|
+
}
|
|
2981
|
+
lines.push({ text: line.text, unique });
|
|
2982
|
+
});
|
|
2983
|
+
const chunks = [];
|
|
2984
|
+
for (const kind of ["id", "domain"]) {
|
|
2985
|
+
const field = fields[kind];
|
|
2986
|
+
const ofKind = [...uniques.values()].filter((u) => u.kind === kind);
|
|
2987
|
+
if (!field || ofKind.length === 0) continue;
|
|
2988
|
+
const max = usableMax(field);
|
|
2989
|
+
if (batchSize !== void 0 && batchSize > max) {
|
|
2990
|
+
throw new HgiError("invalid_input", `--batch-size ${batchSize} is above the tool's limit of ${max} for "${field.field}".`, {
|
|
2991
|
+
hint: "--batch-size can only lower the batch size. Nothing was sent.",
|
|
2992
|
+
details: { reason: "bad_batch_size", field: field.field, max }
|
|
2993
|
+
});
|
|
2994
|
+
}
|
|
2995
|
+
const size = batchSize ?? max;
|
|
2996
|
+
for (let i = 0; i < ofKind.length; i += size) {
|
|
2997
|
+
chunks.push({ kind, field: field.field, items: ofKind.slice(i, i + size) });
|
|
2998
|
+
}
|
|
2999
|
+
}
|
|
3000
|
+
const firstOf = (b) => b.items[0].first;
|
|
3001
|
+
chunks.sort((a, b) => firstOf(a) - firstOf(b));
|
|
3002
|
+
return { batches: chunks, lines };
|
|
3003
|
+
}
|
|
3004
|
+
function usableMax(field) {
|
|
3005
|
+
if (field.max !== null) return field.max;
|
|
3006
|
+
throw new HgiError("invalid_input", `The tool declares an unusable maxItems for "${field.field}", so --ids cannot batch it.`, {
|
|
3007
|
+
hint: "Nothing was sent. Call the tool with --input instead.",
|
|
3008
|
+
details: { reason: "unusable_max_items", field: field.field, max_items: field.declaredMax ?? null }
|
|
3009
|
+
});
|
|
3010
|
+
}
|
|
3011
|
+
function keyText(value) {
|
|
3012
|
+
if (typeof value === "string") return value;
|
|
3013
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
3014
|
+
return null;
|
|
3015
|
+
}
|
|
3016
|
+
function matchEntries(kind, value, key) {
|
|
3017
|
+
if (!isRecord(value) || !Array.isArray(value[key])) return null;
|
|
3018
|
+
const index = /* @__PURE__ */ new Map();
|
|
3019
|
+
for (const entry of value[key]) {
|
|
3020
|
+
if (!isRecord(entry)) continue;
|
|
3021
|
+
let raw = null;
|
|
3022
|
+
if (kind === "id") {
|
|
3023
|
+
for (const k of ID_MATCH_KEYS) {
|
|
3024
|
+
raw = keyText(entry[k]);
|
|
3025
|
+
if (raw !== null) break;
|
|
3026
|
+
}
|
|
3027
|
+
} else {
|
|
3028
|
+
raw = keyText(entry[DOMAIN_MATCH_KEY]);
|
|
3029
|
+
}
|
|
3030
|
+
if (raw === null) continue;
|
|
3031
|
+
const norm = normalize(kind, raw);
|
|
3032
|
+
if (!index.has(norm)) index.set(norm, entry);
|
|
3033
|
+
}
|
|
3034
|
+
return index;
|
|
3035
|
+
}
|
|
3036
|
+
|
|
3037
|
+
// src/commands/io.ts
|
|
3038
|
+
async function readStdin() {
|
|
3039
|
+
const chunks = [];
|
|
3040
|
+
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
|
3041
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
3042
|
+
}
|
|
3043
|
+
function stderrWantsJson() {
|
|
3044
|
+
return !process.stderr.isTTY || process.argv.includes("--json-errors");
|
|
3045
|
+
}
|
|
3046
|
+
function reportCredit(cost) {
|
|
3047
|
+
process.stderr.write(stderrWantsJson() ? `${JSON.stringify({ credit_cost: cost })}
|
|
3048
|
+
` : `credit_cost: ${cost ?? "unknown"}
|
|
3049
|
+
`);
|
|
3050
|
+
}
|
|
3051
|
+
|
|
3052
|
+
// src/commands/batch.ts
|
|
3053
|
+
function usage(message, reason, hint, extra = {}) {
|
|
3054
|
+
return new HgiError("invalid_input", message, { hint, details: { reason, ...extra } });
|
|
3055
|
+
}
|
|
3056
|
+
function preflightBatchFlags(flags) {
|
|
3057
|
+
if (flags.ids === void 0) {
|
|
3058
|
+
if (flags.idsColumn !== void 0) throw usage("--ids-column needs --ids.", "ids_column_without_ids");
|
|
3059
|
+
if (flags.batchSize !== void 0) throw usage("--batch-size needs --ids.", "batch_size_without_ids");
|
|
3060
|
+
return void 0;
|
|
3061
|
+
}
|
|
3062
|
+
if (flags.ids !== "-" && !flags.ids.startsWith("@")) {
|
|
3063
|
+
throw usage("--ids takes @file or - (stdin).", "bad_ids_source", `Did you mean --ids @${flags.ids}?`);
|
|
3064
|
+
}
|
|
3065
|
+
if (flags.ids === "-" && flags.input === "-") {
|
|
3066
|
+
throw usage("--ids - and --input - cannot both read stdin.", "stdin_conflict", "Pass one of them as @file.");
|
|
3067
|
+
}
|
|
3068
|
+
if (flags.batchSize === void 0) return void 0;
|
|
3069
|
+
const raw = flags.batchSize.trim();
|
|
3070
|
+
const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
|
|
3071
|
+
if (!Number.isSafeInteger(n) || n < 1) {
|
|
3072
|
+
throw usage(`--batch-size must be a whole number of at least 1, not "${flags.batchSize}".`, "bad_batch_size");
|
|
3073
|
+
}
|
|
3074
|
+
return n;
|
|
3075
|
+
}
|
|
3076
|
+
async function readIds(flags, input) {
|
|
3077
|
+
for (const field of ["hg_ids", "domains"]) {
|
|
3078
|
+
if (field in input) {
|
|
3079
|
+
throw usage(`--ids builds "${field}" itself; remove it from --input.`, "ids_conflict", void 0, { field });
|
|
3080
|
+
}
|
|
3081
|
+
}
|
|
3082
|
+
const text = flags.ids === "-" ? await readStdin() : readInputFile(flags.ids.slice(1), protectedDirs(), {}, "--ids @file");
|
|
3083
|
+
const lines = flags.idsColumn !== void 0 ? parseCsvColumn(text, flags.idsColumn) : parseIdLines(text);
|
|
3084
|
+
if (lines.length === 0) {
|
|
3085
|
+
throw usage("--ids holds no HG ids or domains (only blank lines or # comments).", "no_ids");
|
|
3086
|
+
}
|
|
3087
|
+
return lines;
|
|
3088
|
+
}
|
|
3089
|
+
function argsFor(input, batch) {
|
|
3090
|
+
return { ...input, [batch.field]: batch.items.map((u) => u.text) };
|
|
3091
|
+
}
|
|
3092
|
+
function stdoutIsTty() {
|
|
3093
|
+
return Boolean(process.stdout.isTTY);
|
|
3094
|
+
}
|
|
3095
|
+
function render2(rows, format) {
|
|
3096
|
+
if (format === "jsonl") return rows.map((r) => `${JSON.stringify(r)}
|
|
3097
|
+
`).join("");
|
|
3098
|
+
return formatValue(rows, format, { pretty: stdoutIsTty() });
|
|
3099
|
+
}
|
|
3100
|
+
var Run = class {
|
|
3101
|
+
constructor(plan, format, streaming) {
|
|
3102
|
+
this.plan = plan;
|
|
3103
|
+
this.format = format;
|
|
3104
|
+
this.streaming = streaming;
|
|
3105
|
+
}
|
|
3106
|
+
plan;
|
|
3107
|
+
format;
|
|
3108
|
+
streaming;
|
|
3109
|
+
outcomes = /* @__PURE__ */ new Map();
|
|
3110
|
+
rows = [];
|
|
3111
|
+
rowErrors = 0;
|
|
3112
|
+
cursor = 0;
|
|
3113
|
+
callsMade = 0;
|
|
3114
|
+
callsWithoutCost = 0;
|
|
3115
|
+
creditSum = 0;
|
|
3116
|
+
failedBatches = 0;
|
|
3117
|
+
/** Emits every row, in input order, whose batch has returned. */
|
|
3118
|
+
async flush(select) {
|
|
3119
|
+
while (this.cursor < this.plan.lines.length) {
|
|
3120
|
+
const line = this.plan.lines[this.cursor];
|
|
3121
|
+
const outcome = this.outcomes.get(line.unique);
|
|
3122
|
+
if (!outcome) return;
|
|
3123
|
+
const row = "result" in outcome ? { input: line.text, result: applySelect(outcome.result, select) } : { input: line.text, error: outcome.error };
|
|
3124
|
+
if ("error" in row) this.rowErrors += 1;
|
|
3125
|
+
this.rows.push(row);
|
|
3126
|
+
this.cursor += 1;
|
|
3127
|
+
if (this.streaming) {
|
|
3128
|
+
const text = `${JSON.stringify(row)}
|
|
3129
|
+
`;
|
|
3130
|
+
await writeStream(process.stdout, stdoutIsTty() ? escapeJsonForTerminal(text) : text);
|
|
3131
|
+
}
|
|
3132
|
+
}
|
|
3133
|
+
}
|
|
3134
|
+
addCost(result) {
|
|
3135
|
+
const cost = result ? creditCostOf(result) : null;
|
|
3136
|
+
if (cost === null) this.callsWithoutCost += 1;
|
|
3137
|
+
else this.creditSum += cost;
|
|
3138
|
+
}
|
|
3139
|
+
creditCost() {
|
|
3140
|
+
return this.callsMade > this.callsWithoutCost ? this.creditSum : null;
|
|
3141
|
+
}
|
|
3142
|
+
failBatch(batch, error) {
|
|
3143
|
+
this.failedBatches += 1;
|
|
3144
|
+
for (const u of batch.items) this.outcomes.set(u, { error });
|
|
3145
|
+
}
|
|
3146
|
+
};
|
|
3147
|
+
function rowError(code, message) {
|
|
3148
|
+
return { code, message: redact(message) };
|
|
3149
|
+
}
|
|
3150
|
+
async function callBatch(run, session, tool, input, batch, key, opts) {
|
|
3151
|
+
const { budget } = opts;
|
|
3152
|
+
run.callsMade += 1;
|
|
3153
|
+
let result;
|
|
3154
|
+
let budgetFailure = null;
|
|
3155
|
+
try {
|
|
3156
|
+
result = await session.callTool(tool.name, argsFor(input, batch));
|
|
3157
|
+
run.addCost(result);
|
|
3158
|
+
await opts.onResult?.(result);
|
|
3159
|
+
if (budget) {
|
|
3160
|
+
try {
|
|
3161
|
+
await recordSpend(budget.id, budget.max, creditCostOf(result));
|
|
3162
|
+
} catch (err) {
|
|
3163
|
+
budgetFailure = toHgiError(err);
|
|
3164
|
+
}
|
|
3165
|
+
}
|
|
3166
|
+
const outcome = interpretResult(result, tool.name);
|
|
3167
|
+
const index = matchEntries(batch.kind, outcome.value, key);
|
|
3168
|
+
if (!index) {
|
|
3169
|
+
run.failBatch(batch, rowError("unexpected_response", `The response has no "${key}" array to match inputs against.`));
|
|
3170
|
+
return budgetFailure;
|
|
3171
|
+
}
|
|
3172
|
+
for (const u of batch.items) {
|
|
3173
|
+
const entry = index.get(u.norm);
|
|
3174
|
+
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.`) });
|
|
3175
|
+
}
|
|
3176
|
+
} catch (raw) {
|
|
3177
|
+
if (!result) run.addCost(void 0);
|
|
3178
|
+
const err = toHgiError(raw);
|
|
3179
|
+
if (err.code !== "tool_error" || err.details?.outcome_unknown === true) {
|
|
3180
|
+
if (budgetFailure) throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, budget_write_failed: true }, cause: err });
|
|
3181
|
+
throw err;
|
|
3182
|
+
}
|
|
3183
|
+
run.failBatch(batch, rowError(err.code, err.message));
|
|
3184
|
+
}
|
|
3185
|
+
return budgetFailure;
|
|
3186
|
+
}
|
|
3187
|
+
async function checkBatchBudget(budget, run) {
|
|
3188
|
+
try {
|
|
3189
|
+
await checkBudget(budget.id, budget.max);
|
|
3190
|
+
} catch (raw) {
|
|
3191
|
+
const err = toHgiError(raw);
|
|
3192
|
+
if (err.code !== "budget_exceeded") throw err;
|
|
3193
|
+
throw new HgiError(err.code, err.message, {
|
|
3194
|
+
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.`,
|
|
3195
|
+
details: err.details,
|
|
3196
|
+
cause: err
|
|
3197
|
+
});
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
3200
|
+
function printMeta(run) {
|
|
3201
|
+
process.stderr.write(
|
|
3202
|
+
`${JSON.stringify({
|
|
3203
|
+
calls: run.callsMade,
|
|
3204
|
+
rows: run.rows.length,
|
|
3205
|
+
row_errors: run.rowErrors,
|
|
3206
|
+
credit_cost: run.creditCost(),
|
|
3207
|
+
calls_without_cost: run.callsWithoutCost
|
|
3208
|
+
})}
|
|
3209
|
+
`
|
|
3210
|
+
);
|
|
3211
|
+
}
|
|
3212
|
+
async function writeBuffered(run, opts) {
|
|
3213
|
+
if (run.streaming) return {};
|
|
3214
|
+
const text = render2(run.rows, run.format);
|
|
3215
|
+
if (!opts.out) {
|
|
3216
|
+
await emitText(text, run.format);
|
|
3217
|
+
return {};
|
|
3218
|
+
}
|
|
3219
|
+
try {
|
|
3220
|
+
await emitText(text, run.format, { out: opts.out });
|
|
3221
|
+
return {};
|
|
3222
|
+
} catch (err) {
|
|
3223
|
+
const outError = toHgiError(err);
|
|
3224
|
+
const note2 = `hgi: could not write ${opts.out} (${String(outError.details?.reason ?? outError.code)}); the rows were printed to stdout instead.`;
|
|
3225
|
+
process.stderr.write(`${sanitizeForTerminal(redact(note2))}
|
|
3226
|
+
`);
|
|
3227
|
+
try {
|
|
3228
|
+
await emitText(text, run.format);
|
|
3229
|
+
} catch {
|
|
3230
|
+
}
|
|
3231
|
+
return { outError };
|
|
3232
|
+
}
|
|
3233
|
+
}
|
|
3234
|
+
function withProgress(details, run, extra = {}) {
|
|
3235
|
+
return { ...details, rows_emitted: run.rows.length, calls_made: run.callsMade, ...extra };
|
|
3236
|
+
}
|
|
3237
|
+
async function runBatch(session, tool, input, lines, opts) {
|
|
3238
|
+
const plan = buildBatches(lines, batchFields(tool), opts.batchSize);
|
|
3239
|
+
if (opts.validate) {
|
|
3240
|
+
plan.batches.forEach((batch, i) => {
|
|
3241
|
+
try {
|
|
3242
|
+
assertValidInput(tool, argsFor(input, batch));
|
|
3243
|
+
} catch (err) {
|
|
3244
|
+
const e = toHgiError(err);
|
|
3245
|
+
throw new HgiError(e.code, `Batch ${i + 1} of ${plan.batches.length}: ${e.message}`, {
|
|
3246
|
+
hint: `${e.hint ?? ""} Nothing was sent.`.trim(),
|
|
3247
|
+
details: { ...e.details, batch: i + 1 }
|
|
3248
|
+
});
|
|
3249
|
+
}
|
|
3250
|
+
});
|
|
3251
|
+
}
|
|
3252
|
+
const format = opts.format ? parseFormat(opts.format) : "jsonl";
|
|
3253
|
+
const run = new Run(plan, format, format === "jsonl" && !opts.out);
|
|
3254
|
+
const key = entriesKey(tool);
|
|
3255
|
+
try {
|
|
3256
|
+
for (const [i, batch] of plan.batches.entries()) {
|
|
3257
|
+
if (opts.budget && i > 0) await checkBatchBudget(opts.budget, run);
|
|
3258
|
+
if (process.stderr.isTTY) process.stderr.write(`hgi: batch ${i + 1}/${plan.batches.length}
|
|
3259
|
+
`);
|
|
3260
|
+
const budgetFailure = await callBatch(run, session, tool, input, batch, key, opts);
|
|
3261
|
+
await run.flush(opts.select);
|
|
3262
|
+
if (budgetFailure) {
|
|
3263
|
+
throw new HgiError("local_state_error", `The batch call ran, but ${budgetFailure.message.replace(/^Could not/, "hgi could not")}`, {
|
|
3264
|
+
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`.",
|
|
3265
|
+
details: { kind: "budget_write_failed", tool_ran: true },
|
|
3266
|
+
cause: budgetFailure
|
|
3267
|
+
});
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
} catch (raw) {
|
|
3271
|
+
const err = toHgiError(raw);
|
|
3272
|
+
let outFailed = false;
|
|
3273
|
+
try {
|
|
3274
|
+
outFailed = (await writeBuffered(run, opts)).outError !== void 0;
|
|
3275
|
+
} catch {
|
|
3276
|
+
}
|
|
3277
|
+
reportCredit(run.creditCost());
|
|
3278
|
+
if (opts.meta) printMeta(run);
|
|
3279
|
+
throw new HgiError(err.code, err.message, {
|
|
3280
|
+
hint: err.hint,
|
|
3281
|
+
details: withProgress(err.details, run, outFailed ? { out_write_failed: true } : {}),
|
|
3282
|
+
cause: err
|
|
3283
|
+
});
|
|
3284
|
+
}
|
|
3285
|
+
let outError;
|
|
3286
|
+
try {
|
|
3287
|
+
({ outError } = await writeBuffered(run, opts));
|
|
3288
|
+
} finally {
|
|
3289
|
+
reportCredit(run.creditCost());
|
|
3290
|
+
if (opts.meta) printMeta(run);
|
|
3291
|
+
}
|
|
3292
|
+
if (outError) {
|
|
3293
|
+
throw new HgiError("local_state_error", `The batch ran, but its rows could not be written to ${opts.out}: ${outError.message}`, {
|
|
3294
|
+
hint: "Every call already ran and was billed; the rows were printed to stdout instead. Do NOT re-run it.",
|
|
3295
|
+
details: { kind: "write_failed", reason: outError.details?.reason ?? outError.code, tool_ran: true, ...withProgress(void 0, run) },
|
|
3296
|
+
cause: outError
|
|
3297
|
+
});
|
|
3298
|
+
}
|
|
3299
|
+
if (run.failedBatches > 0) {
|
|
3300
|
+
throw new HgiError("tool_error", `${run.failedBatches} of ${plan.batches.length} batch calls failed; their rows carry the error.`, {
|
|
3301
|
+
hint: "Every other row was printed. Re-run only the inputs whose rows have an error.",
|
|
3302
|
+
details: withProgress({ failed_batches: run.failedBatches }, run)
|
|
3303
|
+
});
|
|
3304
|
+
}
|
|
3305
|
+
}
|
|
3306
|
+
|
|
2244
3307
|
// src/commands/invoke.ts
|
|
2245
3308
|
function parseTimeoutMs(raw) {
|
|
2246
3309
|
const seconds = Number(raw);
|
|
@@ -2251,11 +3314,6 @@ function parseTimeoutMs(raw) {
|
|
|
2251
3314
|
}
|
|
2252
3315
|
return seconds * 1e3;
|
|
2253
3316
|
}
|
|
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
3317
|
async function readInput(raw) {
|
|
2260
3318
|
if (raw === void 0) return {};
|
|
2261
3319
|
let text = raw;
|
|
@@ -2279,12 +3337,6 @@ function suggest(name, tools) {
|
|
|
2279
3337
|
const needle = name.toLowerCase();
|
|
2280
3338
|
return tools.map((t) => t.name).filter((n) => n.toLowerCase().includes(needle) || needle.includes(n.toLowerCase())).slice(0, 5);
|
|
2281
3339
|
}
|
|
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
3340
|
function assertVerb(requested, tool) {
|
|
2289
3341
|
const expected = verbFor(tool);
|
|
2290
3342
|
if (requested === expected) return;
|
|
@@ -2294,13 +3346,45 @@ function assertVerb(requested, tool) {
|
|
|
2294
3346
|
details: { tool: tool.name, expected_verb: expected, requested_verb: requested }
|
|
2295
3347
|
});
|
|
2296
3348
|
}
|
|
3349
|
+
async function failAfterBudgetWrite(cause, value, opts, creditCost) {
|
|
3350
|
+
try {
|
|
3351
|
+
await emit(value, { format: opts.format });
|
|
3352
|
+
} catch {
|
|
3353
|
+
} finally {
|
|
3354
|
+
reportCredit(creditCost);
|
|
3355
|
+
}
|
|
3356
|
+
throw new HgiError("local_state_error", `The tool ran, but ${cause.message.replace(/^Could not/, "hgi could not")}`, {
|
|
3357
|
+
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`.",
|
|
3358
|
+
details: { kind: "budget_write_failed", tool_ran: true },
|
|
3359
|
+
cause
|
|
3360
|
+
});
|
|
3361
|
+
}
|
|
2297
3362
|
async function runInvoke(verb, toolName, opts, cmd) {
|
|
3363
|
+
const batchSize = preflightBatchFlags(opts);
|
|
2298
3364
|
const input = await readInput(opts.input);
|
|
2299
3365
|
preflightOutput({ format: opts.format, select: opts.select, out: opts.out, force: opts.force, allowForce: verb === "run" });
|
|
2300
3366
|
const timeoutMs = parseTimeoutMs(opts.timeout);
|
|
3367
|
+
const label = parseLabel(opts.label);
|
|
3368
|
+
const ledger = ledgerPath();
|
|
3369
|
+
const ids = opts.ids === void 0 ? void 0 : await readIds({ ...opts, ids: opts.ids }, input);
|
|
3370
|
+
const maxCredits = verb === "call" ? resolveMaxCredits(opts.maxCredits) : null;
|
|
3371
|
+
const budgetId2 = maxCredits === null ? null : resolveBudgetId();
|
|
3372
|
+
if (budgetId2 !== null && maxCredits !== null) await checkBudget(budgetId2, maxCredits);
|
|
2301
3373
|
const ctx = buildContext(cmd);
|
|
2302
3374
|
const creds = ctx.tokens.loadCredentials();
|
|
2303
3375
|
const session = await openSession(ctx, { timeoutMs });
|
|
3376
|
+
const recordUsage = (result) => recordCall(ledger, {
|
|
3377
|
+
v: 1,
|
|
3378
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3379
|
+
host: new URL(ctx.base).host,
|
|
3380
|
+
verb,
|
|
3381
|
+
tool: toolName,
|
|
3382
|
+
label,
|
|
3383
|
+
credit_cost: creditCostOf(result),
|
|
3384
|
+
budget_id: budgetId(),
|
|
3385
|
+
mcp_version: session.state.mcpVersion,
|
|
3386
|
+
status: result.isError ? "tool_error" : "ok"
|
|
3387
|
+
});
|
|
2304
3388
|
try {
|
|
2305
3389
|
const tools = await session.listTools();
|
|
2306
3390
|
writeToolsCache(toolsCachePath(...mcpCacheKey(ctx.base, creds)), {
|
|
@@ -2318,11 +3402,42 @@ async function runInvoke(verb, toolName, opts, cmd) {
|
|
|
2318
3402
|
});
|
|
2319
3403
|
}
|
|
2320
3404
|
assertVerb(verb, tool);
|
|
3405
|
+
if (ids) {
|
|
3406
|
+
await runBatch(session, tool, input, ids, {
|
|
3407
|
+
batchSize,
|
|
3408
|
+
format: opts.format,
|
|
3409
|
+
select: opts.select,
|
|
3410
|
+
out: opts.out,
|
|
3411
|
+
meta: opts.meta,
|
|
3412
|
+
validate: opts.validate,
|
|
3413
|
+
budget: budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : void 0,
|
|
3414
|
+
onResult: recordUsage
|
|
3415
|
+
});
|
|
3416
|
+
return;
|
|
3417
|
+
}
|
|
2321
3418
|
if (opts.validate) assertValidInput(tool, input);
|
|
2322
3419
|
const result = await session.callTool(toolName, input);
|
|
2323
|
-
|
|
3420
|
+
await recordUsage(result);
|
|
3421
|
+
let budgetFailure = null;
|
|
3422
|
+
if (budgetId2 !== null && maxCredits !== null) {
|
|
3423
|
+
try {
|
|
3424
|
+
await recordSpend(budgetId2, maxCredits, creditCostOf(result));
|
|
3425
|
+
} catch (err) {
|
|
3426
|
+
budgetFailure = toHgiError(err);
|
|
3427
|
+
}
|
|
3428
|
+
}
|
|
3429
|
+
let outcome;
|
|
3430
|
+
try {
|
|
3431
|
+
outcome = interpretResult(result, toolName);
|
|
3432
|
+
} catch (err) {
|
|
3433
|
+
if (budgetFailure && err instanceof HgiError) {
|
|
3434
|
+
throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, budget_write_failed: true }, cause: err });
|
|
3435
|
+
}
|
|
3436
|
+
throw err;
|
|
3437
|
+
}
|
|
2324
3438
|
const selected = applySelect(outcome.value, opts.select);
|
|
2325
3439
|
const value = opts.meta ? { result: selected, credit_cost: outcome.creditCost, mcp_version: session.state.mcpVersion } : selected;
|
|
3440
|
+
if (budgetFailure) await failAfterBudgetWrite(budgetFailure, value, opts, outcome.creditCost);
|
|
2326
3441
|
try {
|
|
2327
3442
|
await emit(value, {
|
|
2328
3443
|
format: opts.format,
|
|
@@ -2355,33 +3470,47 @@ function registerInvokeCommands(program) {
|
|
|
2355
3470
|
run: "Run a tool that changes state or starts work. Fails for read-only tools."
|
|
2356
3471
|
};
|
|
2357
3472
|
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())
|
|
3473
|
+
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} instead of the bare result").option("--label <label>", "tag this call in the local credit ledger (see `hgi usage --by label`)").option("--timeout <seconds>", "per-request timeout", "120").addOption(new Option("--no-validate", "skip client-side schema validation (let the server judge the input)").hideHelp());
|
|
3474
|
+
if (verb === "call") {
|
|
3475
|
+
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)").addHelpText(
|
|
3476
|
+
"after",
|
|
3477
|
+
[
|
|
3478
|
+
"",
|
|
3479
|
+
"Run cap (client-side, on top of the server limits):",
|
|
3480
|
+
" --max-credits <n> / HGI_MAX_CREDITS refuse the call, sending nothing (exit 13), once this run has spent n credits",
|
|
3481
|
+
" HGI_BUDGET_ID the run to count against (default: the parent process id, so one shell or script)",
|
|
3482
|
+
" `hgi budget status` shows the spend; `hgi budget reset` starts it over.",
|
|
3483
|
+
" With --ids, every batch call is checked and counted."
|
|
3484
|
+
].join("\n")
|
|
3485
|
+
);
|
|
3486
|
+
}
|
|
3487
|
+
cmd.action((tool, opts, c) => runInvoke(verb, tool, opts, c));
|
|
2359
3488
|
}
|
|
2360
3489
|
}
|
|
2361
3490
|
|
|
2362
3491
|
// src/commands/skill.ts
|
|
2363
|
-
import
|
|
3492
|
+
import fs8 from "fs";
|
|
2364
3493
|
import os2 from "os";
|
|
2365
|
-
import
|
|
3494
|
+
import path7 from "path";
|
|
2366
3495
|
|
|
2367
3496
|
// 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';
|
|
3497
|
+
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 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## 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- Paging and batching are manual for now: a hand-written page loop and sorted id batches, as below.\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 sorted batch of `hg_ids`, filtered (`vendor_names`, `product_names` or `category_ids`) so pages stay small. Page with `offset`. Stop on a short page (fewer rows than `max_results`), once `total_installs_count` is reached, or at the schema\'s `offset` maximum. Don\'t stop on `has_more` alone: it can be wrong at page boundaries. At the `offset` maximum, report the result as partial and narrow the filter.\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# technographics page loop (needs jq); page size and offset maximum come from the schema\ndir=$(mktemp -d) # a fresh directory per run, so concurrent runs never share files\nschema=$(hgi tools list --json | jq \'.tools[] | select(.name=="company_technographic") | .input_schema.properties\')\nmax=$(jq \'.max_results.maximum\' <<<"$schema"); maxoff=$(jq \'.offset.maximum\' <<<"$schema")\nids=\'["<id1>","<id2>"]\'; off=0 # one sorted batch of at most hg_ids.maxItems ids\nwhile [ "$ids" != "[]" ]; do\n if [ "$off" -gt "$maxoff" ]; then echo "partial: offset maximum reached for $ids" >&2; break; fi\n hgi call company_technographic --input "{\\"hg_ids\\":$ids,\\"vendor_names\\":[\\"<vendor>\\"],\\"max_results\\":$max,\\"offset\\":$off}" -f json > "$dir/tech-$off.json" || break\n # next page only for companies that filled this page and are short of their stated total, sorted\n ids=$(jq -c --argjson max "$max" --argjson off "$off" \'[.companies[] | select(.installs_count == $max and $off + $max < .total_installs_count) | .company_id] | sort\' "$dir/tech-$off.json")\n off=$((off + max))\ndone\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. Page with `max_results` and `offset` only when `all_count` exceeds the rows returned, with the same stop rule as technographics.\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 | wait `retry_after_seconds` from the error, then retry |\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 never retries it itself |\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| 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
3498
|
|
|
2370
3499
|
// src/commands/skill.ts
|
|
2371
3500
|
function defaultSkillsDir() {
|
|
2372
|
-
const claude = process.env.CLAUDE_CONFIG_DIR ??
|
|
2373
|
-
return
|
|
3501
|
+
const claude = process.env.CLAUDE_CONFIG_DIR ?? path7.join(os2.homedir(), ".claude");
|
|
3502
|
+
return path7.join(claude, "skills");
|
|
2374
3503
|
}
|
|
2375
3504
|
function refuse2(message, reason) {
|
|
2376
3505
|
return new HgiError("invalid_input", message, { details: { reason } });
|
|
2377
3506
|
}
|
|
2378
3507
|
function installSkill(opts) {
|
|
2379
|
-
const skillsDir =
|
|
2380
|
-
const targetDir =
|
|
2381
|
-
const target =
|
|
3508
|
+
const skillsDir = path7.resolve(opts.dir ?? defaultSkillsDir());
|
|
3509
|
+
const targetDir = path7.join(skillsDir, "hgi");
|
|
3510
|
+
const target = path7.join(targetDir, "SKILL.md");
|
|
2382
3511
|
for (const guarded of [skillsDir, targetDir]) {
|
|
2383
3512
|
try {
|
|
2384
|
-
const st =
|
|
3513
|
+
const st = fs8.lstatSync(guarded);
|
|
2385
3514
|
if (st.isSymbolicLink()) throw refuse2(`Refusing to install through the symlink ${guarded}.`, "symlink");
|
|
2386
3515
|
if (!st.isDirectory()) throw refuse2(`${guarded} is not a directory.`, "not_a_directory");
|
|
2387
3516
|
} catch (err) {
|
|
@@ -2389,24 +3518,24 @@ function installSkill(opts) {
|
|
|
2389
3518
|
if (err.code !== "ENOENT") throw err;
|
|
2390
3519
|
}
|
|
2391
3520
|
}
|
|
2392
|
-
|
|
3521
|
+
fs8.mkdirSync(targetDir, { recursive: true });
|
|
2393
3522
|
let existing = null;
|
|
2394
3523
|
try {
|
|
2395
|
-
existing =
|
|
3524
|
+
existing = fs8.lstatSync(target);
|
|
2396
3525
|
} catch {
|
|
2397
3526
|
existing = null;
|
|
2398
3527
|
}
|
|
2399
3528
|
if (existing) {
|
|
2400
3529
|
if (existing.isSymbolicLink() || !existing.isFile()) throw refuse2(`${target} is not a regular file.`, "not_regular_file");
|
|
2401
|
-
if (
|
|
3530
|
+
if (fs8.readFileSync(target, "utf8") === SKILL_MD) return { path: target, result: "unchanged" };
|
|
2402
3531
|
if (!opts.force) {
|
|
2403
3532
|
throw refuse2(`${target} already exists and differs.`, "exists");
|
|
2404
3533
|
}
|
|
2405
|
-
|
|
2406
|
-
|
|
3534
|
+
fs8.unlinkSync(target);
|
|
3535
|
+
fs8.writeFileSync(target, SKILL_MD, { flag: "wx", mode: 420 });
|
|
2407
3536
|
return { path: target, result: "replaced" };
|
|
2408
3537
|
}
|
|
2409
|
-
|
|
3538
|
+
fs8.writeFileSync(target, SKILL_MD, { flag: "wx", mode: 420 });
|
|
2410
3539
|
return { path: target, result: "installed" };
|
|
2411
3540
|
}
|
|
2412
3541
|
function registerSkillCommands(program) {
|
|
@@ -2416,6 +3545,58 @@ function registerSkillCommands(program) {
|
|
|
2416
3545
|
});
|
|
2417
3546
|
}
|
|
2418
3547
|
|
|
3548
|
+
// src/commands/usage.ts
|
|
3549
|
+
var LOCAL_ONLY_NOTICE = "Local to this machine: calls made by hgi here, not your organization's bill.";
|
|
3550
|
+
var ZERO_COST_CELL = "0 (server cache or free tool)";
|
|
3551
|
+
var TABLE_FOOTNOTE = [
|
|
3552
|
+
"zero_cost_calls: calls the server reported as costing 0 credits (a server-side cache hit or a free tool).",
|
|
3553
|
+
"unknown_cost_calls: calls whose cost the server did not report; they are not counted in credits."
|
|
3554
|
+
].join("\n");
|
|
3555
|
+
function forTable(rows) {
|
|
3556
|
+
return rows.map((row) => {
|
|
3557
|
+
const out = { ...row };
|
|
3558
|
+
if (out.credit_cost === 0) out.credit_cost = ZERO_COST_CELL;
|
|
3559
|
+
if (out.credits === 0 && typeof out.zero_cost_calls === "number" && out.zero_cost_calls > 0) out.credits = ZERO_COST_CELL;
|
|
3560
|
+
if ("label" in out && out.label === null) out.label = "(none)";
|
|
3561
|
+
return out;
|
|
3562
|
+
});
|
|
3563
|
+
}
|
|
3564
|
+
function note(text) {
|
|
3565
|
+
process.stderr.write(`${text}
|
|
3566
|
+
`);
|
|
3567
|
+
}
|
|
3568
|
+
function registerUsageCommands(program) {
|
|
3569
|
+
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) => {
|
|
3570
|
+
const by = parseBy(opts.by);
|
|
3571
|
+
const since = opts.since === void 0 ? null : parseSince(opts.since);
|
|
3572
|
+
preflightOutput({ format: opts.format, select: opts.select, out: opts.out });
|
|
3573
|
+
const globals = cmd.optsWithGlobals();
|
|
3574
|
+
setDebug(Boolean(globals.debug) || process.env.HGI_DEBUG === "1");
|
|
3575
|
+
const host = new URL(resolveBaseUrl(globals.baseUrl ?? process.env.HGI_BASE_URL)).host;
|
|
3576
|
+
const file = ledgerPath();
|
|
3577
|
+
const format = opts.format ? parseFormat(opts.format) : defaultFormat(Boolean(process.stdout.isTTY));
|
|
3578
|
+
note(LOCAL_ONLY_NOTICE);
|
|
3579
|
+
let rows = [];
|
|
3580
|
+
if (file === null) {
|
|
3581
|
+
note("hgi: the credit ledger is disabled (HGI_LEDGER=off); nothing is recorded on this machine.");
|
|
3582
|
+
} else {
|
|
3583
|
+
const read = readLedger(file);
|
|
3584
|
+
if (read.status === "missing") {
|
|
3585
|
+
note("hgi: nothing has been recorded on this machine yet.");
|
|
3586
|
+
} else {
|
|
3587
|
+
if (read.malformed > 0) {
|
|
3588
|
+
note(`hgi: warning: skipped ${read.malformed} malformed ledger line${read.malformed === 1 ? "" : "s"}.`);
|
|
3589
|
+
}
|
|
3590
|
+
if (read.rows.length === 0 && read.malformed === 0) note("hgi: nothing has been recorded on this machine yet.");
|
|
3591
|
+
rows = filterRows(read.rows, host, since);
|
|
3592
|
+
}
|
|
3593
|
+
}
|
|
3594
|
+
const value = by === "call" ? rows.map((r) => ({ ...r })) : summarize2(rows, by);
|
|
3595
|
+
await emit(format === "table" ? forTable(value) : value, { format, select: opts.select, out: opts.out });
|
|
3596
|
+
if (format === "table") note(TABLE_FOOTNOTE);
|
|
3597
|
+
});
|
|
3598
|
+
}
|
|
3599
|
+
|
|
2419
3600
|
// src/cli.ts
|
|
2420
3601
|
function buildProgram() {
|
|
2421
3602
|
const program = new Command();
|
|
@@ -2423,6 +3604,8 @@ function buildProgram() {
|
|
|
2423
3604
|
registerAuthCommands(program);
|
|
2424
3605
|
registerToolsCommands(program);
|
|
2425
3606
|
registerInvokeCommands(program);
|
|
3607
|
+
registerUsageCommands(program);
|
|
3608
|
+
registerBudgetCommands(program);
|
|
2426
3609
|
registerSkillCommands(program);
|
|
2427
3610
|
return program;
|
|
2428
3611
|
}
|