@agledger/cli 1.4.0 → 1.5.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
 
@@ -84,8 +81,9 @@ cause of action accrues, to the maximum extent permitted by applicable law.
84
81
 
85
82
  6. EXPORT COMPLIANCE
86
83
 
87
- The Software may include cryptographic functionality (including Ed25519, AES-
88
- 256-GCM, SHA-256, and X25519). AGLedger LLC classifies the Software under
84
+ The Software may include cryptographic functionality, including Ed25519
85
+ (EdDSA), ECDSA using curve P-256 with SHA-256, HMAC-SHA-256, AES-256-GCM,
86
+ HKDF-SHA-256, and SHA-256. AGLedger LLC classifies the Software under
89
87
  ECCN 5D002 in good faith. To the extent AGLedger LLC makes the source code of
90
88
  the Software publicly available through a public repository, that source code
91
89
  is subject to the treatment afforded under 15 CFR § 742.15(b) of the U.S.
@@ -102,14 +100,13 @@ or trade-control laws.
102
100
 
103
101
  7. TRADEMARKS
104
102
 
105
- AGLedger is a trademark of AGLedger LLC, and Settlement Signal is a pending
106
- trademark of AGLedger LLC. All other trademarks are the property of their
107
- respective owners.
103
+ AGLedger and Settlement Signal are trademarks of AGLedger LLC. All other
104
+ trademarks are the property of their respective owners.
108
105
 
109
106
  8. PATENTS
110
107
 
111
- The Software is covered by one or more U.S. patent applications pending before
112
- 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.
113
110
 
114
111
  9. RELATIONSHIP TO OTHER AGLEDGER AGREEMENTS
115
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
@@ -93,6 +101,7 @@ signed and immutable, with an identifier no other system will match.
93
101
  - `--json` on every command (auto when stdout is piped)
94
102
  - `--quiet` suppresses output (exit code only)
95
103
  - `--dry-run` on `agledger api` shows the request without sending
104
+ - `--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
96
105
  - `--paginate` on GET follows cursor pagination and streams NDJSON
97
106
  - 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
107
  - Structured errors on stderr: `{error: true, code, message, suggestion, ...}`; API errors pass through verbatim
@@ -114,11 +123,11 @@ agledger api GET /openapi.json # Full API route catalog
114
123
  |---|---|
115
124
  | `api` | Call any API endpoint |
116
125
  | `discover` | Health + identity + scopes + quickstart |
117
- | `login` | Verify API key, store in `~/.agledger/config.json` (0600) |
126
+ | `login` | Verify an API key (or, with `--oidc`, an OIDC token source) and store it in `~/.agledger/config.json` (0600) |
118
127
  | `logout` | Remove profile(s) |
119
- | `auth` | Check current login state (exit 0 either way) |
128
+ | `auth` | Check current login state and show the identity, including the OIDC cert (exit 0 when nothing is configured) |
120
129
  | `config` | `list` / `get` / `use <profile>` / `path` |
121
- | `verify` | Offline audit export verification (COSE_Sign1, RFC 9052; Ed25519 or ES256; no network) |
130
+ | `verify` | Offline audit export verification (COSE_Sign1, RFC 9052; Ed25519 or ES256; no network). `--agent-keys <file>` re-verifies the agent signatures sealed on the chain against the cert keys you supply |
122
131
  | `docs` | Fetch the API's agent-oriented narrative (`llms.txt` / `--full`) |
123
132
  | `list-commands` | Inventory (this list) |
124
133
  | `help-json` | Per-command schema |
@@ -127,7 +136,7 @@ agledger api GET /openapi.json # Full API route catalog
127
136
 
128
137
  ```bash
129
138
  # Verifies the key against the API, then stores it under ~/.agledger/config.json (0600)
130
- agledger login --api-key agl_adm_... --profile prod
139
+ agledger login --api-url https://your-agledger-instance --api-key agl_agt_... --profile prod
131
140
 
132
141
  # Switch the active profile; subsequent commands use its key automatically
133
142
  agledger config use prod
@@ -139,12 +148,66 @@ agledger api GET /v1/records --profile prod
139
148
  AGLEDGER_API_KEY=... AGLEDGER_API_URL=... agledger api GET /v1/records
