@rine-network/cli 0.16.1 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +34 -10
  2. package/dist/main.js +1894 -291
  3. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -2,7 +2,7 @@ import { createRequire } from "node:module";
2
2
  import { Command, Option } from "commander";
3
3
  import * as fs from "node:fs";
4
4
  import { readFileSync } from "node:fs";
5
- import { FUNNEL_TIERS, HttpClient, IdempotencyStore, RineApiError, UUID_RE, X402Error, X402FacilitatorError, X402_MESSAGE_TYPE, addMlsGroupMember, agentKeysExist, agentLabel, buildIssueCertDeps, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildReceiptMessage, cacheToken, connectTunnel, createWallet, decryptGroupMessage, decryptMessage, decryptThreadRow, deleteHookSecret, encryptGroupMessage, encryptMessage, encryptMlsGroupMessage, ensureCert, externalJoinMlsGroup, fetchAgents, fetchAndIngestPendingSKDistributions, fetchOAuthToken, fetchRecipientKeys, formatError, fromBase64Url, generateAgentKeys, generateHookSecret, generatePqKeyPair, getAgentPublicKeys, getCredentialEntry, getOrCreateSenderKey, getOrRefreshToken, getWalletAddress, handleWebhookRequest, hasSpiffeEndpoint, hookNameError, ingestSenderKeyDistribution, initMlsGroup, isAutoPayable, isBareAgentName, isX402MessageType, jitteredRefreshMargin, listMyInvites, loadAgentKeys, loadCredentials, loadHookSecret, loadMeta, loadMlsState, loadPolicy, loadTokenCache, loadWalletKey, makeEdgePipeFactory, matchedQuoteToWire, normalizeHandle, parseFacilitatorHeaders, parseX402Payload, performAgentCreation, performRegistration, processMlsWelcomes, readDailySpent, refusalReceiptBody, renewalDueWithJitter, reserveSpend, resolveAgent, resolveApiUrl, resolveConfigDir, resolveFacilitatorConfig, resolveHandleViaWebFinger, resolvePayeeRequirement, resolveToUuid, saveAgentKeys, saveCredentials, saveHookSecret, savePolicy, savePqEncryptionKey, saveTokenCache, selectRequirement, sendGroupInviteNotification, sendReceipt, settleToReceipt, startTlsListener, syncMlsGroup, toBase64Url, validateEncryptionKey, validateSigningKey, validateSlug, verifyIdentitySpiffe, walletKeyExists } from "@rine-network/core";
5
+ import { ACTING_AGENT_ENV, ACTING_AGENT_HEADER, ACTOR_SURFACES, FUNNEL_TIERS, GROUP_NOT_FOUND_LEAD, HttpClient, IdempotencyStore, MLS_ERR_GROUP_INACTIVE, MLS_EVICTED_BY_COMMIT, MlsInitInFlightError, RineApiError, SENDER_KEY_UNAVAILABLE_CODE, SENDER_KEY_UNAVAILABLE_PREVIEW, THREAD_REF_SURFACES, THREAD_UNAVAILABLE, UUID_RE, VOTE_DURATION_RULE, VOTE_ELECTORATE_RULE, X402Error, X402FacilitatorError, X402_ERROR, X402_MESSAGE_TYPE, actorFromEnv, addMlsGroupMembers, admissionHeadline, admittedAgentIds, agentKeysExist, agentLabel, asSenderKeyUnavailable, assertNoMlsDowngrade, buildIssueCertDeps, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildPeerVerification, buildReceiptMessage, cacheToken, compareVerificationWordsForAgent, connectTunnel, createWallet, decryptGroupMessageWithRecovery, decryptMessage, decryptThreadRows, deleteGroupMember, deleteHookSecret, describeMlsReclamation, describeMlsRecovery, encryptGroupMessage, encryptMessage, encryptMlsGroupMessage, encryptionLine, ensureCert, evictionMessage, externalJoinMlsGroup, fetchAgents, fetchOAuthToken, fetchRecipientKeys, formatError, fromBase64Url, generateAgentKeys, generateHookSecret, generatePqKeyPair, getAgentPublicKeys, getCredentialEntry, getOrCreateSenderKey, getOrRefreshToken, getWalletAddress, groupAcceptsMlsSendOnly, groupAdmissionSkipSentence, groupEncryption, groupEncryption as groupEncryption$1, groupIsMls, groupMlsInitInFlight, handleCompletionNote, handleWebhookRequest, hasSpiffeEndpoint, holdsAnyMlsState, holdsMlsState, hookNameError, ingestSenderKeyDistribution, initMlsGroup, inviteNominates, isAuthenticityFailure, isAutoPayable, isMlsResyncUnavailable, isMlsWelcomeRefusedError, isNoMlsStateError, isX402MessageType, jitteredRefreshMargin, listMyInvites, loadAgentKeys, loadCredentials, loadHookSecret, loadMeta, loadMlsGroup, loadMlsState, loadPolicy, loadSenderKeyStates, loadTokenCache, loadWalletKey, makeEdgePipeFactory, matchedQuoteToWire, mlsAdmissionSkipSentence, mlsErrorCode, mlsInitInFlightSync, normalizeActor, normalizeHandle, openMlsClient, parseFacilitatorHeaders, parseX402Payload, peerVerificationLines, performAgentCreation, performRegistration, processMlsWelcomes, readDailySpent, readThreadPage, recordPeerVerification, recoverGroup, refusalReceiptBody, renewalDueWithJitter, requireAuthenticPlaintext, reserveSpend, resolveAgent, resolveApiUrl, resolveConfigDir, resolveFacilitatorConfig, resolveGroup, resolveGroupByHandle, resolveGroupForJoin, resolvePayeeRequirement, resolveThreadRef, resolveToUuid, resumeMlsGroupAdmission, retireLocalGroupState, retirementMessage, saveAgentKeys, saveCredentials, saveHookSecret, savePolicy, savePqEncryptionKey, saveTokenCache, selectRequirement, sendGroupInviteNotification, sendReceipt, senderKeyExplainer, settleToReceipt, singleActorValue, startTlsListener, syncMlsGroup, toBase64Url, validateEncryptionKey, validateSigningKey, validateSlug, verificationWordsLines, verifyIdentitySpiffe, walletKeyExists, withEvictionPointer } from "@rine-network/core";
6
6
  import readline from "node:readline";
7
7
  import { join } from "node:path";
8
8
  import { resolve4 } from "node:dns/promises";
@@ -46,6 +46,219 @@ function printError(msg) {
46
46
  console.error(msg);
47
47
  }
48
48
  //#endregion
49
+ //#region src/acting-agent.ts
50
+ /**
51
+ * The acting-agent ladder, in the one place the CLI climbs it.
52
+ *
53
+ * Rung 1 — what the caller typed — is settled before this module sees it, by
54
+ * `actor.ts`, because two spellings that disagree have to refuse before the
55
+ * call costs a round trip. What is left is the environment, the org's only
56
+ * agent, and the refusal that names them all.
57
+ */
58
+ /**
59
+ * One line of provenance, on stderr, and only when it disambiguates.
60
+ *
61
+ * A single-agent org has nothing to disambiguate and hears nothing; a caller
62
+ * who typed the actor already knows. stdout — and therefore `--json` — is
63
+ * untouched either way.
64
+ */
65
+ function announceEnvActor(agents, agentId) {
66
+ if (agents.length < 2) return;
67
+ printError(`acting as ${agents.find((a) => a.id === agentId)?.name ?? agentId} (from ${ACTING_AGENT_ENV})`);
68
+ }
69
+ /**
70
+ * The other half of that provenance: say so when the environment's choice is
71
+ * what *failed*.
72
+ *
73
+ * A caller who exported `RINE_AGENT` months ago and then renamed the agent
74
+ * reads "No agent named 'ops'" and looks for where they typed `ops` — and in a
75
+ * single-agent org, where the server used to pick the only agent regardless,
76
+ * they have no reason at all to suspect an environment variable. Naming the
77
+ * rung costs one clause and turns an unfalsifiable error into a one-step fix.
78
+ *
79
+ * ⚠️ Multi-agent orgs only, now: a one-agent org resolves a stale `RINE_AGENT`
80
+ * to its only agent and warns, so there is no throw here to decorate. The
81
+ * warning carries that case, and names `RINE_AGENT` itself when the value came
82
+ * off that rung (see `resolve()` below).
83
+ */
84
+ function blameEnvActor(err) {
85
+ const message = err instanceof Error ? err.message : String(err);
86
+ throw new Error(`${message}\n(the acting agent came from ${ACTING_AGENT_ENV}.)`);
87
+ }
88
+ /**
89
+ * Rungs 3, 4 and 5 of the ladder, over a rung-1 value that is already settled.
90
+ *
91
+ * `headers`, when given, is the client's own default header object: resolving
92
+ * writes `X-Rine-Agent` into it, so the rest of the command acts as the agent
93
+ * it just named. A command that scopes by agent in the path (`stream`, `relay`)
94
+ * passes nothing and only wants the id.
95
+ *
96
+ * Takes no `apiUrl`: every rung below reads the org's own agent list, and the
97
+ * one spelling that needs no lookup needs no network either. The ladder cannot
98
+ * reach WebFinger, which is the point — that resolver answers who owns a handle
99
+ * *elsewhere*, and an acting agent is always one of this org's own.
100
+ */
101
+ function actorLadder(flagged, client, headers) {
102
+ let agentList;
103
+ const agents = () => {
104
+ agentList ??= fetchAgents(client);
105
+ return agentList;
106
+ };
107
+ const fromEnv = flagged === void 0 ? actorFromEnv() : void 0;
108
+ const named = flagged ?? fromEnv;
109
+ const resolve = async () => {
110
+ if (named !== void 0 && UUID_RE.test(named)) return named;
111
+ const list = await agents();
112
+ let resolved;
113
+ try {
114
+ resolved = await resolveAgent(list, named, void 0, void 0, fromEnv === void 0 ? "argument" : "environment");
115
+ } catch (err) {
116
+ if (fromEnv !== void 0) blameEnvActor(err);
117
+ throw err;
118
+ }
119
+ if (resolved.warning !== void 0) printError(resolved.warning);
120
+ if (fromEnv !== void 0) announceEnvActor(list, resolved.agentId);
121
+ return resolved.agentId;
122
+ };
123
+ let pending;
124
+ const actingAgent = () => {
125
+ pending ??= resolve().then((id) => {
126
+ if (headers) headers[ACTING_AGENT_HEADER] = id;
127
+ return id;
128
+ });
129
+ return pending;
130
+ };
131
+ return {
132
+ named,
133
+ agents,
134
+ actingAgent
135
+ };
136
+ }
137
+ //#endregion
138
+ //#region src/actor.ts
139
+ /**
140
+ * How the CLI spells the acting agent, in the one place it is spelled.
141
+ *
142
+ * `--agent` is declared per subcommand and never on the program: commander
143
+ * resolves a parent's declared options against the whole argv before it
144
+ * dispatches (`commander/lib/command.js:~1672-1693`), so a program-level
145
+ * `--agent` would steal the flag from `onboard --agent-name`, `send` and
146
+ * `group invite`. The retired spellings — the program's `--as` and
147
+ * `send --from` — stay accepted and are the *same rung* as `--agent`, so two
148
+ * of them that disagree refuse rather than one silently winning.
149
+ *
150
+ * The refusal text, the comparison and the normalisation all come from
151
+ * `rine-core`; nothing here re-implements them, because the MCP server and both
152
+ * SDKs have to print the same sentence.
153
+ */
154
+ /** What `--agent` says in `--help` when a command has nothing to add. */
155
+ const ACTOR_DESCRIPTION = "which agent is acting (name, handle, or agent ID)";
156
+ /** How `--help` mentions the rung below the flag, wherever the flag appears. */
157
+ const ACTOR_ENV_HINT = `(env: ${ACTING_AGENT_ENV})`;
158
+ /**
159
+ * Every actor spelling this process declared, and the label its refusal uses.
160
+ *
161
+ * Keyed by the `Option` object rather than by flag string because `webhook
162
+ * list --agent` is a *filter* — the same flag, a different question — and a
163
+ * name comparison cannot tell them apart.
164
+ */
165
+ const ACTOR_FLAGS = /* @__PURE__ */ new WeakMap();
166
+ /**
167
+ * The actor flag, for a subcommand that needs to know who is acting.
168
+ *
169
+ * It deliberately carries no commander `.env()`. `RINE_AGENT` is rung 3 of the
170
+ * ladder for *every* command that resolves an actor, including the many that
171
+ * declare no flag at all, so it is read once where the ladder is climbed
172
+ * (`acting-agent.ts`) rather than a second time here — a flag that filled
173
+ * itself from the environment would then have to be told apart from one the
174
+ * caller typed, or the conflict check would refuse a pairing the caller never
175
+ * made. The help text still says where the value can come from.
176
+ */
177
+ function actorOption(description = ACTOR_DESCRIPTION) {
178
+ const option = new Option(`${ACTOR_SURFACES.cli.canonical} <agent>`, `${description} ${ACTOR_ENV_HINT}`);
179
+ ACTOR_FLAGS.set(option, ACTOR_SURFACES.cli.canonical);
180
+ return option;
181
+ }
182
+ /**
183
+ * A retired spelling of the actor flag, still accepted.
184
+ *
185
+ * The *same rung* as `--agent`, which is what makes two of them that disagree
186
+ * a refusal rather than a precedence rule.
187
+ */
188
+ function actorAliasOption(flags, description) {
189
+ const option = new Option(flags, description);
190
+ ACTOR_FLAGS.set(option, flags.split(" ")[0] ?? flags);
191
+ return option;
192
+ }
193
+ function isCommand(value) {
194
+ const candidate = value;
195
+ return typeof candidate === "object" && candidate !== null && typeof candidate.getOptionValue === "function" && Array.isArray(candidate.options);
196
+ }
197
+ /**
198
+ * The command commander appended to the action's arguments, when there is one.
199
+ *
200
+ * `Command._actionHandler` pushes `this` last (`command.js:534-542`), but the
201
+ * CLI's own tests call a wrapped action directly with plain objects, so the
202
+ * last argument is only *usually* a command.
203
+ */
204
+ function commandOf(args) {
205
+ const last = args[args.length - 1];
206
+ return isCommand(last) ? last : void 0;
207
+ }
208
+ /** Actor values this invocation typed, in declaration order. Env is not one. */
209
+ function typedActorValues(command) {
210
+ if (command === void 0) return [];
211
+ const typed = [];
212
+ for (const option of command.options) {
213
+ const flag = ACTOR_FLAGS.get(option);
214
+ if (flag === void 0) continue;
215
+ typed.push({
216
+ flag,
217
+ value: command.getOptionValue(option.attributeName())
218
+ });
219
+ }
220
+ return typed;
221
+ }
222
+ /**
223
+ * The one actor value this command line names, or a refusal naming both.
224
+ *
225
+ * Folded pairwise through `rine-core`'s comparison so the sentence a caller
226
+ * reads is the same one every other surface prints, with this pair's spellings
227
+ * in it.
228
+ */
229
+ function oneActorValue(candidates) {
230
+ let chosen;
231
+ for (const candidate of candidates) {
232
+ const value = normalizeActor(candidate.value);
233
+ if (value === void 0) continue;
234
+ if (chosen === void 0) {
235
+ chosen = {
236
+ flag: candidate.flag,
237
+ value
238
+ };
239
+ continue;
240
+ }
241
+ singleActorValue(chosen.value, value, {
242
+ ...ACTOR_SURFACES.cli,
243
+ canonical: chosen.flag,
244
+ alias: candidate.flag
245
+ });
246
+ }
247
+ return chosen?.value;
248
+ }
249
+ /**
250
+ * Rung 1: the actor this command line names, by any of its spellings.
251
+ *
252
+ * `undefined` means nobody was named here, which is the ladder's cue to fall
253
+ * through to `RINE_AGENT` and then to the org's only agent.
254
+ */
255
+ function namedActor(command, gOpts) {
256
+ return oneActorValue([...typedActorValues(command), {
257
+ flag: ACTOR_SURFACES.cli.alias,
258
+ value: gOpts.as
259
+ }]);
260
+ }
261
+ //#endregion
49
262
  //#region src/action.ts
50
263
  async function createClient(configDir, apiUrl, profileFlag, defaultHeaders) {
51
264
  const profileName = profileFlag ?? "default";
@@ -67,23 +280,34 @@ async function createClient(configDir, apiUrl, profileFlag, defaultHeaders) {
67
280
  entry
68
281
  };
69
282
  }
70
- function withClient(program, fn) {
283
+ function withClient(program, fn, precheck) {
71
284
  return async (...args) => {
72
285
  try {
286
+ if (precheck) {
287
+ const refusal = precheck(...args);
288
+ if (refusal !== null) {
289
+ printError(refusal);
290
+ process.exitCode = 2;
291
+ return;
292
+ }
293
+ }
73
294
  const gOpts = program.opts();
295
+ const flagged = namedActor(commandOf(args), gOpts);
74
296
  const configDir = resolveConfigDir();
75
297
  const apiUrl = resolveApiUrl();
76
298
  const defaultHeaders = {};
77
- if (gOpts.as && !isBareAgentName(gOpts.as)) defaultHeaders["X-Rine-Agent"] = await resolveToUuid(apiUrl, gOpts.as);
78
299
  const { client, profileName } = await createClient(configDir, apiUrl, gOpts.profile, defaultHeaders);
79
- if (gOpts.as && isBareAgentName(gOpts.as)) defaultHeaders["X-Rine-Agent"] = await resolveAgent(apiUrl, await fetchAgents(client), void 0, gOpts.as);
300
+ const { named, agents, actingAgent } = actorLadder(flagged, client, defaultHeaders);
301
+ if (named !== void 0) await actingAgent();
80
302
  await fn({
81
303
  client,
82
304
  gOpts,
83
305
  profileName,
84
306
  configDir,
85
307
  apiUrl,
86
- extraHeaders: defaultHeaders
308
+ extraHeaders: defaultHeaders,
309
+ agents,
310
+ actingAgent
87
311
  }, ...args);
88
312
  } catch (err) {
89
313
  printError(formatError(err));
@@ -236,7 +460,7 @@ function registerAgentProfile(program) {
236
460
  });
237
461
  printMutationOk("Skill added", gOpts.json);
238
462
  }));
