@agledger/cli 2.1.0 → 2.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.
Files changed (48) hide show
  1. package/README.md +64 -22
  2. package/SKILL.md +15 -14
  3. package/bin/run.js +2 -2
  4. package/dist/api-client.d.ts +7 -0
  5. package/dist/api-client.js +44 -8
  6. package/dist/base.d.ts +91 -22
  7. package/dist/base.js +76 -47
  8. package/dist/cli/command.d.ts +58 -0
  9. package/dist/cli/command.js +44 -0
  10. package/dist/cli/flags.d.ts +76 -0
  11. package/dist/cli/flags.js +12 -0
  12. package/dist/cli/help.d.ts +6 -0
  13. package/dist/cli/help.js +107 -0
  14. package/dist/cli/index.d.ts +3 -0
  15. package/dist/cli/index.js +3 -0
  16. package/dist/cli/main.d.ts +22 -0
  17. package/dist/cli/main.js +223 -0
  18. package/dist/cli/parse.d.ts +20 -0
  19. package/dist/cli/parse.js +138 -0
  20. package/dist/commands/api.d.ts +106 -18
  21. package/dist/commands/api.js +103 -12
  22. package/dist/commands/auth.d.ts +35 -6
  23. package/dist/commands/auth.js +1 -1
  24. package/dist/commands/config.d.ts +43 -8
  25. package/dist/commands/config.js +9 -8
  26. package/dist/commands/discover.d.ts +35 -6
  27. package/dist/commands/docs.d.ts +41 -7
  28. package/dist/commands/docs.js +4 -4
  29. package/dist/commands/help-json.d.ts +39 -7
  30. package/dist/commands/help-json.js +27 -45
  31. package/dist/commands/list-commands.d.ts +36 -7
  32. package/dist/commands/list-commands.js +2 -2
  33. package/dist/commands/login.d.ts +66 -10
  34. package/dist/commands/login.js +30 -9
  35. package/dist/commands/logout.d.ts +41 -7
  36. package/dist/commands/logout.js +8 -8
  37. package/dist/commands/verify.d.ts +97 -13
  38. package/dist/commands/verify.js +84 -27
  39. package/dist/oidc.d.ts +47 -0
  40. package/dist/oidc.js +162 -3
  41. package/dist/util/config.d.ts +16 -1
  42. package/dist/util/config.js +50 -14
  43. package/dist/util/field-parser.d.ts +3 -1
  44. package/dist/util/field-parser.js +11 -5
  45. package/package.json +9 -21
  46. package/dist/hooks/command-not-found.d.ts +0 -3
  47. package/dist/hooks/command-not-found.js +0 -63
  48. package/oclif.manifest.json +0 -872
