@hginsights/hgi 0.2.0-rc.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -275,7 +275,7 @@ function classifyNetworkError(err, context = "the server", viaProxy) {
275
275
  }
276
276
 
277
277
  // src/config.ts
278
- var VERSION = true ? "0.2.0-rc.1" : "0.0.0-dev";
278
+ var VERSION = true ? "0.2.0" : "0.0.0-dev";
279
279
  var DEFAULT_BASE_URL = "https://phoenix.hginsights.com";
280
280
  var MCP_PATH = "/api/ai/mcp";
281
281
  var SCOPE = "mcp:read mcp:tools offline_access";
@@ -2100,9 +2100,22 @@ import {
2100
2100
 
2101
2101
  // src/mcp/transport-fetch.ts
2102
2102
  var RETRY_BUDGET_MS = 6e4;
2103
+ var RETRIES_BUDGET_MS = 6e5;
2103
2104
  var MAX_RATE_RETRIES = 3;
2104
2105
  var MAX_TRANSIENT_RETRIES = 2;
2105
2106
  var PRE_DISPATCH_CODES = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"]);
2107
+ function retryLimits(opts) {
2108
+ const configured = opts.retries !== void 0 || opts.retryBudgetMs !== void 0;
2109
+ const budgetMs = opts.retryBudgetMs ?? (opts.retries !== void 0 ? RETRIES_BUDGET_MS : RETRY_BUDGET_MS);
2110
+ if (opts.retries !== void 0) {
2111
+ return { rate: opts.retries, shed: opts.retries, transient: opts.retries, shared: false, budgetMs, configured };
2112
+ }
2113
+ return { rate: MAX_RATE_RETRIES, shed: MAX_RATE_RETRIES, transient: MAX_TRANSIENT_RETRIES, shared: true, budgetMs, configured };
2114
+ }
2115
+ function maxHttpSends(limits) {
2116
+ const retries = (limits.shared ? limits.rate : limits.rate + limits.shed) + limits.transient;
2117
+ return 2 * (1 + retries);
2118
+ }
2106
2119
  function rpcMethod(init) {
2107
2120
  const body = init?.body;
2108
2121
  if (typeof body !== "string") return void 0;
@@ -2128,6 +2141,7 @@ function createTransportFetch(authed, state, opts) {
2128
2141
  const wait = opts.sleepFn ?? sleep;
2129
2142
  const now = opts.now ?? Date.now;
2130
2143
  const random = opts.random ?? Math.random;
2144
+ const limits = retryLimits(opts);
2131
2145
  return async (url, rawInit) => {
2132
2146
  const init = rawInit ?? {};
2133
2147
  const method = (init.method ?? "GET").toUpperCase();
@@ -2136,34 +2150,43 @@ function createTransportFetch(authed, state, opts) {
2136
2150
  const signal = init.signal;
2137
2151
  const started = now();
2138
2152
  let rateAttempts = 0;
2153
+ let shedAttempts = 0;
2139
2154
  let transientAttempts = 0;
2155
+ let sends = 0;
2156
+ const remaining = () => limits.budgetMs - (now() - started);
2157
+ const transientFits = () => !limits.configured || 500 * (transientAttempts + 1) <= remaining();
2158
+ const retryWait = async (code, attempt, max, ms) => {
2159
+ opts.onRetry?.({ attempt, max, code, wait_seconds: Math.round(ms / 100) / 10 });
2160
+ await wait(ms, signal);
2161
+ };
2140
2162
  for (; ; ) {
2141
2163
  if (signal?.aborted) throw signal.reason;
2142
2164
  let res;
2143
2165
  try {
2144
- if (isToolsCall) state.toolsCallWritten = true;
2166
+ if (isToolsCall) {
2167
+ state.toolsCallWritten = true;
2168
+ state.toolsCallSends += 1;
2169
+ }
2170
+ sends += 1;
2145
2171
  res = await authed(String(url), init, { redirectKind: "mcp", context: "the MCP server", timeoutMs: opts.timeoutMs });
2146
2172
  } catch (err) {
2147
2173
  if (!(err instanceof HgiError) || err.code !== "server_unreachable") throw err;
2148
2174
  const cause = networkErrorCode(err.cause) ?? err.details?.cause;
2175
+ const preDispatch = Boolean(cause && PRE_DISPATCH_CODES.has(cause));
2176
+ if ((!isToolsCall || preDispatch) && transientAttempts < limits.transient && transientFits()) {
2177
+ transientAttempts += 1;
2178
+ await retryWait("not_established", transientAttempts, limits.transient, 500 * transientAttempts);
2179
+ continue;
2180
+ }
2181
+ const attempts = preDispatch || transientAttempts > 0 ? { attempts: sends } : {};
2149
2182
  if (isToolsCall) {
2150
- if (cause && PRE_DISPATCH_CODES.has(cause) && transientAttempts < MAX_TRANSIENT_RETRIES) {
2151
- transientAttempts += 1;
2152
- await wait(500 * transientAttempts, signal);
2153
- continue;
2154
- }
2155
2183
  throw new HgiError("server_unreachable", err.message, {
2156
2184
  hint: "The call may or may not have run. Check state before re-running.",
2157
- details: { ...err.details, outcome_unknown: true },
2185
+ details: { ...err.details, outcome_unknown: true, ...attempts },
2158
2186
  cause: err.cause
2159
2187
  });
2160
2188
  }
2161
- if (transientAttempts < MAX_TRANSIENT_RETRIES) {
2162
- transientAttempts += 1;
2163
- await wait(500 * transientAttempts, signal);
2164
- continue;
2165
- }
2166
- throw err;
2189
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, attempts: sends }, cause: err.cause });
2167
2190
  }
2168
2191
  const headerVersion = res.headers.get("x-mcp-version");
2169
2192
  if (headerVersion) state.mcpVersion = headerVersion;
@@ -2171,17 +2194,17 @@ function createTransportFetch(authed, state, opts) {
2171
2194
  if (res.status === 429) {
2172
2195
  const header = parseRetryAfter(res.headers.get("retry-after"));
2173
2196
  await res.body?.cancel().catch(() => void 0);
2174
- const delaySec = header ?? Math.min(2 ** (rateAttempts + 1), 30) + random();
2175
- const remaining = RETRY_BUDGET_MS - (now() - started);
2176
- if (rateAttempts >= MAX_RATE_RETRIES || delaySec * 1e3 > remaining) {
2197
+ const used = limits.shared ? rateAttempts + shedAttempts : rateAttempts;
2198
+ const delaySec = header ?? Math.min(2 ** (used + 1), 30) + random();
2199
+ if (used >= limits.rate || delaySec * 1e3 > remaining()) {
2177
2200
  throw new HgiError("rate_limited", "The organization is being rate limited by the server.", {
2178
2201
  hint: "Wait and retry; the limit is shared by every hgi process in your organization.",
2179
- details: { retry_after_seconds: header ?? Math.ceil(delaySec) }
2202
+ details: { retry_after_seconds: header ?? Math.ceil(delaySec), attempts: sends }
2180
2203
  });
2181
2204
  }
2182
2205
  rateAttempts += 1;
2183
2206
  debug("429, waiting", delaySec);
2184
- await wait(delaySec * 1e3 + random() * 250, signal);
2207
+ await retryWait("rate_limited", used + 1, limits.rate, delaySec * 1e3 + random() * 250);
2185
2208
  continue;
2186
2209
  }
2187
2210
  if (res.status === 403) {
@@ -2195,15 +2218,15 @@ function createTransportFetch(authed, state, opts) {
2195
2218
  const shed = await isShed(res);
2196
2219
  if (shed) {
2197
2220
  const header = parseRetryAfter(res.headers.get("retry-after")) ?? 1;
2198
- const remaining = RETRY_BUDGET_MS - (now() - started);
2199
- if (rateAttempts >= MAX_RATE_RETRIES || header * 1e3 > remaining) {
2221
+ const used = limits.shared ? rateAttempts + shedAttempts : shedAttempts;
2222
+ if (used >= limits.shed || header * 1e3 > remaining()) {
2200
2223
  throw new HgiError("server_unreachable", "The server is shedding load (503).", {
2201
2224
  hint: "Nothing was run; retrying is safe.",
2202
- details: { status: 503, outcome_unknown: false, retry_after_seconds: header }
2225
+ details: { status: 503, outcome_unknown: false, retry_after_seconds: header, attempts: sends }
2203
2226
  });
2204
2227
  }
2205
- rateAttempts += 1;
2206
- await wait(header * 1e3 + random() * 250, signal);
2228
+ shedAttempts += 1;
2229
+ await retryWait("load_shed", used + 1, limits.shed, header * 1e3 + random() * 250);
2207
2230
  continue;
2208
2231
  }
2209
2232
  if (isToolsCall) {
@@ -2212,14 +2235,14 @@ function createTransportFetch(authed, state, opts) {
2212
2235
  details: { status: res.status, outcome_unknown: true }
2213
2236
  });
2214
2237
  }
2215
- if ([502, 503, 504].includes(res.status) && transientAttempts < MAX_TRANSIENT_RETRIES) {
2238
+ if ([502, 503, 504].includes(res.status) && transientAttempts < limits.transient && transientFits()) {
2216
2239
  transientAttempts += 1;
2217
- await wait(500 * transientAttempts, signal);
2240
+ await retryWait("not_established", transientAttempts, limits.transient, 500 * transientAttempts);
2218
2241
  continue;
2219
2242
  }
2220
2243
  throw new HgiError("server_unreachable", `The server returned HTTP ${res.status}.`, {
2221
2244
  hint: "Retry in a moment.",
2222
- details: { status: res.status }
2245
+ details: { status: res.status, ...[502, 503, 504].includes(res.status) ? { attempts: sends } : {} }
2223
2246
  });
2224
2247
  }
2225
2248
  return res;
@@ -2286,20 +2309,25 @@ function mapMcpErrorInner(err, state) {
2286
2309
  }
2287
2310
  return toHgiError(err);
2288
2311
  }
2312
+ function sdkTimeoutMs(timeoutMs, retry = {}) {
2313
+ const limits = retryLimits(retry);
2314
+ const sends = maxHttpSends(limits);
2315
+ return timeoutMs * sends + limits.budgetMs + 250 * sends + 5e3;
2316
+ }
2289
2317
  async function openSession(ctx, opts) {
2290
- const state = { mcpVersion: null, toolsCallWritten: false };
2318
+ const state = { mcpVersion: null, toolsCallWritten: false, toolsCallSends: 0 };
2291
2319
  const transport = new StreamableHTTPClientTransport(new URL(mcpUrl(ctx.base)), {
2292
- fetch: createTransportFetch(ctx.authedFetch, state, { timeoutMs: opts.timeoutMs })
2320
+ fetch: createTransportFetch(ctx.authedFetch, state, { timeoutMs: opts.timeoutMs, ...opts.retry })
2293
2321
  });
2294
2322
  const client = new Client({ name: "hgi", version: VERSION }, { capabilities: {} });
2323
+ const requestOptions = { timeout: sdkTimeoutMs(opts.timeoutMs, opts.retry) };
2295
2324
  try {
2296
- await client.connect(transport);
2325
+ await client.connect(transport, requestOptions);
2297
2326
  } catch (err) {
2298
2327
  await transport.close().catch(() => void 0);
2299
2328
  throw mapMcpError(err, state);
2300
2329
  }
2301
2330
  const info = client.getServerVersion();
2302
- const requestOptions = { timeout: opts.timeoutMs };
2303
2331
  return {
2304
2332
  state,
2305
2333
  serverInfo: info ? { name: info.name, version: info.version } : null,
@@ -2921,17 +2949,27 @@ function normalize(kind, text) {
2921
2949
  return kind === "id" ? normalizeId(text) : normalizeDomain(text);
2922
2950
  }
2923
2951
 
2924
- // src/batch/plan.ts
2925
- var DEFAULT_BATCH_SIZE = 25;
2926
- var FIELD_FOR = { id: "hg_ids", domain: "domains" };
2927
- var ID_MATCH_KEYS = ["company_id", "requested_hg_id", "organization_id"];
2928
- var DOMAIN_MATCH_KEY = "company_domain";
2952
+ // src/mcp/schema-shape.ts
2929
2953
  function isRecord(value) {
2930
2954
  return typeof value === "object" && value !== null && !Array.isArray(value);
2931
2955
  }
2932
2956
  function hasType(schema, type) {
2933
2957
  return schema.type === type || Array.isArray(schema.type) && schema.type.includes(type);
2934
2958
  }
2959
+ function isArrayOfObjects(schema) {
2960
+ if (!isRecord(schema) || !hasType(schema, "array")) return false;
2961
+ const items = schema.items;
2962
+ return isRecord(items) && (hasType(items, "object") || isRecord(items.properties));
2963
+ }
2964
+ function propertiesOf(schema) {
2965
+ return isRecord(schema) && isRecord(schema.properties) ? schema.properties : {};
2966
+ }
2967
+
2968
+ // src/batch/plan.ts
2969
+ var DEFAULT_BATCH_SIZE = 25;
2970
+ var FIELD_FOR = { id: "hg_ids", domain: "domains" };
2971
+ var ID_MATCH_KEYS = ["company_id", "requested_hg_id", "organization_id"];
2972
+ var DOMAIN_MATCH_KEY = "company_domain";
2935
2973
  function batchFields(tool) {
2936
2974
  const props = isRecord(tool.inputSchema.properties) ? tool.inputSchema.properties : {};
2937
2975
  const fields = {};
@@ -2950,12 +2988,7 @@ function batchFields(tool) {
2950
2988
  return fields;
2951
2989
  }
2952
2990
  function entriesKey(tool) {
2953
- const props = isRecord(tool.outputSchema?.properties) ? tool.outputSchema.properties : {};
2954
- const candidates = Object.entries(props).filter(([, schema]) => {
2955
- if (!isRecord(schema) || !hasType(schema, "array")) return false;
2956
- const items = schema.items;
2957
- return isRecord(items) && (hasType(items, "object") || isRecord(items.properties));
2958
- });
2991
+ const candidates = Object.entries(propertiesOf(tool.outputSchema)).filter(([, schema]) => isArrayOfObjects(schema));
2959
2992
  return candidates.length === 1 ? candidates[0][0] : "companies";
2960
2993
  }
2961
2994
  function buildBatches(input, fields, batchSize) {
@@ -3048,6 +3081,41 @@ function reportCredit(cost) {
3048
3081
  ` : `credit_cost: ${cost ?? "unknown"}
3049
3082
  `);
3050
3083
  }
3084
+ function roundWait(ms) {
3085
+ return Math.round(ms / 100) / 10;
3086
+ }
3087
+ function reportRetry(e) {
3088
+ const event = { attempt: e.attempt, max: e.max, code: e.code, wait_seconds: e.wait_seconds };
3089
+ process.stderr.write(
3090
+ stderrWantsJson() ? `${JSON.stringify({ retry: event })}
3091
+ ` : `hgi: retry ${event.attempt}/${event.max}: ${event.code}, waiting ${event.wait_seconds}s
3092
+ `
3093
+ );
3094
+ }
3095
+
3096
+ // src/commands/retry.ts
3097
+ var GOVERNANCE_MAX_WAIT_SECONDS = 30;
3098
+ function isGovernanceUnavailable(result) {
3099
+ return result.isError === true && result._meta?.errorCode === "governance_unavailable";
3100
+ }
3101
+ async function sendWithRetry(session, name, args, opts) {
3102
+ const sleep2 = opts.sleep ?? sleep;
3103
+ const now = opts.now ?? Date.now;
3104
+ const random = opts.random ?? Math.random;
3105
+ const sendsBefore = session.state.toolsCallSends;
3106
+ const started = now();
3107
+ for (let attempt = 1; ; attempt += 1) {
3108
+ const result = await session.callTool(name, args);
3109
+ const budgetFailure = await opts.record(result);
3110
+ const outcome = () => ({ result, attempts: session.state.toolsCallSends - sendsBefore, budgetFailure });
3111
+ if (budgetFailure || attempt > opts.retries || !isGovernanceUnavailable(result)) return outcome();
3112
+ const waitMs = random() * Math.min(2 ** attempt, GOVERNANCE_MAX_WAIT_SECONDS) * 1e3;
3113
+ if (waitMs > opts.budgetMs - (now() - started)) return outcome();
3114
+ opts.report({ attempt, max: opts.retries, code: "governance_unavailable", wait_seconds: roundWait(waitMs) });
3115
+ await sleep2(waitMs);
3116
+ await opts.beforeResend?.();
3117
+ }
3118
+ }
3051
3119
 
3052
3120
  // src/commands/batch.ts
3053
3121
  function usage(message, reason, hint, extra = {}) {
@@ -3111,6 +3179,8 @@ var Run = class {
3111
3179
  rowErrors = 0;
3112
3180
  cursor = 0;
3113
3181
  callsMade = 0;
3182
+ /** `tools/call` re-sends across all batch calls (transport retries and governance re-sends). */
3183
+ retries = 0;
3114
3184
  callsWithoutCost = 0;
3115
3185
  creditSum = 0;
3116
3186
  failedBatches = 0;
@@ -3152,17 +3222,28 @@ async function callBatch(run, session, tool, input, batch, key, opts) {
3152
3222
  run.callsMade += 1;
3153
3223
  let result;
3154
3224
  let budgetFailure = null;
3225
+ const sendsBefore = session.state.toolsCallSends;
3226
+ const governanceRetries = opts.governance?.retries ?? 0;
3227
+ let attempts = 1;
3155
3228
  try {
3156
- result = await session.callTool(tool.name, argsFor(input, batch));
3229
+ ({ result, budgetFailure, attempts } = await sendWithRetry(session, tool.name, argsFor(input, batch), {
3230
+ retries: governanceRetries,
3231
+ budgetMs: opts.governance?.budgetMs ?? 0,
3232
+ // Every attempt that came back: one ledger row, and its spend under a run cap.
3233
+ record: async (r) => {
3234
+ await opts.onResult?.(r);
3235
+ if (!budget) return null;
3236
+ try {
3237
+ await recordSpend(budget.id, budget.max, creditCostOf(r));
3238
+ return null;
3239
+ } catch (err) {
3240
+ return toHgiError(err);
3241
+ }
3242
+ },
3243
+ beforeResend: budget ? () => checkBatchBudget(budget, run) : void 0,
3244
+ report: reportRetry
3245
+ }));
3157
3246
  run.addCost(result);
3158
- await opts.onResult?.(result);
3159
- if (budget) {
3160
- try {
3161
- await recordSpend(budget.id, budget.max, creditCostOf(result));
3162
- } catch (err) {
3163
- budgetFailure = toHgiError(err);
3164
- }
3165
- }
3166
3247
  const outcome = interpretResult(result, tool.name);
3167
3248
  const index = matchEntries(batch.kind, outcome.value, key);
3168
3249
  if (!index) {
@@ -3177,10 +3258,16 @@ async function callBatch(run, session, tool, input, batch, key, opts) {
3177
3258
  if (!result) run.addCost(void 0);
3178
3259
  const err = toHgiError(raw);
3179
3260
  if (err.code !== "tool_error" || err.details?.outcome_unknown === true) {
3180
- if (budgetFailure) throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, budget_write_failed: true }, cause: err });
3261
+ const retried = governanceRetries > 0 && err.code === "governance_unavailable";
3262
+ if (budgetFailure || retried) {
3263
+ const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
3264
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, ...extra }, cause: err });
3265
+ }
3181
3266
  throw err;
3182
3267
  }
3183
3268
  run.failBatch(batch, rowError(err.code, err.message));
3269
+ } finally {
3270
+ run.retries += Math.max(0, session.state.toolsCallSends - sendsBefore - 1);
3184
3271
  }
3185
3272
  return budgetFailure;
3186
3273
  }
@@ -3201,6 +3288,7 @@ function printMeta(run) {
3201
3288
  process.stderr.write(
3202
3289
  `${JSON.stringify({
3203
3290
  calls: run.callsMade,
3291
+ retries: run.retries,
3204
3292
  rows: run.rows.length,
3205
3293
  row_errors: run.rowErrors,
3206
3294
  credit_cost: run.creditCost(),
@@ -3304,7 +3392,406 @@ async function runBatch(session, tool, input, lines, opts) {
3304
3392
  }
3305
3393
  }
3306
3394
 
3395
+ // src/mcp/paging.ts
3396
+ var NAMED_TOTALS = ["total", "total_count", "totalCount"];
3397
+ var PAGE_SIZE_KEYS = ["limit", "max_results"];
3398
+ function isNumeric(schema) {
3399
+ return isRecord(schema) && (hasType(schema, "integer") || hasType(schema, "number"));
3400
+ }
3401
+ function isPositiveInt(value) {
3402
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
3403
+ }
3404
+ function totalKeyOf(props, rowsKey) {
3405
+ for (const key of NAMED_TOTALS) {
3406
+ if (Object.hasOwn(props, key) && isNumeric(props[key])) return key;
3407
+ }
3408
+ const candidates = Object.keys(props).filter(
3409
+ (key) => key.startsWith("total_") && isNumeric(props[key]) && key.split("_").includes(rowsKey)
3410
+ );
3411
+ return candidates.length === 1 ? candidates[0] : void 0;
3412
+ }
3413
+ function pageObjectSpec(schema) {
3414
+ const props = propertiesOf(schema);
3415
+ const arrays = Object.keys(props).filter((key) => isArrayOfObjects(props[key]));
3416
+ if (arrays.length !== 1) return null;
3417
+ const rowsKey = arrays[0];
3418
+ const hasMoreKey = Object.hasOwn(props, "has_more") ? "has_more" : Object.hasOwn(props, "hasMore") ? "hasMore" : void 0;
3419
+ const totalKey = totalKeyOf(props, rowsKey);
3420
+ if (hasMoreKey === void 0 && totalKey === void 0) return null;
3421
+ return { rowsKey, ...hasMoreKey ? { hasMoreKey } : {}, ...totalKey ? { totalKey } : {} };
3422
+ }
3423
+ function pageSizeOfSchema(inputProps) {
3424
+ const declared = PAGE_SIZE_KEYS.filter((key2) => Object.hasOwn(inputProps, key2));
3425
+ if (declared.length !== 1) return {};
3426
+ const key = declared[0];
3427
+ const schema = inputProps[key];
3428
+ const fallback = isRecord(schema) ? schema.default : void 0;
3429
+ return { pageSizeKey: key, ...isPositiveInt(fallback) ? { pageSizeDefault: fallback } : {} };
3430
+ }
3431
+ function pagingSpec(tool) {
3432
+ const inputProps = propertiesOf(tool.inputSchema);
3433
+ const offset = inputProps.offset;
3434
+ if (!isRecord(offset) || !hasType(offset, "integer")) return null;
3435
+ if (!isRecord(tool.outputSchema)) return null;
3436
+ const size = pageSizeOfSchema(inputProps);
3437
+ const top = pageObjectSpec(tool.outputSchema);
3438
+ if (top) return { kind: "top", ...top, ...size };
3439
+ const outputProps = propertiesOf(tool.outputSchema);
3440
+ const itemSpecs = Object.keys(outputProps).filter((key) => isArrayOfObjects(outputProps[key])).map((key) => ({ key, spec: pageObjectSpec(outputProps[key].items) })).filter((c) => c.spec !== null);
3441
+ if (itemSpecs.length !== 1) return null;
3442
+ const only = itemSpecs[0];
3443
+ return { kind: "items", itemsKey: only.key, ...only.spec, ...size };
3444
+ }
3445
+ function pageSizeOf(spec, input) {
3446
+ if (spec.pageSizeKey === void 0) return void 0;
3447
+ const sent = input[spec.pageSizeKey];
3448
+ if (isPositiveInt(sent)) return sent;
3449
+ return spec.pageSizeDefault;
3450
+ }
3451
+ function stopReason(state, pageSize, maxPages) {
3452
+ if (state.hasMore === false) return "done";
3453
+ if (state.pageRows === 0) return "done";
3454
+ if (pageSize !== void 0 && state.pageRows < pageSize) return "done";
3455
+ if (typeof state.total === "number" && Number.isFinite(state.total) && state.collected >= state.total) return "done";
3456
+ if (state.pages >= maxPages) return "max_pages";
3457
+ return null;
3458
+ }
3459
+
3460
+ // src/commands/paging.ts
3461
+ var DEFAULT_MAX_PAGES = 10;
3462
+ function usage2(message, reason, extra = {}) {
3463
+ return new HgiError("invalid_input", message, { hint: "Nothing was sent.", details: { reason, ...extra } });
3464
+ }
3465
+ function preflightPaging(flags, input) {
3466
+ if (!flags.allPages) {
3467
+ if (flags.maxPages !== void 0) throw usage2("--max-pages needs --all-pages.", "max_pages_without_all_pages");
3468
+ return null;
3469
+ }
3470
+ let maxPages = DEFAULT_MAX_PAGES;
3471
+ if (flags.maxPages !== void 0) {
3472
+ const raw = flags.maxPages.trim();
3473
+ const n = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
3474
+ if (!Number.isSafeInteger(n) || n < 1) throw usage2(`--max-pages must be a whole number of at least 1, not "${flags.maxPages}".`, "bad_max_pages");
3475
+ maxPages = n;
3476
+ }
3477
+ if (flags.ids !== void 0) throw usage2("--all-pages cannot be combined with --ids yet.", "all_pages_with_ids");
3478
+ if (Object.hasOwn(input, "offset")) throw usage2('--all-pages sets "offset" itself; remove it from --input.', "offset_with_all_pages");
3479
+ return maxPages;
3480
+ }
3481
+ function assertPageable(tool) {
3482
+ const spec = pagingSpec(tool);
3483
+ if (spec) return spec;
3484
+ throw new HgiError("invalid_input", `${tool.name} cannot be paged safely with --all-pages.`, {
3485
+ hint: 'Its schema has no integer "offset" input, or its output has no single rows array with has_more or a total. Nothing was sent. Page it yourself with --input.',
3486
+ details: { reason: "not_pageable", tool: tool.name }
3487
+ });
3488
+ }
3489
+ var StopPaging = class extends Error {
3490
+ constructor(error) {
3491
+ super(error.message);
3492
+ this.error = error;
3493
+ }
3494
+ error;
3495
+ /** The merged result up to the stop, set by the loop that caught it. */
3496
+ merged;
3497
+ };
3498
+ function unexpected(tool, what) {
3499
+ return new HgiError("tool_error", `A later page of ${tool.name} came back without ${what}; paging stopped.`, {
3500
+ details: { reason: "unexpected_response", tool: tool.name }
3501
+ });
3502
+ }
3503
+ var Pager = class {
3504
+ constructor(ctx) {
3505
+ this.ctx = ctx;
3506
+ this.pageSize = pageSizeOf(ctx.spec, ctx.input);
3507
+ }
3508
+ ctx;
3509
+ acc = { callsMade: 0, retries: 0, callsWithoutCost: 0, creditSum: 0 };
3510
+ pageSize;
3511
+ /**
3512
+ * Sends one page. Page 1 was checked against the run cap before the session opened. A page whose spend could
3513
+ * not be recorded is returned with `budgetFailure`, so its rows are kept before paging stops.
3514
+ */
3515
+ async fetch(args, first) {
3516
+ const { session, tool, budget } = this.ctx;
3517
+ if (!first && budget) await checkBudget(budget.id, budget.max);
3518
+ if (!first && this.ctx.validate) assertValidInput(tool, args);
3519
+ this.acc.callsMade += 1;
3520
+ const sendsBefore = session.state.toolsCallSends;
3521
+ const governanceRetries = this.ctx.governance?.retries ?? 0;
3522
+ let sent;
3523
+ try {
3524
+ sent = await sendWithRetry(session, tool.name, args, {
3525
+ retries: governanceRetries,
3526
+ budgetMs: this.ctx.governance?.budgetMs ?? 0,
3527
+ // Every attempt that came back: one ledger row, and its spend under a run cap.
3528
+ record: async (r) => {
3529
+ await this.ctx.onResult?.(r);
3530
+ if (!budget) return null;
3531
+ try {
3532
+ await recordSpend(budget.id, budget.max, creditCostOf(r));
3533
+ return null;
3534
+ } catch (err) {
3535
+ return toHgiError(err);
3536
+ }
3537
+ },
3538
+ beforeResend: budget ? async () => void await checkBudget(budget.id, budget.max) : void 0,
3539
+ report: reportRetry
3540
+ });
3541
+ } catch (err) {
3542
+ this.acc.callsWithoutCost += 1;
3543
+ throw err;
3544
+ } finally {
3545
+ this.acc.retries += Math.max(0, session.state.toolsCallSends - sendsBefore - 1);
3546
+ }
3547
+ const { result, attempts, budgetFailure } = sent;
3548
+ const cost = creditCostOf(result);
3549
+ if (cost === null) this.acc.callsWithoutCost += 1;
3550
+ else this.acc.creditSum += cost;
3551
+ try {
3552
+ return { value: interpretResult(result, tool.name).value, budgetFailure };
3553
+ } catch (err) {
3554
+ const retried = governanceRetries > 0 && err instanceof HgiError && err.code === "governance_unavailable";
3555
+ if ((budgetFailure || retried) && err instanceof HgiError) {
3556
+ const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
3557
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, ...extra }, cause: err });
3558
+ }
3559
+ throw err;
3560
+ }
3561
+ }
3562
+ /** A follow-up page: any failure stops paging. */
3563
+ async fetchLater(args) {
3564
+ try {
3565
+ return await this.fetch(args, false);
3566
+ } catch (err) {
3567
+ throw new StopPaging(toHgiError(err));
3568
+ }
3569
+ }
3570
+ track(entry) {
3571
+ const rows = entry[this.ctx.spec.rowsKey];
3572
+ const t = { entry, rows: Array.isArray(rows) ? [...rows] : null, pages: 0, done: false };
3573
+ this.settle(t, Array.isArray(rows) ? rows.length : 0);
3574
+ return t;
3575
+ }
3576
+ /** Applies the stop rule after a page with `pageRows` rows. */
3577
+ settle(t, pageRows) {
3578
+ t.pages += 1;
3579
+ const { hasMoreKey, totalKey } = this.ctx.spec;
3580
+ const reason = stopReason(
3581
+ {
3582
+ pageRows,
3583
+ collected: t.rows?.length ?? 0,
3584
+ pages: t.pages,
3585
+ hasMore: hasMoreKey ? t.entry[hasMoreKey] : void 0,
3586
+ total: totalKey ? t.entry[totalKey] : void 0
3587
+ },
3588
+ this.pageSize,
3589
+ this.ctx.maxPages
3590
+ );
3591
+ if (reason === null) return;
3592
+ t.done = true;
3593
+ if (reason === "max_pages") t.reason = "max_pages";
3594
+ }
3595
+ /** Adds a follow-up page object's rows to its tracker. */
3596
+ append(t, entry) {
3597
+ const rows = entry[this.ctx.spec.rowsKey];
3598
+ if (!Array.isArray(rows)) throw new StopPaging(unexpected(this.ctx.tool, `a "${this.ctx.spec.rowsKey}" array`));
3599
+ t.entry = entry;
3600
+ t.rows = [...t.rows ?? [], ...rows];
3601
+ this.settle(t, rows.length);
3602
+ }
3603
+ merged(t) {
3604
+ return {
3605
+ ...t.entry,
3606
+ ...t.rows === null ? {} : { [this.ctx.spec.rowsKey]: t.rows },
3607
+ pages_fetched: t.pages,
3608
+ ...t.reason === void 0 ? {} : { truncated: true, truncated_reason: t.reason }
3609
+ };
3610
+ }
3611
+ creditCost() {
3612
+ return this.acc.callsMade > this.acc.callsWithoutCost ? this.acc.creditSum : null;
3613
+ }
3614
+ };
3615
+ function companyInputs(input) {
3616
+ const out = [];
3617
+ for (const [field, kind] of [["hg_ids", "id"], ["domains", "domain"]]) {
3618
+ const values = input[field];
3619
+ if (!Array.isArray(values)) continue;
3620
+ for (const text of values) {
3621
+ if (typeof text === "string") out.push({ field, kind, text, norm: kind === "id" ? normalizeId(text) : normalizeDomain(text) });
3622
+ }
3623
+ }
3624
+ return out;
3625
+ }
3626
+ function entryKey(entry, kind) {
3627
+ if (kind === "domain") {
3628
+ const raw = keyText(entry[DOMAIN_MATCH_KEY]);
3629
+ return raw === null ? null : normalizeDomain(raw);
3630
+ }
3631
+ for (const key of ID_MATCH_KEYS) {
3632
+ const raw = keyText(entry[key]);
3633
+ if (raw !== null) return normalizeId(raw);
3634
+ }
3635
+ return null;
3636
+ }
3637
+ function matches(entry, input) {
3638
+ return entryKey(entry, input.kind) === input.norm;
3639
+ }
3640
+ function withoutCompanies(input) {
3641
+ const rest = { ...input };
3642
+ delete rest.hg_ids;
3643
+ delete rest.domains;
3644
+ return rest;
3645
+ }
3646
+ function planFollowUps(trackers, input) {
3647
+ const live = trackers.filter((t) => t !== null);
3648
+ const inputs = companyInputs(input);
3649
+ if (inputs.length < 2) {
3650
+ const named = inputs[0];
3651
+ for (const t of live) {
3652
+ if (t.done) continue;
3653
+ if (trackers.length === 1 && (named === void 0 || matches(t.entry, named))) {
3654
+ t.follow = "same";
3655
+ if (named) t.expect = { kind: named.kind, norm: named.norm };
3656
+ } else {
3657
+ Object.assign(t, { done: true, reason: "unmatched" });
3658
+ }
3659
+ }
3660
+ return;
3661
+ }
3662
+ const matchedBy = /* @__PURE__ */ new Map();
3663
+ const candidates = live.map((t) => inputs.map((inp, i) => matches(t.entry, inp) ? i : -1).filter((i) => i >= 0));
3664
+ for (const list of candidates) for (const i of list) matchedBy.set(i, (matchedBy.get(i) ?? 0) + 1);
3665
+ live.forEach((t, k) => {
3666
+ if (t.done) return;
3667
+ const list = candidates[k];
3668
+ const only = list.length === 1 ? list[0] : -1;
3669
+ if (only >= 0 && matchedBy.get(only) === 1) {
3670
+ const inp = inputs[only];
3671
+ t.follow = { field: inp.field, text: inp.text, kind: inp.kind, norm: inp.norm };
3672
+ } else {
3673
+ Object.assign(t, { done: true, reason: "unmatched" });
3674
+ }
3675
+ });
3676
+ }
3677
+ async function pageTop(p, ctx, first) {
3678
+ if (!isRecord(first)) return first;
3679
+ const t = p.track(first);
3680
+ try {
3681
+ while (!t.done) {
3682
+ const page = await p.fetchLater({ ...ctx.input, offset: t.rows?.length ?? 0 });
3683
+ if (!isRecord(page.value)) throw new StopPaging(unexpected(ctx.tool, "a result object"));
3684
+ p.append(t, page.value);
3685
+ if (page.budgetFailure) throw new StopPaging(page.budgetFailure);
3686
+ }
3687
+ } catch (err) {
3688
+ if (!(err instanceof StopPaging)) throw err;
3689
+ if (!t.done) Object.assign(t, { done: true, reason: err.error.code });
3690
+ err.merged = p.merged(t);
3691
+ throw err;
3692
+ }
3693
+ return p.merged(t);
3694
+ }
3695
+ async function pageItems(p, ctx, first) {
3696
+ const itemsKey = ctx.spec.itemsKey;
3697
+ if (!isRecord(first) || !Array.isArray(first[itemsKey])) return first;
3698
+ const entries = first[itemsKey];
3699
+ const trackers = entries.map((e) => isRecord(e) ? p.track(e) : null);
3700
+ planFollowUps(trackers, ctx.input);
3701
+ const merge = () => ({ ...first, [itemsKey]: entries.map((e, i) => trackers[i] ? p.merged(trackers[i]) : e) });
3702
+ try {
3703
+ for (const t of trackers) {
3704
+ while (t && !t.done) {
3705
+ const follow = t.follow;
3706
+ const args = follow === "same" ? { ...ctx.input, offset: t.rows?.length ?? 0 } : { ...withoutCompanies(ctx.input), [follow.field]: [follow.text], offset: t.rows?.length ?? 0 };
3707
+ const page = await p.fetchLater(args);
3708
+ if (!isRecord(page.value) || !Array.isArray(page.value[itemsKey])) {
3709
+ throw new StopPaging(unexpected(ctx.tool, `a "${itemsKey}" array`));
3710
+ }
3711
+ const list = page.value[itemsKey];
3712
+ const only = list.length === 1 && isRecord(list[0]) ? list[0] : null;
3713
+ const want = follow === "same" ? t.expect : follow;
3714
+ if (only === null || want !== void 0 && !matches(only, want)) {
3715
+ Object.assign(t, { done: true, reason: "unmatched" });
3716
+ } else {
3717
+ p.append(t, only);
3718
+ }
3719
+ if (page.budgetFailure) throw new StopPaging(page.budgetFailure);
3720
+ }
3721
+ }
3722
+ } catch (err) {
3723
+ if (!(err instanceof StopPaging)) throw err;
3724
+ for (const t of trackers) if (t && !t.done) Object.assign(t, { done: true, reason: err.error.code });
3725
+ err.merged = merge();
3726
+ throw err;
3727
+ }
3728
+ return merge();
3729
+ }
3730
+ async function runAllPages(ctx) {
3731
+ const p = new Pager(ctx);
3732
+ const first = await p.fetch(ctx.input, true);
3733
+ const outcome = (value, failure) => ({
3734
+ value,
3735
+ callsMade: p.acc.callsMade,
3736
+ retries: p.acc.retries,
3737
+ callsWithoutCost: p.acc.callsWithoutCost,
3738
+ creditCost: p.creditCost(),
3739
+ ...failure ? { failure } : {}
3740
+ });
3741
+ if (first.budgetFailure) {
3742
+ return { ...outcome(first.value, first.budgetFailure), pageOneBudgetFailure: true };
3743
+ }
3744
+ try {
3745
+ return outcome(ctx.spec.kind === "top" ? await pageTop(p, ctx, first.value) : await pageItems(p, ctx, first.value));
3746
+ } catch (err) {
3747
+ if (err instanceof StopPaging) return outcome(err.merged, err.error);
3748
+ throw err;
3749
+ }
3750
+ }
3751
+
3752
+ // src/commands/retry-options.ts
3753
+ var MAX_RETRIES = 20;
3754
+ var MAX_RETRY_BUDGET_SECONDS = 3600;
3755
+ function parseRetries(raw, source) {
3756
+ const trimmed = raw.trim();
3757
+ const value = /^\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN;
3758
+ if (!Number.isSafeInteger(value) || value > MAX_RETRIES) {
3759
+ throw new HgiError("invalid_input", `${source} must be a whole number from 0 to ${MAX_RETRIES}.`, {
3760
+ hint: "For example --retries 6. 0 turns every retry off.",
3761
+ details: { reason: "bad_retries" }
3762
+ });
3763
+ }
3764
+ return value;
3765
+ }
3766
+ function parseRetryBudget(raw, source) {
3767
+ const trimmed = raw.trim();
3768
+ const seconds = trimmed === "" ? Number.NaN : Number(trimmed);
3769
+ if (!Number.isFinite(seconds) || seconds <= 0 || seconds > MAX_RETRY_BUDGET_SECONDS) {
3770
+ throw new HgiError("invalid_input", `${source} must be a positive number of seconds, at most ${MAX_RETRY_BUDGET_SECONDS}.`, {
3771
+ hint: "For example --retry-budget 600.",
3772
+ details: { reason: "bad_retry_budget" }
3773
+ });
3774
+ }
3775
+ return seconds * 1e3;
3776
+ }
3777
+ function resolveRetryOptions(flags, env = process.env) {
3778
+ let retries = null;
3779
+ if (flags.retries !== void 0) retries = parseRetries(flags.retries, "--retries");
3780
+ else if (env.HGI_RETRIES) retries = parseRetries(env.HGI_RETRIES, "HGI_RETRIES");
3781
+ let retryBudgetMs = null;
3782
+ if (flags.retryBudget !== void 0) retryBudgetMs = parseRetryBudget(flags.retryBudget, "--retry-budget");
3783
+ else if (env.HGI_RETRY_BUDGET) retryBudgetMs = parseRetryBudget(env.HGI_RETRY_BUDGET, "HGI_RETRY_BUDGET");
3784
+ return { retries, retryBudgetMs };
3785
+ }
3786
+
3307
3787
  // src/commands/invoke.ts
3788
+ function transportRetryOptions(r) {
3789
+ return {
3790
+ ...r.retries !== null ? { retries: r.retries } : {},
3791
+ ...r.retryBudgetMs !== null ? { retryBudgetMs: r.retryBudgetMs } : {},
3792
+ onRetry: reportRetry
3793
+ };
3794
+ }
3308
3795
  function parseTimeoutMs(raw) {
3309
3796
  const seconds = Number(raw);
3310
3797
  if (!Number.isFinite(seconds) || seconds <= 0) {
@@ -3346,7 +3833,7 @@ function assertVerb(requested, tool) {
3346
3833
  details: { tool: tool.name, expected_verb: expected, requested_verb: requested }
3347
3834
  });
3348
3835
  }
3349
- async function failAfterBudgetWrite(cause, value, opts, creditCost) {
3836
+ async function failAfterBudgetWrite(cause, value, opts, creditCost, extraDetails = {}) {
3350
3837
  try {
3351
3838
  await emit(value, { format: opts.format });
3352
3839
  } catch {
@@ -3355,15 +3842,84 @@ async function failAfterBudgetWrite(cause, value, opts, creditCost) {
3355
3842
  }
3356
3843
  throw new HgiError("local_state_error", `The tool ran, but ${cause.message.replace(/^Could not/, "hgi could not")}`, {
3357
3844
  hint: "The tool already ran and was billed; its result was printed to stdout. Do NOT re-run it. Check the budget with `hgi budget status`.",
3358
- details: { kind: "budget_write_failed", tool_ran: true },
3845
+ details: { kind: "budget_write_failed", tool_ran: true, ...extraDetails },
3359
3846
  cause
3360
3847
  });
3361
3848
  }
3849
+ async function emitResult(value, verb, opts, creditCost) {
3850
+ try {
3851
+ await emit(value, { format: opts.format, out: opts.out, force: opts.force, allowForce: verb === "run" });
3852
+ } catch (err) {
3853
+ if (!opts.out) throw err;
3854
+ const cause = toHgiError(err);
3855
+ try {
3856
+ await emit(value, { format: opts.format });
3857
+ } catch {
3858
+ }
3859
+ throw new HgiError("local_state_error", `The tool ran, but its result could not be written to ${opts.out}: ${cause.message}`, {
3860
+ hint: "The tool already ran and was billed; its result was printed to stdout instead. Do NOT re-run it.",
3861
+ details: { kind: "write_failed", reason: cause.details?.reason ?? cause.code, tool_ran: true },
3862
+ cause: err
3863
+ });
3864
+ } finally {
3865
+ reportCredit(creditCost);
3866
+ }
3867
+ }
3868
+ async function runPaged(ctx, verb, opts, mcpVersion) {
3869
+ const paged = await runAllPages(ctx);
3870
+ if (paged.pageOneBudgetFailure && paged.failure) {
3871
+ const one = applySelect(paged.value, opts.select);
3872
+ const value2 = opts.meta ? { result: one, credit_cost: paged.creditCost, mcp_version: mcpVersion() } : one;
3873
+ await failAfterBudgetWrite(paged.failure, value2, opts, paged.creditCost);
3874
+ }
3875
+ const selected = applySelect(paged.value, opts.select);
3876
+ const value = opts.meta ? {
3877
+ result: selected,
3878
+ credit_cost: paged.creditCost,
3879
+ mcp_version: mcpVersion(),
3880
+ pages_fetched: paged.callsMade,
3881
+ retries: paged.retries,
3882
+ calls_without_cost: paged.callsWithoutCost
3883
+ } : selected;
3884
+ const failure = paged.failure;
3885
+ if (!failure) {
3886
+ await emitResult(value, verb, opts, paged.creditCost);
3887
+ return;
3888
+ }
3889
+ const partial = { partial_result: true, pages_fetched: paged.callsMade };
3890
+ if (failure.code === "local_state_error" && failure.details?.kind === "budget_write_failed") {
3891
+ await failAfterBudgetWrite(failure, value, opts, paged.creditCost, partial);
3892
+ }
3893
+ let outFailed = false;
3894
+ try {
3895
+ await emit(value, { format: opts.format, out: opts.out, force: opts.force, allowForce: verb === "run" });
3896
+ } catch {
3897
+ if (opts.out) {
3898
+ outFailed = true;
3899
+ try {
3900
+ await emit(value, { format: opts.format });
3901
+ } catch {
3902
+ }
3903
+ }
3904
+ } finally {
3905
+ reportCredit(paged.creditCost);
3906
+ }
3907
+ const resultWent = outFailed || !opts.out ? "stdout" : opts.out;
3908
+ throw new HgiError(failure.code, failure.message, {
3909
+ hint: `${failure.hint ? `${failure.hint} ` : ""}The pages fetched so far were written to ${resultWent}, with the unfinished parts marked truncated. Do NOT re-run the pages already fetched; they were billed.`,
3910
+ details: { ...failure.details, ...partial, ...outFailed ? { out_write_failed: true } : {} },
3911
+ cause: failure
3912
+ });
3913
+ }
3362
3914
  async function runInvoke(verb, toolName, opts, cmd) {
3363
3915
  const batchSize = preflightBatchFlags(opts);
3364
3916
  const input = await readInput(opts.input);
3917
+ const maxPages = verb === "call" ? preflightPaging(opts, input) : null;
3365
3918
  preflightOutput({ format: opts.format, select: opts.select, out: opts.out, force: opts.force, allowForce: verb === "run" });
3366
3919
  const timeoutMs = parseTimeoutMs(opts.timeout);
3920
+ const retryOptions = resolveRetryOptions({ retries: opts.retries, retryBudget: opts.retryBudget });
3921
+ const transportRetry = transportRetryOptions(retryOptions);
3922
+ const governance = { retries: verb === "call" ? retryOptions.retries ?? 0 : 0, budgetMs: retryLimits(transportRetry).budgetMs };
3367
3923
  const label = parseLabel(opts.label);
3368
3924
  const ledger = ledgerPath();
3369
3925
  const ids = opts.ids === void 0 ? void 0 : await readIds({ ...opts, ids: opts.ids }, input);
@@ -3372,7 +3928,7 @@ async function runInvoke(verb, toolName, opts, cmd) {
3372
3928
  if (budgetId2 !== null && maxCredits !== null) await checkBudget(budgetId2, maxCredits);
3373
3929
  const ctx = buildContext(cmd);
3374
3930
  const creds = ctx.tokens.loadCredentials();
3375
- const session = await openSession(ctx, { timeoutMs });
3931
+ const session = await openSession(ctx, { timeoutMs, retry: transportRetry });
3376
3932
  const recordUsage = (result) => recordCall(ledger, {
3377
3933
  v: 1,
3378
3934
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -3411,55 +3967,65 @@ async function runInvoke(verb, toolName, opts, cmd) {
3411
3967
  meta: opts.meta,
3412
3968
  validate: opts.validate,
3413
3969
  budget: budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : void 0,
3414
- onResult: recordUsage
3970
+ onResult: recordUsage,
3971
+ governance
3415
3972
  });
3416
3973
  return;
3417
3974
  }
3418
- if (opts.validate) assertValidInput(tool, input);
3419
- const result = await session.callTool(toolName, input);
3420
- await recordUsage(result);
3421
- let budgetFailure = null;
3422
- if (budgetId2 !== null && maxCredits !== null) {
3423
- try {
3424
- await recordSpend(budgetId2, maxCredits, creditCostOf(result));
3425
- } catch (err) {
3426
- budgetFailure = toHgiError(err);
3427
- }
3975
+ if (maxPages !== null) {
3976
+ const spec = assertPageable(tool);
3977
+ if (opts.validate) assertValidInput(tool, input);
3978
+ await runPaged(
3979
+ {
3980
+ session,
3981
+ tool,
3982
+ input,
3983
+ spec,
3984
+ maxPages,
3985
+ validate: opts.validate,
3986
+ budget: budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : void 0,
3987
+ onResult: recordUsage,
3988
+ governance
3989
+ },
3990
+ verb,
3991
+ opts,
3992
+ () => session.state.mcpVersion
3993
+ );
3994
+ return;
3428
3995
  }
3996
+ if (opts.validate) assertValidInput(tool, input);
3997
+ const capped = budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : null;
3998
+ const { result, attempts, budgetFailure } = await sendWithRetry(session, toolName, input, {
3999
+ ...governance,
4000
+ // Every attempt that came back: one ledger row, and its spend under a run cap.
4001
+ record: async (r) => {
4002
+ await recordUsage(r);
4003
+ if (!capped) return null;
4004
+ try {
4005
+ await recordSpend(capped.id, capped.max, creditCostOf(r));
4006
+ return null;
4007
+ } catch (err) {
4008
+ return toHgiError(err);
4009
+ }
4010
+ },
4011
+ beforeResend: capped ? async () => void await checkBudget(capped.id, capped.max) : void 0,
4012
+ report: reportRetry
4013
+ });
3429
4014
  let outcome;
3430
4015
  try {
3431
4016
  outcome = interpretResult(result, toolName);
3432
4017
  } catch (err) {
3433
- if (budgetFailure && err instanceof HgiError) {
3434
- throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, budget_write_failed: true }, cause: err });
4018
+ const retried = governance.retries > 0 && err instanceof HgiError && err.code === "governance_unavailable";
4019
+ if ((budgetFailure || retried) && err instanceof HgiError) {
4020
+ const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
4021
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, ...extra }, cause: err });
3435
4022
  }
3436
4023
  throw err;
3437
4024
  }
3438
4025
  const selected = applySelect(outcome.value, opts.select);
3439
- const value = opts.meta ? { result: selected, credit_cost: outcome.creditCost, mcp_version: session.state.mcpVersion } : selected;
4026
+ const value = opts.meta ? { result: selected, credit_cost: outcome.creditCost, mcp_version: session.state.mcpVersion, attempts } : selected;
3440
4027
  if (budgetFailure) await failAfterBudgetWrite(budgetFailure, value, opts, outcome.creditCost);
3441
- try {
3442
- await emit(value, {
3443
- format: opts.format,
3444
- out: opts.out,
3445
- force: opts.force,
3446
- allowForce: verb === "run"
3447
- });
3448
- } catch (err) {
3449
- if (!opts.out) throw err;
3450
- const cause = toHgiError(err);
3451
- try {
3452
- await emit(value, { format: opts.format });
3453
- } catch {
3454
- }
3455
- throw new HgiError("local_state_error", `The tool ran, but its result could not be written to ${opts.out}: ${cause.message}`, {
3456
- hint: "The tool already ran and was billed; its result was printed to stdout instead. Do NOT re-run it.",
3457
- details: { kind: "write_failed", reason: cause.details?.reason ?? cause.code, tool_ran: true },
3458
- cause: err
3459
- });
3460
- } finally {
3461
- reportCredit(outcome.creditCost);
3462
- }
4028
+ await emitResult(value, verb, opts, outcome.creditCost);
3463
4029
  } finally {
3464
4030
  await session.close();
3465
4031
  }
@@ -3470,9 +4036,12 @@ function registerInvokeCommands(program) {
3470
4036
  run: "Run a tool that changes state or starts work. Fails for read-only tools."
3471
4037
  };
3472
4038
  for (const verb of ["call", "run"]) {
3473
- const cmd = program.command(`${verb} <tool>`).description(describeVerb[verb]).option("--input <json>", "tool arguments as a JSON object; @file or - reads a file or stdin").option("-f, --format <format>", "json|jsonl|csv|yaml|table").option("--select <fields>", "keep only these comma-separated fields (dotted paths allowed)").option("--out <file>", "write the result to a new file instead of stdout").option("--force", verb === "run" ? "overwrite an existing --out file" : "not available on call").option("--meta", "print {result, credit_cost, mcp_version} instead of the bare result").option("--label <label>", "tag this call in the local credit ledger (see `hgi usage --by label`)").option("--timeout <seconds>", "per-request timeout", "120").addOption(new Option("--no-validate", "skip client-side schema validation (let the server judge the input)").hideHelp());
4039
+ const cmd = program.command(`${verb} <tool>`).description(describeVerb[verb]).option("--input <json>", "tool arguments as a JSON object; @file or - reads a file or stdin").option("-f, --format <format>", "json|jsonl|csv|yaml|table").option("--select <fields>", "keep only these comma-separated fields (dotted paths allowed)").option("--out <file>", "write the result to a new file instead of stdout").option("--force", verb === "run" ? "overwrite an existing --out file" : "not available on call").option("--meta", `print {result, credit_cost, mcp_version, attempts} instead of the bare result${verb === "call" ? " (with --all-pages: pages_fetched and retries instead of attempts)" : ""}`).option("--label <label>", "tag this call in the local credit ledger (see `hgi usage --by label`)").option("--timeout <seconds>", "per-request timeout (each attempt; retry waits are extra)", "120").option("--retries <n>", "retry rate limits and outages up to n times each, 0-20; 0 turns every retry off (also $HGI_RETRIES)").option("--retry-budget <seconds>", "most seconds one request may spend waiting between retries, at most 3600 (also $HGI_RETRY_BUDGET; default 600 with retries, else 60)").addOption(new Option("--no-validate", "skip client-side schema validation (let the server judge the input)").hideHelp());
3474
4040
  if (verb === "call") {
3475
- cmd.option("--ids <source>", "batch over HG ids or domains, one per line: @file or - (stdin); prints one row per line").option("--ids-column <name>", "with --ids, read the file as CSV with a header row and take ids from this column").option("--batch-size <n>", "with --ids, send fewer ids per call than the tool's limit").option("--max-credits <n>", "stop this run once it has spent n credits (also $HGI_MAX_CREDITS; the flag wins)").addHelpText(
4041
+ cmd.option("--ids <source>", "batch over HG ids or domains, one per line: @file or - (stdin); prints one row per line").option("--ids-column <name>", "with --ids, read the file as CSV with a header row and take ids from this column").option("--batch-size <n>", "with --ids, send fewer ids per call than the tool's limit").option("--max-credits <n>", "stop this run once it has spent n credits (also $HGI_MAX_CREDITS; the flag wins)").option(
4042
+ "--all-pages",
4043
+ "fetch every page of an offset-paged tool and print one merged result; each extra page is a separate, billed call (batch tools: one call per company)"
4044
+ ).option("--max-pages <n>", "with --all-pages, fetch at most n pages per page object, page 1 included (default 10)").addHelpText(
3476
4045
  "after",
3477
4046
  [
3478
4047
  "",
@@ -3480,10 +4049,29 @@ function registerInvokeCommands(program) {
3480
4049
  " --max-credits <n> / HGI_MAX_CREDITS refuse the call, sending nothing (exit 13), once this run has spent n credits",
3481
4050
  " HGI_BUDGET_ID the run to count against (default: the parent process id, so one shell or script)",
3482
4051
  " `hgi budget status` shows the spend; `hgi budget reset` starts it over.",
3483
- " With --ids, every batch call is checked and counted."
4052
+ " With --ids, every batch call is checked and counted.",
4053
+ "",
4054
+ "Paging (--all-pages):",
4055
+ ' Only tools whose schemas show an integer "offset" input and a rows array with has_more or a total.',
4056
+ " Pages are fetched one at a time. Each extra page is a separate, billed call; for batch tools",
4057
+ " (hg_ids/domains), follow-ups go one call per company. Paging stops on has_more: false, an empty or",
4058
+ " short page, the total reached, or --max-pages (default 10). A stopped-early part says",
4059
+ " truncated: true and truncated_reason. A later-page failure prints the pages so far, then exits",
4060
+ " with that failure's code and details.partial_result: true. The run cap is checked before every page."
3484
4061
  ].join("\n")
3485
4062
  );
3486
4063
  }
4064
+ cmd.addHelpText(
4065
+ "after",
4066
+ [
4067
+ "",
4068
+ "Retries (only failures before the tool runs; never a call that may have run):",
4069
+ " hgi retries a 429, the server shedding load (503) and a connection that was never established, and prints",
4070
+ " one line on stderr before each wait. --retries n allows n of each; --retry-budget caps the waiting per request.",
4071
+ verb === "call" ? " With --retries, `hgi call` also re-sends a governance_unavailable refusal (the server could not check the budget)." : " `hgi run` never re-sends governance_unavailable: it exits 7 with retryable: true and you decide.",
4072
+ " The flags win over HGI_RETRIES / HGI_RETRY_BUDGET."
4073
+ ].join("\n")
4074
+ );
3487
4075
  cmd.action((tool, opts, c) => runInvoke(verb, tool, opts, c));
3488
4076
  }
3489
4077
  }
@@ -3494,7 +4082,7 @@ import os2 from "os";
3494
4082
  import path7 from "path";
3495
4083
 
3496
4084
  // src/generated/skill-md.ts
3497
- var SKILL_MD = '---\nname: hgi\ndescription: Look up company, contact, technology, intent and spend data from the HG Insights MCP server with the `hgi` command-line client. Use when the user asks about a company\'s tech stack, firmographics, intent signals, contacts, or wants to run an HG Insights agent, and `hgi` is installed.\n---\n\n# hgi: the HG Insights command-line client\n\n`hgi` is a thin client for the HG Insights MCP server. It signs in once through the user\'s browser, then exposes every tool the server offers to the signed-in user.\n\n## Rules\n\n1. **List tools first.** Run `hgi tools list --json` before your first call in a session. The list depends on the user, their organization and the server version, so never assume a tool exists and never reuse a tool list from memory. Each tool is marked `call` or `run`, and `required` shows the mandatory input fields.\n2. **Use `hgi call <tool> --input \'<json>\'` for lookups.** It only runs tools the server marks read-only. It is safe to run without asking.\n3. **Use `hgi run <tool> --input \'<json>\'` only with the user\'s approval.** It runs tools that change state or start work (for example starting an agent run, uploading an artifact by URL, or starting a customer-data discovery). It also runs tools that do not declare themselves read-only. Ask the user, say what the tool will do, then run it.\n4. **Report the credit cost after every call.** The cost is printed on stderr (`credit_cost: N`, or `{"credit_cost":N}` when stderr is not a terminal). `unknown` or `null` means the server did not report one. Tell the user what the call cost; credits are billed to their organization.\n5. **Never read, print or copy the credentials file** under `~/.config/hgi/`, and do not put tokens in commands. If `hgi` says the login is missing or expired, ask the user to run `hgi auth login` themselves. It opens their browser.\n6. **Using the wrong verb fails safely.** `hgi call` on a state-changing tool, or `hgi run` on a read-only tool, exits 10, names the right verb, and sends nothing.\n7. **Show a plan before working through a list.** When the work needs more than one batch (see `## Recipes`), first run one sample batch and report its `credit_cost`. Then show the plan: the calls, the number of batches, and the total estimated by extrapolating from the sample. **Wait for the user\'s go-ahead** before running the rest. Estimate only from the reported `credit_cost`, never from a price list; a figure from a past run may appear only as an example, labelled "observed".\n\n## Recommended permissions (Claude Code)\n\nAllow lookups, ask for everything that can change state. Put this in your user settings (`~/.claude/settings.json`) or a trusted project\'s `.claude/settings.json` (headless runs ignore the settings file of a directory that was never trusted):\n\n```json\n{\n "permissions": {\n "allow": ["Bash(hgi call *)", "Bash(hgi tools list *)", "Bash(hgi auth whoami)"],\n "ask": ["Bash(hgi run *)"]\n }\n}\n```\n\n## Usage\n\n```bash\nhgi tools list --json # what can I call?\nhgi call company_enrich --input \'{"domain":"acme.com"}\' # lookup, JSON on stdout\nhgi call search_companies --input \'{"query":"saas"}\' --select name,domain -f csv\nhgi call <tool> --input \'{"limit":100}\' --out result.json # big result to a new file\nhgi call <tool> --ids @hg_ids.txt --input \'{...}\' # a whole list: one JSONL row per line\nhgi run <tool> --input \'{...}\' # only after the user approves\n```\n\n- `--input` takes a JSON object. `@file.json` reads a file and `-` reads stdin.\n- Output is JSON when piped and a table on a terminal. Use `-f json|jsonl|csv|yaml|table`.\n- `--select a,b.c` keeps only those fields (dotted paths work through arrays). Prefer it, or `--out <new file>`, for large results; results are never truncated.\n- `--meta` prints `{ "result": ..., "credit_cost": ..., "mcp_version": ... }` on stdout.\n- `--label <stage>` on `call`/`run` tags the call in the local credit ledger (1 to 64 of `A-Z a-z 0-9 . _ : / -`).\n- `hgi usage [--since today|24h|7d|2026-11-01] [--by tool|label|day|call]` shows the credits `hgi` spent on this machine (local only, no sign-in, not the organization\'s bill). `credits` excludes calls with unknown cost (`unknown_cost_calls`); `zero_cost_calls` are cache hits or free tools.\n- A `{"warning":"ledger_not_updated",...}` line on stderr means the call still succeeded; do not re-run it.\n- For more than one company, use `--ids @file` (one HG id or domain per line; `--ids -` for stdin; `--ids-column <name>` for a CSV; `--batch-size <n>` to send fewer per call than the tool\'s limit) instead of looping. hgi batches by the tool\'s limit, sends batches one at a time, and prints `{"input", "result"}` or `{"input", "error"}` rows as JSONL in input order. Exit 3 means a batch failed (its rows carry the error, the rest are fine); any other non-zero exit stopped the run, and `details.rows_emitted` / `calls_made` say how far it got: keep the rows already printed and resume from there.\n\n## Recipes\n\nThese recipes name tools as examples. Before each one:\n\n- **Confirm the tools.** Check every tool a recipe names in `hgi tools list --json`. If one is missing, skip that step and tell the user which tool is unavailable; never substitute a guess.\n- **Take the batch size from the schema.** Read `maxItems` on `hg_ids` or `domains`, and the maximum of `limit`, `max_results` and `offset`, in the tool\'s `input_schema`. Don\'t hard-code them.\n- **Keep batches stable.** The server caches identical inputs for 30 days (7 for search), and a cached call costs nothing (observed). Sort ids and keep the same batches, so a re-run is free. Changing one id in a batch makes the whole batch a new input.\n- **Missing is not zero.** No installs, no intent, or a company left out of a batch response means unknown, not zero. Record it as unknown; don\'t score the account down.\n- **Show a plan first** for more than one batch (Rule 7).\n- Paging and batching are manual for now: a hand-written page loop and sorted id batches, as below.\n\n### Match an account list\n\n**Tools:** `search_companies`, `company_firmographic`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_firmographic`\'s `input_schema`.\n**Order:**\n\n1. `search_companies` per account: the name, the HQ country and a revenue floor (USD), `limit` small. It returns only `hg_id`, `name`, `domain`, `domain_normalized`.\n2. Collect the candidate `hg_id`s, sort them, and confirm them with `company_firmographic` in batches of `hg_ids`: name, `country_code`, `employees_total`, `revenue_total`, `company_level`.\n3. Keep the row whose country and size fit. Don\'t roll up to the global HQ or corporate parent blindly: HG lists Legrand Lebanon as Legrand\'s global HQ, and the French state as EDF\'s parent. Use `company_level` and the parent fields only after a sanity check.\n\n```bash\nhgi call search_companies --input \'{"company_identifiers":{"name":"Accor"},"firmographics":{"country_codes":[{"ids":["FR"],"inclusion_method":"ANY_PRESENT"}],"revenue":{"min":1000000000}},"limit":5}\'\nhgi call company_firmographic --input \'{"hg_ids":["<id1>","<id2>"]}\' --select companies.company_id,companies.firmographics.name,companies.firmographics.country_code,companies.firmographics.company_level\n```\n\n### Score fit and propensity\n\n**Tools:** `company_technographic`, `company_intent`, `list_intent_topics`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_technographic`\'s `input_schema`, and the maximum of `max_results` and `offset`. `company_intent` takes one company per call.\n**Order:**\n\n1. **Fit:** `company_technographic` on a sorted batch of `hg_ids`, filtered (`vendor_names`, `product_names` or `category_ids`) so pages stay small. Page with `offset`. Stop on a short page (fewer rows than `max_results`), once `total_installs_count` is reached, or at the schema\'s `offset` maximum. Don\'t stop on `has_more` alone: it can be wrong at page boundaries. At the `offset` maximum, report the result as partial and narrow the filter.\n2. **Topics:** resolve curated topic names to ids with `list_intent_topics`.\n3. **Intent:** `company_intent` on the company\'s web domain (`company_domain`), not only its HQ id: intent is observed on web domains. In one run, Accor had 0 topics on its HQ id and 18 on `accor.com` (observed; counts change over time). Check `company.id` and `company.name` in the response: a domain can resolve to a subsidiary.\n4. **Baseline:** large companies are active on about 70% of the ~20,000-topic catalogue (observed), so a raw topic count measures size, not interest. Compare the curated topics (`topic_ids`) with the company\'s own unfiltered summary. A summary with `topic_ids` counts only those topics. `fields:["summary"]` without a topic filter rejects `granularity` (422). When you request `fields:["topics"]`, pass `granularity:"global"`: the default is one row per state, which counts a topic several times.\n\n```bash\n# technographics page loop (needs jq); page size and offset maximum come from the schema\ndir=$(mktemp -d) # a fresh directory per run, so concurrent runs never share files\nschema=$(hgi tools list --json | jq \'.tools[] | select(.name=="company_technographic") | .input_schema.properties\')\nmax=$(jq \'.max_results.maximum\' <<<"$schema"); maxoff=$(jq \'.offset.maximum\' <<<"$schema")\nids=\'["<id1>","<id2>"]\'; off=0 # one sorted batch of at most hg_ids.maxItems ids\nwhile [ "$ids" != "[]" ]; do\n if [ "$off" -gt "$maxoff" ]; then echo "partial: offset maximum reached for $ids" >&2; break; fi\n hgi call company_technographic --input "{\\"hg_ids\\":$ids,\\"vendor_names\\":[\\"<vendor>\\"],\\"max_results\\":$max,\\"offset\\":$off}" -f json > "$dir/tech-$off.json" || break\n # next page only for companies that filled this page and are short of their stated total, sorted\n ids=$(jq -c --argjson max "$max" --argjson off "$off" \'[.companies[] | select(.installs_count == $max and $off + $max < .total_installs_count) | .company_id] | sort\' "$dir/tech-$off.json")\n off=$((off + max))\ndone\nhgi call company_intent --input \'{"company_domain":"accor.com"}\'\nhgi call company_intent --input \'{"company_domain":"accor.com","fields":["summary"],"topic_ids":["<topic id>"]}\'\n```\n\n### Size wallet from spend\n\n**Tools:** `company_spend`, `get_product_category`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_spend`\'s `input_schema`, and the maximum of `max_results`.\n**Order:**\n\n1. Use the `hg_id`s from the matching recipe, sorted.\n2. To size one area, resolve its category ids first with `get_product_category`, as `company_spend`\'s description says. Don\'t pass guessed `category_names`: a name that matches nothing returns 0 rows without an error.\n3. One `company_spend` call per batch of `hg_ids`, with `category_ids` set in that same call, not filtered afterwards.\n4. Page with `max_results` and `offset` only when `all_count` exceeds the rows returned, with the same stop rule as technographics.\n5. Rows are per country, and categories form a tree through `category_parent_id` (Total IT \u2192 Total External IT \u2192 Software, \u2026). Sum across countries, never a parent with its children.\n\n```bash\nhgi call company_spend --input \'{"hg_ids":["<id1>","<id2>"],"category_ids":["<category id>"]}\' --select companies.company_id,companies.spend.all\n```\n\n## Data semantics\n\nVerified with one live call per tool. "Scope" is what a call returns by default.\n\n| Tool | Default scope | Nullable fields (what null means) |\n|---|---|---|\n| `search_companies` | global: all countries unless `country_codes` filters the HQ country | no field came back null in the verification call; treat a missing field as unknown |\n| `company_firmographic` | country: one record per entity, in its own `country_code` | `corporate_parent_id`, `corporate_parent_name`, `parent_id`, `domestic_parent_id`, `domestic_parent_name`: none (no parent above it); `fortune_500_rank`, `forbes_2000_rank`: unknown |\n| `company_technographic` | global: default rows have `country_code: null`; `granularity` or `country_codes` give per-country rows | `country_code`: a global or unattributed row, not missing data; `product_category_level4_name`, `product_category_level5_name`: none (the category tree is shallower) |\n| `company_intent` | global: `summary` only, for the resolved entity across all geographies; with `fields:["topics"]`, one row per state unless `granularity:"global"` | no field came back null in the verification call; treat a missing field as unknown |\n| `company_spend` | country: every row has a `country_code` | no field came back null in the verification call; treat a missing field as unknown |\n\nNot null, but easy to misread:\n\n- A batch response leaves out companies it didn\'t match. A left-out company is unknown, not zero.\n- `company_domain` is `""` when you query by `hg_ids`.\n- `company_intent` on a domain answers for whichever company the domain resolves to: `accor.com` resolved to an Accor subsidiary in Australia, not the group HQ.\n\n**HG ids** are hex strings, normally 32 characters and uppercase in responses. An id can come back with its leading zero dropped, as 31 characters: seen on a spend `category_id`, and on company ids (observed). The `hg_ids` inputs accept 31 or 32 characters. Upper-case ids and left-pad them to 32 with `0` before comparing or joining.\n\n## Exit codes\n\n**If an error from `hgi run` has `details.outcome_unknown: true`, whatever its exit code (1, 7 or 9), the work may already have started and been billed. Check state first; never just retry.**\n\n| Code | Meaning | What to do |\n|---|---|---|\n| 0 | success | |\n| 1 | internal error in hgi | report it; check state before re-running a `run` (see `outcome_unknown`) |\n| 2 | invalid input or usage | fix the input; the JSON error lists the problem fields |\n| 3 | the tool reported an error | read the message; do not blindly retry |\n| 4 | not signed in, or login expired | ask the user to run `hgi auth login` |\n| 4 `phoenix_account_required` | the signed-in identity has no Phoenix account | stop; tell the user to sign up, or to sign in with `hgi auth login` as an account that has one |\n| 5 | rate limited | wait `retry_after_seconds` from the error, then retry |\n| 6 | out of credits: `credit_limit_exceeded` (the organization) or `user_credit_limit_exceeded` (the user\'s personal budget) | stop; tell the user which one, and to ask an admin. Retrying will not help |\n| 7 | server unreachable | retry later. If `outcome_unknown` is `true`, check state before re-running a `run` |\n| 7 `governance_unavailable` | the server could not check the budget; nothing ran (`retryable: true`) | wait a little, then retry once; hgi never retries it itself |\n| 8 | OAuth or sign-in failure | ask the user to run `hgi auth login` again |\n| 9 | proxy or TLS problem | the error names the cause (see `NODE_EXTRA_CA_CERTS`, `HTTPS_PROXY`). After a `run`, check `outcome_unknown` before retrying |\n| 10 | wrong verb | use the verb the error names |\n| 11 | forbidden, or `tool_not_enabled_for_team` | the account, organization or team lacks access to this tool; stop and tell the user to ask an admin |\n| 12 | local credential or file problem | follow the hint. If `details.tool_ran` is `true`, the tool already ran and its result is on stdout: do not re-run it |\n| 13 `budget_exceeded` | the run spent its `--max-credits` cap; nothing more was sent (with `--ids`, keep the rows already printed) | stop; tell the user what was spent (`details.spent` of `details.max`). Only the user raises the cap or runs `hgi budget reset` |\n\nErrors are JSON on stderr when it is not a terminal: `{"schema":1,"error":{"code","exit_code","message","hint","details"}}`. Branch on `error.code`, not on the message.\n\n## Run cap\n\nWhen the user gives a credit limit for a task, pass it as `hgi call --max-credits <n>` (or set `HGI_MAX_CREDITS`). It counts every `hgi call` in one budget; `hgi run` is not counted. **Run `export HGI_BUDGET_ID=<something unique to the task>` once first:** agent harnesses usually start a fresh shell per command, and the default budget (the parent process) would then give every call its own empty budget. The cap is client-side, on top of the server\'s limits, and can overshoot by the calls running at the same time. `hgi budget status` shows what the task has spent.\n';
4085
+ var SKILL_MD = '---\nname: hgi\ndescription: Look up company, contact, technology, intent and spend data from the HG Insights MCP server with the `hgi` command-line client. Use when the user asks about a company\'s tech stack, firmographics, intent signals, contacts, or wants to run an HG Insights agent, and `hgi` is installed.\n---\n\n# hgi: the HG Insights command-line client\n\n`hgi` is a thin client for the HG Insights MCP server. It signs in once through the user\'s browser, then exposes every tool the server offers to the signed-in user.\n\n## Rules\n\n1. **List tools first.** Run `hgi tools list --json` before your first call in a session. The list depends on the user, their organization and the server version, so never assume a tool exists and never reuse a tool list from memory. Each tool is marked `call` or `run`, and `required` shows the mandatory input fields.\n2. **Use `hgi call <tool> --input \'<json>\'` for lookups.** It only runs tools the server marks read-only. It is safe to run without asking.\n3. **Use `hgi run <tool> --input \'<json>\'` only with the user\'s approval.** It runs tools that change state or start work (for example starting an agent run, uploading an artifact by URL, or starting a customer-data discovery). It also runs tools that do not declare themselves read-only. Ask the user, say what the tool will do, then run it.\n4. **Report the credit cost after every call.** The cost is printed on stderr (`credit_cost: N`, or `{"credit_cost":N}` when stderr is not a terminal). `unknown` or `null` means the server did not report one. Tell the user what the call cost; credits are billed to their organization.\n5. **Never read, print or copy the credentials file** under `~/.config/hgi/`, and do not put tokens in commands. If `hgi` says the login is missing or expired, ask the user to run `hgi auth login` themselves. It opens their browser.\n6. **Using the wrong verb fails safely.** `hgi call` on a state-changing tool, or `hgi run` on a read-only tool, exits 10, names the right verb, and sends nothing.\n7. **Show a plan before working through a list.** When the work needs more than one batch (see `## Recipes`), first run one sample batch and report its `credit_cost`. Then show the plan: the calls, the number of batches, and the total estimated by extrapolating from the sample. **Wait for the user\'s go-ahead** before running the rest. Estimate only from the reported `credit_cost`, never from a price list; a figure from a past run may appear only as an example, labelled "observed".\n\n## Recommended permissions (Claude Code)\n\nAllow lookups, ask for everything that can change state. Put this in your user settings (`~/.claude/settings.json`) or a trusted project\'s `.claude/settings.json` (headless runs ignore the settings file of a directory that was never trusted):\n\n```json\n{\n "permissions": {\n "allow": ["Bash(hgi call *)", "Bash(hgi tools list *)", "Bash(hgi auth whoami)"],\n "ask": ["Bash(hgi run *)"]\n }\n}\n```\n\n## Usage\n\n```bash\nhgi tools list --json # what can I call?\nhgi call company_enrich --input \'{"domain":"acme.com"}\' # lookup, JSON on stdout\nhgi call search_companies --input \'{"query":"saas"}\' --select name,domain -f csv\nhgi call <tool> --input \'{"limit":100}\' --out result.json # big result to a new file\nhgi call <tool> --ids @hg_ids.txt --input \'{...}\' # a whole list: one JSONL row per line\nhgi call <tool> --all-pages --input \'{...}\' # every page of an offset-paged tool, merged\nhgi run <tool> --input \'{...}\' # only after the user approves\n```\n\n- `--input` takes a JSON object. `@file.json` reads a file and `-` reads stdin.\n- Output is JSON when piped and a table on a terminal. Use `-f json|jsonl|csv|yaml|table`.\n- `--select a,b.c` keeps only those fields (dotted paths work through arrays). Prefer it, or `--out <new file>`, for large results; results are never truncated.\n- `--meta` prints `{ "result": ..., "credit_cost": ..., "mcp_version": ... }` on stdout.\n- `--label <stage>` on `call`/`run` tags the call in the local credit ledger (1 to 64 of `A-Z a-z 0-9 . _ : / -`).\n- `hgi usage [--since today|24h|7d|2026-11-01] [--by tool|label|day|call]` shows the credits `hgi` spent on this machine (local only, no sign-in, not the organization\'s bill). `credits` excludes calls with unknown cost (`unknown_cost_calls`); `zero_cost_calls` are cache hits or free tools.\n- A `{"warning":"ledger_not_updated",...}` line on stderr means the call still succeeded; do not re-run it.\n- For more than one company, use `--ids @file` (one HG id or domain per line; `--ids -` for stdin; `--ids-column <name>` for a CSV; `--batch-size <n>` to send fewer per call than the tool\'s limit) instead of looping. hgi batches by the tool\'s limit, sends batches one at a time, and prints `{"input", "result"}` or `{"input", "error"}` rows as JSONL in input order. Exit 3 means a batch failed (its rows carry the error, the rest are fine); any other non-zero exit stopped the run, and `details.rows_emitted` / `calls_made` say how far it got: keep the rows already printed and resume from there.\n\n### Paging (`--all-pages`)\n\nFor every row of an offset-paged tool, use `hgi call <tool> --all-pages` instead of an `offset` loop. hgi pages only tools whose schemas show it is safe (an integer `offset` input and a rows array with `has_more` or a total); anything else is refused with exit 2 `not_pageable`, nothing sent. Don\'t pass `offset` yourself.\n\n- **Each extra page is a separate, billed call.** For batch tools (`hg_ids`/`domains`), follow-ups go one call per unfinished company.\n- It stops on `has_more: false`, an empty or short page, or the total reached, never on `has_more: true` alone (the server can say `true` after the last row). `--max-pages <n>` caps pages per page object (default 10, page 1 included).\n- The result keeps the server\'s shape. Each page object (the result, or each `companies[]` entry) gets `pages_fetched`; one cut short says `truncated: true` and `truncated_reason`: `max_pages`, `unmatched` (a batch entry hgi could not tie to one input, so it never guesses) or the code of the call that failed. Report truncated parts as incomplete.\n- One credit line at the end with the sum. `--meta` adds `pages_fetched` (pages requested), `retries` (re-sends) and `calls_without_cost`.\n- Not with `--ids` (exit 2 `all_pages_with_ids`): page one company list at a time.\n\n## Recipes\n\nThese recipes name tools as examples. Before each one:\n\n- **Confirm the tools.** Check every tool a recipe names in `hgi tools list --json`. If one is missing, skip that step and tell the user which tool is unavailable; never substitute a guess.\n- **Take the batch size from the schema.** Read `maxItems` on `hg_ids` or `domains`, and the maximum of `limit`, `max_results` and `offset`, in the tool\'s `input_schema`. Don\'t hard-code them.\n- **Keep batches stable.** The server caches identical inputs for 30 days (7 for search), and a cached call costs nothing (observed). Sort ids and keep the same batches, so a re-run is free. Changing one id in a batch makes the whole batch a new input.\n- **Missing is not zero.** No installs, no intent, or a company left out of a batch response means unknown, not zero. Record it as unknown; don\'t score the account down.\n- **Show a plan first** for more than one batch (Rule 7).\n- Batching is manual for now: sorted id batches, as below. Paging is `--all-pages` where the tool allows it (`not_pageable` otherwise).\n\n### Match an account list\n\n**Tools:** `search_companies`, `company_firmographic`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_firmographic`\'s `input_schema`.\n**Order:**\n\n1. `search_companies` per account: the name, the HQ country and a revenue floor (USD), `limit` small. It returns only `hg_id`, `name`, `domain`, `domain_normalized`.\n2. Collect the candidate `hg_id`s, sort them, and confirm them with `company_firmographic` in batches of `hg_ids`: name, `country_code`, `employees_total`, `revenue_total`, `company_level`.\n3. Keep the row whose country and size fit. Don\'t roll up to the global HQ or corporate parent blindly: HG lists Legrand Lebanon as Legrand\'s global HQ, and the French state as EDF\'s parent. Use `company_level` and the parent fields only after a sanity check.\n\n```bash\nhgi call search_companies --input \'{"company_identifiers":{"name":"Accor"},"firmographics":{"country_codes":[{"ids":["FR"],"inclusion_method":"ANY_PRESENT"}],"revenue":{"min":1000000000}},"limit":5}\'\nhgi call company_firmographic --input \'{"hg_ids":["<id1>","<id2>"]}\' --select companies.company_id,companies.firmographics.name,companies.firmographics.country_code,companies.firmographics.company_level\n```\n\n### Score fit and propensity\n\n**Tools:** `company_technographic`, `company_intent`, `list_intent_topics`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_technographic`\'s `input_schema`, and the maximum of `max_results` and `offset`. `company_intent` takes one company per call.\n**Order:**\n\n1. **Fit:** `company_technographic` on a batch of `hg_ids`, filtered (`vendor_names`, `product_names` or `category_ids`) so pages stay small, with `--all-pages` (above). It pages each company on its own and stops on a short page or `total_installs_count`, not on `has_more` alone (it can be wrong at page boundaries). A company with `truncated: true` is partial: say so, and narrow the filter rather than raising `--max-pages`.\n2. **Topics:** resolve curated topic names to ids with `list_intent_topics`.\n3. **Intent:** `company_intent` on the company\'s web domain (`company_domain`), not only its HQ id: intent is observed on web domains. In one run, Accor had 0 topics on its HQ id and 18 on `accor.com` (observed; counts change over time). Check `company.id` and `company.name` in the response: a domain can resolve to a subsidiary.\n4. **Baseline:** large companies are active on about 70% of the ~20,000-topic catalogue (observed), so a raw topic count measures size, not interest. Compare the curated topics (`topic_ids`) with the company\'s own unfiltered summary. A summary with `topic_ids` counts only those topics. `fields:["summary"]` without a topic filter rejects `granularity` (422). When you request `fields:["topics"]`, pass `granularity:"global"`: the default is one row per state, which counts a topic several times.\n\n```bash\n# every install per company, paged safely; max_results up to the schema\'s maximum keeps the call count down\nhgi call company_technographic --all-pages --max-pages 5 \\\n --input \'{"hg_ids":["<id1>","<id2>"],"vendor_names":["<vendor>"],"max_results":<schema maximum>}\' -f json > tech.json\n# exit 0 with truncated companies = capped; non-zero with details.partial_result = stopped early, tech.json still holds what was paid for\nhgi call company_intent --input \'{"company_domain":"accor.com"}\'\nhgi call company_intent --input \'{"company_domain":"accor.com","fields":["summary"],"topic_ids":["<topic id>"]}\'\n```\n\n### Size wallet from spend\n\n**Tools:** `company_spend`, `get_product_category`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_spend`\'s `input_schema`, and the maximum of `max_results`.\n**Order:**\n\n1. Use the `hg_id`s from the matching recipe, sorted.\n2. To size one area, resolve its category ids first with `get_product_category`, as `company_spend`\'s description says. Don\'t pass guessed `category_names`: a name that matches nothing returns 0 rows without an error.\n3. One `company_spend` call per batch of `hg_ids`, with `category_ids` set in that same call, not filtered afterwards.\n4. `company_spend` is not pageable with `--all-pages` (its per-company spend has no rows array). Page with `max_results` and `offset` by hand only when `all_count` exceeds the rows returned; stop on a short page or once `all_count` is reached, never on a has-more flag alone.\n5. Rows are per country, and categories form a tree through `category_parent_id` (Total IT \u2192 Total External IT \u2192 Software, \u2026). Sum across countries, never a parent with its children.\n\n```bash\nhgi call company_spend --input \'{"hg_ids":["<id1>","<id2>"],"category_ids":["<category id>"]}\' --select companies.company_id,companies.spend.all\n```\n\n## Data semantics\n\nVerified with one live call per tool. "Scope" is what a call returns by default.\n\n| Tool | Default scope | Nullable fields (what null means) |\n|---|---|---|\n| `search_companies` | global: all countries unless `country_codes` filters the HQ country | no field came back null in the verification call; treat a missing field as unknown |\n| `company_firmographic` | country: one record per entity, in its own `country_code` | `corporate_parent_id`, `corporate_parent_name`, `parent_id`, `domestic_parent_id`, `domestic_parent_name`: none (no parent above it); `fortune_500_rank`, `forbes_2000_rank`: unknown |\n| `company_technographic` | global: default rows have `country_code: null`; `granularity` or `country_codes` give per-country rows | `country_code`: a global or unattributed row, not missing data; `product_category_level4_name`, `product_category_level5_name`: none (the category tree is shallower) |\n| `company_intent` | global: `summary` only, for the resolved entity across all geographies; with `fields:["topics"]`, one row per state unless `granularity:"global"` | no field came back null in the verification call; treat a missing field as unknown |\n| `company_spend` | country: every row has a `country_code` | no field came back null in the verification call; treat a missing field as unknown |\n\nNot null, but easy to misread:\n\n- A batch response leaves out companies it didn\'t match. A left-out company is unknown, not zero.\n- `company_domain` is `""` when you query by `hg_ids`.\n- `company_intent` on a domain answers for whichever company the domain resolves to: `accor.com` resolved to an Accor subsidiary in Australia, not the group HQ.\n\n**HG ids** are hex strings, normally 32 characters and uppercase in responses. An id can come back with its leading zero dropped, as 31 characters: seen on a spend `category_id`, and on company ids (observed). The `hg_ids` inputs accept 31 or 32 characters. Upper-case ids and left-pad them to 32 with `0` before comparing or joining.\n\n## Exit codes\n\n**If an error from `hgi run` has `details.outcome_unknown: true`, whatever its exit code (1, 7 or 9), the work may already have started and been billed. Check state first; never just retry.**\n\n| Code | Meaning | What to do |\n|---|---|---|\n| 0 | success | |\n| 1 | internal error in hgi | report it; check state before re-running a `run` (see `outcome_unknown`) |\n| 2 | invalid input or usage | fix the input; the JSON error lists the problem fields |\n| 3 | the tool reported an error | read the message; do not blindly retry |\n| 4 | not signed in, or login expired | ask the user to run `hgi auth login` |\n| 4 `phoenix_account_required` | the signed-in identity has no Phoenix account | stop; tell the user to sign up, or to sign in with `hgi auth login` as an account that has one |\n| 5 | rate limited (after hgi\'s own retries) | wait `retry_after_seconds` from the error, then retry. For a long batch of lookups, pass `--retries 6` instead of writing your own retry loop |\n| 6 | out of credits: `credit_limit_exceeded` (the organization) or `user_credit_limit_exceeded` (the user\'s personal budget) | stop; tell the user which one, and to ask an admin. Retrying will not help |\n| 7 | server unreachable | retry later. If `outcome_unknown` is `true`, check state before re-running a `run` |\n| 7 `governance_unavailable` | the server could not check the budget; nothing ran (`retryable: true`) | wait a little, then retry once. `hgi call --retries <n>` retries it itself; `hgi run` never does |\n| 8 | OAuth or sign-in failure | ask the user to run `hgi auth login` again |\n| 9 | proxy or TLS problem | the error names the cause (see `NODE_EXTRA_CA_CERTS`, `HTTPS_PROXY`). After a `run`, check `outcome_unknown` before retrying |\n| 10 | wrong verb | use the verb the error names |\n| 11 | forbidden, or `tool_not_enabled_for_team` | the account, organization or team lacks access to this tool; stop and tell the user to ask an admin |\n| 12 | local credential or file problem | follow the hint. If `details.tool_ran` is `true`, the tool already ran and its result is on stdout: do not re-run it |\n| any, with `details.partial_result: true` | `--all-pages` stopped on a later page; the pages fetched so far are on stdout (or `--out`), unfinished parts marked `truncated` | keep them, they were billed; then act on the code as its own row says. Don\'t re-fetch pages you already have |\n| 13 `budget_exceeded` | the run spent its `--max-credits` cap; nothing more was sent (with `--ids`, keep the rows already printed) | stop; tell the user what was spent (`details.spent` of `details.max`). Only the user raises the cap or runs `hgi budget reset` |\n\nErrors are JSON on stderr when it is not a terminal: `{"schema":1,"error":{"code","exit_code","message","hint","details"}}`. Branch on `error.code`, not on the message.\n\n## Run cap\n\nWhen the user gives a credit limit for a task, pass it as `hgi call --max-credits <n>` (or set `HGI_MAX_CREDITS`). It counts every `hgi call` in one budget; `hgi run` is not counted. **Run `export HGI_BUDGET_ID=<something unique to the task>` once first:** agent harnesses usually start a fresh shell per command, and the default budget (the parent process) would then give every call its own empty budget. The cap is client-side, on top of the server\'s limits, and can overshoot by the calls running at the same time. `hgi budget status` shows what the task has spent.\n';
3498
4086
 
3499
4087
  // src/commands/skill.ts
3500
4088
  function defaultSkillsDir() {