140
149
  ```
141
150
 
151
+ ### OIDC: no stored secret
152
+
153
+ An agent can authenticate with a token from your own identity provider instead
154
+ of an API key. The CLI runs a token source you name, exchanges the token at
155
+ `POST /v1/auth/oidc/cert` for a short-lived cert the Server signs, and sends
156
+ that cert as the bearer. Your operator first registers the IdP as a trusted
157
+ issuer on the Server.
158
+
159
+ | Variable | What it holds |
160
+ |---|---|
161
+ | `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 |
162
+ | `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 |
163
+ | `AGLEDGER_OIDC_AGENT_ID` | Optional. The agent the cert binds to, when the token does not map to one itself |
164
+
165
+ ```bash
166
+ unset AGLEDGER_API_KEY # an API key outranks a token source
167
+ export AGLEDGER_API_URL=https://your-agledger-instance
168
+ export AGLEDGER_OIDC_TOKEN_CMD='gcloud auth print-identity-token --audiences=agledger'
169
+
170
+ # Shows the account and the cert the Server issued: agent, issuer, subject, scopes, expiry
171
+ agledger auth
172
+
173
+ # Every call now exchanges a fresh token for a cert; nothing is written to disk
174
+ agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary='nightly reconciliation'
175
+
176
+ # Or store the token source (never a token) in a profile
177
+ agledger login --oidc --oidc-token-cmd 'gcloud auth print-identity-token --audiences=agledger' --profile work
178
+ ```
179
+
180
+ What the CLI does with it:
181
+
182
+ - **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.
183
+ - **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.
184
+ - **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.
185
+ - **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.
186
+ - **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`.
187
+ - **`--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.
188
+
189
+ ### Working on behalf of someone
190
+
191
+ 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.
192
+
193
+ | Variable | What it holds |
194
+ |---|---|
195
+ | `AGLEDGER_ON_BEHALF_OF_CMD` | A shell command whose stdout is the delegation token |
196
+ | `AGLEDGER_ON_BEHALF_OF_FILE` | A file holding the delegation token |
197
+
198
+ 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.
199
+
200
+ ```bash
201
+ export AGLEDGER_ON_BEHALF_OF_CMD='your-idp-token-exchange --subject alice@example.com --actor my-agent'
202
+ agledger api POST /v1/records -F type=notarize-generic-v1 -F criteria.summary='expense report for alice'
203
+ ```
204
+
142
205
  **Credential precedence** (highest first), applied per command:
143
206
 
144
- - **API key:** `--api-key` flag → `AGLEDGER_API_KEY` env → stored profile (`--profile <name>`, else the active profile).
207
+ - **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.
145
208
  - **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.
146
209
 
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.
210
+ 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
211
 
149
212
  Agent keys (`agl_agt_*`) and admin keys (`agl_adm_*`) are both accepted; the API routes them appropriately.
150
213
 
package/SKILL.md CHANGED
@@ -3,7 +3,9 @@
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
+
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`). 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`).
7
9
 
8
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, the command exits 2 with `CONFIG_ERROR` rather than calling a placeholder host.
9
11
 
@@ -58,7 +60,8 @@ agledger api <METHOD> <PATH> [--data JSON | --input FILE | -F key=value | -f key
58
60
 
59
61
  ## Credentials
60
62
  - `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).
63
+ - `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
64
  - `agledger config use <profile>`: set the active profile; `agledger api ... --profile NAME` uses a specific one per-invocation.
62
65
  - `agledger logout [--profile NAME | --all]`
63
66
  - `agledger config list | get | use <profile> | path`
64
- - `agledger auth`: check login state (exit 0 whether logged in or not)
67
+ - `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 = [b.message, b.detail].filter((v) => typeof v === 'string').join(' ');
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);
package/dist/base.d.ts CHANGED
@@ -11,6 +11,8 @@
11
11
  import { Command } from '@oclif/core';
12
12
  import { ApiClient } from './api-client.js';
13
13
  import type { ApiResponse } from './api-client.js';
14
+ import { OidcCertCredential, type OidcTokenSource } from './oidc.js';
15
+ import { type Profile } from './util/config.js';
14
16
  /** Semantic exit codes for agent consumption. Stable across releases. */