package/README.md CHANGED
@@ -4,7 +4,7 @@ The official CLI for the [AGLedger](https://agledger.ai) API: change control for
4
4
 
5
5
  Requires an AGLedger Server 2.0 or later. For a 1.x Server, use `npm i -g @agledger/cli@1.5.0`, the last release that supports it.
6
6
 
7
- A **thin cover** over the API. The CLI passes your request straight through to the API and forwards the response: no hand-coded per-endpoint wrappers, no flag-to-body translation, no drift. Every AGLedger API route is reachable via `agledger api <METHOD> <path>`.
7
+ A thin pass-through to the API. The CLI sends your request to the API as written and forwards the response. It has no per-endpoint wrappers and does not translate flags into request bodies, so a route the API adds works without a CLI release. Every AGLedger API route is reachable via `agledger api <METHOD> <path>`. An agent skill file, `SKILL.md`, ships with the package.
8
8
 
9
9
  **Learn more**
10
10
 
@@ -56,18 +56,51 @@ agledger api POST /v1/records \
56
56
  -F criteria.summary='deliver 500x copper wire' \
57
57
  -F autoActivate=true
58
58
 
59
- # Submit a completion. The principal then renders a Verdict (accept / reject)
60
- # on the Completion; use the route documented in the API
61
- # (see `agledger api GET /openapi.json`).
59
+ # Submit a completion. Note the `id` it returns.
62
60
  agledger api POST /v1/records/<record-id>/completions \
63
61
  --data '{"evidence":{"summary":"delivered 500x copper wire","evidenceUrl":"https://orders.example.com/CW-500"}}'
62
+
63
+ # The principal agent renders the verdict (accept or reject) on that completion,
64
+ # using its own key. The Record becomes FULFILLED on accept.
65
+ agledger api POST /v1/records/<record-id>/verdict \
66
+ --data '{"completionId":"<completion-id>","verdict":"accept"}'
64
67
  ```
65
68
 
66
- ## Why a thin cover?
69
+ ## Provenance, search filters and the HTML export
70
+
71
+ These are request fields and query parameters of AGLedger Server 3.0.0, sent through `agledger api` like any other.
72
+
73
+ ```bash
74
+ # Say which model and software produced a record or a completion. Every key is
75
+ # optional; digests are sha256:, sha384: or sha512: hex.
76
+ agledger api POST /v1/records/<record-id>/completions \
77
+ --data '{"evidence":{"summary":"done"},"producedBy":{"modelProvider":"acme","modelId":"m-1","agentSoftware":"runner","agentSoftwareVersion":"2.4.0"}}'
78
+
79
+ # Filter by trace id, by producer, or by a numeric bound (-F writes the bracket form
80
+ # criteriaGte[amount]=500; the same pattern covers criteriaGt/Lt/Lte and metadataGt/Gte/Lt/Lte)
81
+ agledger api GET /v1/records/search -F criteriaGte.amount=500 -F producedBy.modelId=m-1
82
+ agledger api GET /v1/records/search -F traceId=<32 lowercase hex> -F originRecordId=<record-id>
83
+
84
+ # Count records instead of listing them, grouped by up to two comma-joined dimensions
85
+ agledger api GET /v1/records/counts -F groupBy=status,type
67
86
 
68
- - **Zero drift.** When the API adds, renames, or removes a route, the CLI keeps working, no code change required.
87
+ # A verdict signed by a named person: `signatureMeaning` is authorship, review,
88
+ # approval or responsibility. It is taken only on an ephemeral OIDC cert; the Server
89
+ # refuses it with 422 on an API key.
90
+ agledger api POST /v1/records/<record-id>/verdict \
91
+ --data '{"completionId":"<completion-id>","verdict":"accept","signatureMeaning":"approval"}'
92
+
93
+ # The audit export as a self-contained HTML page, written as the Server sent it
94
+ agledger api GET /v1/records/<record-id>/audit-export -F format=html --output audit.html
95
+ ```
96
+
97
+ A text response (the `html`, `csv` and `ndjson` exports) is printed or written as the Server sent it. Use the default JSON export for `agledger verify`.
98
+
99
+ ## Why a pass-through?
100
+
101
+ - **No per-route code.** The CLI holds no list of routes, so it does not need a release when the API adds, renames or removes one.
69
102
  - **One mental model.** The API docs are the CLI docs. What you read in the OpenAPI spec is what you type.
70
- - **Every API route on day one.** You get full parity, not a hand-picked subset.
103
+ - **Every API route.** `agledger api` reaches all of them, not a hand-picked subset.
71
104
 
72
105
  ## Ways to pass a body
73
106
 
@@ -76,7 +109,7 @@ agledger api POST /v1/records/<record-id>/completions \
76
109
  | `--data '{...}'` | Agent-friendly: one JSON string |
77
110
  | `--input file.json` | Complex payloads; reuse files |
78
111
  | `--input -` | Pipe JSON from stdin |
79
- | `-F key=value` (repeatable) | Shell-friendly; typed (`true`/`false`/`null`/numbers); nested via `a.b=v`; arrays via `arr[]=v`; JSON literals via `k={...}` / `k=[...]` |
112
+ | `-F key=value` (repeatable) | Shell-friendly; typed (`true`/`false`/`null`, and numbers that print back as typed, so `0123` and `-0` stay strings); nested via `a.b=v`; arrays via `arr[]=v`; JSON literals via `k={...}` / `k=[...]` |
80
113
  | `-f key=value` (repeatable) | Same, but the value is taken verbatim as a string |
81
114
 
82
115
  Merging order (low → high): `--data` → `--input` → `-F`/`-f` → `--query`. Later sources override earlier keys.
@@ -102,7 +135,7 @@ signed and tamper-evident, with an identifier no other system will match.
102
135
 
103
136
  `agledger verify` checks a Record's audit export with no network and no API
104
137
  key: the hash chain, every COSE_Sign1 envelope signature (Ed25519 or ES256),
105
- and the bindings between the signed bytes and the columns beside them.
138
+ and the bindings between the signed bytes and the fields beside them.
106
139
 
107
140
  ```bash
108
141
  # Save a Record's audit export
@@ -113,7 +146,7 @@ agledger verify audit-export.json --trust-anchor sha256:<digest>
113
146
  ```
114
147
 
115
148
  The keys an export embeds, and the ones `GET /v1/verification-keys` serves,
116
- come from the Server's database, so a key written into the database alone
149
+ come from the Server, so a key planted on the Server alone
117
150
  would verify against them. `--trust-anchor` takes the SPKI digest of a vault
118
151
  key you took out of band (the installer prints the first vault key's) and walks
119
152
  the signed key statements the export carries from it:
@@ -124,11 +157,18 @@ the signed key statements the export carries from it:
124
157
  verdict. Either no `--trust-anchor` was given, so nothing links the keys to
125
158
  one you trust (`keyTrust.status` is `no_anchor`), or the anchor was walked
126
159
  but no signature verified under a key it anchors, as for an export of
127
- unsigned history (`no_anchored_signature`). It exits 0, and `--json` output
128
- carries `verdict: "unanchored"` for both. Treat it as unverified
129
- provenance, not as a clean pass.
130
- - `FAIL` exits 1. An entry signed by a key the walk does not reach is
131
- `CHAIN_SIGNING_KEY_UNANCHORED`; a key statement that does not hold is
160
+ unsigned history (`no_anchored_signature`). It exits 0 with no
161
+ `--trust-anchor` and 3 with one, and `--json` output carries
162
+ `verdict: "unanchored"` for both. Treat it as unverified provenance, not as
163
+ a clean pass.
164
+ - `NOT ANCHORED` exits 3: the `--trust-anchor` reaches none of the export's
165
+ keys, so every signed entry reads `CHAIN_SIGNING_KEY_UNANCHORED`, but the
166
+ export verifies without the pin. That is an export from another Server than
167
+ the one pinned, or one re-signed wholesale under keys of its own; check the
168
+ pin. `verdict` is `unanchored` and `valid` is false. This command makes no
169
+ network call, so here 3 never means an auth failure.
170
+ - `FAIL` exits 1. An entry signed by a key the walk does not reach, beside
171
+ entries the pin does anchor, is `CHAIN_SIGNING_KEY_UNANCHORED`; a key statement that does not hold is
132
172
  `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`.
133
173
  Those are listed under `keyTrust.findings`, and are `brokenAt` at position 0
134
174
  only when the chain itself is intact; when the chain also breaks, `brokenAt`
@@ -139,11 +179,10 @@ the signed key statements the export carries from it:
139
179
  that instant counts for nothing, and a key statement it signed counts for
140
180
  nothing at any instant, because the write times an export carries are not
141
181
  signed. A dated `--distrusted-key` may name a key also given to
142
- `--trust-anchor`, as the Server's key-compromise runbook does: the pin then
182
+ `--trust-anchor`, as the Server documentation's key-compromise guidance does: the pin then
143
183
  vouches for what the key signed before the instant. An export accounts for
144
184
  nothing a distrusted key signed; such entries fail here, and only a full dump
145
- verified with `@agledger/verify` lists them as accounted for. An API 2.0
146
- export lists a key the Server's `VAULT_DISTRUSTED_KEYS` names with
185
+ verified with `@agledger/verify` lists them as accounted for. An export from a Server 2.0 or later lists a key the Server's `VAULT_DISTRUSTED_KEYS` names with
147
186
  `distrustedFrom`, the entry's instant, and where that instant is earlier than
148
187
  the retirement the key's closures sign, lists the key retired at it. A run
149
188
  not given the same entry still fails `CHAIN_KEY_WINDOW_DRIFT` on that window
@@ -165,7 +204,7 @@ operator gives it; a sealed message that does not hold fails
165
204
  `--federation-key-history <file>` (the JSON its
166
205
  `GET /.well-known/agledger-federation-keys.json` serves) beside the
167
206
  `--federation-key` for that hub trusts every key the history links to yours, so
168
- the entries sealed before the change verify too. `--trust-anchor`, `--distrusted-key` and
207
+ the entries sealed before the change verify too. Federation key histories need a Server 2.2 or later on the peer. A message the peer signed more than 300 seconds after its key's retirement fails `CHAIN_FEDERATION_WIRE_INVALID`; `--allow-after-retirement` accepts it and counts it, for a peer that kept signing briefly after rotating. The entry counts an export states about itself are unsigned, so an export cut from the end with them deleted still passes; `--expected-entry-count <n>` holds it to a count you took out of band, and a different number of entries fails `CHAIN_POSITION_GAP`. `--trust-anchor`, `--distrusted-key` and
169
208
  `--federation-key` are given once per key. A malformed value, a distrusted key named twice,
170
209
  `--distrusted-key` without `--trust-anchor`, a pinned key distrusted with no
171
210
  instant (the Server refuses to start with that pair), and a
@@ -186,13 +225,13 @@ the same as `@agledger/verify`'s `agledger-verify` and the Python
186
225
  - `--paginate` on GET follows cursor pagination and streams NDJSON
187
226
  - Every POST carries a generated `Idempotency-Key`, so one invocation is replay-safe on its own. Retrying a call that may already have reached the Server? Pass `--idempotency-key` with the first attempt's key and the Server replays the original result instead of recording the work twice. When a POST times out (exit 10, `TIMEOUT`) or its connection drops after the request went out (exit 9, `NETWORK_ERROR`), the error carries the key it sent as `idempotencyKey` and the suggestion is the rerun: `agledger api POST ... --idempotency-key <key>`. A plain rerun mints a new key and can record the work twice. A GET has no key, and neither does a connection that was refused or never resolved, since nothing was sent
188
227
  - Structured errors on stderr: the CLI's own are `{error: true, code, message, suggestion, ...}`; an API error passes through verbatim as the Server's RFC 9457 body, whose human-readable text is `detail`
189
- - Semantic exit codes: 0 (OK), 1 (general), 2 (usage), 3 (auth), 4 (forbidden), 5 (not found), 6 (conflict), 7 (rate limit), 8 (server), 9 (network), 10 (timeout). **1 is the catch-all**: an API error whose status maps to nothing more specific (a 400, for example) exits 1, as does a chain that fails `agledger verify`. Read the `code` field on stderr to tell them apart, and treat any non-zero as failure rather than keying on 1 alone.
228
+ - Semantic exit codes: 0 (OK), 1 (general), 2 (usage), 3 (auth), 4 (forbidden), 5 (not found), 6 (conflict), 7 (rate limit), 8 (server), 9 (network), 10 (timeout). **1 is the catch-all**: an API error whose status maps to nothing more specific (a 400, for example) exits 1, as does a chain that fails `agledger verify`. `agledger verify` makes no network call and uses 3 for a `--trust-anchor` that was not met (see above). Read the `code` field on stderr to tell them apart, and treat any non-zero as failure rather than keying on 1 alone.
190
229
  - `NO_COLOR` supported per [no-color.org](https://no-color.org)
191
230
 
192
231
  ## Discovery
193
232
 
194
233
  ```bash
195
- agledger list-commands --json # 10 CLI-local commands
234
+ agledger list-commands --json # The CLI-local commands
196
235
  agledger help-json api --json # Schema for `api` (args + flags)
197
236
  agledger discover # Health + identity + quickstart
198
237
  agledger api GET /openapi.json # Full API route catalog
@@ -252,6 +291,7 @@ its own Server.
252
291
  |---|---|
253
292
  | `AGLEDGER_OIDC_TOKEN_CMD` | A shell command whose stdout is an OIDC JWT, run on every exchange: `gcloud auth print-identity-token`, `az account get-access-token`, `vault`, `kubectl create token`, or your own script |
254
293
  | `AGLEDGER_OIDC_TOKEN_FILE` | A file holding an OIDC JWT, read on every exchange, such as a projected service-account token that Kubernetes rotates on disk. The Server exchanges each token once, so one file token serves one CLI run until the file rotates; for repeated runs, prefer a command that mints a new token |
294
+ | `AGLEDGER_AGENT_KEYS_FILE` | Optional. A JWK Set file each cert exchange adds its public key to before the cert is used (`--agent-keys-file` on `login --oidc` stores it in the profile). Each command signs under a key pair of its own, so this file is how the agent signatures it seals are re-verified offline: `agledger verify export.json --agent-keys <file>`. Commands running at once can share one file: each takes `<file>.lock` while it adds its key. It holds public keys only |
255
295
  | `AGLEDGER_OIDC_AGENT_ID` | Optional. An assertion of the agent id the token binds to, sent on the exchange. It never chooses the agent: when it names a different one, or the token binds none, the Server refuses the exchange with 403 `CERT_AGENT_BINDING_MISMATCH` rather than issue a cert for an agent you did not expect. Leave it unset unless you want that check |
256
296
 
257
297
  ```bash
@@ -272,7 +312,7 @@ agledger login --oidc --oidc-token-cmd 'gcloud auth print-identity-token --audie
272
312
  What the CLI does with it:
273
313
 
274
314
  - **A fresh token per exchange.** The Server accepts each token id once, so the source is called again for every exchange and a token is never reused or cached.
275
- - **The key stays in memory.** Each invocation generates an Ed25519 key pair, proves possession of it in the exchange, and discards it on exit. The cert and the key are never written anywhere; `login --oidc` stores only the command or the file path. A token command is verified at login with one exchange; a token file is only checked to hold a JWT, because exchanging it would spend the token the next command needs until the file rotates.
315
+ - **The key stays in memory.** Each invocation generates an Ed25519 key pair, proves possession of it in the exchange, and discards it on exit. The cert and the private key are never written anywhere; the public key is, to `AGLEDGER_AGENT_KEYS_FILE` when you set one, and `login --oidc` and `auth` print it as `publicKeyJwk`; `login --oidc` stores only the command or the file path. A token command is verified at login with one exchange; a token file is only checked to hold a JWT, because exchanging it would spend the token the next command needs until the file rotates.
276
316
  - **Signed writes.** Every request with a body carries `X-Agent-Signature` over the SHA-256 of the exact bytes sent, so the chain entry records the agent's own signature in `on_behalf_of.agent_signature`, not only the Server's.
277
317
  - **Refresh.** The cert is re-exchanged once half its lifetime has passed, and once more if the Server answers 401 to it, before the error is reported.
278
318
  - **Failures name the source.** A token command that exits non-zero fails with `OIDC_TOKEN_SOURCE_FAILED` (exit 3), naming the variable and carrying the command's stderr. A refused exchange fails with `OIDC_EXCHANGE_FAILED` and forwards the Server's error, including its `recoveryHint`.
@@ -312,3 +352,5 @@ Agent keys (`agl_agt_*`) and admin keys (`agl_adm_*`) are both accepted; the API
312
352
  ## License
313
353
 
314
354
  Proprietary. Copyright (c) 2026 AGLedger LLC. All rights reserved. See [LICENSE](LICENSE).
355
+
356
+ AGLedger is a trademark of AGLedger LLC. All other trademarks are the property of their respective owners. Patent pending.
package/SKILL.md CHANGED
@@ -1,6 +1,11 @@
1
+ ---
2
+ name: agledger-cli
3
+ description: Use when an agent needs to record what it was asked to do and what it did, submit completions, read verdicts, or verify audit exports, through the `agledger` CLI against a self-hosted AGLedger Server.
4
+ ---
5
+
1
6
  # AGLedger CLI
2
7
 
3
- Thin cover over the AGLedger API. The CLI passes your call through to the API and forwards the response. No flag-to-body translation, no drift.
8
+ Thin pass-through to the AGLedger API. The CLI sends your call to the API as written and forwards the response, with no flag-to-body translation.
4
9
 
5
10
  ## Setup
6
11
  Credentials resolve per command with this precedence: `--api-key` flag > `AGLEDGER_API_KEY` env > `AGLEDGER_OIDC_TOKEN_CMD` > `AGLEDGER_OIDC_TOKEN_FILE` > stored profile (after `agledger login`). API URL: `--api-url` flag > `AGLEDGER_API_URL` env > stored profile URL.
@@ -28,35 +33,31 @@ agledger api <METHOD> <PATH> [--data JSON | --input FILE | -F key=value | -f key
28
33
  - `--data '{"k":"v"}'`: raw JSON string (agent-friendly)
29
34
  - `--input file.json`: read JSON from file
30
35
  - `--input -`: read JSON from stdin
31
- - `-F key=value`: repeatable; types parsed (`true`/`false`/`null`/numbers); nested via `a.b=v`; arrays via `arr[]=v`
36
+ - `-F key=value`: repeatable; types parsed (`true`/`false`/`null`/numbers that print back as typed, so `0123` stays a string); nested via `a.b=v`; arrays via `arr[]=v`
32
37
  - `-f key=value`: same, value taken verbatim as a string. Required for identifiers that look numeric (`externalTaskId`, `correlationId`, `platformRef`, `projectRef`, `publisher`): the Server does not coerce a JSON body, so `-F externalTaskId=4821` sends a number and is refused. Do not quote around `-F` to work around it; the quote characters land inside the notarized value.
33
38
 
34
39
  ## Discovery commands
35
- - `agledger list-commands --json`: full CLI inventory (10 commands)
40
+ - `agledger list-commands --json`: the CLI-local commands
36
41
  - `agledger help-json <command> --json`: per-command schema with args and flags
37
42
  - `agledger api GET /openapi.json`: full API route catalog
38
43
 
39
44
  ## Offline audit verification
40
- - `agledger verify <audit-export.json> --trust-anchor sha256:<digest>`: verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network, no API key. `--trust-anchor` (repeatable) is the SPKI digest of a vault key taken out of band (the installer prints the first one); the signed key statements in the export are walked from it. Exit 0 if valid, 1 if broken, 2 on a usage error; `--json` for structured output, with `verdict` (`trusted`, `unanchored`, `failed`). `--distrusted-key sha256:<digest>[@<instant>]` (repeatable, needs `--trust-anchor`) mirrors the operator's `VAULT_DISTRUSTED_KEYS`; `--keys <file>` supplies keys (a saved `GET /v1/verification-keys` response works as is); `--require-key-id <id>` rejects exports signed by an unexpected key; `--require-supplied-keys` refuses the export's own embedded keys.
45
+ - `agledger verify <audit-export.json> --trust-anchor sha256:<digest>`: verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network, no API key. `--trust-anchor` (repeatable) is the SPKI digest of a vault key taken out of band (the installer prints the first one); the signed key statements in the export are walked from it. Exit 0 when nothing failed (read `verdict`), 1 when the export is broken, 2 on a usage error, 3 when a `--trust-anchor` was given and not met (an export from another Server, or one carrying keys of its own); `--json` for structured output, with `verdict` (`trusted`, `unanchored`, `failed`). `--distrusted-key sha256:<digest>[@<instant>]` (repeatable, needs `--trust-anchor`) mirrors the operator's `VAULT_DISTRUSTED_KEYS`; `--keys <file>` supplies keys (a saved `GET /v1/verification-keys` response works as is); `--require-key-id <id>` rejects exports signed by an unexpected key; `--require-supplied-keys` refuses the export's own embedded keys; `--expected-entry-count <n>` holds the export to a count taken out of band; `--agent-keys <file>` re-verifies agent signatures (an OIDC cert agent's keys collect in `AGLEDGER_AGENT_KEYS_FILE` when it is set).
41
46
 
42
- **Read the verdict, not just the exit code.** Without `--trust-anchor` a chain that verifies prints `VERIFIED, NOT ANCHORED`, exits 0, and its JSON carries `keyTrust.status: "no_anchor"`: the signatures were checked against keys nobody pinned, and a key written into the Server's database alone would pass. A run with `--trust-anchor` that verified no signature under an anchored key (unsigned history) is also `VERIFIED, NOT ANCHORED`, with `keyTrust.status: "no_anchored_signature"`. Both carry `verdict: "unanchored"`. Only `PASS` (`verdict: "trusted"`, `keyTrust.status: "walked"`) says the keys are linked to one you trust.
47
+ **Read the verdict, not just the exit code.** Without `--trust-anchor` a chain that verifies prints `VERIFIED, NOT ANCHORED`, exits 0, and its JSON carries `keyTrust.status: "no_anchor"`: the signatures were checked against keys nobody pinned, and a key planted on the Server alone would pass. A run with `--trust-anchor` that verified no signature under an anchored key (unsigned history) is also `VERIFIED, NOT ANCHORED`, with `keyTrust.status: "no_anchored_signature"`. Both carry `verdict: "unanchored"`. Only `PASS` (`verdict: "trusted"`, `keyTrust.status: "walked"`) says the keys are linked to one you trust.
43
48
 
44
- **What verification proves:**
45
- - Every entry was signed by a key listed in the export (or supplied via `--keys`) at the moment the vault wrote it, and, with `--trust-anchor`, that key is linked by signed key statements to the one you pinned (else `CHAIN_SIGNING_KEY_UNANCHORED`).
46
- - Payloads have not been altered since signing (SHA-256 recomputation matches the stored `payload_hash` over the signed COSE_Sign1 bytes).
47
- - The hash chain is contiguous: no entries were inserted, removed, or reordered between positions.
49
+ **What verification checks:**
50
+ - Every entry's signature verifies under a key listed in the export (or supplied via `--keys`) and valid at the time the entry was written, and, with `--trust-anchor`, that key is linked by signed key statements to the one you pinned (else `CHAIN_SIGNING_KEY_UNANCHORED`).
51
+ - Payloads match what was signed (the SHA-256 recomputation equals the hash the entry records for the signed COSE_Sign1 bytes).
52
+ - The hash chain is contiguous from the first entry to the last: no entries inserted, removed, or reordered between positions.
48
53
  - On failure, `brokenAt.code` is a canonical SCREAMING_SNAKE failure code (e.g. `CHAIN_HASH_MISMATCH`, `CHAIN_SIGNATURE_INVALID`, `CHAIN_SIGNING_KEY_UNANCHORED`, and `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID`, `CHAIN_KEY_WINDOW_DRIFT`, which are listed under `keyTrust.findings` and are `brokenAt` at position 0 only when the chain itself is intact). A `CHAIN_KEY_WINDOW_DRIFT` whose detail names a `--distrusted-key sha256:<digest>@<instant>` is the export saying the Server distrusts that key from that instant (`distrustedFrom`): its unsigned word, so confirm the instant with the operator before rerunning with that flag.
49
54
 
50
- **What verification does NOT prove:**
51
- - That the signing key is *legitimate* without `--trust-anchor`. `/v1/verification-keys` and `/.well-known/scitt-keys` are served from the same database; the export's `exportMetadata.anchoredFrom` is the Server's own claim. Pin a digest you took out of band.
52
- - That the export is *complete*. A vault operator can still truncate the export at either end.
53
- - That the *content* the payload describes actually happened. Payloads record what the agent notarized (declared intent and reported result); the verifier checks tamper-evidence, not whether the work occurred.
54
-
55
55
  ## Agent-native patterns
56
56
  - `--json` on every command (auto when piped)
57
57
  - `--quiet` for exit-code-only operation
58
58
  - `--dry-run` on `agledger api` shows the request without sending
59
59
  - `--paginate` on GET follows cursors, streams NDJSON
60
+ - `--output <file>` writes the response body to a file; a text response (`format=html|csv|ndjson` audit export) is written exactly as the Server sent it, and printed raw to stdout when no file is given
60
61
  - Structured errors on stderr: the CLI's own are `{code, message, suggestion, ...}`; an API error is the Server's RFC 9457 body, verbatim, with its text in `detail`
61
62
  - Semantic exit codes (0-10)
62
63
 
package/bin/run.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { execute } from '@oclif/core';
3
- await execute({ dir: import.meta.url });
2
+ import { main } from '../dist/cli/main.js';
3
+ await main(process.argv.slice(2));
@@ -4,6 +4,13 @@ export interface ApiResponse {
4
4
  body: unknown;
5
5
  ok: boolean;
6
6
  }
7
+ /**
8
+ * The query string a GET or DELETE carries, for a params value. Anything that
9
+ * has no query form is refused: a body that is not an object (`--data '[1,2]'`
10
+ * would send `?0=1&1=2`) and a null (the wire omits it, so a dry run that showed
11
+ * it would describe a request that is not sent).
12
+ */
13
+ export declare function queryParams(query: unknown): URLSearchParams;
7
14
  /**
8
15
  * Which credential a 401 is about, read from the Server's error body.
9
16
  *
@@ -1,3 +1,19 @@
1
+ import { FieldParseError } from './util/field-parser.js';
2
+ /**
3
+ * A query value as text. The bracket form goes one level deep
4
+ * (`criteriaGte[amount]=500`), so an object or array below that has no wire
5
+ * form; it is refused rather than sent as `[object Object]`, which the Server
6
+ * would read as a filter on that literal string.
7
+ */
8
+ function queryText(name, value) {
9
+ if (value instanceof Date)
10
+ return value.toISOString();
11
+ if (typeof value === 'string')
12
+ return value;
13
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint')
14
+ return String(value);
15
+ throw new FieldParseError(name, 'a query parameter goes one level deep (a.b=v becomes a[b]=v); a nested object or array has no query-string form');
16
+ }
1
17
  /**
2
18
  * Serialize one query parameter.
3
19
  *
@@ -18,7 +34,7 @@ function appendQueryParam(search, key, value) {
18
34
  for (const item of value) {
19
35
  if (item === undefined || item === null)
20
36
  continue;
21
- search.append(key, item instanceof Date ? item.toISOString() : String(item));
37
+ search.append(key, queryText(key, item));
22
38
  }
23
39
  return;
24
40
  }
@@ -26,11 +42,34 @@ function appendQueryParam(search, key, value) {
26
42
  for (const [sub, subValue] of Object.entries(value)) {
27
43
  if (subValue === undefined || subValue === null)
28
44
  continue;
29
- search.set(`${key}[${sub}]`, subValue instanceof Date ? subValue.toISOString() : String(subValue));
45
+ search.set(`${key}[${sub}]`, queryText(`${key}.${sub}`, subValue));
30
46
  }
31
47
  return;
32
48
  }
33
- search.set(key, String(value));
49
+ search.set(key, queryText(key, value));
50
+ }
51
+ /**
52
+ * The query string a GET or DELETE carries, for a params value. Anything that
53
+ * has no query form is refused: a body that is not an object (`--data '[1,2]'`
54
+ * would send `?0=1&1=2`) and a null (the wire omits it, so a dry run that showed
55
+ * it would describe a request that is not sent).
56
+ */
57
+ export function queryParams(query) {
58
+ const search = new URLSearchParams();
59
+ if (query === undefined)
60
+ return search;
61
+ if (query === null || typeof query !== 'object' || Array.isArray(query)) {
62
+ throw new FieldParseError('query', 'a GET or DELETE query must be a JSON object of parameters (key=value pairs)');
63
+ }
64
+ for (const [k, v] of Object.entries(query)) {
65
+ if (v === undefined)
66
+ continue;
67
+ if (v === null) {
68
+ throw new FieldParseError(k, 'null has no query-string form; leave the parameter out');
69
+ }
70
+ appendQueryParam(search, k, v);
71
+ }
72
+ return search;
34
73
  }
35
74
  /**
36
75
  * Which credential a 401 is about, read from the Server's error body.
@@ -94,11 +133,8 @@ export class ApiClient {
94
133
  // `apiUrl` has trailing slashes stripped; `path` is guaranteed leading-slash.
95
134
  const url = new URL(this.apiUrl + path);
96
135
  if (options?.query) {
97
- for (const [k, v] of Object.entries(options.query)) {
98
- if (v !== undefined && v !== null) {
99
- appendQueryParam(url.searchParams, k, v);
100
- }
101
- }
136
+ for (const [k, v] of queryParams(options.query))
137
+ url.searchParams.append(k, v);
102
138
  }
103
139
  // Serialized once: with a cert credential the agent signature covers these
104
140
  // exact bytes, so the body that is hashed must be the body that is sent.
package/dist/base.d.ts CHANGED
@@ -5,10 +5,9 @@
5
5
  *
6
6
  * NO_COLOR (no-color.org): the CLI emits plain JSON to both stdout (results)
7
7
  * and stderr (errors) with no ANSI escapes of its own, so it is trivially
8
- * NO_COLOR-conformant by construction. oclif's own help/error rendering also
9
- * honors NO_COLOR via chalk's built-in detection, so no explicit check needed.
8
+ * NO_COLOR-conformant by construction, as is the help text.
10
9
  */
11
- import { Command } from '@oclif/core';
10
+ import { Command } from './cli/index.js';
12
11
  import { ApiClient } from './api-client.js';
13
12
  import type { ApiResponse } from './api-client.js';
14
13
  import { OidcCertCredential, type OidcTokenSource } from './oidc.js';
@@ -48,6 +47,10 @@ export declare const ErrorCode: {
48
47
  readonly INVALID_METHOD: 'INVALID_METHOD';
49
48
  readonly INVALID_FIELD: 'INVALID_FIELD';
50
49
  readonly FILE_READ_ERROR: 'FILE_READ_ERROR';
50
+ /** The `--output` file cannot be written. */
51
+ readonly FILE_WRITE_ERROR: 'FILE_WRITE_ERROR';
52
+ /** `--paginate` on a response that is not a list. */
53
+ readonly NOT_PAGINATED: 'NOT_PAGINATED';
51
54
  readonly TIMEOUT: 'TIMEOUT';
52
55
  readonly NETWORK_ERROR: 'NETWORK_ERROR';
53
56
  readonly UNKNOWN_ERROR: 'UNKNOWN_ERROR';
@@ -68,6 +71,7 @@ export type ResolvedCredential = {
68
71
  kind: 'oidc';
69
72
  source: OidcTokenSource;
70
73
  agentId?: string;
74
+ agentKeysFile?: string;
71
75
  from: 'env' | 'profile';
72
76
  } | {
73
77
  kind: 'none';
@@ -79,7 +83,7 @@ export declare function envOidcSource(): OidcTokenSource | undefined;
79
83
  /** The delegation token source from the environment. The command wins over the file. */
80
84
  export declare function envOnBehalfOfSource(): OidcTokenSource | undefined;
81
85
  /** Whether a flag was passed on the command line (`--flag value` or `--flag=value`),
82
- * as opposed to reaching oclif through its `env` binding. */
86
+ * as opposed to reaching the parser through a flag's `env` binding. */
83
87
  export declare function argvHasFlag(flag: string): boolean;
84
88
  /**
85
89
  * Why an API URL cannot be used, or undefined when it can. Only an absolute
@@ -87,6 +91,8 @@ export declare function argvHasFlag(flag: string): boolean;
87
91
  * scheme is `localhost:`, which then fails at request time as a fetch error.
88
92
  */
89
93
  export declare function apiUrlProblem(url: string): string | undefined;
94
+ /** A URL with anything before an `@` in its authority masked, so a password never reaches a message. */
95
+ export declare function redactUrl(url: string): string;
90
96
  export declare abstract class BaseCommand extends Command {
91
97
  /** The URL the most recent client was built for, so a network failure can
92
98
  * name the host it actually tried. */
@@ -99,27 +105,89 @@ export declare abstract class BaseCommand extends Command {
99
105
  /** The Idempotency-Key the most recent POST went out under, so a timeout or a
100
106
  * dropped connection can hand it back for the retry. Undefined for any other
101
107
  * method: the API ignores the header there, so there is no key to claim. */
102
- private sentIdempotencyKey?;
108
+ protected sentIdempotencyKey?: string;
103
109
  static baseFlags: {
104
- json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
105
- quiet: import("@oclif/core/interfaces").BooleanFlag<boolean>;
106
- 'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
107
- 'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
108
- profile: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
109
- verbose: import("@oclif/core/interfaces").BooleanFlag<boolean>;
110
+ json: {
111
+ readonly description: "Force JSON output (default when stdout is piped)";
112
+ readonly default: false;
113
+ } & {
114
+ readonly type: 'boolean';
115
+ };
116
+ quiet: {
117
+ readonly description: "Suppress output (exit code only)";
118
+ readonly default: false;
119
+ } & {
120
+ readonly type: 'boolean';
121
+ };
122
+ 'api-key': {
123
+ readonly description: "AGLedger API key";
124
+ readonly env: "AGLEDGER_API_KEY";
125
+ } & {
126
+ readonly type: 'option';
127
+ };
128
+ 'api-url': {
129
+ readonly description: "AGLedger API base URL";
130
+ readonly env: "AGLEDGER_API_URL";
131
+ } & {
132
+ readonly type: 'option';
133
+ };
134
+ profile: {
135
+ readonly description: "Stored profile to use for credentials (falls back to the active profile)";
136
+ } & {
137
+ readonly type: 'option';
138
+ };
139
+ verbose: {
140
+ readonly description: "Report which credential was used, and each OIDC cert exchange, as JSON lines on stderr. Never prints a key, token or cert.";
141
+ readonly default: false;
142
+ } & {
143
+ readonly type: 'boolean';
144
+ };
110
145
  };
111
- protected get isJson(): boolean;
112
- protected get isQuiet(): boolean;
113
146
  /**
114
- * oclif's own refusals (an unknown flag, a missing argument, a bad enum
115
- * value) reach here before any command code runs. Under --quiet they exit
116
- * as a usage error with nothing written, as every other error does; an
117
- * explicit `this.exit(code)` passes through untouched, since it already
118
- * carries the code the command chose.
147
+ * The base flags for a command that makes no API call: the credential flags
148
+ * stay accepted (a script may pass them to every command) but are left out of --help.
119
149
  */
120
- protected catch(err: Error & {
121
- exitCode?: number;
122
- }): Promise<unknown>;
150
+ static offlineFlags: {
151
+ json: {
152
+ readonly description: "Force JSON output (default when stdout is piped)";
153
+ readonly default: false;
154
+ } & {
155
+ readonly type: 'boolean';
156
+ };
157
+ quiet: {
158
+ readonly description: "Suppress output (exit code only)";
159
+ readonly default: false;
160
+ } & {
161
+ readonly type: 'boolean';
162
+ };
163
+ 'api-key': {
164
+ type: 'option';
165
+ description: "AGLedger API key";
166
+ env: "AGLEDGER_API_KEY";
167
+ hidden: boolean;
168
+ };
169
+ 'api-url': {
170
+ type: 'option';
171
+ description: "AGLedger API base URL";
172
+ env: "AGLEDGER_API_URL";
173
+ hidden: boolean;
174
+ };
175
+ profile: {
176
+ type: 'option';
177
+ description: "Stored profile to use for credentials (falls back to the active profile)";
178
+ hidden: boolean;
179
+ };
180
+ verbose: {
181
+ type: 'boolean';
182
+ description: "Report which credential was used, and each OIDC cert exchange, as JSON lines on stderr. Never prints a key, token or cert.";
183
+ default: false;
184
+ hidden: boolean;
185
+ };
186
+ };
187
+ protected get isJson(): boolean;
188
+ protected get isQuiet(): boolean;
189
+ /** --json and --quiet as the parser read them, so a value such as `--data --quiet` is not a flag. */
190
+ private parsedOutputFlags;
123
191
  /** Write one diagnostic line to stderr under --verbose. Callers pass no secrets. */
124
192
  protected verboseLog(flags: {
125
193
  verbose?: boolean;
@@ -128,7 +196,7 @@ export declare abstract class BaseCommand extends Command {
128
196
  * Resolve which credential a command uses, without calling anything.
129
197
  *
130
198
  * Precedence, highest first:
131
- * 1. An API key from `--api-key` or `AGLEDGER_API_KEY` (oclif merges the
199
+ * 1. An API key from `--api-key` or `AGLEDGER_API_KEY` (the parser merges the
132
200
  * two into `flags['api-key']`).
133
201
  * 2. `AGLEDGER_OIDC_TOKEN_CMD`, then `AGLEDGER_OIDC_TOKEN_FILE`.
134
202
  * 3. The selected profile (`--profile <name>`, else the active one): its
@@ -166,6 +234,7 @@ export declare abstract class BaseCommand extends Command {
166
234
  }, credential: {
167
235
  source: OidcTokenSource;
168
236
  agentId?: string;
237
+ agentKeysFile?: string;
169
238
  }): OidcCertCredential;
170
239
  /** A secret-free description of a credential, for --verbose, --dry-run and `auth`. */
171
240
  protected describeCredential(credential: ResolvedCredential): Record<string, unknown>;