@hginsights/hgi 0.0.0 → 0.1.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +139 -2
- package/dist/bin.js +2461 -0
- package/docs/compatibility.md +48 -0
- package/docs/exit-codes.md +49 -0
- package/docs/oss-approval.md +35 -0
- package/docs/output-formats.md +56 -0
- package/docs/releasing.md +100 -0
- package/docs/security.md +52 -0
- package/npm-shrinkwrap.json +4701 -0
- package/package.json +58 -4
- package/skills/hgi/SKILL.md +67 -0
package/dist/bin.js
ADDED
|
@@ -0,0 +1,2461 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { Command, CommanderError } from "commander";
|
|
5
|
+
|
|
6
|
+
// src/config.ts
|
|
7
|
+
import { spawnSync } from "child_process";
|
|
8
|
+
import fs from "fs";
|
|
9
|
+
import os from "os";
|
|
10
|
+
import path from "path";
|
|
11
|
+
|
|
12
|
+
// src/output/sanitize.ts
|
|
13
|
+
function isBidi(code) {
|
|
14
|
+
return code === 1564 || code === 8203 || code >= 8206 && code <= 8207 || code === 8232 || code === 8233 || code >= 8234 && code <= 8238 || code >= 8288 && code <= 8292 || code >= 8294 && code <= 8297 || code === 65279;
|
|
15
|
+
}
|
|
16
|
+
function isC1(code) {
|
|
17
|
+
return code >= 127 && code <= 159;
|
|
18
|
+
}
|
|
19
|
+
function visible(code) {
|
|
20
|
+
return code <= 255 ? `\\x${code.toString(16).padStart(2, "0")}` : `\\u${code.toString(16).padStart(4, "0")}`;
|
|
21
|
+
}
|
|
22
|
+
function sanitizeForTerminal(text) {
|
|
23
|
+
let out = "";
|
|
24
|
+
const chars = [...text];
|
|
25
|
+
for (let i = 0; i < chars.length; i += 1) {
|
|
26
|
+
const ch = chars[i];
|
|
27
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
28
|
+
if (code === 13) {
|
|
29
|
+
out += chars[i + 1] === "\n" ? ch : visible(code);
|
|
30
|
+
} else if (code === 9 || code === 10) {
|
|
31
|
+
out += ch;
|
|
32
|
+
} else if (code <= 31 || isC1(code) || isBidi(code)) {
|
|
33
|
+
out += visible(code);
|
|
34
|
+
} else {
|
|
35
|
+
out += ch;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
function escapeJsonForTerminal(text) {
|
|
41
|
+
let out = "";
|
|
42
|
+
for (const ch of text) {
|
|
43
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
44
|
+
out += isC1(code) || isBidi(code) ? `\\u${code.toString(16).padStart(4, "0")}` : ch;
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/redact.ts
|
|
50
|
+
var secrets = /* @__PURE__ */ new Set();
|
|
51
|
+
var MIN_SECRET_LENGTH = 8;
|
|
52
|
+
var MASK = "[REDACTED]";
|
|
53
|
+
var PATTERNS = [
|
|
54
|
+
[/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, `Bearer ${MASK}`],
|
|
55
|
+
[
|
|
56
|
+
/("?(?:access_token|refresh_token|code_verifier|client_secret)"?\s*[:=]\s*)("[^"]*"|[^\s&,}]+)/gi,
|
|
57
|
+
`$1"${MASK}"`
|
|
58
|
+
],
|
|
59
|
+
[/([?&](?:code|code_verifier|access_token|refresh_token)=)[^&\s"']+/gi, `$1${MASK}`]
|
|
60
|
+
];
|
|
61
|
+
function registerSecret(value) {
|
|
62
|
+
if (value && value.length >= MIN_SECRET_LENGTH) secrets.add(value);
|
|
63
|
+
}
|
|
64
|
+
function redact(text) {
|
|
65
|
+
let out = text;
|
|
66
|
+
for (const secret of secrets) {
|
|
67
|
+
out = out.split(secret).join(MASK);
|
|
68
|
+
}
|
|
69
|
+
for (const [pattern, replacement] of PATTERNS) {
|
|
70
|
+
out = out.replace(pattern, replacement);
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
function redactDeep(value) {
|
|
75
|
+
if (typeof value === "string") return redact(value);
|
|
76
|
+
if (Array.isArray(value)) return value.map((v) => redactDeep(v));
|
|
77
|
+
if (value && typeof value === "object") {
|
|
78
|
+
const out = {};
|
|
79
|
+
for (const [k, v] of Object.entries(value)) {
|
|
80
|
+
out[k] = redactDeep(v);
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/errors.ts
|
|
88
|
+
var EXIT = {
|
|
89
|
+
OK: 0,
|
|
90
|
+
INTERNAL: 1,
|
|
91
|
+
INVALID_INPUT: 2,
|
|
92
|
+
TOOL_ERROR: 3,
|
|
93
|
+
LOGIN: 4,
|
|
94
|
+
RATE_LIMITED: 5,
|
|
95
|
+
CREDIT: 6,
|
|
96
|
+
UNREACHABLE: 7,
|
|
97
|
+
OAUTH: 8,
|
|
98
|
+
NETWORK: 9,
|
|
99
|
+
WRONG_VERB: 10,
|
|
100
|
+
FORBIDDEN: 11,
|
|
101
|
+
LOCAL_STATE: 12
|
|
102
|
+
};
|
|
103
|
+
var ERROR_EXIT = {
|
|
104
|
+
internal_error: EXIT.INTERNAL,
|
|
105
|
+
invalid_input: EXIT.INVALID_INPUT,
|
|
106
|
+
tool_error: EXIT.TOOL_ERROR,
|
|
107
|
+
login_required: EXIT.LOGIN,
|
|
108
|
+
login_expired: EXIT.LOGIN,
|
|
109
|
+
rate_limited: EXIT.RATE_LIMITED,
|
|
110
|
+
credit_limit_exceeded: EXIT.CREDIT,
|
|
111
|
+
server_unreachable: EXIT.UNREACHABLE,
|
|
112
|
+
oauth_error: EXIT.OAUTH,
|
|
113
|
+
network_proxy_tls: EXIT.NETWORK,
|
|
114
|
+
wrong_verb: EXIT.WRONG_VERB,
|
|
115
|
+
forbidden: EXIT.FORBIDDEN,
|
|
116
|
+
local_state_error: EXIT.LOCAL_STATE
|
|
117
|
+
};
|
|
118
|
+
var LOGIN_HINT = "Run `hgi auth login` to sign in again.";
|
|
119
|
+
var HgiError = class extends Error {
|
|
120
|
+
code;
|
|
121
|
+
hint;
|
|
122
|
+
details;
|
|
123
|
+
constructor(code, message, init = {}) {
|
|
124
|
+
super(message, init.cause === void 0 ? void 0 : { cause: init.cause });
|
|
125
|
+
this.name = "HgiError";
|
|
126
|
+
this.code = code;
|
|
127
|
+
this.hint = init.hint;
|
|
128
|
+
this.details = init.details;
|
|
129
|
+
}
|
|
130
|
+
get exitCode() {
|
|
131
|
+
return ERROR_EXIT[this.code];
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
function toErrorBody(err) {
|
|
135
|
+
const body = {
|
|
136
|
+
schema: 1,
|
|
137
|
+
error: {
|
|
138
|
+
code: err.code,
|
|
139
|
+
exit_code: err.exitCode,
|
|
140
|
+
message: err.message
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
if (err.hint) body.error.hint = err.hint;
|
|
144
|
+
if (err.details && Object.keys(err.details).length > 0) body.error.details = err.details;
|
|
145
|
+
return redactDeep(body);
|
|
146
|
+
}
|
|
147
|
+
function renderError(err, asJson) {
|
|
148
|
+
const body = toErrorBody(err);
|
|
149
|
+
if (asJson) return `${escapeJsonForTerminal(JSON.stringify(body))}
|
|
150
|
+
`;
|
|
151
|
+
const lines = [`hgi: ${body.error.message}`];
|
|
152
|
+
if (body.error.hint) lines.push(` ${body.error.hint}`);
|
|
153
|
+
return `${sanitizeForTerminal(redact(lines.join("\n")))}
|
|
154
|
+
`;
|
|
155
|
+
}
|
|
156
|
+
function toHgiError(err) {
|
|
157
|
+
if (err instanceof HgiError) return err;
|
|
158
|
+
const net = classifyNetworkError(err);
|
|
159
|
+
if (net) return net;
|
|
160
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
161
|
+
return new HgiError("internal_error", `Unexpected error: ${message}`, {
|
|
162
|
+
hint: "This is a bug in hgi. Re-run with --debug and report it.",
|
|
163
|
+
cause: err
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
var TLS_CODES = /* @__PURE__ */ new Set([
|
|
167
|
+
"CERT_HAS_EXPIRED",
|
|
168
|
+
"CERT_NOT_YET_VALID",
|
|
169
|
+
"CERT_UNTRUSTED",
|
|
170
|
+
"CERT_REVOKED",
|
|
171
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
172
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
173
|
+
"UNABLE_TO_GET_ISSUER_CERT",
|
|
174
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
175
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
176
|
+
"ERR_TLS_CERT_ALTNAME_INVALID",
|
|
177
|
+
"ERR_SSL_WRONG_VERSION_NUMBER",
|
|
178
|
+
"EPROTO"
|
|
179
|
+
]);
|
|
180
|
+
var PROXY_CODES = /* @__PURE__ */ new Set([
|
|
181
|
+
"UND_ERR_PRX_TLS",
|
|
182
|
+
"ERR_PROXY_CONNECT",
|
|
183
|
+
"UND_ERR_PROXY_INFO"
|
|
184
|
+
]);
|
|
185
|
+
var UNREACHABLE_CODES = /* @__PURE__ */ new Set([
|
|
186
|
+
"ENOTFOUND",
|
|
187
|
+
"EAI_AGAIN",
|
|
188
|
+
"ECONNREFUSED",
|
|
189
|
+
"ECONNRESET",
|
|
190
|
+
"ETIMEDOUT",
|
|
191
|
+
"EHOSTUNREACH",
|
|
192
|
+
"ENETUNREACH",
|
|
193
|
+
"EPIPE",
|
|
194
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
195
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
196
|
+
"UND_ERR_BODY_TIMEOUT",
|
|
197
|
+
"UND_ERR_SOCKET",
|
|
198
|
+
"UND_ERR_ABORTED"
|
|
199
|
+
]);
|
|
200
|
+
function causeChain(err) {
|
|
201
|
+
const chain = [];
|
|
202
|
+
let cur = err;
|
|
203
|
+
for (let i = 0; i < 6 && cur; i += 1) {
|
|
204
|
+
chain.push(cur);
|
|
205
|
+
cur = cur.cause;
|
|
206
|
+
}
|
|
207
|
+
return chain;
|
|
208
|
+
}
|
|
209
|
+
function networkErrorCode(err) {
|
|
210
|
+
for (const link of causeChain(err)) {
|
|
211
|
+
const code = link.code;
|
|
212
|
+
if (typeof code === "string") return code;
|
|
213
|
+
}
|
|
214
|
+
return void 0;
|
|
215
|
+
}
|
|
216
|
+
function classifyNetworkError(err, context = "the server", viaProxy) {
|
|
217
|
+
const code = networkErrorCode(err);
|
|
218
|
+
const chainText = causeChain(err).map((l) => l instanceof Error ? l.message : "").join(" ");
|
|
219
|
+
const proxyMentioned = /proxy/i.test(chainText);
|
|
220
|
+
if (code && PROXY_CODES.has(code)) {
|
|
221
|
+
return new HgiError("network_proxy_tls", `Proxy problem reaching ${context} (${code}).`, {
|
|
222
|
+
hint: "Check HTTPS_PROXY / HTTP_PROXY / NO_PROXY and your proxy credentials.",
|
|
223
|
+
details: { cause: code },
|
|
224
|
+
cause: err
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
if (code && TLS_CODES.has(code)) {
|
|
228
|
+
return new HgiError("network_proxy_tls", `TLS verification failed for ${context} (${code}).`, {
|
|
229
|
+
hint: "If a corporate proxy re-signs traffic, point NODE_EXTRA_CA_CERTS at its CA bundle.",
|
|
230
|
+
details: { cause: code },
|
|
231
|
+
cause: err
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
if (viaProxy && code && UNREACHABLE_CODES.has(code)) {
|
|
235
|
+
return new HgiError("network_proxy_tls", `Could not connect through the proxy ${viaProxy} (${code}).`, {
|
|
236
|
+
hint: "Check HTTPS_PROXY / HTTP_PROXY / NO_PROXY, that the proxy is reachable, and your proxy credentials.",
|
|
237
|
+
details: { cause: code, proxy: viaProxy },
|
|
238
|
+
cause: err
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
if (proxyMentioned) {
|
|
242
|
+
return new HgiError("network_proxy_tls", `Proxy problem reaching ${context}.`, {
|
|
243
|
+
hint: "Check HTTPS_PROXY / HTTP_PROXY / NO_PROXY and your proxy credentials.",
|
|
244
|
+
details: code ? { cause: code } : void 0,
|
|
245
|
+
cause: err
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
if (code && UNREACHABLE_CODES.has(code)) {
|
|
249
|
+
return new HgiError("server_unreachable", `Could not reach ${context} (${code}).`, {
|
|
250
|
+
hint: "Check your network connection and HGI_BASE_URL, then retry.",
|
|
251
|
+
details: { cause: code },
|
|
252
|
+
cause: err
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
if (err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) {
|
|
256
|
+
return new HgiError("server_unreachable", `Timed out talking to ${context}.`, {
|
|
257
|
+
hint: "Retry, or raise --timeout.",
|
|
258
|
+
details: { cause: err.name },
|
|
259
|
+
cause: err
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
if (err instanceof TypeError && /fetch failed/i.test(err.message)) {
|
|
263
|
+
return new HgiError("server_unreachable", `Could not reach ${context}.`, {
|
|
264
|
+
hint: "Check your network connection and HGI_BASE_URL, then retry.",
|
|
265
|
+
cause: err
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// src/config.ts
|
|
272
|
+
var VERSION = true ? "0.1.0-rc.2" : "0.0.0-dev";
|
|
273
|
+
var DEFAULT_BASE_URL = "https://phoenix.hginsights.com";
|
|
274
|
+
var MCP_PATH = "/api/ai/mcp";
|
|
275
|
+
var SCOPE = "mcp:read mcp:tools offline_access";
|
|
276
|
+
var LOOPBACK_REDIRECT_HOST = "localhost";
|
|
277
|
+
var USER_AGENT = `hgi/${VERSION}`;
|
|
278
|
+
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
|
|
279
|
+
function resolveBaseUrl(raw) {
|
|
280
|
+
const value = (raw ?? "").trim() || DEFAULT_BASE_URL;
|
|
281
|
+
let url;
|
|
282
|
+
try {
|
|
283
|
+
url = new URL(value);
|
|
284
|
+
} catch {
|
|
285
|
+
throw new HgiError("invalid_input", `Invalid base URL: ${value}`, {
|
|
286
|
+
hint: "Set HGI_BASE_URL to an origin such as https://phoenix.hginsights.com.",
|
|
287
|
+
details: { reason: "invalid_base_url" }
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
const loopback = LOOPBACK_HOSTS.has(url.hostname);
|
|
291
|
+
const httpsOk = url.protocol === "https:";
|
|
292
|
+
const httpLoopbackOk = url.protocol === "http:" && loopback;
|
|
293
|
+
if (!httpsOk && !httpLoopbackOk) {
|
|
294
|
+
throw new HgiError("invalid_input", `Base URL must use https (got ${url.protocol}//).`, {
|
|
295
|
+
hint: "Plain http is only allowed for loopback hosts used in tests.",
|
|
296
|
+
details: { reason: "insecure_base_url" }
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
if (url.username || url.password || url.search || url.hash || url.pathname !== "/" && url.pathname !== "") {
|
|
300
|
+
throw new HgiError("invalid_input", "Base URL must be an origin with no path, query or credentials.", {
|
|
301
|
+
details: { reason: "invalid_base_url" }
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
return url.origin;
|
|
305
|
+
}
|
|
306
|
+
function mcpUrl(base) {
|
|
307
|
+
return `${base}${MCP_PATH}`;
|
|
308
|
+
}
|
|
309
|
+
function clientId(base) {
|
|
310
|
+
return `${base}/.well-known/oauth-clients/hgi-cli.json`;
|
|
311
|
+
}
|
|
312
|
+
function hostSlug(base) {
|
|
313
|
+
const url = new URL(base);
|
|
314
|
+
const host = url.hostname.replace(/[^a-z0-9.-]/gi, "_").toLowerCase();
|
|
315
|
+
return url.port ? `${host}-${url.port}` : host;
|
|
316
|
+
}
|
|
317
|
+
function realpathDeep(target) {
|
|
318
|
+
const resolved = path.resolve(target);
|
|
319
|
+
const rest = [];
|
|
320
|
+
let cur = resolved;
|
|
321
|
+
for (; ; ) {
|
|
322
|
+
try {
|
|
323
|
+
const real = fs.realpathSync(cur);
|
|
324
|
+
return path.join(real, ...rest.reverse());
|
|
325
|
+
} catch {
|
|
326
|
+
const parent = path.dirname(cur);
|
|
327
|
+
if (parent === cur) return resolved;
|
|
328
|
+
rest.push(path.basename(cur));
|
|
329
|
+
cur = parent;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function isInside(child, parent) {
|
|
334
|
+
const rel = path.relative(parent, child);
|
|
335
|
+
return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
336
|
+
}
|
|
337
|
+
function isInsideByInode(child, parent) {
|
|
338
|
+
let parentStat;
|
|
339
|
+
try {
|
|
340
|
+
parentStat = fs.statSync(parent);
|
|
341
|
+
} catch {
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
let cur = path.resolve(child);
|
|
345
|
+
for (; ; ) {
|
|
346
|
+
try {
|
|
347
|
+
const st = fs.statSync(cur);
|
|
348
|
+
if (st.ino === parentStat.ino && st.dev === parentStat.dev) return true;
|
|
349
|
+
} catch {
|
|
350
|
+
}
|
|
351
|
+
const up = path.dirname(cur);
|
|
352
|
+
if (up === cur) return false;
|
|
353
|
+
cur = up;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function workspaceRoot() {
|
|
357
|
+
const home = realpathDeep(os.homedir());
|
|
358
|
+
const res = spawnSync("git", ["rev-parse", "--show-toplevel"], {
|
|
359
|
+
encoding: "utf8",
|
|
360
|
+
timeout: 2e3
|
|
361
|
+
});
|
|
362
|
+
if (res.status !== 0 || !res.stdout) return null;
|
|
363
|
+
const top = realpathDeep(res.stdout.trim());
|
|
364
|
+
if (top === home || top === path.parse(top).root) return null;
|
|
365
|
+
return top;
|
|
366
|
+
}
|
|
367
|
+
function guardOverride(dir, label) {
|
|
368
|
+
const resolved = realpathDeep(dir);
|
|
369
|
+
const root = workspaceRoot();
|
|
370
|
+
if (root && (isInside(resolved, root) || isInsideByInode(resolved, root))) {
|
|
371
|
+
throw new HgiError("invalid_input", `${label} must not be inside a workspace (${root}).`, {
|
|
372
|
+
hint: "Credentials and caches never live in a project directory; choose a path outside it.",
|
|
373
|
+
details: { reason: "workspace_guard" }
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
return path.resolve(dir);
|
|
377
|
+
}
|
|
378
|
+
function configDir(env = process.env) {
|
|
379
|
+
if (env.HGI_CONFIG_DIR) return guardOverride(env.HGI_CONFIG_DIR, "HGI_CONFIG_DIR");
|
|
380
|
+
if (env.XDG_CONFIG_HOME) return guardOverride(path.join(env.XDG_CONFIG_HOME, "hgi"), "XDG_CONFIG_HOME");
|
|
381
|
+
return path.join(os.homedir(), ".config", "hgi");
|
|
382
|
+
}
|
|
383
|
+
function cacheDir(env = process.env) {
|
|
384
|
+
if (env.HGI_CACHE_DIR) return guardOverride(env.HGI_CACHE_DIR, "HGI_CACHE_DIR");
|
|
385
|
+
if (env.XDG_CACHE_HOME) return guardOverride(path.join(env.XDG_CACHE_HOME, "hgi"), "XDG_CACHE_HOME");
|
|
386
|
+
return path.join(os.homedir(), ".cache", "hgi");
|
|
387
|
+
}
|
|
388
|
+
function credentialsPath(base, env = process.env) {
|
|
389
|
+
return path.join(configDir(env), `credentials-${hostSlug(base)}.json`);
|
|
390
|
+
}
|
|
391
|
+
function protectedDirs(env = process.env) {
|
|
392
|
+
return [realpathDeep(configDir(env)), realpathDeep(cacheDir(env))];
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// src/debug.ts
|
|
396
|
+
var enabled = false;
|
|
397
|
+
function setDebug(on) {
|
|
398
|
+
enabled = on;
|
|
399
|
+
}
|
|
400
|
+
function debug(...parts) {
|
|
401
|
+
if (!enabled) return;
|
|
402
|
+
const text = parts.map((p) => typeof p === "string" ? p : p instanceof Error ? p.stack ?? p.message : safeStringify(p)).join(" ");
|
|
403
|
+
process.stderr.write(`hgi[debug] ${redact(text)}
|
|
404
|
+
`);
|
|
405
|
+
}
|
|
406
|
+
function safeStringify(value) {
|
|
407
|
+
try {
|
|
408
|
+
return JSON.stringify(value);
|
|
409
|
+
} catch {
|
|
410
|
+
return String(value);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// src/http.ts
|
|
415
|
+
import { EnvHttpProxyAgent, Headers as UndiciHeaders, fetch as undiciFetch } from "undici";
|
|
416
|
+
var agent;
|
|
417
|
+
function dispatcher() {
|
|
418
|
+
agent ??= new EnvHttpProxyAgent();
|
|
419
|
+
return agent;
|
|
420
|
+
}
|
|
421
|
+
var DEFAULT_TIMEOUT_MS = 15e3;
|
|
422
|
+
function proxyFor(target, env = process.env) {
|
|
423
|
+
const url = new URL(target);
|
|
424
|
+
const noProxy = (env.NO_PROXY ?? env.no_proxy ?? "").split(",").map((h) => h.trim().toLowerCase()).filter(Boolean);
|
|
425
|
+
const host = url.hostname.toLowerCase();
|
|
426
|
+
if (noProxy.some((h) => h === "*" || host === h || host.endsWith(h.startsWith(".") ? h : `.${h}`))) return void 0;
|
|
427
|
+
const raw = url.protocol === "https:" ? env.HTTPS_PROXY ?? env.https_proxy ?? env.HTTP_PROXY ?? env.http_proxy : env.HTTP_PROXY ?? env.http_proxy;
|
|
428
|
+
if (!raw) return void 0;
|
|
429
|
+
try {
|
|
430
|
+
return new URL(raw).host;
|
|
431
|
+
} catch {
|
|
432
|
+
return raw;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
async function httpRequest(url, init = {}, opts = {}) {
|
|
436
|
+
const headers = new UndiciHeaders(init.headers);
|
|
437
|
+
headers.set("User-Agent", USER_AGENT);
|
|
438
|
+
const timeout = AbortSignal.timeout(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
439
|
+
const callerSignals = [opts.signal, init.signal].filter((x) => Boolean(x));
|
|
440
|
+
const signal = callerSignals.length ? AbortSignal.any([timeout, ...callerSignals]) : timeout;
|
|
441
|
+
const target = String(url);
|
|
442
|
+
debug("http", init.method ?? "GET", target);
|
|
443
|
+
let res;
|
|
444
|
+
try {
|
|
445
|
+
res = await undiciFetch(target, {
|
|
446
|
+
...init,
|
|
447
|
+
headers,
|
|
448
|
+
redirect: "manual",
|
|
449
|
+
dispatcher: dispatcher(),
|
|
450
|
+
signal
|
|
451
|
+
});
|
|
452
|
+
} catch (err) {
|
|
453
|
+
throw classifyNetworkError(err, opts.context ?? new URL(target).host, proxyFor(target)) ?? toHgiError(err);
|
|
454
|
+
}
|
|
455
|
+
debug("http ->", res.status, target);
|
|
456
|
+
if (res.status >= 300 && res.status < 400) {
|
|
457
|
+
const location = res.headers.get("location");
|
|
458
|
+
let host = "unknown host";
|
|
459
|
+
try {
|
|
460
|
+
if (location) host = new URL(location, target).host;
|
|
461
|
+
} catch {
|
|
462
|
+
}
|
|
463
|
+
await res.body?.cancel().catch(() => void 0);
|
|
464
|
+
const message = `Unexpected redirect (${res.status}) from ${new URL(target).host} to ${host}.`;
|
|
465
|
+
if (opts.redirectKind === "mcp") {
|
|
466
|
+
throw new HgiError("server_unreachable", message, {
|
|
467
|
+
hint: "Check HGI_BASE_URL points at the canonical host (https://phoenix.hginsights.com).",
|
|
468
|
+
details: { status: res.status, location_host: host }
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
throw new HgiError("oauth_error", message, {
|
|
472
|
+
hint: "hgi never follows redirects on auth requests. Check HGI_BASE_URL.",
|
|
473
|
+
details: { status: res.status, location_host: host }
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
return res;
|
|
477
|
+
}
|
|
478
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
479
|
+
if (!value) return void 0;
|
|
480
|
+
const secs = Number(value);
|
|
481
|
+
if (Number.isFinite(secs) && secs >= 0) return secs;
|
|
482
|
+
const when = Date.parse(value);
|
|
483
|
+
if (Number.isFinite(when)) return Math.max(0, Math.ceil((when - now) / 1e3));
|
|
484
|
+
return void 0;
|
|
485
|
+
}
|
|
486
|
+
function sleep(ms, signal) {
|
|
487
|
+
return new Promise((resolve, reject) => {
|
|
488
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
489
|
+
const timer = setTimeout(() => {
|
|
490
|
+
signal?.removeEventListener("abort", onAbort);
|
|
491
|
+
resolve();
|
|
492
|
+
}, ms);
|
|
493
|
+
const onAbort = () => {
|
|
494
|
+
clearTimeout(timer);
|
|
495
|
+
reject(signal?.reason);
|
|
496
|
+
};
|
|
497
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
async function closeHttp() {
|
|
501
|
+
if (agent) {
|
|
502
|
+
await agent.close().catch(() => void 0);
|
|
503
|
+
agent = void 0;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// src/auth/oauth-client.ts
|
|
508
|
+
var ENDPOINT_KEYS = ["authorization_endpoint", "token_endpoint", "revocation_endpoint", "userinfo_endpoint"];
|
|
509
|
+
function normalizeIssuer(value) {
|
|
510
|
+
return value.trim().replace(/\/+$/, "").toLowerCase();
|
|
511
|
+
}
|
|
512
|
+
async function readJson(res) {
|
|
513
|
+
try {
|
|
514
|
+
const text = await res.text();
|
|
515
|
+
const parsed = JSON.parse(text);
|
|
516
|
+
return typeof parsed === "object" && parsed !== null ? parsed : null;
|
|
517
|
+
} catch {
|
|
518
|
+
return null;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
async function discover(base) {
|
|
522
|
+
const res = await httpRequest(`${base}/.well-known/oauth-authorization-server`, {}, {
|
|
523
|
+
redirectKind: "oauth",
|
|
524
|
+
context: new URL(base).host
|
|
525
|
+
});
|
|
526
|
+
if (res.status !== 200) {
|
|
527
|
+
await res.body?.cancel().catch(() => void 0);
|
|
528
|
+
throw new HgiError("oauth_error", `OAuth discovery failed (HTTP ${res.status}).`, {
|
|
529
|
+
hint: "Check HGI_BASE_URL.",
|
|
530
|
+
details: { status: res.status }
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
const body = await readJson(res);
|
|
534
|
+
if (!body || typeof body.issuer !== "string") {
|
|
535
|
+
throw new HgiError("oauth_error", "OAuth discovery returned an unexpected document.", {
|
|
536
|
+
details: { reason: "bad_metadata" }
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
if (normalizeIssuer(body.issuer) !== normalizeIssuer(base)) {
|
|
540
|
+
throw new HgiError("oauth_error", `OAuth issuer ${body.issuer} does not match ${base}.`, {
|
|
541
|
+
hint: "A host the server does not recognise reports its default URL as issuer. Use the canonical host.",
|
|
542
|
+
details: { reason: "issuer_mismatch" }
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
const meta = {};
|
|
546
|
+
for (const key of ENDPOINT_KEYS) {
|
|
547
|
+
const value = body[key];
|
|
548
|
+
if (typeof value !== "string") {
|
|
549
|
+
throw new HgiError("oauth_error", `OAuth discovery is missing ${key}.`, { details: { reason: "bad_metadata" } });
|
|
550
|
+
}
|
|
551
|
+
let origin;
|
|
552
|
+
try {
|
|
553
|
+
origin = new URL(value).origin;
|
|
554
|
+
} catch {
|
|
555
|
+
throw new HgiError("oauth_error", `OAuth discovery has an invalid ${key}.`, { details: { reason: "bad_metadata" } });
|
|
556
|
+
}
|
|
557
|
+
if (origin !== new URL(base).origin) {
|
|
558
|
+
throw new HgiError("oauth_error", `OAuth ${key} points at a different origin (${origin}); refusing to send tokens there.`, {
|
|
559
|
+
details: { reason: "cross_origin_endpoint" }
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
meta[key] = value;
|
|
563
|
+
}
|
|
564
|
+
return { issuer: body.issuer, ...meta };
|
|
565
|
+
}
|
|
566
|
+
function buildAuthorizeUrl(meta, base, args) {
|
|
567
|
+
const url = new URL(meta.authorization_endpoint);
|
|
568
|
+
url.searchParams.set("response_type", "code");
|
|
569
|
+
url.searchParams.set("client_id", clientId(base));
|
|
570
|
+
url.searchParams.set("redirect_uri", args.redirectUri);
|
|
571
|
+
url.searchParams.set("scope", SCOPE);
|
|
572
|
+
url.searchParams.set("state", args.state);
|
|
573
|
+
url.searchParams.set("code_challenge", args.challenge);
|
|
574
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
575
|
+
return url.toString();
|
|
576
|
+
}
|
|
577
|
+
function describe(body) {
|
|
578
|
+
const error = typeof body?.error === "string" ? body.error : void 0;
|
|
579
|
+
const description = typeof body?.error_description === "string" ? body.error_description : void 0;
|
|
580
|
+
return [error, description].filter(Boolean).join(": ");
|
|
581
|
+
}
|
|
582
|
+
async function tokenRequest(meta, grant, params, now) {
|
|
583
|
+
const form = new URLSearchParams({ grant_type: grant, ...params }).toString();
|
|
584
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
585
|
+
const res = await httpRequest(
|
|
586
|
+
meta.token_endpoint,
|
|
587
|
+
{
|
|
588
|
+
method: "POST",
|
|
589
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
590
|
+
body: form
|
|
591
|
+
},
|
|
592
|
+
{ redirectKind: "oauth", context: "the token endpoint" }
|
|
593
|
+
);
|
|
594
|
+
const receivedAt = now();
|
|
595
|
+
if (res.ok) {
|
|
596
|
+
const body2 = await readJson(res);
|
|
597
|
+
const access = body2?.access_token;
|
|
598
|
+
const refresh = body2?.refresh_token;
|
|
599
|
+
const expires = body2?.expires_in;
|
|
600
|
+
if (typeof access !== "string" || typeof refresh !== "string" || typeof expires !== "number") {
|
|
601
|
+
throw new HgiError("oauth_error", "The token endpoint returned an unexpected response.", {
|
|
602
|
+
details: { reason: "bad_token_response" }
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
registerSecret(access);
|
|
606
|
+
registerSecret(refresh);
|
|
607
|
+
return {
|
|
608
|
+
accessToken: access,
|
|
609
|
+
refreshToken: refresh,
|
|
610
|
+
expiresIn: expires,
|
|
611
|
+
scope: typeof body2?.scope === "string" ? body2.scope : "",
|
|
612
|
+
receivedAt
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
const body = await readJson(res);
|
|
616
|
+
const error = typeof body?.error === "string" ? body.error : void 0;
|
|
617
|
+
debug("token endpoint error", res.status, error);
|
|
618
|
+
if (res.status === 429) {
|
|
619
|
+
const retry = parseRetryAfter(res.headers.get("retry-after"));
|
|
620
|
+
throw new HgiError("rate_limited", "The token endpoint is rate limiting requests.", {
|
|
621
|
+
hint: "Wait and retry.",
|
|
622
|
+
details: retry === void 0 ? void 0 : { retry_after_seconds: retry }
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
if (error === "invalid_grant") {
|
|
626
|
+
if (grant === "refresh_token") {
|
|
627
|
+
throw new HgiError("login_expired", "Your login has expired or was revoked.", {
|
|
628
|
+
hint: LOGIN_HINT,
|
|
629
|
+
details: { reason: "invalid_grant" }
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
throw new HgiError("oauth_error", `Sign-in code was rejected: ${describe(body) || "invalid_grant"}.`, {
|
|
633
|
+
hint: "Run `hgi auth login` again; authorization codes work once.",
|
|
634
|
+
details: { reason: "invalid_grant" }
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
const transient = res.status >= 500 || error === "server_error" || res.status === 401 && error === "invalid_client";
|
|
638
|
+
if (transient && attempt === 0) {
|
|
639
|
+
await sleep(1e3);
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
if (transient) {
|
|
643
|
+
throw new HgiError(
|
|
644
|
+
res.status >= 500 ? "server_unreachable" : "oauth_error",
|
|
645
|
+
`The token endpoint is failing temporarily (HTTP ${res.status}${error ? `, ${error}` : ""}).`,
|
|
646
|
+
{ hint: "Your credentials were kept. Try again in a moment.", details: { status: res.status } }
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
throw new HgiError("oauth_error", `The token endpoint rejected the request (HTTP ${res.status}): ${describe(body) || "no detail"}.`, {
|
|
650
|
+
details: { status: res.status, ...error ? { reason: error } : {} }
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
function exchangeCode(meta, base, args, now = Date.now) {
|
|
655
|
+
return tokenRequest(
|
|
656
|
+
meta,
|
|
657
|
+
"authorization_code",
|
|
658
|
+
{
|
|
659
|
+
code: args.code,
|
|
660
|
+
code_verifier: args.verifier,
|
|
661
|
+
redirect_uri: args.redirectUri,
|
|
662
|
+
client_id: clientId(base)
|
|
663
|
+
},
|
|
664
|
+
now
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
function refreshTokens(meta, base, refreshToken, now = Date.now) {
|
|
668
|
+
return tokenRequest(meta, "refresh_token", { refresh_token: refreshToken, client_id: clientId(base) }, now);
|
|
669
|
+
}
|
|
670
|
+
async function revokeToken(meta, base, token, hint) {
|
|
671
|
+
const res = await httpRequest(
|
|
672
|
+
meta.revocation_endpoint,
|
|
673
|
+
{
|
|
674
|
+
method: "POST",
|
|
675
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
676
|
+
body: new URLSearchParams({ token, token_type_hint: hint, client_id: clientId(base) }).toString()
|
|
677
|
+
},
|
|
678
|
+
{ redirectKind: "oauth", context: "the revocation endpoint" }
|
|
679
|
+
);
|
|
680
|
+
await res.body?.cancel().catch(() => void 0);
|
|
681
|
+
if (res.ok) return;
|
|
682
|
+
if (res.status === 429) {
|
|
683
|
+
throw new HgiError("rate_limited", "The revocation endpoint is rate limiting requests.", {
|
|
684
|
+
details: { retry_after_seconds: parseRetryAfter(res.headers.get("retry-after")) }
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
throw new HgiError(
|
|
688
|
+
res.status >= 500 ? "server_unreachable" : "oauth_error",
|
|
689
|
+
`Token revocation was not accepted (HTTP ${res.status}).`,
|
|
690
|
+
{ details: { status: res.status } }
|
|
691
|
+
);
|
|
692
|
+
}
|
|
693
|
+
async function getUserinfo(meta, doFetch, onUnauthorized) {
|
|
694
|
+
const res = await doFetch(meta.userinfo_endpoint);
|
|
695
|
+
if (res.status === 200) {
|
|
696
|
+
const body = await readJson(res);
|
|
697
|
+
const user = body?.user;
|
|
698
|
+
const org = body?.organization;
|
|
699
|
+
const client = body?.client;
|
|
700
|
+
if (!user || !org || typeof user.id !== "string" || typeof user.email !== "string" || typeof org.slug !== "string") {
|
|
701
|
+
throw new HgiError("oauth_error", "The userinfo endpoint returned an unexpected response.", {
|
|
702
|
+
details: { reason: "bad_userinfo" }
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
return {
|
|
706
|
+
user: { id: user.id, name: typeof user.name === "string" ? user.name : null, email: user.email },
|
|
707
|
+
organization: { slug: org.slug, name: typeof org.name === "string" ? org.name : org.slug },
|
|
708
|
+
client: {
|
|
709
|
+
id: typeof client?.id === "string" ? client.id : "",
|
|
710
|
+
name: typeof client?.name === "string" ? client.name : null
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
await res.body?.cancel().catch(() => void 0);
|
|
715
|
+
if (res.status === 401) {
|
|
716
|
+
if (onUnauthorized === "login") {
|
|
717
|
+
throw new HgiError("login_expired", "Your login has expired or was revoked.", { hint: LOGIN_HINT });
|
|
718
|
+
}
|
|
719
|
+
throw new HgiError("oauth_error", "The server rejected the freshly issued token.", {
|
|
720
|
+
details: { reason: "userinfo_401" }
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
if (res.status === 403) {
|
|
724
|
+
throw new HgiError("forbidden", "The server refused the userinfo request (HTTP 403).", { details: { status: 403 } });
|
|
725
|
+
}
|
|
726
|
+
if (res.status === 429) {
|
|
727
|
+
throw new HgiError("rate_limited", "The userinfo endpoint is rate limiting requests.", {
|
|
728
|
+
details: { retry_after_seconds: parseRetryAfter(res.headers.get("retry-after")) }
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
throw new HgiError("server_unreachable", `The userinfo endpoint is unavailable (HTTP ${res.status}).`, {
|
|
732
|
+
hint: "Retry in a moment.",
|
|
733
|
+
details: { status: res.status, retry_after_seconds: parseRetryAfter(res.headers.get("retry-after")) }
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
// src/auth/credentials-store.ts
|
|
738
|
+
import fs2 from "fs";
|
|
739
|
+
import path2 from "path";
|
|
740
|
+
import lockfile from "proper-lockfile";
|
|
741
|
+
|
|
742
|
+
// src/auth/pkce.ts
|
|
743
|
+
import { createHash, randomBytes, timingSafeEqual } from "crypto";
|
|
744
|
+
function randomUrlSafe(bytes) {
|
|
745
|
+
return randomBytes(bytes).toString("base64url");
|
|
746
|
+
}
|
|
747
|
+
function challengeS256(verifier) {
|
|
748
|
+
return createHash("sha256").update(verifier).digest("base64url");
|
|
749
|
+
}
|
|
750
|
+
function safeEqual(a, b) {
|
|
751
|
+
const left = Buffer.from(a);
|
|
752
|
+
const right = Buffer.from(b);
|
|
753
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// src/auth/credentials-store.ts
|
|
757
|
+
function unsafe(reason, file) {
|
|
758
|
+
return new HgiError("local_state_error", `Credentials path is unsafe (${reason}): ${file}`, {
|
|
759
|
+
hint: "Remove or fix it yourself; hgi will not follow symlinks or write to non-regular files.",
|
|
760
|
+
details: { kind: "credentials_unsafe", reason }
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
function isCredentials(value) {
|
|
764
|
+
if (typeof value !== "object" || value === null) return false;
|
|
765
|
+
const c = value;
|
|
766
|
+
const user = c.user;
|
|
767
|
+
const org = c.organization;
|
|
768
|
+
return c.version === 1 && typeof c.base_url === "string" && typeof c.client_id === "string" && typeof c.access_token === "string" && typeof c.refresh_token === "string" && typeof c.expires_at === "number" && typeof c.scope === "string" && typeof c.obtained_at === "number" && !!user && typeof user.id === "string" && typeof user.email === "string" && !!org && typeof org.slug === "string" && typeof org.name === "string";
|
|
769
|
+
}
|
|
770
|
+
function ensureDir(dir) {
|
|
771
|
+
let st = null;
|
|
772
|
+
try {
|
|
773
|
+
st = fs2.lstatSync(dir);
|
|
774
|
+
} catch {
|
|
775
|
+
st = null;
|
|
776
|
+
}
|
|
777
|
+
if (st) {
|
|
778
|
+
if (st.isSymbolicLink()) throw unsafe("symlink", dir);
|
|
779
|
+
if (!st.isDirectory()) throw unsafe("not_a_directory", dir);
|
|
780
|
+
if ((st.mode & 63) !== 0) {
|
|
781
|
+
try {
|
|
782
|
+
fs2.chmodSync(dir, 448);
|
|
783
|
+
} catch {
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
try {
|
|
789
|
+
fs2.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
790
|
+
fs2.chmodSync(dir, 448);
|
|
791
|
+
} catch (err) {
|
|
792
|
+
throw new HgiError("local_state_error", `Cannot create ${dir}: ${err.code ?? "error"}.`, {
|
|
793
|
+
details: { kind: "write_failed" },
|
|
794
|
+
cause: err
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
function preflightWritable(file) {
|
|
799
|
+
ensureDir(path2.dirname(file));
|
|
800
|
+
let st = null;
|
|
801
|
+
try {
|
|
802
|
+
st = fs2.lstatSync(file);
|
|
803
|
+
} catch {
|
|
804
|
+
st = null;
|
|
805
|
+
}
|
|
806
|
+
if (st?.isSymbolicLink()) throw unsafe("symlink", file);
|
|
807
|
+
if (st && !st.isFile()) throw unsafe("not_regular_file", file);
|
|
808
|
+
}
|
|
809
|
+
function inspectCredentials(file) {
|
|
810
|
+
let fd;
|
|
811
|
+
try {
|
|
812
|
+
fd = fs2.openSync(file, fs2.constants.O_RDONLY | fs2.constants.O_NOFOLLOW);
|
|
813
|
+
} catch (err) {
|
|
814
|
+
const code = err.code;
|
|
815
|
+
if (code === "ENOENT") return { status: "missing" };
|
|
816
|
+
if (code === "ELOOP") throw unsafe("symlink", file);
|
|
817
|
+
throw new HgiError("local_state_error", `Cannot read ${file}: ${code ?? "error"}.`, {
|
|
818
|
+
details: { kind: "credentials_unsafe", reason: code ?? "read_failed" },
|
|
819
|
+
cause: err
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
try {
|
|
823
|
+
const st = fs2.fstatSync(fd);
|
|
824
|
+
if (!st.isFile()) throw unsafe("not_regular_file", file);
|
|
825
|
+
let parsed;
|
|
826
|
+
try {
|
|
827
|
+
parsed = JSON.parse(fs2.readFileSync(fd, "utf8"));
|
|
828
|
+
} catch {
|
|
829
|
+
return { status: "corrupt" };
|
|
830
|
+
}
|
|
831
|
+
if (!isCredentials(parsed)) return { status: "corrupt" };
|
|
832
|
+
registerSecret(parsed.access_token);
|
|
833
|
+
registerSecret(parsed.refresh_token);
|
|
834
|
+
if ((st.mode & 63) !== 0) return { status: "bad_mode", creds: parsed };
|
|
835
|
+
return { status: "ok", creds: parsed };
|
|
836
|
+
} finally {
|
|
837
|
+
fs2.closeSync(fd);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
function readCredentials(file) {
|
|
841
|
+
const found = inspectCredentials(file);
|
|
842
|
+
switch (found.status) {
|
|
843
|
+
case "missing":
|
|
844
|
+
return null;
|
|
845
|
+
case "ok":
|
|
846
|
+
return found.creds;
|
|
847
|
+
case "corrupt":
|
|
848
|
+
throw new HgiError("local_state_error", `Credentials file is corrupt: ${file}`, {
|
|
849
|
+
hint: `Delete it and run \`hgi auth login\`.`,
|
|
850
|
+
details: { kind: "credentials_corrupt" }
|
|
851
|
+
});
|
|
852
|
+
case "bad_mode":
|
|
853
|
+
throw new HgiError("local_state_error", `Credentials file has unsafe permissions: ${file}`, {
|
|
854
|
+
hint: `Run \`chmod 600 ${file}\`, or \`hgi auth login\` to recreate it.`,
|
|
855
|
+
details: { kind: "credentials_unsafe", reason: "mode" }
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
function writePrivateFile(file, content, hooks = {}) {
|
|
860
|
+
preflightWritable(file);
|
|
861
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
862
|
+
let fd;
|
|
863
|
+
try {
|
|
864
|
+
fd = fs2.openSync(
|
|
865
|
+
tmp,
|
|
866
|
+
fs2.constants.O_CREAT | fs2.constants.O_EXCL | fs2.constants.O_WRONLY | fs2.constants.O_NOFOLLOW,
|
|
867
|
+
384
|
|
868
|
+
);
|
|
869
|
+
fs2.writeFileSync(fd, content);
|
|
870
|
+
fs2.fsyncSync(fd);
|
|
871
|
+
fs2.closeSync(fd);
|
|
872
|
+
fd = void 0;
|
|
873
|
+
hooks.afterTemp?.();
|
|
874
|
+
preflightWritable(file);
|
|
875
|
+
hooks.beforeRename?.();
|
|
876
|
+
fs2.renameSync(tmp, file);
|
|
877
|
+
} catch (err) {
|
|
878
|
+
if (fd !== void 0) {
|
|
879
|
+
try {
|
|
880
|
+
fs2.closeSync(fd);
|
|
881
|
+
} catch {
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
try {
|
|
885
|
+
fs2.unlinkSync(tmp);
|
|
886
|
+
} catch {
|
|
887
|
+
}
|
|
888
|
+
if (err instanceof HgiError) throw err;
|
|
889
|
+
throw new HgiError("local_state_error", `Could not write ${path2.basename(file)}: ${err.code ?? "error"}.`, {
|
|
890
|
+
details: { kind: "write_failed" },
|
|
891
|
+
cause: err
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
function writeCredentials(file, creds, hooks = {}) {
|
|
896
|
+
registerSecret(creds.access_token);
|
|
897
|
+
registerSecret(creds.refresh_token);
|
|
898
|
+
writePrivateFile(file, `${JSON.stringify(creds, null, 2)}
|
|
899
|
+
`, hooks);
|
|
900
|
+
}
|
|
901
|
+
function deleteCredentials(file) {
|
|
902
|
+
try {
|
|
903
|
+
fs2.unlinkSync(file);
|
|
904
|
+
} catch (err) {
|
|
905
|
+
if (err.code !== "ENOENT") throw err;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
var LOCK_OPTIONS = {
|
|
909
|
+
stale: 3e4,
|
|
910
|
+
update: 5e3,
|
|
911
|
+
realpath: false,
|
|
912
|
+
retries: { retries: 60, factor: 1.4, minTimeout: 100, maxTimeout: 1500, randomize: true }
|
|
913
|
+
};
|
|
914
|
+
function stampOwner(ownerPath, nonce) {
|
|
915
|
+
let fd;
|
|
916
|
+
try {
|
|
917
|
+
fd = fs2.openSync(
|
|
918
|
+
ownerPath,
|
|
919
|
+
fs2.constants.O_CREAT | fs2.constants.O_WRONLY | fs2.constants.O_TRUNC | fs2.constants.O_NOFOLLOW | fs2.constants.O_NONBLOCK,
|
|
920
|
+
384
|
|
921
|
+
);
|
|
922
|
+
if (!fs2.fstatSync(fd).isFile()) throw new Error("not a regular file");
|
|
923
|
+
fs2.writeFileSync(fd, nonce);
|
|
924
|
+
} catch (err) {
|
|
925
|
+
throw new HgiError("local_state_error", `Could not stamp the credentials lock (${ownerPath}): ${err.code ?? err.message}.`, {
|
|
926
|
+
hint: `Remove ${ownerPath} if it is not a regular file, then retry.`,
|
|
927
|
+
details: { kind: "lock_timeout" },
|
|
928
|
+
cause: err
|
|
929
|
+
});
|
|
930
|
+
} finally {
|
|
931
|
+
if (fd !== void 0) fs2.closeSync(fd);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
function readOwner(ownerPath) {
|
|
935
|
+
let fd;
|
|
936
|
+
try {
|
|
937
|
+
fd = fs2.openSync(ownerPath, fs2.constants.O_RDONLY | fs2.constants.O_NOFOLLOW | fs2.constants.O_NONBLOCK);
|
|
938
|
+
if (!fs2.fstatSync(fd).isFile()) return null;
|
|
939
|
+
return fs2.readFileSync(fd, "utf8");
|
|
940
|
+
} catch {
|
|
941
|
+
return null;
|
|
942
|
+
} finally {
|
|
943
|
+
if (fd !== void 0) fs2.closeSync(fd);
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
async function withLock(file, fn, timing) {
|
|
947
|
+
ensureDir(path2.dirname(file));
|
|
948
|
+
let compromised;
|
|
949
|
+
let release;
|
|
950
|
+
try {
|
|
951
|
+
release = await lockfile.lock(file, {
|
|
952
|
+
...LOCK_OPTIONS,
|
|
953
|
+
...timing ?? {},
|
|
954
|
+
retries: { ...LOCK_OPTIONS.retries },
|
|
955
|
+
onCompromised: (err) => {
|
|
956
|
+
compromised = err;
|
|
957
|
+
debug("lock compromised", err);
|
|
958
|
+
}
|
|
959
|
+
});
|
|
960
|
+
} catch (err) {
|
|
961
|
+
if (err.code === "ELOCKED") {
|
|
962
|
+
throw new HgiError("local_state_error", "Timed out waiting for another hgi process to finish.", {
|
|
963
|
+
hint: `If no other hgi is running, remove ${file}.lock and retry.`,
|
|
964
|
+
details: { kind: "lock_timeout" },
|
|
965
|
+
cause: err
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
throw new HgiError("local_state_error", `Could not take the credentials lock: ${err.code ?? "error"}.`, {
|
|
969
|
+
details: { kind: "lock_timeout" },
|
|
970
|
+
cause: err
|
|
971
|
+
});
|
|
972
|
+
}
|
|
973
|
+
const ownerPath = `${file}.lock-owner`;
|
|
974
|
+
const nonce = randomUrlSafe(12);
|
|
975
|
+
const lost = (cause) => new HgiError("local_state_error", "The credentials lock was lost while hgi was working (the process stalled for too long).", {
|
|
976
|
+
hint: "Another hgi process may have taken over. Re-run your command.",
|
|
977
|
+
details: { kind: "lock_compromised" },
|
|
978
|
+
cause
|
|
979
|
+
});
|
|
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
|
+
}
|
|
1013
|
+
|
|
1014
|
+
// src/auth/login.ts
|
|
1015
|
+
import { spawn } from "child_process";
|
|
1016
|
+
import readline from "readline";
|
|
1017
|
+
|
|
1018
|
+
// src/auth/callback.ts
|
|
1019
|
+
function evaluateCallbackParams(params, expectedState) {
|
|
1020
|
+
const states = params.getAll("state");
|
|
1021
|
+
const state = states.length === 1 ? states[0] : void 0;
|
|
1022
|
+
if (state === void 0 || !safeEqual(state, expectedState)) {
|
|
1023
|
+
throw new HgiError("oauth_error", "Sign-in response had a missing or mismatched state; it was rejected.", {
|
|
1024
|
+
hint: "Run `hgi auth login` again and use the URL it prints.",
|
|
1025
|
+
details: { reason: "state_mismatch" }
|
|
1026
|
+
});
|
|
1027
|
+
}
|
|
1028
|
+
const error = params.get("error");
|
|
1029
|
+
if (error) {
|
|
1030
|
+
const description = params.get("error_description");
|
|
1031
|
+
throw new HgiError(
|
|
1032
|
+
"oauth_error",
|
|
1033
|
+
error === "access_denied" ? "Sign-in was denied or cancelled." : `Sign-in failed: ${error}${description ? ` (${description})` : ""}.`,
|
|
1034
|
+
{ details: { reason: error } }
|
|
1035
|
+
);
|
|
1036
|
+
}
|
|
1037
|
+
const codes = params.getAll("code");
|
|
1038
|
+
const code = codes.length === 1 ? codes[0] : void 0;
|
|
1039
|
+
if (!code) {
|
|
1040
|
+
throw new HgiError("oauth_error", "Sign-in response did not include exactly one authorization code.", {
|
|
1041
|
+
details: { reason: "missing_code" }
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
registerSecret(code);
|
|
1045
|
+
return code;
|
|
1046
|
+
}
|
|
1047
|
+
function parsePastedCallback(input, expected, used) {
|
|
1048
|
+
if (used.value) {
|
|
1049
|
+
throw new HgiError("oauth_error", "This callback URL was already used.", {
|
|
1050
|
+
details: { reason: "callback_reused" }
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
let url;
|
|
1054
|
+
let want;
|
|
1055
|
+
try {
|
|
1056
|
+
url = new URL(input.trim());
|
|
1057
|
+
want = new URL(expected.redirectUri);
|
|
1058
|
+
} catch {
|
|
1059
|
+
throw new HgiError("oauth_error", "That is not a valid callback URL.", {
|
|
1060
|
+
hint: "Paste the full URL from the browser address bar after approving.",
|
|
1061
|
+
details: { reason: "invalid_url" }
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
if (url.protocol !== want.protocol || url.hostname !== want.hostname || url.port !== want.port || url.pathname !== want.pathname || url.username || url.password) {
|
|
1065
|
+
throw new HgiError("oauth_error", "The pasted URL does not match the redirect URI this login started with.", {
|
|
1066
|
+
hint: `Expected it to start with ${expected.redirectUri}`,
|
|
1067
|
+
details: { reason: "redirect_mismatch" }
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
used.value = true;
|
|
1071
|
+
return evaluateCallbackParams(url.searchParams, expected.state);
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// src/auth/loopback.ts
|
|
1075
|
+
import http from "http";
|
|
1076
|
+
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
|
+
async function startLoopback(opts) {
|
|
1078
|
+
let settle;
|
|
1079
|
+
const result = new Promise((resolve, reject) => {
|
|
1080
|
+
settle = { resolve, reject };
|
|
1081
|
+
});
|
|
1082
|
+
result.catch(() => void 0);
|
|
1083
|
+
let done = false;
|
|
1084
|
+
let port = 0;
|
|
1085
|
+
const server = http.createServer((req, res) => {
|
|
1086
|
+
const respond = (status, title, body) => {
|
|
1087
|
+
res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
1088
|
+
res.end(PAGE(title, body));
|
|
1089
|
+
};
|
|
1090
|
+
if (req.method !== "GET") return respond(405, "Method not allowed", "Only GET is accepted.");
|
|
1091
|
+
const allowedHosts = [`127.0.0.1:${port}`, `${LOOPBACK_REDIRECT_HOST}:${port}`];
|
|
1092
|
+
if (!allowedHosts.includes(req.headers.host ?? "")) return respond(400, "Bad request", "Unexpected Host header.");
|
|
1093
|
+
const url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
|
|
1094
|
+
if (url.pathname !== "/callback") return respond(404, "Not found", "Nothing here.");
|
|
1095
|
+
if (done) return respond(409, "Already used", "This sign-in callback was already handled.");
|
|
1096
|
+
done = true;
|
|
1097
|
+
try {
|
|
1098
|
+
const code = evaluateCallbackParams(url.searchParams, opts.state);
|
|
1099
|
+
respond(200, "Signed in", "You can close this tab and return to your terminal.");
|
|
1100
|
+
settle.resolve(code);
|
|
1101
|
+
} catch (err) {
|
|
1102
|
+
respond(400, "Sign-in failed", "Return to your terminal for details.");
|
|
1103
|
+
settle.reject(err);
|
|
1104
|
+
}
|
|
1105
|
+
setImmediate(() => close());
|
|
1106
|
+
});
|
|
1107
|
+
const timer = setTimeout(() => {
|
|
1108
|
+
if (done) return;
|
|
1109
|
+
done = true;
|
|
1110
|
+
settle.reject(
|
|
1111
|
+
new HgiError("oauth_error", "Timed out waiting for the browser sign-in to finish.", {
|
|
1112
|
+
hint: "Run `hgi auth login` again, or use `--no-browser` on a remote machine.",
|
|
1113
|
+
details: { reason: "login_timeout" }
|
|
1114
|
+
})
|
|
1115
|
+
);
|
|
1116
|
+
close();
|
|
1117
|
+
}, opts.timeoutMs);
|
|
1118
|
+
timer.unref();
|
|
1119
|
+
function close() {
|
|
1120
|
+
clearTimeout(timer);
|
|
1121
|
+
server.close();
|
|
1122
|
+
server.closeAllConnections();
|
|
1123
|
+
}
|
|
1124
|
+
await new Promise((resolve, reject) => {
|
|
1125
|
+
server.once("error", reject);
|
|
1126
|
+
server.listen(0, "127.0.0.1", () => resolve());
|
|
1127
|
+
}).catch((err) => {
|
|
1128
|
+
throw new HgiError("local_state_error", "Could not open a loopback port for the sign-in callback.", {
|
|
1129
|
+
details: { kind: "write_failed" },
|
|
1130
|
+
cause: err
|
|
1131
|
+
});
|
|
1132
|
+
});
|
|
1133
|
+
port = server.address().port;
|
|
1134
|
+
return {
|
|
1135
|
+
port,
|
|
1136
|
+
redirectUri: `http://${LOOPBACK_REDIRECT_HOST}:${port}/callback`,
|
|
1137
|
+
waitForCode: () => result,
|
|
1138
|
+
close
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
// src/auth/token-manager.ts
|
|
1143
|
+
var EXPIRY_MARGIN_MS = 6e4;
|
|
1144
|
+
function computeDeadline(tokens) {
|
|
1145
|
+
return tokens.receivedAt + tokens.expiresIn * 1e3 - EXPIRY_MARGIN_MS;
|
|
1146
|
+
}
|
|
1147
|
+
function loginRequired() {
|
|
1148
|
+
return new HgiError("login_required", "You are not signed in.", { hint: LOGIN_HINT });
|
|
1149
|
+
}
|
|
1150
|
+
var TokenManager = class {
|
|
1151
|
+
base;
|
|
1152
|
+
credPath;
|
|
1153
|
+
now;
|
|
1154
|
+
constructor(opts) {
|
|
1155
|
+
this.base = opts.base;
|
|
1156
|
+
this.credPath = opts.credPath;
|
|
1157
|
+
this.now = opts.now ?? Date.now;
|
|
1158
|
+
}
|
|
1159
|
+
loadCredentials() {
|
|
1160
|
+
const creds = readCredentials(this.credPath);
|
|
1161
|
+
if (!creds) throw loginRequired();
|
|
1162
|
+
if (creds.base_url !== this.base) {
|
|
1163
|
+
throw new HgiError("login_required", `Stored credentials are for ${creds.base_url}, not ${this.base}.`, {
|
|
1164
|
+
hint: LOGIN_HINT
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
return creds;
|
|
1168
|
+
}
|
|
1169
|
+
async getAccessToken() {
|
|
1170
|
+
const creds = this.loadCredentials();
|
|
1171
|
+
if (creds.expires_at > this.now()) return creds.access_token;
|
|
1172
|
+
return this.refreshUnderLock(creds.access_token);
|
|
1173
|
+
}
|
|
1174
|
+
forceRefresh(staleAccessToken) {
|
|
1175
|
+
return this.refreshUnderLock(staleAccessToken);
|
|
1176
|
+
}
|
|
1177
|
+
refreshUnderLock(heldAccessToken) {
|
|
1178
|
+
return withLock(this.credPath, async (lock) => {
|
|
1179
|
+
const onDisk = this.loadCredentials();
|
|
1180
|
+
if (onDisk.access_token !== heldAccessToken && onDisk.expires_at > this.now()) {
|
|
1181
|
+
return onDisk.access_token;
|
|
1182
|
+
}
|
|
1183
|
+
const meta = await discover(this.base);
|
|
1184
|
+
const tokens = await refreshTokens(meta, this.base, onDisk.refresh_token, this.now);
|
|
1185
|
+
const next = {
|
|
1186
|
+
...onDisk,
|
|
1187
|
+
access_token: tokens.accessToken,
|
|
1188
|
+
refresh_token: tokens.refreshToken,
|
|
1189
|
+
expires_at: computeDeadline(tokens),
|
|
1190
|
+
scope: tokens.scope || onDisk.scope,
|
|
1191
|
+
obtained_at: tokens.receivedAt
|
|
1192
|
+
};
|
|
1193
|
+
try {
|
|
1194
|
+
lock.write(next);
|
|
1195
|
+
} catch (err) {
|
|
1196
|
+
if (err instanceof HgiError && err.details?.kind === "lock_compromised") {
|
|
1197
|
+
await revokeToken(meta, this.base, tokens.refreshToken, "refresh_token").catch((e) => debug("orphan revoke failed", e));
|
|
1198
|
+
await revokeToken(meta, this.base, tokens.accessToken, "access_token").catch((e) => debug("orphan revoke failed", e));
|
|
1199
|
+
}
|
|
1200
|
+
throw err;
|
|
1201
|
+
}
|
|
1202
|
+
return next.access_token;
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
};
|
|
1206
|
+
|
|
1207
|
+
// src/auth/login.ts
|
|
1208
|
+
var LOGIN_TIMEOUT_MS = 5 * 6e4;
|
|
1209
|
+
function openBrowser(url) {
|
|
1210
|
+
const custom = process.env.BROWSER;
|
|
1211
|
+
let cmd;
|
|
1212
|
+
let args;
|
|
1213
|
+
if (custom) {
|
|
1214
|
+
[cmd = custom, ...args] = custom.split(/\s+/).filter(Boolean);
|
|
1215
|
+
args.push(url);
|
|
1216
|
+
} else if (process.platform === "darwin") {
|
|
1217
|
+
cmd = "open";
|
|
1218
|
+
args = [url];
|
|
1219
|
+
} else {
|
|
1220
|
+
cmd = "xdg-open";
|
|
1221
|
+
args = [url];
|
|
1222
|
+
}
|
|
1223
|
+
try {
|
|
1224
|
+
const child = spawn(cmd, args, { stdio: "ignore", detached: true });
|
|
1225
|
+
child.on("error", (err) => debug("could not open browser", err.message));
|
|
1226
|
+
child.unref();
|
|
1227
|
+
} catch (err) {
|
|
1228
|
+
debug("could not open browser", err);
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
function readPastedLine(prompt) {
|
|
1232
|
+
const rl = readline.createInterface({ input: process.stdin, terminal: false });
|
|
1233
|
+
process.stderr.write(prompt);
|
|
1234
|
+
let answered = false;
|
|
1235
|
+
return new Promise((resolve, reject) => {
|
|
1236
|
+
rl.once("line", (line) => {
|
|
1237
|
+
answered = true;
|
|
1238
|
+
process.stderr.write("\n");
|
|
1239
|
+
resolve(line);
|
|
1240
|
+
rl.close();
|
|
1241
|
+
});
|
|
1242
|
+
rl.once("close", () => {
|
|
1243
|
+
if (answered) return;
|
|
1244
|
+
process.stderr.write("\n");
|
|
1245
|
+
reject(
|
|
1246
|
+
new HgiError("oauth_error", "No callback URL was provided on stdin.", {
|
|
1247
|
+
details: { reason: "no_callback" }
|
|
1248
|
+
})
|
|
1249
|
+
);
|
|
1250
|
+
});
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
async function userinfoForLogin(meta, accessToken) {
|
|
1254
|
+
const fetchOnce = () => getUserinfo(
|
|
1255
|
+
meta,
|
|
1256
|
+
(url) => httpRequest(url, { headers: { Authorization: `Bearer ${accessToken}` } }, { redirectKind: "oauth", context: "the userinfo endpoint" }),
|
|
1257
|
+
"oauth"
|
|
1258
|
+
);
|
|
1259
|
+
try {
|
|
1260
|
+
return await fetchOnce();
|
|
1261
|
+
} catch (err) {
|
|
1262
|
+
const retry = err instanceof HgiError && err.code === "server_unreachable" ? err.details?.retry_after_seconds : void 0;
|
|
1263
|
+
if (err instanceof HgiError && err.code === "server_unreachable" && err.details?.status === 503) {
|
|
1264
|
+
await sleep(Math.min(typeof retry === "number" ? retry : 5, 5) * 1e3);
|
|
1265
|
+
return fetchOnce();
|
|
1266
|
+
}
|
|
1267
|
+
throw err;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
async function revokePair(meta, base, pair) {
|
|
1271
|
+
try {
|
|
1272
|
+
await revokeToken(meta, base, pair.refreshToken, "refresh_token");
|
|
1273
|
+
await revokeToken(meta, base, pair.accessToken, "access_token");
|
|
1274
|
+
return true;
|
|
1275
|
+
} catch (err) {
|
|
1276
|
+
debug("revoke failed", err);
|
|
1277
|
+
return false;
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
async function login(opts) {
|
|
1281
|
+
const { base, credPath, say: say2 } = opts;
|
|
1282
|
+
preflightWritable(credPath);
|
|
1283
|
+
const meta = await discover(base);
|
|
1284
|
+
const verifier = randomUrlSafe(32);
|
|
1285
|
+
registerSecret(verifier);
|
|
1286
|
+
const state = randomUrlSafe(16);
|
|
1287
|
+
const challenge = challengeS256(verifier);
|
|
1288
|
+
let code;
|
|
1289
|
+
let redirectUri;
|
|
1290
|
+
if (opts.noBrowser) {
|
|
1291
|
+
const port = 49152 + Math.floor(Math.random() * (65535 - 49152));
|
|
1292
|
+
redirectUri = `http://${LOOPBACK_REDIRECT_HOST}:${port}/callback`;
|
|
1293
|
+
const url = buildAuthorizeUrl(meta, base, { redirectUri, state, challenge });
|
|
1294
|
+
say2("Open this URL in a browser on any machine and approve access:");
|
|
1295
|
+
say2(` ${url}`);
|
|
1296
|
+
say2("After approving, the browser will fail to load a http://localhost page. Copy that full URL from the address bar.");
|
|
1297
|
+
const pasted = await readPastedLine("Paste the callback URL: ");
|
|
1298
|
+
code = parsePastedCallback(pasted, { redirectUri, state }, { value: false });
|
|
1299
|
+
} else {
|
|
1300
|
+
const loop = await startLoopback({ state, timeoutMs: LOGIN_TIMEOUT_MS });
|
|
1301
|
+
try {
|
|
1302
|
+
redirectUri = loop.redirectUri;
|
|
1303
|
+
const url = buildAuthorizeUrl(meta, base, { redirectUri, state, challenge });
|
|
1304
|
+
say2("Opening your browser to sign in. If it does not open, visit:");
|
|
1305
|
+
say2(` ${url}`);
|
|
1306
|
+
openBrowser(url);
|
|
1307
|
+
code = await loop.waitForCode();
|
|
1308
|
+
} finally {
|
|
1309
|
+
loop.close();
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
const tokens = await exchangeCode(meta, base, { code, verifier, redirectUri });
|
|
1313
|
+
const newPair = { accessToken: tokens.accessToken, refreshToken: tokens.refreshToken };
|
|
1314
|
+
let info;
|
|
1315
|
+
let oldPair = null;
|
|
1316
|
+
let replaced = null;
|
|
1317
|
+
try {
|
|
1318
|
+
info = await userinfoForLogin(meta, tokens.accessToken);
|
|
1319
|
+
oldPair = await withLock(credPath, async (lock) => {
|
|
1320
|
+
const existing = inspectCredentials(credPath);
|
|
1321
|
+
if (existing.status === "corrupt" || existing.status === "bad_mode") replaced = existing.status;
|
|
1322
|
+
lock.write(toCredentials(base, tokens, info));
|
|
1323
|
+
if (existing.status === "ok" || existing.status === "bad_mode") {
|
|
1324
|
+
return { accessToken: existing.creds.access_token, refreshToken: existing.creds.refresh_token };
|
|
1325
|
+
}
|
|
1326
|
+
return null;
|
|
1327
|
+
});
|
|
1328
|
+
} catch (err) {
|
|
1329
|
+
const revoked = await revokePair(meta, base, newPair);
|
|
1330
|
+
if (!revoked) {
|
|
1331
|
+
say2("warning: the new session could not be revoked and may stay valid for up to 30 days.");
|
|
1332
|
+
}
|
|
1333
|
+
throw toHgiError(err);
|
|
1334
|
+
}
|
|
1335
|
+
if (replaced === "corrupt") say2("warning: replaced an unreadable credentials file; any older session could not be revoked.");
|
|
1336
|
+
if (replaced === "bad_mode") say2("warning: the previous credentials file was readable by other users; it has been replaced and the old session revoked.");
|
|
1337
|
+
if (oldPair && !await revokePair(meta, base, oldPair)) {
|
|
1338
|
+
say2("warning: the previous session was not revoked and may stay valid for up to 30 days.");
|
|
1339
|
+
}
|
|
1340
|
+
return { base_url: base, user: info.user, organization: info.organization, client: info.client };
|
|
1341
|
+
}
|
|
1342
|
+
function toCredentials(base, tokens, info) {
|
|
1343
|
+
return {
|
|
1344
|
+
version: 1,
|
|
1345
|
+
base_url: base,
|
|
1346
|
+
client_id: clientId(base),
|
|
1347
|
+
access_token: tokens.accessToken,
|
|
1348
|
+
refresh_token: tokens.refreshToken,
|
|
1349
|
+
expires_at: computeDeadline(tokens),
|
|
1350
|
+
scope: tokens.scope || SCOPE,
|
|
1351
|
+
obtained_at: tokens.receivedAt,
|
|
1352
|
+
user: info.user,
|
|
1353
|
+
organization: info.organization
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
// src/authed-fetch.ts
|
|
1358
|
+
function createAuthedFetch(tokens, base) {
|
|
1359
|
+
const origin = new URL(base).origin;
|
|
1360
|
+
const send = (url, init, token, opts) => {
|
|
1361
|
+
const headers = new Headers(init.headers);
|
|
1362
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
1363
|
+
return httpRequest(url, { ...init, headers: Object.fromEntries(headers.entries()) }, opts);
|
|
1364
|
+
};
|
|
1365
|
+
return async (url, init = {}, opts = {}) => {
|
|
1366
|
+
if (new URL(url).origin !== origin) {
|
|
1367
|
+
throw new HgiError("internal_error", "Refusing to send credentials to a different origin.", {
|
|
1368
|
+
details: { reason: "cross_origin" }
|
|
1369
|
+
});
|
|
1370
|
+
}
|
|
1371
|
+
const token = await tokens.getAccessToken();
|
|
1372
|
+
const first = await send(url, init, token, opts);
|
|
1373
|
+
if (first.status !== 401) return first;
|
|
1374
|
+
await first.body?.cancel().catch(() => void 0);
|
|
1375
|
+
const signal = init.signal;
|
|
1376
|
+
if (signal?.aborted) throw signal.reason;
|
|
1377
|
+
const fresh = await tokens.forceRefresh(token);
|
|
1378
|
+
if (signal?.aborted) throw signal.reason;
|
|
1379
|
+
const second = await send(url, init, fresh, opts);
|
|
1380
|
+
if (second.status === 401) {
|
|
1381
|
+
await second.body?.cancel().catch(() => void 0);
|
|
1382
|
+
throw new HgiError("login_expired", "The server rejected your login again after a refresh.", {
|
|
1383
|
+
hint: LOGIN_HINT,
|
|
1384
|
+
details: { reason: "second_401" }
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
return second;
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
// src/commands/context.ts
|
|
1392
|
+
function buildContext(cmd) {
|
|
1393
|
+
const globals = cmd.optsWithGlobals();
|
|
1394
|
+
setDebug(Boolean(globals.debug) || process.env.HGI_DEBUG === "1");
|
|
1395
|
+
const base = resolveBaseUrl(globals.baseUrl ?? process.env.HGI_BASE_URL);
|
|
1396
|
+
const credPath = credentialsPath(base);
|
|
1397
|
+
const tokens = new TokenManager({ base, credPath });
|
|
1398
|
+
return { base, credPath, tokens, authedFetch: createAuthedFetch(tokens, base) };
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
// src/output/select.ts
|
|
1402
|
+
function parseSelect(raw) {
|
|
1403
|
+
const trie = /* @__PURE__ */ new Map();
|
|
1404
|
+
const paths = raw.split(",").map((p) => p.trim()).filter(Boolean);
|
|
1405
|
+
if (paths.length === 0) {
|
|
1406
|
+
throw new HgiError("invalid_input", "--select needs at least one field name.", {
|
|
1407
|
+
details: { reason: "empty_select" }
|
|
1408
|
+
});
|
|
1409
|
+
}
|
|
1410
|
+
for (const p of paths) {
|
|
1411
|
+
const parts = p.split(".");
|
|
1412
|
+
let node = trie;
|
|
1413
|
+
parts.forEach((part, i) => {
|
|
1414
|
+
const last = i === parts.length - 1;
|
|
1415
|
+
const existing = node.get(part);
|
|
1416
|
+
if (last) {
|
|
1417
|
+
node.set(part, true);
|
|
1418
|
+
} else if (existing === true) {
|
|
1419
|
+
} else {
|
|
1420
|
+
const child = existing ?? /* @__PURE__ */ new Map();
|
|
1421
|
+
node.set(part, child);
|
|
1422
|
+
node = child;
|
|
1423
|
+
}
|
|
1424
|
+
});
|
|
1425
|
+
}
|
|
1426
|
+
return trie;
|
|
1427
|
+
}
|
|
1428
|
+
function isPlainObject(value) {
|
|
1429
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1430
|
+
}
|
|
1431
|
+
function project(node, trie) {
|
|
1432
|
+
if (Array.isArray(node)) return node.map((item) => project(item, trie));
|
|
1433
|
+
if (!isPlainObject(node)) return node;
|
|
1434
|
+
const out = {};
|
|
1435
|
+
for (const [key, sub] of trie) {
|
|
1436
|
+
if (!(key in node)) continue;
|
|
1437
|
+
out[key] = sub === true ? node[key] : project(node[key], sub);
|
|
1438
|
+
}
|
|
1439
|
+
return out;
|
|
1440
|
+
}
|
|
1441
|
+
function applySelect(value, raw) {
|
|
1442
|
+
if (raw === void 0) return value;
|
|
1443
|
+
return project(value, parseSelect(raw));
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
// src/output/format.ts
|
|
1447
|
+
import YAML from "yaml";
|
|
1448
|
+
|
|
1449
|
+
// src/output/rows.ts
|
|
1450
|
+
function isPlainObject2(value) {
|
|
1451
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1452
|
+
}
|
|
1453
|
+
function isRowArray(value) {
|
|
1454
|
+
return Array.isArray(value) && value.length > 0 && value.every(isPlainObject2);
|
|
1455
|
+
}
|
|
1456
|
+
function rowsOf(value) {
|
|
1457
|
+
if (Array.isArray(value)) return { rows: value, collection: true };
|
|
1458
|
+
if (isPlainObject2(value)) {
|
|
1459
|
+
const candidates = Object.values(value).filter(isRowArray);
|
|
1460
|
+
if (candidates.length === 1) return { rows: candidates[0], collection: true };
|
|
1461
|
+
}
|
|
1462
|
+
return { rows: [value], collection: false };
|
|
1463
|
+
}
|
|
1464
|
+
function cellText(value) {
|
|
1465
|
+
if (value === null || value === void 0) return "";
|
|
1466
|
+
if (typeof value === "string") return value;
|
|
1467
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
1468
|
+
return String(value);
|
|
1469
|
+
}
|
|
1470
|
+
return JSON.stringify(value);
|
|
1471
|
+
}
|
|
1472
|
+
function columnsOf(rows) {
|
|
1473
|
+
const cols = [];
|
|
1474
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1475
|
+
let sawScalar = false;
|
|
1476
|
+
for (const row of rows) {
|
|
1477
|
+
if (isPlainObject2(row)) {
|
|
1478
|
+
for (const key of Object.keys(row)) {
|
|
1479
|
+
if (!seen.has(key)) {
|
|
1480
|
+
seen.add(key);
|
|
1481
|
+
cols.push(key);
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
} else {
|
|
1485
|
+
sawScalar = true;
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
if (sawScalar && !seen.has("value")) cols.push("value");
|
|
1489
|
+
return cols;
|
|
1490
|
+
}
|
|
1491
|
+
function rowCells(row, cols) {
|
|
1492
|
+
if (isPlainObject2(row)) return cols.map((c) => cellText(row[c]));
|
|
1493
|
+
return cols.map((c) => c === "value" ? cellText(row) : "");
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
// src/output/csv.ts
|
|
1497
|
+
function quote(cell) {
|
|
1498
|
+
return /[",\r\n]/.test(cell) ? `"${cell.replace(/"/g, '""')}"` : cell;
|
|
1499
|
+
}
|
|
1500
|
+
function toCsv(value) {
|
|
1501
|
+
const { rows } = rowsOf(value);
|
|
1502
|
+
const cols = columnsOf(rows);
|
|
1503
|
+
const lines = [cols.map(quote).join(",")];
|
|
1504
|
+
for (const row of rows) {
|
|
1505
|
+
lines.push(rowCells(row, cols).map(quote).join(","));
|
|
1506
|
+
}
|
|
1507
|
+
return `${lines.join("\r\n")}\r
|
|
1508
|
+
`;
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
// src/output/table.ts
|
|
1512
|
+
function oneLine(text) {
|
|
1513
|
+
return text.replace(/\r\n|\r|\n/g, "\\n");
|
|
1514
|
+
}
|
|
1515
|
+
function render(header, body) {
|
|
1516
|
+
const widths = header.map(
|
|
1517
|
+
(h, i) => Math.max(h.length, ...body.map((r) => (r[i] ?? "").length))
|
|
1518
|
+
);
|
|
1519
|
+
const fmt = (cells) => cells.map((c, i) => c.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
|
|
1520
|
+
const lines = [fmt(header), fmt(widths.map((w) => "-".repeat(w)))];
|
|
1521
|
+
for (const row of body) lines.push(fmt(row));
|
|
1522
|
+
return `${lines.join("\n")}
|
|
1523
|
+
`;
|
|
1524
|
+
}
|
|
1525
|
+
function toTable(value) {
|
|
1526
|
+
const { rows, collection } = rowsOf(value);
|
|
1527
|
+
if (collection) {
|
|
1528
|
+
const cols = columnsOf(rows);
|
|
1529
|
+
if (cols.length === 0) return "(no rows)\n";
|
|
1530
|
+
return render(
|
|
1531
|
+
cols,
|
|
1532
|
+
rows.map((r) => rowCells(r, cols).map(oneLine))
|
|
1533
|
+
);
|
|
1534
|
+
}
|
|
1535
|
+
const single = rows[0];
|
|
1536
|
+
if (typeof single === "object" && single !== null && !Array.isArray(single)) {
|
|
1537
|
+
const entries = Object.entries(single);
|
|
1538
|
+
if (entries.length === 0) return "(empty)\n";
|
|
1539
|
+
return render(
|
|
1540
|
+
["field", "value"],
|
|
1541
|
+
entries.map(([k, v]) => [k, oneLine(cellText(v))])
|
|
1542
|
+
);
|
|
1543
|
+
}
|
|
1544
|
+
return `${oneLine(cellText(single))}
|
|
1545
|
+
`;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
// src/output/format.ts
|
|
1549
|
+
var FORMATS = ["json", "jsonl", "csv", "yaml", "table"];
|
|
1550
|
+
function parseFormat(raw) {
|
|
1551
|
+
if (FORMATS.includes(raw)) return raw;
|
|
1552
|
+
throw new HgiError("invalid_input", `Unknown format "${raw}". Use one of: ${FORMATS.join(", ")}.`, {
|
|
1553
|
+
details: { reason: "unknown_format" }
|
|
1554
|
+
});
|
|
1555
|
+
}
|
|
1556
|
+
function defaultFormat(isTty) {
|
|
1557
|
+
return isTty ? "table" : "json";
|
|
1558
|
+
}
|
|
1559
|
+
function formatValue(value, format, opts) {
|
|
1560
|
+
switch (format) {
|
|
1561
|
+
case "json":
|
|
1562
|
+
return `${JSON.stringify(value, null, opts.pretty ? 2 : void 0)}
|
|
1563
|
+
`;
|
|
1564
|
+
case "jsonl":
|
|
1565
|
+
return `${rowsOf(value).rows.map((r) => JSON.stringify(r)).join("\n")}
|
|
1566
|
+
`;
|
|
1567
|
+
case "csv":
|
|
1568
|
+
return toCsv(value);
|
|
1569
|
+
case "yaml":
|
|
1570
|
+
return YAML.stringify(value);
|
|
1571
|
+
case "table":
|
|
1572
|
+
return toTable(value);
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
// src/output/out-file.ts
|
|
1577
|
+
import fs3 from "fs";
|
|
1578
|
+
import path3 from "path";
|
|
1579
|
+
function refuse(message, reason, hint) {
|
|
1580
|
+
return new HgiError("invalid_input", message, { hint, details: { reason } });
|
|
1581
|
+
}
|
|
1582
|
+
function assertNotProtected(target, protectedDirs2, what) {
|
|
1583
|
+
const real = realpathDeep(target);
|
|
1584
|
+
for (const dir of protectedDirs2) {
|
|
1585
|
+
if (isInside(real, dir) || isInsideByInode(real, dir)) {
|
|
1586
|
+
throw refuse(`${what} may not be inside hgi's own config or cache directory.`, "protected_path");
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
return real;
|
|
1590
|
+
}
|
|
1591
|
+
function sameInode(a, b) {
|
|
1592
|
+
return a.ino === b.ino && a.dev === b.dev;
|
|
1593
|
+
}
|
|
1594
|
+
function protectedInodes(protectedDirs2) {
|
|
1595
|
+
const stats = [];
|
|
1596
|
+
for (const dir of protectedDirs2) {
|
|
1597
|
+
let entries = [];
|
|
1598
|
+
try {
|
|
1599
|
+
entries = fs3.readdirSync(dir);
|
|
1600
|
+
} catch {
|
|
1601
|
+
continue;
|
|
1602
|
+
}
|
|
1603
|
+
for (const name of entries) {
|
|
1604
|
+
try {
|
|
1605
|
+
const st = fs3.statSync(path3.join(dir, name));
|
|
1606
|
+
if (st.isFile()) stats.push(st);
|
|
1607
|
+
} catch {
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
return stats;
|
|
1612
|
+
}
|
|
1613
|
+
function readInputFile(file, protectedDirs2, hooks = {}) {
|
|
1614
|
+
const real = assertNotProtected(file, protectedDirs2, "--input @file");
|
|
1615
|
+
let fd;
|
|
1616
|
+
try {
|
|
1617
|
+
hooks.beforeOpen?.();
|
|
1618
|
+
fd = fs3.openSync(real, fs3.constants.O_RDONLY | fs3.constants.O_NOFOLLOW);
|
|
1619
|
+
const st = fs3.fstatSync(fd);
|
|
1620
|
+
if (!st.isFile()) throw refuse(`${file} is not a regular file.`, "not_regular_file");
|
|
1621
|
+
if (protectedInodes(protectedDirs2).some((other) => sameInode(st, other))) {
|
|
1622
|
+
throw refuse("That file is one of hgi's credential or cache files.", "protected_path");
|
|
1623
|
+
}
|
|
1624
|
+
hooks.afterCheck?.();
|
|
1625
|
+
return fs3.readFileSync(fd, "utf8");
|
|
1626
|
+
} catch (err) {
|
|
1627
|
+
if (err instanceof HgiError) throw err;
|
|
1628
|
+
throw refuse(`Cannot read input file ${file}: ${err.code ?? "error"}.`, "input_unreadable");
|
|
1629
|
+
} finally {
|
|
1630
|
+
if (fd !== void 0) fs3.closeSync(fd);
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
function preflightOutFile(target, opts) {
|
|
1634
|
+
if (opts.force && !opts.allowForce) {
|
|
1635
|
+
throw refuse("--force is only available on `hgi run`.", "force_on_call", "Use a new --out path with `hgi call`.");
|
|
1636
|
+
}
|
|
1637
|
+
const dir = realpathDeep(path3.dirname(target));
|
|
1638
|
+
const dest = path3.join(dir, path3.basename(target));
|
|
1639
|
+
assertNotProtected(dest, opts.protectedDirs, "--out");
|
|
1640
|
+
try {
|
|
1641
|
+
if (!fs3.statSync(dir).isDirectory()) throw new Error("not a directory");
|
|
1642
|
+
fs3.accessSync(dir, fs3.constants.W_OK | fs3.constants.X_OK);
|
|
1643
|
+
} catch {
|
|
1644
|
+
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
|
+
}
|
|
1646
|
+
let existing = null;
|
|
1647
|
+
try {
|
|
1648
|
+
existing = fs3.lstatSync(dest);
|
|
1649
|
+
} catch {
|
|
1650
|
+
existing = null;
|
|
1651
|
+
}
|
|
1652
|
+
if (existing) {
|
|
1653
|
+
if (existing.isSymbolicLink()) throw refuse(`Refusing to write through symlink ${dest}.`, "symlink");
|
|
1654
|
+
if (!existing.isFile()) throw refuse(`${dest} is not a regular file.`, "not_regular_file");
|
|
1655
|
+
if (!opts.force) {
|
|
1656
|
+
throw refuse(`${dest} already exists.`, "out_exists", "Choose a new path, or pass --force to `hgi run`.");
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
return { dest, existing: existing !== null };
|
|
1660
|
+
}
|
|
1661
|
+
function writeOutFile(target, data, opts) {
|
|
1662
|
+
const { dest, existing } = preflightOutFile(target, opts);
|
|
1663
|
+
const flags = fs3.constants.O_CREAT | fs3.constants.O_EXCL | fs3.constants.O_WRONLY | fs3.constants.O_NOFOLLOW;
|
|
1664
|
+
const tmp = existing ? `${dest}.hgi-${process.pid}-${Date.now()}.tmp` : dest;
|
|
1665
|
+
try {
|
|
1666
|
+
const fd = fs3.openSync(tmp, flags, 438);
|
|
1667
|
+
try {
|
|
1668
|
+
fs3.writeFileSync(fd, data);
|
|
1669
|
+
fs3.fsyncSync(fd);
|
|
1670
|
+
} finally {
|
|
1671
|
+
fs3.closeSync(fd);
|
|
1672
|
+
}
|
|
1673
|
+
if (existing) fs3.renameSync(tmp, dest);
|
|
1674
|
+
} catch (err) {
|
|
1675
|
+
if (err.code === "EEXIST" && !existing) {
|
|
1676
|
+
throw refuse(`${dest} already exists.`, "out_exists", "Choose a new path, or pass --force to `hgi run`.");
|
|
1677
|
+
}
|
|
1678
|
+
throw new HgiError("local_state_error", `Could not write ${dest}: ${err.code ?? "error"}.`, {
|
|
1679
|
+
details: { kind: "write_failed" },
|
|
1680
|
+
cause: err
|
|
1681
|
+
});
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
// src/output/stdout.ts
|
|
1686
|
+
import { once } from "events";
|
|
1687
|
+
async function writeStream(stream, text) {
|
|
1688
|
+
try {
|
|
1689
|
+
if (!stream.write(text)) await once(stream, "drain");
|
|
1690
|
+
} catch (err) {
|
|
1691
|
+
if (err.code === "EPIPE") return;
|
|
1692
|
+
throw err;
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
function ignoreEpipe(stream, exitOnEpipe) {
|
|
1696
|
+
stream.on("error", (err) => {
|
|
1697
|
+
if (err.code === "EPIPE") {
|
|
1698
|
+
if (exitOnEpipe) process.exit(0);
|
|
1699
|
+
return;
|
|
1700
|
+
}
|
|
1701
|
+
throw err;
|
|
1702
|
+
});
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
// src/commands/emit.ts
|
|
1706
|
+
function preflightOutput(opts) {
|
|
1707
|
+
if (opts.format) parseFormat(opts.format);
|
|
1708
|
+
if (opts.select !== void 0) parseSelect(opts.select);
|
|
1709
|
+
if (opts.out) {
|
|
1710
|
+
preflightOutFile(opts.out, {
|
|
1711
|
+
force: Boolean(opts.force),
|
|
1712
|
+
allowForce: Boolean(opts.allowForce),
|
|
1713
|
+
protectedDirs: protectedDirs()
|
|
1714
|
+
});
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
async function emit(value, opts = {}) {
|
|
1718
|
+
const isTty = Boolean(process.stdout.isTTY);
|
|
1719
|
+
const format = opts.format ? parseFormat(opts.format) : defaultFormat(isTty);
|
|
1720
|
+
let text = formatValue(applySelect(value, opts.select), format, { pretty: isTty });
|
|
1721
|
+
if (isTty && !opts.out) {
|
|
1722
|
+
if (format === "table" || format === "csv" || format === "yaml") text = sanitizeForTerminal(text);
|
|
1723
|
+
else if (format === "json" || format === "jsonl") text = escapeJsonForTerminal(text);
|
|
1724
|
+
}
|
|
1725
|
+
if (opts.out) {
|
|
1726
|
+
writeOutFile(opts.out, text, {
|
|
1727
|
+
force: Boolean(opts.force),
|
|
1728
|
+
allowForce: Boolean(opts.allowForce),
|
|
1729
|
+
protectedDirs: protectedDirs()
|
|
1730
|
+
});
|
|
1731
|
+
process.stderr.write(`hgi: wrote ${Buffer.byteLength(text)} bytes to ${opts.out}
|
|
1732
|
+
`);
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
await writeStream(process.stdout, text);
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
// src/commands/auth.ts
|
|
1739
|
+
var say = (line) => {
|
|
1740
|
+
process.stderr.write(`${line}
|
|
1741
|
+
`);
|
|
1742
|
+
};
|
|
1743
|
+
function registerAuthCommands(program) {
|
|
1744
|
+
const auth = program.command("auth").description("Sign in, sign out, and see who you are signed in as");
|
|
1745
|
+
auth.command("login").description("Sign in through your browser (OAuth, PKCE)").option("--no-browser", "print the URL and accept a pasted callback URL instead of opening a browser").option("-f, --format <format>", "json|jsonl|csv|yaml|table").action(async (opts, cmd) => {
|
|
1746
|
+
const ctx = buildContext(cmd);
|
|
1747
|
+
const result = await login({ base: ctx.base, credPath: ctx.credPath, noBrowser: !opts.browser, say });
|
|
1748
|
+
await emit(result, { format: opts.format });
|
|
1749
|
+
});
|
|
1750
|
+
auth.command("whoami").description("Show the signed-in user and organization (asks the server)").option("-f, --format <format>", "json|jsonl|csv|yaml|table").action(async (opts, cmd) => {
|
|
1751
|
+
const ctx = buildContext(cmd);
|
|
1752
|
+
ctx.tokens.loadCredentials();
|
|
1753
|
+
const meta = await discover(ctx.base);
|
|
1754
|
+
const info = await getUserinfo(
|
|
1755
|
+
meta,
|
|
1756
|
+
(url) => ctx.authedFetch(url, {}, { redirectKind: "oauth", context: "the userinfo endpoint" }),
|
|
1757
|
+
"login"
|
|
1758
|
+
);
|
|
1759
|
+
await emit({ base_url: ctx.base, ...info }, { format: opts.format });
|
|
1760
|
+
});
|
|
1761
|
+
auth.command("logout").description("Revoke your session on the server and delete the local credentials").option("--force", "delete the local credentials even if the server could not be told").option("-f, --format <format>", "json|jsonl|csv|yaml|table").action(async (opts, cmd) => {
|
|
1762
|
+
const ctx = buildContext(cmd);
|
|
1763
|
+
const outcome = await withLock(ctx.credPath, async (lock) => {
|
|
1764
|
+
const found = inspectCredentials(ctx.credPath);
|
|
1765
|
+
if (found.status === "missing") return "not_signed_in";
|
|
1766
|
+
if (found.status === "corrupt") {
|
|
1767
|
+
if (!opts.force) readCredentials(ctx.credPath);
|
|
1768
|
+
lock.remove();
|
|
1769
|
+
return "deleted_corrupt";
|
|
1770
|
+
}
|
|
1771
|
+
const creds = found.creds;
|
|
1772
|
+
try {
|
|
1773
|
+
const meta = await discover(ctx.base);
|
|
1774
|
+
await revokeToken(meta, ctx.base, creds.refresh_token, "refresh_token");
|
|
1775
|
+
await revokeToken(meta, ctx.base, creds.access_token, "access_token");
|
|
1776
|
+
} catch (err) {
|
|
1777
|
+
if (!opts.force) {
|
|
1778
|
+
const cause = err instanceof HgiError ? err : void 0;
|
|
1779
|
+
throw new HgiError(cause?.code ?? "server_unreachable", `Could not revoke your session: ${cause?.message ?? String(err)} You are NOT signed out.`, {
|
|
1780
|
+
hint: "Your credentials were kept. Retry, or use `hgi auth logout --force` to delete them locally (the server-side token may stay valid for up to 30 days).",
|
|
1781
|
+
details: cause?.details,
|
|
1782
|
+
cause: err
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
say("warning: the server could not be told to revoke the session; it may stay valid for up to 30 days.");
|
|
1786
|
+
}
|
|
1787
|
+
lock.remove();
|
|
1788
|
+
return "signed_out";
|
|
1789
|
+
});
|
|
1790
|
+
await emit({ base_url: ctx.base, result: outcome }, { format: opts.format });
|
|
1791
|
+
});
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
// src/commands/invoke.ts
|
|
1795
|
+
import { Option } from "commander";
|
|
1796
|
+
|
|
1797
|
+
// src/mcp/cache.ts
|
|
1798
|
+
import fs4 from "fs";
|
|
1799
|
+
import path4 from "path";
|
|
1800
|
+
import { createHash as createHash2 } from "crypto";
|
|
1801
|
+
var TOOLS_CACHE_TTL_MS = 15 * 6e4;
|
|
1802
|
+
function toolsCachePath(base, orgSlug, userId) {
|
|
1803
|
+
const userHash = createHash2("sha256").update(userId).digest("hex").slice(0, 12);
|
|
1804
|
+
const org = orgSlug.replace(/[^a-z0-9_-]/gi, "_");
|
|
1805
|
+
return path4.join(cacheDir(), `tools-${hostSlug(base)}-${org}-${userHash}.json`);
|
|
1806
|
+
}
|
|
1807
|
+
function readToolsCache(file, now = Date.now()) {
|
|
1808
|
+
try {
|
|
1809
|
+
const parsed = JSON.parse(fs4.readFileSync(file, "utf8"));
|
|
1810
|
+
if (!Array.isArray(parsed.tools) || typeof parsed.fetched_at !== "number") return null;
|
|
1811
|
+
if (now - parsed.fetched_at > TOOLS_CACHE_TTL_MS) return null;
|
|
1812
|
+
return parsed;
|
|
1813
|
+
} catch {
|
|
1814
|
+
return null;
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
function writeToolsCache(file, cache) {
|
|
1818
|
+
try {
|
|
1819
|
+
writePrivateFile(file, JSON.stringify(cache));
|
|
1820
|
+
} catch (err) {
|
|
1821
|
+
debug("could not write tools cache", err);
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1825
|
+
// src/mcp/session.ts
|
|
1826
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
1827
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
1828
|
+
import {
|
|
1829
|
+
CallToolResultSchema,
|
|
1830
|
+
ErrorCode,
|
|
1831
|
+
ListToolsResultSchema,
|
|
1832
|
+
McpError
|
|
1833
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
1834
|
+
|
|
1835
|
+
// src/mcp/transport-fetch.ts
|
|
1836
|
+
var RETRY_BUDGET_MS = 6e4;
|
|
1837
|
+
var MAX_RATE_RETRIES = 3;
|
|
1838
|
+
var MAX_TRANSIENT_RETRIES = 2;
|
|
1839
|
+
var PRE_DISPATCH_CODES = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"]);
|
|
1840
|
+
function rpcMethod(init) {
|
|
1841
|
+
const body = init?.body;
|
|
1842
|
+
if (typeof body !== "string") return void 0;
|
|
1843
|
+
try {
|
|
1844
|
+
const parsed = JSON.parse(body);
|
|
1845
|
+
const method = parsed.method;
|
|
1846
|
+
return typeof method === "string" ? method : void 0;
|
|
1847
|
+
} catch {
|
|
1848
|
+
return void 0;
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
async function isShed(res) {
|
|
1852
|
+
const text = await res.text();
|
|
1853
|
+
if (res.status !== 503 || !res.headers.get("retry-after")) return false;
|
|
1854
|
+
try {
|
|
1855
|
+
const parsed = JSON.parse(text);
|
|
1856
|
+
return parsed.error?.code === -32e3;
|
|
1857
|
+
} catch {
|
|
1858
|
+
return false;
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
function createTransportFetch(authed, state, opts) {
|
|
1862
|
+
const wait = opts.sleepFn ?? sleep;
|
|
1863
|
+
const now = opts.now ?? Date.now;
|
|
1864
|
+
const random = opts.random ?? Math.random;
|
|
1865
|
+
return async (url, rawInit) => {
|
|
1866
|
+
const init = rawInit ?? {};
|
|
1867
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
1868
|
+
const isPost = method === "POST";
|
|
1869
|
+
const isToolsCall = isPost && rpcMethod(init) === "tools/call";
|
|
1870
|
+
const signal = init.signal;
|
|
1871
|
+
const started = now();
|
|
1872
|
+
let rateAttempts = 0;
|
|
1873
|
+
let transientAttempts = 0;
|
|
1874
|
+
for (; ; ) {
|
|
1875
|
+
if (signal?.aborted) throw signal.reason;
|
|
1876
|
+
let res;
|
|
1877
|
+
try {
|
|
1878
|
+
if (isToolsCall) state.toolsCallWritten = true;
|
|
1879
|
+
res = await authed(String(url), init, { redirectKind: "mcp", context: "the MCP server", timeoutMs: opts.timeoutMs });
|
|
1880
|
+
} catch (err) {
|
|
1881
|
+
if (!(err instanceof HgiError) || err.code !== "server_unreachable") throw err;
|
|
1882
|
+
const cause = networkErrorCode(err.cause) ?? err.details?.cause;
|
|
1883
|
+
if (isToolsCall) {
|
|
1884
|
+
if (cause && PRE_DISPATCH_CODES.has(cause) && transientAttempts < MAX_TRANSIENT_RETRIES) {
|
|
1885
|
+
transientAttempts += 1;
|
|
1886
|
+
await wait(500 * transientAttempts, signal);
|
|
1887
|
+
continue;
|
|
1888
|
+
}
|
|
1889
|
+
throw new HgiError("server_unreachable", err.message, {
|
|
1890
|
+
hint: "The call may or may not have run. Check state before re-running.",
|
|
1891
|
+
details: { ...err.details, outcome_unknown: true },
|
|
1892
|
+
cause: err.cause
|
|
1893
|
+
});
|
|
1894
|
+
}
|
|
1895
|
+
if (transientAttempts < MAX_TRANSIENT_RETRIES) {
|
|
1896
|
+
transientAttempts += 1;
|
|
1897
|
+
await wait(500 * transientAttempts, signal);
|
|
1898
|
+
continue;
|
|
1899
|
+
}
|
|
1900
|
+
throw err;
|
|
1901
|
+
}
|
|
1902
|
+
const headerVersion = res.headers.get("x-mcp-version");
|
|
1903
|
+
if (headerVersion) state.mcpVersion = headerVersion;
|
|
1904
|
+
if (!isPost) return res;
|
|
1905
|
+
if (res.status === 429) {
|
|
1906
|
+
const header = parseRetryAfter(res.headers.get("retry-after"));
|
|
1907
|
+
await res.body?.cancel().catch(() => void 0);
|
|
1908
|
+
const delaySec = header ?? Math.min(2 ** (rateAttempts + 1), 30) + random();
|
|
1909
|
+
const remaining = RETRY_BUDGET_MS - (now() - started);
|
|
1910
|
+
if (rateAttempts >= MAX_RATE_RETRIES || delaySec * 1e3 > remaining) {
|
|
1911
|
+
throw new HgiError("rate_limited", "The organization is being rate limited by the server.", {
|
|
1912
|
+
hint: "Wait and retry; the limit is shared by every hgi process in your organization.",
|
|
1913
|
+
details: { retry_after_seconds: header ?? Math.ceil(delaySec) }
|
|
1914
|
+
});
|
|
1915
|
+
}
|
|
1916
|
+
rateAttempts += 1;
|
|
1917
|
+
debug("429, waiting", delaySec);
|
|
1918
|
+
await wait(delaySec * 1e3 + random() * 250, signal);
|
|
1919
|
+
continue;
|
|
1920
|
+
}
|
|
1921
|
+
if (res.status === 403) {
|
|
1922
|
+
await res.body?.cancel().catch(() => void 0);
|
|
1923
|
+
throw new HgiError("forbidden", "The server refused this request (HTTP 403).", {
|
|
1924
|
+
hint: "Your account or organization may not have access to this tool or endpoint.",
|
|
1925
|
+
details: { status: 403 }
|
|
1926
|
+
});
|
|
1927
|
+
}
|
|
1928
|
+
if (res.status >= 500) {
|
|
1929
|
+
const shed = await isShed(res);
|
|
1930
|
+
if (shed) {
|
|
1931
|
+
const header = parseRetryAfter(res.headers.get("retry-after")) ?? 1;
|
|
1932
|
+
const remaining = RETRY_BUDGET_MS - (now() - started);
|
|
1933
|
+
if (rateAttempts >= MAX_RATE_RETRIES || header * 1e3 > remaining) {
|
|
1934
|
+
throw new HgiError("server_unreachable", "The server is shedding load (503).", {
|
|
1935
|
+
hint: "Nothing was run; retrying is safe.",
|
|
1936
|
+
details: { status: 503, outcome_unknown: false, retry_after_seconds: header }
|
|
1937
|
+
});
|
|
1938
|
+
}
|
|
1939
|
+
rateAttempts += 1;
|
|
1940
|
+
await wait(header * 1e3 + random() * 250, signal);
|
|
1941
|
+
continue;
|
|
1942
|
+
}
|
|
1943
|
+
if (isToolsCall) {
|
|
1944
|
+
throw new HgiError("server_unreachable", `The server failed while running the tool (HTTP ${res.status}).`, {
|
|
1945
|
+
hint: "The call may or may not have run. Check state before re-running.",
|
|
1946
|
+
details: { status: res.status, outcome_unknown: true }
|
|
1947
|
+
});
|
|
1948
|
+
}
|
|
1949
|
+
if ([502, 503, 504].includes(res.status) && transientAttempts < MAX_TRANSIENT_RETRIES) {
|
|
1950
|
+
transientAttempts += 1;
|
|
1951
|
+
await wait(500 * transientAttempts, signal);
|
|
1952
|
+
continue;
|
|
1953
|
+
}
|
|
1954
|
+
throw new HgiError("server_unreachable", `The server returned HTTP ${res.status}.`, {
|
|
1955
|
+
hint: "Retry in a moment.",
|
|
1956
|
+
details: { status: res.status }
|
|
1957
|
+
});
|
|
1958
|
+
}
|
|
1959
|
+
return res;
|
|
1960
|
+
}
|
|
1961
|
+
};
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
// src/mcp/session.ts
|
|
1965
|
+
var POST_DISPATCH_UNCERTAIN = /* @__PURE__ */ new Set(["server_unreachable", "network_proxy_tls", "internal_error"]);
|
|
1966
|
+
function markOutcomeUnknown(err, state) {
|
|
1967
|
+
if (!state.toolsCallWritten || !POST_DISPATCH_UNCERTAIN.has(err.code) || err.details?.outcome_unknown !== void 0) {
|
|
1968
|
+
return err;
|
|
1969
|
+
}
|
|
1970
|
+
return new HgiError(err.code, err.message, {
|
|
1971
|
+
hint: "The call may or may not have run and may have been billed. Check state before re-running; do not just retry.",
|
|
1972
|
+
details: { ...err.details, outcome_unknown: true },
|
|
1973
|
+
cause: err.cause
|
|
1974
|
+
});
|
|
1975
|
+
}
|
|
1976
|
+
function mapMcpError(err, state) {
|
|
1977
|
+
return markOutcomeUnknown(mapMcpErrorInner(err, state), state);
|
|
1978
|
+
}
|
|
1979
|
+
function mapMcpErrorInner(err, state) {
|
|
1980
|
+
if (err instanceof HgiError) return err;
|
|
1981
|
+
const outcomeUnknown = state.toolsCallWritten ? { outcome_unknown: true } : {};
|
|
1982
|
+
if (err instanceof McpError) {
|
|
1983
|
+
if (err.code === ErrorCode.RequestTimeout || err.code === ErrorCode.ConnectionClosed) {
|
|
1984
|
+
return new HgiError("server_unreachable", `The connection to the server failed (${err.message}).`, {
|
|
1985
|
+
hint: state.toolsCallWritten ? "The call may or may not have run. Check state before re-running." : "Check your network and retry, or raise --timeout.",
|
|
1986
|
+
details: { jsonrpc_code: err.code, ...outcomeUnknown },
|
|
1987
|
+
cause: err
|
|
1988
|
+
});
|
|
1989
|
+
}
|
|
1990
|
+
return new HgiError("tool_error", `The server returned an error: ${err.message}`, {
|
|
1991
|
+
details: { jsonrpc_code: err.code },
|
|
1992
|
+
cause: err
|
|
1993
|
+
});
|
|
1994
|
+
}
|
|
1995
|
+
const unsupported = /Server's protocol version is not supported: (\S+)/.exec(err instanceof Error ? err.message : "");
|
|
1996
|
+
if (unsupported) {
|
|
1997
|
+
return new HgiError("server_unreachable", `The server chose MCP protocol version ${unsupported[1]}, which this hgi does not support.`, {
|
|
1998
|
+
hint: "Upgrade hgi (see docs/compatibility.md for the versions this release speaks).",
|
|
1999
|
+
details: { reason: "unsupported_protocol_version", server_protocol_version: unsupported[1] },
|
|
2000
|
+
cause: err
|
|
2001
|
+
});
|
|
2002
|
+
}
|
|
2003
|
+
const name = err?.name;
|
|
2004
|
+
const httpStatus = err?.code;
|
|
2005
|
+
if (name === "StreamableHTTPError" && typeof httpStatus === "number") {
|
|
2006
|
+
if (httpStatus === 403) {
|
|
2007
|
+
return new HgiError("forbidden", "The server refused this request (HTTP 403).", { details: { status: 403 }, cause: err });
|
|
2008
|
+
}
|
|
2009
|
+
return new HgiError("server_unreachable", `The MCP endpoint returned HTTP ${httpStatus}.`, {
|
|
2010
|
+
details: { status: httpStatus, ...outcomeUnknown },
|
|
2011
|
+
cause: err
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
if (state.toolsCallWritten && name !== "TypeError") {
|
|
2015
|
+
return new HgiError("tool_error", "The tool ran but its response could not be parsed.", {
|
|
2016
|
+
hint: "The call may have been billed. Check state before re-running.",
|
|
2017
|
+
details: { unparseable: true },
|
|
2018
|
+
cause: err
|
|
2019
|
+
});
|
|
2020
|
+
}
|
|
2021
|
+
return toHgiError(err);
|
|
2022
|
+
}
|
|
2023
|
+
async function openSession(ctx, opts) {
|
|
2024
|
+
const state = { mcpVersion: null, toolsCallWritten: false };
|
|
2025
|
+
const transport = new StreamableHTTPClientTransport(new URL(mcpUrl(ctx.base)), {
|
|
2026
|
+
fetch: createTransportFetch(ctx.authedFetch, state, { timeoutMs: opts.timeoutMs })
|
|
2027
|
+
});
|
|
2028
|
+
const client = new Client({ name: "hgi", version: VERSION }, { capabilities: {} });
|
|
2029
|
+
try {
|
|
2030
|
+
await client.connect(transport);
|
|
2031
|
+
} catch (err) {
|
|
2032
|
+
await transport.close().catch(() => void 0);
|
|
2033
|
+
throw mapMcpError(err, state);
|
|
2034
|
+
}
|
|
2035
|
+
const info = client.getServerVersion();
|
|
2036
|
+
const requestOptions = { timeout: opts.timeoutMs };
|
|
2037
|
+
return {
|
|
2038
|
+
state,
|
|
2039
|
+
serverInfo: info ? { name: info.name, version: info.version } : null,
|
|
2040
|
+
async listTools() {
|
|
2041
|
+
const tools = [];
|
|
2042
|
+
let cursor;
|
|
2043
|
+
try {
|
|
2044
|
+
do {
|
|
2045
|
+
const page = await client.request(
|
|
2046
|
+
{ method: "tools/list", params: cursor ? { cursor } : {} },
|
|
2047
|
+
ListToolsResultSchema,
|
|
2048
|
+
requestOptions
|
|
2049
|
+
);
|
|
2050
|
+
tools.push(...page.tools);
|
|
2051
|
+
cursor = page.nextCursor;
|
|
2052
|
+
} while (cursor);
|
|
2053
|
+
} catch (err) {
|
|
2054
|
+
throw mapMcpError(err, state);
|
|
2055
|
+
}
|
|
2056
|
+
return tools;
|
|
2057
|
+
},
|
|
2058
|
+
async callTool(name, args) {
|
|
2059
|
+
try {
|
|
2060
|
+
return await client.request(
|
|
2061
|
+
{ method: "tools/call", params: { name, arguments: args } },
|
|
2062
|
+
CallToolResultSchema,
|
|
2063
|
+
requestOptions
|
|
2064
|
+
);
|
|
2065
|
+
} catch (err) {
|
|
2066
|
+
throw mapMcpError(err, state);
|
|
2067
|
+
}
|
|
2068
|
+
},
|
|
2069
|
+
async close() {
|
|
2070
|
+
try {
|
|
2071
|
+
await client.close();
|
|
2072
|
+
} catch (err) {
|
|
2073
|
+
debug("session close failed", err);
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
};
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
// src/mcp/tools.ts
|
|
2080
|
+
function verbFor(tool) {
|
|
2081
|
+
return tool.annotations?.readOnlyHint === true ? "call" : "run";
|
|
2082
|
+
}
|
|
2083
|
+
function typeOf(schema) {
|
|
2084
|
+
if (typeof schema !== "object" || schema === null) return "any";
|
|
2085
|
+
const s = schema;
|
|
2086
|
+
if (typeof s.type === "string") return s.type;
|
|
2087
|
+
if (Array.isArray(s.type)) return s.type.join("|");
|
|
2088
|
+
for (const key of ["anyOf", "oneOf"]) {
|
|
2089
|
+
const alts = s[key];
|
|
2090
|
+
if (Array.isArray(alts)) return alts.map(typeOf).join("|");
|
|
2091
|
+
}
|
|
2092
|
+
if (s.enum) return "enum";
|
|
2093
|
+
return "any";
|
|
2094
|
+
}
|
|
2095
|
+
function summarize(tool) {
|
|
2096
|
+
const props = tool.inputSchema.properties ?? {};
|
|
2097
|
+
const required = Array.isArray(tool.inputSchema.required) ? tool.inputSchema.required : [];
|
|
2098
|
+
return {
|
|
2099
|
+
name: tool.name,
|
|
2100
|
+
verb: verbFor(tool),
|
|
2101
|
+
read_only: typeof tool.annotations?.readOnlyHint === "boolean" ? tool.annotations.readOnlyHint : null,
|
|
2102
|
+
description: tool.description ?? "",
|
|
2103
|
+
required,
|
|
2104
|
+
parameters: Object.entries(props).map(([name, schema]) => ({
|
|
2105
|
+
name,
|
|
2106
|
+
type: typeOf(schema),
|
|
2107
|
+
required: required.includes(name),
|
|
2108
|
+
...typeof schema?.description === "string" ? { description: schema.description } : {}
|
|
2109
|
+
})),
|
|
2110
|
+
input_schema: tool.inputSchema
|
|
2111
|
+
};
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
// src/commands/tools.ts
|
|
2115
|
+
function mcpCacheKey(base, creds) {
|
|
2116
|
+
return [base, creds.organization.slug, creds.user.id];
|
|
2117
|
+
}
|
|
2118
|
+
function shortDescription(text) {
|
|
2119
|
+
const line = text.split(/\r\n|\r|\n/)[0] ?? "";
|
|
2120
|
+
return line.length > 100 ? `${line.slice(0, 97)}...` : line;
|
|
2121
|
+
}
|
|
2122
|
+
function registerToolsCommands(program) {
|
|
2123
|
+
const tools = program.command("tools").description("Discover what the server offers you");
|
|
2124
|
+
tools.command("list").description("List the tools the authenticated server offers, marked call or run").option("--refresh", "ignore the local cache and ask the server").option("--json", "shorthand for -f json").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").option("--timeout <seconds>", "per-request timeout", "120").action(async (opts, cmd) => {
|
|
2125
|
+
preflightOutput({ format: opts.json ? "json" : opts.format, select: opts.select, out: opts.out });
|
|
2126
|
+
const timeoutMs = parseTimeoutMs(opts.timeout);
|
|
2127
|
+
const ctx = buildContext(cmd);
|
|
2128
|
+
const creds = ctx.tokens.loadCredentials();
|
|
2129
|
+
const cachePath = toolsCachePath(...mcpCacheKey(ctx.base, creds));
|
|
2130
|
+
let data = opts.refresh ? null : readToolsCache(cachePath);
|
|
2131
|
+
const fromCache = data !== null;
|
|
2132
|
+
if (!data) {
|
|
2133
|
+
const session = await openSession(ctx, { timeoutMs });
|
|
2134
|
+
try {
|
|
2135
|
+
const list = await session.listTools();
|
|
2136
|
+
data = {
|
|
2137
|
+
fetched_at: Date.now(),
|
|
2138
|
+
mcp_version: session.state.mcpVersion,
|
|
2139
|
+
server: session.serverInfo,
|
|
2140
|
+
tools: list
|
|
2141
|
+
};
|
|
2142
|
+
} finally {
|
|
2143
|
+
await session.close();
|
|
2144
|
+
}
|
|
2145
|
+
writeToolsCache(cachePath, data);
|
|
2146
|
+
}
|
|
2147
|
+
const format = opts.json ? "json" : opts.format ? parseFormat(opts.format) : defaultFormat(Boolean(process.stdout.isTTY));
|
|
2148
|
+
const summaries = data.tools.map(summarize);
|
|
2149
|
+
let value;
|
|
2150
|
+
if (format === "table" || format === "csv") {
|
|
2151
|
+
value = summaries.map((s) => ({
|
|
2152
|
+
name: s.name,
|
|
2153
|
+
verb: s.verb,
|
|
2154
|
+
required: s.required.join(","),
|
|
2155
|
+
description: format === "table" ? shortDescription(s.description) : s.description
|
|
2156
|
+
}));
|
|
2157
|
+
process.stderr.write(`mcp_version: ${data.mcp_version ?? "unknown"}
|
|
2158
|
+
`);
|
|
2159
|
+
} else {
|
|
2160
|
+
value = {
|
|
2161
|
+
base_url: ctx.base,
|
|
2162
|
+
mcp_version: data.mcp_version,
|
|
2163
|
+
server: data.server,
|
|
2164
|
+
fetched_at: new Date(data.fetched_at).toISOString(),
|
|
2165
|
+
from_cache: fromCache,
|
|
2166
|
+
count: summaries.length,
|
|
2167
|
+
tools: summaries
|
|
2168
|
+
};
|
|
2169
|
+
}
|
|
2170
|
+
await emit(value, { format, select: opts.select, out: opts.out });
|
|
2171
|
+
});
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
// src/mcp/result.ts
|
|
2175
|
+
var MAX_ERROR_TEXT = 2e3;
|
|
2176
|
+
function textOf(result) {
|
|
2177
|
+
return (result.content ?? []).map((block) => block.type === "text" ? block.text : "").filter(Boolean).join("\n");
|
|
2178
|
+
}
|
|
2179
|
+
function extractValue(result) {
|
|
2180
|
+
if (result.structuredContent !== void 0 && result.structuredContent !== null) {
|
|
2181
|
+
return result.structuredContent;
|
|
2182
|
+
}
|
|
2183
|
+
const blocks = result.content ?? [];
|
|
2184
|
+
const only = blocks.length === 1 ? blocks[0] : void 0;
|
|
2185
|
+
if (only && only.type === "text") {
|
|
2186
|
+
try {
|
|
2187
|
+
return JSON.parse(only.text);
|
|
2188
|
+
} catch {
|
|
2189
|
+
return { text: only.text };
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
return { content: blocks };
|
|
2193
|
+
}
|
|
2194
|
+
function creditCostOf(result) {
|
|
2195
|
+
const cost = result._meta?.creditCost;
|
|
2196
|
+
return typeof cost === "number" && Number.isFinite(cost) ? cost : null;
|
|
2197
|
+
}
|
|
2198
|
+
function interpretResult(result, toolName) {
|
|
2199
|
+
if (result.isError) {
|
|
2200
|
+
const text = redact(textOf(result)).slice(0, MAX_ERROR_TEXT) || "The tool reported an error.";
|
|
2201
|
+
const code = result._meta?.errorCode;
|
|
2202
|
+
if (code === "credit_limit_exceeded") {
|
|
2203
|
+
throw new HgiError("credit_limit_exceeded", text, {
|
|
2204
|
+
hint: "Your organization has used its credit allowance. Contact your admin; retrying will not help.",
|
|
2205
|
+
details: { tool: toolName }
|
|
2206
|
+
});
|
|
2207
|
+
}
|
|
2208
|
+
throw new HgiError("tool_error", text, { details: { tool: toolName } });
|
|
2209
|
+
}
|
|
2210
|
+
return { value: extractValue(result), creditCost: creditCostOf(result) };
|
|
2211
|
+
}
|
|
2212
|
+
|
|
2213
|
+
// src/mcp/validate.ts
|
|
2214
|
+
import Ajv2020 from "ajv/dist/2020.js";
|
|
2215
|
+
import addFormats from "ajv-formats";
|
|
2216
|
+
var ajv = new Ajv2020.default({ strict: false, allErrors: true, allowUnionTypes: true });
|
|
2217
|
+
addFormats.default(ajv);
|
|
2218
|
+
function validateInput(tool, input) {
|
|
2219
|
+
const { $schema: _ignored, ...schema } = tool.inputSchema;
|
|
2220
|
+
void _ignored;
|
|
2221
|
+
let validate;
|
|
2222
|
+
try {
|
|
2223
|
+
validate = ajv.compile(schema);
|
|
2224
|
+
} catch (err) {
|
|
2225
|
+
debug("skipping client-side validation; schema did not compile", err.message);
|
|
2226
|
+
return [];
|
|
2227
|
+
}
|
|
2228
|
+
if (validate(input)) return [];
|
|
2229
|
+
return (validate.errors ?? []).map((e) => ({
|
|
2230
|
+
path: e.instancePath || "/",
|
|
2231
|
+
message: e.message ?? "invalid"
|
|
2232
|
+
}));
|
|
2233
|
+
}
|
|
2234
|
+
function assertValidInput(tool, input) {
|
|
2235
|
+
const issues = validateInput(tool, input);
|
|
2236
|
+
if (issues.length === 0) return;
|
|
2237
|
+
const first = issues[0];
|
|
2238
|
+
throw new HgiError("invalid_input", `Input for ${tool.name} is invalid: ${first?.path} ${first?.message}.`, {
|
|
2239
|
+
hint: "See `hgi tools list --json` for the tool schema.",
|
|
2240
|
+
details: { reason: "schema", errors: issues.slice(0, 20) }
|
|
2241
|
+
});
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
// src/commands/invoke.ts
|
|
2245
|
+
function parseTimeoutMs(raw) {
|
|
2246
|
+
const seconds = Number(raw);
|
|
2247
|
+
if (!Number.isFinite(seconds) || seconds <= 0) {
|
|
2248
|
+
throw new HgiError("invalid_input", "--timeout must be a positive number of seconds.", {
|
|
2249
|
+
details: { reason: "bad_timeout" }
|
|
2250
|
+
});
|
|
2251
|
+
}
|
|
2252
|
+
return seconds * 1e3;
|
|
2253
|
+
}
|
|
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
|
+
async function readInput(raw) {
|
|
2260
|
+
if (raw === void 0) return {};
|
|
2261
|
+
let text = raw;
|
|
2262
|
+
if (raw === "-") text = await readStdin();
|
|
2263
|
+
else if (raw.startsWith("@")) text = readInputFile(raw.slice(1), protectedDirs());
|
|
2264
|
+
let parsed;
|
|
2265
|
+
try {
|
|
2266
|
+
parsed = JSON.parse(text);
|
|
2267
|
+
} catch {
|
|
2268
|
+
throw new HgiError("invalid_input", "--input is not valid JSON.", {
|
|
2269
|
+
hint: `Pass a JSON object, e.g. --input '{"domain":"example.com"}'. Use @file or - to read from a file or stdin.`,
|
|
2270
|
+
details: { reason: "invalid_json" }
|
|
2271
|
+
});
|
|
2272
|
+
}
|
|
2273
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
2274
|
+
throw new HgiError("invalid_input", "--input must be a JSON object.", { details: { reason: "input_not_object" } });
|
|
2275
|
+
}
|
|
2276
|
+
return parsed;
|
|
2277
|
+
}
|
|
2278
|
+
function suggest(name, tools) {
|
|
2279
|
+
const needle = name.toLowerCase();
|
|
2280
|
+
return tools.map((t) => t.name).filter((n) => n.toLowerCase().includes(needle) || needle.includes(n.toLowerCase())).slice(0, 5);
|
|
2281
|
+
}
|
|
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
|
+
function assertVerb(requested, tool) {
|
|
2289
|
+
const expected = verbFor(tool);
|
|
2290
|
+
if (requested === expected) return;
|
|
2291
|
+
const why = expected === "run" ? "it changes state or starts work (or does not declare itself read-only)" : "it is read-only";
|
|
2292
|
+
throw new HgiError("wrong_verb", `${tool.name} must be run with \`hgi ${expected}\`: ${why}.`, {
|
|
2293
|
+
hint: `Use: hgi ${expected} ${tool.name} --input '<json>'. Nothing was sent.`,
|
|
2294
|
+
details: { tool: tool.name, expected_verb: expected, requested_verb: requested }
|
|
2295
|
+
});
|
|
2296
|
+
}
|
|
2297
|
+
async function runInvoke(verb, toolName, opts, cmd) {
|
|
2298
|
+
const input = await readInput(opts.input);
|
|
2299
|
+
preflightOutput({ format: opts.format, select: opts.select, out: opts.out, force: opts.force, allowForce: verb === "run" });
|
|
2300
|
+
const timeoutMs = parseTimeoutMs(opts.timeout);
|
|
2301
|
+
const ctx = buildContext(cmd);
|
|
2302
|
+
const creds = ctx.tokens.loadCredentials();
|
|
2303
|
+
const session = await openSession(ctx, { timeoutMs });
|
|
2304
|
+
try {
|
|
2305
|
+
const tools = await session.listTools();
|
|
2306
|
+
writeToolsCache(toolsCachePath(...mcpCacheKey(ctx.base, creds)), {
|
|
2307
|
+
fetched_at: Date.now(),
|
|
2308
|
+
mcp_version: session.state.mcpVersion,
|
|
2309
|
+
server: session.serverInfo,
|
|
2310
|
+
tools
|
|
2311
|
+
});
|
|
2312
|
+
const tool = tools.find((t) => t.name === toolName);
|
|
2313
|
+
if (!tool) {
|
|
2314
|
+
const near = suggest(toolName, tools);
|
|
2315
|
+
throw new HgiError("invalid_input", `Unknown tool "${toolName}".`, {
|
|
2316
|
+
hint: near.length ? `Did you mean: ${near.join(", ")}? Run \`hgi tools list\` for everything available.` : "Run `hgi tools list` for everything available.",
|
|
2317
|
+
details: { reason: "unknown_tool", tool: toolName, ...near.length ? { suggestions: near } : {} }
|
|
2318
|
+
});
|
|
2319
|
+
}
|
|
2320
|
+
assertVerb(verb, tool);
|
|
2321
|
+
if (opts.validate) assertValidInput(tool, input);
|
|
2322
|
+
const result = await session.callTool(toolName, input);
|
|
2323
|
+
const outcome = interpretResult(result, toolName);
|
|
2324
|
+
const selected = applySelect(outcome.value, opts.select);
|
|
2325
|
+
const value = opts.meta ? { result: selected, credit_cost: outcome.creditCost, mcp_version: session.state.mcpVersion } : selected;
|
|
2326
|
+
try {
|
|
2327
|
+
await emit(value, {
|
|
2328
|
+
format: opts.format,
|
|
2329
|
+
out: opts.out,
|
|
2330
|
+
force: opts.force,
|
|
2331
|
+
allowForce: verb === "run"
|
|
2332
|
+
});
|
|
2333
|
+
} catch (err) {
|
|
2334
|
+
if (!opts.out) throw err;
|
|
2335
|
+
const cause = toHgiError(err);
|
|
2336
|
+
try {
|
|
2337
|
+
await emit(value, { format: opts.format });
|
|
2338
|
+
} catch {
|
|
2339
|
+
}
|
|
2340
|
+
throw new HgiError("local_state_error", `The tool ran, but its result could not be written to ${opts.out}: ${cause.message}`, {
|
|
2341
|
+
hint: "The tool already ran and was billed; its result was printed to stdout instead. Do NOT re-run it.",
|
|
2342
|
+
details: { kind: "write_failed", reason: cause.details?.reason ?? cause.code, tool_ran: true },
|
|
2343
|
+
cause: err
|
|
2344
|
+
});
|
|
2345
|
+
} finally {
|
|
2346
|
+
reportCredit(outcome.creditCost);
|
|
2347
|
+
}
|
|
2348
|
+
} finally {
|
|
2349
|
+
await session.close();
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
function registerInvokeCommands(program) {
|
|
2353
|
+
const describeVerb = {
|
|
2354
|
+
call: "Run a read-only tool (lookups). Fails for tools that change state.",
|
|
2355
|
+
run: "Run a tool that changes state or starts work. Fails for read-only tools."
|
|
2356
|
+
};
|
|
2357
|
+
for (const verb of ["call", "run"]) {
|
|
2358
|
+
program.command(`${verb} <tool>`).description(describeVerb[verb]).option("--input <json>", "tool arguments as a JSON object; @file or - reads a file or stdin").option("-f, --format <format>", "json|jsonl|csv|yaml|table").option("--select <fields>", "keep only these comma-separated fields (dotted paths allowed)").option("--out <file>", "write the result to a new file instead of stdout").option("--force", verb === "run" ? "overwrite an existing --out file" : "not available on call").option("--meta", "print {result, credit_cost, mcp_version} instead of the bare result").option("--timeout <seconds>", "per-request timeout", "120").addOption(new Option("--no-validate", "skip client-side schema validation (let the server judge the input)").hideHelp()).action((tool, opts, cmd) => runInvoke(verb, tool, opts, cmd));
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
|
|
2362
|
+
// src/commands/skill.ts
|
|
2363
|
+
import fs5 from "fs";
|
|
2364
|
+
import os2 from "os";
|
|
2365
|
+
import path5 from "path";
|
|
2366
|
+
|
|
2367
|
+
// 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';
|
|
2369
|
+
|
|
2370
|
+
// src/commands/skill.ts
|
|
2371
|
+
function defaultSkillsDir() {
|
|
2372
|
+
const claude = process.env.CLAUDE_CONFIG_DIR ?? path5.join(os2.homedir(), ".claude");
|
|
2373
|
+
return path5.join(claude, "skills");
|
|
2374
|
+
}
|
|
2375
|
+
function refuse2(message, reason) {
|
|
2376
|
+
return new HgiError("invalid_input", message, { details: { reason } });
|
|
2377
|
+
}
|
|
2378
|
+
function installSkill(opts) {
|
|
2379
|
+
const skillsDir = path5.resolve(opts.dir ?? defaultSkillsDir());
|
|
2380
|
+
const targetDir = path5.join(skillsDir, "hgi");
|
|
2381
|
+
const target = path5.join(targetDir, "SKILL.md");
|
|
2382
|
+
for (const guarded of [skillsDir, targetDir]) {
|
|
2383
|
+
try {
|
|
2384
|
+
const st = fs5.lstatSync(guarded);
|
|
2385
|
+
if (st.isSymbolicLink()) throw refuse2(`Refusing to install through the symlink ${guarded}.`, "symlink");
|
|
2386
|
+
if (!st.isDirectory()) throw refuse2(`${guarded} is not a directory.`, "not_a_directory");
|
|
2387
|
+
} catch (err) {
|
|
2388
|
+
if (err instanceof HgiError) throw err;
|
|
2389
|
+
if (err.code !== "ENOENT") throw err;
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
2392
|
+
fs5.mkdirSync(targetDir, { recursive: true });
|
|
2393
|
+
let existing = null;
|
|
2394
|
+
try {
|
|
2395
|
+
existing = fs5.lstatSync(target);
|
|
2396
|
+
} catch {
|
|
2397
|
+
existing = null;
|
|
2398
|
+
}
|
|
2399
|
+
if (existing) {
|
|
2400
|
+
if (existing.isSymbolicLink() || !existing.isFile()) throw refuse2(`${target} is not a regular file.`, "not_regular_file");
|
|
2401
|
+
if (fs5.readFileSync(target, "utf8") === SKILL_MD) return { path: target, result: "unchanged" };
|
|
2402
|
+
if (!opts.force) {
|
|
2403
|
+
throw refuse2(`${target} already exists and differs.`, "exists");
|
|
2404
|
+
}
|
|
2405
|
+
fs5.unlinkSync(target);
|
|
2406
|
+
fs5.writeFileSync(target, SKILL_MD, { flag: "wx", mode: 420 });
|
|
2407
|
+
return { path: target, result: "replaced" };
|
|
2408
|
+
}
|
|
2409
|
+
fs5.writeFileSync(target, SKILL_MD, { flag: "wx", mode: 420 });
|
|
2410
|
+
return { path: target, result: "installed" };
|
|
2411
|
+
}
|
|
2412
|
+
function registerSkillCommands(program) {
|
|
2413
|
+
const skill = program.command("skill").description("Install the hgi skill for AI coding agents");
|
|
2414
|
+
skill.command("install").description("Copy SKILL.md to ~/.claude/skills/hgi so Claude Code discovers it").option("--dir <skills-dir>", "skills directory (default: ~/.claude/skills)").option("--force", "replace an existing, different SKILL.md").option("-f, --format <format>", "json|jsonl|csv|yaml|table").action(async (opts) => {
|
|
2415
|
+
await emit(installSkill(opts), { format: opts.format });
|
|
2416
|
+
});
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
// src/cli.ts
|
|
2420
|
+
function buildProgram() {
|
|
2421
|
+
const program = new Command();
|
|
2422
|
+
program.name("hgi").description("Command-line client for the HG Insights MCP server").version(VERSION, "-V, --version", "print the hgi version").option("--base-url <url>", "server origin (default: $HGI_BASE_URL or https://phoenix.hginsights.com)").option("--debug", "log requests to stderr (tokens are always redacted)").option("--json-errors", "always print errors as JSON on stderr").showHelpAfterError(false).exitOverride().configureOutput({ writeErr: () => void 0, outputError: () => void 0 });
|
|
2423
|
+
registerAuthCommands(program);
|
|
2424
|
+
registerToolsCommands(program);
|
|
2425
|
+
registerInvokeCommands(program);
|
|
2426
|
+
registerSkillCommands(program);
|
|
2427
|
+
return program;
|
|
2428
|
+
}
|
|
2429
|
+
function asCliError(err) {
|
|
2430
|
+
if (err instanceof CommanderError) {
|
|
2431
|
+
if (err.code === "commander.helpDisplayed" || err.code === "commander.version") return null;
|
|
2432
|
+
return new HgiError("invalid_input", err.message.replace(/^error: /, ""), {
|
|
2433
|
+
hint: "Run `hgi --help` for usage.",
|
|
2434
|
+
details: { reason: err.code }
|
|
2435
|
+
});
|
|
2436
|
+
}
|
|
2437
|
+
return err;
|
|
2438
|
+
}
|
|
2439
|
+
async function main(argv) {
|
|
2440
|
+
const jsonErrors = argv.includes("--json-errors") || !process.stderr.isTTY;
|
|
2441
|
+
try {
|
|
2442
|
+
await buildProgram().parseAsync(argv);
|
|
2443
|
+
return typeof process.exitCode === "number" ? process.exitCode : 0;
|
|
2444
|
+
} catch (raw) {
|
|
2445
|
+
const mapped = asCliError(raw);
|
|
2446
|
+
if (mapped === null) return 0;
|
|
2447
|
+
const err = toHgiError(mapped);
|
|
2448
|
+
process.stderr.write(renderError(err, jsonErrors));
|
|
2449
|
+
return err.exitCode;
|
|
2450
|
+
} finally {
|
|
2451
|
+
await closeHttp();
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
|
|
2455
|
+
// src/bin.ts
|
|
2456
|
+
ignoreEpipe(process.stdout, true);
|
|
2457
|
+
ignoreEpipe(process.stderr, false);
|
|
2458
|
+
main(process.argv).then((code) => {
|
|
2459
|
+
process.exitCode = code;
|
|
2460
|
+
setTimeout(() => process.exit(code), 1500).unref();
|
|
2461
|
+
});
|