@rine-network/cli 0.17.0 → 0.20.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 +1995 -284
  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, cliSyncRemedy, 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, isEpochConflict, isMlsResyncUnavailable, isMlsWelcomeRefusedError, isNoMlsStateError, isRecoverableMlsRead, isX402MessageType, jitteredRefreshMargin, listMyInvites, loadAgentKeys, loadCredentials, loadHookSecret, loadMeta, loadMlsGroup, loadMlsState, loadPolicy, loadSenderKeyStates, loadTokenCache, loadWalletKey, makeEdgePipeFactory, matchedQuoteToWire, mlsAdmissionSkipSentence, mlsErrorCode, mlsInitInFlightSync, mlsReadRefusal, normalizeActor, normalizeHandle, openMlsClient, parseFacilitatorHeaders, parseX402Payload, peerVerificationLines, performAgentCreation, performRegistration, processMlsWelcomes, readDailySpent, readThreadPage, readableGroupById, 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));
@@ -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,269 @@ 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];
1527
+ }
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
+ /**
1593
+ * Why an MLS commit the server refused for its epoch check did not land, and
1594
+ * what puts it right.
1595
+ *
1596
+ * The server states this as `MLS epoch conflict: group at epoch 5, commit
1597
+ * targets 5`, and both numbers are correct: the first is the group's stored
1598
+ * epoch, the second is the epoch the client's commit would have produced. An
1599
+ * equal pair is the honest signature of a commit built one epoch behind — but
1600
+ * it reads as a contradiction, and it arrives behind `RineApiError`'s
1601
+ * `409: ` with no remedy attached. So the fact is stated instead of the
1602
+ * arithmetic. 🔴 Do not "fix" the server's numbers to make them differ.
1603
+ *
1604
+ * `groupRef` is whatever the caller addressed the group by, so the command it
1605
+ * names back is one the operator can paste.
1606
+ */
1607
+ function epochConflictMessage(groupRef) {
1608
+ return `Another member's commit landed first, so this one was built one epoch behind and the server's epoch check refused it. Nothing was committed and the group is exactly where it was. Run \`rine group sync ${groupRef}\` to catch this agent's state up, then run the command again.`;
1609
+ }
1610
+ /**
1611
+ * A failure's message, in rine's words wherever rine has any.
1612
+ *
1613
+ * Two things reach an operator through here that should not, and both are
1614
+ * recognised by a machine-readable CODE rather than by matching words: the MLS
1615
+ * core's own vocabulary for an invariant rine states as a membership fact, and
1616
+ * `RineApiError`'s `${status}: ${detail}` — a bare `409: ` in front of a
1617
+ * sentence about epochs is the one place these commands drop to a status code.
1618
+ * `formatError` is what every other CLI failure path already renders through.
1619
+ */
1620
+ function mlsFailureText(err, groupId) {
1621
+ if (mlsErrorCode(err) === MLS_ERR_GROUP_INACTIVE) return evictedMessage(groupId);
1622
+ if (isEpochConflict(err)) return epochConflictMessage(groupId);
1623
+ return formatError(err);
939
1624
  }
940
- async function selfJoinViaExternalCommit(client, configDir, groupId, agentId, json) {
1625
+ /**
1626
+ * Report a best-effort MLS step that failed without failing the command.
1627
+ *
1628
+ * Every MLS step in the group commands is a second operation *about* the group,
1629
+ * running after the one the operator asked for has already succeeded on the
1630
+ * server. Failing the command would misreport what happened; going quiet would
1631
+ * hide it. So it warns, in rine's vocabulary.
1632
+ *
1633
+ * 🔴 One step does not use this: a Welcome the group substitution guard REFUSED
1634
+ * for the group being joined. See {@link installWelcomes}.
1635
+ */
1636
+ function warnMls(what, err, groupId, json) {
1637
+ if (json) return;
1638
+ printText(`Warning: ${what}: ${mlsFailureText(err, groupId)}`);
1639
+ }
1640
+ /**
1641
+ * Best-effort: fetch & install pending MLS Welcomes for a freshly-added member.
1642
+ *
1643
+ * 🔴 With one exception. A Welcome the group substitution guard REFUSED for
1644
+ * **this** group is raised, so `rine group join` reports it and exits non-zero
1645
+ * instead of printing a warning under a success line. A refusal is a
1646
+ * security verdict about who minted the Welcome, not a setup step that will
1647
+ * come good on the next read, and `rine.groups.join()` on the Python SDK
1648
+ * already raises it — the same failure must not be loud on one stack and a log
1649
+ * line on the other. The rine membership stands either way; what the operator
1650
+ * has to act on is the refusal's own text.
1651
+ *
1652
+ * A refusal naming a DIFFERENT group still warns: the batch installs every
1653
+ * Welcome it can before raising, and one group's verdict is not this join's.
1654
+ *
1655
+ * 🔴 `forGroup` is what makes that split the CLIENT's to make. Without it the
1656
+ * pass raises "the first refusal whose bytes arrived", ordered by the server's
1657
+ * own response array — so a server suppressed this group's refusal by minting
1658
+ * one throwaway decoy for another group, {@link welcomeRefusedForGroup}
1659
+ * answered false, and the join carried on into
1660
+ * {@link selfJoinViaExternalCommit} for the very group whose Welcome this
1661
+ * client had just refused (MEASURED: the verb's outcome flips from warn to
1662
+ * raise on this argument alone).
1663
+ */
1664
+ async function installWelcomes(client, configDir, agentId, groupId, json) {
941
1665
  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 });
1666
+ await processMlsWelcomes(configDir, agentId, client, { forGroup: groupId });
945
1667
  } catch (err) {
946
- if (!json) printText(`Warning: MLS self-join failed: ${err instanceof Error ? err.message : String(err)}`);
1668
+ if (welcomeRefusedForGroup(err, groupId)) throw err;
1669
+ warnMls("MLS welcome install failed", err, groupId, json);
947
1670
  }
948
1671
  }
949
- async function addMemberToMls(client, configDir, apiUrl, groupId, memberAgentId, as, json) {
1672
+ /**
1673
+ * Whether a failure is the Welcome guard refusing a Welcome for this group.
1674
+ *
1675
+ * Classified by rine-core's exported code check, never by matching the message
1676
+ * — that export exists for this. The `groupId` a refusal carries is the rine
1677
+ * group UUID the delivery was filed under, compared case-insensitively because
1678
+ * the two ids arrive from different reads, as the Python twin compares them.
1679
+ */
1680
+ function welcomeRefusedForGroup(err, groupId) {
1681
+ if (!isMlsWelcomeRefusedError(err)) return false;
1682
+ const named = err.groupId;
1683
+ return typeof named === "string" && named.toLowerCase() === groupId.toLowerCase();
1684
+ }
1685
+ /**
1686
+ * Best-effort open-enrollment fallback: when the joiner became a rine member
1687
+ * with no Welcome (the `open` enrollment case — no admin in the loop) and the
1688
+ * group is MLS-active, self-join via an RFC 9420 external commit. No-op if a
1689
+ * Welcome already installed local state, or for sender-key groups.
1690
+ */
1691
+ async function selfJoinViaExternalCommit(client, configDir, groupId, agentId, mlsGroupId, json) {
1692
+ if (!mlsGroupId) return;
1693
+ if (loadMlsState(configDir, agentId, groupId)) return;
950
1694
  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 });
1695
+ await externalJoinMlsGroup(configDir, agentId, groupId, client, { [ACTING_AGENT_HEADER]: agentId });
954
1696
  } catch (err) {
955
- if (!json) printText(`Warning: MLS add-member failed: ${err instanceof Error ? err.message : String(err)}`);
1697
+ warnMls("MLS self-join failed", err, groupId, json);
956
1698
  }
957
1699
  }
958
- async function sendInviteNotification(client, configDir, apiUrl, groupId, inviteeAgentId, message, as, json) {
1700
+ /**
1701
+ * Give every named agent a leaf in the group's ratchet tree, in batches.
1702
+ *
1703
+ * One call whether one agent was named or five hundred: the singular add is the
1704
+ * plural one over a list of one, and both report per member. A
1705
+ * sender-key group has no tree, so it is a no-op rather than a failure.
1706
+ *
1707
+ * Best-effort by contract, like every MLS step on these paths: the invitations
1708
+ * are already minted server-side when this runs, and a Welcome that could not be
1709
+ * delivered is recoverable by `group resume-admission`. Returns null when the
1710
+ * group has no tree or the admission could not run at all.
1711
+ */
1712
+ async function admitToMls(client, configDir, adminId, groupId, mlsGroupId, memberAgentIds, json) {
1713
+ if (!mlsGroupId || memberAgentIds.length === 0) return null;
959
1714
  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
- });
1715
+ return await addMlsGroupMembers(configDir, adminId, groupId, memberAgentIds, client, { [ACTING_AGENT_HEADER]: adminId });
966
1716
  } catch (err) {
967
- if (!json) printText(`Warning: invite notification failed: ${err instanceof Error ? err.message : String(err)}`);
1717
+ warnMls("MLS add-member failed", err, groupId, json);
1718
+ return null;
968
1719
  }
969
1720
  }
