@hginsights/hgi 0.2.0-rc.1 → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.3.0-rc.1" : "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,41 +3081,465 @@ 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/mcp/paging.ts
3097
+ var NAMED_TOTALS = ["total", "total_count", "totalCount"];
3098
+ var PAGE_SIZE_KEYS = ["limit", "max_results"];
3099
+ function isNumeric(schema) {
3100
+ return isRecord(schema) && (hasType(schema, "integer") || hasType(schema, "number"));
3101
+ }
3102
+ function isPositiveInt(value) {
3103
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
3104
+ }
3105
+ function totalKeyOf(props, rowsKey) {
3106
+ for (const key of NAMED_TOTALS) {
3107
+ if (Object.hasOwn(props, key) && isNumeric(props[key])) return key;
3108
+ }
3109
+ const candidates = Object.keys(props).filter(
3110
+ (key) => key.startsWith("total_") && isNumeric(props[key]) && key.split("_").includes(rowsKey)
3111
+ );
3112
+ return candidates.length === 1 ? candidates[0] : void 0;
3113
+ }
3114
+ function pageObjectSpec(schema) {
3115
+ const props = propertiesOf(schema);
3116
+ const arrays = Object.keys(props).filter((key) => isArrayOfObjects(props[key]));
3117
+ if (arrays.length !== 1) return null;
3118
+ const rowsKey = arrays[0];
3119
+ const hasMoreKey = Object.hasOwn(props, "has_more") ? "has_more" : Object.hasOwn(props, "hasMore") ? "hasMore" : void 0;
3120
+ const totalKey = totalKeyOf(props, rowsKey);
3121
+ if (hasMoreKey === void 0 && totalKey === void 0) return null;
3122
+ return { rowsKey, ...hasMoreKey ? { hasMoreKey } : {}, ...totalKey ? { totalKey } : {} };
3123
+ }
3124
+ function pageSizeOfSchema(inputProps) {
3125
+ const declared = PAGE_SIZE_KEYS.filter((key2) => Object.hasOwn(inputProps, key2));
3126
+ if (declared.length !== 1) return {};
3127
+ const key = declared[0];
3128
+ const schema = inputProps[key];
3129
+ const fallback = isRecord(schema) ? schema.default : void 0;
3130
+ return { pageSizeKey: key, ...isPositiveInt(fallback) ? { pageSizeDefault: fallback } : {} };
3131
+ }
3132
+ function pagingSpec(tool) {
3133
+ const inputProps = propertiesOf(tool.inputSchema);
3134
+ const offset = inputProps.offset;
3135
+ if (!isRecord(offset) || !hasType(offset, "integer")) return null;
3136
+ if (!isRecord(tool.outputSchema)) return null;
3137
+ const size = pageSizeOfSchema(inputProps);
3138
+ const top = pageObjectSpec(tool.outputSchema);
3139
+ if (top) return { kind: "top", ...top, ...size };
3140
+ const outputProps = propertiesOf(tool.outputSchema);
3141
+ const itemSpecs = Object.keys(outputProps).filter((key) => isArrayOfObjects(outputProps[key])).map((key) => ({ key, spec: pageObjectSpec(outputProps[key].items) })).filter((c) => c.spec !== null);
3142
+ if (itemSpecs.length !== 1) return null;
3143
+ const only = itemSpecs[0];
3144
+ return { kind: "items", itemsKey: only.key, ...only.spec, ...size };
3145
+ }
3146
+ function pageSizeOf(spec, input) {
3147
+ if (spec.pageSizeKey === void 0) return void 0;
3148
+ const sent = input[spec.pageSizeKey];
3149
+ if (isPositiveInt(sent)) return sent;
3150
+ return spec.pageSizeDefault;
3151
+ }
3152
+ function stopReason(state, pageSize, maxPages) {
3153
+ if (state.hasMore === false) return "done";
3154
+ if (state.pageRows === 0) return "done";
3155
+ if (pageSize !== void 0 && state.pageRows < pageSize) return "done";
3156
+ if (typeof state.total === "number" && Number.isFinite(state.total) && state.collected >= state.total) return "done";
3157
+ if (state.pages >= maxPages) return "max_pages";
3158
+ return null;
3159
+ }
3160
+
3161
+ // src/commands/retry.ts
3162
+ var GOVERNANCE_MAX_WAIT_SECONDS = 30;
3163
+ function isGovernanceUnavailable(result) {
3164
+ return result.isError === true && result._meta?.errorCode === "governance_unavailable";
3165
+ }
3166
+ async function sendWithRetry(session, name, args, opts) {
3167
+ const sleep2 = opts.sleep ?? sleep;
3168
+ const now = opts.now ?? Date.now;
3169
+ const random = opts.random ?? Math.random;
3170
+ const sendsBefore = session.state.toolsCallSends;
3171
+ const started = now();
3172
+ for (let attempt = 1; ; attempt += 1) {
3173
+ const result = await session.callTool(name, args);
3174
+ const budgetFailure = await opts.record(result);
3175
+ const outcome = () => ({ result, attempts: session.state.toolsCallSends - sendsBefore, budgetFailure });
3176
+ if (budgetFailure || attempt > opts.retries || !isGovernanceUnavailable(result)) return outcome();
3177
+ const waitMs = random() * Math.min(2 ** attempt, GOVERNANCE_MAX_WAIT_SECONDS) * 1e3;
3178
+ if (waitMs > opts.budgetMs - (now() - started)) return outcome();
3179
+ opts.report({ attempt, max: opts.retries, code: "governance_unavailable", wait_seconds: roundWait(waitMs) });
3180
+ await sleep2(waitMs);
3181
+ await opts.beforeResend?.();
3182
+ }
3183
+ }
3184
+
3185
+ // src/commands/paging.ts
3186
+ var DEFAULT_MAX_PAGES = 10;
3187
+ function usage(message, reason, extra = {}) {
3188
+ return new HgiError("invalid_input", message, { hint: "Nothing was sent.", details: { reason, ...extra } });
3189
+ }
3190
+ function preflightPaging(flags, input) {
3191
+ if (!flags.allPages) {
3192
+ if (flags.maxPages !== void 0) throw usage("--max-pages needs --all-pages.", "max_pages_without_all_pages");
3193
+ return null;
3194
+ }
3195
+ let maxPages = DEFAULT_MAX_PAGES;
3196
+ if (flags.maxPages !== void 0) {
3197
+ const raw = flags.maxPages.trim();
3198
+ const n = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
3199
+ if (!Number.isSafeInteger(n) || n < 1) throw usage(`--max-pages must be a whole number of at least 1, not "${flags.maxPages}".`, "bad_max_pages");
3200
+ maxPages = n;
3201
+ }
3202
+ if (Object.hasOwn(input, "offset")) throw usage('--all-pages sets "offset" itself; remove it from --input.', "offset_with_all_pages");
3203
+ return maxPages;
3204
+ }
3205
+ function assertPageable(tool) {
3206
+ const spec = pagingSpec(tool);
3207
+ if (spec) return spec;
3208
+ throw new HgiError("invalid_input", `${tool.name} cannot be paged safely with --all-pages.`, {
3209
+ 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.',
3210
+ details: { reason: "not_pageable", tool: tool.name }
3211
+ });
3212
+ }
3213
+ function assertBatchPageable(tool, entriesKey2) {
3214
+ const spec = assertPageable(tool);
3215
+ if (spec.kind === "items" && spec.itemsKey === entriesKey2) return spec;
3216
+ throw new HgiError("invalid_input", `${tool.name} cannot be paged safely with --ids and --all-pages.`, {
3217
+ hint: `Its page objects are not the items of "${entriesKey2}", the array --ids reads its rows from. Nothing was sent. Use --ids without --all-pages, or --all-pages without --ids.`,
3218
+ details: { reason: "not_pageable", tool: tool.name }
3219
+ });
3220
+ }
3221
+ var StopPaging = class extends Error {
3222
+ constructor(error) {
3223
+ super(error.message);
3224
+ this.error = error;
3225
+ }
3226
+ error;
3227
+ /** The merged result up to the stop, set by the loop that caught it. */
3228
+ merged;
3229
+ };
3230
+ function unexpected(tool, what) {
3231
+ return new HgiError("tool_error", `A later page of ${tool.name} came back without ${what}; paging stopped.`, {
3232
+ details: { reason: "unexpected_response", tool: tool.name }
3233
+ });
3234
+ }
3235
+ var Pager = class {
3236
+ constructor(ctx, acc = { callsMade: 0, retries: 0, callsWithoutCost: 0, creditSum: 0 }) {
3237
+ this.ctx = ctx;
3238
+ this.acc = acc;
3239
+ this.pageSize = pageSizeOf(ctx.spec, ctx.input);
3240
+ }
3241
+ ctx;
3242
+ acc;
3243
+ pageSize;
3244
+ /**
3245
+ * Sends one page. Page 1 was checked against the run cap before the session opened. A page whose spend could
3246
+ * not be recorded is returned with `budgetFailure`, so its rows are kept before paging stops.
3247
+ */
3248
+ async fetch(args, first) {
3249
+ const { session, tool, budget } = this.ctx;
3250
+ if (!first && budget) await checkBudget(budget.id, budget.max);
3251
+ if (!first && this.ctx.validate) assertValidInput(tool, args);
3252
+ this.acc.callsMade += 1;
3253
+ const sendsBefore = session.state.toolsCallSends;
3254
+ const governanceRetries = this.ctx.governance?.retries ?? 0;
3255
+ let sent;
3256
+ try {
3257
+ sent = await sendWithRetry(session, tool.name, args, {
3258
+ retries: governanceRetries,
3259
+ budgetMs: this.ctx.governance?.budgetMs ?? 0,
3260
+ // Every attempt that came back: one ledger row, and its spend under a run cap.
3261
+ record: async (r) => {
3262
+ await this.ctx.onResult?.(r);
3263
+ if (!budget) return null;
3264
+ try {
3265
+ await recordSpend(budget.id, budget.max, creditCostOf(r));
3266
+ return null;
3267
+ } catch (err) {
3268
+ return toHgiError(err);
3269
+ }
3270
+ },
3271
+ beforeResend: budget ? async () => void await checkBudget(budget.id, budget.max) : void 0,
3272
+ report: reportRetry
3273
+ });
3274
+ } catch (err) {
3275
+ this.acc.callsWithoutCost += 1;
3276
+ throw err;
3277
+ } finally {
3278
+ this.acc.retries += Math.max(0, session.state.toolsCallSends - sendsBefore - 1);
3279
+ }
3280
+ const { result, attempts, budgetFailure } = sent;
3281
+ const cost = creditCostOf(result);
3282
+ if (cost === null) this.acc.callsWithoutCost += 1;
3283
+ else this.acc.creditSum += cost;
3284
+ try {
3285
+ return { value: interpretResult(result, tool.name).value, budgetFailure };
3286
+ } catch (err) {
3287
+ const retried = governanceRetries > 0 && err instanceof HgiError && err.code === "governance_unavailable";
3288
+ if ((budgetFailure || retried) && err instanceof HgiError) {
3289
+ const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
3290
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, ...extra }, cause: err });
3291
+ }
3292
+ throw err;
3293
+ }
3294
+ }
3295
+ /** A follow-up page: any failure stops paging. */
3296
+ async fetchLater(args) {
3297
+ try {
3298
+ return await this.fetch(args, false);
3299
+ } catch (err) {
3300
+ throw new StopPaging(toHgiError(err));
3301
+ }
3302
+ }
3303
+ track(entry) {
3304
+ const rows = entry[this.ctx.spec.rowsKey];
3305
+ const t = { entry, rows: Array.isArray(rows) ? [...rows] : null, pages: 0, done: false };
3306
+ this.settle(t, Array.isArray(rows) ? rows.length : 0);
3307
+ return t;
3308
+ }
3309
+ /** Applies the stop rule after a page with `pageRows` rows. */
3310
+ settle(t, pageRows) {
3311
+ t.pages += 1;
3312
+ const { hasMoreKey, totalKey } = this.ctx.spec;
3313
+ const reason = stopReason(
3314
+ {
3315
+ pageRows,
3316
+ collected: t.rows?.length ?? 0,
3317
+ pages: t.pages,
3318
+ hasMore: hasMoreKey ? t.entry[hasMoreKey] : void 0,
3319
+ total: totalKey ? t.entry[totalKey] : void 0
3320
+ },
3321
+ this.pageSize,
3322
+ this.ctx.maxPages
3323
+ );
3324
+ if (reason === null) return;
3325
+ t.done = true;
3326
+ if (reason === "max_pages") t.reason = "max_pages";
3327
+ }
3328
+ /** Adds a follow-up page object's rows to its tracker. */
3329
+ append(t, entry) {
3330
+ const rows = entry[this.ctx.spec.rowsKey];
3331
+ if (!Array.isArray(rows)) throw new StopPaging(unexpected(this.ctx.tool, `a "${this.ctx.spec.rowsKey}" array`));
3332
+ t.entry = entry;
3333
+ t.rows = [...t.rows ?? [], ...rows];
3334
+ this.settle(t, rows.length);
3335
+ }
3336
+ merged(t) {
3337
+ return {
3338
+ ...t.entry,
3339
+ ...t.rows === null ? {} : { [this.ctx.spec.rowsKey]: t.rows },
3340
+ pages_fetched: t.pages,
3341
+ ...t.reason === void 0 ? {} : { truncated: true, truncated_reason: t.reason }
3342
+ };
3343
+ }
3344
+ creditCost() {
3345
+ return this.acc.callsMade > this.acc.callsWithoutCost ? this.acc.creditSum : null;
3346
+ }
3347
+ };
3348
+ function companyInputs(input) {
3349
+ const out = [];
3350
+ for (const [field, kind] of [["hg_ids", "id"], ["domains", "domain"]]) {
3351
+ const values = input[field];
3352
+ if (!Array.isArray(values)) continue;
3353
+ for (const text of values) {
3354
+ if (typeof text === "string") out.push({ field, kind, text, norm: kind === "id" ? normalizeId(text) : normalizeDomain(text) });
3355
+ }
3356
+ }
3357
+ return out;
3358
+ }
3359
+ function entryKey(entry, kind) {
3360
+ if (kind === "domain") {
3361
+ const raw = keyText(entry[DOMAIN_MATCH_KEY]);
3362
+ return raw === null ? null : normalizeDomain(raw);
3363
+ }
3364
+ for (const key of ID_MATCH_KEYS) {
3365
+ const raw = keyText(entry[key]);
3366
+ if (raw !== null) return normalizeId(raw);
3367
+ }
3368
+ return null;
3369
+ }
3370
+ function matches(entry, input) {
3371
+ return entryKey(entry, input.kind) === input.norm;
3372
+ }
3373
+ function withoutCompanies(input) {
3374
+ const rest = { ...input };
3375
+ delete rest.hg_ids;
3376
+ delete rest.domains;
3377
+ return rest;
3378
+ }
3379
+ function planFollowUps(trackers, input) {
3380
+ const live = trackers.filter((t) => t !== null);
3381
+ const inputs = companyInputs(input);
3382
+ if (inputs.length < 2) {
3383
+ const named = inputs[0];
3384
+ for (const t of live) {
3385
+ if (t.done) continue;
3386
+ if (trackers.length === 1 && (named === void 0 || matches(t.entry, named))) {
3387
+ t.follow = "same";
3388
+ if (named) t.expect = { kind: named.kind, norm: named.norm };
3389
+ } else {
3390
+ Object.assign(t, { done: true, reason: "unmatched" });
3391
+ }
3392
+ }
3393
+ return;
3394
+ }
3395
+ const matchedBy = /* @__PURE__ */ new Map();
3396
+ const candidates = live.map((t) => inputs.map((inp, i) => matches(t.entry, inp) ? i : -1).filter((i) => i >= 0));
3397
+ for (const list of candidates) for (const i of list) matchedBy.set(i, (matchedBy.get(i) ?? 0) + 1);
3398
+ live.forEach((t, k) => {
3399
+ if (t.done) return;
3400
+ const list = candidates[k];
3401
+ const only = list.length === 1 ? list[0] : -1;
3402
+ if (only >= 0 && matchedBy.get(only) === 1) {
3403
+ const inp = inputs[only];
3404
+ t.follow = { field: inp.field, text: inp.text, kind: inp.kind, norm: inp.norm };
3405
+ } else {
3406
+ Object.assign(t, { done: true, reason: "unmatched" });
3407
+ }
3408
+ });
3409
+ }
3410
+ async function pageTop(p, ctx, first) {
3411
+ if (!isRecord(first)) return first;
3412
+ const t = p.track(first);
3413
+ try {
3414
+ while (!t.done) {
3415
+ const page = await p.fetchLater({ ...ctx.input, offset: t.rows?.length ?? 0 });
3416
+ if (!isRecord(page.value)) throw new StopPaging(unexpected(ctx.tool, "a result object"));
3417
+ p.append(t, page.value);
3418
+ if (page.budgetFailure) throw new StopPaging(page.budgetFailure);
3419
+ }
3420
+ } catch (err) {
3421
+ if (!(err instanceof StopPaging)) throw err;
3422
+ if (!t.done) Object.assign(t, { done: true, reason: err.error.code });
3423
+ err.merged = p.merged(t);
3424
+ throw err;
3425
+ }
3426
+ return p.merged(t);
3427
+ }
3428
+ async function followCompany(p, ctx, t) {
3429
+ const itemsKey = ctx.spec.itemsKey;
3430
+ while (!t.done) {
3431
+ const follow = t.follow;
3432
+ const args = follow === "same" ? { ...ctx.input, offset: t.rows?.length ?? 0 } : { ...withoutCompanies(ctx.input), [follow.field]: [follow.text], offset: t.rows?.length ?? 0 };
3433
+ const page = await p.fetchLater(args);
3434
+ if (!isRecord(page.value) || !Array.isArray(page.value[itemsKey])) {
3435
+ throw new StopPaging(unexpected(ctx.tool, `a "${itemsKey}" array`));
3436
+ }
3437
+ const list = page.value[itemsKey];
3438
+ const only = list.length === 1 && isRecord(list[0]) ? list[0] : null;
3439
+ const want = follow === "same" ? t.expect : follow;
3440
+ if (only === null || want !== void 0 && !matches(only, want)) {
3441
+ Object.assign(t, { done: true, reason: "unmatched" });
3442
+ } else {
3443
+ p.append(t, only);
3444
+ }
3445
+ if (page.budgetFailure) throw new StopPaging(page.budgetFailure);
3446
+ }
3447
+ }
3448
+ async function pageItems(p, ctx, first) {
3449
+ const itemsKey = ctx.spec.itemsKey;
3450
+ if (!isRecord(first) || !Array.isArray(first[itemsKey])) return first;
3451
+ const entries = first[itemsKey];
3452
+ const trackers = entries.map((e) => isRecord(e) ? p.track(e) : null);
3453
+ planFollowUps(trackers, ctx.input);
3454
+ const merge = () => ({ ...first, [itemsKey]: entries.map((e, i) => trackers[i] ? p.merged(trackers[i]) : e) });
3455
+ try {
3456
+ for (const t of trackers) if (t) await followCompany(p, ctx, t);
3457
+ } catch (err) {
3458
+ if (!(err instanceof StopPaging)) throw err;
3459
+ for (const t of trackers) if (t && !t.done) Object.assign(t, { done: true, reason: err.error.code });
3460
+ err.merged = merge();
3461
+ throw err;
3462
+ }
3463
+ return merge();
3464
+ }
3465
+ function companyPager(ctx, acc) {
3466
+ const p = new Pager(ctx, acc);
3467
+ return {
3468
+ async page(entry, company) {
3469
+ const t = p.track(entry);
3470
+ t.follow = { ...company };
3471
+ try {
3472
+ await followCompany(p, ctx, t);
3473
+ return { merged: p.merged(t) };
3474
+ } catch (err) {
3475
+ if (!(err instanceof StopPaging)) throw err;
3476
+ if (!t.done) Object.assign(t, { done: true, reason: err.error.code });
3477
+ return { merged: p.merged(t), failure: err.error };
3478
+ }
3479
+ },
3480
+ settle(entry, reason) {
3481
+ const t = p.track(entry);
3482
+ if (!t.done) Object.assign(t, { done: true, reason });
3483
+ return p.merged(t);
3484
+ }
3485
+ };
3486
+ }
3487
+ async function runAllPages(ctx) {
3488
+ const p = new Pager(ctx);
3489
+ const first = await p.fetch(ctx.input, true);
3490
+ const outcome = (value, failure) => ({
3491
+ value,
3492
+ callsMade: p.acc.callsMade,
3493
+ retries: p.acc.retries,
3494
+ callsWithoutCost: p.acc.callsWithoutCost,
3495
+ creditCost: p.creditCost(),
3496
+ ...failure ? { failure } : {}
3497
+ });
3498
+ if (first.budgetFailure) {
3499
+ return { ...outcome(first.value, first.budgetFailure), pageOneBudgetFailure: true };
3500
+ }
3501
+ try {
3502
+ return outcome(ctx.spec.kind === "top" ? await pageTop(p, ctx, first.value) : await pageItems(p, ctx, first.value));
3503
+ } catch (err) {
3504
+ if (err instanceof StopPaging) return outcome(err.merged, err.error);
3505
+ throw err;
3506
+ }
3507
+ }
3051
3508
 
