@perpetualsystems/cli 0.0.0-stage → 0.4.0-next-20261110214241

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/README.md CHANGED
@@ -1,3 +1,551 @@
1
- # Temporary Holding Version
1
+ # Perpetual CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/@perpetualsystems/cli.svg)](https://www.npmjs.com/package/@perpetualsystems/cli)
4
+ [![license](https://img.shields.io/badge/license-TBD-blue.svg)](#license)
5
+ [![CI](https://img.shields.io/badge/CI-TBD-lightgrey.svg)](#)
6
+
7
+ > Drive your Perpetual deployment from a terminal, a shell pipeline, or an LLM agent — without writing curl glue.
8
+
9
+ ```sh
10
+ # One-line install (TBD — see Installation for current paths)
11
+ curl -fsSL https://example.com/install-perpetual.sh | sh
12
+ ```
13
+
14
+ ---
15
+
16
+ `perpetual` is a single binary that wraps the entire Perpetual API surface with a structured command tree, three authentication flows, a multi-profile credential store, TTY-aware JSON/text output, and an agent-discovery surface (`perpetual help`, `--robot-status`, `robot-docs guide`) designed for LLMs to use directly.
17
+
18
+ ---
19
+
20
+ ## Quick Example
21
+
22
+ ```sh
23
+ # 1. Log in (browser opens, OAuth completes, token saved)
24
+ perpetual login --endpoint=https://your-endpoint.example.com
25
+
26
+ # 2. Confirm who you are
27
+ perpetual whoami
28
+
29
+ # 3. List the cases you have access to
30
+ perpetual case list
31
+
32
+ # 4. Run a Hamelin query
33
+ perpetual query run --query "FROM simba.signals | AGG count()" --start 2026-10-01T00:00:00Z --end 2026-10-08T00:00:00Z
34
+
35
+ # 5. Render a dashboard's vega-lite panels as PNGs
36
+ perpetual dashboard render-panels DSH_XXXXXXX
37
+
38
+ # 6. Self-diagnose if anything looks broken
39
+ perpetual doctor
40
+ ```
41
+
42
+ Pipe any of the above to `jq` and it switches to JSON automatically — no flag required:
43
+
44
+ ```sh
45
+ perpetual case list | jq '.data[].id'
46
+ ```
47
+
48
+ ---
49
+
50
+ ## Design Philosophy
51
+
52
+ 1. **Humans and agents are first-class peers.** Every command works equally well in a terminal and on the end of a pipe. The CLI auto-detects the caller via `process.stdout.isTTY` and adjusts output, spinners, prompts, and error envelopes accordingly.
53
+ 2. **Silent failure is a bug.** Unknown flags, typo'd subcommands, dangling values, and ambiguous argv shapes all surface as explicit `CliError`s with stable error codes — never silently dropped. The unknown-flag validator, value-position guards, and post-splice typo detection exist so an agent never gets `exit 0` with broken intent.
54
+ 3. **Secrets stay off the wire.** Passwords go through `--password-stdin` / `--password-file` / interactive prompt — never `--password=<pw>` (deprecated, warns). OAuth client secrets live only in `PERPETUAL_CLIENT_SECRET` env, never on disk.
55
+ 4. **One binary, many environments.** Each profile owns one endpoint and its login; `--profile` switches between them per invocation, and env vars mirror every credential flag for non-interactive use.
56
+ 5. **Self-healing over hand-holding.** When something breaks — corrupt profile, stale token, wrong permissions — `perpetual doctor` diagnoses and fixes idempotently rather than dumping a stack trace.
57
+
58
+ ---
59
+
60
+ ## Installation
61
+
62
+ ### Option 1 — Standalone binary (recommended)
63
+
64
+ Download a signed binary from the releases page (TBD — link once published):
65
+
66
+ ```sh
67
+ # macOS / Linux
68
+ curl -fsSL https://example.com/install-perpetual.sh | sh
69
+
70
+ # Or pin a version
71
+ curl -fsSL https://example.com/install-perpetual.sh | sh -s -- --version=0.3.15
72
+ ```
73
+
74
+ The macOS build is codesigned (`bun run dist:sign`).
75
+
76
+ **Internal-only (for now):** while the repo is private, the public installer URL above is a placeholder. Internally, this works:
77
+
78
+ ```sh
79
+ TOKEN=$(gh auth token); curl -fsSL -H "Authorization: Bearer $TOKEN" \
80
+ https://raw.githubusercontent.com/perpetualsystems/typescript-sdk/main/install.sh \
81
+ | GITHUB_TOKEN=$TOKEN sh
82
+ ```
83
+
84
+ This pulls `install.sh` from the private repo using your `gh` auth token and re-exports it as `GITHUB_TOKEN` so the script can fetch the release asset behind the same credential.
85
+
86
+ ### Option 2 — From the npm package
87
+
88
+ Requires Bun ≥ 1.1 or Node ≥ 20:
89
+
90
+ ```sh
91
+ bun add -g @perpetualsystems/cli
92
+ # or
93
+ npm i -g @perpetualsystems/cli
94
+ ```
95
+
96
+ ### Option 3 — From source
97
+
98
+ ```sh
99
+ git clone https://github.com/perpetual/typescript-sdk.git
100
+ cd typescript-sdk/packages/cli
101
+ bun install
102
+ bun run dist:build # → ./perpetual-bin
103
+ ./perpetual-bin --version
104
+ ```
105
+
106
+ For local development without a compiled binary:
107
+
108
+ ```sh
109
+ bun run dev -- login --endpoint=https://your-endpoint.example.com
110
+ ```
111
+
112
+ ---
113
+
114
+ ## Quick Start
115
+
116
+ 1. **Authenticate** (browser opens, token saved to `~/.local/state/perpetual/auth/default.toml`):
117
+ ```sh
118
+ perpetual login --endpoint=https://your-endpoint.example.com
119
+ ```
120
+ 2. **Confirm**:
121
+ ```sh
122
+ perpetual whoami
123
+ ```
124
+ 3. **Browse the surface** — flat, scannable handbook:
125
+ ```sh
126
+ perpetual help
127
+ ```
128
+ 4. **Run a command** — drop into any subcommand's per-command help:
129
+ ```sh
130
+ perpetual query --help
131
+ perpetual query run --query "FROM simba.signals | AGG count()" --start 2026-10-01T00:00:00Z --end 2026-10-01T01:00:00Z
132
+ ```
133
+ 5. **Switch environments** without re-authenticating:
134
+ ```sh
135
+ perpetual login --profile=staging --endpoint=https://staging.example.com
136
+ perpetual --profile=staging case list
137
+ ```
138
+
139
+ ---
140
+
141
+ ### Shell completion
142
+
143
+ `perpetual completion <bash|zsh|fish>` prints a static script that completes command names, flags, enum values and the values of `--format`. Regenerate it after upgrading the CLI.
144
+
145
+ ```bash
146
+ # bash (use eval; `source <(...)` fails on the bash 3.2 that ships with macOS)
147
+ echo 'eval "$(perpetual completion bash)"' >> ~/.bashrc
148
+
149
+ # zsh: write the script to a directory you own...
150
+ mkdir -p ~/.zsh/completions
151
+ perpetual completion zsh > ~/.zsh/completions/_perpetual
152
+ # ...and in ~/.zshrc, put it on fpath before compinit:
153
+ # fpath=(~/.zsh/completions $fpath)
154
+ # autoload -Uz compinit && compinit
155
+ # If completions don't appear, delete ~/.zcompdump and start a new shell.
156
+
157
+ # fish
158
+ mkdir -p ~/.config/fish/completions
159
+ perpetual completion fish > ~/.config/fish/completions/perpetual.fish
160
+ ```
161
+
162
+ ## Command Reference
163
+
164
+ | Command | What it does |
165
+ |---|---|
166
+ | `login` | Authenticate via OAuth/password/client-credentials; save bearer token to a profile |
167
+ | `logout` | Delete a profile's stored login (`--all` for every profile) |
168
+ | `whoami` | Ask the API who you are, and show where the profile, org and login came from |
169
+ | `profile` | `list` / `use` / `show` / `get` / `delete` — manage stored profiles |
170
+ | `org` | `list` / `show` / `use` — see and choose the organization commands act on |
171
+ | `capabilities` | Describe the CLI's commands, flags and error codes as JSON |
172
+ | `api` | `[METHOD] </api/vN/path> [body]` — send a raw request with the profile's login and print the response body unchanged (`--spec` lists every route) |
173
+ | `case` | `list` / `get` — read cases |
174
+ | `catalog` | `get` — fetch the full schema catalog |
175
+ | `changeset` | `list` / `get` / `diff` / `create` / `update` / `delete` / `stage` / `unstage` / `discard-change` / `commit` — build a changeset over several runs and apply it together |
176
+ | `plan` | Show what `apply` would change for GitOps files, field by field, without changing anything (`--server` asks Simba) |
177
+ | `apply` | Apply exactly the GitOps files given: stage them into a new changeset, show its diff, confirm and commit |
178
+ | `delete` | `<kind> <id>` — delete a resource in one run, or stage the deletion into `--changeset` |
179
+ | `credential` | `list` / `get` / `create` / `update` / `delete` — manage connector secrets (live, not staged; secret via `--secret-stdin` or `--secret-env`) |
180
+ | `content-work-item` | `list` / `get` — read content work items |
181
+ | `dashboard` | `list` / `get` / `create` / `render-panels` (vega-lite → PNG or SVG) |
182
+ | `dataset` | `list` / `get` / `create` / `update` / `status` / `wait` — manage datasets and watch their deployment |
183
+ | `detection` | `list` / `get` / `create` / `update` / `delete` — manage detections |
184
+ | `mapper` | `list` / `get` / `create` / `update` — manage mappers |
185
+ | `oauth-client` | `list` / `create` / `delete` — manage OAuth clients (live, not staged) |
186
+ | `pack` | `list` / `get` / `installations` / `status` / `diff` / `install-deployed` read or set up; `install` / `update` / `uninstall` / `link-mode` commit in one run, or stage into `--changeset` — manage content packs and their installations |
187
+ | `parser` | `list` / `get` / `create` / `update` — manage parsers |
188
+ | `query` | `run` / `check` — run (streaming rows) and check Hamelin queries; `exec` / `validate` are deprecated |
189
+ | `search` | Ranked cross-resource search by name (`--limit`, `--kind`) |
190
+ | `threat-report` | `list` / `get` — read threat reports |
191
+ | `user` | `whoami` — show the current user |
192
+ | `robot-docs` | `guide` — print the agent handbook (always, regardless of TTY); `manifest` — print the command tree as JSON |
193
+ | `update` | Update the way perpetual was installed: re-run the release installer for an `install.sh` install, or the package manager's global install for npm, bun, pnpm or yarn (`--version <tag>`, `--dry-run`); with a private repo, run `GH_TOKEN=$(gh auth token) perpetual update` |
194
+ | `completion` | `<bash\|zsh\|fish>` — print a shell completion script |
195
+
196
+ Top-level flags applicable to every command:
197
+
198
+ ```
199
+ --json Force JSON output
200
+ --text Force text output
201
+ --format=<format> Explicit override: json | text
202
+ --profile=<name> Use a named profile (or $PERPETUAL_PROFILE)
203
+ --no-config Ignore the nearest .perpetual.toml
204
+ --robot-status Print auth + profile state as JSON and exit
205
+ --agent-help Print the full agent handbook regardless of TTY
206
+ -h, --help Per-command help (citty)
207
+ -v, --version Print version
208
+ ```
209
+
210
+ ---
211
+
212
+ ## Authentication
213
+
214
+ The CLI supports three ways to authenticate, selected with the `--auth` flag. Each one ends the same way: a bearer token saved on disk so subsequent commands work without re-authenticating.
215
+
216
+ `--auth=interactive` (browser-based OAuth) is the default. Email/password and client-credentials are alternatives — the first for environments without a browser session, the second for CI and automation.
217
+
218
+ ### `--auth=interactive` — browser-based OAuth (Authorization Code + PKCE)
219
+
220
+ The default. Run `perpetual login` with no `--auth` flag and you're here:
221
+
222
+ ```sh
223
+ perpetual login --endpoint=https://your-endpoint.example.com
224
+ ```
225
+
226
+ The CLI launches your default browser, you complete the login the same way you would on the web, and a localhost callback hands control back to the CLI. Equivalent explicit form:
227
+
228
+ ```sh
229
+ perpetual login --auth=interactive --endpoint=https://your-endpoint.example.com
230
+ ```
231
+
232
+ On first use the CLI registers itself as an OAuth client with the server (RFC 7591 dynamic client registration) and caches the registration under `~/.config/perpetual/clients/` for reuse. If your environment requires a pre-registered client, pass `--client-id=<id>` to pin it.
233
+
234
+ **Headless / SSH / WSL:** the browser launch falls back to printing the authorization URL on stderr if `open` / `xdg-open` / `start` can't reach a desktop session. Copy the URL into a browser on a machine where you're already signed in, complete the flow, and the loopback callback finishes the exchange. If your machine truly cannot reach any browser (CI runner, restricted container), use `--auth=client-credentials` instead.
235
+
236
+ ### `--auth=password` — email and password
237
+
238
+ For deployments without a browser-reachable OAuth setup, or when scripted credential injection fits better than the OAuth flow. The CLI accepts your password through three channels:
239
+
240
+ ```sh
241
+ # 1. Interactive prompt — TTY only. The CLI prompts for the password
242
+ # via @inquirer/password (no echo, no shell history):
243
+ perpetual login --auth=password \
244
+ --endpoint=https://your-endpoint.example.com \
245
+ --email=you@example.com
246
+ ```
247
+
248
+ ```sh
249
+ # 2. Piped from stdin — recommended for shells. Keeps the password out of
250
+ # `ps` and shell history:
251
+ echo 'your-password' | perpetual login --auth=password \
252
+ --endpoint=https://your-endpoint.example.com \
253
+ --email=you@example.com \
254
+ --password-stdin
255
+ ```
256
+
257
+ ```sh
258
+ # 3. From a file — recommended for automation:
259
+ perpetual login --auth=password \
260
+ --endpoint=https://your-endpoint.example.com \
261
+ --email=you@example.com \
262
+ --password-file=/path/to/password.txt
263
+ ```
264
+
265
+ The bare `--password=<pw>` flag is deprecated and will warn — passwords on the command line leak into `ps` listings, shell history, and process trees. Use one of the three channels above.
266
+
267
+ ### `--auth=client-credentials` — non-interactive, server-to-server
268
+
269
+ For CI and automation. Requires a pre-issued OAuth client with both `client_id` and `client_secret`. The secret is **never persisted to disk** — pass it via the `PERPETUAL_CLIENT_SECRET` environment variable so it stays out of `ps` listings and shell history:
270
+
271
+ ```sh
272
+ PERPETUAL_CLIENT_SECRET='your-client-secret' perpetual login \
273
+ --auth=client-credentials \
274
+ --endpoint=https://your-endpoint.example.com \
275
+ --client-id=YOUR_CLIENT_ID
276
+ ```
277
+
278
+ ---
279
+
280
+ ## Profiles
281
+
282
+ A profile is a named endpoint plus the credentials from logging in to it, saved to disk so you don't re-authenticate every command. Configuration and credentials live apart (see [XDG layout](#xdg-layout)):
283
+
284
+ - Endpoints: `$XDG_CONFIG_HOME/perpetual/profiles.toml`, one `[profiles.<name>]` table per profile, with no secrets
285
+ - Credentials: `$XDG_STATE_HOME/perpetual/auth/<name>.toml`, one file per profile
286
+ - Permissions: dirs `0700`, files `0600`, locked to the current user
287
+
288
+ ```sh
289
+ perpetual login --profile=staging --endpoint=https://staging.example.com
290
+ perpetual profile list
291
+ ```
292
+
293
+ ```
294
+ ID Name
295
+ default https://your-endpoint.example.com [authenticated]
296
+ staging https://staging.example.com (active) [authenticated]
297
+ ```
298
+
299
+ `(active)` marks the profile commands fall back to when no `--profile` flag is passed. With `--json`, the same flag surfaces as the `isActive: true` field on each profile entry.
300
+
301
+ - `perpetual profile use <name>` makes an existing profile active. On a terminal it logs in when the stored login cannot be used; without one it keeps the switch and exits 4. It never creates a profile; `perpetual login --profile <name>` does, and also makes it active. Inside a repository whose `.perpetual.toml` names a different endpoint, it still switches, and warns that commands there will fail. `profile set-active` still works but is deprecated.
302
+ - `perpetual profile show [<name>]` prints a profile's endpoint, org and login. Secrets appear only as `set`.
303
+ - `perpetual profile get <field>` prints one value for scripts, such as `$(perpetual profile get endpoint)`. Fields: `name`, `endpoint`, `username`, `org`, `auth-mode`, `user-id`, `expires-at`. `org` is the profile's remembered org; `perpetual org show` gives the one commands act on. An unset field exits 1 with nothing on stdout.
304
+ - `perpetual profile delete <name>` removes the profile's endpoint, its stored login and its remembered org. It asks first on a terminal; without one it needs `--force`.
305
+
306
+ - `--endpoint` is only for creating a profile. A later `perpetual login` to the same profile reuses its endpoint, and a different `--endpoint` is refused.
307
+ - `perpetual login` with a valid stored login changes nothing, and refreshes an expiring OAuth login silently.
308
+ - If a login turns out to be a different account from the profile's stored one, a terminal asks whether to replace it, save it as a new profile, or cancel. Without a terminal the login fails with `CONFIRMATION_REQUIRED` and saves nothing.
309
+ - `perpetual logout` deletes a profile's stored login and keeps the profile. An OAuth token cannot be revoked server-side, so it stays valid until it expires.
310
+
311
+ All three auth modes write the same profile shape, so downstream commands work identically regardless of how you authenticated.
312
+
313
+ ---
314
+
315
+ ## Organizations
316
+
317
+ Every command acts on one organization. The CLI picks it in this order:
318
+
319
+ 1. `--org-id`
320
+ 2. `PERPETUAL_ORG_ID`
321
+ 3. `org_id` in the nearest [`.perpetual.toml`](#repository-config-perpetualtoml)
322
+ 4. The active profile's org (`perpetual org use`)
323
+ 5. The org the profile last used
324
+ 6. The login's only org, when it can use exactly one
325
+ 7. The account's default org, when the login can use it
326
+ 8. Otherwise commands fail with `ORG_REQUIRED` (exit 4)
327
+
328
+ The chosen org must be one the login can use; otherwise commands fail with `OAUTH_ORG_NOT_PERMITTED` (exit 4) naming where it came from. `perpetual whoami` and `perpetual org show` show the source.
329
+
330
+ ```sh
331
+ perpetual org list # orgs this login can use, with names
332
+ perpetual org use "Acme" # by name, any case, or by ID; remembered per profile
333
+ perpetual org show # the org commands act on, and where it came from
334
+ ```
335
+
336
+ `PERPETUAL_<PROFILE>_ORG_ID` is no longer read; it is ignored with a warning.
337
+
338
+ ---
339
+
340
+ ## Repository config (`.perpetual.toml`)
341
+
342
+ Commit a `.perpetual.toml` to a repository so everyone working in it, CI included, targets the same deployment and org:
343
+
344
+ ```toml
345
+ endpoint = "https://perpetual.example.com"
346
+ org_id = "ORG_ABC"
347
+ ```
348
+
349
+ - Commands look for it in the working directory and then each parent directory, as git does for `.git`. The closest file wins. `--no-config` skips it.
350
+ - Both fields are optional. Unknown keys are ignored with a warning. It never holds credentials.
351
+ - Because the file decides where logins are sent, its `endpoint` must use `https` (plain `http` only to `localhost`), and a file owned by another user, or a symlink, is ignored with a warning, as git does with `safe.directory`. `perpetual whoami` names the file it read.
352
+ - With no profile, `endpoint` supplies the endpoint, so a CI job needs only `PERPETUAL_TOKEN`. A password is never sent to an endpoint taken from the file, and `PERPETUAL_TOKEN` is sent there only when the token was issued by that server: its `iss` claim must have the endpoint's origin, or both must be on a loopback address. A token with no `iss`, such as a password session's, is refused. Otherwise the command fails with `CONFIG_ERROR` naming the file; select a profile for the endpoint instead.
353
+ - With a profile on the same endpoint, the file's `org_id` applies. If the active profile uses a different endpoint, commands fail with `CONFIG_ERROR` rather than send its login elsewhere. A profile named with `--profile` or `PERPETUAL_PROFILE` wins instead, and the file is ignored with a warning.
354
+ - `perpetual login --profile <name>` without `--endpoint` offers the file's endpoint for a new profile on a terminal, and uses it only once you confirm. Without a terminal it names the endpoint in the hint and needs `--endpoint`.
355
+ - A file that does not parse, or a field of the wrong type, fails with `CONFIG_ERROR` naming the file and line.
356
+
357
+ ---
358
+
359
+ ## Configuration
360
+
361
+ ### Environment variables
362
+
363
+ Every flag has an env-var equivalent for non-interactive use:
364
+
365
+ | Flag | Env var |
366
+ |---|---|
367
+ | `--auth` | `PERPETUAL_AUTH` |
368
+ | `--email` | `PERPETUAL_EMAIL` |
369
+ | `--profile` | `PERPETUAL_PROFILE` |
370
+ | `--client-id` | `PERPETUAL_CLIENT_ID` |
371
+ | `--client-secret` | `PERPETUAL_CLIENT_SECRET` (never written to disk) |
372
+ | `--redirect-uri` | `PERPETUAL_REDIRECT_URI` |
373
+ | `--format` | `PERPETUAL_FORMAT` |
374
+ | `--org-id` | `PERPETUAL_ORG_ID` |
375
+ | — | `PERPETUAL_TOKEN`: a bearer token to use instead of the profile's stored login, for one invocation (never written to disk) |
376
+
377
+ The endpoint has no flag or env var outside `login`: it belongs to the profile, or to the repository's `.perpetual.toml`. `PERPETUAL_ENDPOINT` is ignored with a warning; create a profile per endpoint with `perpetual login --profile <name> --endpoint <url>`.
378
+
379
+ ### XDG layout
380
+
381
+ ```
382
+ ${XDG_CONFIG_HOME:-~/.config}/perpetual/
383
+ ├── profiles.toml # each profile's endpoint and username; no secrets
384
+ └── oauth-clients.json # cached dynamic-client-registration results
385
+
386
+ ${XDG_STATE_HOME:-~/.local/state}/perpetual/
387
+ ├── auth/
388
+ │ ├── default.toml # mode 0600: tokens, expiry, OAuth client
389
+ │ └── staging.toml
390
+ ├── active.toml # active profile, active org, last org per profile
391
+ └── legacy-backup/ # files moved aside by the one-time migration
392
+ ```
393
+
394
+ `profiles.toml` holds nothing secret. `oauth-clients.json` can hold a dynamically registered client's secret, so keep it out of a dotfiles repository.
395
+
396
+ #### Upgrading from an earlier version
397
+
398
+ Earlier versions kept everything in `~/.config/perpetual/profiles/<name>.toml` and `config.toml`. The first command you run after upgrading moves those profiles to the layout above, prints one line to stderr, and moves the old files to `~/.local/state/perpetual/legacy-backup/<timestamp>/`. You stay logged in. Delete the backup once you are happy with the result. An earlier CLI cannot read the new layout.
399
+
400
+ ---
401
+
402
+ ## Use as an Agent Tool
403
+
404
+ The CLI is built to be driven by an LLM agent — not just by humans piping through `jq`.
405
+
406
+ **Discovery.** Point an agent at the binary and tell it: *"Inspect `~/path/to/perpetual` and learn what you can do with it."* The agent will:
407
+
408
+ 1. Run `perpetual help` → gets a flat, ANSI-free reference of every command, sub-command, and flag
409
+ 2. Run `perpetual --robot-status` → gets `{ok, authenticated, profile, endpoint, userId, orgId}` as JSON (`orgId` is `null`, with a `hint`, when the login works but no org is chosen)
410
+ 3. Run `perpetual robot-docs guide` → gets the long-form agent handbook
411
+
412
+ **Execution.** Once oriented, the agent:
413
+
414
+ - Pipes outputs as JSON automatically (no `--json` flag needed when stdout isn't a TTY)
415
+ - Detects errors via the stable `{"ok": false, "error": "...", "code": "..."}` envelope on stderr, which adds `field`, `resource`, `hint` and `retry_after_seconds` when they apply
416
+ - Branches on the exit code: `2` bad argv, `4` log in again, `8` conflict, `9` retry later, `1` anything else. [docs/cli-error-contract.md](../../docs/cli-error-contract.md) has the full contract.
417
+ - Uses stable error codes (`MISSING_ARGUMENT`, `CONFIRMATION_REQUIRED`, `UNKNOWN_FLAG`, `VERSION_CONFLICT`) for control flow
418
+
419
+ **Hard rules for non-interactive callers.** The CLI hard-fails (rather than silently doing the wrong thing) when:
420
+
421
+ - A password is required but no `--password-stdin` / `--password-file` / env was provided
422
+ - A destructive command is run without `--force`
423
+ - `--password-stdin` is passed in a TTY (i.e., stdin isn't piped)
424
+
425
+ ---
426
+
427
+ ## Architecture
428
+
429
+ ```
430
+ ┌───────────────────────────────────────────────────────────────┐
431
+ │ process.argv (raw tokens) │
432
+ └──────────────────────────┬────────────────────────────────────┘
433
+ ▼
434
+ ┌─────────────────────────────────────────┐
435
+ │ argv-rewrite (src/lib/argv-rewrite.ts) │
436
+ │ • -h / -v → --help / --version │
437
+ │ • global flags hoisted after sub │
438
+ │ • dangling-flag validation │
439
+ └──────────────────────┬──────────────────┘
440
+ ▼
441
+ ┌─────────────────────────────────────────┐
442
+ │ Pre-dispatch validators │
443
+ │ • subcommand-typo (Levenshtein) │
444
+ │ • unknown-flag (per leaf path) │
445
+ │ • boolean-attached-value rejection │
446
+ └──────────────────────┬──────────────────┘
447
+ ▼
448
+ ┌─────────────────────────────────────────┐
449
+ │ Dispatch branches (mutually exclusive) │
450
+ │ • help / help <cmd> │
451
+ │ • --agent-help / --global-help │
452
+ │ • --robot-status │
453
+ │ • non-TTY bare → agent handbook │
454
+ │ • citty runMain → subcommand │
455
+ └──────────────────────┬──────────────────┘
456
+ ▼
457
+ ┌─────────────────────────────────────────┐
458
+ │ Subcommand (src/commands/<name>.ts) │
459
+ │ → @perpetualsystems/typescript-sdk │
460
+ │ → detectFormat() → json | text │
461
+ │ → handleTopLevelError on failure │
462
+ └─────────────────────────────────────────┘
463
+ ```
464
+
465
+ The single most important branch — `detectFormat()` in `src/lib/output.ts`:
466
+
467
+ ```ts
468
+ if (args.json) return "json";
469
+ if (args.text) return "text";
470
+ if (args.format === "json" || args.format === "text") return args.format;
471
+ return process.stdout.isTTY ? "text" : "json";
472
+ ```
473
+
474
+ Everything an agent sees — JSON wrapping, no colors, no tables — flows from `process.stdout.isTTY` being false. Override priority: `--json` / `--text` shorthand → `--format=...` → TTY auto-detect.
475
+
476
+ ---
477
+
478
+ ## Troubleshooting
479
+
480
+ | Symptom | Likely cause | Fix |
481
+ |---|---|---|
482
+ | `Token expired — re-authenticating` followed by failure | Refresh token expired or revoked | `perpetual login` again to refresh the profile |
483
+ | `MISSING_PASSWORD` in non-TTY mode | No password channel provided | Add `--password-stdin`, `--password-file=...`, or `PERPETUAL_PASSWORD` env |
484
+ | `CONFIRMATION_REQUIRED` on a delete | Running non-interactively without `--force` | Re-run with `--force` |
485
+ | `Unknown flag '--jsno'. Did you mean '--json'?` | Typo in a flag | Use the suggestion |
486
+ | `Unknown command 'lsit'. Did you mean 'list'?` | Typo in a subcommand | Use the suggestion |
487
+ | Browser doesn't open during `login` (SSH/WSL) | No desktop session reachable | Copy the printed URL into a browser on another machine, or switch to `--auth=client-credentials` |
488
+ | `perpetual` not found after install | Binary not on `PATH` | Confirm install location; add to `PATH` or symlink to `/usr/local/bin/perpetual` |
489
+ | Profile commands say `[not authenticated]` | Token wiped or missing | `perpetual login --profile=<name>` to re-auth |
490
+
491
+ When in doubt:
492
+
493
+ ```sh
494
+ perpetual doctor # diagnose
495
+ perpetual doctor --fix # apply safe, reversible fixes
496
+ perpetual --robot-status # one-shot machine-readable state
497
+ ```
498
+
499
+ ---
500
+
501
+ ## Limitations
502
+
503
+ Honest list of what the CLI does **not** do yet:
504
+
505
+ - **Pretty result rendering.** Query and detection results currently render as flat key/value blocks rather than rich tables for complex shapes.
506
+ - **`--agent` override.** No way to force agent-mode output when the CLI is genuinely attached to a TTY (use `--json` instead for now).
507
+ - **Auto-update.** No built-in `perpetual self-update` — users update manually via the install script or package manager.
508
+ - **GitOps sync.** No CRUD-from-files workflow for detections/dashboards — every change is a discrete API call.
509
+ - **Folder API.** No folder/grouping commands yet for organizing cases or detections client-side.
510
+
511
+ If one of these blocks you, please file an issue (see [Contributions](#about-contributions)) so it gets prioritized.
512
+
513
+ ---
514
+
515
+ ## FAQ
516
+
517
+ **Q: Do I need Node or Bun installed?**
518
+ No — the standalone binary built via `bun build --compile` is self-contained. The npm package does require Bun ≥ 1.1 or Node ≥ 20.
519
+
520
+ **Q: Can I store credentials somewhere other than `~/.local/state/perpetual/`?**
521
+ Yes. Set `XDG_STATE_HOME` for credentials and `XDG_CONFIG_HOME` for profile endpoints before running the CLI.
522
+
523
+ **Q: How do I run two profiles at once?**
524
+ You don't — `--profile` selects one per invocation. Run two terminals or pass `--profile=X` to each invocation.
525
+
526
+ **Q: Is my password ever written to disk?**
527
+ No. Only the OAuth bearer token (and refresh token, where applicable) is persisted, in the profile TOML at mode `0600`. Passwords and client secrets are never written.
528
+
529
+ **Q: Why does the CLI sometimes output JSON when I didn't ask for it?**
530
+ Because `stdout` isn't a TTY — usually because you piped, redirected, or invoked from a non-interactive context. Pass `--text` to force text output, or `--format=text`.
531
+
532
+ **Q: How do I let an agent use this CLI safely?**
533
+ Point the agent at the binary with read+execute permissions. The agent discovers the surface via `perpetual help`, authenticates once via `login`, and runs subsequent commands. Stable error codes (`MISSING_PASSWORD`, `CONFIRMATION_REQUIRED`, `UNKNOWN_FLAG`) let the agent recover programmatically.
534
+
535
+ **Q: What's `robot-docs`?**
536
+ A subcommand that prints the long-form agent handbook to stdout. `perpetual robot-docs guide` always prints the handbook, regardless of TTY, so agents can fetch it deterministically.
537
+
538
+ **Q: What's `--robot-status`?**
539
+ A top-level flag that exits early after printing `{ok, authenticated, profile, endpoint, userId, orgId}` as JSON. Use it as a probe: an agent calls `--robot-status` before doing anything, and routes around `authenticated: false` by running `login`.
540
+
541
+ ---
542
+
543
+ ## About Contributions
544
+
545
+ > Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other "stakeholders," which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via `gh` and independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.
546
+
547
+ ---
548
+
549
+ ## License
550
+
551
+ TBD.