15
17
  export declare const ExitCode: {
16
18
  readonly SUCCESS: 0;
@@ -32,6 +34,10 @@ export declare const ExitCode: {
32
34
  */
33
35
  export declare const ErrorCode: {
34
36
  readonly AUTH_REQUIRED: 'AUTH_REQUIRED';
37
+ /** The OIDC token command or file could not produce a token. */
38
+ readonly OIDC_TOKEN_SOURCE_FAILED: 'OIDC_TOKEN_SOURCE_FAILED';
39
+ /** The Server refused `POST /v1/auth/oidc/cert`; its error body rides along as `apiError`. */
40
+ readonly OIDC_EXCHANGE_FAILED: 'OIDC_EXCHANGE_FAILED';
35
41
  /** Required configuration (currently the API URL) is absent. Exits as a
36
42
  * usage error rather than claiming a new exit code. */
37
43
  readonly CONFIG_ERROR: 'CONFIG_ERROR';
@@ -46,65 +52,113 @@ export declare const ErrorCode: {
46
52
  readonly NETWORK_ERROR: 'NETWORK_ERROR';
47
53
  readonly UNKNOWN_ERROR: 'UNKNOWN_ERROR';
48
54
  };
55
+ type AuthFlags = {
56
+ 'api-key'?: string;
57
+ 'api-url'?: string;
58
+ profile?: string;
59
+ verbose?: boolean;
60
+ };
61
+ /** Where a command's credential comes from. Never holds a cert or a private key. */
62
+ export type ResolvedCredential = {
63
+ kind: 'api-key';
64
+ key: string;
65
+ from: 'flag-or-env' | 'profile';
66
+ origin: string;
67
+ } | {
68
+ kind: 'oidc';
69
+ source: OidcTokenSource;
70
+ agentId?: string;
71
+ from: 'env' | 'profile';
72
+ } | {
73
+ kind: 'none';
74
+ };
75
+ /** The OIDC token source stored on a profile, if it has one. */
76
+ export declare function profileOidcSource(name: string, profile: Profile | undefined): OidcTokenSource | undefined;
77
+ /** The OIDC token source named by the environment: the command outranks the file. */
78
+ export declare function envOidcSource(): OidcTokenSource | undefined;
79
+ /** The delegation token source from the environment. The command wins over the file. */
80
+ export declare function envOnBehalfOfSource(): OidcTokenSource | undefined;
81
+ /** Whether a flag was passed on the command line (`--flag value` or `--flag=value`),
82
+ * as opposed to reaching oclif through its `env` binding. */
83
+ export declare function argvHasFlag(flag: string): boolean;
49
84
  export declare abstract class BaseCommand extends Command {
50
85
  /** The URL the most recent client was built for, so a network failure can
51
86
  * name the host it actually tried. */
52
87
  private lastApiUrl?;
88
+ /** The client `callApi` built for this invocation, reused by every later call. */
89
+ private client?;
53
90
  static baseFlags: {
54
91
  json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
55
92
  quiet: import("@oclif/core/interfaces").BooleanFlag<boolean>;
56
93
  'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
57
94
  'api-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
58
95
  profile: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
96
+ verbose: import("@oclif/core/interfaces").BooleanFlag<boolean>;
59
97
  };
60
98
  protected get isJson(): boolean;
61
99
  protected get isQuiet(): boolean;
100
+ /** Write one diagnostic line to stderr under --verbose. Callers pass no secrets. */
101
+ protected verboseLog(flags: {
102
+ verbose?: boolean;
103
+ }, event: Record<string, unknown>): void;
62
104
  /**
63
- * Resolve credentials and build the API client.
105
+ * Resolve which credential a command uses, without calling anything.
64
106
  *
65
- * Precedence:
66
- * API key: `--api-key` flag > `AGLEDGER_API_KEY` env > stored profile.
67
- * API URL: `--api-url` flag > `AGLEDGER_API_URL` env > stored profile url.
68
- * There is no default; AGLedger is self-hosted.
107
+ * Precedence, highest first:
108
+ * 1. An API key from `--api-key` or `AGLEDGER_API_KEY` (oclif merges the
109
+ * two into `flags['api-key']`).
110
+ * 2. `AGLEDGER_OIDC_TOKEN_CMD`, then `AGLEDGER_OIDC_TOKEN_FILE`.
111
+ * 3. The selected profile (`--profile <name>`, else the active one): its
112
+ * API key, or the OIDC token source `agledger login --oidc` stored.
69
113
  *
70
- * oclif merges the flag and its `env` source into `flags['api-key']` /
71
- * `flags['api-url']`, so a present value there already represents flag-or-env
72
- * (both of which outrank the profile). When absent, fall back to the selected
73
- * profile (`--profile <name>`, else the active profile) in ~/.agledger/config.json.
114
+ * Explicit per-invocation sources outrank stored ones, which is the rule the
115
+ * API key already followed. `AGLEDGER_OIDC_AGENT_ID` overrides a profile's
116
+ * stored agent id.
74
117
  */
75
- protected createApiClient(flags: {
76
- 'api-key'?: string;
77
- 'api-url'?: string;
78
- profile?: string;
79
- }, options?: {
118
+ protected resolveCredential(flags: AuthFlags): {
119
+ credential: ResolvedCredential;
120
+ profileName?: string;
121
+ profile?: Profile;
122
+ };
123
+ /**
124
+ * Resolve credentials and build the API client.
125
+ *
126
+ * Credential precedence is `resolveCredential`'s. API URL: `--api-url` flag >
127
+ * `AGLEDGER_API_URL` env > stored profile url. There is no default;
128
+ * AGLedger is self-hosted.
129
+ */
130
+ protected createApiClient(flags: AuthFlags, options?: {
80
131
  allowAnonymous?: boolean;
81
132
  }): ApiClient;
133
+ /** Build a cert credential for one invocation. Its key pair never leaves memory. */
134
+ protected oidcCredential(flags: {
135
+ verbose?: boolean;
136
+ }, credential: {
137
+ source: OidcTokenSource;
138
+ agentId?: string;
139
+ }): OidcCertCredential;
140
+ /** A secret-free description of a credential, for --verbose, --dry-run and `auth`. */
141
+ protected describeCredential(credential: ResolvedCredential): Record<string, unknown>;
82
142
  /**
83
143
  * Resolve the credentials that an actual call would use, for --dry-run display.
84
- * Same precedence as `createApiClient` (flag > env > profile), but the key is
85
- * masked so it is safe to print. Returns the resolved api URL and which source
86
- * the key came from. Does not throw on a missing key (dry-run is non-fatal).
144
+ * Same precedence as `createApiClient`, but the key is masked so it is safe
145
+ * to print, and an OIDC token source is named, never run. Does not throw on
146
+ * a missing credential (dry-run is non-fatal).
87
147
  */
88
- protected resolvedAuth(flags: {
89
- 'api-key'?: string;
90
- 'api-url'?: string;
91
- profile?: string;
92
- }): {
148
+ protected resolvedAuth(flags: AuthFlags): {
93
149
  apiUrl: string | null;
94
150
  apiUrlSource?: string;
95
151
  apiKey: string | null;
96
- source: 'flag-or-env' | 'profile' | 'none';
152
+ source: 'flag-or-env' | 'env' | 'profile' | 'none';
153
+ credential: 'api-key' | 'oidc-cert' | 'none';
154
+ oidcTokenSource?: string;
97
155
  profile?: string;
98
156
  };
99
157
  /**
100
158
  * Call the API. Path is passed through as-is; caller provides the full path
101
159
  * (e.g. `/v1/records`, `/health`, `/federation/v1/peer`). No auto-prefixing.
102
160
  */
103
- protected callApi(flags: {
104
- 'api-key'?: string;
105
- 'api-url'?: string;
106
- profile?: string;
107
- }, method: string, path: string, options?: {
161
+ protected callApi(flags: AuthFlags, method: string, path: string, options?: {
108
162
  query?: Record<string, unknown>;
109
163
  body?: unknown;
110
164
  idempotencyKey?: string;
@@ -136,3 +190,4 @@ export declare abstract class BaseCommand extends Command {
136
190
  protected handleError(err: unknown): never;
137
191
  private statusToExitCode;
138
192
  }
193
+ export {};