@agledger/cli 1.4.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -17,16 +17,13 @@ Licensor grants you a limited, non-exclusive, non-transferable, revocable
17
17
  license to install and use the Software solely for the purpose of integrating
18
18
  with a self-hosted AGLedger deployment operated by you or your organization, or
19
19
  by a third party on your behalf with your authorization. The Software is not
20
- designed for, and is not licensed for use with, any AGLedger-hosted service.
21
- AGLedger operates the AGLedger software on a self-hosted model; there is no
22
- hosted AGLedger API.
20
+ licensed for use with any AGLedger-hosted service.
23
21
 
24
- AGLedger LLC operates no service in your data path. AGLedger LLC does not
25
- receive, access, inspect, or judge the records, completions, or deliverable
26
- content you process through your self-hosted deployment, and does not use any
27
- such data to train, fine-tune, evaluate, or benchmark any machine-learning or
28
- artificial-intelligence model, or to develop any product or service. AGLedger
29
- LLC receives no usage data or other data from your self-hosted deployment.
22
+ AGLedger LLC does not receive, access, inspect, or judge the data you process
23
+ through your self-hosted deployment, and does not use any such data to train,
24
+ fine-tune, evaluate, or benchmark any machine-learning or artificial-
25
+ intelligence model, or to develop any product or service. AGLedger LLC does not
26
+ collect product usage information from your self-hosted deployment.
30
27
 
31
28
  2. RESTRICTIONS
32
29
 
@@ -103,14 +100,13 @@ or trade-control laws.
103
100
 
104
101
  7. TRADEMARKS
105
102
 
106
- AGLedger is a trademark of AGLedger LLC, and Settlement Signal is a pending
107
- trademark of AGLedger LLC. All other trademarks are the property of their
108
- respective owners.
103
+ AGLedger and Settlement Signal are trademarks of AGLedger LLC. All other
104
+ trademarks are the property of their respective owners.
109
105
 
110
106
  8. PATENTS
111
107
 
112
- The Software is covered by one or more U.S. patent applications pending before
113
- the U.S. Patent and Trademark Office in AGLedger LLC's patent portfolio.
108
+ The Software is covered by one or more issued or pending U.S. patents in
109
+ AGLedger LLC's patent portfolio.
114
110
 
115
111
  9. RELATIONSHIP TO OTHER AGLEDGER AGREEMENTS
116
112
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @agledger/cli
2
2
 
