@hginsights/hgi 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,23 +6,24 @@ Every failure has its own exit code, so a script can branch without parsing Engl
6
6
  |---|---|---|
7
7
  | 0 | | success |
8
8
  | 1 | `internal_error` | a bug in `hgi`. Never used for a server response or a usage error |
9
- | 2 | `invalid_input` | bad flags or usage; invalid JSON; input that fails the tool's schema; unknown tool; unreadable `--input @file`; `--out` refusals (exists, symlink, protected path, `--force` on `call`); config-dir workspace guard |
10
- | 3 | `tool_error` | the tool returned `isError` (including server-side invalid arguments, which the server reports in-band), a JSON-RPC error, or a response `hgi` could not parse after the call was sent |
11
- | 4 | `login_required`, `login_expired` | no credentials; a second 401 after one refresh; the refresh token was rejected (`invalid_grant`) |
12
- | 5 | `rate_limited` | 429 after bounded retries (MCP calls); a 429 from the userinfo or revoke endpoint exits at once |
13
- | 6 | `credit_limit_exceeded` | `_meta.errorCode === "credit_limit_exceeded"` on a tool result |
14
- | 7 | `server_unreachable` | DNS failure, refused connection, timeout, HTTP 5xx, an unexpected redirect from the MCP endpoint, the server shedding load after retries, or the server choosing an MCP protocol version this `hgi` does not speak (`details.reason` is `unsupported_protocol_version`; upgrade `hgi`) |
9
+ | 2 | `invalid_input` | bad flags or usage; invalid JSON; input that fails the tool's schema; unknown tool; unreadable `--input @file` or `--ids @file`; `--out` refusals (exists, symlink, protected path, `--force` on `call`); config-dir or `HGI_LEDGER` workspace guard (`workspace_guard`); a bad `--label` (`bad_label`), `hgi usage --since` (`bad_since`) or `--by` (`bad_by`); any `--ids` refusal (see [below](#partial-output-from---ids)); any `--all-pages` refusal, `not_pageable` among them (see [below](#partial-output-from---all-pages)). Nothing is sent |
10
+ | 3 | `tool_error` | the tool returned `isError` (including server-side invalid arguments, which the server reports in-band), a JSON-RPC error, or a response `hgi` could not parse after the call was sent. With `--ids`: at least one batch call failed (every row is printed first) |
11
+ | 4 | `login_required`, `login_expired`, `phoenix_account_required` | no credentials; a second 401 after one refresh; the refresh token was rejected (`invalid_grant`). `phoenix_account_required`: the server says the signed-in identity has no Phoenix account; sign up, or sign in with `hgi auth login` as an account that has one |
12
+ | 5 | `rate_limited` | 429 after bounded retries (MCP calls: 3 by default, `--retries` to change; see [Retries](#retries)), or a `Retry-After` longer than what is left of the retry budget; `details.attempts` says how many times the request was sent. A 429 from the userinfo or revoke endpoint exits at once |
13
+ | 6 | `credit_limit_exceeded`, `user_credit_limit_exceeded` | the server refused the call: your organization's credit allowance (`credit_limit_exceeded`) or your personal credit budget (`user_credit_limit_exceeded`) is used up. Retrying will not help; ask an admin, or wait for the next billing period |
14
+ | 7 | `server_unreachable`, `governance_unavailable` | `governance_unavailable`: the server could not check your budget, so nothing ran (`details.retryable: true`, `details.outcome_unknown: false`); retry shortly. `hgi call --retries <n>` re-sends it up to n times itself (then `details.attempts` is set); without `--retries`, and always on `hgi run`, it is not retried. `server_unreachable`: DNS failure, refused connection, timeout, HTTP 5xx, an unexpected redirect from the MCP endpoint, the server shedding load after retries (`details.attempts`), or the server choosing an MCP protocol version this `hgi` does not speak (`details.reason` is `unsupported_protocol_version`; upgrade `hgi`) |
15
15
  | 8 | `oauth_error` | discovery or issuer mismatch, state or redirect mismatch, consent denied, a rejected or reused sign-in code, a token-endpoint failure, an unexpected redirect on an auth request |
16
16
  | 9 | `network_proxy_tls` | TLS verification failure or proxy failure; the message names the cause (for example `DEPTH_ZERO_SELF_SIGNED_CERT`) |
17
17
  | 10 | `wrong_verb` | `hgi call` on a state-changing tool, or `hgi run` on a read-only one. Nothing is sent |
18
- | 11 | `forbidden` | HTTP 403 |
19
- | 12 | `local_state_error` | corrupt or unsafe-mode credentials file (`details.kind` is `credentials_corrupt` or `credentials_unsafe`), lock timeout, or a failed local write. If `details.tool_ran` is `true` (an `--out` write failed *after* the tool ran), the tool already ran and was billed, its result was printed to stdout instead, and you must **not** re-run it |
18
+ | 11 | `forbidden`, `tool_not_enabled_for_team` | HTTP 403; or the server says this tool is not enabled for your team (ask an admin) |
19
+ | 12 | `local_state_error` | corrupt or unsafe-mode credentials file (`details.kind` is `credentials_corrupt` or `credentials_unsafe`), lock timeout, or a failed local write; `hgi usage` on a credit ledger that is a symlink or not a regular file (`details.kind: "ledger_unsafe"`) or cannot be read (`details.kind: "read_failed"`, `details.reason` is the error code). If `details.tool_ran` is `true` (an `--out` write failed *after* the tool ran), the tool already ran and was billed, its result was printed to stdout instead, and you must **not** re-run it. Budget files ([Run cap](#run-cap)): `budget_corrupt` (a budget file, or its directory, is unreadable, malformed or unsafe; nothing was sent) and `budget_write_failed` (the spend could not be recorded; after a successful call, `details.tool_ran` is `true` and the result is on stdout, even with `--out`) |
20
+ | 13 | `budget_exceeded` | `hgi call` with a run cap (`--max-credits`, `HGI_MAX_CREDITS`) when the run has already spent its cap. Nothing was sent. `details`: `spent`, `max`, `budget_id`. Raise the cap or run `hgi budget reset` |
20
21
 
21
22
  `hgi --help` and `hgi --version` exit 0.
22
23
 
23
24
  ## The error body
24
25
 
25
- When stderr is not a terminal (or you pass `--json-errors`), errors are one JSON object on stderr and nothing on stdout (the one exception: exit 12 with `details.tool_ran: true`, where the tool already ran and its result is printed on stdout):
26
+ When stderr is not a terminal (or you pass `--json-errors`), errors are one JSON object on stderr and nothing on stdout. There are three exceptions: exit 12 with `details.tool_ran: true`, where the tool already ran and its result is printed on stdout; `hgi call --ids`, where the rows printed before the error stay on stdout ([below](#partial-output-from---ids)); and `hgi call --all-pages` with `details.partial_result: true`, where a later page failed and the merged result of the pages before it is printed where a full result would go, stdout or `--out` ([below](#partial-output-from---all-pages)):
26
27
 
27
28
  ```json
28
29
  {"schema":1,"error":{"code":"credit_limit_exceeded","exit_code":6,"message":"...","hint":"...","details":{"tool":"company_enrich"}}}
@@ -32,18 +33,111 @@ When stderr is not a terminal (or you pass `--json-errors`), errors are one JSON
32
33
  - `code` and `exit_code` are stable. `message` and `hint` are for humans.
33
34
  - `details` carries machine-readable context where it exists:
34
35
  - `retry_after_seconds` on `rate_limited`
36
+ - `attempts` when retries ran out (`rate_limited`, an exhausted load-shed or refused connection, `governance_unavailable` on `hgi call --retries`): how many times the failing request was sent, 1 + its retries
35
37
  - `outcome_unknown` on `tools/call` failures (see below)
36
38
  - `expected_verb` on `wrong_verb`
37
- - `reason` on `invalid_input` and `oauth_error` (for example `unknown_tool`, `schema`, `state_mismatch`)
39
+ - `reason` on `invalid_input` and `oauth_error` (for example `unknown_tool`, `schema`, `state_mismatch`, `bad_retries`, `bad_retry_budget`)
38
40
  - `cause` on `server_unreachable` and `network_proxy_tls` (a Node error code)
39
41
  - `location_host` on an unexpected redirect
42
+ - `tool` and `server_error_code` on every error from a tool result (`server_error_code` is the server's raw `_meta.errorCode`, when it sent one; an unknown one stays `tool_error`)
43
+ - `retryable` on `governance_unavailable`: nothing ran, and retrying later is safe
44
+ - `budget_write_failed: true` on a server refusal (exit 3, 4, 6, 7 or 11) whose spend could not be recorded under a run cap; the refusal is still the error to act on
45
+ - `spent`, `max` and `budget_id` on `budget_exceeded`
46
+ - `partial_result: true` and `pages_fetched` (the pages requested, the failed one included; a re-sent page counts once) when `--all-pages` stopped after page 1; `out_write_failed: true` when the partial result could not be written to `--out` and went to stdout instead
47
+ - `kind` on `local_state_error`: `credentials_corrupt`, `credentials_unsafe`, `lock_timeout`, `lock_compromised`, `write_failed`, `budget_corrupt`, `budget_write_failed`, `ledger_unsafe` or `read_failed`; with `tool_ran` when the tool already ran
40
48
 
41
49
  On a terminal, errors are plain text with a hint.
42
50
 
51
+ ## Partial output from `--ids`
52
+
53
+ `hgi call --ids` sends one call per batch, one at a time, and prints rows as batches return. How a run ends:
54
+
55
+ - **0**: every batch call succeeded, even if some rows are `not_found`.
56
+ - **3**: every row was printed, but at least one batch call failed (`isError`, a JSON-RPC error, an unparseable response, or a response with nothing to match against). Those rows carry the error; the run went on with the next batch. `details` has `failed_batches` (how many), `rows_emitted` and `calls_made`.
57
+ - **Any other code stops the run at once** (out of credits, sign-in expired, rate limited, unreachable, proxy/TLS, forbidden, a failure with `outcome_unknown: true`, and any later client-side stop): no further batch is sent and nothing is retried. The rows already printed stay on stdout (for `-f json|csv|yaml|table` and `--out`, the rows so far are written before the error). `details` adds `rows_emitted` (rows printed, in input order) and `calls_made` (`tools/call` requests attempted, including the one that failed), so you know where to resume. If `--out` cannot be written at that point, the rows go to stdout instead and `details.out_write_failed` is `true`; the exit code is still the original one.
58
+ - **12 with `details.tool_ran: true`**: every call ran, but `--out` could not be written at the end; the rows are on stdout. Do not re-run.
59
+
60
+ Exit 2 refusals specific to `--ids`, each before anything is sent (`details.reason`):
61
+
62
+ | `reason` | When |
63
+ |---|---|
64
+ | `no_ids` | no ids left after skipping blank lines and `#` comments (or empty CSV cells) |
65
+ | `bad_batch_size` | `--batch-size` is zero, not a whole number, or above the limit of a field the input uses (`details.field`, `details.max`) |
66
+ | `unknown_column` | `--ids-column` names a column the CSV header does not have (`details.columns`) |
67
+ | `bad_csv` | the `--ids-column` file has a quoted field that is never closed |
68
+ | `ids_column_without_ids`, `batch_size_without_ids` | `--ids-column` or `--batch-size` without `--ids` |
69
+ | `bad_ids_source` | `--ids` is not `@file` or `-` |
70
+ | `stdin_conflict` | `--ids -` together with `--input -` |
71
+ | `ids_conflict` | `--input` already has `hg_ids` or `domains` (`details.field`) |
72
+ | `unsupported_kind` | a line is a domain (or an HG id) and the tool's input schema has no `domains` (or `hg_ids`) array (`details.line`) |
73
+ | `unusable_max_items` | the tool declares a `maxItems` that is not a positive whole number, so it cannot be batched safely |
74
+ | `schema` | a batch fails the tool's input schema; `details.batch` says which. Every batch is checked before the first is sent |
75
+
76
+ ## Partial output from `--all-pages`
77
+
78
+ `hgi call --all-pages` fetches pages one at a time and prints one merged result ([output formats](output-formats.md#hgi-call---all-pages)). How a run ends:
79
+
80
+ - **0**: paging finished. Parts that stopped at `--max-pages` or could not be tied to one input are marked `truncated: true` (`truncated_reason` `max_pages` or `unmatched`); that is not an error.
81
+ - **A failure on page 1** is exactly the failure of `hgi call` without `--all-pages`: nothing on stdout.
82
+ - **A failure on any later page** (tool error, out of credits, rate limited or `governance_unavailable` after its retries, unreachable, the run cap, a follow-up that fails the input schema, any code) stops all paging; nothing is retried. The merged result of the pages so far is written where a full result would go (stdout, or `--out`; if `--out` fails it goes to stdout and `details.out_write_failed` is `true`), with every part that did not finish marked `truncated: true, truncated_reason: "<error.code>"`. `hgi` then exits with the failing call's own code, and `details` adds `partial_result: true` and `pages_fetched`. Keep what was printed: it was billed.
83
+ - A later page that is not an object, or has no rows array where the schema says one is, is exit 3 `tool_error` with `details.reason: "unexpected_response"`, handled as above.
84
+ - **12 `budget_write_failed` with `details.tool_ran: true`**: a page ran but its spend could not be recorded under a run cap. On page 1 this is exactly the single-call case (page 1 on stdout, no paging fields). On a later page, paging stops and the merged result so far is on stdout (even with `--out`), with `partial_result` and `pages_fetched`. Do not re-run it.
85
+
86
+ Exit 2 refusals specific to `--all-pages`, each before anything is sent (`details.reason`):
87
+
88
+ | `reason` | When |
89
+ |---|---|
90
+ | `not_pageable` | the tool's schemas don't show it can be paged safely: no integer `offset` input, or no output object with exactly one rows array plus `has_more`/`hasMore` or a total (`details.tool`) |
91
+ | `max_pages_without_all_pages` | `--max-pages` without `--all-pages` |
92
+ | `bad_max_pages` | `--max-pages` is not a whole number of at least 1 |
93
+ | `offset_with_all_pages` | `--input` already has `offset`; `--all-pages` sets it |
94
+ | `all_pages_with_ids` | `--all-pages` together with `--ids` |
95
+
43
96
  ## `outcome_unknown`
44
97
 
45
98
  `hgi` retries only failures that happen **before the server runs the tool**: a 401 (after a refresh), a 429, the server's 503 "shedding load" response, and a refused or unresolvable connection. If a connection drops, times out, a proxy resets it, or a 5xx arrives **after** a `tools/call` was sent, it is not retried, because `hgi run` could start the work twice. The error then has `"outcome_unknown": true` and a hint to check state first. This marker is added to every network-class or unclassified failure once the call was sent, so it can appear with exit 1, 7 or 9. An exhausted load-shed retry has `"outcome_unknown": false`: nothing ran and retrying is safe.
46
99
 
100
+ A failure with `"outcome_unknown": true` is never retried, whatever `--retries` says. Neither is a TLS or proxy failure (exit 9: waiting does not fix it) or any exit 2, 3, 4, 6, 8, 10, 11, 12 or 13.
101
+
102
+ ### Retries
103
+
104
+ What `hgi call` and `hgi run` retry, all before the tool runs:
105
+
106
+ | `code` in the retry line | What | Default limit | Wait |
107
+ |---|---|---|---|
108
+ | `rate_limited` | a 429 | 3, shared with `load_shed` | `Retry-After`, else 2, 4, 8 … s (at most 30) plus up to 1 s |
109
+ | `load_shed` | the server's 503 "shedding load" (503 + `Retry-After` + JSON-RPC `-32000`) | 3, shared with `rate_limited` | `Retry-After` |
110
+ | `not_established` | a connection that was refused or did not resolve before the request left; on requests other than `tools/call`, also other network failures and 502/503/504 | 2 | 0.5 s × attempt |
111
+ | `governance_unavailable` | the server could not check the budget (an in-band refusal raised before the tool runs) | not retried | full jitter: random in `[0, min(2^attempt, 30)]` s |
112
+
113
+ `rate_limited` and `load_shed` waits get up to 0.25 s of extra jitter, which the budget check does not count. Every wait is bounded by a **retry budget per request** (each `--ids` batch call is its own request): a wait longer than what is left of it ends the retries at once with the final error. The 401 → refresh → retry-once path is separate and is not counted.
114
+
115
+ - `--retries <n>` (or `HGI_RETRIES`; the flag wins), a whole number 0–20: each class above may retry up to n times, each on its own counter. `0` turns every retry off, built-in ones included. On `hgi call` it also re-sends `governance_unavailable` up to n times; `hgi run` never does (exit 7, `retryable: true`, and you decide).
116
+ - `--retry-budget <seconds>` (or `HGI_RETRY_BUDGET`; the flag wins), a positive number up to 3600: the per-request budget. Default 600 when retries are set, else 60. Without `--retries` it raises the budget and keeps the built-in counts.
117
+ - A bad value exits 2 `invalid_input` (`details.reason` `bad_retries` or `bad_retry_budget`) before credentials are read or anything is sent.
118
+ - `--timeout` bounds each attempt, not the waits between them.
119
+ - Each `governance_unavailable` attempt that came back is recorded like a single call: one credit-ledger row (`status: "tool_error"`) and, under a [run cap](#run-cap), its reported cost. The cap is checked again right before every re-send; when it is reached, the re-send is not sent and the command exits 13. Refused attempts are not billed, so `credit_cost` is the last attempt's.
120
+ - Every retry prints one line on stderr before its wait ([output formats](output-formats.md#retry-lines)).
121
+
122
+ `governance_unavailable` is the one in-band refusal `hgi` re-sends, because the server raises it before the tool runs (see `CONTRIBUTING.md` → Ground rules), and only on the read-only verb.
123
+
47
124
  ## Credit cost
48
125
 
49
126
  Success prints the tool result on stdout and the credit cost on stderr (`credit_cost: 3`, or `{"credit_cost":3}` when stderr is not a terminal). Tools that do not report a cost (external, aggregated tools) show `unknown` / `null`, never `0`.
127
+
128
+ ## Run cap
129
+
130
+ `hgi call --max-credits <n>` (or `HGI_MAX_CREDITS=<n>`; the flag wins) caps what one run may spend. A run is every `hgi call` that shares a budget id: `HGI_BUDGET_ID` when set, otherwise the parent process id, so every `hgi` started from one shell or script counts together. `<n>` is a whole number of credits; `0` refuses every call, which proves a run is free.
131
+
132
+ - The cap is **client-side only, on top of the server's limits**. The organization and personal limits still apply, and are enforced by the server.
133
+ - It covers `hgi call` only. `hgi run` has no `--max-credits`, ignores `HGI_MAX_CREDITS`, and is neither checked nor counted.
134
+ - Before each capped call, `hgi` refuses with exit 13 when the budget has already spent its cap, and sends nothing. After the call, it adds the cost the server reported (`_meta.creditCost`), for error results too. A tool that reports no cost counts as 0 and is counted in `unknown_cost_calls`.
135
+ - With `--all-pages`, every page is a capped call: checked before it is sent and counted after it. When the cap is reached partway, the next page is not sent, the pages so far are printed, and `hgi` exits 13 with `details.partial_result: true` ([above](#partial-output-from---all-pages)).
136
+ - With `--ids`, every batch call is a capped call: checked before it is sent and counted after it. When the cap is reached partway, the run stops with exit 13 and the rows so far stay printed, with `rows_emitted` and `calls_made` as in [Partial output from `--ids`](#partial-output-from---ids). When a batch's spend cannot be recorded, its rows are printed first (to `--out` when given), then the run stops with exit 12 `budget_write_failed` and `details.tool_ran: true`.
137
+ - The server gives no price before a call, so a run can overshoot its cap by the calls running at the same time: one call when calls run one after another, more when they run in parallel.
138
+ - Spend is recorded only when a cap is set. It lives in `~/.config/hgi/budgets/` (see [security](security.md)); a file not updated for 7 days is deleted on the next budget write.
139
+ - `hgi budget status [--max-credits <n>]` prints `{budget_id, spent, max, remaining, calls, unknown_cost_calls}`; `hgi budget reset` starts the count over. Neither needs a sign-in or sends anything.
140
+
141
+ ## Credit ledger
142
+
143
+ A credit ledger problem during `hgi call` or `hgi run` (the lock timed out, the ledger path is a symlink or not a regular file, the write failed) is a warning, never an exit code: the tool already ran and was billed, and a failure would invite a billed re-run. Stdout and the exit code are exactly what they would otherwise be, and stderr gets one line, `hgi: warning: credit ledger not updated: <reason>` on a terminal or `{"warning":"ledger_not_updated","reason":"<reason>"}` when stderr is JSON. The one exception is an `HGI_LEDGER` path inside a git working tree, refused with exit 2 (`workspace_guard`) before anything is sent.
@@ -39,10 +39,80 @@ Results are never truncated. A large result prints complete in every format. Use
39
39
  `--meta` replaces the bare result on stdout with an envelope:
40
40
 
41
41
  ```json
42
- {"result": {...}, "credit_cost": 2, "mcp_version": "v2"}
42
+ {"result": {...}, "credit_cost": 2, "mcp_version": "v2", "attempts": 1}
43
43
  ```
44
44
 
45
- `--select` trims the `result` inside the envelope, so `--meta --select name` gives `{"result": {"name": ...}, "credit_cost": ..., "mcp_version": ...}`.
45
+ `attempts` is how many times the `tools/call` was sent: 1, plus every [retry](exit-codes.md#retries) of it. `--select` trims the `result` inside the envelope, so `--meta --select name` gives `{"result": {"name": ...}, "credit_cost": ..., "mcp_version": ..., "attempts": ...}`.
46
+
47
+ ## Retry lines
48
+
49
+ Every retry writes one line on stderr before its wait, with or without `--retries`. On a terminal:
50
+
51
+ ```
52
+ hgi: retry 2/6: rate_limited, waiting 12s
53
+ ```
54
+
55
+ Otherwise (stderr not a terminal, or `--json-errors`), the same as one JSON object:
56
+
57
+ ```json
58
+ {"retry":{"attempt":2,"max":6,"code":"rate_limited","wait_seconds":12}}
59
+ ```
60
+
61
+ `code` is `rate_limited`, `load_shed`, `not_established` or `governance_unavailable`. `max` is that class's limit (`--retries`, else the built-in 3 or 2). `wait_seconds` is the wait that follows, a number rounded to one decimal place. The lines go to stderr only, so stdout stays the result.
62
+
63
+ ## `hgi call --ids` (batches)
64
+
65
+ With `--ids`, `hgi call` prints **one row per input line, in input order**, instead of one result:
66
+
67
+ ```json
68
+ {"input": "0a1b2c...", "result": {"company_id": "a1b2c...", "...": "..."}}
69
+ {"input": "example.com", "error": {"code": "not_found", "message": "No company for this domain in the response."}}
70
+ ```
71
+
72
+ - `input` is the line as you wrote it (trimmed). A duplicate line repeats its row at each position.
73
+ - `result` is the matching entry from the tool's response: the response's single top-level array-of-objects property named by the tool's output schema, else its `companies` array. Id inputs match an entry's `company_id`, else `requested_hg_id`, else `organization_id`, compared lowercased with leading zeros removed. Domain inputs match `company_domain`, compared lowercased without scheme, leading `www.` or path.
74
+ - `error.code` is `not_found` (the server left the input out), `unexpected_response` (the response has no array to match against), or the code of the failed batch call (for example `tool_error`). Error messages are redacted like every other `hgi` error.
75
+ - **The default format is JSONL, on a terminal or not.** JSONL rows stream as each batch returns. `-f json` prints one array of rows; `-f csv|yaml|table` format the list of rows. Those, and `--out`, are written once when the run ends (or, on a fatal stop, with the rows so far).
76
+ - `--select` trims each row's `result`; `input` and `error` are always kept.
77
+ - **`--meta` does not wrap stdout** with `--ids`. stdout stays pure rows, and `--meta` adds one summary object on stderr at the end: `{"calls", "retries", "rows", "row_errors", "credit_cost", "calls_without_cost"}`. `calls` counts batch calls, one per batch however many times it was sent; `retries` is the total of re-sends across them. `credit_cost` sums the costs the calls reported (for a re-sent batch, its last attempt's); `calls_without_cost` counts calls that reported none, so the sum is a lower bound.
78
+ - The credit line on stderr is printed once, with the total, at the end (and before a fatal error).
79
+ - On a terminal, progress (`hgi: batch 3/40`) goes to stderr. It is never printed when stderr is not a terminal.
80
+
81
+ ## `hgi call --all-pages`
82
+
83
+ `--all-pages` fetches every page of an offset-paged tool, one call at a time, and prints **one merged result in the server's shape**, as if the server had returned every row at once. `--max-pages <n>` caps the pages per page object (default 10, page 1 included). **Each extra page is a separate, billed call.**
84
+
85
+ Which tools can be paged is read from the tool's schemas, never its name:
86
+
87
+ - the input schema has an `offset` property of type `integer`;
88
+ - the output has **page objects**: the result itself if it qualifies, otherwise each item of its one top-level array whose items qualify (`companies[]` on batch tools). A page object has exactly one array-of-objects property (its rows), plus `has_more` or `hasMore`, a total, or both;
89
+ - the **total** is a numeric `total`, `total_count` or `totalCount`; otherwise the one numeric `total_*` property whose `_`-separated name has the rows property's name as a whole segment (`installs` → `total_installs_count`). None, or more than one, means no total. `count` is never a total;
90
+ - the **page size** is the `limit` or `max_results` value in `--input`, else that property's schema `default`, else unknown. A tool declaring both has no known page size.
91
+
92
+ Anything else is refused before anything is sent (exit 2, `details.reason: "not_pageable"`).
93
+
94
+ **Stop rule**, per page object, after each page: stop when `has_more`/`hasMore` is `false`, the page has no rows, the page has fewer rows than a known page size, the rows so far reach the total, or `--max-pages` pages were fetched for it. `has_more: true` alone never keeps paging past a short page, an empty page or the total. Otherwise the next page is the original input plus `offset` = rows so far.
95
+
96
+ **Batch tools.** Page 1 is the call as given. Follow-ups go only for companies that are not finished, because `offset` applies to every company in a call:
97
+
98
+ - with two or more values across `hg_ids` and `domains`, one call per company: the original input with `hg_ids`/`domains` replaced by that company's value as you wrote it (`{"hg_ids": ["<id>"], "offset": n}`), other filters kept. Entries are matched like `--ids` rows: `company_id`, else `requested_hg_id`, else `organization_id` for ids (lowercased, leading zeros removed), `company_domain` for domains (lowercased, no scheme, `www.` or path);
99
+ - otherwise, when page 1 returned exactly one entry (the company the input named, if it named one), the original input plus `offset`; every follow-up must again return exactly that one company;
100
+ - an entry that can't be tied to exactly one input, a page 1 with several entries and nothing to split on, or a follow-up that doesn't return exactly that one company, is not followed up and is marked `unmatched`. hgi never guesses which company a page belongs to.
101
+
102
+ **The merged result.** Rows are appended to each page object's rows array. Its other fields (`has_more`, counts) are those of the last page fetched for it; for batch tools the top level is page 1's. Each page object gains:
103
+
104
+ - `pages_fetched`: the pages that contributed to it;
105
+ - `truncated: true` and `truncated_reason` when it did not finish: `max_pages`, `unmatched`, or the `error.code` of the later page that failed (see [exit codes](exit-codes.md#partial-output-from---all-pages)).
106
+
107
+ `--select`, `-f` and `--out` apply to the merged result, also when a later page failed and a partial result is printed. The credit line on stderr is printed once, with the sum of the reported costs (`null`/`unknown` when no page reported one). With `--meta` the envelope adds `pages_fetched` (the pages requested, the failed one included: one per page however many times it was sent), `retries` (the re-sends across all pages, replacing a single call's `attempts`) and `calls_without_cost` (pages that reported no cost, so `credit_cost`, the sum, is a lower bound; a re-sent page counts its last attempt's cost):
108
+
109
+ ```json
110
+ {"result": {...}, "credit_cost": 6, "mcp_version": "v2", "pages_fetched": 3, "retries": 0, "calls_without_cost": 0}
111
+ ```
112
+
113
+ With `--retries`, each page gets the same retries as a single `hgi call`, `governance_unavailable` re-sends included; a page whose retries run out stops paging like any later-page failure, with `details.attempts`.
114
+
115
+ Without `--all-pages`, `--meta` is unchanged. `--all-pages` is not available with `--ids` or on `hgi run`.
46
116
 
47
117
  ## `hgi tools list`
48
118
 
@@ -50,6 +120,26 @@ Results are never truncated. A large result prints complete in every format. Use
50
120
 
51
121
  On a terminal or with `-f table|csv`, `tools list` prints `name`, `verb`, `required`, `description` (table descriptions are shortened to their first line) and the MCP version on stderr.
52
122
 
123
+ ## `hgi usage`
124
+
125
+ `hgi usage [--since <when>] [--by tool|label|day|call]` reads the local credit ledger (no sign-in, no network) and keeps only rows for the current base URL's host, so staging and production never mix. The JSON value is a top-level array.
126
+
127
+ - `--by tool` (default), `--by label`, `--by day`: one row per key, `{<key>, calls, credits, zero_cost_calls, unknown_cost_calls}`. `credits` sums the reported costs; `zero_cost_calls` counts calls that cost `0` (a server-side cache hit or a free tool); `unknown_cost_calls` counts calls whose cost the server did not report, which are not in `credits`. `tool` and `label` rows are sorted by `credits` descending, then key; `day` rows (`YYYY-MM-DD` in this machine's time zone) by date. Unlabeled calls have `label: null`.
128
+ - `--by call`: the ledger rows themselves, oldest first, with the record keys below. `hgi usage --by call -f csv` is the raw ledger as CSV.
129
+ - `--since`: `2026-11-01`, `2026-11-01T09:00` (local time unless a zone such as `Z` or `+02:00` is given), `today` (local midnight), or `24h` / `7d`. Without it, all history.
130
+
131
+ Stdout carries only data, and credits stay numeric in every machine format. On stderr, every run prints `Local to this machine: calls made by hgi here, not your organization's bill.`, plus a note when nothing has been recorded yet or the ledger is disabled (`HGI_LEDGER=off`; the result is then `[]`), and a warning with the count of malformed lines skipped (a torn last line, hand edits). In `table` format only, a `0` in `credits` reads `0 (server cache or free tool)`, `label: null` reads `(none)`, and a footnote under the table explains `zero_cost_calls` and `unknown_cost_calls`.
132
+
133
+ ### The ledger record
134
+
135
+ The ledger (`~/.config/hgi/ledger.jsonl`, see [security](security.md#the-credit-ledger)) is JSON Lines, one object per tool call that got a result back, keys in this order:
136
+
137
+ ```json
138
+ {"v":1,"ts":"2026-11-04T17:03:12.481Z","host":"phoenix.hginsights.com","verb":"call","tool":"company_firmographic","label":"resolve","credit_cost":2,"budget_id":null,"mcp_version":"v2","status":"ok"}
139
+ ```
140
+
141
+ `v` is the format version; `ts` is UTC with milliseconds; `host` is the server host (and port); `verb` is `call` or `run`; `label` is `--label` or `null`; `credit_cost` is the server's `_meta.creditCost`, `null` when not reported (never `0`); `budget_id` is `HGI_BUDGET_ID` or `null`; `mcp_version` may be `null`; `status` is `ok` or `tool_error` (an `isError` result, including `credit_limit_exceeded`). This is a versioned interface: version 1 may gain new keys, and existing keys keep their meaning. Readers should ignore keys they do not know.
142
+
53
143
  ## Safety notes
54
144
 
55
145
  - **CSV and spreadsheets.** Cells are written as the data is. A value that starts with `=`, `+`, `-` or `@` (third-party text can) is read as a formula by Excel and Google Sheets. Open untrusted exports as text, or prefix such cells yourself.
package/docs/releasing.md CHANGED
@@ -57,12 +57,15 @@ Verify these npm steps against npm's current documentation when you do them; the
57
57
 
58
58
  ## Cutting a release
59
59
 
60
+ In Claude Code, `/release` (`.claude/commands/release.md`) runs these steps. It stops for the bump PR's review, asks before every tag push, and leaves the `release` environment approval and the clean-machine checks to a person. Run it again with no arguments to resume a release in progress.
61
+
60
62
  1. Bump `version` in `package.json` (and `npm-shrinkwrap.json`: `npm install --package-lock-only`), open a PR, merge it.
61
63
  2. **Rehearse** with a release candidate: bump to `X.Y.Z-rc.1`, merge, tag `vX.Y.Z-rc.1`. This does everything for real (GitHub prerelease, smoke tests on all four platforms, `brew install` of the rendered formula, npm publish under dist-tag `next` with provenance) except opening the Homebrew PR.
62
64
  3. Run `scripts/verify-release.sh vX.Y.Z-rc.1 --route binary|npm` on clean machines.
63
65
  4. Bump to `X.Y.Z`, merge, tag `vX.Y.Z`. This publishes `latest` and opens the tap PR; merge it after checking the checksums match.
64
66
  5. Run `scripts/verify-release.sh vX.Y.Z --route brew|binary|npm` on a clean macOS and a clean Linux machine and paste the output into the tracking issue.
65
- 6. After the first release: add a `compat-previous-release` CI job that runs the previous release's binary against the current fake-server fixtures (`docs/compatibility.md` promises it from `v0.1.1`).
67
+ 6. Check that the GitHub release notes carry the line telling users who installed the agent skill to run `hgi skill install --force` after upgrading. If `skills/hgi/SKILL.md` changed since the previous release (`git diff --stat vPREV vX.Y.Z -- skills/hgi/SKILL.md`), say so at the top of the notes (`gh release edit vX.Y.Z --notes-file …`): an installed copy is not updated until the user runs that command.
68
+ 7. After the first release: add a `compat-previous-release` CI job that runs the previous release's binary against the current fake-server fixtures (`docs/compatibility.md` promises it from `v0.1.1`).
66
69
 
67
70
  Dry run at any time: Actions > Release > Run workflow (builds and packages everything; nothing is published).
68
71
 
package/docs/security.md CHANGED
@@ -21,6 +21,7 @@
21
21
  - Stored under `~/.config/hgi/` (or `$XDG_CONFIG_HOME/hgi`), never in a project directory. `HGI_CONFIG_DIR`, `XDG_CONFIG_HOME` and `XDG_CACHE_HOME` overrides inside a git working tree are refused.
22
22
  - One file per server, and a token is only ever sent to the server it was issued by. OAuth endpoints found through discovery must be on the same origin as the base URL, and `hgi` never follows an HTTP redirect on an auth or MCP request, so a token cannot be replayed to another host.
23
23
  - Several `hgi` processes share a lock around refresh, so parallel commands do not invalidate each other's sessions.
24
+ - Run-cap budget files (`hgi call --max-credits`) live in `~/.config/hgi/budgets/`, with the same protections as the credentials file (mode `0600` in a `0700` directory, atomic writes, symlinks refused, a lock across processes). They are named by a hash of the budget id and hold spend counters only, no tokens.
24
25
 
25
26
  ## Signing in and out
26
27
 
@@ -38,8 +39,19 @@
38
39
  ## What `call` and `run` do
39
40
 
40
41
  - `hgi call` only runs tools the server marks `readOnlyHint: true`, decided against a fresh tool list on every invocation. `hgi run` runs everything else, including tools with no annotations. There is no `--yes` flag, so a host permission rule on `hgi call *` approves only lookups.
41
- - `--out <file>` never overwrites an existing file on `hgi call`, never follows symlinks, and refuses paths inside hgi's config and cache directories. `--input @file` refuses hgi's own credential and cache files (including through symlinks and hard links). An allowlisted agent can still write a **new** file or send any other file it can read to HG Insights as tool input; scope your allowlist accordingly.
42
- - Credit cost is reported after each call. Credits are billed to your organization.
42
+ - `--out <file>` never overwrites an existing file on `hgi call`, never follows symlinks, and refuses paths inside hgi's config and cache directories. `--input @file` and `--ids @file` refuse hgi's own credential and cache files (including through symlinks and hard links), and read only regular files. An allowlisted agent can still write a **new** file or send any other file it can read to HG Insights as tool input; scope your allowlist accordingly.
43
+ - Credit cost is reported after each call (with `--ids` or `--all-pages`, once for the whole run, as the sum) and recorded in the local [credit ledger](#the-credit-ledger), one line per call (with `--ids`, one per batch call; with `--all-pages`, one per page), and one per attempt when `hgi call --retries` re-sends a `governance_unavailable` refusal (each attempt also counts against a run cap). Credits are billed to your organization. `--ids` sends batches one at a time and `--all-pages` sends pages one at a time; both stop at the first fatal error, so a run that hits a credit limit or an expired sign-in does not keep sending. Each extra page of `--all-pages` is a separate, billed call, capped by `--max-pages` (default 10 per page object).
44
+
45
+ ## The credit ledger
46
+
47
+ `hgi call` and `hgi run` append one line per tool call that got a result back (a re-sent `governance_unavailable` refusal counts once per attempt) to a local ledger, which `hgi usage` summarizes. It is the one local write a lookup (`hgi call`) makes.
48
+
49
+ - **What it holds:** the time, the server host, `call`/`run`, the tool name, your `--label`, the credit cost, `HGI_BUDGET_ID`, the MCP version and `ok`/`tool_error`. Never the tool input, the result, your user or organization, or any token: every text field is passed through the same redaction as error output, and the server-supplied MCP version is kept only when it is a short plain version string. See [output formats](output-formats.md#the-ledger-record) for the record format.
50
+ - **Where:** `~/.config/hgi/ledger.jsonl` (or `$XDG_CONFIG_HOME/hgi`, `HGI_CONFIG_DIR`). `HGI_LEDGER=<path>` moves it; a path inside a git working tree (as given, or after following symlinks) is refused before anything is sent. If you keep `~/.config` in a dotfiles repository, exclude `hgi/` from it: the ledger records which tools you used and when.
51
+ - **Protection:** the same as the credentials file. The directory is `0700`, the file `0600` from the first write (a pre-existing file with looser permissions is tightened), and a symlink or non-regular file at the ledger path is refused, never followed. Appends from parallel `hgi` processes are serialized with a lock on `<ledger>.lock` and written with one `O_APPEND` write each.
52
+ - **Never fails a call:** if the ledger cannot be written (lock timeout, unsafe path, disk full), `hgi` prints a warning and keeps the call's normal output and exit code, because the tool already ran and was billed.
53
+ - **Off:** `HGI_LEDGER=off` keeps no history: nothing is written and nothing is locked.
54
+ - **Deleting it:** deleting or truncating the file is safe at any time; it only resets the local history `hgi usage` reports.
43
55
 
44
56
  ## Network
45
57