@hginsights/hgi 0.2.0 → 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" : "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";
@@ -3093,6 +3093,71 @@ function reportRetry(e) {
3093
3093
  );
3094
3094
  }
3095
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
+
3096
3161
  // src/commands/retry.ts
3097
3162
  var GOVERNANCE_MAX_WAIT_SECONDS = 30;
3098
3163
  function isGovernanceUnavailable(result) {
@@ -3117,103 +3182,437 @@ async function sendWithRetry(session, name, args, opts) {
3117
3182
  }
3118
3183
  }
3119
3184
 
3120
- // src/commands/batch.ts
3121
- function usage(message, reason, hint, extra = {}) {
3122
- return new HgiError("invalid_input", message, { hint, details: { reason, ...extra } });
3123
- }
3124
- function preflightBatchFlags(flags) {
3125
- if (flags.ids === void 0) {
3126
- if (flags.idsColumn !== void 0) throw usage("--ids-column needs --ids.", "ids_column_without_ids");
3127
- if (flags.batchSize !== void 0) throw usage("--batch-size needs --ids.", "batch_size_without_ids");
3128
- return void 0;
3129
- }
3130
- if (flags.ids !== "-" && !flags.ids.startsWith("@")) {
3131
- throw usage("--ids takes @file or - (stdin).", "bad_ids_source", `Did you mean --ids @${flags.ids}?`);
3132
- }
3133
- if (flags.ids === "-" && flags.input === "-") {
3134
- throw usage("--ids - and --input - cannot both read stdin.", "stdin_conflict", "Pass one of them as @file.");
3135
- }
3136
- if (flags.batchSize === void 0) return void 0;
3137
- const raw = flags.batchSize.trim();
3138
- const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
3139
- if (!Number.isSafeInteger(n) || n < 1) {
3140
- throw usage(`--batch-size must be a whole number of at least 1, not "${flags.batchSize}".`, "bad_batch_size");
3141
- }
3142
- return n;
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 } });
3143
3189
  }
3144
- async function readIds(flags, input) {
3145
- for (const field of ["hg_ids", "domains"]) {
3146
- if (field in input) {
3147
- throw usage(`--ids builds "${field}" itself; remove it from --input.`, "ids_conflict", void 0, { field });
3148
- }
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;
3149
3194
  }
3150
- const text = flags.ids === "-" ? await readStdin() : readInputFile(flags.ids.slice(1), protectedDirs(), {}, "--ids @file");
3151
- const lines = flags.idsColumn !== void 0 ? parseCsvColumn(text, flags.idsColumn) : parseIdLines(text);
3152
- if (lines.length === 0) {
3153
- throw usage("--ids holds no HG ids or domains (only blank lines or # comments).", "no_ids");
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;
3154
3201
  }
3155
- return lines;
3202
+ if (Object.hasOwn(input, "offset")) throw usage('--all-pages sets "offset" itself; remove it from --input.', "offset_with_all_pages");
3203
+ return maxPages;
3156
3204
  }
3157
- function argsFor(input, batch) {
3158
- return { ...input, [batch.field]: batch.items.map((u) => u.text) };
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
+ });
3159
3212
  }
3160
- function stdoutIsTty() {
3161
- return Boolean(process.stdout.isTTY);
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
+ });
3162
3220
  }
3163
- function render2(rows, format) {
3164
- if (format === "jsonl") return rows.map((r) => `${JSON.stringify(r)}
3165
- `).join("");
3166
- return formatValue(rows, format, { pretty: stdoutIsTty() });
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
+ });
3167
3234
  }
3168
- var Run = class {
3169
- constructor(plan, format, streaming) {
3170
- this.plan = plan;
3171
- this.format = format;
3172
- this.streaming = streaming;
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);
3173
3240
  }
3174
- plan;
3175
- format;
3176
- streaming;
3177
- outcomes = /* @__PURE__ */ new Map();
3178
- rows = [];
3179
- rowErrors = 0;
3180
- cursor = 0;
3181
- callsMade = 0;
3182
- /** `tools/call` re-sends across all batch calls (transport retries and governance re-sends). */
3183
- retries = 0;
3184
- callsWithoutCost = 0;
3185
- creditSum = 0;
3186
- failedBatches = 0;
3187
- /** Emits every row, in input order, whose batch has returned. */
3188
- async flush(select) {
3189
- while (this.cursor < this.plan.lines.length) {
3190
- const line = this.plan.lines[this.cursor];
3191
- const outcome = this.outcomes.get(line.unique);
3192
- if (!outcome) return;
3193
- const row = "result" in outcome ? { input: line.text, result: applySelect(outcome.result, select) } : { input: line.text, error: outcome.error };
3194
- if ("error" in row) this.rowErrors += 1;
3195
- this.rows.push(row);
3196
- this.cursor += 1;
3197
- if (this.streaming) {
3198
- const text = `${JSON.stringify(row)}
3199
- `;
3200
- await writeStream(process.stdout, stdoutIsTty() ? escapeJsonForTerminal(text) : text);
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 });
3201
3291
  }
3292
+ throw err;
3202
3293
  }
3203
3294
  }
3204
- addCost(result) {
3205
- const cost = result ? creditCostOf(result) : null;
3206
- if (cost === null) this.callsWithoutCost += 1;
3207
- else this.creditSum += cost;
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
+ }
3208
3302
  }
3209
- creditCost() {
3210
- return this.callsMade > this.callsWithoutCost ? this.creditSum : null;
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;
3211
3308
  }
3212
- failBatch(batch, error) {
3213
- this.failedBatches += 1;
3214
- for (const u of batch.items) this.outcomes.set(u, { error });
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";
3215
3327
  }