1721
+ //#endregion
1722
+ //#region src/commands/group-rows.ts
1723
+ /**
1724
+ * How this surface spells the verb that founds a group's MLS state.
1725
+ *
1726
+ * The CLI is one of the few surfaces that can act on the answer: `rine group
1727
+ * resume-admission` branches to the init on an unlatched group, so every
1728
+ * sentence the CLI prints about a group whose ratchet tree was never founded
1729
+ * names it. One constant rather than the literal at each of the seven call
1730
+ * sites — the spelling is the load-bearing token, and a verb that only half the
1731
+ * CLI's outputs name is worse than one none of them do.
1732
+ */
1733
+ const CLI_UNFOUNDED_REPAIR = "cli-resume-admission";
1734
+ /**
1735
+ * What `rine group get` prints when no agent of this org holds a seat.
1736
+ *
1737
+ * `member_agent_ids` answers the question `Members` never did — which of YOUR
1738
+ * agents is in this group — and an empty list is a fact rather than a gap: none
1739
+ * of them is, so a send here would be refused and the remedy is an invitation,
1740
+ * not a different `--agent`. An empty cell would say the server forgot to
1741
+ * report it, which is the one reading that is false, and `printTable` renders
1742
+ * an empty array as exactly that empty cell.
1743
+ *
1744
+ * Restated per package for the same reason {@link NO_CONVERSATION} is: seven
1745
+ * surfaces print this sentence and no runtime module reaches all seven. The
1746
+ * three Python surfaces have `rine-sdk` and import
1747
+ * `rine.group_words.NO_OWN_AGENTS` rather than restating it; nothing bridges
1748
+ * Python and TypeScript, so that half of the split is permanent.
1749
+ *
1750
+ * The three TypeScript copies are NOT permanent, and an earlier version of this
1751
+ * comment said they were: `rine-eve` and `rine-mastra` declare
1752
+ * `@rine-network/core` as a direct dependency alongside the SDK and already
1753
+ * import from it at runtime, so `rine-core` does reach all three TS renderers
1754
+ * and could hold this sentence and `renderOwnAgents` once. Consolidating them
1755
+ * re-runs three `--external` gates and the `rine-core` → `rine-ts-sdk` →
1756
+ * CLI/MCP rebuild chain, which is a scheduled refactor of its own.
1757
+ *
1758
+ * The name is that constant's name on purpose. Four packages declare this one
1759
+ * sentence and `tests/test_client-server-contract_group0.py` compares them, so
1760
+ * a reword that lands in one of them fails there rather than shipping two
1761
+ * answers to one question.
1762
+ */
1763
+ const NO_OWN_AGENTS = "(none — no agent of your org is seated in this group)";
1764
+ /**
1765
+ * The agents of this org that are seated in the group, as one cell.
1766
+ *
1767
+ * Each id is printed as its **handle** where this org has one, and as the id
1768
+ * where it does not — the three cases and the reasons for them are stated once,
1769
+ * on `AgentHandles` in `./own-agents.js`, and this renderer is one of the four
1770
+ * that follow them. `handles` is empty whenever the agent list could not be
1771
+ * read, which is exactly case 2 for every id: the cell degrades to the UUIDs it
1772
+ * printed before handles were rendered rather than degrading the group read.
1773
+ *
1774
+ * A server that predates the field reports nothing rather than an empty list,
1775
+ * and that is a different fact from "none of your agents is seated" — but it is
1776
+ * only reachable inside the release-order window (the server ships before the
1777
+ * clients), so it collapses into the same sentence rather than earning a third
1778
+ * one. What it must not do is throw, which is what reading `.length` off the
1779
+ * missing key would do to every `rine group get` against an older deployment.
1780
+ */
1781
+ function ownAgentsCell(g, handles) {
1782
+ const seated = g.member_agent_ids ?? [];
1783
+ if (seated.length === 0) return NO_OWN_AGENTS;
1784
+ return seated.map((id) => handles?.get(id.toLowerCase()) ?? id).join(", ");
1785
+ }
970
1786
  function groupRow(g) {
971
1787
  return {
972
1788
  ID: g.id,
@@ -975,10 +1791,21 @@ function groupRow(g) {
975
1791
  Enrollment: g.enrollment_policy,
976
1792
  Visibility: g.visibility,
977
1793
  Members: g.member_count,
1794
+ "Conversation ID": g.conversation_id ?? "(none — nothing has been said in this group yet)",
978
1795
  Created: g.created_at
979
1796
  };
980
1797
  }
981
- function groupDetailRow(g) {
1798
+ /**
1799
+ * The one-group table `rine group get` and `rine group create` both print.
1800
+ *
1801
+ * It takes a {@link RenderableGroup} rather than a row because `create` renders
1802
+ * a group it has just founded the ratchet tree of, and the row it holds can
1803
+ * predate that founding — the `Encryption` and `Post-Quantum` cells are read
1804
+ * from the create result there, exactly as the line under the table is. Every
1805
+ * other caller passes a plain row, which satisfies the type unchanged.
1806
+ */
1807
+ function groupDetailRow(g, handles) {
1808
+ const encryption = groupEncryption(g);
982
1809
  return {
983
1810
  ID: g.id,
984
1811
  Name: g.name,
@@ -989,72 +1816,376 @@ function groupDetailRow(g) {
989
1816
  Isolated: g.isolated,
990
1817
  "Vote Duration": g.vote_duration_hours,
991
1818
  Members: g.member_count,
1819
+ "Your Agents": ownAgentsCell(g, handles),
1820
+ "Conversation ID": g.conversation_id ?? "(none — nothing has been said in this group yet)",
1821
+ Encryption: encryption.version,
1822
+ "Post-Quantum": encryption.post_quantum,
992
1823
  Created: g.created_at
993
1824
  };
994
1825
  }
1826
+ /**
1827
+ * One roster row, and whether it is one of yours.
1828
+ *
1829
+ * `Yours` is a MARKER and never a filter: every member of the group is listed,
1830
+ * including the rows where it is false, because those are exactly the agents a
1831
+ * group send reaches. Hiding them would answer a question nobody asked and
1832
+ * would make `Members` disagree with the table under it.
1833
+ *
1834
+ * An em dash is a server that does not report the field at all, on the same
1835
+ * distinction {@link barCell} draws: "not yours" and "this build cannot tell
1836
+ * you" are different facts, and printing `false` for the second would state
1837
+ * something about another org's seat that nothing here knows.
1838
+ */
995
1839
  function memberRow(m) {
996
1840
  return {
997
1841
  "Agent ID": m.agent_id,
998
1842
  Handle: m.agent_handle ?? "",
999
1843
  Role: m.role,
1844
+ Yours: m.is_own_org ?? "—",
1000
1845
  Joined: m.joined_at
1001
1846
  };
1002
1847
  }
1848
+ /**
1849
+ * Whether this reader's own vote would count, in one clause.
1850
+ *
1851
+ * A join request is decided by the members the group had when it was filed, and
1852
+ * only by those of them who are still in it — so a member who joined afterwards
1853
+ * learns that here rather than from a 403. The clause the server's reason maps
1854
+ * to is the same one every other surface prints for that reason, and the reason
1855
+ * predicts the refusal one-to-one: `not_in_electorate`, `electorate_empty`,
1856
+ * `bar_unreachable` and `is_applicant` are 403s, `already_voted` a 409,
1857
+ * `not_pending` a 422.
1858
+ *
1859
+ * `bar_unreachable` and `electorate_empty` are two different facts and are told
1860
+ * apart on purpose: the first is a request no recorded electorate can decide,
1861
+ * the second one whose recorded electorate has entirely left. `is_applicant` is
1862
+ * what a reader sees on its own request — including a nominee reading the
1863
+ * request a member filed on its behalf.
1864
+ *
1865
+ * A server that predates the electorate sends no reason at all, and the one its
1866
+ * behaviour implies is read off `status` — the same derivation the ts-SDK's
1867
+ * schema and the Python `vote_eligibility_reason` make. Not a flat
1868
+ * `electorate_not_recorded`: that is right for a pending request and wrong for
1869
+ * an **invitation**, which nobody votes on and which `POST …/vote` answers 422
1870
+ * for, so the row would have told the operator "you can vote" about the one
1871
+ * population that cannot. A reason this build predates renders as itself rather
1872
+ * than as a guess about whether the vote would count.
1873
+ */
1874
+ function voteEligibilityClause(r) {
1875
+ const reason = r.you_may_vote_reason ?? (r.status === "pending" ? "electorate_not_recorded" : "not_pending");
1876
+ switch (reason) {
1877
+ case "in_electorate": return "you can vote";
1878
+ case "electorate_not_recorded": return "you can vote (filed before the electorate was recorded; any member may)";
1879
+ case "not_in_electorate": return "you cannot vote: you were not in the group when this was filed";
1880
+ case "already_voted": return `you already voted ${r.your_vote ?? ""}`.trimEnd();
1881
+ case "electorate_empty": return "nobody eligible is still in the group";
1882
+ case "bar_unreachable": return "nobody can decide this request";
1883
+ case "is_applicant": return "this is your own request";
1884
+ case "not_pending": return "not open for voting";
1885
+ default: return reason;
1886
+ }
1887
+ }
1888
+ /**
1889
+ * How one bar of a vote stands, in one cell: votes cast, of the votes that bar
1890
+ * takes.
1891
+ *
1892
+ * 🔴 The wire carries a SHORTFALL — `approvals_needed` and `denials_needed` are
1893
+ * both "how many MORE it takes" — and this cell prints a THRESHOLD, which is the
1894
+ * shortfall added back onto what has been cast. The two are the same number only
1895
+ * while nothing has been cast, which is why `0 of 2` was right and `1 of 1` was
1896
+ * not: a bar rendered as cast-of-shortfall reads as met on every row somebody
1897
+ * has already voted on. The arithmetic is the server's and is correct; the
1898
+ * addition here is a rendering of it, not a second opinion about it.
1899
+ *
1900
+ * Both bars come from the same electorate, so each falls as members leave in
1901
+ * exactly the way the other does — a standing denial can refuse a request nobody
1902
+ * has voted on since, and a departure can carry one nobody has approved since.
1903
+ * That is also the one state where the threshold this prints sits UNDER what the
1904
+ * required count was when the vote opened, and printing it is the honest answer:
1905
+ * the bar as it stands now is the bar the next vote is measured against.
1906
+ *
1907
+ * A number the server did not report is an em dash and never a zero: "no more
1908
+ * votes are needed" and "this server does not report this bar" are different
1909
+ * facts, and printing `0` for the second would tell an operator the request is
1910
+ * one vote from resolving. A threshold cannot be known from half the pair, so an
1911
+ * unreported shortfall takes the dash on the right of the `of`, and an
1912
+ * unreported cast count takes it on both.
1913
+ *
1914
+ * 🔴 A shortfall of **zero** is the one case the addition cannot resolve, and it
1915
+ * is reachable: the server clamps at zero (`max(required - cast, 0)`,
1916
+ * `src/rine/api/group_vote_math.py`), so a request whose electorate shrank below
1917
+ * what it already holds reports `needed = 0` while still pending — nothing votes
1918
+ * again, so nothing resolves it. Adding gives `cast`, and printing that would
1919
+ * state a bar of 3 on a request whose bar is 2: the one number an operator
1920
+ * quotes, wrong, with the meaning ("met") still right. What the shortfall proves
1921
+ * is an upper bound and not a value, so the cell says exactly that much.
1922
+ */
1923
+ function barCell(cast, needed) {
1924
+ if (cast === null && needed === null) return "—";
1925
+ if (cast !== null && needed === 0) return `${cast} of ${cast} or fewer`;
1926
+ const required = cast === null || needed === null ? null : cast + needed;
1927
+ return `${cast ?? "—"} of ${required ?? "—"}`;
1928
+ }
1929
+ /**
1930
+ * One row per request, carrying the arithmetic a member needs before spending a
1931
+ * call: approvals that count, how many more each bar wants, and how many
1932
+ * eligible voters are still in the group.
1933
+ *
1934
+ * 🔴 `Approved` and `Denials` are ONE convention, read together: each is
1935
+ * {@link barCell}'s cast-of-threshold. They were two, and side by side the pair
1936
+ * `Approved 1 | Needed 1` read as "one of one, carried" on a request that was
1937
+ * still open — the approval bar printed its shortfall in a column of its own
1938
+ * while the denial bar printed a cell. Neither number was wrong; the two
1939
+ * spellings of the same fact were. `Needed` stays beside `Approved` as the
1940
+ * shortfall it always was — how many more calls resolve this — and now says the
1941
+ * same thing as the cell to its left rather than a different-looking one.
1942
+ *
1943
+ * The counts are null on an invitation, which nobody votes on, so `Approved`,
1944
+ * `Needed` and `Eligible` render blank there. `Denials` says `—` instead, on the
1945
+ * distinction {@link barCell} draws: it is the one cell whose emptiness could
1946
+ * otherwise be read as a zero.
1947
+ *
1948
+ * `Needed` is an em dash when no bar is reachable — everyone eligible has left,
1949
+ * and the request stands until it expires — and `Approved` is then `N of —` for
1950
+ * the same reason: what has been cast is known, what it would take is not.
1951
+ * `Denials` reports the other direction as one cell rather than a second
1952
+ * `Denied`/`Deny Needed` pair, because eleven columns is what a terminal shows
1953
+ * and twelve is not.
1954
+ *
1955
+ * A request a member filed on somebody else's behalf is born carrying that
1956
+ * member's own approval, so `Approved: 1 of 2` on an untouched row is ordinary
1957
+ * here and not a double count.
1958
+ */
1003
1959
  function requestRow(r) {
1960
+ const approvals = r.approvals ?? null;
1004
1961
  return {
1005
1962
  "Request ID": r.id,
1006
1963
  "Agent ID": r.agent_id,
1007
1964
  Message: r.message ?? "",
1965
+ Approved: approvals === null ? "" : barCell(approvals, r.approvals_needed ?? null),
1966
+ Needed: approvals === null ? "" : r.approvals_needed ?? "—",
1967
+ Denials: barCell(r.denials ?? null, r.denials_needed ?? null),
1968
+ Eligible: r.electorate_size ?? "",
1008
1969
  "Your Vote": r.your_vote ?? "",
1970
+ "Can Vote": voteEligibilityClause(r),
1009
1971
  Expires: r.expires_at ?? "",
1010
1972
  Created: r.created_at
1011
1973
  };
1012
1974
  }
1975
+ /**
1976
+ * The invitee's perspective: who reached you, about which group, and with what
1977
+ * kind of row. Distinct from requestRow, whose `Your Vote`/`Agent ID` columns
1978
+ * are voter-scoped.
1979
+ *
1980
+ * `Status` is the column that tells an invitation from a nomination.
1981
+ * `GET /groups/invites` answers both, and it is the only route an agent that is
1982
+ * not yet a member can read its own nomination on — so without this column the
1983
+ * one row a nominee can see would read as an invitation to accept, which is
1984
+ * false: a nomination seats nobody until the electorate decides. `invited` is a
1985
+ * voucher this join spends; `pending` is a nomination the group's electorate
1986
+ * has still to decide, and joining it records consent rather than enrolling.
1987
+ */
1013
1988
  function inviteRow(r) {
1014
1989
  return {
1015
1990
  Group: r.group_handle ?? r.group_name ?? "",
1016
1991
  "Group ID": r.group_id,
1017
1992
  "Invited By": r.invited_by ?? "",
1993
+ Status: r.status,
1018
1994
  Message: r.message ?? "",
1019
1995
  Created: r.created_at
1020
1996
  };
1021
1997
  }
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"})`);
1998
+ /**
1999
+ * One requested agent id and what the server did about it.
2000
+ *
2001
+ * The reason column carries the sentence, not the wire token: `not_applicable`
2002
+ * printed as-is read as a refusal on exactly the groups it is not one for — an
2003
+ * open group mints no invitation because it needs none, and those agents may
2004
+ * walk in. The map lives in `rine-core` so every surface says it the same way.
2005
+ * An `invited` or `nominated` entry carries no reason and gets no
2006
+ * sentence — the status is the whole answer, and the two are separate values
2007
+ * precisely so this column never offers an invitation to accept where the
2008
+ * electorate has yet to decide.
2009
+ */
2010
+ function admissionRow(e) {
2011
+ return {
2012
+ "Agent ID": e.agent_id,
2013
+ Status: e.status,
2014
+ Reason: e.status === "skipped" ? groupAdmissionSkipSentence(e.reason) : ""
2015
+ };
2016
+ }
2017
+ /** One requested agent id and whether the ratchet tree took them. */
2018
+ function admissionOutcomeRows(result) {
2019
+ return result.outcomes.map((o) => ({
2020
+ "Agent ID": o.agentId,
2021
+ Seated: o.status === "added" ? "yes" : "no",
2022
+ Reason: o.status === "skipped" ? mlsAdmissionSkipSentence(o.reason) : ""
2023
+ }));
2024
+ }
2025
+ //#endregion
2026
+ //#region src/commands/own-agents.ts
2027
+ /**
2028
+ * Index the agent list the actor ladder has already paid for.
2029
+ *
2030
+ * `ctx.agents()` is memoised per command invocation, so a command that also
2031
+ * resolves an acting agent (`group update`, `group create`) spends nothing
2032
+ * extra here; `group get`, which names no actor, spends one `GET /agents` — and
2033
+ * only on a group where a seat would actually be spelled, because the empty
2034
+ * cell reads the same whichever map it is handed. That call is the one cost
2035
+ * accepted in exchange for a cell an operator can read; its callers own
2036
+ * the seat check, since this function is handed the list and not the group.
2037
+ *
2038
+ * Ids are lowercased on both sides of the lookup because a UUID is
2039
+ * case-insensitive and the two lists come from different responses.
2040
+ */
2041
+ async function ownAgentHandles(agents) {
2042
+ try {
2043
+ const list = await agents();
2044
+ return new Map(list.filter((a) => a.handle !== null).map((a) => [a.id.toLowerCase(), a.handle]));
2045
+ } catch {
2046
+ return /* @__PURE__ */ new Map();
2047
+ }
2048
+ }
2049
+ //#endregion
2050
+ //#region src/commands/group-create.ts
2051
+ 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.";
2052
+ /** Read either create response: a bare group, or `{group, roster}` when a roster was named. */
2053
+ function unwrapCreate(data) {
2054
+ const body = data;
2055
+ if (body.group && body.roster) return {
2056
+ group: body.group,
2057
+ roster: body.roster
2058
+ };
2059
+ return {
2060
+ group: body,
2061
+ roster: null
2062
+ };
2063
+ }
2064
+ /**
2065
+ * Found the new group's ratchet tree, seating its roster in size-aware batches.
2066
+ *
2067
+ * Open-enrollment groups are exempt: the server refuses MLS there, so an init
2068
+ * would only ever fail — they run on Sender Keys. Best-effort, and the group
2069
+ * stands either way; `group resume-admission` finishes an init that stopped
2070
+ * part-way.
2071
+ */
2072
+ async function foundMlsState(ctx, group) {
2073
+ if (group.enrollment_policy === "open") return null;
2074
+ try {
2075
+ const actingAgentId = await ctx.actingAgent();
2076
+ return await initMlsGroup(ctx.configDir, actingAgentId, group.id, ctx.client, { [ACTING_AGENT_HEADER]: actingAgentId });
2077
+ } catch (err) {
2078
+ warnMls("MLS init failed (group still created)", err, group.id, ctx.gOpts.json);
2079
+ return null;
2080
+ }
2081
+ }
2082
+ /** Re-read the group so the rendered row carries the MLS latch the init just set. */
2083
+ async function refresh(client, group) {
2084
+ try {
2085
+ return await client.get(`/groups/${group.id}`);
2086
+ } catch {
2087
+ return group;
2088
+ }
2089
+ }
2090
+ function printCreated$1(group, roster, admission, json, handles) {
2091
+ const created = admission ? {
2092
+ ...group,
2093
+ mlsAdmission: admission
2094
+ } : group;
2095
+ if (json) {
2096
+ printJson({
2097
+ ...group,
2098
+ encryption: groupEncryption$1(created, CLI_UNFOUNDED_REPAIR),
2099
+ ...roster ? { roster } : {},
2100
+ ...admission ? { admission } : {}
2101
+ });
2102
+ return;
2103
+ }
2104
+ printTable([groupDetailRow(created, handles)]);
2105
+ printText(`\nGroup created — handle: ${group.handle}`);
2106
+ printText(encryptionLine(created, CLI_UNFOUNDED_REPAIR));
2107
+ if (roster) {
2108
+ printText(`\nRoster: ${admissionHeadline(roster)} ${ROSTER_NOTE}`);
2109
+ printTable(roster.entries.map(admissionRow));
2110
+ }
2111
+ if (admission && admission.outcomes.length > 0) {
2112
+ printText(`\nSeated in the ratchet tree: ${admission.added} of ${admission.outcomes.length} in ${admission.commits} commit(s), now at epoch ${admission.epoch}.`);
2113
+ printTable(admissionOutcomeRows(admission));
2114
+ }
2115
+ }
2116
+ function registerGroupCreate(program, group) {
2117
+ 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).addOption(actorOption("which agent is acting, and founds the group")).action(withClient(program, async (ctx, opts) => {
2118
+ const refusal = visibilityRefusal(opts.visibility);
2119
+ if (refusal) {
2120
+ printError(refusal);
2121
+ process.exitCode = 2;
2122
+ return;
1031
2123
  }
2124
+ const body = {
2125
+ name: opts.name,
2126
+ visibility: opts.visibility
2127
+ };
2128
+ if (opts.description !== void 0) body.description = opts.description;
2129
+ if (opts.enrollment) body.enrollment_policy = opts.enrollment;
1032
2130
  if (opts.isolated) body.isolated = true;
1033
2131
  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
- }
2132
+ if (opts.member.length > 0) body.members = dedupeIds(await Promise.all(opts.member.map((m) => {
2133
+ announceHandleCompletion(m);
2134
+ return resolveToUuid(ctx.apiUrl, m);
2135
+ })));
2136
+ const { group: created, roster } = unwrapCreate(await ctx.client.post("/groups", body));
2137
+ const admission = await foundMlsState(ctx, created);
2138
+ const latched = admission ? await refresh(ctx.client, created) : created;
2139
+ const handles = ctx.gOpts.json ? void 0 : await ownAgentHandles(ctx.agents);
2140
+ printCreated$1(latched, roster, admission, ctx.gOpts.json, handles);
1046
2141
  }));
2142
+ }
2143
+ //#endregion
2144
+ //#region src/commands/group-crud.ts
2145
+ /**
2146
+ * Whether a Remove commit has already evicted the acting agent from this group.
2147
+ *
2148
+ * Reading a group is where an evicted agent finds out, so the ratchet tree is
2149
+ * consulted here rather than left to surface as an mls-rs invariant from the
2150
+ * next send. Local and best-effort: the answer lives on disk, and a
2151
+ * group whose state this agent never held simply has no answer.
2152
+ *
2153
+ * This is the half that runs when the group *was* readable — an evicted member
2154
+ * still inside the owning org. The cross-org case never gets here at all: the
2155
+ * server refuses the read, so it is answered on the refusal instead
2156
+ * ({@link readGroup}).
2157
+ */
2158
+ async function evictionState(ctx, group) {
2159
+ if (!groupIsMls(group)) return null;
2160
+ try {
2161
+ return isEvictedFrom(ctx.configDir, await ctx.actingAgent(), group.id);
2162
+ } catch {
2163
+ return null;
2164
+ }
2165
+ }
2166
+ function registerGroupCrud(program, group) {
1047
2167
  group.command("list").description("List groups").action(withClient(program, async ({ client, gOpts }) => {
1048
2168
  const data = await client.get("/groups");
1049
2169
  if (gOpts.json) printJson(data);
1050
2170
  else printTable(data.items.map(groupRow));
1051
2171
  }));
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)]);
2172
+ group.command("get").description("Get group details").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is acting, and whose eviction from this group is reported")).action(withClient(program, async (ctx, ref) => {
2173
+ const { row: data } = await groupTarget(ctx, ref);
2174
+ const evicted = await evictionState(ctx, data);
2175
+ if (ctx.gOpts.json) {
2176
+ printJson({
2177
+ ...data,
2178
+ encryption: groupEncryption$1(data, CLI_UNFOUNDED_REPAIR),
2179
+ ...evicted === null ? {} : { evicted }
2180
+ });
2181
+ return;
2182
+ }
2183
+ printTable([groupDetailRow(data, data.member_agent_ids?.length ? await ownAgentHandles(ctx.agents) : void 0)]);
2184
+ printText(encryptionLine(data, CLI_UNFOUNDED_REPAIR));
2185
+ if (evicted) printText(`\n${evictedMessage(data.id)}`);
1056
2186
  }));
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) => {
2187
+ 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) => {
2188
+ const { client, gOpts, actingAgent, agents } = ctx;
1058
2189
  const body = {};
1059
2190
  if (opts.description !== void 0) body.description = opts.description;
1060
2191
  if (opts.enrollment) body.enrollment_policy = opts.enrollment;
@@ -1065,34 +2196,311 @@ function registerGroup(program) {
1065
2196
  process.exitCode = 2;
1066
2197
  return;
1067
2198
  }
1068
- const data = await client.patch(`/groups/${groupId}`, body);
1069
- if (gOpts.json) printJson(data);
2199
+ const { id: groupId } = await groupTarget(ctx, ref);
2200
+ const data = await client.patch(`/groups/${groupId}`, body, { [ACTING_AGENT_HEADER]: await actingAgent() });
2201
+ if (gOpts.json) printJson({
2202
+ ...data,
2203
+ encryption: groupEncryption$1(data, CLI_UNFOUNDED_REPAIR)
2204
+ });
1070
2205
  else {
1071
- printTable([groupDetailRow(data)]);
2206
+ printTable([groupDetailRow(data, await ownAgentHandles(agents))]);
1072
2207
  printText("Group updated");
2208
+ printText(encryptionLine(data, CLI_UNFOUNDED_REPAIR));
1073
2209
  }
1074
2210
  }));
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) => {
2211
+ 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) => {
2212
+ const { client, gOpts, actingAgent } = ctx;
2213
+ const headers = { [ACTING_AGENT_HEADER]: await actingAgent() };
2214
+ const target = await groupTarget(ctx, ref);
2215
+ const groupId = target.id;
1076
2216
  if (!opts.yes && !gOpts.json) {
1077
- if (!await promptConfirm(`Delete group ${groupId}?`)) return;
2217
+ if (!await promptConfirm(`Delete group ${target.handle ?? target.id}?`)) return;
1078
2218
  }
1079
- await client.delete(`/groups/${groupId}`);
2219
+ await client.delete(`/groups/${groupId}`, headers);
1080
2220
  printMutationOk("Group deleted", gOpts.json);
1081
2221
  }));
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));
2222
+ }
2223
+ //#endregion
2224
+ //#region src/commands/group-invite.ts
2225
+ /**
2226
+ * An invite that names nobody is refused before it costs anything.
2227
+ *
2228
+ * It runs ahead of the acting agent, so a caller who typed no `--invitee` is
2229
+ * told that rather than being asked which of their agents is inviting — a
2230
+ * question they cannot answer usefully and did not come here to answer.
2231
+ *
2232
+ * The options object is found by the shape only this command has rather than by
2233
+ * its position, because commander's argument order depends on how many
2234
+ * arguments the command declares.
2235
+ */
2236
+ const invitesSomebody = (...args) => {
2237
+ const opts = args.find((arg) => Array.isArray(arg?.invitee));
2238
+ if (opts === void 0) return null;
2239
+ return opts.invitee.length === 0 ? INVITEE_REQUIRED : null;
2240
+ };
2241
+ const INVITATION_NOTE = "An invitation holds a ratchet-tree seat until it is accepted or expires.";
2242
+ 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.";
2243
+ /**
2244
+ * What the agents this batch reached now hold — said only of what it minted.
2245
+ *
2246
+ * Read off the entries, the same place {@link admissionHeadline} reads, because
2247
+ * a batch answers one of three ways and only two of them have anything to hold.
2248
+ * An open group mints no invitation and no nomination and runs Sender Keys, so
2249
+ * it has no ratchet tree either: every entry comes back `not_applicable`, and
2250
+ * both sentences below would name objects that do not exist. The per-agent line
2251
+ * carries the fact there — the agent may join whenever it likes — so the note
2252
+ * is simply absent rather than replaced.
2253
+ *
2254
+ * A closed group's invite mints vouchers and a voting group's files
2255
+ * nominations, one policy per call, so in practice one clause prints. Both are
2256
+ * stated when both are present, which costs nothing and keeps this true of a
2257
+ * report rather than of a policy this function never sees.
2258
+ */
2259
+ function admissionNote(report) {
2260
+ const notes = [];
2261
+ if (report.entries.some((entry) => entry.status === "invited")) notes.push(INVITATION_NOTE);
2262
+ if (report.entries.some((entry) => entry.status === "nominated")) notes.push(NOMINATION_NOTE);
2263
+ return notes.join(" ");
2264
+ }
2265
+ const UNRESOLVED_INVITER = "Warning: the request was filed, but this agent could not be resolved, so no Welcome was minted and nobody was notified:";
2266
+ /**
2267
+ * Nudge each reached agent's inbox with a sealed `rine.v1.group_invite` DM.
2268
+ *
2269
+ * The authoritative discovery path is `GET /groups/invites` (`group invites`),
2270
+ * which answers nominations as well as invitations and tells them
2271
+ * apart by `status` — so a failure here — a `groups_only` 403, missing keys —
2272
+ * warns and never fails the row the server has already written.
2273
+ *
2274
+ * The DM carries the group and who reached out, not a rendered sentence: its
2275
+ * payload is `{group_id, group_handle, invited_by, message}`
2276
+ * (`rine-core/src/group-invite-ops.ts`), so nothing on this path claims a seat
2277
+ * a nomination does not confer.
2278
+ */
2279
+ async function notifyInvitees(client, configDir, inviterId, group, inviteeIds, message, json) {
2280
+ for (const inviteeId of inviteeIds) try {
2281
+ await sendGroupInviteNotification(client, configDir, inviterId, inviteeId, {
2282
+ group_id: group.id,
2283
+ group_handle: group.handle,
2284
+ message: message ?? null
2285
+ });
2286
+ } catch (err) {
2287
+ if (!json) printText(`Warning: invite notification to ${inviteeId} failed: ${err instanceof Error ? err.message : String(err)}`);
2288
+ }
2289
+ }
2290
+ /**
2291
+ * The agents this call actually reached, whichever shape answered.
2292
+ *
2293
+ * A singular invite gets a bare row back and no report, so the one agent it
2294
+ * named is the answer. A plural one is `admittedAgentIds` — `rine-core`'s, not
2295
+ * a second copy of the arithmetic — which counts `not_applicable` as reached
2296
+ * because that is an open group's answer: it mints no voucher since it needs
2297
+ * none, and those agents are still being told to come in.
2298
+ *
2299
+ * 🔴 This is "who was reached and is owed a notice", NOT "who gets a leaf".
2300
+ * It also counts `nominated` entries, so feeding it to an MLS add
2301
+ * without asking {@link inviteNominates} first would Welcome an agent the
2302
+ * electorate has not decided on. {@link afterInvite} is where that question is
2303
+ * asked.
2304
+ */
2305
+ function reachedAgents(report, singular) {
2306
+ if (!report) return singular ? [singular] : [];
2307
+ return admittedAgentIds(report);
2308
+ }
2309
+ /**
2310
+ * What one invite call did, in its own words.
2311
+ *
2312
+ * Read off the row the server wrote rather than off the group, because the row
2313
+ * is the answer: a `closed` group's invite mints a voucher (`invited`), a
2314
+ * `majority` or `unanimity` group's files a nomination (`pending`),
2315
+ * and an `open` group's is a notification with no row at all — which answers
2316
+ * `invited` and carries no `id`.
2317
+ *
2318
+ * That missing `id` is what tells the third case from the first, and it is the
2319
+ * only signal there is: the two answers carry the same status. An open group
2320
+ * mints nothing because it needs nothing, so the head says so and there is no
2321
+ * row to table underneath it — reported in `rine-core`'s words, the same
2322
+ * sentence the plural report's per-agent line carries.
2323
+ */
2324
+ function singularHead(row) {
2325
+ if (row.status === "pending") return "Nomination filed — the group's electorate decides it";
2326
+ if (!row.id) return `Invited: ${groupAdmissionSkipSentence("not_applicable")}`;
2327
+ return "Invitation sent";
2328
+ }
2329
+ function printInvited(data, report, admission, json) {
2330
+ if (json) {
2331
+ printJson(admission ? {
2332
+ ...data,
2333
+ admission
2334
+ } : data);
2335
+ return;
2336
+ }
2337
+ if (report) {
2338
+ const note = admissionNote(report);
2339
+ printText(`Admission: ${admissionHeadline(report)}${note ? ` ${note}` : ""}`);
2340
+ printTable(report.entries.map(admissionRow));
2341
+ } else {
2342
+ const voucher = data;
2343
+ printText(singularHead(voucher));
2344
+ if (voucher.id) printTable([requestRow(voucher)]);
2345
+ }
2346
+ if (admission && admission.outcomes.length > 0) {
2347
+ printText(`\nSeated in the ratchet tree: ${admission.added} of ${admission.outcomes.length} in ${admission.commits} commit(s), now at epoch ${admission.epoch}.`);
2348
+ printTable(admissionOutcomeRows(admission));
2349
+ }
2350
+ }
2351
+ /**
2352
+ * The two steps that happen *after* the server has written the row, and neither
2353
+ * of which may fail the command.
2354
+ *
2355
+ * Both need the group's handle and the acting inviter, so both are read once
2356
+ * here rather than twice inside each. That resolution is itself best-effort: a
2357
+ * multi-agent org that named no agent — no `--agent`, no `RINE_AGENT`, and more
2358
+ * than one to choose from — cannot be told which agent is inviting, and refusing
2359
+ * to report an invitation that the server already accepted would be the wrong
2360
+ * answer to that.
2361
+ *
2362
+ * 🔴 **A nomination gets the notice and no leaf.** On `majority` and
2363
+ * `unanimity` this call filed a request the electorate has not decided, so
2364
+ * claiming the nominee's KeyPackage and Welcoming them here would put an agent
2365
+ * the vote may refuse inside the ratchet tree, holding an epoch secret, with
2366
+ * only the manual reclamation pass able to retire the leaf afterwards — and
2367
+ * that pass cannot reach it while the row is live. The vote seats the member,
2368
+ * and seating is what grants the key: `group vote` posts the add on the approve
2369
+ * that carries, which is what the self-application path has always done. The
2370
+ * notice still goes out, because a nominee that never learns of the nomination
2371
+ * can never consent to it.
2372
+ *
2373
+ * The GROUP's policy decides this and not the response, because it is the same
2374
+ * question the server asked when it chose what to write, and it answers the
2375
+ * singular and the plural call in one place.
2376
+ */
2377
+ async function afterInvite(ctx, groupId, reached, message) {
2378
+ let group;
2379
+ let inviterId;
2380
+ try {
2381
+ group = await ctx.client.get(`/groups/${groupId}`);
2382
+ inviterId = await ctx.actingAgent();
2383
+ } catch (err) {
2384
+ if (!ctx.gOpts.json) printText(`${UNRESOLVED_INVITER} ${err instanceof Error ? err.message : String(err)}`);
2385
+ return null;
2386
+ }
2387
+ const admission = inviteNominates(group.enrollment_policy) ? null : await admitToMls(ctx.client, ctx.configDir, inviterId, groupId, group.mls_group_id, reached, ctx.gOpts.json);
2388
+ await notifyInvitees(ctx.client, ctx.configDir, inviterId, group, reached, message, ctx.gOpts.json);
2389
+ return admission;
2390
+ }
2391
+ function registerGroupInvite(program, group) {
2392
+ 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) => {
2393
+ const { id: groupId } = await groupTarget(ctx, ref);
2394
+ const agentIds = dedupeIds(await Promise.all(opts.invitee.map((a) => {
2395
+ announceHandleCompletion(a);
2396
+ return resolveToUuid(ctx.apiUrl, a);
2397
+ })));
2398
+ const single = agentIds.length === 1 ? agentIds[0] : void 0;
2399
+ const body = single ? { agent_id: single } : { agent_ids: agentIds };
2400
+ if (opts.message) body.message = opts.message;
2401
+ const data = await ctx.client.post(`/groups/${groupId}/invite`, body);
2402
+ const report = single ? null : data;
2403
+ printInvited(data, report, await afterInvite(ctx, groupId, reachedAgents(report, single), opts.message), ctx.gOpts.json);
2404
+ }, invitesSomebody));
2405
+ }
2406
+ //#endregion
2407
+ //#region src/commands/group-senderkey.ts
2408
+ const lower = (id) => id.toLowerCase();
2409
+ /**
2410
+ * Which members hold this agent's current sender key, and which do not.
2411
+ *
2412
+ * `distributeSenderKey` reports a per-recipient `DistributeResult` and **every
2413
+ * caller discards the failures**: a distribution that reached four of five
2414
+ * members looks exactly like one that reached all five, and the fifth member
2415
+ * silently cannot read anything this agent sends until some later send happens
2416
+ * to reach them. The information is on disk — `distributedTo` records only the
2417
+ * recipients that were actually reached — and nothing has ever read it back.
2418
+ * This is that read.
2419
+ *
2420
+ * Returns null when this agent holds no sender key for the group, which is the
2421
+ * normal state of an MLS group and of one nobody has sent to yet. That is not
2422
+ * the same answer as "everybody has it", so it is a different value.
2423
+ *
2424
+ * ⚠️ The current state is the **last** one this agent owns, which is the same
2425
+ * rule `getOrCreateSenderKey` applies when it decides which key to send under
2426
+ * (`rine-core/src/sender-key-ops.ts`): a rotation appends and drops the key it
2427
+ * superseded, so reading the first match would report a retired key's audience.
2428
+ * The rule is stated in both places because rine-core exports no reader for it;
2429
+ * one exported accessor would be the better home.
2430
+ */
2431
+ function senderKeyCoverage(configDir, agentId, groupId, memberIds) {
2432
+ const own = loadSenderKeyStates(configDir, agentId, groupId).filter((state) => lower(state.senderAgentId) === lower(agentId));
2433
+ const current = own[own.length - 1];
2434
+ if (!current) return null;
2435
+ const held = new Set((current.distributedTo ?? []).map(lower));
2436
+ const recipients = memberIds.filter((id) => lower(id) !== lower(agentId));
2437
+ return {
2438
+ senderKeyId: current.senderKeyId,
2439
+ reached: recipients.filter((id) => held.has(lower(id))),
2440
+ unreached: recipients.filter((id) => !held.has(lower(id)))
2441
+ };
2442
+ }
2443
+ /**
2444
+ * What an operator is told when a distribution reached only part of the group.
2445
+ *
2446
+ * Empty when everybody has the key — there is nothing to report, and a line
2447
+ * that appears every time stops being read.
2448
+ */
2449
+ function coverageWarning(coverage) {
2450
+ if (coverage.unreached.length === 0) return "";
2451
+ const total = coverage.reached.length + coverage.unreached.length;
2452
+ 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(", ")}`;
2453
+ }
2454
+ //#endregion
2455
+ //#region src/commands/group-membership.ts
2456
+ /** The group, or null when it cannot be read — only its rendering depends on it. */
2457
+ async function readGroup(ctx, groupId) {
2458
+ try {
2459
+ return await ctx.client.get(`/groups/${groupId}`);
2460
+ } catch {
2461
+ return null;
2462
+ }
2463
+ }
2464
+ /** Who holds this agent's sender key for the group; null when it holds none. */
2465
+ async function coverageFor(ctx, groupId, memberIds) {
2466
+ try {
2467
+ return senderKeyCoverage(ctx.configDir, await ctx.actingAgent(), groupId, memberIds);
2468
+ } catch {
2469
+ return null;
2470
+ }
2471
+ }
2472
+ function registerGroupMembership(program, group) {
2473
+ group.command("members").description("List group members").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is acting, and whose sender-key coverage is reported")).action(withClient(program, async (ctx, ref) => {
2474
+ const { id: groupId } = await groupTarget(ctx, ref);
2475
+ let data;
2476
+ try {
2477
+ data = await ctx.client.get(`/groups/${groupId}/members`);
2478
+ } catch (err) {
2479
+ throw await asGroupAccessError(ctx.configDir, groupId, err, () => ctx.actingAgent());
2480
+ }
2481
+ const coverage = await coverageFor(ctx, groupId, data.items.map((m) => m.agent_id));
2482
+ if (ctx.gOpts.json) {
2483
+ printJson(coverage ? {
2484
+ ...data,
2485
+ sender_key_coverage: coverage
2486
+ } : data);
2487
+ return;
2488
+ }
2489
+ printTable(data.items.map(memberRow));
2490
+ const warning = coverage ? coverageWarning(coverage) : "";
2491
+ if (warning) printText(warning);
1086
2492
  }));
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) => {
2493
+ group.command("join").description("Join a group").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent joins the group")).option("--message <msg>", "Join request message").action(withClient(program, async (ctx, ref, opts) => {
2494
+ const { id: groupId } = await joinGroupTarget(ctx, ref);
1088
2495
  const body = {};
1089
2496
  if (opts.message) body.message = opts.message;
1090
- const data = await client.post(`/groups/${groupId}/join`, body);
2497
+ const data = await ctx.client.post(`/groups/${groupId}/join`, body);
1091
2498
  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);
2499
+ await installWelcomes(ctx.client, ctx.configDir, data.agent_id, groupId, ctx.gOpts.json);
2500
+ const joined = await readGroup(ctx, groupId);
2501
+ await selfJoinViaExternalCommit(ctx.client, ctx.configDir, groupId, data.agent_id, joined?.mls_group_id, ctx.gOpts.json);
1094
2502
  }
1095
- if (gOpts.json) printJson(data);
2503
+ if (ctx.gOpts.json) printJson(data);
1096
2504
  else if ("role" in data) {
1097
2505
  printTable([memberRow(data)]);
1098
2506
  printText("Joined group (member)");
@@ -1101,53 +2509,185 @@ function registerGroup(program) {
1101
2509
  printText("Join request submitted (pending approval)");
1102
2510
  }
1103
2511
  }));
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);
2512
+ group.command("leave").description("Leave a group").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).action(withClient(program, async (ctx, ref) => {
2513
+ const groupId = UUID_RE.test(ref) ? ref : (await groupTarget(ctx, ref)).id;
2514
+ const agentId = await ctx.actingAgent();
2515
+ const left = await readGroup(ctx, groupId);
2516
+ const heldMlsState = loadMlsState(ctx.configDir, agentId, groupId) !== null;
2517
+ await deleteGroupMember(ctx.client, ctx.configDir, groupId, agentId, void 0, { [ACTING_AGENT_HEADER]: agentId });
2518
+ const wipe = retireLocalGroupState(ctx.configDir, agentId, groupId);
2519
+ printMutationOk("Left group", ctx.gOpts.json);
2520
+ if (!ctx.gOpts.json) {
2521
+ if (wipe.error) printText(wipe.error);
2522
+ if (wipe.retired) printText(retirementMessage(left, heldMlsState));
2523
+ }
1113
2524
  }));
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);
2525
+ 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").addOption(actorOption("which agent is acting, and removes the member")).action(withClient(program, async (ctx, ref, agentId) => {
2526
+ announceHandleCompletion(agentId);
2527
+ const resolved = await resolveToUuid(ctx.apiUrl, agentId);
2528
+ let groupId = ref;
2529
+ let target;
2530
+ if (UUID_RE.test(ref)) target = await readGroup(ctx, ref);
1122
2531
  else {
1123
- printText("Invitation sent");
1124
- if (data.id) printTable([requestRow(data)]);
2532
+ const seated = await groupTarget(ctx, ref);
2533
+ groupId = seated.id;
2534
+ target = seated.row;
1125
2535
  }
2536
+ const removal = await deleteGroupMember(ctx.client, ctx.configDir, groupId, resolved, () => ctx.actingAgent(), ctx.extraHeaders);
2537
+ printMutationOk("Member removed", ctx.gOpts.json);
2538
+ const evicted = evictionMessage(target, removal);
2539
+ if (!ctx.gOpts.json && evicted) printText(evicted);
1126
2540
  }));
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`);
2541
+ }
2542
+ //#endregion
2543
+ //#region src/commands/group-requests.ts
2544
+ /** An open group has no ratchet tree, so there is no admission to resume in it. */
2545
+ 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.";
2546
+ function printAdmission(result, json) {
2547
+ if (json) {
2548
+ printJson(result);
2549
+ return;
2550
+ }
2551
+ printText(`Seated ${result.added} of ${result.outcomes.length} in ${result.commits} commit(s), now at epoch ${result.epoch}.`);
2552
+ printTable(admissionOutcomeRows(result));
2553
+ printReclamation(result.reclamation);
2554
+ }
2555
+ /**
2556
+ * What `--reclaim` did, or the stated reason it did nothing.
2557
+ *
2558
+ * The sentence is `describeMlsReclamation`'s, from rine-core — the TypeScript
2559
+ * stack's one copy, sentence for sentence identical to the Python twin. This
2560
+ * function composed its own three branches until the MCP server, eve and mastra
2561
+ * needed the same three, which is the drift a single shared sentence stops: four
2562
+ * surfaces reporting the same reclamation in four wordings.
2563
+ */
2564
+ function printReclamation(reclamation) {
2565
+ const said = describeMlsReclamation(reclamation);
2566
+ if (said) printText(said);
2567
+ }
2568
+ /**
2569
+ * What the vote did to the request, beside the wire token.
2570
+ *
2571
+ * There are **four** answers and not three. `invited` is the one no client
2572
+ * anticipated: the electorate approved a nomination whose subject has not
2573
+ * answered yet, so the row resolves to a spendable invitation rather than to a
2574
+ * seat — a carried vote seats only an agent that consented. Reported
2575
+ * by name here because a fall-through would render a carried vote as an unknown
2576
+ * status, and because it is the one outcome where nobody is added to the
2577
+ * ratchet tree despite the bar being met.
2578
+ *
2579
+ * An unrecognised status renders as itself and gets no sentence — a guess about
2580
+ * a token this build predates would be worse than the token.
2581
+ */
2582
+ function voteOutcomeSentence(status) {
2583
+ switch (status) {
2584
+ case "approved": return "the request carried and that agent is now a member";
2585
+ case "denied": return "the request was refused";
2586
+ case "pending": return "neither bar is reached yet, so the request stands";
2587
+ 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";
2588
+ default: return "";
2589
+ }
2590
+ }
2591
+ function registerGroupRequests(program, group) {
2592
+ group.command("requests").description("List what this group still owes an answer on").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is asking, and whose vote the rows report")).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) => {
2593
+ const { client, gOpts } = ctx;
2594
+ const { id: groupId } = await groupTarget(ctx, ref);
2595
+ const data = await client.get(`/groups/${groupId}/requests`, { outstanding: opts.outstanding });
1129
2596
  if (gOpts.json) printJson(data);
1130
2597
  else printTable(data.items.map(requestRow));
1131
2598
  }));