3052
3509
  // src/commands/batch.ts
3053
- function usage(message, reason, hint, extra = {}) {
3510
+ function usage2(message, reason, hint, extra = {}) {
3054
3511
  return new HgiError("invalid_input", message, { hint, details: { reason, ...extra } });
3055
3512
  }
3056
3513
  function preflightBatchFlags(flags) {
3057
3514
  if (flags.ids === void 0) {
3058
- if (flags.idsColumn !== void 0) throw usage("--ids-column needs --ids.", "ids_column_without_ids");
3059
- if (flags.batchSize !== void 0) throw usage("--batch-size needs --ids.", "batch_size_without_ids");
3515
+ if (flags.idsColumn !== void 0) throw usage2("--ids-column needs --ids.", "ids_column_without_ids");
3516
+ if (flags.batchSize !== void 0) throw usage2("--batch-size needs --ids.", "batch_size_without_ids");
3060
3517
  return void 0;
3061
3518
  }
3062
3519
  if (flags.ids !== "-" && !flags.ids.startsWith("@")) {
3063
- throw usage("--ids takes @file or - (stdin).", "bad_ids_source", `Did you mean --ids @${flags.ids}?`);
3520
+ throw usage2("--ids takes @file or - (stdin).", "bad_ids_source", `Did you mean --ids @${flags.ids}?`);
3064
3521
  }
3065
3522
  if (flags.ids === "-" && flags.input === "-") {
3066
- throw usage("--ids - and --input - cannot both read stdin.", "stdin_conflict", "Pass one of them as @file.");
3523
+ throw usage2("--ids - and --input - cannot both read stdin.", "stdin_conflict", "Pass one of them as @file.");
3067
3524
  }
3068
3525
  if (flags.batchSize === void 0) return void 0;
3069
3526
  const raw = flags.batchSize.trim();
3070
3527
  const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
3071
3528
  if (!Number.isSafeInteger(n) || n < 1) {
3072
- throw usage(`--batch-size must be a whole number of at least 1, not "${flags.batchSize}".`, "bad_batch_size");
3529
+ throw usage2(`--batch-size must be a whole number of at least 1, not "${flags.batchSize}".`, "bad_batch_size");
3073
3530
  }
3074
3531
  return n;
3075
3532
  }
3076
3533
  async function readIds(flags, input) {
3077
3534
  for (const field of ["hg_ids", "domains"]) {
3078
3535
  if (field in input) {
3079
- throw usage(`--ids builds "${field}" itself; remove it from --input.`, "ids_conflict", void 0, { field });
3536
+ throw usage2(`--ids builds "${field}" itself; remove it from --input.`, "ids_conflict", void 0, { field });
3080
3537
  }
3081
3538
  }
3082
3539
  const text = flags.ids === "-" ? await readStdin() : readInputFile(flags.ids.slice(1), protectedDirs(), {}, "--ids @file");
3083
3540
  const lines = flags.idsColumn !== void 0 ? parseCsvColumn(text, flags.idsColumn) : parseIdLines(text);
3084
3541
  if (lines.length === 0) {
3085
- throw usage("--ids holds no HG ids or domains (only blank lines or # comments).", "no_ids");
3542
+ throw usage2("--ids holds no HG ids or domains (only blank lines or # comments).", "no_ids");
3086
3543
  }
3087
3544
  return lines;
3088
3545
  }
@@ -3098,22 +3555,30 @@ function render2(rows, format) {
3098
3555
  return formatValue(rows, format, { pretty: stdoutIsTty() });
3099
3556
  }
3100
3557
  var Run = class {
3101
- constructor(plan, format, streaming) {
3558
+ constructor(plan, format, streaming, paging = false) {
3102
3559
  this.plan = plan;
3103
3560
  this.format = format;
3104
3561
  this.streaming = streaming;
3562
+ this.paging = paging;
3105
3563
  }
3106
3564
  plan;
3107
3565
  format;
3108
3566
  streaming;
3567
+ paging;
3109
3568
  outcomes = /* @__PURE__ */ new Map();
3110
3569
  rows = [];
3111
3570
  rowErrors = 0;
3112
3571
  cursor = 0;
3113
3572
  callsMade = 0;
3573
+ /** `tools/call` re-sends across all batch calls (transport retries and governance re-sends). */
3574
+ retries = 0;
3114
3575
  callsWithoutCost = 0;
3115
3576
  creditSum = 0;
3116
3577
  failedBatches = 0;
3578
+ /** `--all-pages`: companies whose paging a tool error ended early. */
3579
+ pagingFailures = 0;
3580
+ /** `--all-pages`: rows whose result is marked truncated. */
3581
+ truncatedRows = 0;
3117
3582
  /** Emits every row, in input order, whose batch has returned. */
3118
3583
  async flush(select) {
3119
3584
  while (this.cursor < this.plan.lines.length) {
@@ -3122,6 +3587,7 @@ var Run = class {
3122
3587
  if (!outcome) return;
3123
3588
  const row = "result" in outcome ? { input: line.text, result: applySelect(outcome.result, select) } : { input: line.text, error: outcome.error };
3124
3589
  if ("error" in row) this.rowErrors += 1;
3590
+ else if ("result" in outcome && isRecord(outcome.result) && outcome.result.truncated === true) this.truncatedRows += 1;
3125
3591
  this.rows.push(row);
3126
3592
  this.cursor += 1;
3127
3593
  if (this.streaming) {
@@ -3144,6 +3610,9 @@ var Run = class {
3144
3610
  for (const u of batch.items) this.outcomes.set(u, { error });
3145
3611
  }
3146
3612
  };
3613
+ function isRowFailure(err) {
3614
+ return err.code === "tool_error" && err.details?.outcome_unknown !== true && err.details?.budget_write_failed !== true;
3615
+ }
3147
3616
  function rowError(code, message) {
3148
3617
  return { code, message: redact(message) };
3149
3618
  }
@@ -3152,17 +3621,28 @@ async function callBatch(run, session, tool, input, batch, key, opts) {
3152
3621
  run.callsMade += 1;
3153
3622
  let result;
3154
3623
  let budgetFailure = null;
3624
+ const sendsBefore = session.state.toolsCallSends;
3625
+ const governanceRetries = opts.governance?.retries ?? 0;
3626
+ let attempts = 1;
3155
3627
  try {
3156
- result = await session.callTool(tool.name, argsFor(input, batch));
3628
+ ({ result, budgetFailure, attempts } = await sendWithRetry(session, tool.name, argsFor(input, batch), {
3629
+ retries: governanceRetries,
3630
+ budgetMs: opts.governance?.budgetMs ?? 0,
3631
+ // Every attempt that came back: one ledger row, and its spend under a run cap.
3632
+ record: async (r) => {
3633
+ await opts.onResult?.(r);
3634
+ if (!budget) return null;
3635
+ try {
3636
+ await recordSpend(budget.id, budget.max, creditCostOf(r));
3637
+ return null;
3638
+ } catch (err) {
3639
+ return toHgiError(err);
3640
+ }
3641
+ },
3642
+ beforeResend: budget ? () => checkBatchBudget(budget, run) : void 0,
3643
+ report: reportRetry
3644
+ }));
3157
3645
  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
3646
  const outcome = interpretResult(result, tool.name);
3167
3647
  const index = matchEntries(batch.kind, outcome.value, key);
3168
3648
  if (!index) {
@@ -3176,11 +3656,17 @@ async function callBatch(run, session, tool, input, batch, key, opts) {
3176
3656
  } catch (raw) {
3177
3657
  if (!result) run.addCost(void 0);
3178
3658
  const err = toHgiError(raw);
3179
- if (err.code !== "tool_error" || err.details?.outcome_unknown === true) {
3180
- if (budgetFailure) throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, budget_write_failed: true }, cause: err });
3659
+ if (!isRowFailure(err)) {
3660
+ const retried = governanceRetries > 0 && err.code === "governance_unavailable";
3661
+ if (budgetFailure || retried) {
3662
+ const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
3663
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, ...extra }, cause: err });
3664
+ }
3181
3665
  throw err;
3182
3666
  }
3183
3667
  run.failBatch(batch, rowError(err.code, err.message));
3668
+ } finally {
3669
+ run.retries += Math.max(0, session.state.toolsCallSends - sendsBefore - 1);
3184
3670
  }
3185
3671
  return budgetFailure;
3186
3672
  }
@@ -3188,21 +3674,33 @@ async function checkBatchBudget(budget, run) {
3188
3674
  try {
3189
3675
  await checkBudget(budget.id, budget.max);
3190
3676
  } catch (raw) {
3191
- const err = toHgiError(raw);
3192
- if (err.code !== "budget_exceeded") throw err;
3193
- throw new HgiError(err.code, err.message, {
3194
- hint: `${run.callsMade} batch call(s) already ran and their rows were printed; nothing more was sent. Keep those rows, raise --max-credits or run \`hgi budget reset\`, then resume from the rest.`,
3195
- details: err.details,
3196
- cause: err
3197
- });
3677
+ throw capReached(toHgiError(raw), run);
3198
3678
  }
3199
3679
  }
3680
+ function capReached(err, run) {
3681
+ if (err.code !== "budget_exceeded") return err;
3682
+ const calls = run.paging ? "call(s)" : "batch call(s)";
3683
+ return new HgiError(err.code, err.message, {
3684
+ hint: `${run.callsMade} ${calls} already ran and their rows were printed; nothing more was sent. Keep those rows, raise --max-credits or run \`hgi budget reset\`, then resume from the rest.`,
3685
+ details: err.details,
3686
+ cause: err
3687
+ });
3688
+ }
3689
+ function budgetWriteFailed(budgetFailure, what) {
3690
+ return new HgiError("local_state_error", `The ${what} ran, but ${budgetFailure.message.replace(/^Could not/, "hgi could not")}`, {
3691
+ hint: "Every call so far already ran and was billed, and its rows were printed. Do NOT re-run them. Check the budget with `hgi budget status`.",
3692
+ details: { kind: "budget_write_failed", tool_ran: true },
3693
+ cause: budgetFailure
3694
+ });
3695
+ }
3200
3696
  function printMeta(run) {
3201
3697
  process.stderr.write(
3202
3698
  `${JSON.stringify({
3203
3699
  calls: run.callsMade,
3700
+ retries: run.retries,
3204
3701
  rows: run.rows.length,
3205
3702
  row_errors: run.rowErrors,
3703
+ ...run.paging ? { truncated_rows: run.truncatedRows } : {},
3206
3704
  credit_cost: run.creditCost(),
3207
3705
  calls_without_cost: run.callsWithoutCost
3208
3706
  })}
@@ -3234,6 +3732,70 @@ async function writeBuffered(run, opts) {
3234
3732
  function withProgress(details, run, extra = {}) {
3235
3733
  return { ...details, rows_emitted: run.rows.length, calls_made: run.callsMade, ...extra };
3236
3734
  }
3735
+ async function sendBatch(d, i) {
3736
+ const { run, opts } = d;
3737
+ const batch = run.plan.batches[i];
3738
+ if (opts.budget && i > 0) await checkBatchBudget(opts.budget, run);
3739
+ if (process.stderr.isTTY) process.stderr.write(`hgi: batch ${i + 1}/${run.plan.batches.length}
3740
+ `);
3741
+ return callBatch(run, d.session, d.tool, d.input, batch, d.key, opts);
3742
+ }
3743
+ async function runBatches(d) {
3744
+ for (const i of d.run.plan.batches.keys()) {
3745
+ const budgetFailure = await sendBatch(d, i);
3746
+ await d.run.flush(d.opts.select);
3747
+ if (budgetFailure) throw budgetWriteFailed(budgetFailure, "batch call");
3748
+ }
3749
+ }
3750
+ async function runPagedBatches(d, pager) {
3751
+ const { run, opts } = d;
3752
+ const batchOf = /* @__PURE__ */ new Map();
3753
+ run.plan.batches.forEach((b, i) => b.items.forEach((u) => batchOf.set(u, i)));
3754
+ const sent = /* @__PURE__ */ new Set();
3755
+ const pending = /* @__PURE__ */ new Map();
3756
+ const reached = /* @__PURE__ */ new Set();
3757
+ for (const { unique: u } of run.plan.lines) {
3758
+ if (reached.has(u)) continue;
3759
+ reached.add(u);
3760
+ const i = batchOf.get(u);
3761
+ const batch = run.plan.batches[i];
3762
+ if (!sent.has(i)) {
3763
+ sent.add(i);
3764
+ const budgetFailure = await sendBatch(d, i);
3765
+ for (const item of batch.items) {
3766
+ const outcome2 = run.outcomes.get(item);
3767
+ if (!outcome2) continue;
3768
+ run.outcomes.delete(item);
3769
+ pending.set(item, outcome2);
3770
+ }
3771
+ if (budgetFailure) {
3772
+ for (const [item, outcome2] of pending) {
3773
+ run.outcomes.set(item, "result" in outcome2 && isRecord(outcome2.result) ? { result: pager.settle(outcome2.result, "local_state_error") } : outcome2);
3774
+ }
3775
+ await run.flush(opts.select);
3776
+ throw budgetWriteFailed(budgetFailure, "batch call");
3777
+ }
3778
+ }
3779
+ const outcome = pending.get(u);
3780
+ if (!outcome) continue;
3781
+ pending.delete(u);
3782
+ if (!("result" in outcome) || !isRecord(outcome.result)) {
3783
+ run.outcomes.set(u, outcome);
3784
+ await run.flush(opts.select);
3785
+ continue;
3786
+ }
3787
+ const { merged, failure } = await pager.page(outcome.result, { field: batch.field, text: u.text, kind: u.kind, norm: u.norm });
3788
+ run.outcomes.set(u, { result: merged });
3789
+ await run.flush(opts.select);
3790
+ if (!failure) continue;
3791
+ if (isRowFailure(failure)) {
3792
+ run.pagingFailures += 1;
3793
+ continue;
3794
+ }
3795
+ if (failure.code === "local_state_error" && failure.details?.kind === "budget_write_failed") throw budgetWriteFailed(failure, "follow-up page");
3796
+ throw capReached(failure, run);
3797
+ }
3798
+ }
3237
3799
  async function runBatch(session, tool, input, lines, opts) {
3238
3800
  const plan = buildBatches(lines, batchFields(tool), opts.batchSize);
3239
3801
  if (opts.validate) {
@@ -3250,22 +3812,25 @@ async function runBatch(session, tool, input, lines, opts) {
3250
3812
  });
3251
3813
  }
3252
3814
  const format = opts.format ? parseFormat(opts.format) : "jsonl";
3253
- const run = new Run(plan, format, format === "jsonl" && !opts.out);
3254
- const key = entriesKey(tool);
3815
+ const run = new Run(plan, format, format === "jsonl" && !opts.out, opts.paging !== void 0);
3816
+ const driver = { run, session, tool, input, key: entriesKey(tool), opts };
3255
3817
  try {
3256
- for (const [i, batch] of plan.batches.entries()) {
3257
- if (opts.budget && i > 0) await checkBatchBudget(opts.budget, run);
3258
- if (process.stderr.isTTY) process.stderr.write(`hgi: batch ${i + 1}/${plan.batches.length}
3259
- `);
3260
- const budgetFailure = await callBatch(run, session, tool, input, batch, key, opts);
3261
- await run.flush(opts.select);
3262
- if (budgetFailure) {
3263
- throw new HgiError("local_state_error", `The batch call ran, but ${budgetFailure.message.replace(/^Could not/, "hgi could not")}`, {
3264
- hint: "Every call so far already ran and was billed, and its rows were printed. Do NOT re-run them. Check the budget with `hgi budget status`.",
3265
- details: { kind: "budget_write_failed", tool_ran: true },
3266
- cause: budgetFailure
3267
- });
3268
- }
3818
+ if (opts.paging) {
3819
+ const { spec, maxPages } = opts.paging;
3820
+ const pagingCtx = {
3821
+ session,
3822
+ tool,
3823
+ input,
3824
+ spec,
3825
+ maxPages,
3826
+ validate: opts.validate,
3827
+ budget: opts.budget,
3828
+ onResult: opts.onResult,
3829
+ governance: opts.governance
3830
+ };
3831
+ await runPagedBatches(driver, companyPager(pagingCtx, run));
3832
+ } else {
3833
+ await runBatches(driver);
3269
3834
  }
3270
3835
  } catch (raw) {
3271
3836
  const err = toHgiError(raw);
@@ -3278,7 +3843,7 @@ async function runBatch(session, tool, input, lines, opts) {
3278
3843
  if (opts.meta) printMeta(run);
3279
3844
  throw new HgiError(err.code, err.message, {
3280
3845
  hint: err.hint,
3281
- details: withProgress(err.details, run, outFailed ? { out_write_failed: true } : {}),
3846
+ details: withProgress(err.details, run, { ...run.paging ? { partial_result: true } : {}, ...outFailed ? { out_write_failed: true } : {} }),
3282
3847
  cause: err
3283
3848
  });
3284
3849
  }
@@ -3296,15 +3861,65 @@ async function runBatch(session, tool, input, lines, opts) {
3296
3861
  cause: outError
3297
3862
  });
3298
3863
  }
3864
+ if (run.pagingFailures > 0) {
3865
+ const batches = run.failedBatches > 0 ? `${run.failedBatches} of ${plan.batches.length} batch calls failed, and ` : "";
3866
+ const companies = `${run.pagingFailures} ${run.pagingFailures === 1 ? "company" : "companies"}`;
3867
+ throw new HgiError("tool_error", `${batches}paging stopped early on a tool error for ${companies}.`, {
3868
+ hint: 'Every row was printed. Rows with truncated_reason "tool_error" hold the pages fetched before the error; rows with an error hold none. Re-run only those inputs.',
3869
+ details: withProgress({ failed_batches: run.failedBatches, paging_failures: run.pagingFailures }, run)
3870
+ });
3871
+ }
3299
3872
  if (run.failedBatches > 0) {
3300
3873
  throw new HgiError("tool_error", `${run.failedBatches} of ${plan.batches.length} batch calls failed; their rows carry the error.`, {
3301
3874
  hint: "Every other row was printed. Re-run only the inputs whose rows have an error.",
3302
- details: withProgress({ failed_batches: run.failedBatches }, run)
3875
+ details: withProgress({ failed_batches: run.failedBatches, ...run.paging ? { paging_failures: 0 } : {} }, run)
3876
+ });
3877
+ }
3878
+ }
3879
+
3880
+ // src/commands/retry-options.ts
3881
+ var MAX_RETRIES = 20;
3882
+ var MAX_RETRY_BUDGET_SECONDS = 3600;
3883
+ function parseRetries(raw, source) {
3884
+ const trimmed = raw.trim();
3885
+ const value = /^\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN;
3886
+ if (!Number.isSafeInteger(value) || value > MAX_RETRIES) {
3887
+ throw new HgiError("invalid_input", `${source} must be a whole number from 0 to ${MAX_RETRIES}.`, {
3888
+ hint: "For example --retries 6. 0 turns every retry off.",
3889
+ details: { reason: "bad_retries" }
3303
3890
  });
3304
3891
  }
3892
+ return value;
3893
+ }
3894
+ function parseRetryBudget(raw, source) {
3895
+ const trimmed = raw.trim();
3896
+ const seconds = trimmed === "" ? Number.NaN : Number(trimmed);
3897
+ if (!Number.isFinite(seconds) || seconds <= 0 || seconds > MAX_RETRY_BUDGET_SECONDS) {
3898
+ throw new HgiError("invalid_input", `${source} must be a positive number of seconds, at most ${MAX_RETRY_BUDGET_SECONDS}.`, {
3899
+ hint: "For example --retry-budget 600.",
3900
+ details: { reason: "bad_retry_budget" }
3901
+ });
3902
+ }
3903
+ return seconds * 1e3;
3904
+ }
3905
+ function resolveRetryOptions(flags, env = process.env) {
3906
+ let retries = null;
3907
+ if (flags.retries !== void 0) retries = parseRetries(flags.retries, "--retries");
3908
+ else if (env.HGI_RETRIES) retries = parseRetries(env.HGI_RETRIES, "HGI_RETRIES");
3909
+ let retryBudgetMs = null;
3910
+ if (flags.retryBudget !== void 0) retryBudgetMs = parseRetryBudget(flags.retryBudget, "--retry-budget");
3911
+ else if (env.HGI_RETRY_BUDGET) retryBudgetMs = parseRetryBudget(env.HGI_RETRY_BUDGET, "HGI_RETRY_BUDGET");
3912
+ return { retries, retryBudgetMs };
3305
3913
  }
3306
3914
 
3307
3915
  // src/commands/invoke.ts
3916
+ function transportRetryOptions(r) {
3917
+ return {
3918
+ ...r.retries !== null ? { retries: r.retries } : {},
3919
+ ...r.retryBudgetMs !== null ? { retryBudgetMs: r.retryBudgetMs } : {},
3920
+ onRetry: reportRetry
3921
+ };
3922
+ }
3308
3923
  function parseTimeoutMs(raw) {
3309
3924
  const seconds = Number(raw);
3310
3925
  if (!Number.isFinite(seconds) || seconds <= 0) {
@@ -3346,7 +3961,7 @@ function assertVerb(requested, tool) {
3346
3961
  details: { tool: tool.name, expected_verb: expected, requested_verb: requested }
3347
3962
  });
3348
3963
  }
3349
- async function failAfterBudgetWrite(cause, value, opts, creditCost) {
3964
+ async function failAfterBudgetWrite(cause, value, opts, creditCost, extraDetails = {}) {
3350
3965
  try {
3351
3966
  await emit(value, { format: opts.format });
3352
3967
  } catch {
@@ -3355,15 +3970,84 @@ async function failAfterBudgetWrite(cause, value, opts, creditCost) {
3355
3970
  }
3356
3971
  throw new HgiError("local_state_error", `The tool ran, but ${cause.message.replace(/^Could not/, "hgi could not")}`, {
3357
3972
  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 },
3973
+ details: { kind: "budget_write_failed", tool_ran: true, ...extraDetails },
3359
3974
  cause
3360
3975
  });
3361
3976
  }
3977
+ async function emitResult(value, verb, opts, creditCost) {
3978
+ try {
3979
+ await emit(value, { format: opts.format, out: opts.out, force: opts.force, allowForce: verb === "run" });
3980
+ } catch (err) {
3981
+ if (!opts.out) throw err;
3982
+ const cause = toHgiError(err);
3983
+ try {
3984
+ await emit(value, { format: opts.format });
3985
+ } catch {
3986
+ }
3987
+ throw new HgiError("local_state_error", `The tool ran, but its result could not be written to ${opts.out}: ${cause.message}`, {
3988
+ hint: "The tool already ran and was billed; its result was printed to stdout instead. Do NOT re-run it.",
3989
+ details: { kind: "write_failed", reason: cause.details?.reason ?? cause.code, tool_ran: true },
3990
+ cause: err
3991
+ });
3992
+ } finally {
3993
+ reportCredit(creditCost);
3994
+ }
3995
+ }
3996
+ async function runPaged(ctx, verb, opts, mcpVersion) {
3997
+ const paged = await runAllPages(ctx);
3998
+ if (paged.pageOneBudgetFailure && paged.failure) {
3999
+ const one = applySelect(paged.value, opts.select);
4000
+ const value2 = opts.meta ? { result: one, credit_cost: paged.creditCost, mcp_version: mcpVersion() } : one;
4001
+ await failAfterBudgetWrite(paged.failure, value2, opts, paged.creditCost);
4002
+ }
4003
+ const selected = applySelect(paged.value, opts.select);
4004
+ const value = opts.meta ? {
4005
+ result: selected,
4006
+ credit_cost: paged.creditCost,
4007
+ mcp_version: mcpVersion(),
4008
+ pages_fetched: paged.callsMade,
4009
+ retries: paged.retries,
4010
+ calls_without_cost: paged.callsWithoutCost
4011
+ } : selected;
4012
+ const failure = paged.failure;
4013
+ if (!failure) {
4014
+ await emitResult(value, verb, opts, paged.creditCost);
4015
+ return;
4016
+ }
4017
+ const partial = { partial_result: true, pages_fetched: paged.callsMade };
4018
+ if (failure.code === "local_state_error" && failure.details?.kind === "budget_write_failed") {
4019
+ await failAfterBudgetWrite(failure, value, opts, paged.creditCost, partial);
4020
+ }
4021
+ let outFailed = false;
4022
+ try {
4023
+ await emit(value, { format: opts.format, out: opts.out, force: opts.force, allowForce: verb === "run" });
4024
+ } catch {
4025
+ if (opts.out) {
4026
+ outFailed = true;
4027
+ try {
4028
+ await emit(value, { format: opts.format });
4029
+ } catch {
4030
+ }
4031
+ }
4032
+ } finally {
4033
+ reportCredit(paged.creditCost);
4034
+ }
4035
+ const resultWent = outFailed || !opts.out ? "stdout" : opts.out;
4036
+ throw new HgiError(failure.code, failure.message, {
4037
+ 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.`,
4038
+ details: { ...failure.details, ...partial, ...outFailed ? { out_write_failed: true } : {} },
4039
+ cause: failure
4040
+ });
4041
+ }
3362
4042
  async function runInvoke(verb, toolName, opts, cmd) {
3363
4043
  const batchSize = preflightBatchFlags(opts);
3364
4044
  const input = await readInput(opts.input);
4045
+ const maxPages = verb === "call" ? preflightPaging(opts, input) : null;
3365
4046
  preflightOutput({ format: opts.format, select: opts.select, out: opts.out, force: opts.force, allowForce: verb === "run" });
3366
4047
  const timeoutMs = parseTimeoutMs(opts.timeout);
4048
+ const retryOptions = resolveRetryOptions({ retries: opts.retries, retryBudget: opts.retryBudget });
4049
+ const transportRetry = transportRetryOptions(retryOptions);
4050
+ const governance = { retries: verb === "call" ? retryOptions.retries ?? 0 : 0, budgetMs: retryLimits(transportRetry).budgetMs };
3367
4051
  const label = parseLabel(opts.label);
3368
4052
  const ledger = ledgerPath();
3369
4053
  const ids = opts.ids === void 0 ? void 0 : await readIds({ ...opts, ids: opts.ids }, input);
@@ -3372,7 +4056,7 @@ async function runInvoke(verb, toolName, opts, cmd) {
3372
4056
  if (budgetId2 !== null && maxCredits !== null) await checkBudget(budgetId2, maxCredits);
3373
4057
  const ctx = buildContext(cmd);
3374
4058
  const creds = ctx.tokens.loadCredentials();
3375
- const session = await openSession(ctx, { timeoutMs });
4059
+ const session = await openSession(ctx, { timeoutMs, retry: transportRetry });
3376
4060
  const recordUsage = (result) => recordCall(ledger, {
3377
4061
  v: 1,
3378
4062
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -3403,6 +4087,7 @@ async function runInvoke(verb, toolName, opts, cmd) {
3403
4087
  }
3404
4088
  assertVerb(verb, tool);
3405
4089
  if (ids) {
4090
+ const paging = maxPages === null ? void 0 : { spec: assertBatchPageable(tool, entriesKey(tool)), maxPages };
3406
4091
  await runBatch(session, tool, input, ids, {
3407
4092
  batchSize,
3408
4093
  format: opts.format,
@@ -3411,55 +4096,66 @@ async function runInvoke(verb, toolName, opts, cmd) {
3411
4096
  meta: opts.meta,
3412
4097
  validate: opts.validate,
3413
4098
  budget: budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : void 0,
3414
- onResult: recordUsage
4099
+ onResult: recordUsage,
4100
+ governance,
4101
+ paging
3415
4102
  });
3416
4103
  return;
3417
4104
  }
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
- }
4105
+ if (maxPages !== null) {
4106
+ const spec = assertPageable(tool);
4107
+ if (opts.validate) assertValidInput(tool, input);
4108
+ await runPaged(
4109
+ {
4110
+ session,
4111
+ tool,
4112
+ input,
4113
+ spec,
4114
+ maxPages,
4115
+ validate: opts.validate,
4116
+ budget: budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : void 0,
4117
+ onResult: recordUsage,
4118
+ governance
4119
+ },
4120
+ verb,
4121
+ opts,
4122
+ () => session.state.mcpVersion
4123
+ );
4124
+ return;
3428
4125
  }
4126
+ if (opts.validate) assertValidInput(tool, input);
4127
+ const capped = budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : null;
4128
+ const { result, attempts, budgetFailure } = await sendWithRetry(session, toolName, input, {
4129
+ ...governance,
4130
+ // Every attempt that came back: one ledger row, and its spend under a run cap.
4131
+ record: async (r) => {
4132
+ await recordUsage(r);
4133
+ if (!capped) return null;
4134
+ try {
4135
+ await recordSpend(capped.id, capped.max, creditCostOf(r));
4136
+ return null;
4137
+ } catch (err) {
4138
+ return toHgiError(err);
4139
+ }
4140
+ },
4141
+ beforeResend: capped ? async () => void await checkBudget(capped.id, capped.max) : void 0,
4142
+ report: reportRetry
4143
+ });
3429
4144
  let outcome;
3430
4145
  try {
3431
4146
  outcome = interpretResult(result, toolName);
3432
4147
  } 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 });
4148
+ const retried = governance.retries > 0 && err instanceof HgiError && err.code === "governance_unavailable";
4149
+ if ((budgetFailure || retried) && err instanceof HgiError) {
4150
+ const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
4151
+ throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, ...extra }, cause: err });
3435
4152
  }
3436
4153
  throw err;
3437
4154
  }