3216
- };
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
+ }
3508
+
3509
+ // src/commands/batch.ts
3510
+ function usage2(message, reason, hint, extra = {}) {
3511
+ return new HgiError("invalid_input", message, { hint, details: { reason, ...extra } });
3512
+ }
3513
+ function preflightBatchFlags(flags) {
3514
+ if (flags.ids === void 0) {
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");
3517
+ return void 0;
3518
+ }
3519
+ if (flags.ids !== "-" && !flags.ids.startsWith("@")) {
3520
+ throw usage2("--ids takes @file or - (stdin).", "bad_ids_source", `Did you mean --ids @${flags.ids}?`);
3521
+ }
3522
+ if (flags.ids === "-" && flags.input === "-") {
3523
+ throw usage2("--ids - and --input - cannot both read stdin.", "stdin_conflict", "Pass one of them as @file.");
3524
+ }
3525
+ if (flags.batchSize === void 0) return void 0;
3526
+ const raw = flags.batchSize.trim();
3527
+ const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
3528
+ if (!Number.isSafeInteger(n) || n < 1) {
3529
+ throw usage2(`--batch-size must be a whole number of at least 1, not "${flags.batchSize}".`, "bad_batch_size");
3530
+ }
3531
+ return n;
3532
+ }
3533
+ async function readIds(flags, input) {
3534
+ for (const field of ["hg_ids", "domains"]) {
3535
+ if (field in input) {
3536
+ throw usage2(`--ids builds "${field}" itself; remove it from --input.`, "ids_conflict", void 0, { field });
3537
+ }
3538
+ }
3539
+ const text = flags.ids === "-" ? await readStdin() : readInputFile(flags.ids.slice(1), protectedDirs(), {}, "--ids @file");
3540
+ const lines = flags.idsColumn !== void 0 ? parseCsvColumn(text, flags.idsColumn) : parseIdLines(text);
3541
+ if (lines.length === 0) {
3542
+ throw usage2("--ids holds no HG ids or domains (only blank lines or # comments).", "no_ids");
3543
+ }
3544
+ return lines;
3545
+ }
3546
+ function argsFor(input, batch) {
3547
+ return { ...input, [batch.field]: batch.items.map((u) => u.text) };
3548
+ }
3549
+ function stdoutIsTty() {
3550
+ return Boolean(process.stdout.isTTY);
3551
+ }
3552
+ function render2(rows, format) {
3553
+ if (format === "jsonl") return rows.map((r) => `${JSON.stringify(r)}
3554
+ `).join("");
3555
+ return formatValue(rows, format, { pretty: stdoutIsTty() });
3556
+ }
3557
+ var Run = class {
3558
+ constructor(plan, format, streaming, paging = false) {
3559
+ this.plan = plan;
3560
+ this.format = format;
3561
+ this.streaming = streaming;
3562
+ this.paging = paging;
3563
+ }
3564
+ plan;
3565
+ format;
3566
+ streaming;
3567
+ paging;
3568
+ outcomes = /* @__PURE__ */ new Map();
3569
+ rows = [];
3570
+ rowErrors = 0;
3571
+ cursor = 0;
3572
+ callsMade = 0;
3573
+ /** `tools/call` re-sends across all batch calls (transport retries and governance re-sends). */
3574
+ retries = 0;
3575
+ callsWithoutCost = 0;
3576
+ creditSum = 0;
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;
3582
+ /** Emits every row, in input order, whose batch has returned. */
3583
+ async flush(select) {
3584
+ while (this.cursor < this.plan.lines.length) {
3585
+ const line = this.plan.lines[this.cursor];
3586
+ const outcome = this.outcomes.get(line.unique);
3587
+ if (!outcome) return;
3588
+ const row = "result" in outcome ? { input: line.text, result: applySelect(outcome.result, select) } : { input: line.text, error: outcome.error };
3589
+ if ("error" in row) this.rowErrors += 1;
3590
+ else if ("result" in outcome && isRecord(outcome.result) && outcome.result.truncated === true) this.truncatedRows += 1;
3591
+ this.rows.push(row);
3592
+ this.cursor += 1;
3593
+ if (this.streaming) {
3594
+ const text = `${JSON.stringify(row)}
3595
+ `;
3596
+ await writeStream(process.stdout, stdoutIsTty() ? escapeJsonForTerminal(text) : text);
3597
+ }
3598
+ }
3599
+ }
3600
+ addCost(result) {
3601
+ const cost = result ? creditCostOf(result) : null;
3602
+ if (cost === null) this.callsWithoutCost += 1;
3603
+ else this.creditSum += cost;
3604
+ }
3605
+ creditCost() {
3606
+ return this.callsMade > this.callsWithoutCost ? this.creditSum : null;
3607
+ }
3608
+ failBatch(batch, error) {
3609
+ this.failedBatches += 1;
3610
+ for (const u of batch.items) this.outcomes.set(u, { error });
3611
+ }
3612
+ };
3613
+ function isRowFailure(err) {
3614
+ return err.code === "tool_error" && err.details?.outcome_unknown !== true && err.details?.budget_write_failed !== true;
3615
+ }
3217
3616
  function rowError(code, message) {
3218
3617
  return { code, message: redact(message) };
3219
3618
  }