1132
- group.command("invites").description("List group invitations addressed to you").action(withClient(program, async ({ client, gOpts, extraHeaders }) => {
2599
+ 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.").addOption(actorOption("whose invitations and nominations to list")).action(withClient(program, async ({ client, gOpts, extraHeaders }) => {
1133
2600
  const items = await listMyInvites(client, extraHeaders);
1134
2601
  if (gOpts.json) printJson(items);
1135
2602
  else printTable(items.map(inviteRow));
1136
2603
  }));
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) => {
2604
+ group.command("resume-admission").description("Seat every member and invitee this group has not seated yet").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is acting, and seats the others")).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) => {
2605
+ const { id: groupId, row: target } = await groupTarget(ctx, ref);
2606
+ if (target.enrollment_policy === "open") {
2607
+ printError(NOT_AN_MLS_GROUP);
2608
+ process.exitCode = 2;
2609
+ return;
2610
+ }
2611
+ const actingId = await ctx.actingAgent();
2612
+ const headers = { [ACTING_AGENT_HEADER]: actingId };
2613
+ try {
2614
+ 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);
2615
+ } catch (err) {
2616
+ printError(mlsFailureText(err, groupId));
2617
+ process.exitCode = 1;
2618
+ }
2619
+ }));
2620
+ 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").addOption(actorOption("which agent casts the vote")).requiredOption("--vote <vote>", "Vote: approve or deny").action(withClient(program, async (ctx, ref, requestId, opts) => {
1138
2621
  if (opts.vote !== "approve" && opts.vote !== "deny") {
1139
2622
  printError("--vote must be 'approve' or 'deny'");
1140
2623
  process.exitCode = 2;
1141
2624
  return;
1142
2625
  }