239
- agent.command("set-pricing").description("Set agent pricing model and/or x402 payment terms (rine.x402.terms)").argument("<agent-id>", "Agent ID").option("--model <model>", `Pricing model (${VALID_PRICING.join("|")})`).option("--x402-terms <json>", "x402 card terms as a JSON array (REQ-P03 shape); advisory only").option("--x402-terms-file <path>", "Read the x402 terms JSON array from a file (use - for stdin)").action(withClient(program, async ({ client, gOpts }, agentId, opts) => {
463
+ agent.command("set-pricing").description("Set agent pricing model and/or x402 payment terms (rine.x402.terms)").argument("<agent-id>", "Agent ID").option("--model <model>", `Pricing model (${VALID_PRICING.join("|")})`).option("--x402-terms <json>", "x402 card terms as a JSON array; advisory only").option("--x402-terms-file <path>", "Read the x402 terms JSON array from a file (use - for stdin)").action(withClient(program, async ({ client, gOpts }, agentId, opts) => {
240
464
  if (opts.model === void 0 && opts.x402Terms === void 0 && opts.x402TermsFile === void 0) {
241
465
  printError("Nothing to set. Provide --model and/or --x402-terms/--x402-terms-file.");
242
466
  process.exitCode = 2;
@@ -287,20 +511,69 @@ function registerAgentProfile(program) {
287
511
  }
288
512
  //#endregion
289
513
  //#region src/agent-format.ts
514
+ /**
515
+ * One agent as a table row.
516
+ *
517
+ * `verification` is the comparison between the words this client derives from
518
+ * the key it holds and the words the server asserts — never the server's string
519
+ * on its own. When the two disagree the row carries **both**, in two columns,
520
+ * because a mismatch is a state to read rather than an error to swallow. When
521
+ * this client holds no key for the agent, only the server's column appears, so
522
+ * the header says whose statement it is.
523
+ */
290
524
  function toAgentRow(a, opts = {}) {
291
525
  const row = {
292
526
  ID: a.id,
293
527
  Name: a.name,
294
- Handle: a.handle,
528
+ Handle: a.handle ?? a.id,
295
529
  "Human Oversight": String(a.human_oversight),
296
530
  Created: a.created_at
297
531
  };
298
- if (opts.includeVerificationWords && a.verification_words) row["Verification Words"] = a.verification_words;
532
+ const v = opts.verification;
533
+ if (v) {
534
+ if (v.computed !== null) row["Verification Words"] = v.computed;
535
+ if (v.asserted !== null && v.status !== "match") row["Verification Words (server)"] = v.asserted;
536
+ }
299
537
  if (opts.includeCard) row.Card = a.unlisted ? "unlisted" : "public";
300
538
  if (opts.includeRevoked) row.Revoked = a.revoked_at ? String(a.revoked_at) : "—";
301
539
  return row;
302
540
  }
303
541
  //#endregion
542
+ //#region src/handle-completion.ts
543
+ /**
544
+ * Tell the caller when the spelling they typed was not the spelling looked up.
545
+ *
546
+ * 🔴 Item 18. `resolveToUuid` completes a short handle before it reaches
547
+ * WebFinger — `kofi@acme` is looked up as `kofi@acme.rine.network` — and it
548
+ * returns the resolved UUID, never the handle it resolved. So the substitution
549
+ * is invisible at every call site by construction: the caller asked about one
550
+ * agent and may be told about another, with nothing on either stream saying so.
551
+ *
552
+ * The completion itself is a good default and stays. What changes is that it
553
+ * stops being silent.
554
+ *
555
+ * 🔴 STDERR, and deliberately NOT gated on `--json`: the machine reader is the
556
+ * caller a silent rewrite harms most, and stdout stays byte-for-byte parseable
557
+ * because the notice was never on it.
558
+ *
559
+ * 🔴 The SENTENCE is {@link handleCompletionNote}'s, in `@rine-network/core`,
560
+ * and is not retyped here. Four surfaces say it and each renders it
561
+ * differently — a stderr line here, a result key on `@rine-network/mcp`, a
562
+ * result line on `rine-mastra` and `rine-eve` — so the bytes live in one place
563
+ * and this module decides only where they go. That also keeps `normalizeHandle`
564
+ * CALLED rather than restated: a second copy of the completion rule could
565
+ * disagree with the lookup and announce a substitution that never happened.
566
+ *
567
+ * What that composer returns for a value with no `@`, or for a UUID, is
568
+ * nothing — and this prints nothing, which is correct: `resolveToUuid` refuses
569
+ * that arm outright rather than completing it, so there is no substitution to
570
+ * report.
571
+ */
572
+ function announceHandleCompletion(spelling) {
573
+ const note = handleCompletionNote(spelling);
574
+ if (note !== void 0) printError(note);
575
+ }
576
+ //#endregion
304
577
  //#region src/prompt.ts
305
578
  /** Prompt for a plain-text value on stdout/stdin. */
306
579
  async function promptText(question) {
@@ -345,6 +618,76 @@ async function promptConfirm(question) {
345
618
  return (await promptText(`${question} [y/N] `)).toLowerCase() === "y";
346
619
  }
347
620
  //#endregion
621
+ //#region src/commands/agent-verify.ts
622
+ /**
623
+ * `rine agent verify <peer>` — the out-of-band compare/confirm flow.
624
+ *
625
+ * Verification words recomputed locally show that this config dir and the
626
+ * server agree about **this** agent's signing key. They show nothing about a
627
+ * peer: a peer's words and any key that could be fetched for it both come from
628
+ * the same server. Two operators reading five words to each other is what
629
+ * closes that, and this verb puts the two strings side by side and remembers
630
+ * that it happened.
631
+ *
632
+ * Advisory by design. A peer that has never been confirmed is still reachable
633
+ * and still sends — this is a display of key agreement, not an access control.
634
+ */
635
+ function registerAgentVerify(program, agent) {
636
+ agent.command("verify").description("Compare a peer's verification words with this agent's, and record the result").argument("<peer>", "Peer handle (e.g. bot@acme) or agent UUID").addOption(actorOption("which agent is acting, and whose words these are (name, handle, or agent ID)")).option("--yes", "Record the confirmation without prompting").action(withClient(program, async ({ client, gOpts, configDir, apiUrl, actingAgent, agents }, peer, opts) => {
637
+ const ownId = await actingAgent();
638
+ const own = (await agents()).find((a) => a.id === ownId);
639
+ announceHandleCompletion(peer);
640
+ const peerId = await resolveToUuid(apiUrl, peer);
641
+ if (peerId.toLowerCase() === ownId.toLowerCase()) {
642
+ printError("That is this agent. Words are confirmed with another operator, not with yourself.");
643
+ process.exitCode = 2;
644
+ return;
645
+ }
646
+ const state = await buildPeerVerification(client, configDir, ownId, peerId);
647
+ const comparison = compareVerificationWordsForAgent(configDir, ownId, own?.verification_words);
648
+ if (!gOpts.json) for (const line of peerVerificationLines(state, comparison, own?.handle ?? ownId)) printText(line);
649
+ const words = state.peer.words;
650
+ let recorded = false;
651
+ if (words !== null) {
652
+ if (opts.yes) recorded = true;
653
+ else if (!gOpts.json) {
654
+ printText("");
655
+ recorded = await promptConfirm("Did the peer's operator read back the same words?");
656
+ }
657
+ if (recorded) recordPeerVerification(configDir, ownId, {
658
+ peerAgentId: state.peerAgentId,
659
+ handle: state.peer.handle,
660
+ words
661
+ });
662
+ }
663
+ if (gOpts.json) {
664
+ printJson({
665
+ agent: {
666
+ id: ownId,
667
+ handle: own?.handle ?? null
668
+ },
669
+ peer: {
670
+ agent_id: state.peerAgentId,
671
+ handle: state.peer.handle,
672
+ verification_words: words,
673
+ card_published: state.peer.published,
674
+ card_unreadable: state.peer.unreadable
675
+ },
676
+ verification: comparison,
677
+ confirmed: state.confirmed,
678
+ words_changed_since_confirmed: state.wordsChangedSinceConfirmed,
679
+ recorded
680
+ });
681
+ return;
682
+ }
683
+ if (words === null) {
684
+ printText("");
685
+ printText("Their card names no words, so there is nothing to record.");
686
+ } else if (recorded) printSuccess(`Confirmed ${state.peer.handle ?? state.peerAgentId}. Run this again if their card changes.`);
687
+ else printText("Nothing recorded.");
688
+ }));
689
+ }
690
+ //#endregion
348
691
  //#region src/commands/agent.ts
349
692
  function registerAgent(program) {
350
693
  const agent = program.command("agent").description("Agent management");
@@ -363,15 +706,19 @@ function registerAgent(program) {
363
706
  humanOversight: opts.humanOversight,
364
707
  unlisted: opts.unlisted
365
708
  });
366
- if (gOpts.json) printJson(data);
709
+ const verification = compareVerificationWordsForAgent(configDir, data.id, data.verification_words);
710
+ if (gOpts.json) printJson({
711
+ ...data,
712
+ verification
713
+ });
367
714
  else {
368
715
  printTable([toAgentRow(data, {
369
716
  includeCard: true,
370
- includeVerificationWords: true
717
+ verification
371
718
  })]);
372
719
  console.log(`\nAgent '${data.name}' created \u2014 reachable at ${data.handle}`);
373
720
  console.log("E2EE keys generated and stored locally.");
374
- if (data.verification_words) console.log(`Verification words: ${data.verification_words}`);
721
+ for (const line of verificationWordsLines(verification)) console.log(line);
375
722
  if (data.poll_url) console.log(`Poll URL: ${data.poll_url}`);
376
723
  if (data.identity) console.log(`SPIFFE identity verified: ${data.identity.spiffe_id} (trust tier ${data.identity.trust_tier})`);
377
724
  }
@@ -426,6 +773,7 @@ function registerAgent(program) {
426
773
  process.exitCode = 1;
427
774
  }
428
775
  }));
776
+ registerAgentVerify(program, agent);
429
777
  }
430
778
  //#endregion
431
779
  //#region src/commands/auth.ts
@@ -478,20 +826,21 @@ function registerAuth(program) {
478
826
  }
479
827
  try {
480
828
  const token = await getOrRefreshToken(configDir, apiUrl, entry, profile);
829
+ const defaultHeaders = {};
481
830
  const client = new HttpClient({
482
831
  tokenFn: () => Promise.resolve(token),
483
832
  apiUrl,
484
833
  canRefresh: false,
485
- defaultHeaders: {}
834
+ defaultHeaders
486
835
  });
836
+ const { agents, actingAgent } = actorLadder(namedActor(void 0, gOpts), client, defaultHeaders);
487
837
  const org = await client.get("/org");
488
838
  let agentHandle;
489
839
  let agentId;
490
840
  let keysLabel;
491
841
  try {
492
- const agents = await fetchAgents(client);
493
- agentId = await resolveAgent(apiUrl, agents, void 0, gOpts.as);
494
- agentHandle = agents.find((a) => a.id === agentId)?.handle;
842
+ agentId = await actingAgent();
843
+ agentHandle = (await agents()).find((a) => a.id === agentId)?.handle ?? void 0;
495
844
  const hasLocal = agentKeysExist(configDir, agentId);
496
845
  let hasServer = false;
497
846
  try {
@@ -604,6 +953,242 @@ async function showOrgStatus(client, gOpts) {
604
953
  ]);
605
954
  }
606
955
  //#endregion
956
+ //#region src/commands/group-eviction.ts
957
+ const EVICTED_EXPLAINED = "A Remove commit evicted this agent's leaf from the group's ratchet tree, so it can no longer send to the group, read anything committed since, or admit anyone. Ask an admin to invite you again — returning takes a fresh invitation and a new Welcome, not the keys this agent still holds.";
958
+ /**
959
+ * What rine says when the native core reports this agent's handle is retired.
960
+ *
961
+ * `isActive()` goes false exactly once: a Remove commit evicted this member's
962
+ * leaf. Until eviction shipped nothing ever sent that commit, so the state was
963
+ * unreachable and every surface would have shown whatever the mls-rs binding
964
+ * said. An evicted agent is told it was evicted, in rine's words, and what to
965
+ * do about it.
966
+ */
967
+ function evictedMessage(groupId) {
968
+ return `You were removed from group ${groupId}. ${EVICTED_EXPLAINED}`;
969
+ }
970
+ /**
971
+ * True when a Remove commit has already evicted this agent from the group.
972
+ *
973
+ * Local and network-free: the ratchet tree is what knows, and it is on disk.
974
+ * Null means the question could not be answered — no local state, no key
975
+ * material, an unreadable store — which is not the same as "still a member".
976
+ */
977
+ function isEvictedFrom(configDir, agentId, groupId) {
978
+ try {
979
+ const group = loadMlsGroup(openMlsClient(configDir, agentId), groupId);
980
+ return group === null ? null : !group.isActive();
981
+ } catch {
982
+ return null;
983
+ }
984
+ }
985
+ /**
986
+ * Re-word a group read the server refused, when this agent's own MLS state says
987
+ * it used to be a member.
988
+ *
989
+ * This is the case eviction detection exists for and the only one an evicted
990
+ * agent normally reaches. `has_read_access` (`src/rine/api/group_helpers.py`)
991
+ * 403s an evicted agent from another org, so the read never returns a group at
992
+ * all — a check that runs on the response body cannot fire, and the operator
993
+ * gets a bare refusal identical to the one an agent who was never a member
994
+ * gets.
995
+ *
996
+ * `holdsMlsState` is what answers it, not `isEvictedFrom`: holding local MLS
997
+ * state for a group the server will not let you read means one thing, whereas
998
+ * `isActive()` turns false only once the Remove commit has been applied
999
+ * locally, and an evicted agent has no reason to have synced. Everything else
1000
+ * is returned untouched, so an agent who was never a member still gets the
1001
+ * server's own answer, and an open (Sender-Keys) group — which holds no MLS
1002
+ * state and has no cryptographic eviction at all — is never described
1003
+ * as one.
1004
+ *
1005
+ * The acting agent is resolved through a callback and only on the refusal path,
1006
+ * so a read that succeeded costs no extra round trip.
1007
+ */
1008
+ async function asGroupAccessError(configDir, groupId, err, actingAgent) {
1009
+ if (!(err instanceof RineApiError)) return err;
1010
+ if (err.status !== 403 && err.status !== 404) return err;
1011
+ return await asEvictionRefusal(configDir, groupId, err, actingAgent);
1012
+ }
1013
+ /**
1014
+ * The same rewrite, for a refusal whose status has already been swallowed.
1015
+ *
1016
+ * `resolveGroup`'s UUID rung catches exactly the 403/404 the guard above needs
1017
+ * and rethrows the roster refusal in its place, so a verb that resolves its
1018
+ * argument before it reads has no status left to branch on — only the local
1019
+ * question, which is the one that actually decides it. Its own export rather
1020
+ * than a loosening of the guard above: a caller still holding a live
1021
+ * `RineApiError` must prove the status, or a 500 comes back as an eviction.
1022
+ */
1023
+ async function asEvictionRefusal(configDir, groupId, err, actingAgent) {
1024
+ try {
1025
+ if (!holdsMlsState(configDir, await actingAgent(), groupId)) return err;
1026
+ } catch {
1027
+ return err;
1028
+ }
1029
+ return new Error(evictedMessage(groupId), { cause: err });
1030
+ }
1031
+ //#endregion
1032
+ //#region src/commands/group-target.ts
1033
+ /**
1034
+ * How every group verb on this CLI takes the group it acts on.
1035
+ *
1036
+ * Thirteen commands used to declare `.argument("<group-id>", "Group ID")` and
1037
+ * hand the raw string straight to `GET /groups/{id}`. That sentence was TRUE:
1038
+ * nothing on this surface called `resolveGroup`, and the server does not answer
1039
+ * `/groups/{handle}`, so a handle really was refused. Taking one is therefore a
1040
+ * user-visible WIDENING, not a help-text tidy-up — twelve verbs begin
1041
+ * accepting a handle, a name and a unique prefix here for the first time, and
1042
+ * the resolve happens in ONE place instead of thirteen. `rine thread --group`
1043
+ * is the only group reference that already climbed the ladder; its help string
1044
+ * is the one these twelve now share.
1045
+ *
1046
+ * 🔴 `GROUP_REFERENCE_HELP` stays HERE and is deliberately not hoisted into
1047
+ * `rine-core`. A constant in the shared package is a constant the Python stack
1048
+ * is then expected to twin (`GROUP_NOT_FOUND_LEAD` and `GENERIC_GROUP_NOUNS`
1049
+ * both are, and both are gated), and this is CLI help text for a CLI argument —
1050
+ * there is no Python twin to keep it honest with, so hoisting it would mint an
1051
+ * obligation nothing pays.
1052
+ *
1053
+ * 🔴 **`join` is not on this ladder.** {@link joinGroupTarget} is a separate
1054
+ * export for a separate resolver, and the two must never be collapsed: `join`
1055
+ * is aimed at a group this org holds no seat in by definition, so the member
1056
+ * ladder's first rung — the org's own group list — is the one thing that cannot
1057
+ * answer it.
1058
+ */
1059
+ /**
1060
+ * What the twelve member-ladder group arguments say they take.
1061
+ *
1062
+ * Byte-for-byte the sentence `rine thread --group` already published, because
1063
+ * the two resolve through the same ladder and a caller who reads both must not
1064
+ * be told they differ.
1065
+ */
1066
+ const GROUP_REFERENCE_HELP = "Group handle (e.g. #logistics@acme.rine.network), name or UUID";
1067
+ /**
1068
+ * What the thirteenth one says instead.
1069
+ *
1070
+ * `rine discover groups inspect` reads the PUBLIC directory, which is not the
1071
+ * caller's own group list: the member ladder's rungs — the org roster, a
1072
+ * normalised name, a unique prefix — have nothing to match against there, so
1073
+ * the widening the other twelve verbs got cannot land here. The help
1074
+ * says so, and {@link directoryGroupUuidRefusal} says it again to anyone who
1075
+ * tries.
1076
+ */
1077
+ const DIRECTORY_GROUP_ID_HELP = "Group UUID (the public directory indexes groups by id only — `rine discover groups` lists them with theirs)";
1078
+ /**
1079
+ * The refusal `rine discover groups inspect` gives a handle or a name.
1080
+ *
1081
+ * 🔴 It does NOT open with `GROUP_NOT_FOUND_LEAD`: nothing was looked up. The
1082
+ * reference was refused on its shape, before any request, and six published
1083
+ * surfaces branch on that lead to decide which half of the directory a model is
1084
+ * sent to. Naming the two verbs that DO take a name is the whole point — a
1085
+ * refusal that only says no leaves the caller with the same question.
1086
+ */
1087
+ function directoryGroupUuidRefusal(ref) {
1088
+ return `'${ref}' is not a group UUID, and the public directory indexes groups by id only. Run \`rine discover groups\` to find the group and its UUID, or — for a group this org is already in — \`rine group get\`, which takes a handle or a name.`;
1089
+ }
1090
+ /**
1091
+ * Widen an unknown-group refusal with the eviction pointer, where it applies.
1092
+ *
1093
+ * The arm above it — a reference that is not a UUID — is where the eviction
1094
+ * sentence is unreachable: the ladder resolved to no row, so there is
1095
+ * no group id to ask `holdsMlsState` with, and an evicted agent naming its
1096
+ * group by handle reads "Group not found" over a roster it is no longer on.
1097
+ * That case is answered with a POINTER instead, composed in `rine-core`
1098
+ * beside the refusal it grows onto.
1099
+ *
1100
+ * Three gates, in this order and lazily, which is the whole cost argument:
1101
+ *
1102
+ * 1. the error is the UNKNOWN-group refusal, decided by the lead six published
1103
+ * surfaces already branch on. 🔴 An AMBIGUOUS reference opens with a
1104
+ * different lead and must not get this — it resolved to too many rows, not
1105
+ * to none — and neither must a transport failure, which opens with neither;
1106
+ * 2. only then {@link ActionContext.actingAgent}, which costs a round trip on
1107
+ * a multi-agent org;
1108
+ * 3. only then the local store scan.
1109
+ *
1110
+ * Either of the last two raising returns the error untouched, exactly as
1111
+ * {@link asEvictionRefusal} does: a store that cannot be read, or a caller
1112
+ * whose acting agent cannot be named, has not proved anything about a removal.
1113
+ *
1114
+ * 🔴 Not threaded down into `matchGroupByName`. That function is synchronous
1115
+ * and a published export of `@rine-network/core`, `actingAgent()` is async, and
1116
+ * computing the fact eagerly would pay it on every group verb call rather than
1117
+ * on the refusal path it is confined to.
1118
+ *
1119
+ * 🔴 Exported because {@link groupTarget} is not the only place these two
1120
+ * spellings are refused. `rine send --to '#standup@acme.rine.network'` does not
1121
+ * climb this ladder — it calls `resolveGroupByHandle` itself — and `send` is
1122
+ * the verb an evicted agent is most likely to reach for. One group, one
1123
+ * spelling, two different answers on two verbs is the inconsistency this
1124
+ * trigger exists to end, so it is shared rather than re-derived.
1125
+ *
1126
+ * 🔴 It stays off the JOIN path. {@link joinGroupTarget} names a group this org
1127
+ * holds no seat in BY DEFINITION, so "you may have been removed" is nonsense
1128
+ * there, not a milder version of the truth.
1129
+ */
1130
+ async function withEvictionPointerIfHeld(ctx, err) {
1131
+ if (!(err instanceof Error)) return err;
1132
+ if (!err.message.startsWith(GROUP_NOT_FOUND_LEAD)) return err;
1133
+ try {
1134
+ if (!holdsAnyMlsState(ctx.configDir, await ctx.actingAgent())) return err;
1135
+ } catch {
1136
+ return err;
1137
+ }
1138
+ return new Error(withEvictionPointer(err.message), { cause: err });
1139
+ }
1140
+ /**
1141
+ * Resolve one of the twelve member-ladder group arguments, carrying the row.
1142
+ *
1143
+ * The row comes back because {@link resolveGroup} already paid for it: its UUID
1144
+ * rung reads `GET /groups/{id}` and its two name rungs match against the org
1145
+ * roster, so a caller that re-fetches the group afterwards is buying a row it
1146
+ * was handed. Every PRE-mutation read on this CLI folds into this call. A read
1147
+ * taken AFTER the verb mutated the group does not, and must not — that one is
1148
+ * asking what the group became, which is a different question from what it was.
1149
+ *
1150
+ * 🔴 **The eviction wrap is load-bearing, not defensive.** `readableGroupById`
1151
+ * swallows exactly the 403 and 404 that `asGroupAccessError` needs and rethrows
1152
+ * the roster refusal instead, so an evicted agent naming its group by UUID
1153
+ * would be told "Group not found" and a list it is no longer on — the eviction
1154
+ * sentence pre-empted by the very read that used to raise it. The status is
1155
+ * gone by the time we catch, which is why this asks the local question
1156
+ * ({@link asEvictionRefusal}) rather than re-running the status guard.
1157
+ *
1158
+ * A `RineApiError` that reaches here is some OTHER fault — the UUID rung
1159
+ * rethrows anything that is not a 403/404 — and keeps its own message.
1160
+ */
1161
+ async function groupTarget(ctx, ref) {
1162
+ try {
1163
+ return await resolveGroup(ctx.client, ref, { extraHeaders: ctx.extraHeaders });
1164
+ } catch (err) {
1165
+ if (!UUID_RE.test(ref)) throw await withEvictionPointerIfHeld(ctx, err);
1166
+ const actingAgent = () => ctx.actingAgent();
1167
+ throw err instanceof RineApiError ? await asGroupAccessError(ctx.configDir, ref, err, actingAgent) : await asEvictionRefusal(ctx.configDir, ref, err, actingAgent);
1168
+ }
1169
+ }
1170
+ /**
1171
+ * Resolve `rine group join`'s argument — the one verb aimed outside the org.
1172
+ *
1173
+ * 🔴 **`resolveGroupForJoin`, never `resolveGroup`.** The rungs differ because
1174
+ * the question differs: `join` names a group this org holds no seat in, so
1175
+ * `GET /groups` answering nothing is this ladder's FIRST rung rather than its
1176
+ * refusal, and its UUID rung is a passthrough on purpose — there is no
1177
+ * readable row to check it against, and inventing one would be a client
1178
+ * asserting a membership fact it has not been told.
1179
+ *
1180
+ * `row` and `handle` come back UNSET for that reason, and a caller that needs
1181
+ * either asks after the join lands. No eviction wrap: an agent that holds MLS
1182
+ * state for a group it is joining is not the eviction case at all.
1183
+ *
1184
+ * Headers are the client's own defaults and nothing more — resolving the acting
1185
+ * agent here would make a multi-agent org name one before it may join, which is
1186
+ * a refusal this verb does not have today.
1187
+ */
1188
+ async function joinGroupTarget(ctx, ref) {
1189
+ return await resolveGroupForJoin(ctx.client, ref, { extraHeaders: ctx.extraHeaders });
1190
+ }
1191
+ //#endregion
607
1192
  //#region src/commands/discover-groups.ts
608
1193
  function registerDiscoverGroups(discover, program) {
609
1194
  discover.command("groups").description("List public groups in the directory").option("-q, --query <query>", "Search query").option("--limit <n>", "Max results").option("--cursor <cursor>", "Pagination cursor").action(withErrorHandler(program, async (gOpts, opts) => {
@@ -624,7 +1209,12 @@ function registerDiscoverGroups(discover, program) {
624
1209
  Enrollment: g.enrollment_policy,
625
1210
  Members: g.member_count
626
1211
  })));
627
- })).command("inspect").description("Inspect a public group").argument("<group-id>", "Group ID").action(withErrorHandler(program, async (gOpts, groupId) => {
1212
+ })).command("inspect").description("Inspect a public group").argument("<group-id>", DIRECTORY_GROUP_ID_HELP).action(withErrorHandler(program, async (gOpts, groupId) => {
1213
+ if (!UUID_RE.test(groupId)) {
1214
+ printError(directoryGroupUuidRefusal(groupId));
1215
+ process.exitCode = 1;
1216
+ return;
1217
+ }
628
1218
  const apiUrl = resolveApiUrl();
629
1219
  const data = await HttpClient.publicGet(apiUrl, `/directory/groups/${groupId}`);
630
1220
  if (gOpts.json) {
@@ -680,12 +1270,12 @@ async function doAgentSearch(opts, gOpts) {
680
1270
  })));
681
1271
  if (result.next_cursor) printText(`Next cursor: ${result.next_cursor}`);
682
1272
  }
683
- const collect = (v, prev) => [...prev, v];
1273
+ const collect$1 = (v, prev) => [...prev, v];
684
1274
  function addAgentSearchCommand(parent, name, description, program, requireQuery) {
685
1275
  const cmd = parent.command(name).description(description);
686
1276
  if (requireQuery) cmd.requiredOption("-q, --query <query>", "Search query");
687
1277
  else cmd.option("-q, --query <query>", "Search query");
688
- cmd.option("--category <cat>", "Category filter (repeatable)", collect, []).option("--tag <tag>", "Tag filter (repeatable)", collect, []).option("--jurisdiction <j>", "Jurisdiction filter").option("--language <lang>", "Language filter (repeatable)", collect, []).option("--verified", "Only verified agents").option("--no-verified", "Only unverified agents").option("--pricing-model <model>", "Pricing model filter").option("--limit <n>", "Max results").option("--cursor <cursor>", "Pagination cursor").option("--sort <sort>", "Sort order (relevance|name|created_at)").action(withErrorHandler(program, async (gOpts, opts) => {
1278
+ cmd.option("--category <cat>", "Category filter (repeatable)", collect$1, []).option("--tag <tag>", "Tag filter (repeatable)", collect$1, []).option("--jurisdiction <j>", "Jurisdiction filter").option("--language <lang>", "Language filter (repeatable)", collect$1, []).option("--verified", "Only verified agents").option("--no-verified", "Only unverified agents").option("--pricing-model <model>", "Pricing model filter").option("--limit <n>", "Max results").option("--cursor <cursor>", "Pagination cursor").option("--sort <sort>", "Sort order (relevance|name|created_at)").action(withErrorHandler(program, async (gOpts, opts) => {
689
1279
  await doAgentSearch(opts, gOpts);
690
1280
  }));
691
1281
  }
@@ -707,13 +1297,8 @@ function registerDiscover(program) {
707
1297
  }));
708
1298
  discover.command("inspect").description("Inspect a specific agent in the directory").argument("<agent-id>", "Agent UUID or handle").action(withErrorHandler(program, async (gOpts, agentIdArg) => {
709
1299
  const apiUrl = resolveApiUrl();
710
- let resolvedId = agentIdArg;
711
- if (agentIdArg.includes("@")) resolvedId = await resolveHandleViaWebFinger(apiUrl, agentIdArg);
712
- if (!UUID_RE.test(resolvedId)) {
713
- printError(`Could not resolve '${agentIdArg}' to an agent UUID. Provide a UUID or a valid handle (e.g. agent@org).`);
714
- process.exitCode = 1;
715
- return;
716
- }
1300
+ announceHandleCompletion(agentIdArg);
1301
+ const resolvedId = await resolveToUuid(apiUrl, agentIdArg);
717
1302
  const data = await HttpClient.publicGet(apiUrl, `/directory/agents/${resolvedId}`);
718
1303
  if (gOpts.json) {
719
1304
  printJson(data);
@@ -802,7 +1387,8 @@ function collectHeader(v, acc) {
802
1387
  return acc;
803
1388
  }
804
1389
  function registerFulfill(program) {
805
- program.command("fulfill").description("Settle a received x402_payment via the facilitator and reply with an x402_receipt. The payment is bound to the ONE payee-issued x402_payment_required quote it references (the signed quoteMessageId) and reconciled against THAT quote (payTo/amount/asset/network/scheme) — the payer's echoed terms are never trusted. A payment carrying no/forged/cross-conversation quote reference REFUSES to settle (fail closed) unless explicit expected terms (--pay-to/--expect-amount/--expect-asset/--expect-network) authorise an out-of-band quote.").argument("<message-id>", "ID of the received rine.v1.x402_payment").option("--agent <id>", "Payee agent ID (defaults to your agent)").option("--facilitator <preset|url>", "Facilitator preset (cdp | payai | x402-rs) or an http(s):// base URL", "payai").option("--facilitator-header <k:v>", "Auth header for the facilitator (repeatable), e.g. 'Authorization: Bearer …'", collectHeader, []).option("--verify-path <path>", "Override the facilitator /verify path").option("--settle-path <path>", "Override the facilitator /settle path").option("--pay-to <address>", "Out-of-band quote: expected payee wallet (0x). Requires --expect-amount/--expect-asset/--expect-network; overrides the referenced quote (no quoteMessageId needed)").option("--expect-amount <major>", "Out-of-band quote: expected amount in MAJOR units (e.g. 1.00). Overpayment is accepted, underpayment refused").option("--expect-asset <address>", "Out-of-band quote: expected token contract (0x)").option("--expect-network <caip2>", "Out-of-band quote: expected CAIP-2 network (e.g. eip155:8453)").option("--no-marker", "Omit the cleartext status marker (fully sealed)").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, messageId, opts) => {
1390
+ program.command("fulfill").description("Settle a received x402_payment via the facilitator and reply with an x402_receipt. The payment is bound to the ONE payee-issued x402_payment_required quote it references (the signed quoteMessageId) and reconciled against THAT quote (payTo/amount/asset/network/scheme) — the payer's echoed terms are never trusted. A payment carrying no/forged/cross-conversation quote reference REFUSES to settle (fail closed) unless explicit expected terms (--pay-to/--expect-amount/--expect-asset/--expect-network) authorise an out-of-band quote.").argument("<message-id>", "ID of the received rine.v1.x402_payment").addOption(actorOption("which agent is acting, as payee (name, handle, or agent ID)")).option("--facilitator <preset|url>", "Facilitator preset (cdp | payai | x402-rs) or an http(s):// base URL", "payai").option("--facilitator-header <k:v>", "Auth header for the facilitator (repeatable), e.g. 'Authorization: Bearer …'", collectHeader, []).option("--verify-path <path>", "Override the facilitator /verify path").option("--settle-path <path>", "Override the facilitator /settle path").option("--pay-to <address>", "Out-of-band quote: expected payee wallet (0x). Requires --expect-amount/--expect-asset/--expect-network; overrides the referenced quote (no quoteMessageId needed)").option("--expect-amount <major>", "Out-of-band quote: expected amount in MAJOR units (e.g. 1.00). Overpayment is accepted, underpayment refused").option("--expect-asset <address>", "Out-of-band quote: expected token contract (0x)").option("--expect-network <caip2>", "Out-of-band quote: expected CAIP-2 network (e.g. eip155:8453)").option("--no-marker", "Omit the cleartext status marker (fully sealed)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, messageId, opts) => {
1391
+ const payeeAgentId = await actingAgent();
806
1392
  const message = await client.get(`/messages/${messageId}`);
807
1393
  if (message.type !== X402_MESSAGE_TYPE.PAYMENT) {
808
1394
  printError(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT}. Nothing to fulfill.`);
@@ -815,12 +1401,16 @@ function registerFulfill(program) {
815
1401
  process.exitCode = 1;
816
1402
  return;
817
1403
  }
818
- const payeeAgentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
819
1404
  if (payeeAgentId === payerAgentId) {
820
1405
  printError("Cannot fulfill your own payment.");
821
1406
  process.exitCode = 1;
822
1407
  return;
823
1408
  }
1409
+ if (message.to_agent_id && message.to_agent_id !== payeeAgentId) {
1410
+ printError(`Payment ${messageId} is addressed to agent ${message.to_agent_id}, not ${payeeAgentId}. Fulfill as that agent (--agent) — only the addressee holds the key that opens it.`);
1411
+ process.exitCode = 1;
1412
+ return;
1413
+ }
824
1414
  if (!agentKeysExist(configDir, payeeAgentId)) {
825
1415
  printError(`No E2EE keys for agent ${payeeAgentId}. Run 'rine keys generate' first.`);
826
1416
  process.exitCode = 1;
@@ -838,12 +1428,13 @@ function registerFulfill(program) {
838
1428
  process.exitCode = 2;
839
1429
  return;
840
1430
  }
841
- const decrypted = await decryptMessage(configDir, payeeAgentId, message.encrypted_payload, client);
1431
+ const decrypted = await decryptMessage(configDir, payeeAgentId, message.encrypted_payload, client, payerAgentId);
842
1432
  let pp;
843
1433
  try {
844
- pp = parseX402Payload(message.type, decrypted.plaintext);
1434
+ pp = parseX402Payload(message.type, requireAuthenticPlaintext(decrypted, payerAgentId, messageId));
845
1435
  } catch (err) {
846
1436
  if (!(err instanceof X402Error)) throw err;
1437
+ const resealed = err.code === X402_ERROR.INAUTHENTIC_SENDER;
847
1438
  const sent = await sendReceipt({
848
1439
  client,
849
1440
  configDir,
@@ -853,9 +1444,9 @@ function registerFulfill(program) {
853
1444
  receiptBody: refusalReceiptBody("", "", err.code),
854
1445
  emitMarker: opts.marker !== false
855
1446
  });
856
- printError(`Malformed payment payload: ${err.message}`);
1447
+ printError(resealed ? `Refusing to settle: ${err.message}` : `Malformed payment payload: ${err.message}`);
857
1448
  if (gOpts.json) printJson({
858
- status: "malformed-payload",
1449
+ status: resealed ? "payment-refused" : "malformed-payload",
859
1450
  code: err.code,
860
1451
  detail: err.message,
861
1452
  receipt_id: sent.id
@@ -929,44 +1520,241 @@ function registerFulfill(program) {
929
1520
  }));
930
1521
  }
931
1522
  //#endregion
932
- //#region src/commands/group.ts
933
- async function installWelcomes(client, configDir, agentId, json) {
934
- try {
935
- await processMlsWelcomes(configDir, agentId, client);
936
- } catch (err) {
937
- if (!json) printText(`Warning: MLS welcome install failed: ${err instanceof Error ? err.message : String(err)}`);
938
- }
1523
+ //#region src/commands/group-args.ts
1524
+ /** Collect a repeatable option into a list, in the order it was given. */
1525
+ function collect(value, previous) {
1526
+ return [...previous, value];
939
1527
  }
940
- async function selfJoinViaExternalCommit(client, configDir, groupId, agentId, json) {
1528
+ /** De-duplicate resolved agent ids, case-insensitively, keeping request order. */
1529
+ function dedupeIds(ids) {
1530
+ const seen = /* @__PURE__ */ new Set();
1531
+ return ids.filter((id) => {
1532
+ const key = id.toLowerCase();
1533
+ if (seen.has(key)) return false;
1534
+ seen.add(key);
1535
+ return true;
1536
+ });
1537
+ }
1538
+ const VISIBILITY_CHOICES = ["public", "private"];
1539
+ const VISIBILITY_EXPLAINED = "\n --visibility public Lists this group in rine's public directory at\n dir.rine.network, where any agent can find it — and\n turns the join signal OFF: admins are not notified\n when someone joins.\n --visibility private Keeps this group out of the directory, and admins\n are notified when someone joins.\n\nThere is no default. rine used to pick one, and it picked differently on every\nsurface — the same command made a publicly listed group from the CLI and an\nunlisted one from the SDK. Name the value and run it again.";
1540
+ /**
1541
+ * The refusal when a group's visibility was not stated, or null when it was.
1542
+ *
1543
+ * `visibility` is required server-side with no default, and every client used to
1544
+ * invent its own: the CLI answered `public` for open enrollment and `private`
1545
+ * otherwise, the SDKs always answered `private`. So `rine group create standup
1546
+ * --enrollment open` produced a group listed at dir.rine.network while the same
1547
+ * call through any SDK produced a private one — and because the directory
1548
+ * listing also flips the member-joined signal, the two differed in who
1549
+ * gets told about a join as well as in who can find the group.
1550
+ *
1551
+ * The refusal names both choices and what each one decides, so an agent reading
1552
+ * it can pick without consulting documentation. It is a rine sentence, not a
1553
+ * schema dump, and it arrives at the call site rather than in the directory.
1554
+ */
1555
+ function visibilityRefusal(value) {
1556
+ if (value === void 0) return `--visibility is required. Choose one:\n${VISIBILITY_EXPLAINED}`;
1557
+ if (!VISIBILITY_CHOICES.includes(value)) return `--visibility must be "public" or "private", not "${value}".\n${VISIBILITY_EXPLAINED}`;
1558
+ return null;
1559
+ }
1560
+ /**
1561
+ * What `--description` says about itself wherever the CLI offers it.
1562
+ *
1563
+ * The description is the group's durable house rules: it rides on the row every
1564
+ * `GroupRead` returns, so every member and every later arrival reads it at any
1565
+ * time — including the arrival who was told nothing about the posts made before
1566
+ * them. That is what it is for, and it is why the second sentence is not
1567
+ * optional. This text is a plain column our server can read, unlike a message
1568
+ * body; an operator who assumes otherwise will put something in it that should
1569
+ * have been sent instead.
1570
+ */
1571
+ const DESCRIPTION_HELP = "Group description — durable house rules every member and every later arrival can read. NOT end-to-end encrypted: unlike a message, this text is stored in the clear and the rine server can read it";
1572
+ /**
1573
+ * The refusal when an invite named nobody to invite.
1574
+ *
1575
+ * "No agent" would now be ambiguous: on this command `--agent` names the agent
1576
+ * doing the inviting, and that one may well have been given.
1577
+ *
1578
+ * 🔴 This is a REFUSAL, so it may not print a placeholder handle.
1579
+ * It used to demonstrate the repeat with two pasteable ones
1580
+ * (`kofi@…`/`bob@…`); rung 1 is unreachable from a module constant — there is
1581
+ * no client and no caller org in hand — so it takes rung 2 and names the three
1582
+ * PARTS of a handle, the same form `invalidAgentIdentifierRefusal` settled on.
1583
+ * A `<slot>` is not the alternative: `check-model-facing-examples.mjs`'s
1584
+ * `template-org` rule forbids that too. Nothing the old text taught is lost —
1585
+ * that the flag repeats, that one of it is unchanged, and that `--agent` is the
1586
+ * inviter — and the handle's shape is now said outright instead of implied by
1587
+ * an example a model copies domain-and-all.
1588
+ */
1589
+ const INVITEE_REQUIRED = "--invitee is required, and it repeats: give the flag once per agent to invite several in one call and be told what happened to each. One --invitee behaves exactly as a single invitation always did.\nEach invitee is an agent handle written in full — the agent's name, an at sign, and its org's domain — or an agent UUID.\nOn this command --agent names the agent doing the inviting, not the agent being invited.";
1590
+ //#endregion
1591
+ //#region src/commands/group-mls.ts
1592
+ /** A failure's message, with the one mls-rs invariant rine has words for translated. */
1593
+ function mlsFailureText(err, groupId) {
1594
+ if (mlsErrorCode(err) === MLS_ERR_GROUP_INACTIVE) return evictedMessage(groupId);
1595
+ return err instanceof Error ? err.message : String(err);
1596
+ }
1597
+ /**
1598
+ * Report a best-effort MLS step that failed without failing the command.
1599
+ *
1600
+ * Every MLS step in the group commands is a second operation *about* the group,
1601
+ * running after the one the operator asked for has already succeeded on the
1602
+ * server. Failing the command would misreport what happened; going quiet would
1603
+ * hide it. So it warns, in rine's vocabulary.
1604
+ *
1605
+ * 🔴 One step does not use this: a Welcome the group substitution guard REFUSED
1606
+ * for the group being joined. See {@link installWelcomes}.
1607
+ */
1608
+ function warnMls(what, err, groupId, json) {
1609
+ if (json) return;
1610
+ printText(`Warning: ${what}: ${mlsFailureText(err, groupId)}`);
1611
+ }
1612
+ /**
1613
+ * Best-effort: fetch & install pending MLS Welcomes for a freshly-added member.
1614
+ *
1615
+ * 🔴 With one exception. A Welcome the group substitution guard REFUSED for
1616
+ * **this** group is raised, so `rine group join` reports it and exits non-zero
1617
+ * instead of printing a warning under a success line. A refusal is a
1618
+ * security verdict about who minted the Welcome, not a setup step that will
1619
+ * come good on the next read, and `rine.groups.join()` on the Python SDK
1620
+ * already raises it — the same failure must not be loud on one stack and a log
1621
+ * line on the other. The rine membership stands either way; what the operator
1622
+ * has to act on is the refusal's own text.
1623
+ *
1624
+ * A refusal naming a DIFFERENT group still warns: the batch installs every
1625
+ * Welcome it can before raising, and one group's verdict is not this join's.
1626
+ *
1627
+ * 🔴 `forGroup` is what makes that split the CLIENT's to make. Without it the
1628
+ * pass raises "the first refusal whose bytes arrived", ordered by the server's
1629
+ * own response array — so a server suppressed this group's refusal by minting
1630
+ * one throwaway decoy for another group, {@link welcomeRefusedForGroup}
1631
+ * answered false, and the join carried on into
1632
+ * {@link selfJoinViaExternalCommit} for the very group whose Welcome this
1633
+ * client had just refused (MEASURED: the verb's outcome flips from warn to
1634
+ * raise on this argument alone).
1635
+ */
1636
+ async function installWelcomes(client, configDir, agentId, groupId, json) {
941
1637
  try {
942
- if (!(await client.get(`/groups/${groupId}`)).mls_group_id) return;
943
- if (loadMlsState(configDir, agentId, groupId)) return;
944
- await externalJoinMlsGroup(configDir, agentId, groupId, client, { "X-Rine-Agent": agentId });
1638
+ await processMlsWelcomes(configDir, agentId, client, { forGroup: groupId });
945
1639
  } catch (err) {
946
- if (!json) printText(`Warning: MLS self-join failed: ${err instanceof Error ? err.message : String(err)}`);
1640
+ if (welcomeRefusedForGroup(err, groupId)) throw err;
1641
+ warnMls("MLS welcome install failed", err, groupId, json);
947
1642
  }
948
1643
  }
949
- async function addMemberToMls(client, configDir, apiUrl, groupId, memberAgentId, as, json) {
1644
+ /**
1645
+ * Whether a failure is the Welcome guard refusing a Welcome for this group.
1646
+ *
1647
+ * Classified by rine-core's exported code check, never by matching the message
1648
+ * — that export exists for this. The `groupId` a refusal carries is the rine
1649
+ * group UUID the delivery was filed under, compared case-insensitively because
1650
+ * the two ids arrive from different reads, as the Python twin compares them.
1651
+ */
1652
+ function welcomeRefusedForGroup(err, groupId) {
1653
+ if (!isMlsWelcomeRefusedError(err)) return false;
1654
+ const named = err.groupId;
1655
+ return typeof named === "string" && named.toLowerCase() === groupId.toLowerCase();
1656
+ }
1657
+ /**
1658
+ * Best-effort open-enrollment fallback: when the joiner became a rine member
1659
+ * with no Welcome (the `open` enrollment case — no admin in the loop) and the
1660
+ * group is MLS-active, self-join via an RFC 9420 external commit. No-op if a
1661
+ * Welcome already installed local state, or for sender-key groups.
1662
+ */
1663
+ async function selfJoinViaExternalCommit(client, configDir, groupId, agentId, mlsGroupId, json) {
1664
+ if (!mlsGroupId) return;
1665
+ if (loadMlsState(configDir, agentId, groupId)) return;
950
1666
  try {
951
- if (!(await client.get(`/groups/${groupId}`)).mls_group_id) return;
952
- const adminId = await resolveAgent(apiUrl, await fetchAgents(client), void 0, as);
953
- await addMlsGroupMember(configDir, adminId, groupId, memberAgentId, client, { "X-Rine-Agent": adminId });
1667
+ await externalJoinMlsGroup(configDir, agentId, groupId, client, { [ACTING_AGENT_HEADER]: agentId });
954
1668
  } catch (err) {
955
- if (!json) printText(`Warning: MLS add-member failed: ${err instanceof Error ? err.message : String(err)}`);
1669
+ warnMls("MLS self-join failed", err, groupId, json);
956
1670
  }
957
1671
  }
958
- async function sendInviteNotification(client, configDir, apiUrl, groupId, inviteeAgentId, message, as, json) {
1672
+ /**
1673
+ * Give every named agent a leaf in the group's ratchet tree, in batches.
1674
+ *
1675
+ * One call whether one agent was named or five hundred: the singular add is the
1676
+ * plural one over a list of one, and both report per member. A
1677
+ * sender-key group has no tree, so it is a no-op rather than a failure.
1678
+ *
1679
+ * Best-effort by contract, like every MLS step on these paths: the invitations
1680
+ * are already minted server-side when this runs, and a Welcome that could not be
1681
+ * delivered is recoverable by `group resume-admission`. Returns null when the
1682
+ * group has no tree or the admission could not run at all.
1683
+ */
1684
+ async function admitToMls(client, configDir, adminId, groupId, mlsGroupId, memberAgentIds, json) {
1685
+ if (!mlsGroupId || memberAgentIds.length === 0) return null;
959
1686
  try {
960
- const group = await client.get(`/groups/${groupId}`);
961
- await sendGroupInviteNotification(client, configDir, await resolveAgent(apiUrl, await fetchAgents(client), void 0, as), inviteeAgentId, {
962
- group_id: groupId,
963
- group_handle: group.handle,
964
- message: message ?? null
965
- });
1687
+ return await addMlsGroupMembers(configDir, adminId, groupId, memberAgentIds, client, { [ACTING_AGENT_HEADER]: adminId });
966
1688
  } catch (err) {
967
- if (!json) printText(`Warning: invite notification failed: ${err instanceof Error ? err.message : String(err)}`);
1689
+ warnMls("MLS add-member failed", err, groupId, json);
1690
+ return null;
968
1691
  }
969
1692
  }
1693
+ //#endregion
1694
+ //#region src/commands/group-rows.ts
1695
+ /**
1696
+ * How this surface spells the verb that founds a group's MLS state.
1697
+ *
1698
+ * The CLI is one of the few surfaces that can act on the answer: `rine group
1699
+ * resume-admission` branches to the init on an unlatched group, so every
1700
+ * sentence the CLI prints about a group whose ratchet tree was never founded
1701
+ * names it. One constant rather than the literal at each of the seven call
1702
+ * sites — the spelling is the load-bearing token, and a verb that only half the
1703
+ * CLI's outputs name is worse than one none of them do.
1704
+ */
1705
+ const CLI_UNFOUNDED_REPAIR = "cli-resume-admission";
1706
+ /**
1707
+ * What `rine group get` prints when no agent of this org holds a seat.
1708
+ *
1709
+ * `member_agent_ids` answers the question `Members` never did — which of YOUR
1710
+ * agents is in this group — and an empty list is a fact rather than a gap: none
1711
+ * of them is, so a send here would be refused and the remedy is an invitation,
1712
+ * not a different `--agent`. An empty cell would say the server forgot to
1713
+ * report it, which is the one reading that is false, and `printTable` renders
1714
+ * an empty array as exactly that empty cell.
1715
+ *
1716
+ * Restated per package for the same reason {@link NO_CONVERSATION} is: seven
1717
+ * surfaces print this sentence and no runtime module reaches all seven. The
1718
+ * three Python surfaces have `rine-sdk` and import
1719
+ * `rine.group_words.NO_OWN_AGENTS` rather than restating it; nothing bridges
1720
+ * Python and TypeScript, so that half of the split is permanent.
1721
+ *
1722
+ * The three TypeScript copies are NOT permanent, and an earlier version of this
1723
+ * comment said they were: `rine-eve` and `rine-mastra` declare
1724
+ * `@rine-network/core` as a direct dependency alongside the SDK and already
1725
+ * import from it at runtime, so `rine-core` does reach all three TS renderers
1726
+ * and could hold this sentence and `renderOwnAgents` once. Consolidating them
1727
+ * re-runs three `--external` gates and the `rine-core` → `rine-ts-sdk` →
1728
+ * CLI/MCP rebuild chain, which is a scheduled refactor of its own.
1729
+ *
1730
+ * The name is that constant's name on purpose. Four packages declare this one
1731
+ * sentence and `tests/test_client-server-contract_group0.py` compares them, so
1732
+ * a reword that lands in one of them fails there rather than shipping two
1733
+ * answers to one question.
1734
+ */
1735
+ const NO_OWN_AGENTS = "(none — no agent of your org is seated in this group)";
1736
+ /**
1737
+ * The agents of this org that are seated in the group, as one cell.
1738
+ *
1739
+ * Each id is printed as its **handle** where this org has one, and as the id
1740
+ * where it does not — the three cases and the reasons for them are stated once,
1741
+ * on `AgentHandles` in `./own-agents.js`, and this renderer is one of the four
1742
+ * that follow them. `handles` is empty whenever the agent list could not be
1743
+ * read, which is exactly case 2 for every id: the cell degrades to the UUIDs it
1744
+ * printed before handles were rendered rather than degrading the group read.
1745
+ *
1746
+ * A server that predates the field reports nothing rather than an empty list,
1747
+ * and that is a different fact from "none of your agents is seated" — but it is
1748
+ * only reachable inside the release-order window (the server ships before the
1749
+ * clients), so it collapses into the same sentence rather than earning a third
1750
+ * one. What it must not do is throw, which is what reading `.length` off the
1751
+ * missing key would do to every `rine group get` against an older deployment.
1752
+ */
1753
+ function ownAgentsCell(g, handles) {
1754
+ const seated = g.member_agent_ids ?? [];
1755
+ if (seated.length === 0) return NO_OWN_AGENTS;
1756
+ return seated.map((id) => handles?.get(id.toLowerCase()) ?? id).join(", ");
1757
+ }
970
1758
  function groupRow(g) {
971
1759
  return {
972
1760
  ID: g.id,
@@ -975,10 +1763,21 @@ function groupRow(g) {
975
1763
  Enrollment: g.enrollment_policy,
976
1764
  Visibility: g.visibility,
977
1765
  Members: g.member_count,
1766
+ "Conversation ID": g.conversation_id ?? "(none — nothing has been said in this group yet)",
978
1767
  Created: g.created_at
979
1768
  };
980
1769
  }
981
- function groupDetailRow(g) {
1770
+ /**
1771
+ * The one-group table `rine group get` and `rine group create` both print.
1772
+ *
1773
+ * It takes a {@link RenderableGroup} rather than a row because `create` renders
1774
+ * a group it has just founded the ratchet tree of, and the row it holds can
1775
+ * predate that founding — the `Encryption` and `Post-Quantum` cells are read
1776
+ * from the create result there, exactly as the line under the table is. Every
1777
+ * other caller passes a plain row, which satisfies the type unchanged.
1778
+ */
1779
+ function groupDetailRow(g, handles) {
1780
+ const encryption = groupEncryption(g);
982
1781
  return {
983
1782
  ID: g.id,
984
1783
  Name: g.name,
@@ -989,72 +1788,338 @@ function groupDetailRow(g) {
989
1788
  Isolated: g.isolated,
990
1789
  "Vote Duration": g.vote_duration_hours,
991
1790
  Members: g.member_count,
1791
+ "Your Agents": ownAgentsCell(g, handles),
1792
+ "Conversation ID": g.conversation_id ?? "(none — nothing has been said in this group yet)",
1793
+ Encryption: encryption.version,
1794
+ "Post-Quantum": encryption.post_quantum,
992
1795
  Created: g.created_at
993
1796
  };
994
1797
  }
1798
+ /**
1799
+ * One roster row, and whether it is one of yours.
1800
+ *
1801
+ * `Yours` is a MARKER and never a filter: every member of the group is listed,
1802
+ * including the rows where it is false, because those are exactly the agents a
1803
+ * group send reaches. Hiding them would answer a question nobody asked and
1804
+ * would make `Members` disagree with the table under it.
1805
+ *
1806
+ * An em dash is a server that does not report the field at all, on the same
1807
+ * distinction {@link denialCell} draws: "not yours" and "this build cannot tell
1808
+ * you" are different facts, and printing `false` for the second would state
1809
+ * something about another org's seat that nothing here knows.
1810
+ */
995
1811
  function memberRow(m) {
996
1812
  return {
997
1813
  "Agent ID": m.agent_id,
998
1814
  Handle: m.agent_handle ?? "",
999
1815
  Role: m.role,
1816
+ Yours: m.is_own_org ?? "—",
1000
1817
  Joined: m.joined_at
1001
1818
  };
1002
1819
  }
1820
+ /**
1821
+ * Whether this reader's own vote would count, in one clause.
1822
+ *
1823
+ * A join request is decided by the members the group had when it was filed, and
1824
+ * only by those of them who are still in it — so a member who joined afterwards
1825
+ * learns that here rather than from a 403. The clause the server's reason maps
1826
+ * to is the same one every other surface prints for that reason, and the reason
1827
+ * predicts the refusal one-to-one: `not_in_electorate`, `electorate_empty`,
1828
+ * `bar_unreachable` and `is_applicant` are 403s, `already_voted` a 409,
1829
+ * `not_pending` a 422.
1830
+ *
1831
+ * `bar_unreachable` and `electorate_empty` are two different facts and are told
1832
+ * apart on purpose: the first is a request no recorded electorate can decide,
1833
+ * the second one whose recorded electorate has entirely left. `is_applicant` is
1834
+ * what a reader sees on its own request — including a nominee reading the
1835
+ * request a member filed on its behalf.
1836
+ *
1837
+ * A server that predates the electorate sends no reason at all, and the one its
1838
+ * behaviour implies is read off `status` — the same derivation the ts-SDK's
1839
+ * schema and the Python `vote_eligibility_reason` make. Not a flat
1840
+ * `electorate_not_recorded`: that is right for a pending request and wrong for
1841
+ * an **invitation**, which nobody votes on and which `POST …/vote` answers 422
1842
+ * for, so the row would have told the operator "you can vote" about the one
1843
+ * population that cannot. A reason this build predates renders as itself rather
1844
+ * than as a guess about whether the vote would count.
1845
+ */
1846
+ function voteEligibilityClause(r) {
1847
+ const reason = r.you_may_vote_reason ?? (r.status === "pending" ? "electorate_not_recorded" : "not_pending");
1848
+ switch (reason) {
1849
+ case "in_electorate": return "you can vote";
1850
+ case "electorate_not_recorded": return "you can vote (filed before the electorate was recorded; any member may)";
1851
+ case "not_in_electorate": return "you cannot vote: you were not in the group when this was filed";
1852
+ case "already_voted": return `you already voted ${r.your_vote ?? ""}`.trimEnd();
1853
+ case "electorate_empty": return "nobody eligible is still in the group";
1854
+ case "bar_unreachable": return "nobody can decide this request";
1855
+ case "is_applicant": return "this is your own request";
1856
+ case "not_pending": return "not open for voting";
1857
+ default: return reason;
1858
+ }
1859
+ }
1860
+ /**
1861
+ * How the denial bar stands, in one cell: denials cast, and how many more would
1862
+ * refuse the request.
1863
+ *
1864
+ * Both bars come from the same electorate, so this one falls as members leave in
1865
+ * exactly the way the approval bar does — a standing denial can refuse a request
1866
+ * nobody has voted on since. A number the server did not report is an em dash
1867
+ * and never a zero: "no more denials are needed" and "this server does not
1868
+ * report the denial bar" are different facts, and printing `0` for the second
1869
+ * would tell an operator the request is one denial from refusal.
1870
+ */
1871
+ function denialCell(r) {
1872
+ const denials = r.denials ?? null;
1873
+ const needed = r.denials_needed ?? null;
1874
+ if (denials === null && needed === null) return "—";
1875
+ return `${denials ?? "—"} of ${needed ?? "—"}`;
1876
+ }
1877
+ /**
1878
+ * One row per request, carrying the arithmetic a member needs before spending a
1879
+ * call: approvals that count, how many more each bar wants, and how many
1880
+ * eligible voters are still in the group.
1881
+ *
1882
+ * The counts are null on an invitation, which nobody votes on, so that whole
1883
+ * clause renders blank there. `Needed` is an em dash when no bar is reachable —
1884
+ * everyone eligible has left, and the request stands until it expires.
1885
+ * `Denials` reports the other direction the same way, as one cell
1886
+ * rather than a second `Denied`/`Deny Needed` pair, because eleven columns is
1887
+ * what a terminal shows and twelve is not.
1888
+ *
1889
+ * A request a member filed on somebody else's behalf is born carrying that
1890
+ * member's own approval, so `Approved: 1` on an untouched row is
1891
+ * ordinary here and not a double count.
1892
+ */
1003
1893
  function requestRow(r) {
1894
+ const approvals = r.approvals ?? null;
1004
1895
  return {
1005
1896
  "Request ID": r.id,
1006
1897
  "Agent ID": r.agent_id,
1007
1898
  Message: r.message ?? "",
1899
+ Approved: approvals ?? "",
1900
+ Needed: approvals === null ? "" : r.approvals_needed ?? "—",
1901
+ Denials: denialCell(r),
1902
+ Eligible: r.electorate_size ?? "",
1008
1903
  "Your Vote": r.your_vote ?? "",
1904
+ "Can Vote": voteEligibilityClause(r),
1009
1905
  Expires: r.expires_at ?? "",
1010
1906
  Created: r.created_at
1011
1907
  };
1012
1908
  }
1909
+ /**
1910
+ * The invitee's perspective: who reached you, about which group, and with what
1911
+ * kind of row. Distinct from requestRow, whose `Your Vote`/`Agent ID` columns
1912
+ * are voter-scoped.
1913
+ *
1914
+ * `Status` is the column that tells an invitation from a nomination.
1915
+ * `GET /groups/invites` answers both, and it is the only route an agent that is
1916
+ * not yet a member can read its own nomination on — so without this column the
1917
+ * one row a nominee can see would read as an invitation to accept, which is
1918
+ * false: a nomination seats nobody until the electorate decides. `invited` is a
1919
+ * voucher this join spends; `pending` is a nomination the group's electorate
1920
+ * has still to decide, and joining it records consent rather than enrolling.
1921
+ */
1013
1922
  function inviteRow(r) {
1014
1923
  return {
1015
1924
  Group: r.group_handle ?? r.group_name ?? "",
1016
1925
  "Group ID": r.group_id,
1017
1926
  "Invited By": r.invited_by ?? "",
1927
+ Status: r.status,
1018
1928
  Message: r.message ?? "",
1019
1929
  Created: r.created_at
1020
1930
  };
1021
1931
  }
1022
- function registerGroup(program) {
1023
- const group = program.command("group").description("Group management");
1024
- group.command("create").description("Create a new group").requiredOption("--name <name>", "Group name (DNS-safe slug)").option("--enrollment <policy>", "Enrollment policy (open|closed|majority|unanimity)").option("--visibility <vis>", "Visibility (public|private)").option("--isolated", "Isolate group communication").option("--vote-duration <hours>", "Vote duration in hours (1-72)").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, opts) => {
1025
- const body = { name: opts.name };
1026
- if (opts.enrollment) body.enrollment_policy = opts.enrollment;
1027
- if (opts.visibility) body.visibility = opts.visibility;
1028
- else {
1029
- body.visibility = opts.enrollment === "open" ? "public" : "private";
1030
- if (!gOpts.json) printText(`Visibility defaulted to "${body.visibility}" (enrollment: ${opts.enrollment ?? "closed"})`);
1932
+ /**
1933
+ * One requested agent id and what the server did about it.
1934
+ *
1935
+ * The reason column carries the sentence, not the wire token: `not_applicable`
1936
+ * printed as-is read as a refusal on exactly the groups it is not one for — an
1937
+ * open group mints no invitation because it needs none, and those agents may
1938
+ * walk in. The map lives in `rine-core` so every surface says it the same way.
1939
+ * An `invited` or `nominated` entry carries no reason and gets no
1940
+ * sentence — the status is the whole answer, and the two are separate values
1941
+ * precisely so this column never offers an invitation to accept where the
1942
+ * electorate has yet to decide.
1943
+ */
1944
+ function admissionRow(e) {
1945
+ return {
1946
+ "Agent ID": e.agent_id,
1947
+ Status: e.status,
1948
+ Reason: e.status === "skipped" ? groupAdmissionSkipSentence(e.reason) : ""
1949
+ };
1950
+ }
1951
+ /** One requested agent id and whether the ratchet tree took them. */
1952
+ function admissionOutcomeRows(result) {
1953
+ return result.outcomes.map((o) => ({
1954
+ "Agent ID": o.agentId,
1955
+ Seated: o.status === "added" ? "yes" : "no",
1956
+ Reason: o.status === "skipped" ? mlsAdmissionSkipSentence(o.reason) : ""
1957
+ }));
1958
+ }
1959
+ //#endregion
1960
+ //#region src/commands/own-agents.ts
1961
+ /**
1962
+ * Index the agent list the actor ladder has already paid for.
1963
+ *
1964
+ * `ctx.agents()` is memoised per command invocation, so a command that also
1965
+ * resolves an acting agent (`group update`, `group create`) spends nothing
1966
+ * extra here; `group get`, which names no actor, spends one `GET /agents` — and
1967
+ * only on a group where a seat would actually be spelled, because the empty
1968
+ * cell reads the same whichever map it is handed. That call is the one cost
1969
+ * accepted in exchange for a cell an operator can read; its callers own
1970
+ * the seat check, since this function is handed the list and not the group.
1971
+ *
1972
+ * Ids are lowercased on both sides of the lookup because a UUID is
1973
+ * case-insensitive and the two lists come from different responses.
1974
+ */
1975
+ async function ownAgentHandles(agents) {
1976
+ try {
1977
+ const list = await agents();
1978
+ return new Map(list.filter((a) => a.handle !== null).map((a) => [a.id.toLowerCase(), a.handle]));
1979
+ } catch {
1980
+ return /* @__PURE__ */ new Map();
1981
+ }
1982
+ }
1983
+ //#endregion
1984
+ //#region src/commands/group-create.ts
1985
+ const ROSTER_NOTE = "A founding roster invites; nobody is a member until they join. On a closed, majority or unanimity group it mints real invitations — majority and unanimity included, because you are the only member at this point, so a vote would auto-approve every row — and each holds a seat until it is accepted or expires. An open group mints nothing at all: anyone may join it, so there is no invitation to authorise.";
1986
+ /** Read either create response: a bare group, or `{group, roster}` when a roster was named. */
1987
+ function unwrapCreate(data) {
1988
+ const body = data;
1989
+ if (body.group && body.roster) return {
1990
+ group: body.group,
1991
+ roster: body.roster
1992
+ };
1993
+ return {
1994
+ group: body,
1995
+ roster: null
1996
+ };
1997
+ }
1998
+ /**
1999
+ * Found the new group's ratchet tree, seating its roster in size-aware batches.
2000
+ *
2001
+ * Open-enrollment groups are exempt: the server refuses MLS there, so an init
2002
+ * would only ever fail — they run on Sender Keys. Best-effort, and the group
2003
+ * stands either way; `group resume-admission` finishes an init that stopped
2004
+ * part-way.
2005
+ */
2006
+ async function foundMlsState(ctx, group) {
2007
+ if (group.enrollment_policy === "open") return null;
2008
+ try {
2009
+ const actingAgentId = await ctx.actingAgent();
2010
+ return await initMlsGroup(ctx.configDir, actingAgentId, group.id, ctx.client, { [ACTING_AGENT_HEADER]: actingAgentId });
2011
+ } catch (err) {
2012
+ warnMls("MLS init failed (group still created)", err, group.id, ctx.gOpts.json);
2013
+ return null;
2014
+ }
2015
+ }
2016
+ /** Re-read the group so the rendered row carries the MLS latch the init just set. */
2017
+ async function refresh(client, group) {
2018
+ try {
2019
+ return await client.get(`/groups/${group.id}`);
2020
+ } catch {
2021
+ return group;
2022
+ }
2023
+ }
2024
+ function printCreated$1(group, roster, admission, json, handles) {
2025
+ const created = admission ? {
2026
+ ...group,
2027
+ mlsAdmission: admission
2028
+ } : group;
2029
+ if (json) {
2030
+ printJson({
2031
+ ...group,
2032
+ encryption: groupEncryption$1(created, CLI_UNFOUNDED_REPAIR),
2033
+ ...roster ? { roster } : {},
2034
+ ...admission ? { admission } : {}
2035
+ });
2036
+ return;
2037
+ }
2038
+ printTable([groupDetailRow(created, handles)]);
2039
+ printText(`\nGroup created — handle: ${group.handle}`);
2040
+ printText(encryptionLine(created, CLI_UNFOUNDED_REPAIR));
2041
+ if (roster) {
2042
+ printText(`\nRoster: ${admissionHeadline(roster)} ${ROSTER_NOTE}`);
2043
+ printTable(roster.entries.map(admissionRow));
2044
+ }
2045
+ if (admission && admission.outcomes.length > 0) {
2046
+ printText(`\nSeated in the ratchet tree: ${admission.added} of ${admission.outcomes.length} in ${admission.commits} commit(s), now at epoch ${admission.epoch}.`);
2047
+ printTable(admissionOutcomeRows(admission));
2048
+ }
2049
+ }
2050
+ function registerGroupCreate(program, group) {
2051
+ group.command("create").description("Create a new group").requiredOption("--name <name>", "Group name (DNS-safe slug)").option("--description <desc>", DESCRIPTION_HELP).option("--enrollment <policy>", "Enrollment policy (open|closed|majority|unanimity). `open` runs Sender Keys, which are NOT post-quantum").option("--visibility <vis>", "Required. `public` lists the group at dir.rine.network and turns the join signal off; `private` does neither").option("--member <id>", "Invite an agent into the new group (repeatable). A roster invites — it never seats — and it invites under every enrollment policy, because you are the only member at founding and a vote would auto-approve each row", collect, []).option("--isolated", "Isolate group communication").option("--vote-duration <hours>", VOTE_DURATION_RULE).action(withClient(program, async (ctx, opts) => {
2052
+ const refusal = visibilityRefusal(opts.visibility);
2053
+ if (refusal) {
2054
+ printError(refusal);
2055
+ process.exitCode = 2;
2056
+ return;
1031
2057
  }
2058
+ const body = {
2059
+ name: opts.name,
2060
+ visibility: opts.visibility
2061
+ };
2062
+ if (opts.description !== void 0) body.description = opts.description;
2063
+ if (opts.enrollment) body.enrollment_policy = opts.enrollment;
1032
2064
  if (opts.isolated) body.isolated = true;
1033
2065
  if (opts.voteDuration) body.vote_duration_hours = Number(opts.voteDuration);
1034
- const data = await client.post("/groups", body);
1035
- if (data.enrollment_policy !== "open") try {
1036
- const actingAgentId = await resolveAgent(apiUrl, await fetchAgents(client), void 0, gOpts.as);
1037
- await initMlsGroup(configDir, actingAgentId, data.id, client, { "X-Rine-Agent": actingAgentId });
1038
- } catch (err) {
1039
- if (!gOpts.json) printText(`Warning: MLS init failed (group still created): ${err instanceof Error ? err.message : String(err)}`);
1040
- }
1041
- if (gOpts.json) printJson(data);
1042
- else {
1043
- printTable([groupDetailRow(data)]);
1044
- printText(`\nGroup created — handle: ${data.handle}`);
1045
- }
2066
+ if (opts.member.length > 0) body.members = dedupeIds(await Promise.all(opts.member.map((m) => {
2067
+ announceHandleCompletion(m);
2068
+ return resolveToUuid(ctx.apiUrl, m);
2069
+ })));
2070
+ const { group: created, roster } = unwrapCreate(await ctx.client.post("/groups", body));
2071
+ const admission = await foundMlsState(ctx, created);
2072
+ const latched = admission ? await refresh(ctx.client, created) : created;
2073
+ const handles = ctx.gOpts.json ? void 0 : await ownAgentHandles(ctx.agents);
2074
+ printCreated$1(latched, roster, admission, ctx.gOpts.json, handles);
1046
2075
  }));
2076
+ }
2077
+ //#endregion
2078
+ //#region src/commands/group-crud.ts
2079
+ /**
2080
+ * Whether a Remove commit has already evicted the acting agent from this group.
2081
+ *
2082
+ * Reading a group is where an evicted agent finds out, so the ratchet tree is
2083
+ * consulted here rather than left to surface as an mls-rs invariant from the
2084
+ * next send. Local and best-effort: the answer lives on disk, and a
2085
+ * group whose state this agent never held simply has no answer.
2086
+ *
2087
+ * This is the half that runs when the group *was* readable — an evicted member
2088
+ * still inside the owning org. The cross-org case never gets here at all: the
2089
+ * server refuses the read, so it is answered on the refusal instead
2090
+ * ({@link readGroup}).
2091
+ */
2092
+ async function evictionState(ctx, group) {
2093
+ if (!groupIsMls(group)) return null;
2094
+ try {
2095
+ return isEvictedFrom(ctx.configDir, await ctx.actingAgent(), group.id);
2096
+ } catch {
2097
+ return null;
2098
+ }
2099
+ }
2100
+ function registerGroupCrud(program, group) {
1047
2101
  group.command("list").description("List groups").action(withClient(program, async ({ client, gOpts }) => {
1048
2102
  const data = await client.get("/groups");
1049
2103
  if (gOpts.json) printJson(data);
1050
2104
  else printTable(data.items.map(groupRow));
1051
2105
  }));
1052
- group.command("get").description("Get group details").argument("<group-id>", "Group ID").action(withClient(program, async ({ client, gOpts }, groupId) => {
1053
- const data = await client.get(`/groups/${groupId}`);
1054
- if (gOpts.json) printJson(data);
1055
- else printTable([groupDetailRow(data)]);
2106
+ group.command("get").description("Get group details").argument("<group-ref>", GROUP_REFERENCE_HELP).action(withClient(program, async (ctx, ref) => {
2107
+ const { row: data } = await groupTarget(ctx, ref);
2108
+ const evicted = await evictionState(ctx, data);
2109
+ if (ctx.gOpts.json) {
2110
+ printJson({
2111
+ ...data,
2112
+ encryption: groupEncryption$1(data, CLI_UNFOUNDED_REPAIR),
2113
+ ...evicted === null ? {} : { evicted }
2114
+ });
2115
+ return;
2116
+ }
2117
+ printTable([groupDetailRow(data, data.member_agent_ids?.length ? await ownAgentHandles(ctx.agents) : void 0)]);
2118
+ printText(encryptionLine(data, CLI_UNFOUNDED_REPAIR));
2119
+ if (evicted) printText(`\n${evictedMessage(data.id)}`);
1056
2120
  }));
1057
- group.command("update").description("Update group settings").argument("<group-id>", "Group ID").option("--description <desc>", "Group description").option("--enrollment <policy>", "Enrollment policy (open|closed|majority|unanimity)").option("--visibility <vis>", "Visibility (public|private)").option("--vote-duration <hours>", "Vote duration in hours (1-72)").action(withClient(program, async ({ client, gOpts }, groupId, opts) => {
2121
+ group.command("update").description("Update group settings").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).option("--description <desc>", DESCRIPTION_HELP).option("--enrollment <policy>", "Enrollment policy (open|closed|majority|unanimity)").option("--visibility <vis>", "`public` lists the group at dir.rine.network and turns the join signal off; `private` does neither").option("--vote-duration <hours>", VOTE_DURATION_RULE).action(withClient(program, async (ctx, ref, opts) => {
2122
+ const { client, gOpts, actingAgent, agents } = ctx;
1058
2123
  const body = {};
1059
2124
  if (opts.description !== void 0) body.description = opts.description;
1060
2125
  if (opts.enrollment) body.enrollment_policy = opts.enrollment;
@@ -1065,34 +2130,311 @@ function registerGroup(program) {
1065
2130
  process.exitCode = 2;
1066
2131
  return;
1067
2132
  }
1068
- const data = await client.patch(`/groups/${groupId}`, body);
1069
- if (gOpts.json) printJson(data);
2133
+ const { id: groupId } = await groupTarget(ctx, ref);
2134
+ const data = await client.patch(`/groups/${groupId}`, body, { [ACTING_AGENT_HEADER]: await actingAgent() });
2135
+ if (gOpts.json) printJson({
2136
+ ...data,
2137
+ encryption: groupEncryption$1(data, CLI_UNFOUNDED_REPAIR)
2138
+ });
1070
2139
  else {
1071
- printTable([groupDetailRow(data)]);
2140
+ printTable([groupDetailRow(data, await ownAgentHandles(agents))]);
1072
2141
  printText("Group updated");
2142
+ printText(encryptionLine(data, CLI_UNFOUNDED_REPAIR));
1073
2143
  }
1074
2144
  }));
1075
- group.command("delete").description("Delete a group").argument("<group-id>", "Group ID").option("--yes", "Skip confirmation prompt").action(withClient(program, async ({ client, gOpts }, groupId, opts) => {
2145
+ group.command("delete").description("Delete a group").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).option("--yes", "Skip confirmation prompt").action(withClient(program, async (ctx, ref, opts) => {
2146
+ const { client, gOpts, actingAgent } = ctx;
2147
+ const headers = { [ACTING_AGENT_HEADER]: await actingAgent() };
2148
+ const target = await groupTarget(ctx, ref);
2149
+ const groupId = target.id;
1076
2150
  if (!opts.yes && !gOpts.json) {
1077
- if (!await promptConfirm(`Delete group ${groupId}?`)) return;
2151
+ if (!await promptConfirm(`Delete group ${target.handle ?? target.id}?`)) return;
1078
2152
  }
1079
- await client.delete(`/groups/${groupId}`);
2153
+ await client.delete(`/groups/${groupId}`, headers);
1080
2154
  printMutationOk("Group deleted", gOpts.json);
1081
2155
  }));
1082
- group.command("members").description("List group members").argument("<group-id>", "Group ID").action(withClient(program, async ({ client, gOpts }, groupId) => {
1083
- const data = await client.get(`/groups/${groupId}/members`);
1084
- if (gOpts.json) printJson(data);
1085
- else printTable(data.items.map(memberRow));
2156
+ }
2157
+ //#endregion
2158
+ //#region src/commands/group-invite.ts
2159
+ /**
2160
+ * An invite that names nobody is refused before it costs anything.
2161
+ *
2162
+ * It runs ahead of the acting agent, so a caller who typed no `--invitee` is
2163
+ * told that rather than being asked which of their agents is inviting — a
2164
+ * question they cannot answer usefully and did not come here to answer.
2165
+ *
2166
+ * The options object is found by the shape only this command has rather than by
2167
+ * its position, because commander's argument order depends on how many
2168
+ * arguments the command declares.
2169
+ */
2170
+ const invitesSomebody = (...args) => {
2171
+ const opts = args.find((arg) => Array.isArray(arg?.invitee));
2172
+ if (opts === void 0) return null;
2173
+ return opts.invitee.length === 0 ? INVITEE_REQUIRED : null;
2174
+ };
2175
+ const INVITATION_NOTE = "An invitation holds a ratchet-tree seat until it is accepted or expires.";
2176
+ const NOMINATION_NOTE = "A nomination holds a seat too, and the group's electorate decides it: nothing is added to the ratchet tree until the vote carries.";
2177
+ /**
2178
+ * What the agents this batch reached now hold — said only of what it minted.
2179
+ *
2180
+ * Read off the entries, the same place {@link admissionHeadline} reads, because
2181
+ * a batch answers one of three ways and only two of them have anything to hold.
2182
+ * An open group mints no invitation and no nomination and runs Sender Keys, so
2183
+ * it has no ratchet tree either: every entry comes back `not_applicable`, and
2184
+ * both sentences below would name objects that do not exist. The per-agent line
2185
+ * carries the fact there — the agent may join whenever it likes — so the note
2186
+ * is simply absent rather than replaced.
2187
+ *
2188
+ * A closed group's invite mints vouchers and a voting group's files
2189
+ * nominations, one policy per call, so in practice one clause prints. Both are
2190
+ * stated when both are present, which costs nothing and keeps this true of a
2191
+ * report rather than of a policy this function never sees.
2192
+ */
2193
+ function admissionNote(report) {
2194
+ const notes = [];
2195
+ if (report.entries.some((entry) => entry.status === "invited")) notes.push(INVITATION_NOTE);
2196
+ if (report.entries.some((entry) => entry.status === "nominated")) notes.push(NOMINATION_NOTE);
2197
+ return notes.join(" ");
2198
+ }
2199
+ const UNRESOLVED_INVITER = "Warning: the request was filed, but this agent could not be resolved, so no Welcome was minted and nobody was notified:";
2200
+ /**
2201
+ * Nudge each reached agent's inbox with a sealed `rine.v1.group_invite` DM.
2202
+ *
2203
+ * The authoritative discovery path is `GET /groups/invites` (`group invites`),
2204
+ * which answers nominations as well as invitations and tells them
2205
+ * apart by `status` — so a failure here — a `groups_only` 403, missing keys —
2206
+ * warns and never fails the row the server has already written.
2207
+ *
2208
+ * The DM carries the group and who reached out, not a rendered sentence: its
2209
+ * payload is `{group_id, group_handle, invited_by, message}`
2210
+ * (`rine-core/src/group-invite-ops.ts`), so nothing on this path claims a seat
2211
+ * a nomination does not confer.
2212
+ */
2213
+ async function notifyInvitees(client, configDir, inviterId, group, inviteeIds, message, json) {
2214
+ for (const inviteeId of inviteeIds) try {
2215
+ await sendGroupInviteNotification(client, configDir, inviterId, inviteeId, {
2216
+ group_id: group.id,
2217
+ group_handle: group.handle,
2218
+ message: message ?? null
2219
+ });
2220
+ } catch (err) {
2221
+ if (!json) printText(`Warning: invite notification to ${inviteeId} failed: ${err instanceof Error ? err.message : String(err)}`);
2222
+ }
2223
+ }
2224
+ /**
2225
+ * The agents this call actually reached, whichever shape answered.
2226
+ *
2227
+ * A singular invite gets a bare row back and no report, so the one agent it
2228
+ * named is the answer. A plural one is `admittedAgentIds` — `rine-core`'s, not
2229
+ * a second copy of the arithmetic — which counts `not_applicable` as reached
2230
+ * because that is an open group's answer: it mints no voucher since it needs
2231
+ * none, and those agents are still being told to come in.
2232
+ *
2233
+ * 🔴 This is "who was reached and is owed a notice", NOT "who gets a leaf".
2234
+ * It also counts `nominated` entries, so feeding it to an MLS add
2235
+ * without asking {@link inviteNominates} first would Welcome an agent the
2236
+ * electorate has not decided on. {@link afterInvite} is where that question is
2237
+ * asked.
2238
+ */
2239
+ function reachedAgents(report, singular) {
2240
+ if (!report) return singular ? [singular] : [];
2241
+ return admittedAgentIds(report);
2242
+ }
2243
+ /**
2244
+ * What one invite call did, in its own words.
2245
+ *
2246
+ * Read off the row the server wrote rather than off the group, because the row
2247
+ * is the answer: a `closed` group's invite mints a voucher (`invited`), a
2248
+ * `majority` or `unanimity` group's files a nomination (`pending`),
2249
+ * and an `open` group's is a notification with no row at all — which answers
2250
+ * `invited` and carries no `id`.
2251
+ *
2252
+ * That missing `id` is what tells the third case from the first, and it is the
2253
+ * only signal there is: the two answers carry the same status. An open group
2254
+ * mints nothing because it needs nothing, so the head says so and there is no
2255
+ * row to table underneath it — reported in `rine-core`'s words, the same
2256
+ * sentence the plural report's per-agent line carries.
2257
+ */
2258
+ function singularHead(row) {
2259
+ if (row.status === "pending") return "Nomination filed — the group's electorate decides it";
2260
+ if (!row.id) return `Invited: ${groupAdmissionSkipSentence("not_applicable")}`;
2261
+ return "Invitation sent";
2262
+ }
2263
+ function printInvited(data, report, admission, json) {
2264
+ if (json) {
2265
+ printJson(admission ? {
2266
+ ...data,
2267
+ admission
2268
+ } : data);
2269
+ return;
2270
+ }
2271
+ if (report) {
2272
+ const note = admissionNote(report);
2273
+ printText(`Admission: ${admissionHeadline(report)}${note ? ` ${note}` : ""}`);
2274
+ printTable(report.entries.map(admissionRow));
2275
+ } else {
2276
+ const voucher = data;
2277
+ printText(singularHead(voucher));
2278
+ if (voucher.id) printTable([requestRow(voucher)]);
2279
+ }
2280
+ if (admission && admission.outcomes.length > 0) {
2281
+ printText(`\nSeated in the ratchet tree: ${admission.added} of ${admission.outcomes.length} in ${admission.commits} commit(s), now at epoch ${admission.epoch}.`);
2282
+ printTable(admissionOutcomeRows(admission));
2283
+ }
2284
+ }
2285
+ /**
2286
+ * The two steps that happen *after* the server has written the row, and neither
2287
+ * of which may fail the command.
2288
+ *
2289
+ * Both need the group's handle and the acting inviter, so both are read once
2290
+ * here rather than twice inside each. That resolution is itself best-effort: a
2291
+ * multi-agent org that named no agent — no `--agent`, no `RINE_AGENT`, and more
2292
+ * than one to choose from — cannot be told which agent is inviting, and refusing
2293
+ * to report an invitation that the server already accepted would be the wrong
2294
+ * answer to that.
2295
+ *
2296
+ * 🔴 **A nomination gets the notice and no leaf.** On `majority` and
2297
+ * `unanimity` this call filed a request the electorate has not decided, so
2298
+ * claiming the nominee's KeyPackage and Welcoming them here would put an agent
2299
+ * the vote may refuse inside the ratchet tree, holding an epoch secret, with
2300
+ * only the manual reclamation pass able to retire the leaf afterwards — and
2301
+ * that pass cannot reach it while the row is live. The vote seats the member,
2302
+ * and seating is what grants the key: `group vote` posts the add on the approve
2303
+ * that carries, which is what the self-application path has always done. The
2304
+ * notice still goes out, because a nominee that never learns of the nomination
2305
+ * can never consent to it.
2306
+ *
2307
+ * The GROUP's policy decides this and not the response, because it is the same
2308
+ * question the server asked when it chose what to write, and it answers the
2309
+ * singular and the plural call in one place.
2310
+ */
2311
+ async function afterInvite(ctx, groupId, reached, message) {
2312
+ let group;
2313
+ let inviterId;
2314
+ try {
2315
+ group = await ctx.client.get(`/groups/${groupId}`);
2316
+ inviterId = await ctx.actingAgent();
2317
+ } catch (err) {
2318
+ if (!ctx.gOpts.json) printText(`${UNRESOLVED_INVITER} ${err instanceof Error ? err.message : String(err)}`);
2319
+ return null;
2320
+ }
2321
+ const admission = inviteNominates(group.enrollment_policy) ? null : await admitToMls(ctx.client, ctx.configDir, inviterId, groupId, group.mls_group_id, reached, ctx.gOpts.json);
2322
+ await notifyInvitees(ctx.client, ctx.configDir, inviterId, group, reached, message, ctx.gOpts.json);
2323
+ return admission;
2324
+ }
2325
+ function registerGroupInvite(program, group) {
2326
+ group.command("invite").description("Invite one or more agents to the group. On a majority or unanimity group this nominates rather than invites: it files a join request the group's electorate decides, counted as your own approval, and nobody is added to the ratchet tree until the vote carries. On a closed group an admin's invite is a voucher the agent redeems with `rine group join`. `rine group create --member` is the exception — a founding roster invites under every policy, because the creator is the only member and a vote would auto-approve each row.").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is acting, and invites")).option("--invitee <id>", "Agent ID or handle to invite or nominate (repeatable — naming two or more reaches them in one call and reports each)", collect, []).option("--message <msg>", "Message to carry with the invitation or nomination").action(withClient(program, async (ctx, ref, opts) => {
2327
+ const { id: groupId } = await groupTarget(ctx, ref);
2328
+ const agentIds = dedupeIds(await Promise.all(opts.invitee.map((a) => {
2329
+ announceHandleCompletion(a);
2330
+ return resolveToUuid(ctx.apiUrl, a);
2331
+ })));
2332
+ const single = agentIds.length === 1 ? agentIds[0] : void 0;
2333
+ const body = single ? { agent_id: single } : { agent_ids: agentIds };
2334
+ if (opts.message) body.message = opts.message;
2335
+ const data = await ctx.client.post(`/groups/${groupId}/invite`, body);
2336
+ const report = single ? null : data;
2337
+ printInvited(data, report, await afterInvite(ctx, groupId, reachedAgents(report, single), opts.message), ctx.gOpts.json);
2338
+ }, invitesSomebody));
2339
+ }
2340
+ //#endregion
2341
+ //#region src/commands/group-senderkey.ts
2342
+ const lower = (id) => id.toLowerCase();
2343
+ /**
2344
+ * Which members hold this agent's current sender key, and which do not.
2345
+ *
2346
+ * `distributeSenderKey` reports a per-recipient `DistributeResult` and **every
2347
+ * caller discards the failures**: a distribution that reached four of five
2348
+ * members looks exactly like one that reached all five, and the fifth member
2349
+ * silently cannot read anything this agent sends until some later send happens
2350
+ * to reach them. The information is on disk — `distributedTo` records only the
2351
+ * recipients that were actually reached — and nothing has ever read it back.
2352
+ * This is that read.
2353
+ *
2354
+ * Returns null when this agent holds no sender key for the group, which is the
2355
+ * normal state of an MLS group and of one nobody has sent to yet. That is not
2356
+ * the same answer as "everybody has it", so it is a different value.
2357
+ *
2358
+ * ⚠️ The current state is the **last** one this agent owns, which is the same
2359
+ * rule `getOrCreateSenderKey` applies when it decides which key to send under
2360
+ * (`rine-core/src/sender-key-ops.ts`): a rotation appends and drops the key it
2361
+ * superseded, so reading the first match would report a retired key's audience.
2362
+ * The rule is stated in both places because rine-core exports no reader for it;
2363
+ * one exported accessor would be the better home.
2364
+ */
2365
+ function senderKeyCoverage(configDir, agentId, groupId, memberIds) {
2366
+ const own = loadSenderKeyStates(configDir, agentId, groupId).filter((state) => lower(state.senderAgentId) === lower(agentId));
2367
+ const current = own[own.length - 1];
2368
+ if (!current) return null;
2369
+ const held = new Set((current.distributedTo ?? []).map(lower));
2370
+ const recipients = memberIds.filter((id) => lower(id) !== lower(agentId));
2371
+ return {
2372
+ senderKeyId: current.senderKeyId,
2373
+ reached: recipients.filter((id) => held.has(lower(id))),
2374
+ unreached: recipients.filter((id) => !held.has(lower(id)))
2375
+ };
2376
+ }
2377
+ /**
2378
+ * What an operator is told when a distribution reached only part of the group.
2379
+ *
2380
+ * Empty when everybody has the key — there is nothing to report, and a line
2381
+ * that appears every time stops being read.
2382
+ */
2383
+ function coverageWarning(coverage) {
2384
+ if (coverage.unreached.length === 0) return "";
2385
+ const total = coverage.reached.length + coverage.unreached.length;
2386
+ return `Your sender key has reached ${coverage.reached.length} of ${total} other members. These ${coverage.unreached.length} cannot read what you send until a later send reaches them: ${coverage.unreached.join(", ")}`;
2387
+ }
2388
+ //#endregion
2389
+ //#region src/commands/group-membership.ts
2390
+ /** The group, or null when it cannot be read — only its rendering depends on it. */
2391
+ async function readGroup(ctx, groupId) {
2392
+ try {
2393
+ return await ctx.client.get(`/groups/${groupId}`);
2394
+ } catch {
2395
+ return null;
2396
+ }
2397
+ }
2398
+ /** Who holds this agent's sender key for the group; null when it holds none. */
2399
+ async function coverageFor(ctx, groupId, memberIds) {
2400
+ try {
2401
+ return senderKeyCoverage(ctx.configDir, await ctx.actingAgent(), groupId, memberIds);
2402
+ } catch {
2403
+ return null;
2404
+ }
2405
+ }
2406
+ function registerGroupMembership(program, group) {
2407
+ group.command("members").description("List group members").argument("<group-ref>", GROUP_REFERENCE_HELP).action(withClient(program, async (ctx, ref) => {
2408
+ const { id: groupId } = await groupTarget(ctx, ref);
2409
+ let data;
2410
+ try {
2411
+ data = await ctx.client.get(`/groups/${groupId}/members`);
2412
+ } catch (err) {
2413
+ throw await asGroupAccessError(ctx.configDir, groupId, err, () => ctx.actingAgent());
2414
+ }
2415
+ const coverage = await coverageFor(ctx, groupId, data.items.map((m) => m.agent_id));
2416
+ if (ctx.gOpts.json) {
2417
+ printJson(coverage ? {
2418
+ ...data,
2419
+ sender_key_coverage: coverage
2420
+ } : data);
2421
+ return;
2422
+ }
2423
+ printTable(data.items.map(memberRow));
2424
+ const warning = coverage ? coverageWarning(coverage) : "";
2425
+ if (warning) printText(warning);
1086
2426
  }));
1087
- group.command("join").description("Join a group").argument("<group-id>", "Group ID").option("--message <msg>", "Join request message").action(withClient(program, async ({ client, gOpts, configDir }, groupId, opts) => {
2427
+ group.command("join").description("Join a group").argument("<group-ref>", GROUP_REFERENCE_HELP).option("--message <msg>", "Join request message").action(withClient(program, async (ctx, ref, opts) => {
2428
+ const { id: groupId } = await joinGroupTarget(ctx, ref);
1088
2429
  const body = {};
1089
2430
  if (opts.message) body.message = opts.message;
1090
- const data = await client.post(`/groups/${groupId}/join`, body);
2431
+ const data = await ctx.client.post(`/groups/${groupId}/join`, body);
1091
2432
  if ("role" in data) {
1092
- await installWelcomes(client, configDir, data.agent_id, gOpts.json);
1093
- await selfJoinViaExternalCommit(client, configDir, groupId, data.agent_id, gOpts.json);
2433
+ await installWelcomes(ctx.client, ctx.configDir, data.agent_id, groupId, ctx.gOpts.json);
2434
+ const joined = await readGroup(ctx, groupId);
2435
+ await selfJoinViaExternalCommit(ctx.client, ctx.configDir, groupId, data.agent_id, joined?.mls_group_id, ctx.gOpts.json);
1094
2436
  }
1095
- if (gOpts.json) printJson(data);
2437
+ if (ctx.gOpts.json) printJson(data);
1096
2438
  else if ("role" in data) {
1097
2439
  printTable([memberRow(data)]);
1098
2440
  printText("Joined group (member)");
@@ -1101,54 +2443,186 @@ function registerGroup(program) {
1101
2443
  printText("Join request submitted (pending approval)");
1102
2444
  }
1103
2445
  }));
1104
- group.command("leave").description("Leave a group").argument("<group-id>", "Group ID").option("--agent <id>", "Agent ID (defaults to your agent)").action(withClient(program, async ({ client, gOpts, apiUrl }, groupId, opts) => {
1105
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
1106
- await client.delete(`/groups/${groupId}/members/${agentId}`);
1107
- printMutationOk("Left group", gOpts.json);
1108
- }));
1109
- group.command("kick").description("Remove a member from the group (admin)").argument("<group-id>", "Group ID").argument("<agent-id>", "Agent ID or handle to remove").action(withClient(program, async ({ client, gOpts, apiUrl }, groupId, agentId) => {
1110
- const resolved = await resolveToUuid(apiUrl, agentId);
1111
- await client.delete(`/groups/${groupId}/members/${resolved}`);
1112
- printMutationOk("Member removed", gOpts.json);
2446
+ group.command("leave").description("Leave a group").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).action(withClient(program, async (ctx, ref) => {
2447
+ const groupId = UUID_RE.test(ref) ? ref : (await groupTarget(ctx, ref)).id;
2448
+ const agentId = await ctx.actingAgent();
2449
+ const left = await readGroup(ctx, groupId);
2450
+ const heldMlsState = loadMlsState(ctx.configDir, agentId, groupId) !== null;
2451
+ await deleteGroupMember(ctx.client, ctx.configDir, groupId, agentId, void 0, { [ACTING_AGENT_HEADER]: agentId });
2452
+ const wipe = retireLocalGroupState(ctx.configDir, agentId, groupId);
2453
+ printMutationOk("Left group", ctx.gOpts.json);
2454
+ if (!ctx.gOpts.json) {
2455
+ if (wipe.error) printText(wipe.error);
2456
+ if (wipe.retired) printText(retirementMessage(left, heldMlsState));
2457
+ }
1113
2458
  }));
1114
- group.command("invite").description("Invite an agent to the group").argument("<group-id>", "Group ID").requiredOption("--agent <id>", "Agent ID to invite").option("--message <msg>", "Invitation message").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, groupId, opts) => {
1115
- const agentId = await resolveToUuid(apiUrl, opts.agent);
1116
- const body = { agent_id: agentId };
1117
- if (opts.message) body.message = opts.message;
1118
- const data = await client.post(`/groups/${groupId}/invite`, body);
1119
- await addMemberToMls(client, configDir, apiUrl, groupId, agentId, gOpts.as, gOpts.json);
1120
- await sendInviteNotification(client, configDir, apiUrl, groupId, agentId, opts.message, gOpts.as, gOpts.json);
1121
- if (gOpts.json) printJson(data);
2459
+ group.command("kick").description("Remove a member from the group (admin)").argument("<group-ref>", GROUP_REFERENCE_HELP).argument("<agent-id>", "Agent ID or handle to remove").action(withClient(program, async (ctx, ref, agentId) => {
2460
+ announceHandleCompletion(agentId);
2461
+ const resolved = await resolveToUuid(ctx.apiUrl, agentId);
2462
+ let groupId = ref;
2463
+ let target;
2464
+ if (UUID_RE.test(ref)) target = await readGroup(ctx, ref);
1122
2465
  else {
1123
- printText("Invitation sent");
1124
- if (data.id) printTable([requestRow(data)]);
2466
+ const seated = await groupTarget(ctx, ref);
2467
+ groupId = seated.id;
2468
+ target = seated.row;
1125
2469
  }
2470
+ const removal = await deleteGroupMember(ctx.client, ctx.configDir, groupId, resolved, () => ctx.actingAgent(), ctx.extraHeaders);
2471
+ printMutationOk("Member removed", ctx.gOpts.json);
2472
+ const evicted = evictionMessage(target, removal);
2473
+ if (!ctx.gOpts.json && evicted) printText(evicted);
1126
2474
  }));
1127
- group.command("requests").description("List pending join requests").argument("<group-id>", "Group ID").action(withClient(program, async ({ client, gOpts }, groupId) => {
1128
- const data = await client.get(`/groups/${groupId}/requests`);
2475
+ }
2476
+ //#endregion
2477
+ //#region src/commands/group-requests.ts
2478
+ /** An open group has no ratchet tree, so there is no admission to resume in it. */
2479
+ const NOT_AN_MLS_GROUP = "This group runs on Sender Keys, not MLS, so it has no ratchet tree to seat anyone in. Open-enrollment groups are sender-key groups by design: MLS would hand an unattested joiner a cryptographic seat, so the server keeps open enrollment off the MLS path. There is nothing to resume here.";
2480
+ function printAdmission(result, json) {
2481
+ if (json) {
2482
+ printJson(result);
2483
+ return;
2484
+ }
2485
+ printText(`Seated ${result.added} of ${result.outcomes.length} in ${result.commits} commit(s), now at epoch ${result.epoch}.`);
2486
+ printTable(admissionOutcomeRows(result));
2487
+ printReclamation(result.reclamation);
2488
+ }
2489
+ /**
2490
+ * What `--reclaim` did, or the stated reason it did nothing.
2491
+ *
2492
+ * The sentence is `describeMlsReclamation`'s, from rine-core — the TypeScript
2493
+ * stack's one copy, sentence for sentence identical to the Python twin. This
2494
+ * function composed its own three branches until the MCP server, eve and mastra
2495
+ * needed the same three, which is the drift a single shared sentence stops: four
2496
+ * surfaces reporting the same reclamation in four wordings.
2497
+ */
2498
+ function printReclamation(reclamation) {
2499
+ const said = describeMlsReclamation(reclamation);
2500
+ if (said) printText(said);
2501
+ }
2502
+ /**
2503
+ * What the vote did to the request, beside the wire token.
2504
+ *
2505
+ * There are **four** answers and not three. `invited` is the one no client
2506
+ * anticipated: the electorate approved a nomination whose subject has not
2507
+ * answered yet, so the row resolves to a spendable invitation rather than to a
2508
+ * seat — a carried vote seats only an agent that consented. Reported
2509
+ * by name here because a fall-through would render a carried vote as an unknown
2510
+ * status, and because it is the one outcome where nobody is added to the
2511
+ * ratchet tree despite the bar being met.
2512
+ *
2513
+ * An unrecognised status renders as itself and gets no sentence — a guess about
2514
+ * a token this build predates would be worse than the token.
2515
+ */
2516
+ function voteOutcomeSentence(status) {
2517
+ switch (status) {
2518
+ case "approved": return "the request carried and that agent is now a member";
2519
+ case "denied": return "the request was refused";
2520
+ case "pending": return "neither bar is reached yet, so the request stands";
2521
+ case "invited": return "the request carried, and because its subject was nominated and has not answered yet it is now an invitation for them to accept";
2522
+ default: return "";
2523
+ }
2524
+ }
2525
+ function registerGroupRequests(program, group) {
2526
+ group.command("requests").description("List what this group still owes an answer on").argument("<group-ref>", GROUP_REFERENCE_HELP).option("--outstanding <filter>", "pending (the vote queue — requests agents filed for themselves and nominations members filed for them), invited (unaccepted invitations), or live (both)", "pending").action(withClient(program, async (ctx, ref, opts) => {
2527
+ const { client, gOpts } = ctx;
2528
+ const { id: groupId } = await groupTarget(ctx, ref);
2529
+ const data = await client.get(`/groups/${groupId}/requests`, { outstanding: opts.outstanding });
1129
2530
  if (gOpts.json) printJson(data);
1130
2531
  else printTable(data.items.map(requestRow));
1131
2532
  }));
1132
- group.command("invites").description("List group invitations addressed to you").action(withClient(program, async ({ client, gOpts, extraHeaders }) => {
2533
+ group.command("invites").description("List group invitations and nominations addressed to you. The Status column tells them apart: `invited` is a voucher `rine group join` spends, `pending` a nomination a member filed for you that the group's electorate decides — joining that one records that you want in and leaves the request with them.").action(withClient(program, async ({ client, gOpts, extraHeaders }) => {
1133
2534
  const items = await listMyInvites(client, extraHeaders);
1134
2535
  if (gOpts.json) printJson(items);
1135
2536
  else printTable(items.map(inviteRow));
1136
2537
  }));
1137
- group.command("vote").description("Vote on a join request").argument("<group-id>", "Group ID").argument("<request-id>", "Join request ID").requiredOption("--vote <vote>", "Vote: approve or deny").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, groupId, requestId, opts) => {
2538
+ group.command("resume-admission").description("Seat every member and invitee this group has not seated yet").argument("<group-ref>", GROUP_REFERENCE_HELP).option("--reclaim", "Also retire ratchet-tree leaves no member and no live invitation or nomination accounts for — a lapsed invitation frees its seat but not its leaf. Costs one O(N) commit per leaf, billed to every member. Never automatic, and any member may run it: nothing retires a leaf until somebody does.").action(withClient(program, async (ctx, ref, opts) => {
2539
+ const { id: groupId, row: target } = await groupTarget(ctx, ref);
2540
+ if (target.enrollment_policy === "open") {
2541
+ printError(NOT_AN_MLS_GROUP);
2542
+ process.exitCode = 2;
2543
+ return;
2544
+ }
2545
+ const actingId = await ctx.actingAgent();
2546
+ const headers = { [ACTING_AGENT_HEADER]: actingId };
2547
+ try {
2548
+ printAdmission(groupIsMls(target) ? await resumeMlsGroupAdmission(ctx.configDir, actingId, groupId, ctx.client, headers, { reclaim: opts.reclaim }) : await initMlsGroup(ctx.configDir, actingId, groupId, ctx.client, headers), ctx.gOpts.json);
2549
+ } catch (err) {
2550
+ printError(mlsFailureText(err, groupId));
2551
+ process.exitCode = 1;
2552
+ }
2553
+ }));
2554
+ group.command("vote").description(`Vote on a join request. ${VOTE_ELECTORATE_RULE} \`rine group requests\` says whether your own vote counts before you spend a call on it. A vote that carries an agent's own application seats it; one that carries a nomination the agent has not answered yet turns it into an invitation for them to accept.`).argument("<group-ref>", GROUP_REFERENCE_HELP).argument("<request-id>", "Join request ID").requiredOption("--vote <vote>", "Vote: approve or deny").action(withClient(program, async (ctx, ref, requestId, opts) => {
1138
2555
  if (opts.vote !== "approve" && opts.vote !== "deny") {
1139
2556
  printError("--vote must be 'approve' or 'deny'");
1140
2557
  process.exitCode = 2;
1141
2558
  return;
1142
2559
  }
2560
+ const { id: groupId } = await groupTarget(ctx, ref);
1143
2561
  let applicantId;
1144
- if (opts.vote === "approve") applicantId = (await client.get(`/groups/${groupId}/requests`)).items.find((r) => r.id === requestId)?.agent_id;
1145
- const data = await client.post(`/groups/${groupId}/requests/${requestId}/vote`, { vote: opts.vote });
1146
- if (data.status === "approved" && applicantId) await addMemberToMls(client, configDir, apiUrl, groupId, applicantId, gOpts.as, gOpts.json);
1147
- if (gOpts.json) printJson(data);
1148
- else printText(`Vote recorded. Request status: ${data.status}`);
2562
+ if (opts.vote === "approve") applicantId = (await ctx.client.get(`/groups/${groupId}/requests`)).items.find((r) => r.id === requestId)?.agent_id;
2563
+ const data = await ctx.client.post(`/groups/${groupId}/requests/${requestId}/vote`, { vote: opts.vote });
2564
+ if (data.status === "approved" && applicantId) await seatApplicant(ctx, groupId, applicantId);
2565
+ if (ctx.gOpts.json) printJson(data);
2566
+ else {
2567
+ const said = voteOutcomeSentence(data.status);
2568
+ printText(`Vote recorded. Request status: ${data.status}` + (said ? ` — ${said}` : ""));
2569
+ }
2570
+ }));
2571
+ }
2572
+ /** Best-effort MLS add for a newly approved applicant; never fails the vote. */
2573
+ async function seatApplicant(ctx, groupId, applicantId) {
2574
+ try {
2575
+ const target = await ctx.client.get(`/groups/${groupId}`);
2576
+ const actingId = await ctx.actingAgent();
2577
+ await admitToMls(ctx.client, ctx.configDir, actingId, groupId, target.mls_group_id, [applicantId], ctx.gOpts.json);
2578
+ } catch (err) {
2579
+ if (!ctx.gOpts.json) printText(`Warning: MLS add-member failed: ${mlsFailureText(err, groupId)}`);
2580
+ }
2581
+ }
2582
+ //#endregion
2583
+ //#region src/commands/group-sync.ts
2584
+ function registerGroupSync(program, group) {
2585
+ group.command("sync").description("Catch this agent's group encryption state up, and say what it cost").argument("<group-ref>", GROUP_REFERENCE_HELP).action(withClient(program, async (ctx, ref) => {
2586
+ const { row: target } = await groupTarget(ctx, ref);
2587
+ const label = target.handle ?? target.id;
2588
+ if (groupMlsInitInFlight(target)) {
2589
+ printError(mlsInitInFlightSync(target.handle ?? target.id));
2590
+ process.exitCode = 2;
2591
+ return;
2592
+ }
2593
+ const actingId = await ctx.actingAgent();
2594
+ try {
2595
+ const result = await recoverGroup(ctx.configDir, actingId, target, ctx.client, { [ACTING_AGENT_HEADER]: actingId }, CLI_UNFOUNDED_REPAIR);
2596
+ if (ctx.gOpts.json) printJson(result);
2597
+ else printText(describeMlsRecovery(label, result));
2598
+ } catch (err) {
2599
+ printError(mlsFailureText(err, label));
2600
+ process.exitCode = isMlsResyncUnavailable(err) ? 2 : 1;
2601
+ }
1149
2602
  }));
1150
2603
  }
1151
2604
  //#endregion
2605
+ //#region src/commands/group.ts
2606
+ /**
2607
+ * `rine group` — the group lifecycle, in six files.
2608
+ *
2609
+ * Split by what a subcommand is about rather than left as one listing: create
2610
+ * carries the visibility refusal and the roster, membership carries the
2611
+ * removal path and what leaving retires, invite carries plural admission,
2612
+ * requests carries the vote and the resume verb, and sync carries the recovery
2613
+ * ladder. Each registrar takes the root `program` because `withClient` reads
2614
+ * the global options off it.
2615
+ */
2616
+ function registerGroup(program) {
2617
+ const group = program.command("group").description("Group management");
2618
+ registerGroupCreate(program, group);
2619
+ registerGroupCrud(program, group);
2620
+ registerGroupMembership(program, group);
2621
+ registerGroupInvite(program, group);
2622
+ registerGroupRequests(program, group);
2623
+ registerGroupSync(program, group);
2624
+ }
2625
+ //#endregion
1152
2626
  //#region src/commands/hook.ts
1153
2627
  const SIGNATURE_HEADER = "X-Hub-Signature-256";
1154
2628
  const CONTENT_TYPE = "application/json";
@@ -1166,7 +2640,7 @@ function resolveTier(raw) {
1166
2640
  }
1167
2641
  function registerHook(program) {
1168
2642
  const hook = program.command("hook").description("Manage inbound webhook funnel hooks");
1169
- hook.command("create").description("Allocate a funnel hook and print its GitHub setup (secret shown once)").option("--agent <id>", "Agent ID (defaults to your agent)").option("--name <name>", "Hook name (default: default)", "default").addOption(new Option("--tier <tier>", "Termination tier: zero-trust (your relay terminates TLS; rine never sees the cleartext) or shared-edge (rine's broker terminates TLS for high-scale delivery; brief in-memory cleartext, never stored). Default: by trust tier.").choices(Object.keys(TIER_CLI_TO_WIRE))).action(withClient(program, async ({ client, gOpts, apiUrl, configDir }, opts) => {
2643
+ hook.command("create").description("Allocate a funnel hook and print its GitHub setup (secret shown once)").addOption(actorOption()).option("--name <name>", "Hook name (default: default)", "default").addOption(new Option("--tier <tier>", "Termination tier: zero-trust (your relay terminates TLS; rine never sees the cleartext) or shared-edge (rine's broker terminates TLS for high-scale delivery; brief in-memory cleartext, never stored). Default: by trust tier.").choices(Object.keys(TIER_CLI_TO_WIRE))).action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, opts) => {
1170
2644
  const nameError = hookNameError(opts.name);
1171
2645
  if (nameError) {
1172
2646
  printError(`Invalid hook name '${opts.name}': ${nameError}.`);
@@ -1181,7 +2655,7 @@ function registerHook(program) {
1181
2655
  process.exitCode = 2;
1182
2656
  return;
1183
2657
  }
1184
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
2658
+ const agentId = await actingAgent();
1185
2659
  const secret = generateHookSecret();
1186
2660
  saveHookSecret(configDir, agentId, opts.name, secret);
1187
2661
  let created;
@@ -1196,8 +2670,8 @@ function registerHook(program) {
1196
2670
  }
1197
2671
  printCreated(created, secret, gOpts.json);
1198
2672
  }));
1199
- hook.command("list").description("List your agent's funnel hooks").option("--agent <id>", "Agent ID (defaults to your agent)").action(withClient(program, async ({ client, gOpts, apiUrl }, opts) => {
1200
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
2673
+ hook.command("list").description("List your agent's funnel hooks").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, actingAgent }) => {
2674
+ const agentId = await actingAgent();
1201
2675
  const data = await client.get(`/agents/${agentId}/funnel/hooks`, {});
1202
2676
  if (gOpts.json) printJson(data);
1203
2677
  else printTable(data.items.map((h) => ({
@@ -1208,8 +2682,8 @@ function registerHook(program) {
1208
2682
  Created: h.created_at
1209
2683
  })));
1210
2684
  }));
1211
- hook.command("delete").description("Delete a funnel hook and purge its local secret").option("--agent <id>", "Agent ID (defaults to your agent)").requiredOption("--name <name>", "Hook name to delete").option("--yes", "Skip confirmation prompt").action(withClient(program, async ({ client, gOpts, apiUrl, configDir }, opts) => {
1212
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
2685
+ hook.command("delete").description("Delete a funnel hook and purge its local secret").addOption(actorOption()).requiredOption("--name <name>", "Hook name to delete").option("--yes", "Skip confirmation prompt").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, opts) => {
2686
+ const agentId = await actingAgent();
1213
2687
  if (!opts.yes && !gOpts.json) {
1214
2688
  if (!await promptConfirm(`Delete funnel hook '${opts.name}'?`)) return;
1215
2689
  }
@@ -1305,10 +2779,9 @@ async function verifyServerKeys(client, agentId, expected) {
1305
2779
  }
1306
2780
  function registerKeys(program) {
1307
2781
  const keys = program.command("keys").description("E2EE key management");
1308
- keys.command("status").description("Show E2EE key status for an agent").option("--agent <id>", "Agent ID").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, opts) => {
1309
- const agents = await fetchAgents(client);
1310
- const agentId = await resolveAgent(apiUrl, agents, opts.agent, gOpts.as);
1311
- const handle = agents.find((a) => a.id === agentId)?.handle ?? "unknown";
2782
+ keys.command("status").description("Show E2EE key status for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, configDir, actingAgent, agents }) => {
2783
+ const agentId = await actingAgent();
2784
+ const handle = (await agents()).find((a) => a.id === agentId)?.handle ?? "unknown";
1312
2785
  const hasLocal = agentKeysExist(configDir, agentId);
1313
2786
  let hasServer = false;
1314
2787
  let serverKeys;
@@ -1376,8 +2849,8 @@ function registerKeys(program) {
1376
2849
  }
1377
2850
  ]);
1378
2851
  }));
1379
- keys.command("generate").description("Generate new E2EE keys for an agent").option("--agent <id>", "Agent ID").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, opts) => {
1380
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
2852
+ keys.command("generate").description("Generate new E2EE keys for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, configDir, actingAgent }) => {
2853
+ const agentId = await actingAgent();
1381
2854
  if (agentKeysExist(configDir, agentId)) {
1382
2855
  printError(`Keys already exist for agent ${agentId}. Use 'rine keys rotate' to replace them.`);
1383
2856
  process.exitCode = 1;
@@ -1390,8 +2863,8 @@ function registerKeys(program) {
1390
2863
  saveAgentKeys(configDir, agentId, agentKeys);
1391
2864
  printMutationOk(`E2EE keys generated for agent ${agentId}`, gOpts.json);
1392
2865
  }));
1393
- keys.command("rotate").description("Rotate E2EE keys for an agent").option("--agent <id>", "Agent ID").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, opts) => {
1394
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
2866
+ keys.command("rotate").description("Rotate E2EE keys for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, configDir, actingAgent }) => {
2867
+ const agentId = await actingAgent();
1395
2868
  if (agentKeysExist(configDir, agentId)) backupKeys(configDir, agentId);
1396
2869
  const agentKeys = generateAgentKeys();
1397
2870
  const pubKeys = getAgentPublicKeys(configDir, agentId, agentKeys);
@@ -1400,8 +2873,8 @@ function registerKeys(program) {
1400
2873
  saveAgentKeys(configDir, agentId, agentKeys);
1401
2874
  printMutationOk(`E2EE keys rotated for agent ${agentId}`, gOpts.json);
1402
2875
  }));
1403
- keys.command("add-pq").description("Add a post-quantum encryption key without rotating other keys").option("--agent <id>", "Agent ID").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, opts) => {
1404
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
2876
+ keys.command("add-pq").description("Add a post-quantum encryption key without rotating other keys").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, configDir, actingAgent }) => {
2877
+ const agentId = await actingAgent();
1405
2878
  if (!agentKeysExist(configDir, agentId)) {
1406
2879
  printError(`No keys found for agent ${agentId}. Use 'rine keys generate' first.`);
1407
2880
  process.exitCode = 1;
@@ -1424,8 +2897,8 @@ function registerKeys(program) {
1424
2897
  savePqEncryptionKey(configDir, agentId, pqKeyPair);
1425
2898
  printMutationOk(`Post-quantum encryption key added for agent ${agentId}`, gOpts.json);
1426
2899
  }));
1427
- keys.command("export").description("Export private keys to a file").option("--agent <id>", "Agent ID").requiredOption("--output <file>", "Output file path").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, opts) => {
1428
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
2900
+ keys.command("export").description("Export private keys to a file").addOption(actorOption()).requiredOption("--output <file>", "Output file path").action(withClient(program, async ({ gOpts, configDir, actingAgent }, opts) => {
2901
+ const agentId = await actingAgent();
1429
2902
  if (!agentKeysExist(configDir, agentId)) {
1430
2903
  printError(`No keys found for agent ${agentId}`);
1431
2904
  process.exitCode = 1;
@@ -1519,7 +2992,58 @@ function x402SendExtras(type, payload, emitMarker) {
1519
2992
  return extras;
1520
2993
  }
1521
2994
  //#endregion
1522
- //#region src/commands/messages.ts
2995
+ //#region src/commands/messages-read-decrypt.ts
2996
+ /**
2997
+ * Open one fetched message with the caller's own keys, and — when it stays
2998
+ * closed — say why in one sentence a reader can act on.
2999
+ *
3000
+ * Split out of `messages-read.ts` (file-size budget) so that command is left
3001
+ * with its rendering. This is the SINGLE tier of the explain-once rule: the
3002
+ * caller named ONE message, so the refusal is stated in full. There is no
3003
+ * second row for it to repeat itself on, and nothing here creates a
3004
+ * `senderKeyExplainer`.
3005
+ *
3006
+ * A refusal is returned rather than printed, because the same fact has to reach
3007
+ * two different outputs: stderr prose for a human, and a field on the `--json`
3008
+ * envelope for a program. A helper that printed could only serve one of them.
3009
+ */
3010
+ /** Decrypt one message, dispatching on its encryption version. Never throws. */
3011
+ async function openMessage(opts) {
3012
+ const { client, configDir, agentId, data, fromAgentId } = opts;
3013
+ if (!((data.encryption_version === "sender-key-v1" || data.encryption_version === "mls-v1") && data.group_id != null)) try {
3014
+ return {
3015
+ result: await decryptMessage(configDir, agentId, data.encrypted_payload, client, fromAgentId),
3016
+ refusal: null
3017
+ };
3018
+ } catch (err) {
3019
+ return { refusal: {
3020
+ message: `Decryption failed: ${text(err)}`,
3021
+ code: null
3022
+ } };
3023
+ }
3024
+ const groupId = data.group_id;
3025
+ try {
3026
+ return {
3027
+ result: await decryptGroupMessageWithRecovery(client, configDir, agentId, groupId, data.encrypted_payload, fromAgentId),
3028
+ refusal: null
3029
+ };
3030
+ } catch (err) {
3031
+ const unavailable = asSenderKeyUnavailable(err, groupId);
3032
+ if (unavailable !== null) return { refusal: {
3033
+ message: unavailable.message,
3034
+ code: SENDER_KEY_UNAVAILABLE_CODE
3035
+ } };
3036
+ return { refusal: {
3037
+ message: `Decryption failed: ${text(err)}`,
3038
+ code: null
3039
+ } };
3040
+ }
3041
+ }
3042
+ function text(err) {
3043
+ return err instanceof Error ? err.message : String(err);
3044
+ }
3045
+ //#endregion
3046
+ //#region src/commands/messages-rows.ts
1523
3047
  function msgFrom(m) {
1524
3048
  return m.sender_handle ?? m.from_agent_id ?? "";
1525
3049
  }
@@ -1550,6 +3074,16 @@ function inboxRow(m) {
1550
3074
  Created: m.created_at
1551
3075
  };
1552
3076
  }
3077
+ /**
3078
+ * Render the sender-signature outcome for a table column. Both authenticity
3079
+ * failures are marked, and told apart: tampered bytes and content attributed to
3080
+ * an agent that did not sign it are different problems for an operator.
3081
+ */
3082
+ function verifiedMark(status) {
3083
+ if (status === "verified") return "✓";
3084
+ if (!isAuthenticityFailure(status)) return "?";
3085
+ return status === "sender-mismatch" ? "✗ SENDER MISMATCH" : "✗ INVALID";
3086
+ }
1553
3087
  /** One thread turn rendered as a role-tagged row (`[sent]` you / `[received]`). */
1554
3088
  function threadRow(e) {
1555
3089
  const who = e.direction === "sent" ? "you" : e.sender_handle ?? "unknown";
@@ -1557,11 +3091,89 @@ function threadRow(e) {
1557
3091
  Direction: `[${e.direction}]`,
1558
3092
  From: who,
1559
3093
  Type: e.type,
1560
- Verified: e.verification_status === "verified" ? "✓" : e.verification_status === "invalid" ? "✗ INVALID" : "?",
3094
+ Verified: verifiedMark(e.verification_status),
1561
3095
  Text: e.text,
1562
3096
  Created: e.created_at
1563
3097
  };
1564
3098
  }
3099
+ //#endregion
3100
+ //#region src/commands/messages-read.ts
3101
+ /**
3102
+ * `rine message read` — fetch one message and open it.
3103
+ *
3104
+ * Split out of `messages.ts` because the decrypt-and-render pipeline is the
3105
+ * longest handler there by a wide margin and has nothing to do with sending.
3106
+ * The command is registered by `messages.ts` alongside its siblings, so the
3107
+ * CLI surface is unchanged.
3108
+ */
3109
+ /** Register `read` on the `message` command group. */
3110
+ function addReadCommand(parent, program) {
3111
+ parent.command("read").description("Read and decrypt a message by ID").argument("<message-id>", "Message ID").addOption(actorOption("which agent is acting, and whose key decrypts (name, handle, or agent ID)")).action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, messageId) => {
3112
+ const agentId = await actingAgent();
3113
+ const data = await client.get(`/messages/${messageId}`);
3114
+ const fromAgentId = data.from_agent_id;
3115
+ const canDecrypt = fromAgentId !== void 0 && (data.encryption_version === "hpke-v1" || data.encryption_version === "hpke-hybrid-v1" || data.encryption_version === "sender-key-v1" || data.encryption_version === "mls-v1") && agentKeysExist(configDir, agentId);
3116
+ let refusal = null;
3117
+ if (canDecrypt) {
3118
+ const opened = await openMessage({
3119
+ client,
3120
+ configDir,
3121
+ agentId,
3122
+ data,
3123
+ fromAgentId
3124
+ });
3125
+ const decResult = opened.result;
3126
+ refusal = opened.refusal;
3127
+ if (refusal !== null && !gOpts.json) printError(refusal.message);
3128
+ if (decResult) {
3129
+ if (ingestSenderKeyDistribution(configDir, agentId, data.type, decResult)) printText("Sender key ingested");
3130
+ if (gOpts.json) printJson({
3131
+ ...data,
3132
+ decrypted_payload: decResult.plaintext === void 0 ? null : JSON.parse(decResult.plaintext),
3133
+ signature_verified: decResult.verified,
3134
+ verification_status: decResult.verificationStatus,
3135
+ sender_kid: decResult.senderKid,
3136
+ ...decResult.catchUp ? { catch_up: decResult.catchUp } : {}
3137
+ });
3138
+ else {
3139
+ if (decResult.catchUp?.evicted) printError(MLS_EVICTED_BY_COMMIT);
3140
+ printTable([{
3141
+ ID: data.id,
3142
+ "Conversation ID": data.conversation_id,
3143
+ From: msgFrom(data),
3144
+ To: msgTo(data),
3145
+ Group: msgGroup(data),
3146
+ Type: data.type,
3147
+ Verified: verifiedMark(decResult.verificationStatus),
3148
+ Payload: decResult.plaintext?.slice(0, 200) ?? THREAD_UNAVAILABLE,
3149
+ Created: data.created_at
3150
+ }]);
3151
+ }
3152
+ return;
3153
+ }
3154
+ }
3155
+ if (gOpts.json) printJson({
3156
+ ...data,
3157
+ ...refusal !== null ? {
3158
+ decrypt_error: refusal.message,
3159
+ decrypt_error_code: refusal.code
3160
+ } : {}
3161
+ });
3162
+ else printTable([{
3163
+ ID: data.id,
3164
+ "Conversation ID": data.conversation_id,
3165
+ From: msgFrom(data),
3166
+ To: msgTo(data),
3167
+ Group: msgGroup(data),
3168
+ Type: data.type,
3169
+ Encryption: data.encryption_version,
3170
+ "Encrypted Payload": `${data.encrypted_payload.slice(0, 40)}...`,
3171
+ Created: data.created_at
3172
+ }]);
3173
+ }));
3174
+ }
3175
+ //#endregion
3176
+ //#region src/commands/messages.ts
1565
3177
  function resolvePayload(payload, payloadFile) {
1566
3178
  if (payload !== void 0 && payloadFile !== void 0) return { error: "--payload and --payload-file are mutually exclusive" };
1567
3179
  if (payload === void 0 && payloadFile === void 0) return { error: "Provide --payload or --payload-file" };
@@ -1578,20 +3190,15 @@ function resolvePayload(payload, payloadFile) {
1578
3190
  return { error: "Payload must be valid JSON" };
1579
3191
  }
1580
3192
  }
1581
- async function resolveGroup(client, handle) {
1582
- const group = (await client.get("/groups", { handle })).items?.[0];
1583
- if (!group) throw new Error(`Group not found: ${handle}`);
1584
- return group;
1585
- }
1586
3193
  async function encryptMlsWithRecovery(client, configDir, senderAgentId, groupId, payload) {
1587
- const hdrs = { "X-Rine-Agent": senderAgentId };
3194
+ const hdrs = { [ACTING_AGENT_HEADER]: senderAgentId };
1588
3195
  await processMlsWelcomes(configDir, senderAgentId, client).catch(() => {});
1589
3196
  await syncMlsGroup(configDir, senderAgentId, groupId, client, hdrs).catch(() => {});
1590
3197
  try {
1591
3198
  return await encryptMlsGroupMessage(configDir, senderAgentId, groupId, payload);
1592
3199
  } catch (err) {
1593
- if (err instanceof Error && err.message.startsWith("No MLS state for group")) {
1594
- await processMlsWelcomes(configDir, senderAgentId, client);
3200
+ if (isNoMlsStateError(err)) {
3201
+ await processMlsWelcomes(configDir, senderAgentId, client, { forGroup: groupId });
1595
3202
  await syncMlsGroup(configDir, senderAgentId, groupId, client, hdrs);
1596
3203
  return await encryptMlsGroupMessage(configDir, senderAgentId, groupId, payload);
1597
3204
  }
@@ -1599,7 +3206,9 @@ async function encryptMlsWithRecovery(client, configDir, senderAgentId, groupId,
1599
3206
  }
1600
3207
  }
1601
3208
  function addMessageCommands(parent, program) {
1602
- parent.command("send").description("Send an encrypted message").requiredOption("--to <address>", "Recipient: agent handle (agent@org), agent ID, or group handle (#group@org)").option("--type <type>", "Message type (default: rine.v1.dm)").option("--payload <json>", "Message payload as JSON string").option("--payload-file <path>", "Read payload JSON from file (use - for stdin)").option("--from <address>", "Sender: agent handle (agent@org) or agent ID").option("--idempotency-key <key>", "Idempotency key header").option("--no-marker", "For x402 message types: omit the cleartext status marker").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, opts) => {
3209
+ addReadCommand(parent, program);
3210
+ parent.command("send").description("Send an encrypted message").requiredOption("--to <address>", "Recipient: an agent handle (kofi@acme.rine.network), an agent ID, or a group — by handle (#logistics@acme.rine.network) or by sigiled name (#logistics)").option("--type <type>", "Message type (default: rine.v1.dm)").option("--payload <json>", "Message payload as JSON string").option("--payload-file <path>", "Read payload JSON from file (use - for stdin)").addOption(actorOption("which agent is acting, and sends")).addOption(actorAliasOption("--from <address>", "which agent is acting — the retired spelling of --agent (handle or agent ID)")).option("--idempotency-key <key>", "Idempotency key header").option("--no-marker", "For x402 message types: omit the cleartext status marker").action(withClient(program, async (ctx, opts) => {
3211
+ const { client, gOpts, configDir, apiUrl, actingAgent } = ctx;
1603
3212
  const result = resolvePayload(opts.payload, opts.payloadFile);
1604
3213
  if ("error" in result) {
1605
3214
  printError(result.error);
@@ -1609,19 +3218,17 @@ function addMessageCommands(parent, program) {
1609
3218
  const parsedPayload = result.parsed;
1610
3219
  const to = normalizeHandle(opts.to);
1611
3220
  const from = opts.from ? normalizeHandle(opts.from) : opts.from;
3221
+ const senderAgentId = await actingAgent();
1612
3222
  const extraHeaders = {};
1613
- let senderAgentId;
1614
- if (from !== void 0) {
1615
- senderAgentId = await resolveToUuid(apiUrl, from);
1616
- extraHeaders["X-Rine-Agent"] = senderAgentId;
1617
- } else if (!gOpts.as) {
1618
- senderAgentId = await resolveAgent(apiUrl, await fetchAgents(client), void 0, void 0);
1619
- extraHeaders["X-Rine-Agent"] = senderAgentId;
1620
- } else senderAgentId = await resolveAgent(apiUrl, await fetchAgents(client), void 0, gOpts.as);
1621
3223
  if (opts.idempotencyKey) extraHeaders["Idempotency-Key"] = opts.idempotencyKey;
3224
+ const isGroupSend = to.startsWith("#");
1622
3225
  let recipientAgentId;
1623
- if (!to.includes("@")) recipientAgentId = to;
1624
- else if (!to.startsWith("#")) recipientAgentId = await resolveToUuid(apiUrl, to);
3226
+ if (isGroupSend) recipientAgentId = void 0;
3227
+ else if (!to.includes("@")) recipientAgentId = to;
3228
+ else {
3229
+ announceHandleCompletion(opts.to);
3230
+ recipientAgentId = await resolveToUuid(apiUrl, to);
3231
+ }
1625
3232
  const resolvedType = opts.type ?? "rine.v1.dm";
1626
3233
  const body = { type: resolvedType };
1627
3234
  const x402 = x402SendExtras(resolvedType, parsedPayload, opts.marker !== false);
@@ -1630,20 +3237,26 @@ function addMessageCommands(parent, program) {
1630
3237
  body.payload_schema = x402.payload_schema;
1631
3238
  if (x402.metadata) body.metadata = x402.metadata;
1632
3239
  }
1633
- if (to.includes("@")) body.to_handle = to;
3240
+ if (!isGroupSend) if (to.includes("@")) body.to_handle = to;
1634
3241
  else body.to_agent_id = to;
1635
3242
  if (from?.includes("@")) body.from_handle = from;
1636
- if (to.startsWith("#") && senderAgentId) {
1637
- const group = await resolveGroup(client, to);
1638
- if (group.mls_group_id) {
3243
+ if (isGroupSend) {
3244
+ const group = await resolveGroupByHandle(client, to).catch(async (err) => {
3245
+ throw await withEvictionPointerIfHeld(ctx, err);
3246
+ });
3247
+ body.to_handle = group.handle;
3248
+ const mlsOnly = groupAcceptsMlsSendOnly(group);
3249
+ assertNoMlsDowngrade(configDir, senderAgentId, group.id, mlsOnly);
3250
+ if (mlsOnly) {
3251
+ if (group.mls_group_id == null) throw new MlsInitInFlightError(to);
1639
3252
  const encResult = await encryptMlsWithRecovery(client, configDir, senderAgentId, group.id, parsedPayload);
1640
3253
  Object.assign(body, encResult);
1641
3254
  } else {
1642
- const { state, groupId } = await getOrCreateSenderKey(client, configDir, senderAgentId, to, Object.keys(extraHeaders).length > 0 ? extraHeaders : void 0);
3255
+ const { state, groupId } = await getOrCreateSenderKey(client, configDir, senderAgentId, group.handle);
1643
3256
  const { result: encResult } = await encryptGroupMessage(configDir, senderAgentId, groupId, state, parsedPayload);
1644
3257
  Object.assign(body, encResult);
1645
3258
  }
1646
- } else if (senderAgentId && recipientAgentId) {
3259
+ } else if (recipientAgentId) {
1647
3260
  const recipientKeys = await fetchRecipientKeys(client, recipientAgentId);
1648
3261
  const encrypted = await encryptMessage(configDir, senderAgentId, recipientKeys.encryption, parsedPayload, recipientKeys.pqEncryption);
1649
3262
  Object.assign(body, encrypted);
@@ -1652,72 +3265,13 @@ function addMessageCommands(parent, program) {
1652
3265
  if (gOpts.json) printJson(data);
1653
3266
  else printTable([sendRow(data)]);
1654
3267
  }));
1655
- parent.command("read").description("Read and decrypt a message by ID").argument("<message-id>", "Message ID").option("--agent <id>", "Agent ID (for decryption key)").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, messageId, opts) => {
1656
- const data = await client.get(`/messages/${messageId}`);
1657
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
1658
- if ((data.encryption_version === "hpke-v1" || data.encryption_version === "hpke-hybrid-v1" || data.encryption_version === "sender-key-v1" || data.encryption_version === "mls-v1") && agentKeysExist(configDir, agentId)) {
1659
- let decResult;
1660
- if ((data.encryption_version === "sender-key-v1" || data.encryption_version === "mls-v1") && data.group_id) try {
1661
- decResult = await decryptGroupMessage(configDir, agentId, data.group_id, data.encrypted_payload, client);
1662
- } catch (err) {
1663
- const match = err instanceof Error && err.message.match(/^unknown sender key id: (.+)$/);
1664
- if (match) {
1665
- if (await fetchAndIngestPendingSKDistributions(client, configDir, agentId, match[1]) > 0) try {
1666
- decResult = await decryptGroupMessage(configDir, agentId, data.group_id, data.encrypted_payload, client);
1667
- } catch (retryErr) {
1668
- if (!gOpts.json) printError(`Decryption failed after auto-ingest: ${retryErr instanceof Error ? retryErr.message : String(retryErr)}`);
1669
- }
1670
- else if (!gOpts.json) printError(`Decryption failed: ${err.message}`);
1671
- } else if (!gOpts.json) printError(`Decryption failed: ${err instanceof Error ? err.message : String(err)}`);
1672
- }
1673
- else try {
1674
- decResult = await decryptMessage(configDir, agentId, data.encrypted_payload, client);
1675
- } catch (err) {
1676
- if (!gOpts.json) printError(`Decryption failed: ${err instanceof Error ? err.message : String(err)}`);
1677
- }
1678
- if (decResult) {
1679
- if (ingestSenderKeyDistribution(configDir, agentId, data.type, decResult)) printText("Sender key ingested");
1680
- if (gOpts.json) printJson({
1681
- ...data,
1682
- decrypted_payload: JSON.parse(decResult.plaintext),
1683
- signature_verified: decResult.verified,
1684
- verification_status: decResult.verificationStatus,
1685
- sender_kid: decResult.senderKid
1686
- });
1687
- else printTable([{
1688
- ID: data.id,
1689
- "Conversation ID": data.conversation_id,
1690
- From: msgFrom(data),
1691
- To: msgTo(data),
1692
- Group: msgGroup(data),
1693
- Type: data.type,
1694
- Verified: decResult.verificationStatus === "verified" ? "✓" : decResult.verificationStatus === "invalid" ? "✗ INVALID" : "?",
1695
- Payload: decResult.plaintext.slice(0, 200),
1696
- Created: data.created_at
1697
- }]);
1698
- return;
1699
- }
1700
- }
1701
- if (gOpts.json) printJson(data);
1702
- else printTable([{
1703
- ID: data.id,
1704
- "Conversation ID": data.conversation_id,
1705
- From: msgFrom(data),
1706
- To: msgTo(data),
1707
- Group: msgGroup(data),
1708
- Type: data.type,
1709
- Encryption: data.encryption_version,
1710
- "Encrypted Payload": `${data.encrypted_payload.slice(0, 40)}...`,
1711
- Created: data.created_at
1712
- }]);
1713
- }));
1714
- parent.command("inbox").description("List inbox messages").option("--agent <id>", "Agent ID (defaults to your agent)").option("--new", "Show only new (undelivered) messages").option("--delivered", "Show only delivered messages").option("--read", "Show only read messages").option("--limit <n>", "Maximum number of messages to return").option("--cursor <cursor>", "Pagination cursor").action(withClient(program, async ({ client, gOpts, apiUrl }, opts) => {
3268
+ parent.command("inbox").description("List inbox messages").addOption(actorOption()).option("--new", "Show only new (undelivered) messages").option("--delivered", "Show only delivered messages").option("--read", "Show only read messages").option("--limit <n>", "Maximum number of messages to return").option("--cursor <cursor>", "Pagination cursor").action(withClient(program, async ({ client, gOpts, actingAgent }, opts) => {
1715
3269
  if ([
1716
3270
  opts.new,
1717
3271
  opts.delivered,
1718
3272
  opts.read
1719
3273
  ].filter(Boolean).length > 1) throw new Error("Only one of --new, --delivered, --read can be specified");
1720
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
3274
+ const agentId = await actingAgent();
1721
3275
  const params = {};
1722
3276
  if (opts.new) params.status = "new";
1723
3277
  else if (opts.delivered) params.status = "delivered";
@@ -1731,7 +3285,7 @@ function addMessageCommands(parent, program) {
1731
3285
  if (data.next_cursor) printText(`Next cursor: ${data.next_cursor}`);
1732
3286
  }
1733
3287
  }));
1734
- parent.command("reply").description("Reply to a message (encrypted)").argument("<message-id>", "Message ID to reply to").option("--type <type>", "Message type (defaults to original message type)").option("--payload <json>", "Reply payload as JSON string").option("--payload-file <path>", "Read payload JSON from file (use - for stdin)").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, messageId, opts) => {
3288
+ parent.command("reply").description("Reply to a message (encrypted)").argument("<message-id>", "Message ID to reply to").addOption(actorOption("which agent is acting, and replies")).option("--type <type>", "Message type (defaults to original message type)").option("--payload <json>", "Reply payload as JSON string").option("--payload-file <path>", "Read payload JSON from file (use - for stdin)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, messageId, opts) => {
1735
3289
  const result = resolvePayload(opts.payload, opts.payloadFile);
1736
3290
  if ("error" in result) {
1737
3291
  printError(result.error);
@@ -1739,8 +3293,8 @@ function addMessageCommands(parent, program) {
1739
3293
  return;
1740
3294
  }
1741
3295
  const parsedPayload = result.parsed;
3296
+ const senderAgentId = await actingAgent();
1742
3297
  const original = await client.get(`/messages/${messageId}`);
1743
- const senderAgentId = await resolveAgent(apiUrl, await fetchAgents(client), void 0, gOpts.as);
1744
3298
  if (original.from_agent_id === senderAgentId) {
1745
3299
  console.error("Cannot reply to your own message. Use 'rine send' to follow up in this conversation.");
1746
3300
  process.exitCode = 1;
@@ -1763,12 +3317,16 @@ function addMessageCommands(parent, program) {
1763
3317
  process.exitCode = 1;
1764
3318
  }
1765
3319
  }));
1766
- parent.command("thread").description("Show the both-sided, decrypted transcript of a conversation (role-tagged)").argument("<conversation-id>", "Conversation ID").option("--agent <id>", "Agent ID (defaults to your agent)").option("--limit <n>", "Max turns to return (most-recent window)").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, conversationId, opts) => {
1767
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
1768
- const params = {};
1769
- if (opts.limit) params.limit = opts.limit;
1770
- const data = await client.get(`/conversations/${conversationId}/messages`, params, { "X-Rine-Agent": agentId });
1771
- const entries = await Promise.all((data.messages ?? []).map((row) => decryptThreadRow(configDir, agentId, row, client)));
3320
+ parent.command("thread").description("Show the both-sided, decrypted transcript of a conversation or a group (role-tagged)").argument("[conversation-id]", "Conversation ID").option("--group <ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).option("--limit <n>", "Max turns to return (most-recent window)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, conversationId, opts) => {
3321
+ const ref = resolveThreadRef({
3322
+ group: opts.group,
3323
+ conversationId
3324
+ }, THREAD_REF_SURFACES.cli);
3325
+ const agentId = await actingAgent();
3326
+ const entries = await decryptThreadRows(configDir, agentId, (await readThreadPage(client, ref, {
3327
+ ...opts.limit ? { limit: opts.limit } : {},
3328
+ extraHeaders: { [ACTING_AGENT_HEADER]: agentId }
3329
+ })).messages ?? [], client);
1772
3330
  if (gOpts.json) printJson(entries);
1773
3331
  else printTable(entries.map(threadRow));
1774
3332
  }));
@@ -1780,7 +3338,7 @@ function registerMessages(program) {
1780
3338
  //#endregion
1781
3339
  //#region src/commands/onboard.ts
1782
3340
  function registerOnboard(program) {
1783
- program.command("onboard").description("Register a new organization and create your first agent").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organization name").requiredOption("--slug <slug>", "Organization slug").requiredOption("--agent <agent-name>", "Name for the first agent").option("--[no-]human-oversight", "Require human oversight (default: true)").option("--unlisted", "Mark agent as unlisted (not in public directory)").option("--verify-identity", "After creating the agent, prove a SPIFFE identity (auto-runs when SPIFFE_ENDPOINT_SOCKET is set)").option("--svid <jwt>", "SPIFFE JWT-SVID to use for --verify-identity (when no Workload API auto-fetch is available)").action(withErrorHandler(program, async (gOpts, opts) => {
3341
+ program.command("onboard").description("Register a new organization and create your first agent").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organization name").requiredOption("--slug <slug>", "Organization slug").requiredOption("--agent-name <name>", "Name for the first agent").option("--[no-]human-oversight", "Require human oversight (default: true)").option("--unlisted", "Mark agent as unlisted (not in public directory)").option("--verify-identity", "After creating the agent, prove a SPIFFE identity (auto-runs when SPIFFE_ENDPOINT_SOCKET is set)").option("--svid <jwt>", "SPIFFE JWT-SVID to use for --verify-identity (when no Workload API auto-fetch is available)").action(withErrorHandler(program, async (gOpts, opts) => {
1784
3342
  const profile = gOpts.profile ?? "default";
1785
3343
  const configDir = resolveConfigDir();
1786
3344
  const apiUrl = resolveApiUrl();
@@ -1820,16 +3378,18 @@ function registerOnboard(program) {
1820
3378
  progressStream.write("\rSolving PoW challenge: 100%\n");
1821
3379
  const { client } = await createClient(configDir, apiUrl, gOpts.profile);
1822
3380
  const agent = await performAgentCreation(client, configDir, profile, {
1823
- name: opts.agent,
3381
+ name: opts.agentName,
1824
3382
  humanOversight: opts.humanOversight,
1825
3383
  unlisted: opts.unlisted,
1826
3384
  verifyIdentity: opts.verifyIdentity || Boolean(opts.svid) || hasSpiffeEndpoint(),
1827
3385
  svid: opts.svid
1828
3386
  });
3387
+ const verification = compareVerificationWordsForAgent(configDir, agent.id, agent.verification_words);
1829
3388
  if (gOpts.json) printJson({
1830
3389
  org_id: regResult.org_id,
1831
3390
  client_id: regResult.client_id,
1832
3391
  agent,
3392
+ verification,
1833
3393
  poll_url: agent.poll_url,
1834
3394
  identity: agent.identity,
1835
3395
  identity_error: agent.identityError,
@@ -1838,10 +3398,10 @@ function registerOnboard(program) {
1838
3398
  else {
1839
3399
  printTable([toAgentRow(agent, {
1840
3400
  includeCard: true,
1841
- includeVerificationWords: true
3401
+ verification
1842
3402
  })]);
1843
3403
  console.log(`\nAgent '${agent.name}' created — reachable at ${agent.handle}`);
1844
- if (agent.verification_words) console.log(`Verification words: ${agent.verification_words}`);
3404
+ for (const line of verificationWordsLines(verification)) console.log(line);
1845
3405
  if (agent.poll_url) console.log(`Poll URL: ${agent.poll_url}`);
1846
3406
  if (agent.identity) console.log(`SPIFFE identity verified: ${agent.identity.spiffe_id} (trust tier ${agent.identity.trust_tier})`);
1847
3407
  }
@@ -1888,7 +3448,8 @@ function registerOrg(program) {
1888
3448
  //#endregion
1889
3449
  //#region src/commands/pay.ts
1890
3450
  function registerPay(program) {
1891
- program.command("pay").description("Pay an in-thread x402 payment_required (sign + reply with x402_payment)").argument("<message-id>", "ID of the received rine.v1.x402_payment_required").option("--agent <id>", "Payer agent ID (defaults to your agent)").option("--auto-pay", "Only pay when the quote is at/below the wallet autoPayThreshold").option("--force", "Re-pay a quote already paid today (bypasses the once-per-message guard)").option("--no-marker", "Omit the cleartext status marker (fully sealed)").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, messageId, opts) => {
3451
+ program.command("pay").description("Pay an in-thread x402 payment_required (sign + reply with x402_payment)").argument("<message-id>", "ID of the received rine.v1.x402_payment_required").addOption(actorOption("which agent is acting, as payer (name, handle, or agent ID)")).option("--auto-pay", "Only pay when the quote is at/below the wallet autoPayThreshold").option("--force", "Re-pay a quote already paid today (bypasses the once-per-message guard)").option("--no-marker", "Omit the cleartext status marker (fully sealed)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, messageId, opts) => {
3452
+ const payerAgentId = await actingAgent();
1892
3453
  const message = await client.get(`/messages/${messageId}`);
1893
3454
  if (message.type !== X402_MESSAGE_TYPE.PAYMENT_REQUIRED) {
1894
3455
  printError(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT_REQUIRED}. Nothing to pay.`);
@@ -1901,12 +3462,16 @@ function registerPay(program) {
1901
3462
  process.exitCode = 1;
1902
3463
  return;
1903
3464
  }
1904
- const payerAgentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
1905
3465
  if (payeeAgentId === payerAgentId) {
1906
3466
  printError("Cannot pay your own quote.");
1907
3467
  process.exitCode = 1;
1908
3468
  return;
1909
3469
  }
3470
+ if (message.to_agent_id && message.to_agent_id !== payerAgentId) {
3471
+ printError(`Quote ${messageId} is addressed to agent ${message.to_agent_id}, not ${payerAgentId}. Pay as that agent (--agent), or ask the payee to re-issue the quote to this one.`);
3472
+ process.exitCode = 1;
3473
+ return;
3474
+ }
1910
3475
  if (!agentKeysExist(configDir, payerAgentId)) {
1911
3476
  printError(`No E2EE keys for agent ${payerAgentId}. Run 'rine keys generate' first.`);
1912
3477
  process.exitCode = 1;
@@ -1917,8 +3482,16 @@ function registerPay(program) {
1917
3482
  process.exitCode = 1;
1918
3483
  return;
1919
3484
  }
1920
- const decrypted = await decryptMessage(configDir, payerAgentId, message.encrypted_payload, client);
1921
- const pr = parseX402Payload(message.type, decrypted.plaintext);
3485
+ const decrypted = await decryptMessage(configDir, payerAgentId, message.encrypted_payload, client, payeeAgentId);
3486
+ let pr;
3487
+ try {
3488
+ pr = parseX402Payload(message.type, requireAuthenticPlaintext(decrypted, payeeAgentId, messageId));
3489
+ } catch (err) {
3490
+ if (!(err instanceof X402Error)) throw err;
3491
+ printError(`Payment refused: ${err.message}`);
3492
+ process.exitCode = 1;
3493
+ return;
3494
+ }
1922
3495
  const policy = loadPolicy(configDir, payerAgentId);
1923
3496
  const dailySpent = readDailySpent(configDir, payerAgentId);
1924
3497
  try {
@@ -1930,7 +3503,8 @@ function registerPay(program) {
1930
3503
  return;
1931
3504
  }
1932
3505
  }
1933
- const built = buildPaymentMessage(buildPaymentPayload(pr, requirement, loadWalletKey(configDir, payerAgentId), { quoteMessageId: messageId }), { emitMarker: opts.marker !== false });
3506
+ const walletKey = loadWalletKey(configDir, payerAgentId);
3507
+ const built = buildPaymentMessage(buildPaymentPayload(pr, requirement, walletKey, { quoteMessageId: messageId }), { emitMarker: opts.marker !== false });
1934
3508
  const recipientKeys = await fetchRecipientKeys(client, payeeAgentId);
1935
3509
  const encrypted = await encryptMessage(configDir, payerAgentId, recipientKeys.encryption, built.payload, recipientKeys.pqEncryption);
1936
3510
  const body = {
@@ -1944,7 +3518,7 @@ function registerPay(program) {
1944
3518
  messageId,
1945
3519
  force: opts.force
1946
3520
  });
1947
- const sent = await client.post(`/messages/${messageId}/reply`, body, { "X-Rine-Agent": payerAgentId });
3521
+ const sent = await client.post(`/messages/${messageId}/reply`, body, { [ACTING_AGENT_HEADER]: payerAgentId });
1948
3522
  if (gOpts.json) printJson({
1949
3523
  ok: true,
1950
3524
  payment_message_id: sent.id,
@@ -1993,8 +3567,8 @@ function registerPay(program) {
1993
3567
  //#endregion
1994
3568
  //#region src/commands/poll-token.ts
1995
3569
  function registerPollToken(program) {
1996
- program.command("poll-token").description("Generate or revoke a poll token for inbox monitoring").option("--agent <id>", "Agent ID (auto-resolved for single-agent orgs)").option("--revoke", "Revoke the poll token").action(withClient(program, async ({ client, gOpts, profileName, configDir, apiUrl }, opts) => {
1997
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
3570
+ program.command("poll-token").description("Generate or revoke a poll token for inbox monitoring").addOption(actorOption()).option("--revoke", "Revoke the poll token").action(withClient(program, async ({ client, gOpts, profileName, configDir, actingAgent }, opts) => {
3571
+ const agentId = await actingAgent();
1998
3572
  if (opts.revoke) {
1999
3573
  await client.delete(`/agents/${agentId}/poll-token`);
2000
3574
  const creds = loadCredentials(configDir);
@@ -2060,7 +3634,7 @@ function sleep(ms) {
2060
3634
  }
2061
3635
  /**
2062
3636
  * Parse --port into a valid TCP port. `0` is accepted as "OS-assign an ephemeral
2063
- * port" (it is NOT coerced to the default — that was the L3 footgun); a
3637
+ * port" (it is NOT coerced to the default — that coercion was the footgun); a
2064
3638
  * non-integer or out-of-range value throws a clear error rather than silently
2065
3639
  * falling back. The default flag value "8443" parses straight through.
2066
3640
  */
@@ -2076,7 +3650,7 @@ function isRevoked(err) {
2076
3650
  * Resolve the HMAC secret: --secret-env > --secret-file > the persisted file.
2077
3651
  * Returns "" (after a stderr warning naming the three sources tried) when none is
2078
3652
  * found. An empty secret is NOT safe to run with: an attacker who controls the
2079
- * body can compute `HMAC("", body)` and forge a "verified" self-send (T1), so the
3653
+ * body can compute `HMAC("", body)` and forge a "verified" self-send, so the
2080
3654
  * caller (runRelayLoop) HARD-REFUSES to start on an empty result — the relay never
2081
3655
  * enters the reconnect loop or opens the listener without a secret.
2082
3656
  */
@@ -2092,13 +3666,14 @@ function resolveSecret(opts, configDir, agentId) {
2092
3666
  return "";
2093
3667
  }
2094
3668
  function registerRelay(program) {
2095
- program.command("relay").description("Run the inbound webhook funnel relay (long-lived foreground daemon)").option("--agent <id>", "Agent ID (defaults to your agent)").option("--hook <name>", "Hook name to relay", "default").option("--port <n>", "Local TLS listener port", "8443").option("--secret-file <path>", "Read the HMAC secret from a file").option("--secret-env <VAR>", "Read the HMAC secret from an env var").option("--staging", "Use the Let's Encrypt staging CA (dev)").option("--verbose", "Verbose reconnect logging").action(async (opts) => {
3669
+ program.command("relay").description("Run the inbound webhook funnel relay (long-lived foreground daemon)").addOption(actorOption()).option("--hook <name>", "Hook name to relay", "default").option("--port <n>", "Local TLS listener port", "8443").option("--secret-file <path>", "Read the HMAC secret from a file").option("--secret-env <VAR>", "Read the HMAC secret from an env var").option("--staging", "Use the Let's Encrypt staging CA (dev)").option("--verbose", "Verbose reconnect logging").action(async (opts, command) => {
2096
3670
  try {
2097
3671
  const gOpts = program.opts();
2098
3672
  const configDir = resolveConfigDir();
2099
3673
  const apiUrl = resolveApiUrl();
2100
3674
  const { client, profileName, entry } = await createClient(configDir, apiUrl, gOpts.profile);
2101
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
3675
+ const { actingAgent } = actorLadder(namedActor(command, gOpts), client);
3676
+ const agentId = await actingAgent();
2102
3677
  if (!agentKeysExist(configDir, agentId)) {
2103
3678
  printError(`Agent identity keys not found under ${configDir}/keys/${agentId}/ — register first.`);
2104
3679
  process.exitCode = 2;
@@ -2363,9 +3938,9 @@ var UnsupportedTierError = class extends Error {
2363
3938
  }
2364
3939
  };
2365
3940
  /**
2366
- * (AUD-A1) Assert the zero-trust hostname resolves to an A record before
3941
+ * Assert the zero-trust hostname resolves to an A record before
2367
3942
  * declaring the listener ready. The per-agent `*.{agentLabel}.hook` A is a
2368
- * DELIVERY prerequisite written best-effort by the backend (REQ-OPS-04); a
3943
+ * DELIVERY prerequisite written best-effort by the backend; a
2369
3944
  * healthy cert does NOT imply a routable name (DNS-01 validates the independent
2370
3945
  * challenge TXT). Non-fatal — emit a loud `dns_a_missing` event and continue (the
2371
3946
  * cert is valid and the backend self-heals the A on the next ZT-hook create), so
@@ -2437,7 +4012,23 @@ function emitLifecycle(gOpts, monitor, data) {
2437
4012
  function jitteredDelayMs(backoffSeconds) {
2438
4013
  return Math.round(backoffSeconds * (.5 + Math.random()) * 1e3);
2439
4014
  }
2440
- async function formatMessageLine(dataStr, agentId, configDir, client) {
4015
+ /**
4016
+ * Encryption versions the stream preview can decrypt. A payload carrying one of
4017
+ * these that still fails is reported as "[decrypt failed]" rather than the
4018
+ * misleading "[encrypted]", which is reserved for versions we never attempt.
4019
+ *
4020
+ * One failure says more than that: a group message whose sender key never
4021
+ * arrived reports {@link SENDER_KEY_UNAVAILABLE_PREVIEW}, which names the cause
4022
+ * and the move. Every other failure keeps the generic line, because nothing
4023
+ * here knows enough about it to say anything truer.
4024
+ */
4025
+ const DECRYPTABLE_VERSIONS = new Set([
4026
+ "hpke-v1",
4027
+ "hpke-hybrid-v1",
4028
+ "sender-key-v1",
4029
+ "mls-v1"
4030
+ ]);
4031
+ async function formatMessageLine(dataStr, agentId, configDir, client, explain) {
2441
4032
  try {
2442
4033
  const data = JSON.parse(dataStr);
2443
4034
  const ts = (data.created_at ?? "").slice(0, 19) || "?";
@@ -2445,39 +4036,48 @@ async function formatMessageLine(dataStr, agentId, configDir, client) {
2445
4036
  const msgType = data.type ?? "?";
2446
4037
  const target = data.group_handle ? `${data.group_handle} (${msgType})` : msgType;
2447
4038
  let preview = "[encrypted]";
2448
- if (data.encrypted_payload && agentKeysExist(configDir, agentId)) {
4039
+ let notice = null;
4040
+ const fromAgentId = data.from_agent_id;
4041
+ if (data.encrypted_payload && fromAgentId && agentKeysExist(configDir, agentId)) {
2449
4042
  let result;
2450
- if (data.encryption_version === "sender-key-v1" && data.group_id) try {
2451
- result = await decryptGroupMessage(configDir, agentId, data.group_id, data.encrypted_payload, client);
4043
+ let unavailable = null;
4044
+ if ((data.encryption_version === "sender-key-v1" || data.encryption_version === "mls-v1") && data.group_id) try {
4045
+ result = await decryptGroupMessageWithRecovery(client, configDir, agentId, data.group_id, data.encrypted_payload, fromAgentId);
2452
4046
  } catch (err) {
2453
- const match = err instanceof Error && err.message.match(/^unknown sender key id: (.+)$/);
2454
- if (match) {
2455
- if (await fetchAndIngestPendingSKDistributions(client, configDir, agentId, match[1]) > 0) try {
2456
- result = await decryptGroupMessage(configDir, agentId, data.group_id, data.encrypted_payload, client);
2457
- } catch {}
2458
- }
4047
+ unavailable = asSenderKeyUnavailable(err, data.group_id);
2459
4048
  }
2460
- else if (data.encryption_version === "hpke-v1") try {
2461
- result = await decryptMessage(configDir, agentId, data.encrypted_payload, client);
4049
+ else if (data.encryption_version === "hpke-v1" || data.encryption_version === "hpke-hybrid-v1") try {
4050
+ result = await decryptMessage(configDir, agentId, data.encrypted_payload, client, fromAgentId);
2462
4051
  } catch {}
2463
- if (result) {
4052
+ if (result && isAuthenticityFailure(result.verificationStatus)) preview = result.verificationStatus === "sender-mismatch" ? "[✗ sender mismatch]" : "[✗ invalid signature]";
4053
+ else if (result?.plaintext !== void 0) {
2464
4054
  ingestSenderKeyDistribution(configDir, agentId, data.type ?? "", result);
2465
4055
  preview = `[${result.verified ? "✓" : "?"}] ${result.plaintext.slice(0, 60)}`;
2466
- } else if (data.encryption_version === "hpke-v1" || data.encryption_version === "sender-key-v1") preview = "[decrypt failed]";
4056
+ } else if (unavailable !== null) {
4057
+ preview = data.id ? `${SENDER_KEY_UNAVAILABLE_PREVIEW} rine message read ${data.id}` : SENDER_KEY_UNAVAILABLE_PREVIEW;
4058
+ notice = explain(unavailable.message).notice;
4059
+ } else if (DECRYPTABLE_VERSIONS.has(data.encryption_version ?? "")) preview = "[decrypt failed]";
2467
4060
  }
2468
- return `[${ts}] ${sender} \u2192 ${target}: ${preview}`;
4061
+ return {
4062
+ line: `[${ts}] ${sender} \u2192 ${target}: ${preview}`,
4063
+ notice
4064
+ };
2469
4065
  } catch {
2470
- return `[message] ${dataStr.slice(0, 80)}`;
4066
+ return {
4067
+ line: `[message] ${dataStr.slice(0, 80)}`,
4068
+ notice: null
4069
+ };
2471
4070
  }
2472
4071
  }
2473
4072
  function registerStream(program) {
2474
- program.command("stream").description("Stream incoming messages via SSE").option("--agent <id>", "Agent ID to stream (defaults to your agent)").option("--verbose", "Show heartbeats and reconnect details").option("--persistent", "Disable server-side connection timeout").option("--heartbeat-timeout <seconds>", "Seconds of silence before reconnecting (default: 70)", "70").option("--monitor", "Suppress non-message stdout (for CC plugin monitors)").action(async (opts) => {
4073
+ program.command("stream").description("Stream incoming messages via SSE").addOption(actorOption("which agent is acting, and whose messages stream (name, handle, or agent ID)")).option("--verbose", "Show heartbeats and reconnect details").option("--persistent", "Disable server-side connection timeout").option("--heartbeat-timeout <seconds>", "Seconds of silence before reconnecting (default: 70)", "70").option("--monitor", "Suppress non-message stdout (for CC plugin monitors)").action(async (opts, command) => {
2475
4074
  try {
2476
4075
  const gOpts = program.opts();
2477
4076
  const configDir = resolveConfigDir();
2478
4077
  const apiUrl = resolveApiUrl();
2479
4078
  const { client, profileName, entry } = await createClient(configDir, apiUrl, gOpts.profile);
2480
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
4079
+ const { actingAgent } = actorLadder(namedActor(command, gOpts), client);
4080
+ const agentId = await actingAgent();
2481
4081
  let url = `${apiUrl}/agents/${agentId}/stream`;
2482
4082
  if (opts.persistent) url += "?persistent=true";
2483
4083
  const heartbeatTimeoutMs = Math.max(Number(opts.heartbeatTimeout) || 70, 10) * 1e3;
@@ -2486,6 +4086,7 @@ function registerStream(program) {
2486
4086
  let attempt = 0;
2487
4087
  let stopped = false;
2488
4088
  const refreshMargin = jitteredRefreshMargin();
4089
+ const explain = senderKeyExplainer();
2489
4090
  process.on("SIGINT", () => {
2490
4091
  stopped = true;
2491
4092
  process.exitCode = 0;
@@ -2538,7 +4139,10 @@ function registerStream(program) {
2538
4139
  id,
2539
4140
  data
2540
4141
  }));
2541
- } else if (event === "message") formatMessageLine(data, agentId, configDir, client).then((line) => console.log(line), () => console.log(`[message] ${data.slice(0, 80)}`));
4142
+ } else if (event === "message") formatMessageLine(data, agentId, configDir, client, explain).then(({ line, notice }) => {
4143
+ if (notice !== null) printError(notice);
4144
+ console.log(line);
4145
+ }, () => console.log(`[message] ${data.slice(0, 80)}`));
2542
4146
  else if (event === "heartbeat" && opts.verbose) process.stderr.write(`[heartbeat] ${data}\n`);
2543
4147
  },
2544
4148
  onDisconnect: () => {
@@ -2639,9 +4243,8 @@ function printResult(result) {
2639
4243
  console.log(` Verified at: ${result.verified_at}`);
2640
4244
  }
2641
4245
  function registerVerifyIdentity(program) {
2642
- program.command("verify-identity").description("Prove control of a SPIFFE identity for an agent (elevates the org to trust tier 2)").option("--agent <id>", "Agent UUID, handle, or name (defaults to the only agent)").option("--svid <jwt>", "A SPIFFE JWT-SVID. Required unless a Workload API auto-fetch is available.").action(withClient(program, async (ctx, opts) => {
2643
- const agents = await fetchAgents(ctx.client);
2644
- const agentId = await resolveAgent(ctx.apiUrl, agents, opts.agent, ctx.gOpts.as);
4246
+ program.command("verify-identity").description("Prove control of a SPIFFE identity for an agent (elevates the org to trust tier 2)").addOption(actorOption()).option("--svid <jwt>", "A SPIFFE JWT-SVID. Required unless a Workload API auto-fetch is available.").action(withClient(program, async (ctx, opts) => {
4247
+ const agentId = await ctx.actingAgent();
2645
4248
  const result = await verifyIdentitySpiffe(ctx.client, agentId, { svid: opts.svid });
2646
4249
  if (ctx.gOpts.json) printJson(result);
2647
4250
  else printResult(result);
@@ -2654,8 +4257,8 @@ function csv(raw) {
2654
4257
  }
2655
4258
  function registerWallet(program) {
2656
4259
  const wallet = program.command("wallet").description("Manage the agent payment wallet and spend policy (x402)");
2657
- wallet.command("create").description("Create a payment wallet for an agent (refuses to overwrite)").option("--agent <id>", "Agent ID (defaults to your agent)").action(withClient(program, async ({ client, gOpts, apiUrl, configDir }, opts) => {
2658
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
4260
+ wallet.command("create").description("Create a payment wallet for an agent (refuses to overwrite)").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
4261
+ const agentId = await actingAgent();
2659
4262
  if (walletKeyExists(configDir, agentId)) {
2660
4263
  printError(`Wallet already exists for agent ${agentId}. The private key is never overwritten.`);
2661
4264
  process.exitCode = 1;
@@ -2674,8 +4277,8 @@ function registerWallet(program) {
2674
4277
  Value: address
2675
4278
  }]);
2676
4279
  }));
2677
- wallet.command("address").description("Print an agent's payment wallet address").option("--agent <id>", "Agent ID (defaults to your agent)").action(withClient(program, async ({ client, gOpts, apiUrl, configDir }, opts) => {
2678
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
4280
+ wallet.command("address").description("Print an agent's payment wallet address").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
4281
+ const agentId = await actingAgent();
2679
4282
  if (!walletKeyExists(configDir, agentId)) {
2680
4283
  printError(`No wallet for agent ${agentId}. Run 'rine wallet create' first.`);
2681
4284
  process.exitCode = 1;
@@ -2688,8 +4291,8 @@ function registerWallet(program) {
2688
4291
  });
2689
4292
  else printTable([{ "Wallet address": address }]);
2690
4293
  }));
2691
- wallet.command("policy").description("Show the effective spend policy (deny-by-default when unset)").option("--agent <id>", "Agent ID (defaults to your agent)").action(withClient(program, async ({ client, gOpts, apiUrl, configDir }, opts) => {
2692
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
4294
+ wallet.command("policy").description("Show the effective spend policy (deny-by-default when unset)").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
4295
+ const agentId = await actingAgent();
2693
4296
  const p = loadPolicy(configDir, agentId);
2694
4297
  if (gOpts.json) {
2695
4298
  printJson({
@@ -2735,8 +4338,8 @@ function registerWallet(program) {
2735
4338
  Value: p.allowedNetworks.join(", ") || "—"
2736
4339
  }
2737
4340
  ]);
2738
- })).command("set").description("Set the spend policy (all caps are decimal major-unit strings)").option("--agent <id>", "Agent ID (defaults to your agent)").requiredOption("--per-tx-cap <amount>", "Max per-transaction spend, e.g. 5.00").requiredOption("--daily-cap <amount>", "Max total spend per UTC day, e.g. 50.00").requiredOption("--allowed-assets <list>", "Comma-separated assets (symbols e.g. EURC or 0x contract addresses)").requiredOption("--allowed-networks <list>", "Comma-separated CAIP-2 networks, e.g. eip155:8453").option("--auto-pay-threshold <amount>", "Auto-pay ceiling for 'rine pay --auto-pay' (default 0 = never auto-pay)", "0").action(withClient(program, async ({ client, gOpts, apiUrl, configDir }, opts) => {
2739
- savePolicy(configDir, await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as), {
4341
+ })).command("set").description("Set the spend policy (all caps are decimal major-unit strings)").addOption(actorOption()).requiredOption("--per-tx-cap <amount>", "Max per-transaction spend, e.g. 5.00").requiredOption("--daily-cap <amount>", "Max total spend per UTC day, e.g. 50.00").requiredOption("--allowed-assets <list>", "Comma-separated assets (symbols e.g. EURC or 0x contract addresses)").requiredOption("--allowed-networks <list>", "Comma-separated CAIP-2 networks, e.g. eip155:8453").option("--auto-pay-threshold <amount>", "Auto-pay ceiling for 'rine pay --auto-pay' (default 0 = never auto-pay)", "0").action(withClient(program, async ({ gOpts, configDir, actingAgent }, opts) => {
4342
+ savePolicy(configDir, await actingAgent(), {
2740
4343
  perTxCap: opts.perTxCap,
2741
4344
  dailyCap: opts.dailyCap,
2742
4345
  allowedAssets: csv(opts.allowedAssets),
@@ -2750,13 +4353,13 @@ function registerWallet(program) {
2750
4353
  //#region src/commands/webhook.ts
2751
4354
  function registerWebhook(program) {
2752
4355
  const webhook = program.command("webhook").description("Manage webhooks");
2753
- webhook.command("create").description("Create a new webhook").option("--agent <id>", "Agent ID (defaults to your agent)").requiredOption("--url <url>", "Webhook target URL (must be https://)").action(withClient(program, async ({ client, gOpts, apiUrl }, opts) => {
4356
+ webhook.command("create").description("Create a new webhook").addOption(actorOption()).requiredOption("--url <url>", "Webhook target URL (must be https://)").action(withClient(program, async ({ client, gOpts, actingAgent }, opts) => {
2754
4357
  if (!opts.url.startsWith("https://")) {
2755
4358
  printError("Webhook URL must start with https://");
2756
4359
  process.exitCode = 2;
2757
4360
  return;
2758
4361
  }
2759
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
4362
+ const agentId = await actingAgent();
2760
4363
  const data = await client.post("/webhooks", {
2761
4364
  agent_id: agentId,
2762
4365
  url: opts.url
@@ -2819,7 +4422,7 @@ function registerWebhook(program) {
2819
4422
  //#endregion
2820
4423
  //#region src/main.ts
2821
4424
  const { version } = createRequire(import.meta.url)("../package.json");
2822
- const program = new Command("rine").version(version).description("rine.network CLI — messaging infrastructure for AI agents").option("--profile <name>", "credential profile to use", "default").option("--json", "output as JSON").option("--table", "output as table").option("--as <agent>", "act as a specific agent (UUID, handle, or bare name e.g. kofi)");
4425
+ const program = new Command("rine").version(version).description("rine.network CLI — messaging infrastructure for AI agents").option("--profile <name>", "credential profile to use", "default").option("--json", "output as JSON").option("--table", "output as table").option("--as <agent>", "which agent is acting — the retired spelling of --agent (name, handle, or agent ID)");
2823
4426
  registerAuth(program);
2824
4427
  registerRegister(program);
2825
4428
  registerOnboard(program);