@@ -3257,7 +3656,7 @@ async function callBatch(run, session, tool, input, batch, key, opts) {
3257
3656
  } catch (raw) {
3258
3657
  if (!result) run.addCost(void 0);
3259
3658
  const err = toHgiError(raw);
3260
- if (err.code !== "tool_error" || err.details?.outcome_unknown === true) {
3659
+ if (!isRowFailure(err)) {
3261
3660
  const retried = governanceRetries > 0 && err.code === "governance_unavailable";
3262
3661
  if (budgetFailure || retried) {
3263
3662
  const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
@@ -3275,15 +3674,25 @@ async function checkBatchBudget(budget, run) {
3275
3674
  try {
3276
3675
  await checkBudget(budget.id, budget.max);
3277
3676
  } catch (raw) {
3278
- const err = toHgiError(raw);
3279
- if (err.code !== "budget_exceeded") throw err;
3280
- throw new HgiError(err.code, err.message, {
3281
- hint: `${run.callsMade} batch call(s) already ran and their rows were printed; nothing more was sent. Keep those rows, raise --max-credits or run \`hgi budget reset\`, then resume from the rest.`,
3282
- details: err.details,
3283
- cause: err
3284
- });
3677
+ throw capReached(toHgiError(raw), run);
3285
3678
  }
3286
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
+ }
3287
3696
  function printMeta(run) {
3288
3697
  process.stderr.write(
3289
3698
  `${JSON.stringify({
@@ -3291,6 +3700,7 @@ function printMeta(run) {
3291
3700
  retries: run.retries,
3292
3701
  rows: run.rows.length,
3293
3702
  row_errors: run.rowErrors,
3703
+ ...run.paging ? { truncated_rows: run.truncatedRows } : {},
3294
3704
  credit_cost: run.creditCost(),
3295
3705
  calls_without_cost: run.callsWithoutCost
3296
3706
  })}
@@ -3322,10 +3732,74 @@ async function writeBuffered(run, opts) {
3322
3732
  function withProgress(details, run, extra = {}) {
3323
3733
  return { ...details, rows_emitted: run.rows.length, calls_made: run.callsMade, ...extra };
3324
3734
  }
3325
- async function runBatch(session, tool, input, lines, opts) {
3326
- const plan = buildBatches(lines, batchFields(tool), opts.batchSize);
3327
- if (opts.validate) {
3328
- plan.batches.forEach((batch, i) => {
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
+ }
3799
+ async function runBatch(session, tool, input, lines, opts) {
3800
+ const plan = buildBatches(lines, batchFields(tool), opts.batchSize);
3801
+ if (opts.validate) {
3802
+ plan.batches.forEach((batch, i) => {
3329
3803
  try {
3330
3804
  assertValidInput(tool, argsFor(input, batch));
3331
3805
  } catch (err) {
@@ -3338,22 +3812,25 @@ async function runBatch(session, tool, input, lines, opts) {
3338
3812
  });
3339
3813
  }
3340
3814
  const format = opts.format ? parseFormat(opts.format) : "jsonl";
3341
- const run = new Run(plan, format, format === "jsonl" && !opts.out);
3342
- 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 };
3343
3817
  try {
3344
- for (const [i, batch] of plan.batches.entries()) {
3345
- if (opts.budget && i > 0) await checkBatchBudget(opts.budget, run);
3346
- if (process.stderr.isTTY) process.stderr.write(`hgi: batch ${i + 1}/${plan.batches.length}
3347
- `);
3348
- const budgetFailure = await callBatch(run, session, tool, input, batch, key, opts);
3349
- await run.flush(opts.select);
3350
- if (budgetFailure) {
3351
- throw new HgiError("local_state_error", `The batch call ran, but ${budgetFailure.message.replace(/^Could not/, "hgi could not")}`, {
3352
- hint: "Every call so far already ran and was billed, and its rows were printed. Do NOT re-run them. Check the budget with `hgi budget status`.",
3353
- details: { kind: "budget_write_failed", tool_ran: true },
3354
- cause: budgetFailure
3355
- });
3356
- }
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);
3357
3834
  }
3358
3835
  } catch (raw) {
3359
3836
  const err = toHgiError(raw);
@@ -3366,7 +3843,7 @@ async function runBatch(session, tool, input, lines, opts) {
3366
3843
  if (opts.meta) printMeta(run);
3367
3844
  throw new HgiError(err.code, err.message, {
3368
3845
  hint: err.hint,
3369
- 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 } : {} }),
3370
3847
  cause: err
3371
3848
  });
3372
3849
  }
@@ -3384,371 +3861,22 @@ async function runBatch(session, tool, input, lines, opts) {
3384
3861
  cause: outError
3385
3862
  });
3386
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
+ }
3387
3872
  if (run.failedBatches > 0) {
3388
3873
  throw new HgiError("tool_error", `${run.failedBatches} of ${plan.batches.length} batch calls failed; their rows carry the error.`, {
3389
3874
  hint: "Every other row was printed. Re-run only the inputs whose rows have an error.",
3390
- details: withProgress({ failed_batches: run.failedBatches }, run)
3875
+ details: withProgress({ failed_batches: run.failedBatches, ...run.paging ? { paging_failures: 0 } : {} }, run)
3391
3876
  });
3392
3877
  }
3393
3878
  }
3394
3879
 
3395
- // src/mcp/paging.ts
3396
- var NAMED_TOTALS = ["total", "total_count", "totalCount"];
3397
- var PAGE_SIZE_KEYS = ["limit", "max_results"];
3398
- function isNumeric(schema) {
3399
- return isRecord(schema) && (hasType(schema, "integer") || hasType(schema, "number"));
3400
- }
3401
- function isPositiveInt(value) {
3402
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
3403
- }
3404
- function totalKeyOf(props, rowsKey) {
3405
- for (const key of NAMED_TOTALS) {
3406
- if (Object.hasOwn(props, key) && isNumeric(props[key])) return key;
3407
- }
3408
- const candidates = Object.keys(props).filter(
3409
- (key) => key.startsWith("total_") && isNumeric(props[key]) && key.split("_").includes(rowsKey)
3410
- );
3411
- return candidates.length === 1 ? candidates[0] : void 0;
3412
- }
3413
- function pageObjectSpec(schema) {
3414
- const props = propertiesOf(schema);
3415
- const arrays = Object.keys(props).filter((key) => isArrayOfObjects(props[key]));
3416
- if (arrays.length !== 1) return null;
3417
- const rowsKey = arrays[0];
3418
- const hasMoreKey = Object.hasOwn(props, "has_more") ? "has_more" : Object.hasOwn(props, "hasMore") ? "hasMore" : void 0;
3419
- const totalKey = totalKeyOf(props, rowsKey);
3420
- if (hasMoreKey === void 0 && totalKey === void 0) return null;
3421
- return { rowsKey, ...hasMoreKey ? { hasMoreKey } : {}, ...totalKey ? { totalKey } : {} };
3422
- }
3423
- function pageSizeOfSchema(inputProps) {
3424
- const declared = PAGE_SIZE_KEYS.filter((key2) => Object.hasOwn(inputProps, key2));
3425
- if (declared.length !== 1) return {};
3426
- const key = declared[0];
3427
- const schema = inputProps[key];
3428
- const fallback = isRecord(schema) ? schema.default : void 0;
3429
- return { pageSizeKey: key, ...isPositiveInt(fallback) ? { pageSizeDefault: fallback } : {} };
3430
- }
3431
- function pagingSpec(tool) {
3432
- const inputProps = propertiesOf(tool.inputSchema);
3433
- const offset = inputProps.offset;
3434
- if (!isRecord(offset) || !hasType(offset, "integer")) return null;
3435
- if (!isRecord(tool.outputSchema)) return null;
3436
- const size = pageSizeOfSchema(inputProps);
3437
- const top = pageObjectSpec(tool.outputSchema);
3438
- if (top) return { kind: "top", ...top, ...size };
3439
- const outputProps = propertiesOf(tool.outputSchema);
3440
- const itemSpecs = Object.keys(outputProps).filter((key) => isArrayOfObjects(outputProps[key])).map((key) => ({ key, spec: pageObjectSpec(outputProps[key].items) })).filter((c) => c.spec !== null);
3441
- if (itemSpecs.length !== 1) return null;
3442
- const only = itemSpecs[0];
3443
- return { kind: "items", itemsKey: only.key, ...only.spec, ...size };
3444
- }
3445
- function pageSizeOf(spec, input) {
3446
- if (spec.pageSizeKey === void 0) return void 0;
3447
- const sent = input[spec.pageSizeKey];
3448
- if (isPositiveInt(sent)) return sent;
3449
- return spec.pageSizeDefault;
3450
- }
3451
- function stopReason(state, pageSize, maxPages) {
3452
- if (state.hasMore === false) return "done";
3453
- if (state.pageRows === 0) return "done";
3454
- if (pageSize !== void 0 && state.pageRows < pageSize) return "done";
3455
- if (typeof state.total === "number" && Number.isFinite(state.total) && state.collected >= state.total) return "done";
3456
- if (state.pages >= maxPages) return "max_pages";
3457
- return null;
3458
- }
3459
-
3460
- // src/commands/paging.ts
3461
- var DEFAULT_MAX_PAGES = 10;
3462
- function usage2(message, reason, extra = {}) {
3463
- return new HgiError("invalid_input", message, { hint: "Nothing was sent.", details: { reason, ...extra } });
3464
- }
3465
- function preflightPaging(flags, input) {
3466
- if (!flags.allPages) {
3467
- if (flags.maxPages !== void 0) throw usage2("--max-pages needs --all-pages.", "max_pages_without_all_pages");
3468
- return null;
3469
- }
3470
- let maxPages = DEFAULT_MAX_PAGES;
3471
- if (flags.maxPages !== void 0) {
3472
- const raw = flags.maxPages.trim();
3473
- const n = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
3474
- if (!Number.isSafeInteger(n) || n < 1) throw usage2(`--max-pages must be a whole number of at least 1, not "${flags.maxPages}".`, "bad_max_pages");
3475
- maxPages = n;
3476
- }
3477
- if (flags.ids !== void 0) throw usage2("--all-pages cannot be combined with --ids yet.", "all_pages_with_ids");
3478
- if (Object.hasOwn(input, "offset")) throw usage2('--all-pages sets "offset" itself; remove it from --input.', "offset_with_all_pages");
3479
- return maxPages;
3480
- }
3481
- function assertPageable(tool) {
3482
- const spec = pagingSpec(tool);
3483
- if (spec) return spec;
3484
- throw new HgiError("invalid_input", `${tool.name} cannot be paged safely with --all-pages.`, {
3485
- hint: 'Its schema has no integer "offset" input, or its output has no single rows array with has_more or a total. Nothing was sent. Page it yourself with --input.',
3486
- details: { reason: "not_pageable", tool: tool.name }
3487
- });
3488
- }
3489
- var StopPaging = class extends Error {
3490
- constructor(error) {
3491
- super(error.message);
3492
- this.error = error;
3493
- }
3494
- error;
3495
- /** The merged result up to the stop, set by the loop that caught it. */
3496
- merged;
3497
- };
3498
- function unexpected(tool, what) {
3499
- return new HgiError("tool_error", `A later page of ${tool.name} came back without ${what}; paging stopped.`, {
3500
- details: { reason: "unexpected_response", tool: tool.name }
3501
- });
3502
- }
3503
- var Pager = class {
3504
- constructor(ctx) {
3505
- this.ctx = ctx;
3506
- this.pageSize = pageSizeOf(ctx.spec, ctx.input);
3507
- }
3508
- ctx;
3509
- acc = { callsMade: 0, retries: 0, callsWithoutCost: 0, creditSum: 0 };
3510
- pageSize;
3511
- /**
3512
- * Sends one page. Page 1 was checked against the run cap before the session opened. A page whose spend could
3513
- * not be recorded is returned with `budgetFailure`, so its rows are kept before paging stops.
3514
- */
3515
- async fetch(args, first) {
3516
- const { session, tool, budget } = this.ctx;
3517
- if (!first && budget) await checkBudget(budget.id, budget.max);
3518
- if (!first && this.ctx.validate) assertValidInput(tool, args);
3519
- this.acc.callsMade += 1;
3520
- const sendsBefore = session.state.toolsCallSends;
3521
- const governanceRetries = this.ctx.governance?.retries ?? 0;
3522
- let sent;
3523
- try {
3524
- sent = await sendWithRetry(session, tool.name, args, {
3525
- retries: governanceRetries,
3526
- budgetMs: this.ctx.governance?.budgetMs ?? 0,
3527
- // Every attempt that came back: one ledger row, and its spend under a run cap.
3528
- record: async (r) => {
3529
- await this.ctx.onResult?.(r);
3530
- if (!budget) return null;
3531
- try {
3532
- await recordSpend(budget.id, budget.max, creditCostOf(r));
3533
- return null;
3534
- } catch (err) {
3535
- return toHgiError(err);
3536
- }
3537
- },
3538
- beforeResend: budget ? async () => void await checkBudget(budget.id, budget.max) : void 0,
3539
- report: reportRetry
3540
- });
3541
- } catch (err) {
3542
- this.acc.callsWithoutCost += 1;
3543
- throw err;
3544
- } finally {
3545
- this.acc.retries += Math.max(0, session.state.toolsCallSends - sendsBefore - 1);
3546
- }
3547
- const { result, attempts, budgetFailure } = sent;
3548
- const cost = creditCostOf(result);
3549
- if (cost === null) this.acc.callsWithoutCost += 1;
3550
- else this.acc.creditSum += cost;
3551
- try {
3552
- return { value: interpretResult(result, tool.name).value, budgetFailure };
3553
- } catch (err) {
3554
- const retried = governanceRetries > 0 && err instanceof HgiError && err.code === "governance_unavailable";
3555
- if ((budgetFailure || retried) && err instanceof HgiError) {
3556
- const extra = { ...budgetFailure ? { budget_write_failed: true } : {}, ...retried ? { attempts } : {} };
3557
- throw new HgiError(err.code, err.message, { hint: err.hint, details: { ...err.details, ...extra }, cause: err });
3558
- }
3559
- throw err;
3560
- }
3561
- }
3562
- /** A follow-up page: any failure stops paging. */
3563
- async fetchLater(args) {
3564
- try {
3565
- return await this.fetch(args, false);
3566
- } catch (err) {
3567
- throw new StopPaging(toHgiError(err));
3568
- }
3569
- }
3570
- track(entry) {
3571
- const rows = entry[this.ctx.spec.rowsKey];
3572
- const t = { entry, rows: Array.isArray(rows) ? [...rows] : null, pages: 0, done: false };
3573
- this.settle(t, Array.isArray(rows) ? rows.length : 0);
3574
- return t;
3575
- }
3576
- /** Applies the stop rule after a page with `pageRows` rows. */
3577
- settle(t, pageRows) {
3578
- t.pages += 1;
3579
- const { hasMoreKey, totalKey } = this.ctx.spec;
3580
- const reason = stopReason(
3581
- {
3582
- pageRows,
3583
- collected: t.rows?.length ?? 0,
3584
- pages: t.pages,
3585
- hasMore: hasMoreKey ? t.entry[hasMoreKey] : void 0,
3586
- total: totalKey ? t.entry[totalKey] : void 0
3587
- },
3588
- this.pageSize,
3589
- this.ctx.maxPages
3590
- );
3591
- if (reason === null) return;
3592
- t.done = true;
3593
- if (reason === "max_pages") t.reason = "max_pages";
3594
- }
3595
- /** Adds a follow-up page object's rows to its tracker. */
3596
- append(t, entry) {
3597
- const rows = entry[this.ctx.spec.rowsKey];
3598
- if (!Array.isArray(rows)) throw new StopPaging(unexpected(this.ctx.tool, `a "${this.ctx.spec.rowsKey}" array`));
3599
- t.entry = entry;
3600
- t.rows = [...t.rows ?? [], ...rows];
3601
- this.settle(t, rows.length);
3602
- }
3603
- merged(t) {
3604
- return {
3605
- ...t.entry,
3606
- ...t.rows === null ? {} : { [this.ctx.spec.rowsKey]: t.rows },
3607
- pages_fetched: t.pages,
3608
- ...t.reason === void 0 ? {} : { truncated: true, truncated_reason: t.reason }
3609
- };
3610
- }
3611
- creditCost() {
3612
- return this.acc.callsMade > this.acc.callsWithoutCost ? this.acc.creditSum : null;
3613
- }
3614
- };
3615
- function companyInputs(input) {
3616
- const out = [];
3617
- for (const [field, kind] of [["hg_ids", "id"], ["domains", "domain"]]) {
3618
- const values = input[field];
3619
- if (!Array.isArray(values)) continue;
3620
- for (const text of values) {
3621
- if (typeof text === "string") out.push({ field, kind, text, norm: kind === "id" ? normalizeId(text) : normalizeDomain(text) });
3622
- }
3623
- }
3624
- return out;
3625
- }
3626
- function entryKey(entry, kind) {
3627
- if (kind === "domain") {
3628
- const raw = keyText(entry[DOMAIN_MATCH_KEY]);
3629
- return raw === null ? null : normalizeDomain(raw);
3630
- }
3631
- for (const key of ID_MATCH_KEYS) {
3632
- const raw = keyText(entry[key]);
3633
- if (raw !== null) return normalizeId(raw);
3634
- }
3635
- return null;
3636
- }
3637
- function matches(entry, input) {
3638
- return entryKey(entry, input.kind) === input.norm;
3639
- }
3640
- function withoutCompanies(input) {
3641
- const rest = { ...input };
3642
- delete rest.hg_ids;
3643
- delete rest.domains;
3644
- return rest;
3645
- }
3646
- function planFollowUps(trackers, input) {
3647
- const live = trackers.filter((t) => t !== null);
3648
- const inputs = companyInputs(input);
3649
- if (inputs.length < 2) {
3650
- const named = inputs[0];
3651
- for (const t of live) {
3652
- if (t.done) continue;
3653
- if (trackers.length === 1 && (named === void 0 || matches(t.entry, named))) {
3654
- t.follow = "same";
3655
- if (named) t.expect = { kind: named.kind, norm: named.norm };
3656
- } else {
3657
- Object.assign(t, { done: true, reason: "unmatched" });
3658
- }
3659
- }
3660
- return;
3661
- }
3662
- const matchedBy = /* @__PURE__ */ new Map();
3663
- const candidates = live.map((t) => inputs.map((inp, i) => matches(t.entry, inp) ? i : -1).filter((i) => i >= 0));
3664
- for (const list of candidates) for (const i of list) matchedBy.set(i, (matchedBy.get(i) ?? 0) + 1);
3665
- live.forEach((t, k) => {
3666
- if (t.done) return;
3667
- const list = candidates[k];
3668
- const only = list.length === 1 ? list[0] : -1;
3669
- if (only >= 0 && matchedBy.get(only) === 1) {
3670
- const inp = inputs[only];
3671
- t.follow = { field: inp.field, text: inp.text, kind: inp.kind, norm: inp.norm };
3672
- } else {
3673
- Object.assign(t, { done: true, reason: "unmatched" });
3674
- }
3675
- });
3676
- }
3677
- async function pageTop(p, ctx, first) {
3678
- if (!isRecord(first)) return first;
3679
- const t = p.track(first);
3680
- try {
3681
- while (!t.done) {
3682
- const page = await p.fetchLater({ ...ctx.input, offset: t.rows?.length ?? 0 });
3683
- if (!isRecord(page.value)) throw new StopPaging(unexpected(ctx.tool, "a result object"));
3684
- p.append(t, page.value);
3685
- if (page.budgetFailure) throw new StopPaging(page.budgetFailure);
3686
- }
3687
- } catch (err) {
3688
- if (!(err instanceof StopPaging)) throw err;
3689
- if (!t.done) Object.assign(t, { done: true, reason: err.error.code });
3690
- err.merged = p.merged(t);
3691
- throw err;
3692
- }
3693
- return p.merged(t);
3694
- }
3695
- async function pageItems(p, ctx, first) {
3696
- const itemsKey = ctx.spec.itemsKey;
3697
- if (!isRecord(first) || !Array.isArray(first[itemsKey])) return first;
3698
- const entries = first[itemsKey];
3699
- const trackers = entries.map((e) => isRecord(e) ? p.track(e) : null);
3700
- planFollowUps(trackers, ctx.input);
3701
- const merge = () => ({ ...first, [itemsKey]: entries.map((e, i) => trackers[i] ? p.merged(trackers[i]) : e) });
3702
- try {
3703
- for (const t of trackers) {
3704
- while (t && !t.done) {
3705
- const follow = t.follow;
3706
- const args = follow === "same" ? { ...ctx.input, offset: t.rows?.length ?? 0 } : { ...withoutCompanies(ctx.input), [follow.field]: [follow.text], offset: t.rows?.length ?? 0 };
3707
- const page = await p.fetchLater(args);
3708
- if (!isRecord(page.value) || !Array.isArray(page.value[itemsKey])) {
3709
- throw new StopPaging(unexpected(ctx.tool, `a "${itemsKey}" array`));
3710
- }
3711
- const list = page.value[itemsKey];
3712
- const only = list.length === 1 && isRecord(list[0]) ? list[0] : null;
3713
- const want = follow === "same" ? t.expect : follow;
3714
- if (only === null || want !== void 0 && !matches(only, want)) {
3715
- Object.assign(t, { done: true, reason: "unmatched" });
3716
- } else {
3717
- p.append(t, only);
3718
- }
3719
- if (page.budgetFailure) throw new StopPaging(page.budgetFailure);
3720
- }
3721
- }
3722
- } catch (err) {
3723
- if (!(err instanceof StopPaging)) throw err;
3724
- for (const t of trackers) if (t && !t.done) Object.assign(t, { done: true, reason: err.error.code });
3725
- err.merged = merge();
3726
- throw err;
3727
- }
3728
- return merge();
3729
- }
3730
- async function runAllPages(ctx) {
3731
- const p = new Pager(ctx);
3732
- const first = await p.fetch(ctx.input, true);
3733
- const outcome = (value, failure) => ({
3734
- value,
3735
- callsMade: p.acc.callsMade,
3736
- retries: p.acc.retries,
3737
- callsWithoutCost: p.acc.callsWithoutCost,
3738
- creditCost: p.creditCost(),
3739
- ...failure ? { failure } : {}
3740
- });
3741
- if (first.budgetFailure) {
3742
- return { ...outcome(first.value, first.budgetFailure), pageOneBudgetFailure: true };
3743
- }
3744
- try {
3745
- return outcome(ctx.spec.kind === "top" ? await pageTop(p, ctx, first.value) : await pageItems(p, ctx, first.value));
3746
- } catch (err) {
3747
- if (err instanceof StopPaging) return outcome(err.merged, err.error);
3748
- throw err;
3749
- }
3750
- }
3751
-
3752
3880
  // src/commands/retry-options.ts
3753
3881
  var MAX_RETRIES = 20;
3754
3882
  var MAX_RETRY_BUDGET_SECONDS = 3600;
@@ -3959,6 +4087,7 @@ async function runInvoke(verb, toolName, opts, cmd) {
3959
4087
  }
3960
4088
  assertVerb(verb, tool);
3961
4089
  if (ids) {
4090
+ const paging = maxPages === null ? void 0 : { spec: assertBatchPageable(tool, entriesKey(tool)), maxPages };
3962
4091
  await runBatch(session, tool, input, ids, {
3963
4092
  batchSize,
3964
4093
  format: opts.format,
@@ -3968,7 +4097,8 @@ async function runInvoke(verb, toolName, opts, cmd) {
3968
4097
  validate: opts.validate,
3969
4098
  budget: budgetId2 !== null && maxCredits !== null ? { id: budgetId2, max: maxCredits } : void 0,
3970
4099
  onResult: recordUsage,
3971
- governance
4100
+ governance,
4101
+ paging
3972
4102
  });
3973
4103
  return;
3974
4104
  }
@@ -4049,7 +4179,7 @@ function registerInvokeCommands(program) {
4049
4179
  " --max-credits <n> / HGI_MAX_CREDITS refuse the call, sending nothing (exit 13), once this run has spent n credits",
4050
4180
  " HGI_BUDGET_ID the run to count against (default: the parent process id, so one shell or script)",
4051
4181
  " `hgi budget status` shows the spend; `hgi budget reset` starts it over.",
4052
- " 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.",
4053
4183
  "",
4054
4184
  "Paging (--all-pages):",
4055
4185
  ' Only tools whose schemas show an integer "offset" input and a rows array with has_more or a total.',
@@ -4057,7 +4187,10 @@ function registerInvokeCommands(program) {
4057
4187
  " (hg_ids/domains), follow-ups go one call per company. Paging stops on has_more: false, an empty or",
4058
4188
  " short page, the total reached, or --max-pages (default 10). A stopped-early part says",
4059
4189
  " truncated: true and truncated_reason. A later-page failure prints the pages so far, then exits",
4060
- " with that failure's code and details.partial_result: true. The run cap is checked before every page."
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."
4061
4194
  ].join("\n")
4062
4195
  );
4063
4196
  }
@@ -4082,7 +4215,7 @@ import os2 from "os";
4082
4215
  import path7 from "path";
4083
4216
 
4084
4217
  // src/generated/skill-md.ts
4085
- var SKILL_MD = '---\nname: hgi\ndescription: Look up company, contact, technology, intent and spend data from the HG Insights MCP server with the `hgi` command-line client. Use when the user asks about a company\'s tech stack, firmographics, intent signals, contacts, or wants to run an HG Insights agent, and `hgi` is installed.\n---\n\n# hgi: the HG Insights command-line client\n\n`hgi` is a thin client for the HG Insights MCP server. It signs in once through the user\'s browser, then exposes every tool the server offers to the signed-in user.\n\n## Rules\n\n1. **List tools first.** Run `hgi tools list --json` before your first call in a session. The list depends on the user, their organization and the server version, so never assume a tool exists and never reuse a tool list from memory. Each tool is marked `call` or `run`, and `required` shows the mandatory input fields.\n2. **Use `hgi call <tool> --input \'<json>\'` for lookups.** It only runs tools the server marks read-only. It is safe to run without asking.\n3. **Use `hgi run <tool> --input \'<json>\'` only with the user\'s approval.** It runs tools that change state or start work (for example starting an agent run, uploading an artifact by URL, or starting a customer-data discovery). It also runs tools that do not declare themselves read-only. Ask the user, say what the tool will do, then run it.\n4. **Report the credit cost after every call.** The cost is printed on stderr (`credit_cost: N`, or `{"credit_cost":N}` when stderr is not a terminal). `unknown` or `null` means the server did not report one. Tell the user what the call cost; credits are billed to their organization.\n5. **Never read, print or copy the credentials file** under `~/.config/hgi/`, and do not put tokens in commands. If `hgi` says the login is missing or expired, ask the user to run `hgi auth login` themselves. It opens their browser.\n6. **Using the wrong verb fails safely.** `hgi call` on a state-changing tool, or `hgi run` on a read-only tool, exits 10, names the right verb, and sends nothing.\n7. **Show a plan before working through a list.** When the work needs more than one batch (see `## Recipes`), first run one sample batch and report its `credit_cost`. Then show the plan: the calls, the number of batches, and the total estimated by extrapolating from the sample. **Wait for the user\'s go-ahead** before running the rest. Estimate only from the reported `credit_cost`, never from a price list; a figure from a past run may appear only as an example, labelled "observed".\n\n## Recommended permissions (Claude Code)\n\nAllow lookups, ask for everything that can change state. Put this in your user settings (`~/.claude/settings.json`) or a trusted project\'s `.claude/settings.json` (headless runs ignore the settings file of a directory that was never trusted):\n\n```json\n{\n "permissions": {\n "allow": ["Bash(hgi call *)", "Bash(hgi tools list *)", "Bash(hgi auth whoami)"],\n "ask": ["Bash(hgi run *)"]\n }\n}\n```\n\n## Usage\n\n```bash\nhgi tools list --json # what can I call?\nhgi call company_enrich --input \'{"domain":"acme.com"}\' # lookup, JSON on stdout\nhgi call search_companies --input \'{"query":"saas"}\' --select name,domain -f csv\nhgi call <tool> --input \'{"limit":100}\' --out result.json # big result to a new file\nhgi call <tool> --ids @hg_ids.txt --input \'{...}\' # a whole list: one JSONL row per line\nhgi call <tool> --all-pages --input \'{...}\' # every page of an offset-paged tool, merged\nhgi run <tool> --input \'{...}\' # only after the user approves\n```\n\n- `--input` takes a JSON object. `@file.json` reads a file and `-` reads stdin.\n- Output is JSON when piped and a table on a terminal. Use `-f json|jsonl|csv|yaml|table`.\n- `--select a,b.c` keeps only those fields (dotted paths work through arrays). Prefer it, or `--out <new file>`, for large results; results are never truncated.\n- `--meta` prints `{ "result": ..., "credit_cost": ..., "mcp_version": ... }` on stdout.\n- `--label <stage>` on `call`/`run` tags the call in the local credit ledger (1 to 64 of `A-Z a-z 0-9 . _ : / -`).\n- `hgi usage [--since today|24h|7d|2026-11-01] [--by tool|label|day|call]` shows the credits `hgi` spent on this machine (local only, no sign-in, not the organization\'s bill). `credits` excludes calls with unknown cost (`unknown_cost_calls`); `zero_cost_calls` are cache hits or free tools.\n- A `{"warning":"ledger_not_updated",...}` line on stderr means the call still succeeded; do not re-run it.\n- For more than one company, use `--ids @file` (one HG id or domain per line; `--ids -` for stdin; `--ids-column <name>` for a CSV; `--batch-size <n>` to send fewer per call than the tool\'s limit) instead of looping. hgi batches by the tool\'s limit, sends batches one at a time, and prints `{"input", "result"}` or `{"input", "error"}` rows as JSONL in input order. Exit 3 means a batch failed (its rows carry the error, the rest are fine); any other non-zero exit stopped the run, and `details.rows_emitted` / `calls_made` say how far it got: keep the rows already printed and resume from there.\n\n### Paging (`--all-pages`)\n\nFor every row of an offset-paged tool, use `hgi call <tool> --all-pages` instead of an `offset` loop. hgi pages only tools whose schemas show it is safe (an integer `offset` input and a rows array with `has_more` or a total); anything else is refused with exit 2 `not_pageable`, nothing sent. Don\'t pass `offset` yourself.\n\n- **Each extra page is a separate, billed call.** For batch tools (`hg_ids`/`domains`), follow-ups go one call per unfinished company.\n- It stops on `has_more: false`, an empty or short page, or the total reached, never on `has_more: true` alone (the server can say `true` after the last row). `--max-pages <n>` caps pages per page object (default 10, page 1 included).\n- The result keeps the server\'s shape. Each page object (the result, or each `companies[]` entry) gets `pages_fetched`; one cut short says `truncated: true` and `truncated_reason`: `max_pages`, `unmatched` (a batch entry hgi could not tie to one input, so it never guesses) or the code of the call that failed. Report truncated parts as incomplete.\n- One credit line at the end with the sum. `--meta` adds `pages_fetched` (pages requested), `retries` (re-sends) and `calls_without_cost`.\n- Not with `--ids` (exit 2 `all_pages_with_ids`): page one company list at a time.\n\n## Recipes\n\nThese recipes name tools as examples. Before each one:\n\n- **Confirm the tools.** Check every tool a recipe names in `hgi tools list --json`. If one is missing, skip that step and tell the user which tool is unavailable; never substitute a guess.\n- **Take the batch size from the schema.** Read `maxItems` on `hg_ids` or `domains`, and the maximum of `limit`, `max_results` and `offset`, in the tool\'s `input_schema`. Don\'t hard-code them.\n- **Keep batches stable.** The server caches identical inputs for 30 days (7 for search), and a cached call costs nothing (observed). Sort ids and keep the same batches, so a re-run is free. Changing one id in a batch makes the whole batch a new input.\n- **Missing is not zero.** No installs, no intent, or a company left out of a batch response means unknown, not zero. Record it as unknown; don\'t score the account down.\n- **Show a plan first** for more than one batch (Rule 7).\n- Batching is manual for now: sorted id batches, as below. Paging is `--all-pages` where the tool allows it (`not_pageable` otherwise).\n\n### Match an account list\n\n**Tools:** `search_companies`, `company_firmographic`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_firmographic`\'s `input_schema`.\n**Order:**\n\n1. `search_companies` per account: the name, the HQ country and a revenue floor (USD), `limit` small. It returns only `hg_id`, `name`, `domain`, `domain_normalized`.\n2. Collect the candidate `hg_id`s, sort them, and confirm them with `company_firmographic` in batches of `hg_ids`: name, `country_code`, `employees_total`, `revenue_total`, `company_level`.\n3. Keep the row whose country and size fit. Don\'t roll up to the global HQ or corporate parent blindly: HG lists Legrand Lebanon as Legrand\'s global HQ, and the French state as EDF\'s parent. Use `company_level` and the parent fields only after a sanity check.\n\n```bash\nhgi call search_companies --input \'{"company_identifiers":{"name":"Accor"},"firmographics":{"country_codes":[{"ids":["FR"],"inclusion_method":"ANY_PRESENT"}],"revenue":{"min":1000000000}},"limit":5}\'\nhgi call company_firmographic --input \'{"hg_ids":["<id1>","<id2>"]}\' --select companies.company_id,companies.firmographics.name,companies.firmographics.country_code,companies.firmographics.company_level\n```\n\n### Score fit and propensity\n\n**Tools:** `company_technographic`, `company_intent`, `list_intent_topics`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_technographic`\'s `input_schema`, and the maximum of `max_results` and `offset`. `company_intent` takes one company per call.\n**Order:**\n\n1. **Fit:** `company_technographic` on a batch of `hg_ids`, filtered (`vendor_names`, `product_names` or `category_ids`) so pages stay small, with `--all-pages` (above). It pages each company on its own and stops on a short page or `total_installs_count`, not on `has_more` alone (it can be wrong at page boundaries). A company with `truncated: true` is partial: say so, and narrow the filter rather than raising `--max-pages`.\n2. **Topics:** resolve curated topic names to ids with `list_intent_topics`.\n3. **Intent:** `company_intent` on the company\'s web domain (`company_domain`), not only its HQ id: intent is observed on web domains. In one run, Accor had 0 topics on its HQ id and 18 on `accor.com` (observed; counts change over time). Check `company.id` and `company.name` in the response: a domain can resolve to a subsidiary.\n4. **Baseline:** large companies are active on about 70% of the ~20,000-topic catalogue (observed), so a raw topic count measures size, not interest. Compare the curated topics (`topic_ids`) with the company\'s own unfiltered summary. A summary with `topic_ids` counts only those topics. `fields:["summary"]` without a topic filter rejects `granularity` (422). When you request `fields:["topics"]`, pass `granularity:"global"`: the default is one row per state, which counts a topic several times.\n\n```bash\n# every install per company, paged safely; max_results up to the schema\'s maximum keeps the call count down\nhgi call company_technographic --all-pages --max-pages 5 \\\n --input \'{"hg_ids":["<id1>","<id2>"],"vendor_names":["<vendor>"],"max_results":<schema maximum>}\' -f json > tech.json\n# exit 0 with truncated companies = capped; non-zero with details.partial_result = stopped early, tech.json still holds what was paid for\nhgi call company_intent --input \'{"company_domain":"accor.com"}\'\nhgi call company_intent --input \'{"company_domain":"accor.com","fields":["summary"],"topic_ids":["<topic id>"]}\'\n```\n\n### Size wallet from spend\n\n**Tools:** `company_spend`, `get_product_category`. Confirm them in `hgi tools list --json`; if one is missing, skip that step and tell the user which tool is unavailable.\n**Batch:** read `maxItems` on `hg_ids` in `company_spend`\'s `input_schema`, and the maximum of `max_results`.\n**Order:**\n\n1. Use the `hg_id`s from the matching recipe, sorted.\n2. To size one area, resolve its category ids first with `get_product_category`, as `company_spend`\'s description says. Don\'t pass guessed `category_names`: a name that matches nothing returns 0 rows without an error.\n3. One `company_spend` call per batch of `hg_ids`, with `category_ids` set in that same call, not filtered afterwards.\n4. `company_spend` is not pageable with `--all-pages` (its per-company spend has no rows array). Page with `max_results` and `offset` by hand only when `all_count` exceeds the rows returned; stop on a short page or once `all_count` is reached, never on a has-more flag alone.\n5. Rows are per country, and categories form a tree through `category_parent_id` (Total IT \u2192 Total External IT \u2192 Software, \u2026). Sum across countries, never a parent with its children.\n\n```bash\nhgi call company_spend --input \'{"hg_ids":["<id1>","<id2>"],"category_ids":["<category id>"]}\' --select companies.company_id,companies.spend.all\n```\n\n## Data semantics\n\nVerified with one live call per tool. "Scope" is what a call returns by default.\n\n| Tool | Default scope | Nullable fields (what null means) |\n|---|---|---|\n| `search_companies` | global: all countries unless `country_codes` filters the HQ country | no field came back null in the verification call; treat a missing field as unknown |\n| `company_firmographic` | country: one record per entity, in its own `country_code` | `corporate_parent_id`, `corporate_parent_name`, `parent_id`, `domestic_parent_id`, `domestic_parent_name`: none (no parent above it); `fortune_500_rank`, `forbes_2000_rank`: unknown |\n| `company_technographic` | global: default rows have `country_code: null`; `granularity` or `country_codes` give per-country rows | `country_code`: a global or unattributed row, not missing data; `product_category_level4_name`, `product_category_level5_name`: none (the category tree is shallower) |\n| `company_intent` | global: `summary` only, for the resolved entity across all geographies; with `fields:["topics"]`, one row per state unless `granularity:"global"` | no field came back null in the verification call; treat a missing field as unknown |\n| `company_spend` | country: every row has a `country_code` | no field came back null in the verification call; treat a missing field as unknown |\n\nNot null, but easy to misread:\n\n- A batch response leaves out companies it didn\'t match. A left-out company is unknown, not zero.\n- `company_domain` is `""` when you query by `hg_ids`.\n- `company_intent` on a domain answers for whichever company the domain resolves to: `accor.com` resolved to an Accor subsidiary in Australia, not the group HQ.\n\n**HG ids** are hex strings, normally 32 characters and uppercase in responses. An id can come back with its leading zero dropped, as 31 characters: seen on a spend `category_id`, and on company ids (observed). The `hg_ids` inputs accept 31 or 32 characters. Upper-case ids and left-pad them to 32 with `0` before comparing or joining.\n\n## Exit codes\n\n**If an error from `hgi run` has `details.outcome_unknown: true`, whatever its exit code (1, 7 or 9), the work may already have started and been billed. Check state first; never just retry.**\n\n| Code | Meaning | What to do |\n|---|---|---|\n| 0 | success | |\n| 1 | internal error in hgi | report it; check state before re-running a `run` (see `outcome_unknown`) |\n| 2 | invalid input or usage | fix the input; the JSON error lists the problem fields |\n| 3 | the tool reported an error | read the message; do not blindly retry |\n| 4 | not signed in, or login expired | ask the user to run `hgi auth login` |\n| 4 `phoenix_account_required` | the signed-in identity has no Phoenix account | stop; tell the user to sign up, or to sign in with `hgi auth login` as an account that has one |\n| 5 | rate limited (after hgi\'s own retries) | wait `retry_after_seconds` from the error, then retry. For a long batch of lookups, pass `--retries 6` instead of writing your own retry loop |\n| 6 | out of credits: `credit_limit_exceeded` (the organization) or `user_credit_limit_exceeded` (the user\'s personal budget) | stop; tell the user which one, and to ask an admin. Retrying will not help |\n| 7 | server unreachable | retry later. If `outcome_unknown` is `true`, check state before re-running a `run` |\n| 7 `governance_unavailable` | the server could not check the budget; nothing ran (`retryable: true`) | wait a little, then retry once. `hgi call --retries <n>` retries it itself; `hgi run` never does |\n| 8 | OAuth or sign-in failure | ask the user to run `hgi auth login` again |\n| 9 | proxy or TLS problem | the error names the cause (see `NODE_EXTRA_CA_CERTS`, `HTTPS_PROXY`). After a `run`, check `outcome_unknown` before retrying |\n| 10 | wrong verb | use the verb the error names |\n| 11 | forbidden, or `tool_not_enabled_for_team` | the account, organization or team lacks access to this tool; stop and tell the user to ask an admin |\n| 12 | local credential or file problem | follow the hint. If `details.tool_ran` is `true`, the tool already ran and its result is on stdout: do not re-run it |\n| any, with `details.partial_result: true` | `--all-pages` stopped on a later page; the pages fetched so far are on stdout (or `--out`), unfinished parts marked `truncated` | keep them, they were billed; then act on the code as its own row says. Don\'t re-fetch pages you already have |\n| 13 `budget_exceeded` | the run spent its `--max-credits` cap; nothing more was sent (with `--ids`, keep the rows already printed) | stop; tell the user what was spent (`details.spent` of `details.max`). Only the user raises the cap or runs `hgi budget reset` |\n\nErrors are JSON on stderr when it is not a terminal: `{"schema":1,"error":{"code","exit_code","message","hint","details"}}`. Branch on `error.code`, not on the message.\n\n## Run cap\n\nWhen the user gives a credit limit for a task, pass it as `hgi call --max-credits <n>` (or set `HGI_MAX_CREDITS`). It counts every `hgi call` in one budget; `hgi run` is not counted. **Run `export HGI_BUDGET_ID=<something unique to the task>` once first:** agent harnesses usually start a fresh shell per command, and the default budget (the parent process) would then give every call its own empty budget. The cap is client-side, on top of the server\'s limits, and can overshoot by the calls running at the same time. `hgi budget status` shows what the task has spent.\n';
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';
4086
4219
 
4087
4220
  // src/commands/skill.ts
4088
4221
  function defaultSkillsDir() {