2626
+ const { id: groupId } = await groupTarget(ctx, ref);
1143
2627
  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}`);
2628
+ if (opts.vote === "approve") applicantId = (await ctx.client.get(`/groups/${groupId}/requests`)).items.find((r) => r.id === requestId)?.agent_id;
2629
+ const data = await ctx.client.post(`/groups/${groupId}/requests/${requestId}/vote`, { vote: opts.vote });
2630
+ if (data.status === "approved" && applicantId) await seatApplicant(ctx, groupId, applicantId);
2631
+ if (ctx.gOpts.json) printJson(data);
2632
+ else {
2633
+ const said = voteOutcomeSentence(data.status);
2634
+ printText(`Vote recorded. Request status: ${data.status}` + (said ? ` — ${said}` : ""));
2635
+ }
1149
2636
  }));
1150
2637
  }
2638
+ /** Best-effort MLS add for a newly approved applicant; never fails the vote. */
2639
+ async function seatApplicant(ctx, groupId, applicantId) {
2640
+ try {
2641
+ const target = await ctx.client.get(`/groups/${groupId}`);
2642
+ const actingId = await ctx.actingAgent();
2643
+ await admitToMls(ctx.client, ctx.configDir, actingId, groupId, target.mls_group_id, [applicantId], ctx.gOpts.json);
2644
+ } catch (err) {
2645
+ if (!ctx.gOpts.json) printText(`Warning: MLS add-member failed: ${mlsFailureText(err, groupId)}`);
2646
+ }
2647
+ }
2648
+ //#endregion
2649
+ //#region src/commands/group-sync.ts
2650
+ function registerGroupSync(program, group) {
2651
+ group.command("sync").description("Catch this agent's group encryption state up, and say what it cost").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent's group state is caught up")).action(withClient(program, async (ctx, ref) => {
2652
+ const { row: target } = await groupTarget(ctx, ref);
2653
+ const label = target.handle ?? target.id;
2654
+ if (groupMlsInitInFlight(target)) {
2655
+ printError(mlsInitInFlightSync(target.handle ?? target.id));
2656
+ process.exitCode = 2;
2657
+ return;
2658
+ }
2659
+ const actingId = await ctx.actingAgent();
2660
+ try {
2661
+ const result = await recoverGroup(ctx.configDir, actingId, target, ctx.client, { [ACTING_AGENT_HEADER]: actingId }, CLI_UNFOUNDED_REPAIR);
2662
+ if (ctx.gOpts.json) printJson(result);
2663
+ else printText(describeMlsRecovery(label, result));
2664
+ } catch (err) {
2665
+ printError(mlsFailureText(err, label));
2666
+ process.exitCode = isMlsResyncUnavailable(err) ? 2 : 1;
2667
+ }
2668
+ }));
2669
+ }
2670
+ //#endregion
2671
+ //#region src/commands/group.ts
2672
+ /**
2673
+ * `rine group` — the group lifecycle, in six files.
2674
+ *
2675
+ * Split by what a subcommand is about rather than left as one listing: create
2676
+ * carries the visibility refusal and the roster, membership carries the
2677
+ * removal path and what leaving retires, invite carries plural admission,
2678
+ * requests carries the vote and the resume verb, and sync carries the recovery
2679
+ * ladder. Each registrar takes the root `program` because `withClient` reads
2680
+ * the global options off it.
2681
+ */
2682
+ function registerGroup(program) {
2683
+ const group = program.command("group").description("Group management");
2684
+ registerGroupCreate(program, group);
2685
+ registerGroupCrud(program, group);
2686
+ registerGroupMembership(program, group);
2687
+ registerGroupInvite(program, group);
2688
+ registerGroupRequests(program, group);
2689
+ registerGroupSync(program, group);
2690
+ }
1151
2691
  //#endregion
1152
2692
  //#region src/commands/hook.ts
1153
2693
  const SIGNATURE_HEADER = "X-Hub-Signature-256";
@@ -1166,7 +2706,7 @@ function resolveTier(raw) {
1166
2706
  }
1167
2707
  function registerHook(program) {
1168
2708
  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) => {
2709
+ 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
2710
  const nameError = hookNameError(opts.name);
1171
2711
  if (nameError) {
1172
2712
  printError(`Invalid hook name '${opts.name}': ${nameError}.`);
@@ -1181,7 +2721,7 @@ function registerHook(program) {
1181
2721
  process.exitCode = 2;
1182
2722
  return;
1183
2723
  }
1184
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
2724
+ const agentId = await actingAgent();
1185
2725
  const secret = generateHookSecret();
1186
2726
  saveHookSecret(configDir, agentId, opts.name, secret);
1187
2727
  let created;
@@ -1196,8 +2736,8 @@ function registerHook(program) {
1196
2736
  }
1197
2737
  printCreated(created, secret, gOpts.json);
1198
2738
  }));
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);
2739
+ hook.command("list").description("List your agent's funnel hooks").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, actingAgent }) => {
2740
+ const agentId = await actingAgent();
1201
2741
  const data = await client.get(`/agents/${agentId}/funnel/hooks`, {});
1202
2742
  if (gOpts.json) printJson(data);
1203
2743
  else printTable(data.items.map((h) => ({
@@ -1208,8 +2748,8 @@ function registerHook(program) {
1208
2748
  Created: h.created_at
1209
2749
  })));
1210
2750
  }));
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);
2751
+ 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) => {
2752
+ const agentId = await actingAgent();
1213
2753
  if (!opts.yes && !gOpts.json) {
1214
2754
  if (!await promptConfirm(`Delete funnel hook '${opts.name}'?`)) return;
1215
2755
  }
@@ -1305,10 +2845,9 @@ async function verifyServerKeys(client, agentId, expected) {
1305
2845
  }
1306
2846
  function registerKeys(program) {
1307
2847
  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";
2848
+ keys.command("status").description("Show E2EE key status for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, configDir, actingAgent, agents }) => {
2849
+ const agentId = await actingAgent();
2850
+ const handle = (await agents()).find((a) => a.id === agentId)?.handle ?? "unknown";
1312
2851
  const hasLocal = agentKeysExist(configDir, agentId);
1313
2852
  let hasServer = false;
1314
2853
  let serverKeys;
@@ -1376,8 +2915,8 @@ function registerKeys(program) {
1376
2915
  }
1377
2916
  ]);
1378
2917
  }));
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);
2918
+ keys.command("generate").description("Generate new E2EE keys for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, configDir, actingAgent }) => {
2919
+ const agentId = await actingAgent();
1381
2920
  if (agentKeysExist(configDir, agentId)) {
1382
2921
  printError(`Keys already exist for agent ${agentId}. Use 'rine keys rotate' to replace them.`);
1383
2922
  process.exitCode = 1;
@@ -1390,8 +2929,8 @@ function registerKeys(program) {
1390
2929
  saveAgentKeys(configDir, agentId, agentKeys);
1391
2930
  printMutationOk(`E2EE keys generated for agent ${agentId}`, gOpts.json);
1392
2931
  }));
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);
2932
+ keys.command("rotate").description("Rotate E2EE keys for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, configDir, actingAgent }) => {
2933
+ const agentId = await actingAgent();
1395
2934
  if (agentKeysExist(configDir, agentId)) backupKeys(configDir, agentId);
1396
2935
  const agentKeys = generateAgentKeys();
1397
2936
  const pubKeys = getAgentPublicKeys(configDir, agentId, agentKeys);
@@ -1400,8 +2939,8 @@ function registerKeys(program) {
1400
2939
  saveAgentKeys(configDir, agentId, agentKeys);
1401
2940
  printMutationOk(`E2EE keys rotated for agent ${agentId}`, gOpts.json);
1402
2941
  }));
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);
2942
+ 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 }) => {
2943
+ const agentId = await actingAgent();
1405
2944
  if (!agentKeysExist(configDir, agentId)) {
1406
2945
  printError(`No keys found for agent ${agentId}. Use 'rine keys generate' first.`);
1407
2946
  process.exitCode = 1;
@@ -1424,8 +2963,8 @@ function registerKeys(program) {
1424
2963
  savePqEncryptionKey(configDir, agentId, pqKeyPair);
1425
2964
  printMutationOk(`Post-quantum encryption key added for agent ${agentId}`, gOpts.json);
1426
2965
  }));
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);
2966
+ 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) => {
2967
+ const agentId = await actingAgent();
1429
2968
  if (!agentKeysExist(configDir, agentId)) {
1430
2969
  printError(`No keys found for agent ${agentId}`);
1431
2970
  process.exitCode = 1;
@@ -1519,7 +3058,79 @@ function x402SendExtras(type, payload, emitMarker) {
1519
3058
  return extras;
1520
3059
  }
1521
3060
  //#endregion
1522
- //#region src/commands/messages.ts
3061
+ //#region src/commands/messages-read-decrypt.ts
3062
+ /**
3063
+ * Open one fetched message with the caller's own keys, and — when it stays
3064
+ * closed — say why in one sentence a reader can act on.
3065
+ *
3066
+ * Split out of `messages-read.ts` (file-size budget) so that command is left
3067
+ * with its rendering. This is the SINGLE tier of the explain-once rule: the
3068
+ * caller named ONE message, so the refusal is stated in full. There is no
3069
+ * second row for it to repeat itself on, and nothing here creates a
3070
+ * `senderKeyExplainer`.
3071
+ *
3072
+ * A refusal is returned rather than printed, because the same fact has to reach
3073
+ * two different outputs: stderr prose for a human, and a field on the `--json`
3074
+ * envelope for a program. A helper that printed could only serve one of them.
3075
+ */
3076
+ /** Decrypt one message, dispatching on its encryption version. Never throws. */
3077
+ async function openMessage(opts) {
3078
+ const { client, configDir, agentId, data, fromAgentId } = opts;
3079
+ if (!((data.encryption_version === "sender-key-v1" || data.encryption_version === "mls-v1") && data.group_id != null)) try {
3080
+ return {
3081
+ result: await decryptMessage(configDir, agentId, data.encrypted_payload, client, fromAgentId),
3082
+ refusal: null
3083
+ };
3084
+ } catch (err) {
3085
+ return { refusal: refusalFor(err, null) };
3086
+ }
3087
+ const groupId = data.group_id;
3088
+ try {
3089
+ return {
3090
+ result: await decryptGroupMessageWithRecovery(client, configDir, agentId, groupId, data.encrypted_payload, fromAgentId),
3091
+ refusal: null
3092
+ };
3093
+ } catch (err) {
3094
+ return { refusal: refusalFor(err, groupId) };
3095
+ }
3096
+ }
3097
+ /**
3098
+ * Why the message stayed closed, chosen by the failure's machine-readable CODE
3099
+ * and never by its words.
3100
+ *
3101
+ * `groupId` is null for a 1:1 envelope, where no group arm can apply.
3102
+ *
3103
+ * `rine thread` has degraded correctly since it was written — a recognised
3104
+ * cause becomes a rine sentence, an unrecognised one becomes `[unavailable]` —
3105
+ * while this path interpolated whatever it caught. What that let through was
3106
+ * mls-rs's own KDF error, *the provided length of the key 0 is shorter than the
3107
+ * minimum length 32*: the crypto library refusing to derive from an epoch
3108
+ * secret this member never held. Same message, same agent, same moment, two
3109
+ * renderers, and the raw one was the outlier.
3110
+ */
3111
+ function refusalFor(err, groupId) {
3112
+ if (groupId !== null) {
3113
+ const unavailable = asSenderKeyUnavailable(err, groupId);
3114
+ if (unavailable !== null) return {
3115
+ message: unavailable.message,
3116
+ code: SENDER_KEY_UNAVAILABLE_CODE
3117
+ };
3118
+ if (mlsErrorCode(err) === MLS_ERR_GROUP_INACTIVE) return {
3119
+ message: mlsFailureText(err, groupId),
3120
+ code: null
3121
+ };
3122
+ if (isRecoverableMlsRead(err)) return {
3123
+ message: mlsReadRefusal(groupId, cliSyncRemedy(groupId)),
3124
+ code: null
3125
+ };
3126
+ }
3127
+ return {
3128
+ message: `Decryption failed: ${formatError(err)}`,
3129
+ code: null
3130
+ };
3131
+ }
3132
+ //#endregion
3133
+ //#region src/commands/messages-rows.ts
1523
3134
  function msgFrom(m) {
1524
3135
  return m.sender_handle ?? m.from_agent_id ?? "";
1525
3136
  }
@@ -1550,6 +3161,16 @@ function inboxRow(m) {
1550
3161
  Created: m.created_at
1551
3162
  };
1552
3163
  }
3164
+ /**
3165
+ * Render the sender-signature outcome for a table column. Both authenticity
3166
+ * failures are marked, and told apart: tampered bytes and content attributed to
3167
+ * an agent that did not sign it are different problems for an operator.
3168
+ */
3169
+ function verifiedMark(status) {
3170
+ if (status === "verified") return "✓";
3171
+ if (!isAuthenticityFailure(status)) return "?";
3172
+ return status === "sender-mismatch" ? "✗ SENDER MISMATCH" : "✗ INVALID";
3173
+ }
1553
3174
  /** One thread turn rendered as a role-tagged row (`[sent]` you / `[received]`). */
1554
3175
  function threadRow(e) {
1555
3176
  const who = e.direction === "sent" ? "you" : e.sender_handle ?? "unknown";
@@ -1557,11 +3178,99 @@ function threadRow(e) {
1557
3178
  Direction: `[${e.direction}]`,
1558
3179
  From: who,
1559
3180
  Type: e.type,
1560
- Verified: e.verification_status === "verified" ? "✓" : e.verification_status === "invalid" ? "✗ INVALID" : "?",
3181
+ Verified: verifiedMark(e.verification_status),
1561
3182
  Text: e.text,
1562
3183
  Created: e.created_at
1563
3184
  };
1564
3185
  }
3186
+ //#endregion
3187
+ //#region src/commands/messages-read.ts
3188
+ /**
3189
+ * `rine message read` — fetch one message and open it.
3190
+ *
3191
+ * Split out of `messages.ts` because the decrypt-and-render pipeline is the
3192
+ * longest handler there by a wide margin and has nothing to do with sending.
3193
+ * The command is registered by `messages.ts` alongside its siblings, so the
3194
+ * CLI surface is unchanged.
3195
+ */
3196
+ /** Register `read` on the `message` command group. */
3197
+ function addReadCommand(parent, program) {
3198
+ 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) => {
3199
+ const agentId = await actingAgent();
3200
+ const data = await client.get(`/messages/${messageId}`);
3201
+ const fromAgentId = data.from_agent_id;
3202
+ 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);
3203
+ let refusal = null;
3204
+ if (canDecrypt) {
3205
+ const opened = await openMessage({
3206
+ client,
3207
+ configDir,
3208
+ agentId,
3209
+ data,
3210
+ fromAgentId
3211
+ });
3212
+ const decResult = opened.result;
3213
+ refusal = opened.refusal;
3214
+ if (refusal !== null && !gOpts.json) printError(refusal.message);
3215
+ if (decResult) {
3216
+ if (ingestSenderKeyDistribution(configDir, agentId, data.type, decResult)) printText("Sender key ingested");
3217
+ if (gOpts.json) printJson({
3218
+ ...data,
3219
+ decrypted_payload: decResult.plaintext === void 0 ? null : JSON.parse(decResult.plaintext),
3220
+ signature_verified: decResult.verified,
3221
+ verification_status: decResult.verificationStatus,
3222
+ sender_kid: decResult.senderKid,
3223
+ ...decResult.catchUp ? { catch_up: decResult.catchUp } : {}
3224
+ });
3225
+ else {
3226
+ if (decResult.catchUp?.evicted) printError(MLS_EVICTED_BY_COMMIT);
3227
+ printTable([openedRow(data, verifiedMark(decResult.verificationStatus), decResult.plaintext?.slice(0, 200) ?? THREAD_UNAVAILABLE)]);
3228
+ }
3229
+ return;
3230
+ }
3231
+ }
3232
+ if (gOpts.json) printJson({
3233
+ ...data,
3234
+ ...refusal !== null ? {
3235
+ decrypt_error: refusal.message,
3236
+ decrypt_error_code: refusal.code
3237
+ } : {}
3238
+ });
3239
+ else if (refusal !== null) printTable([openedRow(data, verifiedMark("unverifiable"), THREAD_UNAVAILABLE)]);
3240
+ else printTable([{
3241
+ ...readRow(data),
3242
+ Encryption: data.encryption_version,
3243
+ "Encrypted Payload": `${data.encrypted_payload.slice(0, 40)}...`,
3244
+ Created: data.created_at
3245
+ }]);
3246
+ }));
3247
+ }
3248
+ /** The columns every rendering of one read shares, in one order. */
3249
+ function readRow(data) {
3250
+ return {
3251
+ ID: data.id,
3252
+ "Conversation ID": data.conversation_id,
3253
+ From: msgFrom(data),
3254
+ To: msgTo(data),
3255
+ Group: msgGroup(data),
3256
+ Type: data.type
3257
+ };
3258
+ }
3259
+ /**
3260
+ * One row for a message this read tried to open — whether it opened, withheld
3261
+ * its content or would not open at all. One shape for all three, so a refused
3262
+ * read and a successful one are read off the same columns.
3263
+ */
3264
+ function openedRow(data, verified, payload) {
3265
+ return {
3266
+ ...readRow(data),
3267
+ Verified: verified,
3268
+ Payload: payload,
3269
+ Created: data.created_at
3270
+ };
3271
+ }
3272
+ //#endregion
3273
+ //#region src/commands/messages.ts
1565
3274
  function resolvePayload(payload, payloadFile) {
1566
3275
  if (payload !== void 0 && payloadFile !== void 0) return { error: "--payload and --payload-file are mutually exclusive" };
1567
3276
  if (payload === void 0 && payloadFile === void 0) return { error: "Provide --payload or --payload-file" };
@@ -1578,20 +3287,35 @@ function resolvePayload(payload, payloadFile) {
1578
3287
  return { error: "Payload must be valid JSON" };
1579
3288
  }
1580
3289
  }
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;
3290
+ /**
3291
+ * What a caller is told when the ID they typed named a group, not an agent.
3292
+ *
3293
+ * 🔴 It quotes the caller's own spelling and the handle the wire will carry,
3294
+ * and nothing else. A third handle would be a placeholder in a sentence about
3295
+ * a real send, and an `@org` slot for the caller to fill would advertise a
3296
+ * spelling this notice is not about.
3297
+ *
3298
+ * 🔴 It stays on this surface rather than moving into `@rine-network/core`,
3299
+ * for `GROUP_REFERENCE_HELP`'s reason (`group-target.ts`): a constant in the
3300
+ * shared package is a constant the Python stack is then expected to twin and a
3301
+ * gate is expected to hold, and this is one CLI's rendering of a substitution
3302
+ * the shared door discharges through its RETURN VALUE — `RecipientTarget`
3303
+ * carries `spelling` beside `handle` so every other surface can compare the
3304
+ * two and say it in its own idiom. Hoisting it would mint an obligation
3305
+ * nothing pays.
3306
+ */
3307
+ function groupIdRecipientNote(spelling, handle) {
3308
+ return `Note: '${spelling}' is a group ID, so this was addressed to the group '${handle}' and not to an agent.`;
1585
3309
  }
1586
3310
  async function encryptMlsWithRecovery(client, configDir, senderAgentId, groupId, payload) {
1587
- const hdrs = { "X-Rine-Agent": senderAgentId };
3311
+ const hdrs = { [ACTING_AGENT_HEADER]: senderAgentId };
1588
3312
  await processMlsWelcomes(configDir, senderAgentId, client).catch(() => {});
1589
3313
  await syncMlsGroup(configDir, senderAgentId, groupId, client, hdrs).catch(() => {});
1590
3314
  try {
1591
3315
  return await encryptMlsGroupMessage(configDir, senderAgentId, groupId, payload);
1592
3316
  } catch (err) {
1593
- if (err instanceof Error && err.message.startsWith("No MLS state for group")) {
1594
- await processMlsWelcomes(configDir, senderAgentId, client);
3317
+ if (isNoMlsStateError(err)) {
3318
+ await processMlsWelcomes(configDir, senderAgentId, client, { forGroup: groupId });
1595
3319
  await syncMlsGroup(configDir, senderAgentId, groupId, client, hdrs);
1596
3320
  return await encryptMlsGroupMessage(configDir, senderAgentId, groupId, payload);
1597
3321
  }
@@ -1599,7 +3323,9 @@ async function encryptMlsWithRecovery(client, configDir, senderAgentId, groupId,
1599
3323
  }
1600
3324
  }
1601
3325
  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) => {
3326
+ addReadCommand(parent, program);
3327
+ 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), by sigiled name (#logistics), or by the group's own ID").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) => {
3328
+ const { client, gOpts, configDir, apiUrl, actingAgent } = ctx;
1603
3329
  const result = resolvePayload(opts.payload, opts.payloadFile);
1604
3330
  if ("error" in result) {
1605
3331
  printError(result.error);
@@ -1609,19 +3335,19 @@ function addMessageCommands(parent, program) {
1609
3335
  const parsedPayload = result.parsed;
1610
3336
  const to = normalizeHandle(opts.to);
1611
3337
  const from = opts.from ? normalizeHandle(opts.from) : opts.from;
3338
+ const senderAgentId = await actingAgent();
1612
3339
  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
3340
  if (opts.idempotencyKey) extraHeaders["Idempotency-Key"] = opts.idempotencyKey;
3341
+ const groupNamedById = UUID_RE.test(to) ? await readableGroupById(client, to) : void 0;
3342
+ const isGroupSend = to.startsWith("#") || groupNamedById !== void 0;
3343
+ if (groupNamedById !== void 0) printError(groupIdRecipientNote(opts.to, groupNamedById.handle));
1622
3344
  let recipientAgentId;
1623
- if (!to.includes("@")) recipientAgentId = to;
1624
- else if (!to.startsWith("#")) recipientAgentId = await resolveToUuid(apiUrl, to);
3345
+ if (isGroupSend) recipientAgentId = void 0;
3346
+ else if (!to.includes("@")) recipientAgentId = to;
3347
+ else {
3348
+ announceHandleCompletion(opts.to);
3349
+ recipientAgentId = await resolveToUuid(apiUrl, to);
3350
+ }
1625
3351
  const resolvedType = opts.type ?? "rine.v1.dm";
1626
3352
  const body = { type: resolvedType };
1627
3353
  const x402 = x402SendExtras(resolvedType, parsedPayload, opts.marker !== false);
@@ -1630,20 +3356,26 @@ function addMessageCommands(parent, program) {
1630
3356
  body.payload_schema = x402.payload_schema;
1631
3357
  if (x402.metadata) body.metadata = x402.metadata;
1632
3358
  }
1633
- if (to.includes("@")) body.to_handle = to;
3359
+ if (!isGroupSend) if (to.includes("@")) body.to_handle = to;
1634
3360
  else body.to_agent_id = to;
1635
3361
  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) {
3362
+ if (isGroupSend) {
3363
+ const group = groupNamedById ?? await resolveGroupByHandle(client, to).catch(async (err) => {
3364
+ throw await withEvictionPointerIfHeld(ctx, err);
3365
+ });
3366
+ body.to_handle = group.handle;
3367
+ const mlsOnly = groupAcceptsMlsSendOnly(group);
3368
+ assertNoMlsDowngrade(configDir, senderAgentId, group.id, mlsOnly);
3369
+ if (mlsOnly) {
3370
+ if (group.mls_group_id == null) throw new MlsInitInFlightError(group.handle);
1639
3371
  const encResult = await encryptMlsWithRecovery(client, configDir, senderAgentId, group.id, parsedPayload);
1640
3372
  Object.assign(body, encResult);
1641
3373
  } else {
1642
- const { state, groupId } = await getOrCreateSenderKey(client, configDir, senderAgentId, to, Object.keys(extraHeaders).length > 0 ? extraHeaders : void 0);
3374
+ const { state, groupId } = await getOrCreateSenderKey(client, configDir, senderAgentId, group.handle);
1643
3375
  const { result: encResult } = await encryptGroupMessage(configDir, senderAgentId, groupId, state, parsedPayload);
1644
3376
  Object.assign(body, encResult);
1645
3377
  }
1646
- } else if (senderAgentId && recipientAgentId) {
3378
+ } else if (recipientAgentId) {
1647
3379
  const recipientKeys = await fetchRecipientKeys(client, recipientAgentId);
1648
3380
  const encrypted = await encryptMessage(configDir, senderAgentId, recipientKeys.encryption, parsedPayload, recipientKeys.pqEncryption);
1649
3381
  Object.assign(body, encrypted);
@@ -1652,72 +3384,13 @@ function addMessageCommands(parent, program) {
1652
3384
  if (gOpts.json) printJson(data);
1653
3385
  else printTable([sendRow(data)]);
1654
3386
  }));
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) => {
3387
+ 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
3388
  if ([
1716
3389
  opts.new,
1717
3390
  opts.delivered,
1718
3391
  opts.read
1719
3392
  ].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);
3393
+ const agentId = await actingAgent();
1721
3394
  const params = {};
1722
3395
  if (opts.new) params.status = "new";
1723
3396
  else if (opts.delivered) params.status = "delivered";
@@ -1731,7 +3404,7 @@ function addMessageCommands(parent, program) {
1731
3404
  if (data.next_cursor) printText(`Next cursor: ${data.next_cursor}`);
1732
3405
  }
1733
3406
  }));
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) => {
3407
+ 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
3408
  const result = resolvePayload(opts.payload, opts.payloadFile);
1736
3409
  if ("error" in result) {
1737
3410
  printError(result.error);
@@ -1739,8 +3412,8 @@ function addMessageCommands(parent, program) {
1739
3412
  return;
1740
3413
  }
1741
3414
  const parsedPayload = result.parsed;
3415
+ const senderAgentId = await actingAgent();
1742
3416
  const original = await client.get(`/messages/${messageId}`);
1743
- const senderAgentId = await resolveAgent(apiUrl, await fetchAgents(client), void 0, gOpts.as);
1744
3417
  if (original.from_agent_id === senderAgentId) {
1745
3418
  console.error("Cannot reply to your own message. Use 'rine send' to follow up in this conversation.");
1746
3419
  process.exitCode = 1;
@@ -1763,12 +3436,16 @@ function addMessageCommands(parent, program) {
1763
3436
  process.exitCode = 1;
1764
3437
  }
1765
3438
  }));
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)));
3439
+ 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) => {
3440
+ const ref = resolveThreadRef({
3441
+ group: opts.group,
3442
+ conversationId
3443
+ }, THREAD_REF_SURFACES.cli);
3444
+ const agentId = await actingAgent();
3445
+ const entries = await decryptThreadRows(configDir, agentId, (await readThreadPage(client, ref, {
3446
+ ...opts.limit ? { limit: opts.limit } : {},
3447
+ extraHeaders: { [ACTING_AGENT_HEADER]: agentId }
3448
+ })).messages ?? [], client);
1772
3449
  if (gOpts.json) printJson(entries);
1773
3450
  else printTable(entries.map(threadRow));
1774
3451
  }));
@@ -1780,7 +3457,7 @@ function registerMessages(program) {
1780
3457
  //#endregion
1781
3458
  //#region src/commands/onboard.ts
1782
3459
  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) => {
3460
+ 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
3461
  const profile = gOpts.profile ?? "default";
1785
3462
  const configDir = resolveConfigDir();
1786
3463
  const apiUrl = resolveApiUrl();
@@ -1820,16 +3497,18 @@ function registerOnboard(program) {
1820
3497
  progressStream.write("\rSolving PoW challenge: 100%\n");
1821
3498
  const { client } = await createClient(configDir, apiUrl, gOpts.profile);
1822
3499
  const agent = await performAgentCreation(client, configDir, profile, {
1823
- name: opts.agent,
3500
+ name: opts.agentName,
1824
3501
  humanOversight: opts.humanOversight,
1825
3502
  unlisted: opts.unlisted,
1826
3503
  verifyIdentity: opts.verifyIdentity || Boolean(opts.svid) || hasSpiffeEndpoint(),
1827
3504
  svid: opts.svid
1828
3505
  });
3506
+ const verification = compareVerificationWordsForAgent(configDir, agent.id, agent.verification_words);
1829
3507
  if (gOpts.json) printJson({
1830
3508
  org_id: regResult.org_id,
1831
3509
  client_id: regResult.client_id,
1832
3510
  agent,
3511
+ verification,
1833
3512
  poll_url: agent.poll_url,
1834
3513
  identity: agent.identity,
1835
3514
  identity_error: agent.identityError,
@@ -1838,10 +3517,10 @@ function registerOnboard(program) {
1838
3517
  else {
1839
3518
  printTable([toAgentRow(agent, {
1840
3519
  includeCard: true,
1841
- includeVerificationWords: true
3520
+ verification
1842
3521
  })]);
1843
3522
  console.log(`\nAgent '${agent.name}' created — reachable at ${agent.handle}`);
1844
- if (agent.verification_words) console.log(`Verification words: ${agent.verification_words}`);
3523
+ for (const line of verificationWordsLines(verification)) console.log(line);
1845
3524
  if (agent.poll_url) console.log(`Poll URL: ${agent.poll_url}`);
1846
3525
  if (agent.identity) console.log(`SPIFFE identity verified: ${agent.identity.spiffe_id} (trust tier ${agent.identity.trust_tier})`);
1847
3526
  }
@@ -1888,7 +3567,8 @@ function registerOrg(program) {
1888
3567
  //#endregion
1889
3568
  //#region src/commands/pay.ts
1890
3569
  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) => {
3570
+ 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) => {
3571
+ const payerAgentId = await actingAgent();
1892
3572
  const message = await client.get(`/messages/${messageId}`);
1893
3573
  if (message.type !== X402_MESSAGE_TYPE.PAYMENT_REQUIRED) {
1894
3574
  printError(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT_REQUIRED}. Nothing to pay.`);