3438
4155
  const selected = applySelect(outcome.value, opts.select);
3439
- const value = opts.meta ? { result: selected, credit_cost: outcome.creditCost, mcp_version: session.state.mcpVersion } : selected;
4156
+ const value = opts.meta ? { result: selected, credit_cost: outcome.creditCost, mcp_version: session.state.mcpVersion, attempts } : selected;
3440
4157
  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
- }
4158
+ await emitResult(value, verb, opts, outcome.creditCost);
3463
4159
  } finally {
3464
4160
  await session.close();
3465
4161
  }
@@ -3470,9 +4166,12 @@ function registerInvokeCommands(program) {
3470
4166
  run: "Run a tool that changes state or starts work. Fails for read-only tools."
3471
4167
  };
3472
4168
  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());
4169
+ 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
4170
  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(
4171
+ 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(
4172
+ "--all-pages",
4173
+ "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)"
4174
+ ).option("--max-pages <n>", "with --all-pages, fetch at most n pages per page object, page 1 included (default 10)").addHelpText(
3476
4175
  "after",
3477
4176
  [
3478
4177
  "",
@@ -3480,10 +4179,32 @@ function registerInvokeCommands(program) {
3480
4179
  " --max-credits <n> / HGI_MAX_CREDITS refuse the call, sending nothing (exit 13), once this run has spent n credits",
3481
4180
  " HGI_BUDGET_ID the run to count against (default: the parent process id, so one shell or script)",
3482
4181
  " `hgi budget status` shows the spend; `hgi budget reset` starts it over.",
3483
- " With --ids, every batch call is checked and counted."
4182
+ " With --ids, every batch call (and, with --all-pages, every follow-up page) is checked and counted.",
4183
+ "",
4184
+ "Paging (--all-pages):",
4185
+ ' Only tools whose schemas show an integer "offset" input and a rows array with has_more or a total.',
4186
+ " Pages are fetched one at a time. Each extra page is a separate, billed call; for batch tools",
4187
+ " (hg_ids/domains), follow-ups go one call per company. Paging stops on has_more: false, an empty or",
4188
+ " short page, the total reached, or --max-pages (default 10). A stopped-early part says",
4189
+ " truncated: true and truncated_reason. A later-page failure prints the pages so far, then exits",
4190
+ " with that failure's code and details.partial_result: true. The run cap is checked before every page.",
4191
+ " With --ids: each batch is sent as --ids sends it, then every unfinished company is paged on its own",
4192
+ " (--max-pages per company); each row's result is that company's merged entry. A tool error on a",
4193
+ " follow-up truncates only that row (exit 3 at the end); any other failure stops the run."
3484
4194
  ].join("\n")
3485
4195
  );
3486
4196
  }
4197
+ cmd.addHelpText(
4198
+ "after",
4199
+ [
4200
+ "",
4201
+ "Retries (only failures before the tool runs; never a call that may have run):",
4202
+ " hgi retries a 429, the server shedding load (503) and a connection that was never established, and prints",
4203
+ " one line on stderr before each wait. --retries n allows n of each; --retry-budget caps the waiting per request.",
4204
+ 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.",
4205
+ " The flags win over HGI_RETRIES / HGI_RETRY_BUDGET."
4206
+ ].join("\n")
4207
+ );
3487
4208
  cmd.action((tool, opts, c) => runInvoke(verb, tool, opts, c));
3488
4209
  }
3489
4210
  }
@@ -3494,7 +4215,7 @@ import os2 from "os";
3494
4215
  import path7 from "path";
3495
4216
 
3496
4217
  // 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';
4218
+ 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> --ids @hg_ids.txt --all-pages # a whole list, every page per company\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- With `--ids`: each batch is sent as usual, then every unfinished company is paged on its own (`--max-pages` per company), and each row\'s `result` is that company\'s merged entry. A tool error on a follow-up truncates only that row (`truncated_reason: "tool_error"`, exit 3 at the end); any other failure stops the run with the rows so far printed and `details.partial_result: true`. `--meta`\'s stderr summary adds `truncated_rows`.\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`. With `--ids`, the rows so far, the last one possibly `truncated` (`rows_emitted`, `calls_made`) | 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
4219
 
3499
4220
  // src/commands/skill.ts
3500
4221
  function defaultSkillsDir() {