Repository navigation
feat(mocactl): headless sessions and credentials commands with --json (#406) - #416
Conversation
…rossoctl#406) Listing sessions and adding credentials existed only in the TUI overlays, so the two-user acceptance run listed sessions with curl and a scripted setup could not store an inference credential. - `mocactl sessions [--json]` follows every page of GET /v1/sessions and shows the local title; `sessions delete ID` goes through the session manager so the local history goes too. - `mocactl credentials [--json]`, `credentials add NAME --host … [--kind] [--consumer] [--endpoint]` with the secret read from stdin only (a terminal on stdin is refused), and `credentials delete NAME`. - The TUI form's checks move to core/credential-checks.ts, taking the secret apart from the field values, so the CLI applies the same checks to what it read from stdin. (Not core/credentials.ts: .gitignore ignores credentials.*.) - One output convention for every listing (README "Output"): stdout carries only the result, a table or one JSON document; messages go to stderr. The --json shapes are documented as stable. - The VM two-user runbook uses `mocactl sessions --json` in Act 2a and shows the scripted credential add in 1b; fix-list item 5 is closed. Fixes rossoctl#406 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]> # Conflicts: # docs/demos/vm-two-user-acceptance.md # packages/mocactl/src/headless.ts
huang195
left a comment
There was a problem hiding this comment.
I read the full diff and ran the mocactl suite (533 pass, 2 skipped) and tsc. I also ran mutation checks, and probed the real src/main.ts against a fake control plane.
Checked and fine:
- The TUI refactor keeps behaviour: the old
validateCredential/toPutRequestand the newcredentialProblem/credentialRequest/formSecretagree path for path, including the free-form kinds. - Paging requests limit 200, which is the server's
MAX_PAGE_SIZE, and stops on a repeated cursor. - 202 maps to
accepted. - The
--jsonshapes match the README table, and the text output is terminal-safe. - The runbook's 2a works, because 0b exports
SH_CONTROL_PLANE_URL.
Nothing blocks. Five suggestions are worth doing in this PR:
--endpointis silently dropped for non-inference consumers, a combination the server refuses on purpose.turnsis always 0, now as a column and a stable JSON field.credentials deletereportsdeletedfor a name that never existed.- The early check covers less than its comment says.
- Two test gaps: the TTY refusal and the early check can both be removed with the suite still green.
The rest are nits.
Agent/IDE config (.claude/.vscode): none · Commits: 2, both signed off · CI: green
| const hosts = parseHosts(values.hosts ?? ''); | ||
| const consumer = values.consumer as CredentialConsumer; | ||
| const req: PutCredentialRequest = { kind: values.kind, consumer, destination: { hosts }, secret }; | ||
| if (consumer === 'inference' && values.endpoint?.trim()) req.endpoint = values.endpoint.trim(); |
There was a problem hiding this comment.
suggestion — --endpoint with a non-inference consumer is dropped here silently. printf tok | mocactl credentials add x --host h --consumer sandbox-egress --endpoint https://x.example exits 0 with stored credential x, and the PUT carries no endpoint.
The server refuses that combination on purpose (control-plane/src/credential-store.ts:274-278: "Accepting it elsewhere would create a second, silently ignored notion of 'where this credential goes'"). The TUI hides the field for other consumers, so only the CLI can reach this. I'd refuse it in cmdCredentialAdd before stdin is read: exit 2 with --endpoint only applies to --consumer inference. test/cli.test.ts:120-135 currently routes exactly this combination as a valid call.
There was a problem hiding this comment.
Fixed in 473d0ef. cmdCredentialAdd refuses --endpoint with any consumer other than inference before reading stdin: exit 2 with --endpoint only applies to --consumer inference. The routing case in cli.test.ts no longer passes --endpoint, and a new test runs this combination through main and checks that readStdin was never called.
| hosts: opts.hosts.join(','), | ||
| endpoint: opts.endpoint ?? '', | ||
| }; | ||
| // Everything but the secret is checked before stdin is read, so a typo costs no re-piping. |
There was a problem hiding this comment.
suggestion — Only descriptionProblem (name, consumer, hosts) runs before the read. The other checks that don't need the secret run after it: the inference single-secret-kind refusal, and the endpoint URL/shape checks in inferenceShapeProblem.
--consumer defaults to inference, and the README's basic example (README:77) shows no --consumer. So mocactl credentials add reg --kind basic --host ghcr.io takes username=/password= on stdin, and only then refuses basic. I'd move the kind-arity and endpoint checks into the early check (for a known kind they depend only on values), and add --consumer sandbox-egress to the README example.
There was a problem hiding this comment.
Fixed in 473d0ef. descriptionProblem now also covers, for inference, a known kind's arity and the endpoint checks (split out of the old inferenceShapeProblem as inferenceEndpointProblem). What still runs after the read needs the secret: an unknown kind's arity, which depends on the keys on stdin, and the sk-ant-oat/sk-ant-api prefix checks. --kind basic with the default consumer is now refused before stdin is read. The README example shows --consumer sandbox-egress.
| io.err(describeError(err)); | ||
| return 1; | ||
| } | ||
| io.err(`deleted credential ${sanitizeRemote(opts.name)}`); |
There was a problem hiding this comment.
suggestion — The server answers 204 whether or not the credential existed (handlers.ts deleteCredential: "a 404 here would be an existence oracle"). So mocactl credentials delete never-existed --json prints deleted credential never-existed and {"status":"deleted"}, and a typo in scripted cleanup reads as success.
The oracle concern doesn't apply to the owner, who can list their own names. Two ways out: check listCredentials() first and exit 1 with no credential named X, or report only what is known (no credential named X remains) and define deleted that way in the README table.
There was a problem hiding this comment.
Fixed in 473d0ef, the first way: credentials delete lists the user's credentials and exits 1 with no credential named X (nothing on stdout, no DELETE sent) when the name isn't there. The README now says so.
| r.sessionId, | ||
| utc(r.createdAt), | ||
| r.lastTurnAt === null ? '-' : utc(r.lastTurnAt), | ||
| String(r.turns), |
There was a problem hiding this comment.
suggestion — turns will be 0 on every real deployment, because nothing writes it:
- The control plane reads
runtime.turns(control-plane/src/handlers.ts:168), andturnsis on the runtime allow-list (ownership.ts:74). - The only
putRuntimecaller isknative-server/src/turn-auth.ts:383. ItsruntimeFieldsForTurn(313-329) writeslastTurnAt/turnStartedAt/turnEndedAt, neverturns. - A repo-wide grep finds no other writer.
The gap predates this PR (the TUI Sessions overlay shows "0 turns" too). This PR makes it a table column and a field the README calls stable, though. I'd drop TURNS here and keep turns out of the documented shape until the server counts turns, or file that fix alongside. The fixtures use turns: 2, which is why the fake control-plane run didn't show it.
| endpoint: values.endpoint, | ||
| json, | ||
| readStdin, | ||
| stdinIsTTY: deps.stdinIsTTY === true, |
There was a problem hiding this comment.
suggestion (tests) — Two mutations survive cli.test.ts + headless-manage.test.ts (47 tests green):
- this line replaced with
stdinIsTTY: false; descriptionProblem(values)atheadless.ts:335replaced withundefined.
The TTY refusal is what keeps a secret from being typed with echo on, and no test exercises it through main: every case passes stdinIsTTY: false. The 'no host' and 'bad name' cases (headless-manage.test.ts:302-303) check exit 2 and no PUT. They don't check that readStdin was never called, which is what the early check promises.
Two additions would catch both: a main(['credentials','add',…], …, { stdinIsTTY: true, readStdin: spy }) case asserting exit 2 and spy not called, and expect(readStdin).not.toHaveBeenCalled() in those two cases.
There was a problem hiding this comment.
Fixed in 473d0ef. cli.test.ts has a main(['credentials','add',…], { stdinIsTTY: true, readStdin: spy }) case that uses a logged-in runtime, so ready() doesn't refuse first. It asserts exit 2 and that spy was never called. Every refusal that needs no secret (TTY, no host, bad name, multi-field inference kind, bad endpoint, /v1, --endpoint for another consumer) now also asserts readStdin was never called. I re-ran both of your mutations: the first now fails 1 test, the second 5.
| ): { secret: Record<string, string> } | { problem: string } { | ||
| const fields = KNOWN_KINDS[kind]; | ||
| if (fields?.length === 1) { | ||
| const value = text.replace(/\r?\n$/, ''); |
There was a problem hiding this comment.
nit — The single-field path keeps everything except one trailing newline. That lets through three inputs that the TUI or the runbook catch:
- A whitespace-only secret:
' \n'is stored, where the TUI's Form refuses a blank required field (Form.tsx:112). - Leading whitespace or a UTF-8 BOM, which gets past the
sk-ant-oat/sk-ant-apiprefix checks here and on the server. key=sk-ant-…, stored with thekey=included.
The runbook already warns about the last one for the TUI (vm-two-user-acceptance.md:186-188), and the README's field=value format for other kinds makes it easy to repeat here. I'd refuse a blank value, and one starting with ${fields[0]}=.
There was a problem hiding this comment.
Fixed in 473d0ef. The single-field path refuses a blank value, a value with leading or trailing whitespace (\s covers the BOM), and one starting with ${field}=. Each message names the field only. There are tests for all four.
| io.err('no sessions'); | ||
| return 0; | ||
| } | ||
| const head = ['ID', 'CREATED (UTC)', 'LAST TURN (UTC)', 'TURNS', 'TITLE']; |
There was a problem hiding this comment.
nit — There's no STATE column, so a session whose delete came back accepted lists like a live one. Its title is blank too, because its local history is already gone. --json has state; a STATE column, or marking deleting, would make the table say the same.
There was a problem hiding this comment.
Fixed in 473d0ef: the table has a STATE column (ID STATE CREATED LAST TURN TITLE), so a session being deleted lists as deleting.
|
|
||
| ```bash | ||
| mocactl sessions [--json] # every session you own, all pages | ||
| mocactl sessions delete ID [--json] # also drops its local history |
There was a problem hiding this comment.
nit — This holds only when the control-plane delete succeeds. SessionManager.remove (session-manager.ts:247-250) deletes the transcript after cp.deleteSession, so on a 404 the command exits 1 and the local history stays. That happens when the session is already gone, e.g. deleted from another machine.
mocactl sessions lists only server sessions, so that history can't be seen or removed from the CLI. Either drop the transcript on session_not_found as well, or say so here.
There was a problem hiding this comment.
Fixed in 473d0ef, the first way: SessionManager.remove also drops the transcript on session_not_found, then rethrows, so the command still exits 1. Other failures keep the history. There are tests for both cases, and the README line now says so.
|
|
||
| Exit codes, for every command: `0` it worked, `1` it failed (the turn, or the control plane | ||
| refused), `2` a usage or setup problem (bad flags, not logged in, no destination for the turn), | ||
| `130` cancelled (Ctrl-C). |
There was a problem hiding this comment.
nit — 130 on Ctrl-C holds for run and login, which take deps.signal; the new commands don't. main.ts:4 replaces Node's default handler with process.once('SIGINT', () => ac.abort()), so the first Ctrl-C does nothing in two cases: credentials add waiting on a stdin with no writer (CI, cat |), or a listing waiting on a slow control plane. The second Ctrl-C exits. Passing the signal through, and printing reading the secret from stdin… on stderr, would cover both.
There was a problem hiding this comment.
Fixed in 473d0ef. sessions, sessions delete, credentials, credentials add and credentials delete take deps.signal. Their requests and the stdin read are raced against it, so the first Ctrl-C exits 130. The control-plane client takes no signal, so the pending work is abandoned rather than stopped, and main.ts calls process.exit once stdout has drained after an abort. credentials add prints reading the secret from stdin… on stderr before reading. There are tests for a hung listing and a hung stdin.
| Or, from a script, with the key on stdin (never on the command line): | ||
|
|
||
| ```bash | ||
| read -rs KEY && printf %s "$KEY" | mocactl credentials add anthropic --kind api-key \ |
There was a problem hiding this comment.
nit — read -rs KEY prints no prompt, so the presenter pastes this and nothing visible happens.
In a shell without bracketed paste (e.g. macOS's /bin/bash 3.2), read also takes the block's next line, mocactl credentials, as the key. With --kind api-key that passes every client and server check, so only 1d would notice. zsh and bash 5.1+ are fine.
Suggested changes:
- a prompt that works in both shells:
printf 'API key: ' >&2; read -rs KEY; echo >&2(read -pmeans something else in zsh); mocactl credentialsin its own block;unset KEYafterwards.
There was a problem hiding this comment.
Fixed in 473d0ef. The runbook now uses printf 'API key: ' >&2; read -rs KEY; echo >&2 in a block of its own, then the add, unset KEY and mocactl credentials in a second block. I split it further than you suggested: with the add command under read, bash 3.2 would have taken the printf … | mocactl credentials add line as the key.
…lete, Ctrl-C - credentials add: refuse --endpoint for a non-inference consumer, and run every check that needs no secret (kind arity, endpoint shape) before stdin is read; refuse a blank, whitespace-wrapped or `field=`-prefixed single-field secret; say when stdin is being read. - credentials delete: exit 1 for a name the user owns no credential of (the server answers 204 either way). - sessions: drop the TURNS column and the `turns` field (nothing writes it server-side yet); add a STATE column. - sessions delete: drop the local history on session_not_found too. - Known kinds are looked up by own key only (`--kind toString`). - Ctrl-C exits 130 from listings and the stdin read. - Runbook: visible prompt, `read` in its own block, `unset KEY`. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…eporting 0 `turns` was on the runtime hash's allow-list (ownership.ts) and read by both the session summary (handlers.ts) and the resources view (resources.ts), but nothing ever wrote it: `runtimeFieldsForTurn` stamps turnStartedAt / turnEndedAt / lastTurnAt and no other putRuntime caller exists. So every real deployment reported 0 turns, visible in the mocactl TUI's Sessions overlay -- and #416 left the field out of `mocactl sessions` because of it. Counted with HINCRBY, not a read-modify-write. The server does not serialize concurrent turns of one session (ADR-0036), so reading the old value would have both turns read N and both write N+1, losing a count. This adds hIncrBy to CpRedisLike and a bumpTurns() that goes through the same guard as every other index write, so a transport failure is still redis_unavailable. `turns` is now readable but NOT settable through putRuntime (RUNTIME_COUNTERS). It is the only runtime field whose new value depends on its old one, and the tier that self-reports this hash is untrusted (spec §7.4) -- a `turns` passed to putRuntime would let a compromised harness claim any count. It is dropped on write, as a field off the allow-list is, rather than stored and then ignored. The reporter bumps when the fields carry turnEndedAt, rather than at each of the six call sites: a completed turn is exactly the report that stamps that timestamp, so no call site can report an end and forget to count it, and the counter cannot drift from the timestamp beside it. With a writer in place, `mocactl sessions` brings the field back: a TURNS column in the table and `turns` in `--json`, both straight from the server's summary. The local transcript store is deliberately not the source -- a headless `mocactl run` writes no transcript and a session resumed on another machine has none, yet both have run turns (#417's other half). The TUI already renders `s.turns` (Sessions.tsx), so it shows real counts with no change. Eight mutants, all caught: a read-modify-write instead of HINCRBY, a dropped RUNTIME_COUNTERS guard (turns forgeable through putRuntime), a reporter that never bumps, one that bumps unconditionally (counting started turns), a summary hardcoded to 0, a fake-redis op log that cannot tell HINCRBY from hSet, a TURNS column fed from the local transcript, and a header with no cell. Closes #420. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Fixes #406.
Problem
Listing sessions and adding credentials existed only in the TUI overlays. So the VM two-user acceptance run listed sessions with
curland a hand-built header file (Act 2a), and a scripted setup could not store an inference credential.Change
mocactl sessions [--json]follows every page ofGET /v1/sessions(and stops with an error if the control plane repeats a cursor). It shows id, created and last-turn times (UTC), turns and the local title.mocactl sessions delete IDgoes through the session manager, so the local history goes too.mocactl credentials [--json]lists name, kind, consumer, hosts and endpoint, never secrets.mocactl credentials add NAME --host … [--kind] [--consumer] [--endpoint]reads the secret from stdin only, never argv. A terminal on stdin is refused with aread -rshint. A single-field kind takes stdin as the secret (one line, trailing newline dropped); any other kind takesfield=valuelines.mocactl credentials delete NAME. The issue didn't ask for it, but scripted cleanup needs it.src/core/credential-checks.ts, taking the secret apart from the field values, so the CLI runs the same checks on what it read from stdin. The module isn't namedcredentials.tsbecause.gitignoreignorescredentials.*.--kind,--consumer,--hostand--endpointare rejected on any other command.Output convention (for #381 to share)
Documented in
packages/mocactl/README.md, "Output":--json.run's.--jsonshapes are listed and stable: fields may be added, but none is renamed or removed.Docs
docs/demos/vm-two-user-acceptance.mdnow:mocactl sessions --json | jqin Act 2a;The 2b probes stay on
curlbecause they test the raw API's 404s.Testing
test/headless-manage.test.ts(new) covers paging, the table and JSON shapes, empty lists, errors, and the stdin secret cases, including that a refused secret is never echoed.test/cli.test.tscovers routing and usage errors.tsc,make lintand prettier.sk-ant-oat…token was refused with no request sent, and a stray--kindexited 2.🤖 Generated with Claude Code