3
- The official CLI for the [AGLedger](https://agledger.ai) API: change control for AI agents. A self-hosted notary that records every change an agent makes, signed and hash-chained, and gates the ones that matter.
3
+ The official CLI for the [AGLedger](https://agledger.ai) API: change control for AI agents. Agent memory, approvals, audit trail, and notifications: one API, one signed ledger, self-hosted.
4
4
 
5
5
  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>`.
6
6
 
@@ -21,7 +21,7 @@ npm install -g @agledger/cli
21
21
  ## Quick Start
22
22
 
23
23
  ```bash
24
- export AGLEDGER_API_KEY=agl_adm_...
24
+ export AGLEDGER_API_KEY=agl_agt_...
25
25
  export AGLEDGER_API_URL=https://your-agledger-instance
26
26
 
27
27
  # Check health, identity, scopes, and get the quickstart workflow
@@ -46,8 +46,16 @@ agledger api POST /v1/records \
46
46
  -F criteria.summary='summarize Q3 filings' \
47
47
  -f externalTaskId=4821
48
48
 
49
- # Submit a completion. On a gated record the principal then renders a Verdict
50
- # (accept / reject) on the Completion; use the route documented in the API
49
+ # A type with a completion phase, such as the seeded principal-gate-generic-v1,
50
+ # takes a Completion once the record is ACTIVE; autoActivate gets it there on
51
+ # create. Note the `id` it returns.
52
+ agledger api POST /v1/records \
53
+ -F type=principal-gate-generic-v1 \
54
+ -F criteria.summary='deliver 500x copper wire' \
55
+ -F autoActivate=true
56
+
57
+ # Submit a completion. The principal then renders a Verdict (accept / reject)
58
+ # on the Completion; use the route documented in the API
51
59
  # (see `agledger api GET /openapi.json`).
52
60
  agledger api POST /v1/records/<record-id>/completions \
53
61
  --data '{"evidence":{"summary":"delivered 500x copper wire","evidenceUrl":"https://orders.example.com/CW-500"}}'
@@ -79,8 +87,8 @@ The Server does not coerce the fields of a JSON body, so a field declared
79
87
  minted by other systems, and those are frequently all digits:
80
88
 
81
89
  ```bash
82
- agledger api POST /v1/records -F externalTaskId=4821 # sends 4821, refused
83
- agledger api POST /v1/records -f externalTaskId=4821 # sends "4821"
90
+ agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary=x -F externalTaskId=4821 # sends 4821, refused
91
+ agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary=x -f externalTaskId=4821 # sends "4821"
84
92
  ```
85
93
 
86
94
  Reach for `-f` rather than quoting. Shell quotes that survive into the value
@@ -88,14 +96,86 @@ Reach for `-f` rather than quoting. Shell quotes that survive into the value
88
96
  characters inside it, and the Server accepts that: the Record is notarized,
89
97
  signed and immutable, with an identifier no other system will match.
90
98
 
99
+ ## Verifying an export offline
100
+
101
+ `agledger verify` checks a Record's audit export with no network and no API
102
+ key: the hash chain, every COSE_Sign1 envelope signature (Ed25519 or ES256),
103
+ and the bindings between the signed bytes and the columns beside them.
104
+
105
+ ```bash
106
+ # Save a Record's audit export
107
+ agledger api GET /v1/records/<record-id>/audit-export > audit-export.json
108
+
109
+ # Verify it against a vault key you pinned
110
+ agledger verify audit-export.json --trust-anchor sha256:<digest>
111
+ ```
112
+
113
+ The keys an export embeds, and the ones `GET /v1/verification-keys` serves,
114
+ come from the Server's database, so a key written into the database alone
115
+ would verify against them. `--trust-anchor` takes the SPKI digest of a vault
116
+ key you took out of band (the installer prints the first vault key's) and walks
117
+ the signed key statements the export carries from it:
118
+
119
+ - `PASS` means the chain verifies, every key is linked to your anchor, and at
120
+ least one signature verified under an anchored key.
121
+ - `VERIFIED, NOT ANCHORED` means nothing failed, but it is not a trusted
122
+ verdict. Either no `--trust-anchor` was given, so nothing links the keys to
123
+ one you trust (`keyTrust.status` is `no_anchor`), or the anchor was walked
124
+ but no signature verified under a key it anchors, as for an export of
125
+ unsigned history (`no_anchored_signature`). It exits 0, and `--json` output
126
+ carries `verdict: "unanchored"` for both. Treat it as unverified
127
+ provenance, not as a clean pass.
128
+ - `FAIL` exits 1. An entry signed by a key the walk does not reach is
129
+ `CHAIN_SIGNING_KEY_UNANCHORED`; a key statement that does not hold is
130
+ `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`.
131
+ Those are listed under `keyTrust.findings`, and are `brokenAt` at position 0
132
+ only when the chain itself is intact; when the chain also breaks, `brokenAt`
133
+ is the chain failure.
134
+
135
+ `--distrusted-key sha256:<digest>[@<RFC 3339 instant>]` mirrors the operator's
136
+ `VAULT_DISTRUSTED_KEYS` and needs `--trust-anchor`: what such a key signed from
137
+ that instant counts for nothing, and a key statement it signed counts for
138
+ nothing at any instant, because the write times an export carries are not
139
+ signed. A dated `--distrusted-key` may name a key also given to
140
+ `--trust-anchor`, as the Server's key-compromise runbook does: the pin then
141
+ vouches for what the key signed before the instant. An export accounts for
142
+ nothing a distrusted key signed; such entries fail here, and only a full dump
143
+ verified with `@agledger/verify` lists them as accounted for. An API 2.0
144
+ export lists a key the Server's `VAULT_DISTRUSTED_KEYS` names with
145
+ `distrustedFrom`, the entry's instant, and where that instant is earlier than
146
+ the retirement the key's closures sign, lists the key retired at it. A run
147
+ not given the same entry still fails `CHAIN_KEY_WINDOW_DRIFT` on that window
148
+ (`KEY_CLOSURE_INVALID` where no closure retires the key), but the finding names
149
+ the entry, as `--distrusted-key sha256:<digest>@<distrustedFrom>`, and says so
150
+ when the entry you gave carries another instant; one at an earlier instant
151
+ draws no finding on the window and is a `Key note:`, though entries the key
152
+ signed after that instant still fail. The listing is the Server's unsigned word, so confirm the instant
153
+ with its operator before passing that entry. Findings and notes name the flags
154
+ in human and `--json` output alike. `--keys <file>` supplies
155
+ keys (a saved `GET /v1/verification-keys` response works as is, and its
156
+ statements are walked too), `--require-supplied-keys` refuses the export's
157
+ embedded keys, and `--agent-keys <file>` re-verifies the agent signatures an
158
+ OIDC cert sealed on the chain. `--trust-anchor` and `--distrusted-key` are
159
+ given once per key. A malformed value, a distrusted key named twice,
160
+ `--distrusted-key` without `--trust-anchor`, a pinned key distrusted with no
161
+ instant (the Server refuses to start with that pair), and a
162
+ file that does not exist are each a usage error (exit 2), refused before the
163
+ export is read. A `--keys` file whose shape or key window (RFC 3339) is wrong
164
+ is `INVALID_FIELD`, exit 2. The flags,
165
+ these refusals and their messages, the headline words and the exit codes are
166
+ the same as `@agledger/verify`'s `agledger-verify` and the Python
167
+ `agledger-verify`'s, and `--json` output carries their `verdict` (`trusted`,
168
+ `unanchored` or `failed`).
169
+
91
170
  ## Agent-native DX
92
171
 
93
172
  - `--json` on every command (auto when stdout is piped)
94
173
  - `--quiet` suppresses output (exit code only)
95
174
  - `--dry-run` on `agledger api` shows the request without sending
175
+ - `--verbose` on every command reports which credential was used, and each OIDC cert exchange, as JSON lines on stderr; it never prints a key, token or cert. A POST also reports the `Idempotency-Key` it goes out under (`{"event":"request",...}`)
96
176
  - `--paginate` on GET follows cursor pagination and streams NDJSON
97
- - 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
98
- - Structured errors on stderr: `{error: true, code, message, suggestion, ...}`; API errors pass through verbatim
177
+ - 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
178
+ - 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`
99
179
  - 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.
100
180
  - `NO_COLOR` supported per [no-color.org](https://no-color.org)
101
181
 
@@ -114,11 +194,11 @@ agledger api GET /openapi.json # Full API route catalog
114
194
  |---|---|
115
195
  | `api` | Call any API endpoint |
116
196
  | `discover` | Health + identity + scopes + quickstart |
117
- | `login` | Verify API key, store in `~/.agledger/config.json` (0600) |
118
- | `logout` | Remove profile(s) |
119
- | `auth` | Check current login state (exit 0 either way) |
197
+ | `login` | Verify an API key (or, with `--oidc`, an OIDC token source) and store it in `~/.agledger/config.json` (0600) |
198
+ | `logout` | Remove the active profile, the one named by `--profile`, or all of them with `--all`; exits 2 `MISSING_INPUT` when there is no such profile to remove. Removing the active profile leaves none active (`activeProfile: null` in the output): pick another with `config use` |
199
+ | `auth` | Check current login state and show the identity, including the OIDC cert (exit 0 when nothing is configured) |
120
200
  | `config` | `list` / `get` / `use <profile>` / `path` |
121
- | `verify` | Offline audit export verification (COSE_Sign1, RFC 9052; Ed25519 or ES256; no network) |
201
+ | `verify` | Offline audit export verification (COSE_Sign1, RFC 9052; Ed25519 or ES256; no network). `--trust-anchor sha256:<digest>` anchors the keys to one you pinned; see [Verifying an export offline](#verifying-an-export-offline) |
122
202
  | `docs` | Fetch the API's agent-oriented narrative (`llms.txt` / `--full`) |
123
203
  | `list-commands` | Inventory (this list) |
124
204
  | `help-json` | Per-command schema |
@@ -127,7 +207,7 @@ agledger api GET /openapi.json # Full API route catalog
127
207
 
128
208
  ```bash
129
209
  # Verifies the key against the API, then stores it under ~/.agledger/config.json (0600)
130
- agledger login --api-key agl_adm_... --profile prod
210
+ agledger login --api-url https://your-agledger-instance --api-key agl_agt_... --profile prod
131
211
 
132
212
  # Switch the active profile; subsequent commands use its key automatically
133
213
  agledger config use prod
@@ -139,12 +219,78 @@ agledger api GET /v1/records --profile prod
139
219
  AGLEDGER_API_KEY=... AGLEDGER_API_URL=... agledger api GET /v1/records
140
220
  ```
141
221
 
222
+ ### OIDC: no stored secret
223
+
224
+ An agent can authenticate with a token from your own identity provider instead
225
+ of an API key. The CLI runs a token source you name, exchanges the token at
226
+ `POST /v1/auth/oidc/cert` for a short-lived cert the Server signs, and sends
227
+ that cert as the bearer. Your operator first registers the IdP as a trusted
228
+ issuer on the Server.
229
+
230
+ **The token decides which agent the cert binds to**, never the CLI. An
231
+ administrator binds an agent to the token's identity in one of two ways:
232
+ `PATCH /v1/agents/{id}` with `oidcIss` and `oidcSub` (the token's issuer and
233
+ subject), or a `claimMapping` of `agent_id` on the trusted issuer, which reads
234
+ the agent id from a claim in the token. An issuer that auto-provisions agents
235
+ creates one for an unbound subject instead. A token that binds no agent is
236
+ refused, and the Server's `recoveryHint` says which binding is missing. A
237
+ token bound to a federation shadow agent (one listed at `GET /v1/peer-agents`)
238
+ is refused with 403 `SHADOW_AGENT_CERT_FORBIDDEN`: that agent authenticates on
239
+ its own Server.
240
+
241
+ | Variable | What it holds |
242
+ |---|---|
243
+ | `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 |
244
+ | `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 |
245
+ | `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 |
246
+
247
+ ```bash
248
+ unset AGLEDGER_API_KEY # an API key outranks a token source
249
+ export AGLEDGER_API_URL=https://your-agledger-instance
250
+ export AGLEDGER_OIDC_TOKEN_CMD='gcloud auth print-identity-token --audiences=agledger'
251
+
252
+ # Shows the account and the cert the Server issued: agent, issuer, subject, scopes, expiry
253
+ agledger auth
254
+
255
+ # Every call now exchanges a fresh token for a cert; nothing is written to disk
256
+ agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary='nightly reconciliation'
257
+
258
+ # Or store the token source (never a token) in a profile
259
+ agledger login --oidc --oidc-token-cmd 'gcloud auth print-identity-token --audiences=agledger' --profile work
260
+ ```
261
+
262
+ What the CLI does with it:
263
+
264
+ - **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.
265
+ - **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.
266
+ - **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.
267
+ - **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.
268
+ - **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`.
269
+ - **`--verbose`** prints which credential a command used and each exchange (cert id, agent, subject, expiry) as JSON lines on stderr. It never prints a key, token or cert.
270
+
271
+ ### Working on behalf of someone
272
+
273
+ When the work is done for a person or another party rather than for the agent itself, give the CLI the RFC 8693 delegation token your IdP's token exchange issued (it must carry an `act` claim naming the agent). The CLI sends it as `AGLedger-On-Behalf-Of` on every POST, beside its own credential, and the Server seals the delegation into the signed chain entry: `bound` when the CLI authenticates through an OIDC cert whose subject is the token's `act`, `unbound` on an API key.
274
+
275
+ | Variable | What it holds |
276
+ |---|---|
277
+ | `AGLEDGER_ON_BEHALF_OF_CMD` | A shell command whose stdout is the delegation token |
278
+ | `AGLEDGER_ON_BEHALF_OF_FILE` | A file holding the delegation token |
279
+
280
+ The command wins over the file. The Server never deduplicates a delegation token, so one is reused until shortly before its `exp` and then read again; one with no `exp` is read again for every request, and one already expired is refused before it is sent. If the Server refuses the delegation token, the source is read once more and the request retried. It never appears in output, errors or `--verbose`, which names only the variable in use.
281
+
282
+ ```bash
283
+ export AGLEDGER_ON_BEHALF_OF_CMD='your-idp-token-exchange --subject alice@example.com --actor my-agent'
284
+ agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary='expense report for alice'
285
+ ```
286
+
142
287
  **Credential precedence** (highest first), applied per command:
143
288
 
144
- - **API key:** `--api-key` flag → `AGLEDGER_API_KEY` env → stored profile (`--profile <name>`, else the active profile).
145
- - **API URL:** `--api-url` flag → `AGLEDGER_API_URL` env → stored profile URL. There is no default: AGLedger is self-hosted, so a call with no URL from any of those three sources exits 2 with `CONFIG_ERROR` rather than guessing a host.
289
+ - **Credential:** `--api-key` flag → `AGLEDGER_API_KEY` env → `AGLEDGER_OIDC_TOKEN_CMD` → `AGLEDGER_OIDC_TOKEN_FILE` → stored profile (`--profile <name>`, else the active profile), whose API key or OIDC token source is used. `AGLEDGER_OIDC_AGENT_ID` overrides a profile's stored agent id (an assertion, as above).
290
+ - **Timeout:** `AGLEDGER_TIMEOUT`, in seconds (default 30), is how long each API response is awaited. It must be a positive number up to 2147483, or the call exits 2 `CONFIG_ERROR` naming the variable. A POST that times out may still have been applied: see the `idempotencyKey` its `TIMEOUT` error carries, above.
291
+ - **API URL:** `--api-url` flag → `AGLEDGER_API_URL` env → stored profile URL. There is no default: AGLedger is self-hosted, so a call with no URL from any of those three sources exits 2 with `CONFIG_ERROR` rather than guessing a host. A URL that is not an absolute `http` or `https` URL (`not-a-url`, or `localhost:3000` with no scheme) also exits 2 with `CONFIG_ERROR`, naming where it came from. The URL is checked before the credential, so a call with neither exits 2 `CONFIG_ERROR`, not 3 `AUTH_REQUIRED`. The one check that comes earlier is a `--profile` naming no stored profile, which exits 3 `AUTH_REQUIRED` and says the profile was not found, on every command but `login`, whose `--profile` names the profile it writes.
146
292
 
147
- So once you `agledger login`, plain `agledger api ...` calls authenticate from the stored profile with no flags or env. `--dry-run` echoes the resolved auth (URL, source, masked key) so you can confirm which credentials a call would use without sending it; when no URL is configured it reports `apiUrl: null` and names the error the real call would raise.
293
+ So once you `agledger login`, plain `agledger api ...` calls authenticate from the stored profile with no flags or env. `--dry-run` echoes the resolved auth (URL, source, masked key, or the name of the OIDC token source, which it does not run) so you can confirm which credentials a call would use without sending it; when no URL is configured it reports `apiUrl: null` and names the error the real call would raise.
148
294
 
149
295
  Agent keys (`agl_agt_*`) and admin keys (`agl_adm_*`) are both accepted; the API routes them appropriately.
150
296
 
package/SKILL.md CHANGED
@@ -3,9 +3,11 @@
3
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.
4
4
 
5
5
  ## Setup
6
- Credentials resolve per command with this precedence: `--api-key` flag > `AGLEDGER_API_KEY` env > stored profile (after `agledger login`). API URL: `--api-url` flag > `AGLEDGER_API_URL` env > stored profile URL.
6
+ 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.
7
7
 
8
- **There is no default API URL, and it is not optional.** AGLedger is self-hosted, so the CLI has no server to guess. If none of those three sources supplies one, the command exits 2 with `CONFIG_ERROR` rather than calling a placeholder host.
8
+ OIDC instead of an API key: set `AGLEDGER_OIDC_TOKEN_CMD` to a command that prints an OIDC JWT from your identity provider, or `AGLEDGER_OIDC_TOKEN_FILE` to a file holding one (optional `AGLEDGER_OIDC_AGENT_ID`, an assertion only: the token decides the agent, and a different id, or any id on a token bound to no agent, is 403 `CERT_AGENT_BINDING_MISMATCH`; bind the agent with `PATCH /v1/agents/{id}` and `oidcIss`/`oidcSub`, or `claimMapping.agent_id` on the trusted issuer). The CLI exchanges a fresh token for a short-lived cert on each invocation, signs request bodies with a key held only in memory, and re-exchanges on expiry or a 401. `agledger auth` shows the cert identity; `--verbose` names the credential source on stderr. Failures: `OIDC_TOKEN_SOURCE_FAILED` (exit 3, names the variable, carries the command's stderr) and `OIDC_EXCHANGE_FAILED` (forwards the Server error and its `recoveryHint`).
9
+
10
+ **There is no default API URL, and it is not optional.** AGLedger is self-hosted, so the CLI has no server to guess. If none of those three sources supplies one, or the one it supplies is not an absolute `http(s)` URL, the command exits 2 with `CONFIG_ERROR` rather than calling a placeholder host. The URL is checked before the credential.
9
11
 
10
12
  ## Primary command: `agledger api`
11
13
  Call any API endpoint:
@@ -35,16 +37,18 @@ agledger api <METHOD> <PATH> [--data JSON | --input FILE | -F key=value | -f key
35
37
  - `agledger api GET /openapi.json`: full API route catalog
36
38
 
37
39
  ## Offline audit verification
38
- - `agledger verify <audit-export.json>`: verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network, no API key. Exit 0 if valid, 1 if broken; `--json` for structured output; `--keys <file>` supplies keys out of band (merged over any embedded in the export); `--require-key-id <id>` rejects exports signed by an unexpected key; `--require-out-of-band-keys` refuses the export's own embedded keys for an independent audit.
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.
41
+
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.
39
43
 
40
44
  **What verification proves:**
41
- - Every entry was signed by a key listed in the export (or supplied via `--keys`) at the moment the vault wrote it.
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`).
42
46
  - Payloads have not been altered since signing (SHA-256 recomputation matches the stored `payload_hash` over the signed COSE_Sign1 bytes).
43
47
  - The hash chain is contiguous: no entries were inserted, removed, or reordered between positions.
44
- - On failure, `brokenAt.code` is a canonical SCREAMING_SNAKE failure code (e.g. `CHAIN_HASH_MISMATCH`, `CHAIN_SIGNATURE_INVALID`).
48
+ - 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.
45
49
 
46
50
  **What verification does NOT prove:**
47
- - That the signing key is *legitimate*. Obtain the key out of band from `/.well-known/scitt-keys` on the issuing instance (or the `/v1/verification-keys` API) and pass it via `--keys --require-out-of-band-keys`.
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.
48
52
  - That the export is *complete*. A vault operator can still truncate the export at either end.
49
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.
50
54
 
@@ -53,12 +57,13 @@ agledger api <METHOD> <PATH> [--data JSON | --input FILE | -F key=value | -f key
53
57
  - `--quiet` for exit-code-only operation
54
58
  - `--dry-run` on `agledger api` shows the request without sending
55
59
  - `--paginate` on GET follows cursors, streams NDJSON
56
- - Structured errors on stderr: `{code, message, suggestion, ...}`
60
+ - 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`
57
61
  - Semantic exit codes (0-10)
58
62
 
59
63
  ## Credentials
60
64
  - `agledger login --api-key <key> [--profile NAME]`: verifies key, stores in `~/.agledger/config.json` (0600). After login, plain `agledger api ...` calls authenticate from the stored profile (no flag/env needed).
65
+ - `agledger login --oidc --oidc-token-cmd <command> | --oidc-token-file <path> [--oidc-agent-id ID] [--profile NAME]`: stores the source (never a token, cert or key). A command is verified first with one exchange; a file is only checked to hold a JWT, since exchanging it would spend the token until the file rotates.
61
66
  - `agledger config use <profile>`: set the active profile; `agledger api ... --profile NAME` uses a specific one per-invocation.
62
- - `agledger logout [--profile NAME | --all]`
67
+ - `agledger logout [--profile NAME | --all]`: removes the active profile unless `--profile` names another; exits 2 `MISSING_INPUT` when there is no such profile (`--all` with nothing stored included). Removing the active profile leaves none active (`activeProfile: null`); choose another with `config use`
63
68
  - `agledger config list | get | use <profile> | path`
64
- - `agledger auth`: check login state (exit 0 whether logged in or not)
69
+ - `agledger auth`: check login state and identity, including the OIDC cert (exit 0 when nothing is configured)
@@ -1,17 +1,35 @@
1
+ import type { DelegationToken, OidcCertCredential } from './oidc.js';
1
2
  export interface ApiResponse {
2
3
  status: number;
3
4
  body: unknown;
4
5
  ok: boolean;
5
6
  }
7
+ /**
8
+ * Which credential a 401 is about, read from the Server's error body.
9
+ *
10
+ * - A delegation token the Server refused names the header or the delegation
11
+ * (`AGLedger-On-Behalf-Of: ...`, `Delegation token could not be validated`).
12
+ * - A body signature it refused names `X-Agent-Signature`.
13
+ * - Anything else is about the bearer itself.
14
+ */
15
+ export declare function classify401(body: unknown): 'delegation' | 'agent-signature' | 'bearer';
6
16
  export declare class ApiClient {
7
17
  private readonly apiUrl;
8
- /** Null sends no Authorization header: the Server's discovery surfaces
9
- * (/health, /llms.txt, /openapi.json, /v1/conformance) answer unauthenticated,
10
- * and an agent holding only a URL must be able to reach them. */
11
- private readonly apiKey;
18
+ /** An API key, an OIDC cert credential, or null. Null sends no
19
+ * Authorization header: the Server's discovery surfaces (/health, /llms.txt,
20
+ * /openapi.json, /v1/conformance) answer unauthenticated, and an agent
21
+ * holding only a URL must be able to reach them. */
22
+ private readonly auth;
12
23
  private readonly userAgent;
13
24
  private readonly timeoutMs;
14
- constructor(apiUrl: string, apiKey: string | null, version?: string, timeoutMs?: number);
25
+ /** Sent as `AGLedger-On-Behalf-Of` on POST. Every route that declares the
26
+ * header is a POST, and the Server ignores it on routes that do not. */
27
+ private readonly onBehalfOf;
28
+ constructor(apiUrl: string, auth: string | OidcCertCredential | null, version?: string, timeoutMs?: number, onBehalfOf?: DelegationToken | null);
29
+ /** True when requests go out with no Authorization header. */
30
+ get isAnonymous(): boolean;
31
+ /** The OIDC credential in use, if any, so `auth` can show the cert identity. */
32
+ get credential(): OidcCertCredential | null;
15
33
  /** The base URL requests go to. Surfaced so a network failure can name the
16
34
  * host it actually tried instead of a bare "fetch failed". */
17
35
  get baseUrl(): string;
@@ -20,4 +38,5 @@ export declare class ApiClient {
20
38
  body?: unknown;
21
39
  idempotencyKey?: string;
22
40
  }): Promise<ApiResponse>;
41
+ private send;
23
42
  }
@@ -32,19 +32,49 @@ function appendQueryParam(search, key, value) {
32
32
  }
33
33
  search.set(key, String(value));
34
34
  }
35
+ /**
36
+ * Which credential a 401 is about, read from the Server's error body.
37
+ *
38
+ * - A delegation token the Server refused names the header or the delegation
39
+ * (`AGLedger-On-Behalf-Of: ...`, `Delegation token could not be validated`).
40
+ * - A body signature it refused names `X-Agent-Signature`.
41
+ * - Anything else is about the bearer itself.
42
+ */
43
+ export function classify401(body) {
44
+ const b = (body ?? {});
45
+ const text = typeof b.detail === 'string' ? b.detail : '';
46
+ if (/x-agent-signature/i.test(text))
47
+ return 'agent-signature';
48
+ if (/on-behalf-of|delegation/i.test(text))
49
+ return 'delegation';
50
+ return 'bearer';
51
+ }
35
52
  export class ApiClient {
36
53
  apiUrl;
37
- /** Null sends no Authorization header: the Server's discovery surfaces
38
- * (/health, /llms.txt, /openapi.json, /v1/conformance) answer unauthenticated,
39
- * and an agent holding only a URL must be able to reach them. */
40
- apiKey;
54
+ /** An API key, an OIDC cert credential, or null. Null sends no
55
+ * Authorization header: the Server's discovery surfaces (/health, /llms.txt,
56
+ * /openapi.json, /v1/conformance) answer unauthenticated, and an agent
57
+ * holding only a URL must be able to reach them. */
58
+ auth;
41
59
  userAgent;
42
60
  timeoutMs;
43
- constructor(apiUrl, apiKey, version = '0.0.0', timeoutMs = 30_000) {
61
+ /** Sent as `AGLedger-On-Behalf-Of` on POST. Every route that declares the
62
+ * header is a POST, and the Server ignores it on routes that do not. */
63
+ onBehalfOf;
64
+ constructor(apiUrl, auth, version = '0.0.0', timeoutMs = 30_000, onBehalfOf = null) {
44
65
  this.apiUrl = apiUrl.replace(/\/+$/, '');
45
- this.apiKey = apiKey;
66
+ this.auth = auth;
46
67
  this.userAgent = `agledger-cli/${version}`;
47
68
  this.timeoutMs = timeoutMs;
69
+ this.onBehalfOf = onBehalfOf;
70
+ }
71
+ /** True when requests go out with no Authorization header. */
72
+ get isAnonymous() {
73
+ return this.auth === null;
74
+ }
75
+ /** The OIDC credential in use, if any, so `auth` can show the cert identity. */
76
+ get credential() {
77
+ return this.auth !== null && typeof this.auth === 'object' ? this.auth : null;
48
78
  }
49
79
  /** The base URL requests go to. Surfaced so a network failure can name the
50
80
  * host it actually tried instead of a bare "fetch failed". */
@@ -70,14 +100,14 @@ export class ApiClient {
70
100
  }
71
101
  }
72
102
  }
103
+ // Serialized once: with a cert credential the agent signature covers these
104
+ // exact bytes, so the body that is hashed must be the body that is sent.
105
+ const body = options?.body !== undefined ? JSON.stringify(options.body) : undefined;
73
106
  const headers = {
74
107
  Accept: 'application/json',
75
108
  'User-Agent': this.userAgent,
76
109
  };
77
- if (this.apiKey !== null) {
78
- headers.Authorization = `Bearer ${this.apiKey}`;
79
- }
80
- if (options?.body !== undefined) {
110
+ if (body !== undefined) {
81
111
  headers['Content-Type'] = 'application/json';
82
112
  }
83
113
  // POST is the only method the API arms for idempotency: all 18 routes that
@@ -85,28 +115,67 @@ export class ApiClient {
85
115
  // ignored. A generated key makes the CLI's own writes replay-safe by default;
86
116
  // a caller retrying the same logical operation across processes passes its
87
117
  // own key so the second attempt dedups instead of creating a second record.
88
- if (method.toUpperCase() === 'POST') {
118
+ const isPost = method.toUpperCase() === 'POST';
119
+ if (isPost) {
89
120
  headers['Idempotency-Key'] = options?.idempotencyKey ?? crypto.randomUUID();
90
121
  }
122
+ const delegation = isPost ? this.onBehalfOf : null;
123
+ if (delegation)
124
+ headers['AGLedger-On-Behalf-Of'] = await delegation.get();
125
+ const credential = this.credential;
126
+ if (typeof this.auth === 'string') {
127
+ headers.Authorization = `Bearer ${this.auth}`;
128
+ }
129
+ if (credential && body !== undefined) {
130
+ Object.assign(headers, credential.signBody(body));
131
+ }
132
+ const bearer = credential ? await credential.getToken(this.apiUrl) : null;
133
+ const withBearer = (token) => (token ? { ...headers, Authorization: `Bearer ${token}` } : headers);
134
+ const first = await this.send(url, method, withBearer(bearer), body);
135
+ if (first.status !== 401)
136
+ return first;
137
+ // One retry at most, and only when something the CLI holds can be renewed.
138
+ // The retry reuses the Idempotency-Key: a 401 means nothing was processed.
139
+ switch (classify401(first.body)) {
140
+ case 'agent-signature':
141
+ // The key did not change, so re-sending the same signature cannot help.
142
+ return first;
143
+ case 'delegation': {
144
+ if (!delegation)
145
+ return first;
146
+ const token = await delegation.get(true);
147
+ return this.send(url, method, { ...withBearer(bearer), 'AGLedger-On-Behalf-Of': token }, body);
148
+ }
149
+ case 'bearer': {
150
+ // A cert the Server stops accepting (expired, revoked, clock skew) gets
151
+ // one re-exchange. A second 401 is reported as it came.
152
+ if (!credential || !bearer)
153
+ return first;
154
+ const renewed = await credential.getToken(this.apiUrl, bearer);
155
+ return this.send(url, method, withBearer(renewed), body);
156
+ }
157
+ }
158
+ }
159
+ async send(url, method, headers, body) {
91
160
  const controller = new AbortController();
92
161
  const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
93
162
  try {
94
163
  const res = await fetch(url.toString(), {
95
164
  method,
96
165
  headers,
97
- body: options?.body !== undefined ? JSON.stringify(options.body) : undefined,
166
+ body,
98
167
  signal: controller.signal,
99
168
  });
100
169
  const contentType = res.headers.get('content-type') ?? '';
101
- let body;
170
+ let resBody;
102
171
  if (contentType.includes('json')) {
103
- body = await res.json();
172
+ resBody = await res.json();
104
173
  }
105
174
  else {
106
175
  const text = await res.text();
107
- body = { _raw: text, _contentType: contentType };
176
+ resBody = { _raw: text, _contentType: contentType };
108
177
  }
109
- return { status: res.status, body, ok: res.ok };
178
+ return { status: res.status, body: resBody, ok: res.ok };
110
179
  }
111
180
  finally {
112
181
  clearTimeout(timeout);