@@ -1901,12 +3581,16 @@ function registerPay(program) {
1901
3581
  process.exitCode = 1;
1902
3582
  return;
1903
3583
  }
1904
- const payerAgentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
1905
3584
  if (payeeAgentId === payerAgentId) {
1906
3585
  printError("Cannot pay your own quote.");
1907
3586
  process.exitCode = 1;
1908
3587
  return;
1909
3588
  }
3589
+ if (message.to_agent_id && message.to_agent_id !== payerAgentId) {
3590
+ 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.`);
3591
+ process.exitCode = 1;
3592
+ return;
3593
+ }
1910
3594
  if (!agentKeysExist(configDir, payerAgentId)) {
1911
3595
  printError(`No E2EE keys for agent ${payerAgentId}. Run 'rine keys generate' first.`);
1912
3596
  process.exitCode = 1;
@@ -1917,8 +3601,16 @@ function registerPay(program) {
1917
3601
  process.exitCode = 1;
1918
3602
  return;
1919
3603
  }
1920
- const decrypted = await decryptMessage(configDir, payerAgentId, message.encrypted_payload, client);
1921
- const pr = parseX402Payload(message.type, decrypted.plaintext);
3604
+ const decrypted = await decryptMessage(configDir, payerAgentId, message.encrypted_payload, client, payeeAgentId);
3605
+ let pr;
3606
+ try {
3607
+ pr = parseX402Payload(message.type, requireAuthenticPlaintext(decrypted, payeeAgentId, messageId));
3608
+ } catch (err) {
3609
+ if (!(err instanceof X402Error)) throw err;
3610
+ printError(`Payment refused: ${err.message}`);
3611
+ process.exitCode = 1;
3612
+ return;
3613
+ }
1922
3614
  const policy = loadPolicy(configDir, payerAgentId);
1923
3615
  const dailySpent = readDailySpent(configDir, payerAgentId);
1924
3616
  try {
@@ -1930,7 +3622,8 @@ function registerPay(program) {
1930
3622
  return;
1931
3623
  }
1932
3624
  }
1933
- const built = buildPaymentMessage(buildPaymentPayload(pr, requirement, loadWalletKey(configDir, payerAgentId), { quoteMessageId: messageId }), { emitMarker: opts.marker !== false });
3625
+ const walletKey = loadWalletKey(configDir, payerAgentId);
3626
+ const built = buildPaymentMessage(buildPaymentPayload(pr, requirement, walletKey, { quoteMessageId: messageId }), { emitMarker: opts.marker !== false });
1934
3627
  const recipientKeys = await fetchRecipientKeys(client, payeeAgentId);
1935
3628
  const encrypted = await encryptMessage(configDir, payerAgentId, recipientKeys.encryption, built.payload, recipientKeys.pqEncryption);
1936
3629
  const body = {
@@ -1944,7 +3637,7 @@ function registerPay(program) {
1944
3637
  messageId,
1945
3638
  force: opts.force
1946
3639
  });
1947
- const sent = await client.post(`/messages/${messageId}/reply`, body, { "X-Rine-Agent": payerAgentId });
3640
+ const sent = await client.post(`/messages/${messageId}/reply`, body, { [ACTING_AGENT_HEADER]: payerAgentId });
1948
3641
  if (gOpts.json) printJson({
1949
3642
  ok: true,
1950
3643
  payment_message_id: sent.id,
@@ -1993,8 +3686,8 @@ function registerPay(program) {
1993
3686
  //#endregion
1994
3687
  //#region src/commands/poll-token.ts
1995
3688
  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);
3689
+ 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) => {
3690
+ const agentId = await actingAgent();
1998
3691
  if (opts.revoke) {
1999
3692
  await client.delete(`/agents/${agentId}/poll-token`);
2000
3693
  const creds = loadCredentials(configDir);
@@ -2060,7 +3753,7 @@ function sleep(ms) {
2060
3753
  }
2061
3754
  /**
2062
3755
  * 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
3756
+ * port" (it is NOT coerced to the default — that coercion was the footgun); a
2064
3757
  * non-integer or out-of-range value throws a clear error rather than silently
2065
3758
  * falling back. The default flag value "8443" parses straight through.
2066
3759
  */
@@ -2076,7 +3769,7 @@ function isRevoked(err) {
2076
3769
  * Resolve the HMAC secret: --secret-env > --secret-file > the persisted file.
2077
3770
  * Returns "" (after a stderr warning naming the three sources tried) when none is
2078
3771
  * 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
3772
+ * body can compute `HMAC("", body)` and forge a "verified" self-send, so the
2080
3773
  * caller (runRelayLoop) HARD-REFUSES to start on an empty result — the relay never
2081
3774
  * enters the reconnect loop or opens the listener without a secret.
2082
3775
  */
@@ -2092,13 +3785,14 @@ function resolveSecret(opts, configDir, agentId) {
2092
3785
  return "";
2093
3786
  }
2094
3787
  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) => {
3788
+ 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
3789
  try {
2097
3790
  const gOpts = program.opts();
2098
3791
  const configDir = resolveConfigDir();
2099
3792
  const apiUrl = resolveApiUrl();
2100
3793
  const { client, profileName, entry } = await createClient(configDir, apiUrl, gOpts.profile);
2101
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
3794
+ const { actingAgent } = actorLadder(namedActor(command, gOpts), client);
3795
+ const agentId = await actingAgent();
2102
3796
  if (!agentKeysExist(configDir, agentId)) {
2103
3797
  printError(`Agent identity keys not found under ${configDir}/keys/${agentId}/ — register first.`);
2104
3798
  process.exitCode = 2;
@@ -2441,6 +4135,11 @@ function jitteredDelayMs(backoffSeconds) {
2441
4135
  * Encryption versions the stream preview can decrypt. A payload carrying one of
2442
4136
  * these that still fails is reported as "[decrypt failed]" rather than the
2443
4137
  * misleading "[encrypted]", which is reserved for versions we never attempt.
4138
+ *
4139
+ * One failure says more than that: a group message whose sender key never
4140
+ * arrived reports {@link SENDER_KEY_UNAVAILABLE_PREVIEW}, which names the cause
4141
+ * and the move. Every other failure keeps the generic line, because nothing
4142
+ * here knows enough about it to say anything truer.
2444
4143
  */
2445
4144
  const DECRYPTABLE_VERSIONS = new Set([
2446
4145
  "hpke-v1",
@@ -2448,7 +4147,7 @@ const DECRYPTABLE_VERSIONS = new Set([
2448
4147
  "sender-key-v1",
2449
4148
  "mls-v1"
2450
4149
  ]);
2451
- async function formatMessageLine(dataStr, agentId, configDir, client) {
4150
+ async function formatMessageLine(dataStr, agentId, configDir, client, explain) {
2452
4151
  try {
2453
4152
  const data = JSON.parse(dataStr);
2454
4153
  const ts = (data.created_at ?? "").slice(0, 19) || "?";
@@ -2456,39 +4155,48 @@ async function formatMessageLine(dataStr, agentId, configDir, client) {
2456
4155
  const msgType = data.type ?? "?";
2457
4156
  const target = data.group_handle ? `${data.group_handle} (${msgType})` : msgType;
2458
4157
  let preview = "[encrypted]";
2459
- if (data.encrypted_payload && agentKeysExist(configDir, agentId)) {
4158
+ let notice = null;
4159
+ const fromAgentId = data.from_agent_id;
4160
+ if (data.encrypted_payload && fromAgentId && agentKeysExist(configDir, agentId)) {
2460
4161
  let result;
4162
+ let unavailable = null;
2461
4163
  if ((data.encryption_version === "sender-key-v1" || data.encryption_version === "mls-v1") && data.group_id) try {
2462
- result = await decryptGroupMessage(configDir, agentId, data.group_id, data.encrypted_payload, client);
4164
+ result = await decryptGroupMessageWithRecovery(client, configDir, agentId, data.group_id, data.encrypted_payload, fromAgentId);
2463
4165
  } catch (err) {
2464
- const match = err instanceof Error && err.message.match(/^unknown sender key id: (.+)$/);
2465
- if (match) {
2466
- if (await fetchAndIngestPendingSKDistributions(client, configDir, agentId, match[1]) > 0) try {
2467
- result = await decryptGroupMessage(configDir, agentId, data.group_id, data.encrypted_payload, client);
2468
- } catch {}
2469
- }
4166
+ unavailable = asSenderKeyUnavailable(err, data.group_id);
2470
4167
  }
2471
4168
  else if (data.encryption_version === "hpke-v1" || data.encryption_version === "hpke-hybrid-v1") try {
2472
- result = await decryptMessage(configDir, agentId, data.encrypted_payload, client);
4169
+ result = await decryptMessage(configDir, agentId, data.encrypted_payload, client, fromAgentId);
2473
4170
  } catch {}
2474
- if (result) {
4171
+ if (result && isAuthenticityFailure(result.verificationStatus)) preview = result.verificationStatus === "sender-mismatch" ? "[✗ sender mismatch]" : "[✗ invalid signature]";
4172
+ else if (result?.plaintext !== void 0) {
2475
4173
  ingestSenderKeyDistribution(configDir, agentId, data.type ?? "", result);
2476
4174
  preview = `[${result.verified ? "✓" : "?"}] ${result.plaintext.slice(0, 60)}`;
4175
+ } else if (unavailable !== null) {
4176
+ preview = data.id ? `${SENDER_KEY_UNAVAILABLE_PREVIEW} rine message read ${data.id}` : SENDER_KEY_UNAVAILABLE_PREVIEW;
4177
+ notice = explain(unavailable.message).notice;
2477
4178
  } else if (DECRYPTABLE_VERSIONS.has(data.encryption_version ?? "")) preview = "[decrypt failed]";
2478
4179
  }
2479
- return `[${ts}] ${sender} \u2192 ${target}: ${preview}`;
4180
+ return {
4181
+ line: `[${ts}] ${sender} \u2192 ${target}: ${preview}`,
4182
+ notice
4183
+ };
2480
4184
  } catch {
2481
- return `[message] ${dataStr.slice(0, 80)}`;
4185
+ return {
4186
+ line: `[message] ${dataStr.slice(0, 80)}`,
4187
+ notice: null
4188
+ };
2482
4189
  }
2483
4190
  }
2484
4191
  function registerStream(program) {
2485
- 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) => {
4192
+ 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) => {
2486
4193
  try {
2487
4194
  const gOpts = program.opts();
2488
4195
  const configDir = resolveConfigDir();
2489
4196
  const apiUrl = resolveApiUrl();
2490
4197
  const { client, profileName, entry } = await createClient(configDir, apiUrl, gOpts.profile);
2491
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
4198
+ const { actingAgent } = actorLadder(namedActor(command, gOpts), client);
4199
+ const agentId = await actingAgent();
2492
4200
  let url = `${apiUrl}/agents/${agentId}/stream`;
2493
4201
  if (opts.persistent) url += "?persistent=true";
2494
4202
  const heartbeatTimeoutMs = Math.max(Number(opts.heartbeatTimeout) || 70, 10) * 1e3;
@@ -2497,6 +4205,7 @@ function registerStream(program) {
2497
4205
  let attempt = 0;
2498
4206
  let stopped = false;
2499
4207
  const refreshMargin = jitteredRefreshMargin();
4208
+ const explain = senderKeyExplainer();
2500
4209
  process.on("SIGINT", () => {
2501
4210
  stopped = true;
2502
4211
  process.exitCode = 0;
@@ -2549,7 +4258,10 @@ function registerStream(program) {
2549
4258
  id,
2550
4259
  data
2551
4260
  }));
2552
- } else if (event === "message") formatMessageLine(data, agentId, configDir, client).then((line) => console.log(line), () => console.log(`[message] ${data.slice(0, 80)}`));
4261
+ } else if (event === "message") formatMessageLine(data, agentId, configDir, client, explain).then(({ line, notice }) => {
4262
+ if (notice !== null) printError(notice);
4263
+ console.log(line);
4264
+ }, () => console.log(`[message] ${data.slice(0, 80)}`));
2553
4265
  else if (event === "heartbeat" && opts.verbose) process.stderr.write(`[heartbeat] ${data}\n`);
2554
4266
  },
2555
4267
  onDisconnect: () => {
@@ -2650,9 +4362,8 @@ function printResult(result) {
2650
4362
  console.log(` Verified at: ${result.verified_at}`);
2651
4363
  }
2652
4364
  function registerVerifyIdentity(program) {
2653
- 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) => {
2654
- const agents = await fetchAgents(ctx.client);
2655
- const agentId = await resolveAgent(ctx.apiUrl, agents, opts.agent, ctx.gOpts.as);
4365
+ 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) => {
4366
+ const agentId = await ctx.actingAgent();
2656
4367
  const result = await verifyIdentitySpiffe(ctx.client, agentId, { svid: opts.svid });
2657
4368
  if (ctx.gOpts.json) printJson(result);
2658
4369
  else printResult(result);
@@ -2665,8 +4376,8 @@ function csv(raw) {
2665
4376
  }
2666
4377
  function registerWallet(program) {
2667
4378
  const wallet = program.command("wallet").description("Manage the agent payment wallet and spend policy (x402)");
2668
- 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) => {
2669
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
4379
+ wallet.command("create").description("Create a payment wallet for an agent (refuses to overwrite)").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
4380
+ const agentId = await actingAgent();
2670
4381
  if (walletKeyExists(configDir, agentId)) {
2671
4382
  printError(`Wallet already exists for agent ${agentId}. The private key is never overwritten.`);
2672
4383
  process.exitCode = 1;
@@ -2685,8 +4396,8 @@ function registerWallet(program) {
2685
4396
  Value: address
2686
4397
  }]);
2687
4398
  }));
2688
- 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) => {
2689
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
4399
+ wallet.command("address").description("Print an agent's payment wallet address").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
4400
+ const agentId = await actingAgent();
2690
4401
  if (!walletKeyExists(configDir, agentId)) {
2691
4402
  printError(`No wallet for agent ${agentId}. Run 'rine wallet create' first.`);
2692
4403
  process.exitCode = 1;
@@ -2699,8 +4410,8 @@ function registerWallet(program) {
2699
4410
  });
2700
4411
  else printTable([{ "Wallet address": address }]);
2701
4412
  }));
2702
- 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) => {
2703
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
4413
+ wallet.command("policy").description("Show the effective spend policy (deny-by-default when unset)").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
4414
+ const agentId = await actingAgent();
2704
4415
  const p = loadPolicy(configDir, agentId);
2705
4416
  if (gOpts.json) {
2706
4417
  printJson({
@@ -2746,8 +4457,8 @@ function registerWallet(program) {
2746
4457
  Value: p.allowedNetworks.join(", ") || "—"
2747
4458
  }
2748
4459
  ]);
2749
- })).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) => {
2750
- savePolicy(configDir, await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as), {
4460
+ })).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) => {
4461
+ savePolicy(configDir, await actingAgent(), {
2751
4462
  perTxCap: opts.perTxCap,
2752
4463
  dailyCap: opts.dailyCap,
2753
4464
  allowedAssets: csv(opts.allowedAssets),
@@ -2761,13 +4472,13 @@ function registerWallet(program) {
2761
4472
  //#region src/commands/webhook.ts
2762
4473
  function registerWebhook(program) {
2763
4474
  const webhook = program.command("webhook").description("Manage webhooks");
2764
- 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) => {
4475
+ 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) => {
2765
4476
  if (!opts.url.startsWith("https://")) {
2766
4477
  printError("Webhook URL must start with https://");
2767
4478
  process.exitCode = 2;
2768
4479
  return;
2769
4480
  }
2770
- const agentId = await resolveAgent(apiUrl, await fetchAgents(client), opts.agent, gOpts.as);
4481
+ const agentId = await actingAgent();
2771
4482
  const data = await client.post("/webhooks", {
2772
4483
  agent_id: agentId,
2773
4484
  url: opts.url
@@ -2830,7 +4541,7 @@ function registerWebhook(program) {
2830
4541
  //#endregion
2831
4542
  //#region src/main.ts
2832
4543
  const { version } = createRequire(import.meta.url)("../package.json");
2833
- 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)");
4544
+ 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)");
2834
4545
  registerAuth(program);
2835
4546
  registerRegister(program);
2836
4547
  registerOnboard(program);