@rine-network/cli 0.24.0 → 0.25.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 +44 -1
  2. package/dist/main.js +1676 -927
  3. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -1,13 +1,41 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { Command, Option } from "commander";
3
- import { A2A_CLEARTEXT_NOTICE, ACTING_AGENT_ENV, ACTING_AGENT_HEADER, ACTOR_SURFACES, BindNakReason, CLOSE_SUSPENDED, DEFAULT_PROFILE, Decision, DelegateScope, ENCRYPTION_VERSION_HYBRID_V2, EXPOSURE_COPY, FUNNEL_TIERS, GROUP_NOT_FOUND_LEAD, GROUP_READERS_NOTICE, HeadFault, HttpClient, IdempotencyStore, KEY_NOT_CURRENT_MESSAGE, KeyPackageRotation, MLS_ERR_GROUP_INACTIVE, MLS_EVICTED_BY_COMMIT, MalformedPageError, MessageDefault, MlsEstablishStep, MlsInitInFlightError, OrgReader, PHRASE_FILE, PHRASE_INSTRUCTION, PRESETS, PolicyRule, Preset, PrincipalKind, RULE_MODES, ReadGapReason, ReadKey, ReaderNetworkError, RineApiError, RuleDirection, RuleMode, SENDER_KEY_UNAVAILABLE_CODE, SENDER_KEY_UNAVAILABLE_PREVIEW, SeatUpdateStatus, SignalClass, Surface, THREAD_REF_SURFACES, THREAD_UNAVAILABLE, TokenBucket, TunnelBindError, UUID_RE, VOTE_DURATION_RULE, VOTE_ELECTORATE_RULE, X402Error, X402FacilitatorError, X402_ERROR, X402_MESSAGE_TYPE, a2aCleartextMark, a2aCleartextPayload, a2aCleartextPlaintext, aboveCeilingLine, ackAfterRead, ackFailureNotice, actorFromEnv, addDomain, addMlsGroupMembers, addProfileIfAbsent, admissionHeadline, admittedAgentIds, agentKeysExist, agentKeysFromPrivate, agentLabel, asSenderKeyUnavailable, assertBranchName, assertGroupPostable, assertNoMlsDowngrade, buildIssueCertDeps, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildPeerVerification, buildReceiptMessage, cappedLine, ceilingLine, cliSyncRemedy, clipToWidth, clipWithEllipsis, clusterWidth, compareVerificationWordsForAgent, connectTunnel, controlFrameReplyRefusal, createAckBatcher, createBranch, createDelegate, createHook, createWallet, createdPrivateLine, decryptGroupMessageWithRecovery, decryptMessage, decryptThreadRows, deleteAllow, deleteGroupMember, deleteHookSecret, deriveBranch, describeEscrowGaps, describeMlsReclamation, describeMlsRecovery, describeVoteEligibility, displayHandle, displayWidth, encryptGroupMessage, encryptionLine, ensureCert, establishMlsMembership, evictionMessage, fetchAgents, fetchAllAllow, fetchCounterparties, fetchGroupMembers, fetchHeadKeys, fetchLogSettings, fetchOrgEventHead, fetchOrgEvents, fetchOrgMetadata, findingKey, fitFromTo, fitGroupSender, forkPointOf, formatError, freezeOrg, fromBase64Url, gapToJson, getExposure, getOrCreateSenderKey, getOrRefreshToken, getOrgExposure, getPolicy, getProfile, getSuspension, getWalletAddress, graphemes, groupAcceptsMlsSendOnly, groupAdmissionSkipSentence, groupAuthenticityStatus, groupEncryption, groupEncryption as groupEncryption$1, groupIsMls, groupMlsInitInFlight, handleCompletionNote, handleWebhookRequest, hasRoot, hasSpiffeEndpoint, holdOf, holdsAnyMlsState, holdsBranchKeys, holdsMlsState, hookNameError, humanTime, impliedVoteEligibilityReason, inBackground, ingestSenderKeyDistribution, initMlsGroup, invalidSurfaces, inviteNominates, isA2aCleartext, isAuthenticityFailure, isAutoPayable, isControlFrameType, isDecryptableVersion, isEpochConflict, isGroupEncryptionVersion, isMlsResyncUnavailable, isMlsRotatedLeaf, isNamedPreset, isPathSafeId, isRecoverableMlsRead, isRefusalStatus, isSettledRow, isX402MessageType, jcsCanonicalize, jitteredDelayMs, jitteredRefreshMargin, listAgentStates, listDelegates, listDomains, listMyInvites, loadAgentKeys, loadHookSecret, loadMeta, loadMlsGroup, loadMlsState, loadOrgFromOwner, loadPolicy, loadProfiles, loadSenderKeyStates, loadTokenCache, loadWalletKey, lookupCounterparty, makeEdgePipeFactory, markA2aCleartext, markDeliveredAs, matchedQuoteToWire, messageToJson, mlsAdmissionSkipSentence, mlsErrorCode, mlsInitInFlightSync, mlsReadRefusal, namesASeatedSibling, newDelegateKey, nextReconnectBackoffSeconds, normalizeActor, normalizeHandle, openMlsClient, orgIdOfAgent, orgSummaryLine, orgWords, ownIdentityFor, parseFacilitatorHeaders, parseRecipientKey, parseX402Payload, patchRules, peerVerificationLines, performAgentCreation, performRecovery, performRegistration, pickAgent, postingLine, presetLine, presetOf, previewExposure, previewLines, previewRule, principalString, putAllow, putExposure, putLogSettings, raceDeadline, readDailySpent, readOwnerPhrase, readThreadPage, readableGroupById, recipientKeyWords, recordPeerVerification, recoverGroup, refusalReceiptBody, refusedLine, removeDomain, renewalDueWithJitter, reportFailedSetup, requireVerifiedPlaintext, reserveSpend, resolveAgent, resolveApiUrl, resolveAuth, resolveConfigDir, resolveFacilitatorConfig, resolveGroup, resolveGroupByHandle, resolveGroupForJoin, resolveHandleViaWebFinger, resolveOwnerDir, resolvePayeeRequirement, resolveThreadRef, resolveToUuid, restoreOwnerFromPhrase, resumeAgent, resumeBranch, resumeMlsGroupAdmission, retireLocalGroupState, retirementMessage, retryAfterMsFromError, revokeBranch, revokeDelegate, rotateAgentWithSeats, safeBlock, saveAgentKeys, saveDelegateSeed, savePolicy, saveProfiles, saveTokenCache, scrub, sealAndPostMlsGroupMessage, sealBranchBundle, sealForAgent, seatUpdateLine, seatedMemberAfterConflict, selectRequirement, sendGroupInviteNotification, sendReceipt, senderKeyExplainer, settleToReceipt, signalClass, singleActorValue, sleep, sleepWithSignal, startTlsListener, startupEscrowSweep, stopExisting, summaryLine, suspendAgent, suspendBranch, switchLines, toBase64Url, unfreezeOrg, unreadableByOrgsSentence, validateEncryptionKey, validateSigningKey, validateSlug, verificationWordsLines, verifyDomain, verifyHead, verifyIdentitySpiffe, walletKeyExists, withA2aCleartextNotice, withEvictionPointer, withPeekHeader, writeAtomic } from "@rine-network/core";
3
+ import * as core from "@rine-network/core";
4
+ import { A2A_CLEARTEXT_NOTICE, ACTING_AGENT_ENV, ACTING_AGENT_HEADER, ACTOR_SURFACES, ADOPT_COMMAND, AGENT_ONLY_ENV, AGENT_ONLY_LIST_NOTICE, AdminTierUnavailableError, CARRIED_NOMINATION_SENTENCE, ConsentEnvError, DEFAULT_PROFILE, Decision, DelegateScope, ENCRYPTION_VERSION_HYBRID_V2, EXPOSURE_COPY, EmptyHookSecretError, FUNNEL_TIERS, GROUP_NOT_FOUND_LEAD, GROUP_READERS_NOTICE, HeadFault, HttpClient, IDENTITY_FILE, IdentityFileError, KEY_NOT_CURRENT_MESSAGE, KeyPackageRotation, MLS_ERR_GROUP_INACTIVE, MalformedPageError, MessageDefault, MlsEstablishStep, MlsInitInFlightError, OpTier, OrgReader, PAY_CONFIRM_WHY, PHRASE_FILE, PHRASE_INSTRUCTION, PRESETS, PROFILES_FILE, PROJECT_ENTRY_PREFIX, PolicyRule, Preset, PrincipalKind, ProjectDirRefusalCode, RULE_MODES, ReadGapReason, ReadKey, ReaderNetworkError, RelayFatalError, RineApiError, RuleDirection, RuleMode, SENDER_KEY_UNAVAILABLE_CODE, SENDER_KEY_UNAVAILABLE_PREVIEW, SeatUpdateStatus, SignalClass, StoredPolicyKind, Surface, THREAD_REF_SURFACES, THREAD_UNAVAILABLE, Tier, TokenBucket, UUID_RE, UnsupportedTierError, VOTE_DURATION_RULE, VOTE_ELECTORATE_RULE, X402Error, X402FacilitatorError, X402_ERROR, X402_MESSAGE_TYPE, a2aCleartextMark, a2aCleartextPayload, a2aCleartextPlaintext, aboveCeilingLine, ackAfterRead, ackFailureNotice, actingRoster, actorFromEnv, addDomain, addMlsGroupMembers, addProfileIfAbsent, admissionHeadline, admittedAgentIds, agentKeysExist, agentKeysFromPrivate, agentOnlyFromEnv, asSenderKeyUnavailable, assertBranchName, assertGroupPostable, assertNoMlsDowngrade, assertOwnerDirAllowed, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildPeerVerification, buildReceiptMessage, cappedLine, catchUpFields, catchUpNote, ceilingLine, checkIdentityCopy, cliSyncRemedy, clipToWidth, clipWithEllipsis, clusterWidth, compareVerificationWordsForAgent, configDirAt, controlFrameReplyRefusal, createAckBatcher, createBranch, createDelegate, createHook, createTierTokenFn, createWallet, createdPrivateLine, decryptGroupMessageWithRecovery, decryptMessage, decryptThreadRows, deleteAllow, deleteGroupMember, deleteHook, deleteHookSecret, deriveBranch, describeEscrowGaps, describeMlsReclamation, describeMlsRecovery, describeProjectDirIdentity, describeTiers, describeVoteEligibility, displayHandle, displayWidth, encryptGroupMessage, encryptionLine, establishMlsMembership, evictionMessage, fetchAllAllow, fetchCounterparties, fetchGroupMembers, fetchHeadKeys, fetchLogSettings, fetchOrgEventHead, fetchOrgEvents, fetchOrgMetadata, findOrgAgent, findingKey, fitFromTo, fitGroupSender, forgetBoundDir, forkPointOf, formatError, freezeOrg, fromBase64Url, gapToJson, getExposure, getOrCreateSenderKey, getOrRefreshToken, getOrgExposure, getPolicy, getProfile, getSuspension, getWalletAddress, graphemes, groupAcceptsMlsSendOnly, groupAdmissionSkipSentence, groupAuthenticityStatus, groupEncryption, groupEncryption as groupEncryption$1, groupIsMls, groupMlsInitInFlight, handleCompletionNote, hasRoot, hasSpiffeEndpoint, holdsAnyMlsState, holdsBranchKeys, holdsMlsState, hookNameError, hookNamePatternError, humanTime, identityStoreDir, impliedVoteEligibilityReason, inBackground, ingestSenderKeyDistribution, initMlsGroup, invalidHookNameMessage, invalidSurfaces, inviteNominates, isA2aCleartext, isAuthenticityFailure, isAutoPayable, isControlFrameType, isDecryptableVersion, isEpochConflict, isGroupEncryptionVersion, isMlsResyncUnavailable, isMlsRotatedLeaf, isNamedPreset, isPathSafeId, isRecoverableMlsRead, isSettledRow, isX402MessageType, jcsCanonicalize, jitteredDelayMs, jitteredRefreshMargin, leadsNowhere, linksToProjectEntry, listAgentStates, listDelegates, listDomains, listHooks, listMyInvites, listOperations, loadAgentKeys, loadHookSecret, loadMlsGroup, loadMlsState, loadOrgFromOwner, loadPolicy, loadPolicyWithTrust, loadProfiles, loadSenderKeyStates, loadTokenCache, loadWalletKey, localActorId, lookupCounterparty, markA2aCleartext, markDeliveredAs, matchedQuoteToWire, messageToJson, missingKeysMessage, mlsAdmissionSkipSentence, mlsErrorCode, mlsInitInFlightSync, mlsReadRefusal, namesASeatedSibling, newDelegateKey, nextReconnectBackoffSeconds, normalizeActor, normalizeHandle, openMlsClient, operationByCli, orgIdOfAgent, orgRosterClient, orgSummaryLine, orgWords, ownIdentityFor, ownedByUs, ownerStoreDir, parseFacilitatorHeaders, parsePort, parseRecipientKey, parseX402Payload, patchRules, paymentConfirmReason, peerVerificationLines, performAgentCreation, performRecovery, performRegistration, pickAgent, postingLine, presetLine, presetOf, previewExposure, previewLines, previewRule, principalString, projectDirIdentity, projectLinkPath, projectLinkRefusal, putAllow, putExposure, putLogSettings, raceDeadline, readBoundDirs, readDailySpent, readIdentityFile, readOwnerPhrase, readProjectIdentityFile, readStoredPolicy, readThreadPage, readableGroupById, recipientKeyWords, recordBoundDir, recordPeerVerification, recoverGroup, recoveredCatchUp, refusalReceiptBody, refusedLine, relaySeams, removeAgentKeys, removeDomain, reportFailedSetup, reportedCatchUp, requireVerifiedPlaintext, requirementAmount, reserveSpend, resolveAgent, resolveApiUrl, resolveAuth, resolveConfigDir, resolveFacilitatorConfig, resolveGroup, resolveGroupByHandle, resolveGroupForJoin, resolveHandleViaWebFinger, resolveOwnerDir, resolvePayeeRequirement, resolveThreadRef, resolveToUuid, restoreAgentInto, restoreOwnerFromPhrase, resumeAgent, resumeBranch, resumeMlsGroupAdmission, retireLocalGroupState, retirementMessage, retryAfterMsFromError, revokeBranch, revokeDelegate, rotateAgentWithSeats, runRelay, safeBlock, saveAgentKeys, saveDelegateSeed, savePolicy, savePolicyUnlessSigned, saveProfiles, saveSignedPolicy, saveTokenCache, scrub, sealAndPostMlsGroupMessage, sealBranchBundle, sealForAgent, sealedX402Body, seatUpdateLine, seatedMemberAfterConflict, selectRequirement, sendGroupInviteNotification, sendReceipt, senderKeyExplainer, settleToReceipt, signPolicy, signalClass, singleActorValue, sleepWithSignal, spendPolicyModeFromEnv, splitThreadCatchUp, startupEscrowSweep, stopExisting, summaryLine, suspendAgent, suspendBranch, switchLines, toBase64Url, unfreezeOrg, unreadableByOrgsSentence, validateEncryptionKey, validateSigningKey, validateSlug, verificationWordsLines, verifyDomain, verifyHead, verifyIdentitySpiffe, walletKeyExists, withA2aCleartextNotice, withEvictionPointer, withPeekHeader, writableByOthers, writeAtomic, writeIdentityFile } from "@rine-network/core";
4
5
  import * as fs$1 from "node:fs";
5
6
  import fs, { readFileSync } from "node:fs";
6
7
  import readline from "node:readline";
7
- import { join } from "node:path";
8
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
8
9
  import { createHash, randomBytes } from "node:crypto";
9
10
  import { resolve4 } from "node:dns/promises";
10
11
  import { createEventSource } from "eventsource-client";
12
+ //#region src/agent-only.ts
13
+ /** The space-joined command path (`"group create"`): the key the operation catalog uses. */
14
+ function commandPath(command) {
15
+ const names = [];
16
+ for (let node = command; node?.parent; node = node.parent) names.unshift(node.name());
17
+ return names.join(" ");
18
+ }
19
+ /**
20
+ * Under `RINE_AGENT_ONLY` a command whose operation is not Agent tier is refused before it
21
+ * runs: it would need the org root, which an agent-only runtime never loads. A command the
22
+ * catalog does not know is left to run, because the catalog gate keeps every command mapped.
23
+ * With the variable unset the hook does nothing.
24
+ */
25
+ function refuseOutsideAgentTier(program) {
26
+ program.hook("preAction", (_, action) => {
27
+ try {
28
+ if (!agentOnlyFromEnv()) return;
29
+ } catch (err) {
30
+ if (!(err instanceof ConsentEnvError)) throw err;
31
+ program.error(err.message, { exitCode: 1 });
32
+ }
33
+ const path = commandPath(action);
34
+ const tier = operationByCli(path)?.tier;
35
+ if (tier !== void 0 && tier !== OpTier.Agent) program.error(`rine ${path} needs the org, and ${AGENT_ONLY_ENV}=1 keeps this runtime to its own agent: run it where the org root lives.`, { exitCode: 1 });
36
+ });
37
+ }
38
+ //#endregion
11
39
  //#region src/output.ts
12
40
  function printSuccess(msg) {
13
41
  console.log(`✓ ${msg}`);
@@ -100,15 +128,17 @@ function blameEnvActor(err) {
100
128
  * *elsewhere*, and an acting agent is always one of this org's own.
101
129
  */
102
130
  function actorLadder(flagged, client, headers) {
131
+ const fromEnv = flagged === void 0 ? actorFromEnv() : void 0;
132
+ const named = flagged ?? fromEnv;
103
133
  let agentList;
104
134
  const agents = () => {
105
- agentList ??= fetchAgents(client);
135
+ agentList ??= actingRoster(client, named);
106
136
  return agentList;
107
137
  };
108
- const fromEnv = flagged === void 0 ? actorFromEnv() : void 0;
109
- const named = flagged ?? fromEnv;
110
138
  const resolve = async () => {
111
139
  if (named !== void 0 && UUID_RE.test(named)) return named;
140
+ const local = localActorId(client, named);
141
+ if (local !== void 0) return local;
112
142
  const list = await agents();
113
143
  let resolved;
114
144
  try {
@@ -260,39 +290,88 @@ function namedActor(command, gOpts) {
260
290
  }]);
261
291
  }
262
292
  //#endregion
263
- //#region src/action.ts
264
- /** The runtime config dir and the owner dir, as the environment resolves them. */
293
+ //#region src/dirs.ts
294
+ /**
295
+ * The config dir's files and the owner dir that holds the org root: what the
296
+ * commands that read the org root (the Admin tier) take.
297
+ */
298
+ function custodyDirsOf(dir) {
299
+ return {
300
+ configDir: dir.path,
301
+ ownerDir: resolveOwnerDir(dir)
302
+ };
303
+ }
304
+ /**
305
+ * What a command signs from: the runtime dir alone under `RINE_AGENT_ONLY`, else
306
+ * the custody dirs.
307
+ */
308
+ function authDirsOf(dir) {
309
+ return agentOnlyFromEnv() ? {
310
+ configDir: dir.path,
311
+ agentOnly: true
312
+ } : custodyDirsOf(dir);
313
+ }
314
+ /** {@link custodyDirsOf} for the dir the environment resolves, for a command that shows nothing of it. */
315
+ function resolveCustodyDirs() {
316
+ return custodyDirsOf(resolveConfigDir());
317
+ }
318
+ /** {@link authDirsOf} for the dir the environment resolves, for a command that shows nothing of it. */
265
319
  function resolveDirs() {
320
+ return authDirsOf(resolveConfigDir());
321
+ }
322
+ /** The dirs of an org-level command: the owner dir holds `root.key`. Throws under `RINE_AGENT_ONLY`. */
323
+ function custodyOf(dirs) {
324
+ if (dirs.agentOnly === true) throw new AdminTierUnavailableError();
325
+ return dirs;
326
+ }
327
+ //#endregion
328
+ //#region src/tier-client.ts
329
+ /**
330
+ * A client that signs each request as the least principal that may make it
331
+ * (`createTierTokenFn`), and the tier resolution behind it. `identity` is the
332
+ * principal the dir acts as day to day: its agent, else the admin principal.
333
+ * It reads the org root only when the dir holds no agent profile.
334
+ */
335
+ function buildTierClient(opts) {
336
+ const { dirs, apiUrl, profile, defaultHeaders, refreshMargin } = opts;
337
+ const tier = createTierTokenFn(dirs, apiUrl, profile, { refreshMargin });
338
+ const identity = tier.agentAuth() ?? tier.adminAuth();
266
339
  return {
267
- configDir: resolveConfigDir(),
268
- ownerDir: resolveOwnerDir()
269
- };
270
- }
271
- async function createClient(apiUrl, profileFlag, defaultHeaders) {
272
- const dirs = resolveDirs();
273
- const profileName = profileFlag ?? DEFAULT_PROFILE;
274
- const auth = resolveAuth(dirs, profileFlag);
275
- const envToken = process.env.RINE_TOKEN;
276
- const token = (opts = {}) => getOrRefreshToken(auth?.cacheDir ?? dirs.configDir, apiUrl, auth?.signer, {
277
- force: opts.force ?? false,
278
- envToken,
340
+ client: new HttpClient({
341
+ tokenFn: tier.tokenFn,
342
+ localAgent: tier.localAgent,
343
+ canRefresh: tier.canRefresh,
344
+ apiUrl,
345
+ defaultHeaders,
346
+ ownIdentity: ownIdentityFor(dirs.configDir, identity)
347
+ }),
348
+ tier,
349
+ identity
350
+ };
351
+ }
352
+ //#endregion
353
+ //#region src/action.ts
354
+ async function createClient(opts) {
355
+ const dir = opts.dir ?? resolveConfigDir();
356
+ const dirs = authDirsOf(dir);
357
+ const { client, tier, identity } = buildTierClient({
358
+ dirs,
359
+ apiUrl: opts.apiUrl,
360
+ profile: opts.profile,
361
+ defaultHeaders: opts.defaultHeaders,
279
362
  refreshMargin: opts.refreshMargin
280
363
  });
281
- const tokenFn = (force = false) => token({ force });
282
- const client = new HttpClient({
283
- tokenFn,
284
- apiUrl,
285
- canRefresh: !envToken,
286
- defaultHeaders,
287
- ownIdentity: ownIdentityFor(dirs.configDir, auth)
364
+ const tokenFor = (actor) => ({ force = false } = {}) => tier.tokenFn(force, {
365
+ tier: Tier.Agent,
366
+ actor
288
367
  });
289
- inBackground(() => startupEscrowSweep(client, dirs.configDir, auth?.agentId));
368
+ inBackground(() => startupEscrowSweep(client, dirs.configDir, identity?.agentId));
290
369
  return {
291
370
  client,
292
- profileName,
371
+ profileName: opts.profile ?? DEFAULT_PROFILE,
372
+ dir,
293
373
  dirs,
294
- auth,
295
- token
374
+ tokenFor
296
375
  };
297
376
  }
298
377
  function withClient(program, fn, precheck) {
@@ -310,16 +389,25 @@ function withClient(program, fn, precheck) {
310
389
  const flagged = namedActor(commandOf(args), gOpts);
311
390
  const apiUrl = resolveApiUrl();
312
391
  const defaultHeaders = {};
313
- const { client, profileName, dirs, auth } = await createClient(apiUrl, gOpts.profile, defaultHeaders);
392
+ const { client, profileName, dir, dirs } = await createClient({
393
+ apiUrl,
394
+ profile: gOpts.profile,
395
+ defaultHeaders
396
+ });
314
397
  const { named, agents, actingAgent } = actorLadder(flagged, client, defaultHeaders);
315
398
  if (named !== void 0) await actingAgent();
399
+ let admin;
316
400
  await fn({
317
401
  client,
318
402
  gOpts,
319
403
  profileName,
320
- configDir: dirs.configDir,
321
- ownerDir: dirs.ownerDir,
322
- auth,
404
+ dir,
405
+ dirs,
406
+ custody: () => custodyOf(dirs),
407
+ get auth() {
408
+ admin ??= resolveAuth(dirs, gOpts.profile);
409
+ return admin;
410
+ },
323
411
  apiUrl,
324
412
  extraHeaders: defaultHeaders,
325
413
  agents,
@@ -651,7 +739,7 @@ function announceExposure(agent, asked) {
651
739
  //#endregion
652
740
  //#region src/commands/agent-create.ts
653
741
  function registerAgentCreate(agent, program) {
654
- agent.command("create").description("Create a new agent").option("--name <name>", "Agent name").option("--[no-]human-oversight", "Require human oversight (default: true)").option("--unlisted", "Mark agent as unlisted (not in public directory)").option("--exposure <preset>", EXPOSURE_OPTION_HELP).action(withClient(program, async ({ client, gOpts, configDir, ownerDir }, opts) => {
742
+ agent.command("create").description("Create a new agent").option("--name <name>", "Agent name").option("--[no-]human-oversight", "Require human oversight (default: true)").option("--unlisted", "Mark agent as unlisted (not in public directory)").option("--exposure <preset>", EXPOSURE_OPTION_HELP).action(withClient(program, async ({ client, gOpts, custody }, opts) => {
655
743
  const exposure = exposurePreset(opts.exposure);
656
744
  let name = opts.name;
657
745
  if (!name) {
@@ -663,10 +751,9 @@ function registerAgentCreate(agent, program) {
663
751
  }
664
752
  }
665
753
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
666
- const data = await performAgentCreation(client, {
667
- configDir,
668
- ownerDir
669
- }, profile, {
754
+ const dirs = custody();
755
+ const { configDir } = dirs;
756
+ const data = await performAgentCreation(client, dirs, profile, {
670
757
  name,
671
758
  humanOversight: opts.humanOversight,
672
759
  unlisted: opts.unlisted,
@@ -847,7 +934,7 @@ function announceHandleCompletion(spelling) {
847
934
  * and still sends — this is a display of key agreement, not an access control.
848
935
  */
849
936
  function registerAgentVerify(program, agent) {
850
- 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) => {
937
+ 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, dirs: { configDir }, apiUrl, actingAgent, agents }, peer, opts) => {
851
938
  const ownId = await actingAgent();
852
939
  const own = (await agents()).find((a) => a.id === ownId);
853
940
  announceHandleCompletion(peer);
@@ -907,7 +994,9 @@ function registerAgent(program) {
907
994
  const agent = program.command("agent").description("Agent management");
908
995
  agent.command("list").description("List all agents").option("--include-revoked", "Include revoked agents").action(withClient(program, async ({ client, gOpts }, opts) => {
909
996
  const params = opts.includeRevoked ? { include_revoked: true } : void 0;
910
- const data = await client.get("/agents", params);
997
+ const agentOnly = agentOnlyFromEnv();
998
+ const data = await orgRosterClient(client, agentOnly).get("/agents", params);
999
+ if (agentOnly) process.stderr.write(`${AGENT_ONLY_LIST_NOTICE}\n`);
911
1000
  if (gOpts.json) printJson(data);
912
1001
  else printTable(data.items.map((a) => toAgentRow(a, { includeRevoked: opts.includeRevoked })));
913
1002
  }));
@@ -957,6 +1046,62 @@ function registerAgent(program) {
957
1046
  registerAgentExposure(agent, program);
958
1047
  }
959
1048
  //#endregion
1049
+ //#region src/commands/whoami-fields.ts
1050
+ /** `dir.path` is where the config dir's files are read; `dir.shown` is the dir as found, which is what the table shows. */
1051
+ function dirFacts(dirs, dir, profile) {
1052
+ const copy = checkIdentityCopy(dirs.configDir);
1053
+ const refused = dir.refused ?? [];
1054
+ return {
1055
+ config_dir: dir.path,
1056
+ config_dir_shown: dir.shown,
1057
+ source: dir.source,
1058
+ tiers: describeTiers(dirs, profile),
1059
+ ...dirs.agentOnly === true && { agent_only: true },
1060
+ ...copy !== void 0 && { copied_from: copy.copiedFrom },
1061
+ ...refused.length > 0 && { refused_project_dirs: [...refused] }
1062
+ };
1063
+ }
1064
+ const AGENT_ONLY_MODE = `agent-only (${AGENT_ONLY_ENV}): this process signs as its own agent and never as the org`;
1065
+ /** Where the dir is and why it was chosen: the rows even a dir with no identity can print. */
1066
+ function locationRows(facts) {
1067
+ return [
1068
+ {
1069
+ Field: "Config dir",
1070
+ Value: facts.config_dir_shown
1071
+ },
1072
+ ...facts.config_dir === facts.config_dir_shown ? [] : [{
1073
+ Field: "Stored at",
1074
+ Value: facts.config_dir
1075
+ }],
1076
+ {
1077
+ Field: "Source",
1078
+ Value: facts.source
1079
+ },
1080
+ ...(facts.refused_project_dirs ?? []).map(({ dir, reason, copied_from, also_bound_at }) => ({
1081
+ Field: "Skipped",
1082
+ Value: `${dir} (${reason}${copied_from === void 0 ? "" : `; copied from ${copied_from}`}${also_bound_at === void 0 ? "" : `; also bound at ${also_bound_at}`})`
1083
+ }))
1084
+ ];
1085
+ }
1086
+ /** The rows `whoami` and `identity show` both print for {@link DirFacts}. */
1087
+ function dirFactRows(facts) {
1088
+ return [
1089
+ ...locationRows(facts),
1090
+ ...facts.agent_only === true ? [{
1091
+ Field: "Mode",
1092
+ Value: AGENT_ONLY_MODE
1093
+ }] : [],
1094
+ {
1095
+ Field: "Admin",
1096
+ Value: facts.tiers.admin ?? "-"
1097
+ },
1098
+ ...facts.copied_from === void 0 ? [] : [{
1099
+ Field: "Copied from",
1100
+ Value: facts.copied_from
1101
+ }]
1102
+ ];
1103
+ }
1104
+ //#endregion
960
1105
  //#region src/commands/whoami.ts
961
1106
  /**
962
1107
  * Where this agent's keys are. The server serves the keys of every agent it
@@ -970,108 +1115,115 @@ function keysLabel(hasLocal, serverKnows) {
970
1115
  return hasLocal ? "local + server" : "server only";
971
1116
  }
972
1117
  function registerWhoami(program) {
973
- program.command("whoami").description("Show current identity and status").action(async () => {
974
- const gOpts = program.opts();
1118
+ program.command("whoami").description("Show current identity and status").action(withErrorHandler(program, async (gOpts) => {
975
1119
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
976
- const dirs = resolveDirs();
1120
+ const dir = resolveConfigDir();
1121
+ const dirs = authDirsOf(dir);
977
1122
  const apiUrl = resolveApiUrl();
978
- const auth = resolveAuth(dirs, gOpts.profile);
979
- if (!auth) {
980
- if (gOpts.json) printJson({ logged_in: false });
1123
+ const facts = dirFacts(dirs, dir, gOpts.profile);
1124
+ const defaultHeaders = {};
1125
+ const { client, identity } = buildTierClient({
1126
+ dirs,
1127
+ apiUrl,
1128
+ profile: gOpts.profile,
1129
+ defaultHeaders
1130
+ });
1131
+ if (identity === void 0) {
1132
+ if (gOpts.json) printJson({
1133
+ logged_in: false,
1134
+ config_dir: facts.config_dir,
1135
+ config_dir_shown: facts.config_dir_shown,
1136
+ source: facts.source,
1137
+ ...facts.refused_project_dirs !== void 0 && { refused_project_dirs: facts.refused_project_dirs }
1138
+ });
981
1139
  else printTable([{
982
1140
  Field: "Status",
983
1141
  Value: "not logged in"
984
- }]);
1142
+ }, ...locationRows(facts)]);
985
1143
  return;
986
1144
  }
1145
+ const { agents, actingAgent } = actorLadder(namedActor(void 0, gOpts), client, defaultHeaders);
1146
+ const { org, agents: orgAgents } = await client.get("/whoami");
1147
+ const roster = await agents();
1148
+ let agentId;
987
1149
  try {
988
- const token = await getOrRefreshToken(auth.cacheDir, apiUrl, auth.signer, {});
989
- const defaultHeaders = {};
990
- const client = new HttpClient({
991
- tokenFn: () => Promise.resolve(token),
992
- apiUrl,
993
- canRefresh: false,
994
- defaultHeaders,
995
- ownIdentity: ownIdentityFor(dirs.configDir, auth)
996
- });
997
- const { agents, actingAgent } = actorLadder(namedActor(void 0, gOpts), client, defaultHeaders);
998
- const { org } = await client.get("/whoami");
999
- let agentHandle;
1000
- let agentId;
1001
- let keys;
1150
+ agentId = await actingAgent();
1151
+ } catch {}
1152
+ let agentHandle;
1153
+ let keys;
1154
+ let humanOversight;
1155
+ if (agentId !== void 0) {
1156
+ agentHandle = roster.find((a) => a.id === agentId)?.handle ?? void 0;
1157
+ humanOversight = orgAgents.find((a) => a.id === agentId)?.human_oversight;
1158
+ const hasLocal = agentKeysExist(dirs.configDir, agentId);
1159
+ let serverKnows;
1002
1160
  try {
1003
- agentId = await actingAgent();
1004
- agentHandle = (await agents()).find((a) => a.id === agentId)?.handle ?? void 0;
1005
- const hasLocal = agentKeysExist(dirs.configDir, agentId);
1006
- let serverKnows;
1007
- try {
1008
- await client.get(`/agents/${agentId}/keys`);
1009
- serverKnows = true;
1010
- } catch (err) {
1011
- if (err instanceof RineApiError && err.status === 404) serverKnows = false;
1012
- }
1013
- keys = keysLabel(hasLocal, serverKnows);
1014
- } catch {}
1015
- const principal = principalString(auth.signer.principal);
1016
- if (gOpts.json) printJson({
1017
- profile,
1018
- api: apiUrl,
1019
- principal,
1020
- org: {
1021
- name: org.name,
1022
- slug: org.slug
1161
+ await client.get(`/agents/${agentId}/keys`);
1162
+ serverKnows = true;
1163
+ } catch (err) {
1164
+ if (err instanceof RineApiError && err.status === 404) serverKnows = false;
1165
+ }
1166
+ keys = keysLabel(hasLocal, serverKnows);
1167
+ }
1168
+ const principal = principalString(identity.signer.principal);
1169
+ if (gOpts.json) printJson({
1170
+ profile,
1171
+ api: apiUrl,
1172
+ principal,
1173
+ ...facts,
1174
+ org: {
1175
+ name: org.name,
1176
+ slug: org.slug
1177
+ },
1178
+ trust_tier: org.trust_tier,
1179
+ ...agentId ? {
1180
+ agent: agentHandle ?? null,
1181
+ agent_id: agentId,
1182
+ keys,
1183
+ ...humanOversight !== void 0 && { human_oversight: humanOversight }
1184
+ } : {}
1185
+ });
1186
+ else {
1187
+ const rows = [
1188
+ {
1189
+ Field: "Profile",
1190
+ Value: profile
1023
1191
  },
1024
- trust_tier: org.trust_tier,
1025
- ...agentId ? {
1026
- agent: agentHandle ?? null,
1027
- agent_id: agentId,
1028
- keys
1029
- } : {}
1030
- });
1031
- else {
1032
- const rows = [
1033
- {
1034
- Field: "Profile",
1035
- Value: profile
1036
- },
1037
- {
1038
- Field: "API",
1039
- Value: apiUrl
1040
- },
1041
- {
1042
- Field: "Principal",
1043
- Value: principal
1044
- },
1045
- {
1046
- Field: "Org",
1047
- Value: `${org.name} (${org.slug})`
1048
- },
1049
- {
1050
- Field: "Trust Tier",
1051
- Value: String(org.trust_tier)
1052
- }
1053
- ];
1054
- if (agentId) {
1055
- rows.push({
1056
- Field: "Agent",
1057
- Value: agentHandle ?? "-"
1058
- });
1059
- rows.push({
1060
- Field: "Agent ID",
1061
- Value: agentId
1062
- });
1063
- rows.push({
1064
- Field: "Keys",
1065
- Value: keys ?? "none"
1066
- });
1192
+ {
1193
+ Field: "API",
1194
+ Value: apiUrl
1195
+ },
1196
+ {
1197
+ Field: "Principal",
1198
+ Value: principal
1199
+ },
1200
+ ...dirFactRows(facts),
1201
+ {
1202
+ Field: "Org",
1203
+ Value: `${org.name} (${org.slug})`
1204
+ },
1205
+ {
1206
+ Field: "Trust Tier",
1207
+ Value: String(org.trust_tier)
1067
1208
  }
1068
- printTable(rows);
1209
+ ];
1210
+ if (agentId) {
1211
+ rows.push({
1212
+ Field: "Agent",
1213
+ Value: agentHandle ?? "-"
1214
+ });
1215
+ rows.push({
1216
+ Field: "Agent ID",
1217
+ Value: agentId
1218
+ });
1219
+ rows.push({
1220
+ Field: "Keys",
1221
+ Value: keys ?? "none"
1222
+ });
1069
1223
  }
1070
- } catch (err) {
1071
- printError(formatError(err));
1072
- process.exitCode = 1;
1224
+ printTable(rows);
1073
1225
  }
1074
- });
1226
+ }));
1075
1227
  }
1076
1228
  //#endregion
1077
1229
  //#region src/commands/auth.ts
@@ -1144,6 +1296,35 @@ async function showOrgStatus(client, gOpts) {
1144
1296
  ]);
1145
1297
  }
1146
1298
  //#endregion
1299
+ //#region src/commands/catalog.ts
1300
+ /**
1301
+ * The operation catalog as a plugin or script reads it: which tier each command signs as and
1302
+ * what it risks. Hidden, and offline: it needs no identity and makes no request.
1303
+ */
1304
+ function registerCatalog(program) {
1305
+ program.command("catalog", { hidden: true }).description("List every operation with its tier and risk").action(withErrorHandler(program, (gOpts) => {
1306
+ const operations = listOperations().map((op) => ({
1307
+ id: op.id,
1308
+ tier: op.tier,
1309
+ risk: op.risk,
1310
+ cli: op.cli ?? null,
1311
+ cli_aliases: op.cliAliases ?? [],
1312
+ mcp: op.mcp ?? null
1313
+ }));
1314
+ if (gOpts.json) {
1315
+ printJson({ operations });
1316
+ return;
1317
+ }
1318
+ printTable(operations.map((op) => ({
1319
+ Id: op.id,
1320
+ Tier: op.tier,
1321
+ Risk: op.risk,
1322
+ Command: op.cli ?? "-",
1323
+ Tool: op.mcp ?? "-"
1324
+ })));
1325
+ }));
1326
+ }
1327
+ //#endregion
1147
1328
  //#region src/commands/group-eviction.ts
1148
1329
  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.";
1149
1330
  /**
@@ -1272,7 +1453,7 @@ async function withEvictionPointerIfHeld(ctx, err) {
1272
1453
  if (!(err instanceof Error)) return err;
1273
1454
  if (!err.message.startsWith(GROUP_NOT_FOUND_LEAD)) return err;
1274
1455
  try {
1275
- if (!holdsAnyMlsState(ctx.configDir, await ctx.actingAgent())) return err;
1456
+ if (!holdsAnyMlsState(ctx.dirs.configDir, await ctx.actingAgent())) return err;
1276
1457
  } catch {
1277
1458
  return err;
1278
1459
  }
@@ -1364,7 +1545,7 @@ async function groupTarget(ctx, ref) {
1364
1545
  } catch (err) {
1365
1546
  if (!UUID_RE.test(ref)) throw await withEvictionPointerIfHeld(ctx, err);
1366
1547
  const actingAgent = () => ctx.actingAgent();
1367
- throw err instanceof RineApiError ? await asGroupAccessError(ctx.configDir, ref, err, actingAgent) : await asEvictionRefusal(ctx.configDir, ref, err, actingAgent);
1548
+ throw err instanceof RineApiError ? await asGroupAccessError(ctx.dirs.configDir, ref, err, actingAgent) : await asEvictionRefusal(ctx.dirs.configDir, ref, err, actingAgent);
1368
1549
  }
1369
1550
  }
1370
1551
  /**
@@ -1606,7 +1787,7 @@ function collectHeader(v, acc) {
1606
1787
  return acc;
1607
1788
  }
1608
1789
  function registerFulfill(program) {
1609
- 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) => {
1790
+ 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, dirs: { configDir }, actingAgent }, messageId, opts) => {
1610
1791
  const payeeAgentId = await actingAgent();
1611
1792
  const message = await client.get(`/messages/${messageId}`);
1612
1793
  if (message.type !== X402_MESSAGE_TYPE.PAYMENT) {
@@ -2205,7 +2386,7 @@ async function foundMlsState(ctx, group) {
2205
2386
  if (group.enrollment_policy === "open") return null;
2206
2387
  try {
2207
2388
  const actingAgentId = await ctx.actingAgent();
2208
- return await initMlsGroup(ctx.configDir, actingAgentId, group.id, ctx.client, { [ACTING_AGENT_HEADER]: actingAgentId });
2389
+ return await initMlsGroup(ctx.dirs.configDir, actingAgentId, group.id, ctx.client, { [ACTING_AGENT_HEADER]: actingAgentId });
2209
2390
  } catch (err) {
2210
2391
  warnMls("MLS init failed (group still created)", err, group.id, ctx.gOpts.json);
2211
2392
  return null;
@@ -2290,7 +2471,7 @@ function registerGroupCreate(program, group) {
2290
2471
  async function evictionState(ctx, group) {
2291
2472
  if (!groupIsMls(group)) return null;
2292
2473
  try {
2293
- return isEvictedFrom(ctx.configDir, await ctx.actingAgent(), group.id);
2474
+ return isEvictedFrom(ctx.dirs.configDir, await ctx.actingAgent(), group.id);
2294
2475
  } catch {
2295
2476
  return null;
2296
2477
  }
@@ -2398,6 +2579,140 @@ async function admitToMls(client, configDir, adminId, groupId, mlsGroupId, membe
2398
2579
  }
2399
2580
  }
2400
2581
  //#endregion
2582
+ //#region src/commands/group-requests.ts
2583
+ /** An open group has no ratchet tree, so there is no admission to resume in it. */
2584
+ const NOT_AN_MLS_GROUP = "This group runs on Sender Keys, not MLS, so it has no ratchet tree to seat anyone in. Open-enrolment groups are sender-key groups by design: MLS would hand an unattested joiner a cryptographic seat, so the server keeps open enrolment off the MLS path. There is nothing to resume here.";
2585
+ function printAdmission(result, json) {
2586
+ if (json) {
2587
+ printJson(result);
2588
+ return;
2589
+ }
2590
+ printText(`Seated ${result.added} of ${result.outcomes.length} in ${result.commits} commit(s), now at epoch ${result.epoch}.`);
2591
+ printTable(admissionOutcomeRows(result));
2592
+ printReclamation(result.reclamation);
2593
+ }
2594
+ /**
2595
+ * What `--reclaim` did, or the stated reason it did nothing.
2596
+ *
2597
+ * The sentence is `describeMlsReclamation`'s, from rine-core — the TypeScript
2598
+ * stack's one copy, sentence for sentence identical to the Python twin. This
2599
+ * function composed its own three branches until the MCP server, eve and mastra
2600
+ * needed the same three, which is the drift a single shared sentence stops: four
2601
+ * surfaces reporting the same reclamation in four wordings.
2602
+ */
2603
+ function printReclamation(reclamation) {
2604
+ const said = describeMlsReclamation(reclamation);
2605
+ if (said) printText(said);
2606
+ }
2607
+ /**
2608
+ * What the vote did to the request, beside the wire token.
2609
+ *
2610
+ * There are **four** answers and not three. `invited` is the one no client
2611
+ * anticipated: the electorate approved a nomination whose subject has not
2612
+ * answered yet, so the row resolves to a spendable invitation rather than to a
2613
+ * seat — a carried vote seats only an agent that consented. Reported
2614
+ * by name here because a fall-through would render a carried vote as an unknown
2615
+ * status, and because it is the one outcome where nobody is added to the
2616
+ * ratchet tree despite the bar being met.
2617
+ *
2618
+ * An unrecognised status renders as itself and gets no sentence — a guess about
2619
+ * a token this build predates would be worse than the token.
2620
+ */
2621
+ function voteOutcomeSentence(status) {
2622
+ switch (status) {
2623
+ case "approved": return "the request carried and that agent is now a member";
2624
+ case "denied": return "the request was refused";
2625
+ case "pending": return "neither bar is reached yet, so the request stands";
2626
+ 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";
2627
+ default: return "";
2628
+ }
2629
+ }
2630
+ function registerGroupRequests(program, group) {
2631
+ 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) => {
2632
+ const { client, gOpts } = ctx;
2633
+ const { id: groupId } = await groupTarget(ctx, ref);
2634
+ const data = await client.get(`/groups/${groupId}/requests`, { outstanding: opts.outstanding });
2635
+ if (gOpts.json) printJson(data);
2636
+ else printTable(data.items.map(requestRow));
2637
+ }));
2638
+ 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 }) => {
2639
+ const items = await listMyInvites(client, extraHeaders);
2640
+ if (gOpts.json) printJson(items);
2641
+ else printTable(items.map(inviteRow));
2642
+ }));
2643
+ 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) => {
2644
+ const { id: groupId, row: target } = await groupTarget(ctx, ref);
2645
+ if (target.enrollment_policy === "open") {
2646
+ printError(NOT_AN_MLS_GROUP);
2647
+ process.exitCode = 2;
2648
+ return;
2649
+ }
2650
+ const actingId = await ctx.actingAgent();
2651
+ const headers = { [ACTING_AGENT_HEADER]: actingId };
2652
+ try {
2653
+ printAdmission(groupIsMls(target) ? await resumeMlsGroupAdmission(ctx.dirs.configDir, actingId, groupId, ctx.client, headers, { reclaim: opts.reclaim }) : await initMlsGroup(ctx.dirs.configDir, actingId, groupId, ctx.client, headers), ctx.gOpts.json);
2654
+ } catch (err) {
2655
+ printError(mlsFailureText(err, groupId));
2656
+ process.exitCode = 1;
2657
+ }
2658
+ }));
2659
+ 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) => {
2660
+ if (opts.vote !== "approve" && opts.vote !== "deny") {
2661
+ printError("--vote must be 'approve' or 'deny'");
2662
+ process.exitCode = 2;
2663
+ return;
2664
+ }
2665
+ const { id: groupId } = await groupTarget(ctx, ref);
2666
+ let applicantId;
2667
+ if (opts.vote === "approve") applicantId = (await ctx.client.get(`/groups/${groupId}/requests`)).items.find((r) => r.id === requestId)?.agent_id;
2668
+ const data = await ctx.client.post(`/groups/${groupId}/requests/${requestId}/vote`, { vote: opts.vote });
2669
+ const admission = data.status === "approved" && applicantId ? await seatApplicant(ctx, groupId, applicantId) : null;
2670
+ if (ctx.gOpts.json) printJson(withAdmission(data, admission));
2671
+ else {
2672
+ const said = voteOutcomeSentence(data.status);
2673
+ printText(`Vote recorded. Request status: ${data.status}` + (said ? ` — ${said}` : ""));
2674
+ }
2675
+ }));
2676
+ }
2677
+ /**
2678
+ * Best-effort MLS add for a newly approved applicant; never fails the vote. The
2679
+ * failure comes back as data so `--json` can report it, as `group invite` does.
2680
+ */
2681
+ async function seatApplicant(ctx, groupId, applicantId) {
2682
+ try {
2683
+ const target = await ctx.client.get(`/groups/${groupId}`);
2684
+ const actingId = await ctx.actingAgent();
2685
+ return await admitToMls(ctx.client, ctx.dirs.configDir, actingId, groupId, target.mls_group_id, [applicantId], ctx.gOpts.json);
2686
+ } catch (err) {
2687
+ return failedAdmission(err, groupId, ctx.gOpts.json);
2688
+ }
2689
+ }
2690
+ //#endregion
2691
+ //#region src/commands/group-invite-head.ts
2692
+ /**
2693
+ * What one invite call did, in its own words.
2694
+ *
2695
+ * Read off the row the server wrote and the group's policy, because the two
2696
+ * together are the answer: a `closed` group's invite mints a voucher
2697
+ * (`invited`), a `majority` or `unanimity` group's files a nomination
2698
+ * (`pending`) — or, when the nominator's own approval carried it at filing, the
2699
+ * voucher it resolved to (`invited`), or a refusal (`denied`) when a rule,
2700
+ * isolation or capacity check refused it in the same transaction — and an
2701
+ * `open` group's is a notification with no row at all, which answers `invited`
2702
+ * and carries no `id`.
2703
+ *
2704
+ * The missing `id` tells the open case apart, the only signal there is. The
2705
+ * carried-nomination sentence is said only where a nomination can carry, so a
2706
+ * closed group's ordinary voucher reads as it always has. Words are
2707
+ * `rine-core`'s, as the plural report's per-agent line is.
2708
+ */
2709
+ function singularHead(row, policy) {
2710
+ if (row.status === "pending") return "Nomination filed — the group's electorate decides it";
2711
+ if (row.status === "denied") return `Not invited: ${voteOutcomeSentence("denied")}`;
2712
+ if (!row.id) return `Invited: ${groupAdmissionSkipSentence("not_applicable")}`;
2713
+ return inviteNominates(policy) ? `Invitation sent. ${CARRIED_NOMINATION_SENTENCE}` : "Invitation sent";
2714
+ }
2715
+ //#endregion
2401
2716
  //#region src/commands/group-invite.ts
2402
2717
  /**
2403
2718
  * An invite that names nobody is refused before it costs anything.
@@ -2468,7 +2783,7 @@ async function notifyInvitees(client, configDir, inviterId, group, inviteeIds, m
2468
2783
  * The agents this call actually reached, whichever shape answered.
2469
2784
  *
2470
2785
  * A singular invite gets a bare row back and no report, so the one agent it
2471
- * named is the answer. A plural one is `admittedAgentIds` — `rine-core`'s, not
2786
+ * named is the answer, unless its row came back `denied`. A plural one is `admittedAgentIds` — `rine-core`'s, not
2472
2787
  * a second copy of the arithmetic — which counts `not_applicable` as reached
2473
2788
  * because that is an open group's answer: it mints no voucher since it needs
2474
2789
  * none, and those agents are still being told to come in.
@@ -2479,31 +2794,12 @@ async function notifyInvitees(client, configDir, inviterId, group, inviteeIds, m
2479
2794
  * electorate has not decided on. {@link afterInvite} is where that question is
2480
2795
  * asked.
2481
2796
  */
2482
- function reachedAgents(report, singular) {
2483
- if (!report) return singular ? [singular] : [];
2484
- return admittedAgentIds(report);
2485
- }
2486
- /**
2487
- * What one invite call did, in its own words.
2488
- *
2489
- * Read off the row the server wrote rather than off the group, because the row
2490
- * is the answer: a `closed` group's invite mints a voucher (`invited`), a
2491
- * `majority` or `unanimity` group's files a nomination (`pending`),
2492
- * and an `open` group's is a notification with no row at all — which answers
2493
- * `invited` and carries no `id`.
2494
- *
2495
- * That missing `id` is what tells the third case from the first, and it is the
2496
- * only signal there is: the two answers carry the same status. An open group
2497
- * mints nothing because it needs nothing, so the head says so and there is no
2498
- * row to table underneath it — reported in `rine-core`'s words, the same
2499
- * sentence the plural report's per-agent line carries.
2500
- */
2501
- function singularHead(row) {
2502
- if (row.status === "pending") return "Nomination filed — the group's electorate decides it";
2503
- if (!row.id) return `Invited: ${groupAdmissionSkipSentence("not_applicable")}`;
2504
- return "Invitation sent";
2797
+ function reachedAgents(data, report, singular) {
2798
+ if (report) return admittedAgentIds(report);
2799
+ const refused = data.status === "denied";
2800
+ return singular && !refused ? [singular] : [];
2505
2801
  }
2506
- function printInvited(data, report, admission, json) {
2802
+ function printInvited(data, report, admission, policy, json) {
2507
2803
  if (json) {
2508
2804
  printJson(withAdmission(data, admission));
2509
2805
  return;
@@ -2514,7 +2810,7 @@ function printInvited(data, report, admission, json) {
2514
2810
  printTable(report.entries.map(admissionRow));
2515
2811
  } else {
2516
2812
  const voucher = data;
2517
- printText(singularHead(voucher));
2813
+ printText(singularHead(voucher, policy));
2518
2814
  if (voucher.id) printTable([requestRow(voucher)]);
2519
2815
  }
2520
2816
  if (admissionRan(admission) && admission.outcomes.length > 0) {
@@ -2540,13 +2836,14 @@ function printInvited(data, report, admission, json) {
2540
2836
  * only the manual reclamation pass able to retire the leaf afterwards — and
2541
2837
  * that pass cannot reach it while the row is live. The vote seats the member,
2542
2838
  * and seating is what grants the key: `group vote` posts the add on the approve
2543
- * that carries, as the self-application path does. The
2839
+ * that carries, as the self-application path does. A nomination that already
2840
+ * carried at filing is no different: no vote follows, so the nominee's leaf
2841
+ * comes from its own join (an external join), and nothing here mints one. The
2544
2842
  * notice still goes out, because a nominee that never learns of the nomination
2545
2843
  * can never consent to it.
2546
2844
  *
2547
- * The GROUP's policy decides this and not the response, because it is the same
2548
- * question the server asked when it chose what to write, and it answers the
2549
- * singular and the plural call in one place.
2845
+ * The GROUP's policy decides this and not the response: the server's own question,
2846
+ * answered for the singular and the plural call in one place.
2550
2847
  */
2551
2848
  async function afterInvite(ctx, groupId, reached, message) {
2552
2849
  let group;
@@ -2558,13 +2855,13 @@ async function afterInvite(ctx, groupId, reached, message) {
2558
2855
  if (!ctx.gOpts.json) printText(`${UNRESOLVED_INVITER} ${err instanceof Error ? err.message : String(err)}`);
2559
2856
  return null;
2560
2857
  }
2561
- const admission = inviteNominates(group.enrollment_policy) ? null : await admitToMls(ctx.client, ctx.configDir, inviterId, groupId, group.mls_group_id, reached, ctx.gOpts.json);
2562
- await notifyInvitees(ctx.client, ctx.configDir, inviterId, group, reached, message, ctx.gOpts.json);
2858
+ const admission = inviteNominates(group.enrollment_policy) ? null : await admitToMls(ctx.client, ctx.dirs.configDir, inviterId, groupId, group.mls_group_id, reached, ctx.gOpts.json);
2859
+ await notifyInvitees(ctx.client, ctx.dirs.configDir, inviterId, group, reached, message, ctx.gOpts.json);
2563
2860
  return admission;
2564
2861
  }
2565
2862
  function registerGroupInvite(program, group) {
2566
- 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) => {
2567
- const { id: groupId } = await groupTarget(ctx, ref);
2863
+ 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; where your approval alone carries it (you are the only active member) it answers an invitation the agent accepts, with no vote left. 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) => {
2864
+ const { id: groupId, row: groupRow } = await groupTarget(ctx, ref);
2568
2865
  const agentIds = dedupeIds(await Promise.all(opts.invitee.map((a) => {
2569
2866
  announceHandleCompletion(a);
2570
2867
  return resolveToUuid(ctx.apiUrl, a);
@@ -2574,7 +2871,7 @@ function registerGroupInvite(program, group) {
2574
2871
  if (opts.message) body.message = opts.message;
2575
2872
  const data = await ctx.client.post(`/groups/${groupId}/invite`, body);
2576
2873
  const report = single ? null : data;
2577
- printInvited(data, report, await afterInvite(ctx, groupId, reachedAgents(report, single), opts.message), ctx.gOpts.json);
2874
+ printInvited(data, report, await afterInvite(ctx, groupId, reachedAgents(data, report, single), opts.message), groupRow.enrollment_policy, ctx.gOpts.json);
2578
2875
  }, invitesSomebody));
2579
2876
  }
2580
2877
  //#endregion
@@ -2602,7 +2899,7 @@ function registerGroupInvite(program, group) {
2602
2899
  * {@link establishMlsMembership}, shared by every TypeScript surface.
2603
2900
  */
2604
2901
  async function establishJoinedMls(ctx, groupId, agentId) {
2605
- reportFailedSetup(await establishMlsMembership(ctx.configDir, agentId, groupId, ctx.client, { [ACTING_AGENT_HEADER]: agentId }), warnFailedSetup(ctx, groupId));
2902
+ reportFailedSetup(await establishMlsMembership(ctx.dirs.configDir, agentId, groupId, ctx.client, { [ACTING_AGENT_HEADER]: agentId }), warnFailedSetup(ctx, groupId));
2606
2903
  }
2607
2904
  const STEP_LABEL = {
2608
2905
  [MlsEstablishStep.GroupRead]: "MLS group read failed",
@@ -2627,7 +2924,7 @@ async function joinAndEstablish(ctx, groupId, body) {
2627
2924
  data = await ctx.client.post(`/groups/${groupId}/join`, body);
2628
2925
  } catch (err) {
2629
2926
  const seated = await seatedMemberAfterConflict(err, {
2630
- configDir: ctx.configDir,
2927
+ configDir: ctx.dirs.configDir,
2631
2928
  groupId,
2632
2929
  client: ctx.client,
2633
2930
  actingAgent: ctx.actingAgent
@@ -2699,7 +2996,7 @@ async function readGroup(ctx, groupId) {
2699
2996
  /** Who holds this agent's sender key for the group; null when it holds none. */
2700
2997
  async function coverageFor(ctx, groupId, memberIds) {
2701
2998
  try {
2702
- return senderKeyCoverage(ctx.configDir, await ctx.actingAgent(), groupId, memberIds);
2999
+ return senderKeyCoverage(ctx.dirs.configDir, await ctx.actingAgent(), groupId, memberIds);
2703
3000
  } catch {
2704
3001
  return null;
2705
3002
  }
@@ -2711,7 +3008,7 @@ function registerGroupMembership(program, group) {
2711
3008
  try {
2712
3009
  items = await fetchGroupMembers(ctx.client, groupId);
2713
3010
  } catch (err) {
2714
- throw await asGroupAccessError(ctx.configDir, groupId, err, () => ctx.actingAgent());
3011
+ throw await asGroupAccessError(ctx.dirs.configDir, groupId, err, () => ctx.actingAgent());
2715
3012
  }
2716
3013
  const coverage = await coverageFor(ctx, groupId, items.map((m) => m.agent_id));
2717
3014
  const data = {
@@ -2747,9 +3044,9 @@ function registerGroupMembership(program, group) {
2747
3044
  const groupId = UUID_RE.test(ref) ? ref : (await groupTarget(ctx, ref)).id;
2748
3045
  const agentId = await ctx.actingAgent();
2749
3046
  const left = await readGroup(ctx, groupId);
2750
- const heldMlsState = loadMlsState(ctx.configDir, agentId, groupId) !== null;
2751
- await deleteGroupMember(ctx.client, ctx.configDir, groupId, agentId, void 0, { [ACTING_AGENT_HEADER]: agentId });
2752
- const wipe = retireLocalGroupState(ctx.configDir, agentId, groupId);
3047
+ const heldMlsState = loadMlsState(ctx.dirs.configDir, agentId, groupId) !== null;
3048
+ await deleteGroupMember(ctx.client, ctx.dirs.configDir, groupId, agentId, void 0, { [ACTING_AGENT_HEADER]: agentId });
3049
+ const wipe = retireLocalGroupState(ctx.dirs.configDir, agentId, groupId);
2753
3050
  printMutationOk("Left group", ctx.gOpts.json);
2754
3051
  if (!ctx.gOpts.json) {
2755
3052
  if (wipe.error) printText(wipe.error);
@@ -2767,122 +3064,13 @@ function registerGroupMembership(program, group) {
2767
3064
  groupId = seated.id;
2768
3065
  target = seated.row;
2769
3066
  }
2770
- const removal = await deleteGroupMember(ctx.client, ctx.configDir, groupId, resolved, () => ctx.actingAgent(), ctx.extraHeaders);
3067
+ const removal = await deleteGroupMember(ctx.client, ctx.dirs.configDir, groupId, resolved, () => ctx.actingAgent(), ctx.extraHeaders);
2771
3068
  printMutationOk("Member removed", ctx.gOpts.json);
2772
3069
  const evicted = evictionMessage(target, removal);
2773
3070
  if (!ctx.gOpts.json && evicted) printText(evicted);
2774
3071
  }));
2775
3072
  }
2776
3073
  //#endregion
2777
- //#region src/commands/group-requests.ts
2778
- /** An open group has no ratchet tree, so there is no admission to resume in it. */
2779
- const NOT_AN_MLS_GROUP = "This group runs on Sender Keys, not MLS, so it has no ratchet tree to seat anyone in. Open-enrolment groups are sender-key groups by design: MLS would hand an unattested joiner a cryptographic seat, so the server keeps open enrolment off the MLS path. There is nothing to resume here.";
2780
- function printAdmission(result, json) {
2781
- if (json) {
2782
- printJson(result);
2783
- return;
2784
- }
2785
- printText(`Seated ${result.added} of ${result.outcomes.length} in ${result.commits} commit(s), now at epoch ${result.epoch}.`);
2786
- printTable(admissionOutcomeRows(result));
2787
- printReclamation(result.reclamation);
2788
- }
2789
- /**
2790
- * What `--reclaim` did, or the stated reason it did nothing.
2791
- *
2792
- * The sentence is `describeMlsReclamation`'s, from rine-core — the TypeScript
2793
- * stack's one copy, sentence for sentence identical to the Python twin. This
2794
- * function composed its own three branches until the MCP server, eve and mastra
2795
- * needed the same three, which is the drift a single shared sentence stops: four
2796
- * surfaces reporting the same reclamation in four wordings.
2797
- */
2798
- function printReclamation(reclamation) {
2799
- const said = describeMlsReclamation(reclamation);
2800
- if (said) printText(said);
2801
- }
2802
- /**
2803
- * What the vote did to the request, beside the wire token.
2804
- *
2805
- * There are **four** answers and not three. `invited` is the one no client
2806
- * anticipated: the electorate approved a nomination whose subject has not
2807
- * answered yet, so the row resolves to a spendable invitation rather than to a
2808
- * seat — a carried vote seats only an agent that consented. Reported
2809
- * by name here because a fall-through would render a carried vote as an unknown
2810
- * status, and because it is the one outcome where nobody is added to the
2811
- * ratchet tree despite the bar being met.
2812
- *
2813
- * An unrecognised status renders as itself and gets no sentence — a guess about
2814
- * a token this build predates would be worse than the token.
2815
- */
2816
- function voteOutcomeSentence(status) {
2817
- switch (status) {
2818
- case "approved": return "the request carried and that agent is now a member";
2819
- case "denied": return "the request was refused";
2820
- case "pending": return "neither bar is reached yet, so the request stands";
2821
- 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";
2822
- default: return "";
2823
- }
2824
- }
2825
- function registerGroupRequests(program, group) {
2826
- 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) => {
2827
- const { client, gOpts } = ctx;
2828
- const { id: groupId } = await groupTarget(ctx, ref);
2829
- const data = await client.get(`/groups/${groupId}/requests`, { outstanding: opts.outstanding });
2830
- if (gOpts.json) printJson(data);
2831
- else printTable(data.items.map(requestRow));
2832
- }));
2833
- 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 }) => {
2834
- const items = await listMyInvites(client, extraHeaders);
2835
- if (gOpts.json) printJson(items);
2836
- else printTable(items.map(inviteRow));
2837
- }));
2838
- 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) => {
2839
- const { id: groupId, row: target } = await groupTarget(ctx, ref);
2840
- if (target.enrollment_policy === "open") {
2841
- printError(NOT_AN_MLS_GROUP);
2842
- process.exitCode = 2;
2843
- return;
2844
- }
2845
- const actingId = await ctx.actingAgent();
2846
- const headers = { [ACTING_AGENT_HEADER]: actingId };
2847
- try {
2848
- 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);
2849
- } catch (err) {
2850
- printError(mlsFailureText(err, groupId));
2851
- process.exitCode = 1;
2852
- }
2853
- }));
2854
- 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) => {
2855
- if (opts.vote !== "approve" && opts.vote !== "deny") {
2856
- printError("--vote must be 'approve' or 'deny'");
2857
- process.exitCode = 2;
2858
- return;
2859
- }
2860
- const { id: groupId } = await groupTarget(ctx, ref);
2861
- let applicantId;
2862
- if (opts.vote === "approve") applicantId = (await ctx.client.get(`/groups/${groupId}/requests`)).items.find((r) => r.id === requestId)?.agent_id;
2863
- const data = await ctx.client.post(`/groups/${groupId}/requests/${requestId}/vote`, { vote: opts.vote });
2864
- const admission = data.status === "approved" && applicantId ? await seatApplicant(ctx, groupId, applicantId) : null;
2865
- if (ctx.gOpts.json) printJson(withAdmission(data, admission));
2866
- else {
2867
- const said = voteOutcomeSentence(data.status);
2868
- printText(`Vote recorded. Request status: ${data.status}` + (said ? ` — ${said}` : ""));
2869
- }
2870
- }));
2871
- }
2872
- /**
2873
- * Best-effort MLS add for a newly approved applicant; never fails the vote. The
2874
- * failure comes back as data so `--json` can report it, as `group invite` does.
2875
- */
2876
- async function seatApplicant(ctx, groupId, applicantId) {
2877
- try {
2878
- const target = await ctx.client.get(`/groups/${groupId}`);
2879
- const actingId = await ctx.actingAgent();
2880
- return await admitToMls(ctx.client, ctx.configDir, actingId, groupId, target.mls_group_id, [applicantId], ctx.gOpts.json);
2881
- } catch (err) {
2882
- return failedAdmission(err, groupId, ctx.gOpts.json);
2883
- }
2884
- }
2885
- //#endregion
2886
3074
  //#region src/commands/group-sync.ts
2887
3075
  function registerGroupSync(program, group) {
2888
3076
  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) => {
@@ -2895,7 +3083,7 @@ function registerGroupSync(program, group) {
2895
3083
  }
2896
3084
  const actingId = await ctx.actingAgent();
2897
3085
  try {
2898
- const result = await recoverGroup(ctx.configDir, actingId, target, ctx.client, { [ACTING_AGENT_HEADER]: actingId }, CLI_UNFOUNDED_REPAIR);
3086
+ const result = await recoverGroup(ctx.dirs.configDir, actingId, target, ctx.client, { [ACTING_AGENT_HEADER]: actingId }, CLI_UNFOUNDED_REPAIR);
2899
3087
  if (ctx.gOpts.json) printJson(result);
2900
3088
  else printText(describeMlsRecovery(label, result));
2901
3089
  } catch (err) {
@@ -2926,6 +3114,19 @@ function registerGroup(program) {
2926
3114
  registerGroupSync(program, group);
2927
3115
  }
2928
3116
  //#endregion
3117
+ //#region src/commands/hook-name.ts
3118
+ /**
3119
+ * Print `Invalid hook name '<name>': <problem>.` and set exit code 2 when
3120
+ * `problem` is a reason (the result of `hookNameError` or `hookNamePatternError`).
3121
+ * Returns true when the command must stop.
3122
+ */
3123
+ function refuseHookName(name, problem) {
3124
+ if (problem === null) return false;
3125
+ printError(invalidHookNameMessage(name, problem));
3126
+ process.exitCode = 2;
3127
+ return true;
3128
+ }
3129
+ //#endregion
2929
3130
  //#region src/commands/hook.ts
2930
3131
  const SIGNATURE_HEADER = "X-Hub-Signature-256";
2931
3132
  const CONTENT_TYPE = "application/json";
@@ -2943,13 +3144,8 @@ function resolveTier(raw) {
2943
3144
  }
2944
3145
  function registerHook(program) {
2945
3146
  const hook = program.command("hook").description("Manage inbound webhook funnel hooks");
2946
- 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) => {
2947
- const nameError = hookNameError(opts.name);
2948
- if (nameError) {
2949
- printError(`Invalid hook name '${opts.name}': ${nameError}.`);
2950
- process.exitCode = 2;
2951
- return;
2952
- }
3147
+ 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, dirs: { configDir }, actingAgent }, opts) => {
3148
+ if (refuseHookName(opts.name, hookNameError(opts.name))) return;
2953
3149
  let tier;
2954
3150
  try {
2955
3151
  tier = resolveTier(opts.tier);
@@ -2962,8 +3158,7 @@ function registerHook(program) {
2962
3158
  printCreated(created, secret, gOpts.json);
2963
3159
  }));
2964
3160
  hook.command("list").description("List your agent's funnel hooks").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, actingAgent }) => {
2965
- const agentId = await actingAgent();
2966
- const data = await client.get(`/agents/${agentId}/funnel/hooks`, {});
3161
+ const data = await listHooks(client, await actingAgent());
2967
3162
  if (gOpts.json) printJson(data);
2968
3163
  else printTable(data.items.map((h) => ({
2969
3164
  Name: h.hook_name,
@@ -2973,13 +3168,14 @@ function registerHook(program) {
2973
3168
  Created: h.created_at
2974
3169
  })));
2975
3170
  }));
2976
- 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) => {
3171
+ 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, dirs: { configDir }, actingAgent }, opts) => {
3172
+ if (refuseHookName(opts.name, hookNamePatternError(opts.name))) return;
2977
3173
  const agentId = await actingAgent();
2978
3174
  if (!opts.yes && !gOpts.json) {
2979
3175
  if (!await promptConfirm(`Delete funnel hook '${opts.name}'?`)) return;
2980
3176
  }
2981
3177
  try {
2982
- await client.delete(`/agents/${agentId}/funnel/hooks/${opts.name}`);
3178
+ await deleteHook(client, configDir, agentId, opts.name);
2983
3179
  } catch (err) {
2984
3180
  if (opts.yes && err instanceof RineApiError && err.status === 404) {
2985
3181
  deleteHookSecret(configDir, agentId, opts.name);
@@ -2988,7 +3184,6 @@ function registerHook(program) {
2988
3184
  }
2989
3185
  throw err;
2990
3186
  }
2991
- deleteHookSecret(configDir, agentId, opts.name);
2992
3187
  printMutationOk("Funnel hook deleted", gOpts.json);
2993
3188
  }));
2994
3189
  }
@@ -3039,10 +3234,896 @@ function printCreated(created, secret, json) {
3039
3234
  Field: "Secret",
3040
3235
  Value: secret
3041
3236
  }
3042
- ]);
3043
- console.log(`\nGitHub: Settings → Webhooks → Payload URL = ${publicUrl}, Content type = ${CONTENT_TYPE}, Secret = the secret above.`);
3044
- console.log("Save this secret now — it is not stored on rine and cannot be retrieved.");
3045
- if (created.termination === "shared_edge") console.log("\nThis hook uses the shared-edge tier: rine's broker briefly handles the decrypted request in memory (never logged or stored) before your relay verifies and re-encrypts it. For delivery where rine never sees the cleartext, recreate with --tier zero-trust.");
3237
+ ]);
3238
+ console.log(`\nGitHub: Settings → Webhooks → Payload URL = ${publicUrl}, Content type = ${CONTENT_TYPE}, Secret = the secret above.`);
3239
+ console.log("Save this secret now — it is not stored on rine and cannot be retrieved.");
3240
+ if (created.termination === "shared_edge") console.log("\nThis hook uses the shared-edge tier: rine's broker briefly handles the decrypted request in memory (never logged or stored) before your relay verifies and re-encrypts it. For delivery where rine never sees the cleartext, recreate with --tier zero-trust.");
3241
+ }
3242
+ //#endregion
3243
+ //#region src/fs-entry.ts
3244
+ /** What is at `path` itself (a link is not followed), or undefined when nothing is. */
3245
+ function entryAt(path) {
3246
+ return fs$1.lstatSync(path, { throwIfNoEntry: false });
3247
+ }
3248
+ /** Where the link `link` leads, or undefined when it leads nowhere (dangling, looping, or through a non-folder). */
3249
+ function linkTarget(link) {
3250
+ try {
3251
+ return fs$1.realpathSync(link);
3252
+ } catch (error) {
3253
+ if (leadsNowhere(error)) return void 0;
3254
+ throw error;
3255
+ }
3256
+ }
3257
+ //#endregion
3258
+ //#region src/git-repository.ts
3259
+ /** The longest `.git`, `gitdir` or `commondir` file read: each names one path. */
3260
+ const MAX_GIT_FILE_BYTES = 4096;
3261
+ const OPEN_FLAGS = fs$1.constants.O_NOFOLLOW | fs$1.constants.O_NONBLOCK;
3262
+ /**
3263
+ * Open `path` without following a link or blocking on a FIFO; anything but a
3264
+ * regular file this user owns, with no second name, throws.
3265
+ */
3266
+ function openOwnedFile(path, flags, mode) {
3267
+ const fd = fs$1.openSync(path, flags | OPEN_FLAGS, mode);
3268
+ const stat = fs$1.fstatSync(fd);
3269
+ if (stat.isFile() && ownedByUs(stat) && stat.nlink === 1) return fd;
3270
+ fs$1.closeSync(fd);
3271
+ throw new Error(`${path} is not a plain file of yours`);
3272
+ }
3273
+ /** A small git pointer file's text. */
3274
+ function readPointer(path) {
3275
+ const fd = openOwnedFile(path, fs$1.constants.O_RDONLY);
3276
+ try {
3277
+ if (fs$1.fstatSync(fd).size > MAX_GIT_FILE_BYTES) throw new Error(`${path} is too large`);
3278
+ return fs$1.readFileSync(fd, "utf8").trim();
3279
+ } finally {
3280
+ fs$1.closeSync(fd);
3281
+ }
3282
+ }
3283
+ /** `path` with every symlink resolved; undefined when nothing (readable) is there. */
3284
+ function realOrUndefined(path) {
3285
+ try {
3286
+ return fs$1.realpathSync(path);
3287
+ } catch {
3288
+ return;
3289
+ }
3290
+ }
3291
+ /** Whether `path` is what `isKind` asks and this user's; false when nothing (readable) is there. */
3292
+ function ownedEntry(path, isKind) {
3293
+ try {
3294
+ const stat = fs$1.statSync(path);
3295
+ return isKind(stat) && ownedByUs(stat);
3296
+ } catch {
3297
+ return false;
3298
+ }
3299
+ }
3300
+ /**
3301
+ * git's own test of a git dir (`is_git_directory`): a `HEAD` file in `gitDir`
3302
+ * and `objects/` and `refs/` in its common dir `common`, all this user's.
3303
+ */
3304
+ function passesGitTest(gitDir, common) {
3305
+ return ownedEntry(gitDir, (s) => s.isDirectory()) && ownedEntry(join(gitDir, "HEAD"), (s) => s.isFile()) && ownedEntry(join(common, "objects"), (s) => s.isDirectory()) && ownedEntry(join(common, "refs"), (s) => s.isDirectory());
3306
+ }
3307
+ /** The git dir a `.git` file's `gitdir:` line names, realpath'd; undefined when it names none that exists. */
3308
+ function namedGitDir(dotGit) {
3309
+ const named = /^gitdir: (.+)$/.exec(readPointer(dotGit))?.[1];
3310
+ return named === void 0 ? void 0 : realOrUndefined(resolve(dirname(dotGit), named.trim()));
3311
+ }
3312
+ /**
3313
+ * The main repository's git dir for a linked worktree's git dir `gitDir`, with
3314
+ * git's checks: `gitDir` is `<common>/worktrees/<n>`, its `gitdir` names the
3315
+ * `.git` file back, its `commondir` names `<common>`, and `<common>` passes git's
3316
+ * own test. Anything else throws.
3317
+ */
3318
+ function worktreeCommonDir(dotGit, gitDir) {
3319
+ const common = dirname(dirname(gitDir));
3320
+ const backlink = resolve(gitDir, readPointer(join(gitDir, "gitdir")));
3321
+ if (basename(dirname(gitDir)) !== "worktrees" || fs$1.realpathSync(backlink) !== fs$1.realpathSync(dotGit)) throw new Error(`${dotGit} is not a worktree its git dir names back`);
3322
+ if (fs$1.realpathSync(resolve(gitDir, readPointer(join(gitDir, "commondir")))) !== common || !passesGitTest(common, common)) throw new Error(`${gitDir} names a common dir that is not its repository's`);
3323
+ return common;
3324
+ }
3325
+ /** {@link commonDirOf} for the git dir `gitDir` the `.git` at `dotGit` resolved to. */
3326
+ function provenCommonDir(dotGit, stat, gitDir) {
3327
+ if (entryAt(join(gitDir, "commondir")) === void 0) return passesGitTest(gitDir, gitDir) ? gitDir : void 0;
3328
+ if (!stat.isFile() || !ownedEntry(join(gitDir, "HEAD"), (s) => s.isFile())) return void 0;
3329
+ return worktreeCommonDir(dotGit, gitDir);
3330
+ }
3331
+ /**
3332
+ * The git dir git reads `info/exclude` from for the `.git` at `dotGit`: a `.git`
3333
+ * dir, or the dir a `.git` symlink or `.git` file names, when it passes git's own
3334
+ * test (a linked worktree's through its common dir); undefined when git would
3335
+ * walk past it. A `.git` file git would not take throws, since git stops there.
3336
+ */
3337
+ function commonDirOf(dotGit, stat) {
3338
+ let gitDir;
3339
+ if (stat.isFile()) gitDir = namedGitDir(dotGit);
3340
+ else if (stat.isDirectory() || stat.isSymbolicLink()) gitDir = realOrUndefined(dotGit);
3341
+ const common = gitDir === void 0 ? void 0 : provenCommonDir(dotGit, stat, gitDir);
3342
+ if (common === void 0 && stat.isFile()) throw new Error(`${dotGit} names no git dir git would take`);
3343
+ return common;
3344
+ }
3345
+ /**
3346
+ * The work tree root holding `dir` and the git dir git reads `info/exclude`
3347
+ * from; undefined outside a repository. A `.git` folder or link git would not
3348
+ * take is walked past, as git walks past it; a `.git` file it would not take
3349
+ * stops the walk with an error, as it stops git.
3350
+ */
3351
+ function repositoryOf(dir) {
3352
+ for (let at = dir;; at = dirname(at)) {
3353
+ const dotGit = join(at, ".git");
3354
+ const stat = entryAt(dotGit);
3355
+ const common = stat === void 0 ? void 0 : commonDirOf(dotGit, stat);
3356
+ if (common !== void 0) return {
3357
+ root: at,
3358
+ common
3359
+ };
3360
+ if (dirname(at) === at) return void 0;
3361
+ }
3362
+ }
3363
+ //#endregion
3364
+ //#region src/git-exclude.ts
3365
+ /** What git reads as a pattern in an exclude line, escaped so the line names only the link. */
3366
+ const GLOB = /[\\[\]*?]/g;
3367
+ const CONTROL = /[\u0000-\u001f\u007f]/;
3368
+ /** The repository's `info/exclude`, opened for appending (made when missing), inside a real `info` dir of yours. */
3369
+ function openExclude(common) {
3370
+ const info = join(common, "info");
3371
+ const stat = entryAt(info);
3372
+ if (stat === void 0) fs$1.mkdirSync(info, { mode: 493 });
3373
+ else if (!stat.isDirectory() || !ownedByUs(stat)) throw new Error(`${info} is not a folder of yours`);
3374
+ const path = join(info, "exclude");
3375
+ const append = fs$1.constants.O_RDWR | fs$1.constants.O_APPEND;
3376
+ try {
3377
+ return openOwnedFile(path, append);
3378
+ } catch (error) {
3379
+ if (error.code !== "ENOENT") throw error;
3380
+ return openOwnedFile(path, append | fs$1.constants.O_CREAT | fs$1.constants.O_EXCL, 420);
3381
+ }
3382
+ }
3383
+ /**
3384
+ * List the project link `link` in its repository's `info/exclude`. Nothing is
3385
+ * done outside a repository; returns what to tell the user when it could not be
3386
+ * listed (the link stays either way).
3387
+ */
3388
+ function excludeFromGit(link) {
3389
+ try {
3390
+ const project = fs$1.realpathSync(dirname(link));
3391
+ const repo = repositoryOf(project);
3392
+ if (repo === void 0) return void 0;
3393
+ const path = relative(repo.root, join(project, basename(link))).split(sep).join("/");
3394
+ if (CONTROL.test(path)) throw new Error("its path holds a control character");
3395
+ const line = `/${path.replace(GLOB, "\\$&")}`;
3396
+ const fd = openExclude(repo.common);
3397
+ try {
3398
+ const now = fs$1.readFileSync(fd, "utf8");
3399
+ if (now.split("\n").includes(line)) return void 0;
3400
+ fs$1.writeSync(fd, `${now === "" || now.endsWith("\n") ? "" : "\n"}${line}\n`);
3401
+ } finally {
3402
+ fs$1.closeSync(fd);
3403
+ }
3404
+ return;
3405
+ } catch (error) {
3406
+ return `rine: could not list ${link} in the repository's info/exclude (${formatError(error)}); add .rine to .gitignore so it is not committed.`;
3407
+ }
3408
+ }
3409
+ //#endregion
3410
+ //#region src/identity-files.ts
3411
+ /** Where the named identity lives in the store. */
3412
+ function storeEntryDir(name) {
3413
+ return join(identityStoreDir(), name);
3414
+ }
3415
+ /** The names in the identity store: its directories, sorted. A missing store is empty. */
3416
+ function storeNames() {
3417
+ try {
3418
+ return fs$1.readdirSync(identityStoreDir(), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
3419
+ } catch {
3420
+ return [];
3421
+ }
3422
+ }
3423
+ /** The project `.rine` to make: where the walk reads it, refused where the walk never would (your home directory). */
3424
+ function projectLinkToMake() {
3425
+ const refusal = projectLinkRefusal();
3426
+ if (refusal !== void 0) throw new Error(refusal);
3427
+ return projectLinkPath();
3428
+ }
3429
+ /**
3430
+ * Refuse, where a project link cannot be made (Windows grants no symbolic link by
3431
+ * default), naming how to use the store entry `name` instead. `what` is the act refused.
3432
+ */
3433
+ function requireLinkSupport(what, name) {
3434
+ if (process.platform !== "win32") return;
3435
+ throw new Error(`${what} needs a symbolic link, which Windows does not grant by default. Point this shell at the identity instead: set RINE_CONFIG_DIR=%USERPROFILE%\\.config\\rine-ids\\${name}`);
3436
+ }
3437
+ /**
3438
+ * Make a free store entry for a project's own identity named `name`:
3439
+ * `project.<name>`, or `project.<name>-2`, `-3`, … when that is taken. Making it
3440
+ * is the claim, so two runs racing for one name each get their own entry.
3441
+ */
3442
+ function claimProjectEntry(name) {
3443
+ for (let n = 1;; n++) {
3444
+ const entry = storeEntryDir(`${PROJECT_ENTRY_PREFIX}${n === 1 ? name : `${name}-${n}`}`);
3445
+ try {
3446
+ fs$1.mkdirSync(entry, { mode: 448 });
3447
+ return entry;
3448
+ } catch (error) {
3449
+ if (error.code !== "EEXIST") throw error;
3450
+ }
3451
+ }
3452
+ }
3453
+ /**
3454
+ * Link `link` to the store entry `store`, the way every project `.rine` is made,
3455
+ * and keep it out of git. Returns what to tell the user when it could not be
3456
+ * kept out of git.
3457
+ */
3458
+ function linkProject(store, link) {
3459
+ fs$1.symlinkSync(store, link, "dir");
3460
+ return excludeFromGit(link);
3461
+ }
3462
+ /**
3463
+ * `identity.json` when it is readable; a missing or malformed file reads as none.
3464
+ * A project folder is read with `readProjectIdentityFile`, which refuses a linked file.
3465
+ */
3466
+ function readIdentityLoosely(dir, read = readIdentityFile) {
3467
+ try {
3468
+ return read(dir);
3469
+ } catch (error) {
3470
+ if (error instanceof IdentityFileError) return void 0;
3471
+ throw error;
3472
+ }
3473
+ }
3474
+ /** The agent the dir's `default` profile names, from the profile file alone. */
3475
+ function defaultAgentId(dir) {
3476
+ return getProfile(dir, DEFAULT_PROFILE)?.agent_id ?? null;
3477
+ }
3478
+ /** Whether the dir holds a `profiles.json`, that is, an identity was ever set up in it. */
3479
+ function isRegistered(dir) {
3480
+ return fs$1.existsSync(join(dir, PROFILES_FILE));
3481
+ }
3482
+ /**
3483
+ * Mark an identity-store entry: its `identity.json` (the real path it is at, so a
3484
+ * copy elsewhere names where it came from) and a `.gitignore` that keeps every file
3485
+ * of it out of a repository should the store sit in one. An adopted identity keeps
3486
+ * its `createdAt`.
3487
+ */
3488
+ function writeIdentityMarkers(dir, identity) {
3489
+ writeIdentityFile(dir, {
3490
+ home: fs$1.realpathSync(dir),
3491
+ created_at: identity.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
3492
+ ...identity.handle ? { handle: identity.handle } : {},
3493
+ ...identity.ownerDir !== void 0 && { owner_dir: identity.ownerDir }
3494
+ });
3495
+ writeIgnoreAll(dir);
3496
+ }
3497
+ /** A `.gitignore` in `dir` that keeps every file of it out of git. */
3498
+ function writeIgnoreAll(dir) {
3499
+ fs$1.writeFileSync(join(dir, ".gitignore"), "*\n", { mode: 384 });
3500
+ }
3501
+ //#endregion
3502
+ //#region src/commands/identity-adopt-move.ts
3503
+ /** A store name that is one plain path component. */
3504
+ const STORE_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
3505
+ const OWNER_RWX = 448;
3506
+ /** Why `path` (inside the folder `root`) cannot be carried into the store, or undefined when it can. */
3507
+ function unsafe(root, path, stat) {
3508
+ const at = relative(root, path) || ".";
3509
+ if (stat.isSymbolicLink()) return `${at} is a symbolic link`;
3510
+ if (!stat.isFile() && !stat.isDirectory()) return `${at} is not a plain file or folder`;
3511
+ if (!ownedByUs(stat)) return `${at} is owned by another user`;
3512
+ if (writableByOthers(stat)) return `${at} is writable by its group or by others`;
3513
+ if (stat.isDirectory() && (stat.mode & OWNER_RWX) !== OWNER_RWX) return `${at} is not fully accessible to you`;
3514
+ }
3515
+ /**
3516
+ * Copy the folder `root` to `to`, walking it with `lstat`: regular files keep
3517
+ * their modes, folders are 0700, and anything {@link unsafe} refuses throws.
3518
+ */
3519
+ function copyChecked(root, from, to) {
3520
+ const stat = fs$1.lstatSync(from);
3521
+ const why = unsafe(root, from, stat);
3522
+ if (why !== void 0) throw new Error(`Refusing to adopt ${root}: ${why}. Only plain files and folders that are yours and not writable by others are adopted.`);
3523
+ if (stat.isFile()) {
3524
+ fs$1.copyFileSync(from, to, fs$1.constants.COPYFILE_EXCL);
3525
+ fs$1.chmodSync(to, stat.mode & 511);
3526
+ return;
3527
+ }
3528
+ fs$1.mkdirSync(to, { mode: 448 });
3529
+ for (const name of fs$1.readdirSync(from)) {
3530
+ if (from === root && rewrittenOnAdopt(from, name)) continue;
3531
+ copyChecked(root, join(from, name), join(to, name));
3532
+ }
3533
+ }
3534
+ /** A linked top-level `identity.json`: adopt reads it as none and writes a fresh one, so it is left behind. */
3535
+ function rewrittenOnAdopt(root, name) {
3536
+ return name === IDENTITY_FILE && entryAt(join(root, name))?.isSymbolicLink() === true;
3537
+ }
3538
+ /**
3539
+ * Move the real folder `dir` into the identity store and leave a link in its
3540
+ * place. The entry is a project entry of its own, named after the handle's local
3541
+ * part, or the agent id when that is no usable name. The folder is copied to a
3542
+ * temp sibling in the store, renamed into place, linked, and only then removed;
3543
+ * any failure before the link stands removes the copy and puts the folder back.
3544
+ * While it waits to be removed, the folder sits in a dir whose `.gitignore`
3545
+ * keeps it out of git, so an adopt that is stopped there leaves nothing to commit.
3546
+ */
3547
+ function moveIntoStore(dir, named) {
3548
+ const name = [named.handle?.split("@")[0], named.agentId].find((candidate) => candidate !== void 0 && STORE_NAME.test(candidate));
3549
+ if (name === void 0) throw new Error(`Refusing to adopt ${dir}: neither its handle nor its agent id can name an identity in the store.`);
3550
+ requireLinkSupport("Adopting a folder", name);
3551
+ const tag = randomBytes(6).toString("hex");
3552
+ const copy = join(identityStoreDir(), `.adopting-${name}-${tag}`);
3553
+ const aside = `${dir}.adopting-${tag}`;
3554
+ fs$1.mkdirSync(identityStoreDir(), {
3555
+ recursive: true,
3556
+ mode: 448
3557
+ });
3558
+ const store = claimProjectEntry(name);
3559
+ let movedAside = false;
3560
+ try {
3561
+ copyChecked(dir, dir, copy);
3562
+ fs$1.renameSync(copy, store);
3563
+ fs$1.mkdirSync(aside, { mode: 448 });
3564
+ writeIgnoreAll(aside);
3565
+ fs$1.renameSync(dir, join(aside, "rine"));
3566
+ movedAside = true;
3567
+ const unlisted = linkProject(store, dir);
3568
+ if (unlisted !== void 0) printError(unlisted);
3569
+ } catch (error) {
3570
+ if (movedAside) fs$1.renameSync(join(aside, "rine"), dir);
3571
+ fs$1.rmSync(aside, {
3572
+ recursive: true,
3573
+ force: true
3574
+ });
3575
+ fs$1.rmSync(copy, {
3576
+ recursive: true,
3577
+ force: true
3578
+ });
3579
+ fs$1.rmSync(store, {
3580
+ recursive: true,
3581
+ force: true
3582
+ });
3583
+ throw error;
3584
+ }
3585
+ try {
3586
+ fs$1.rmSync(aside, { recursive: true });
3587
+ } catch (error) {
3588
+ printError(`rine: could not remove the old folder ${aside} (${formatError(error)}); remove it yourself.`);
3589
+ }
3590
+ }
3591
+ //#endregion
3592
+ //#region src/commands/identity-adopt.ts
3593
+ /** What adopting cannot fix: someone else's folder, one others can write to, or a link out of the store. */
3594
+ const NotFixableByAdopt = [
3595
+ ProjectDirRefusalCode.ForeignOwner,
3596
+ ProjectDirRefusalCode.Writable,
3597
+ ProjectDirRefusalCode.NotInStore
3598
+ ];
3599
+ const ADOPT_WARNING = "Adopt only a folder you made yourself: from now on this agent acts as the identity in it.";
3600
+ /** The org whose root `ownerDir` holds, or undefined when it holds none or a corrupt one. */
3601
+ function rootOrgOf(ownerDir) {
3602
+ try {
3603
+ return loadOrgFromOwner(ownerDir)?.orgId;
3604
+ } catch {
3605
+ return;
3606
+ }
3607
+ }
3608
+ /**
3609
+ * Whether a recorded owner dir is one to keep: it exists, it is ours, and it
3610
+ * holds the root of the org the folder's profile names (a planted hint naming
3611
+ * the user's own owner dir of another org is dropped).
3612
+ */
3613
+ function soundOwnerDir(ownerDir, orgId) {
3614
+ if (ownerDir === void 0 || orgId === void 0) return false;
3615
+ const stat = fs$1.lstatSync(ownerDir, { throwIfNoEntry: false });
3616
+ return stat?.isDirectory() === true && ownedByUs(stat) && rootOrgOf(ownerDir) === orgId;
3617
+ }
3618
+ function registerIdentityAdopt(identity, program) {
3619
+ identity.command("adopt").description("Accept the project .rine this directory skipped as yours, recording where it is").option("--confirm <handle>", "the handle the folder names (its agent id when it names no handle); required").action(withErrorHandler(program, (gOpts, opts) => {
3620
+ readBoundDirs();
3621
+ const skipped = resolveConfigDir().refused?.[0];
3622
+ if (skipped === void 0) throw new Error("Nothing to adopt: no project .rine was skipped here.");
3623
+ const { dir, code, reason } = skipped;
3624
+ if (NotFixableByAdopt.includes(code)) throw new Error(`Refusing to adopt ${dir}: ${reason}. Fix its owner and permissions first (mode 0700, yours), or bind a named identity.`);
3625
+ const named = projectDirIdentity(dir);
3626
+ const names = describeProjectDirIdentity(named);
3627
+ const expected = named.handle ?? named.agentId;
3628
+ if (expected === void 0) throw new Error(`Refusing to adopt ${dir}: it names no agent (${names}).`);
3629
+ if (opts.confirm !== expected) throw new Error(`Refusing to adopt ${dir} without --confirm naming the identity it holds: ${names}. ${ADOPT_WARNING}`);
3630
+ const known = readIdentityLoosely(dir, readProjectIdentityFile);
3631
+ const keepOwner = soundOwnerDir(known?.owner_dir, named.orgId);
3632
+ if (!fs$1.lstatSync(dir).isSymbolicLink()) moveIntoStore(dir, named);
3633
+ writeIdentityMarkers(dir, {
3634
+ handle: known?.handle,
3635
+ ownerDir: keepOwner ? known?.owner_dir : void 0,
3636
+ createdAt: known?.created_at
3637
+ });
3638
+ recordBoundDir(dir);
3639
+ if (gOpts.json) {
3640
+ printJson({
3641
+ ok: true,
3642
+ dir,
3643
+ handle: named.handle ?? null,
3644
+ agent_id: named.agentId ?? null,
3645
+ org_id: named.orgId ?? null,
3646
+ owner_dir_kept: keepOwner
3647
+ });
3648
+ return;
3649
+ }
3650
+ const dropped = known?.owner_dir !== void 0 && !keepOwner ? " Dropped its owner dir hint: that dir is not yours or holds no root of its org." : "";
3651
+ printSuccess(`Adopted ${dir} at ${fs$1.realpathSync(dir)}: it acts as ${names}.${dropped} ${ADOPT_WARNING}`);
3652
+ }));
3653
+ }
3654
+ //#endregion
3655
+ //#region src/commands/identity-new-flags.ts
3656
+ /** The one thing `--org` can ask for. */
3657
+ const OrgChoice = { New: "new" };
3658
+ /** Refuse an identity name that is not a slug, before it is looked up or made. */
3659
+ function checkName(name) {
3660
+ if (!validateSlug(name)) throw new Error("Invalid name: use 2-32 lowercase alphanumeric characters or hyphens, no leading/trailing hyphen");
3661
+ }
3662
+ /** The refusals that need nothing but the flags, so they cost no request. */
3663
+ function checkFlags(name, opts) {
3664
+ checkName(name);
3665
+ if (opts.move && opts.agent === void 0) throw new Error("--move needs --agent");
3666
+ if (opts.org === void 0) return void 0;
3667
+ if (opts.org !== OrgChoice.New) throw new Error(`--org takes '${OrgChoice.New}', not '${opts.org}'`);
3668
+ if (opts.agent !== void 0) throw new Error("--agent restores an agent of an existing org, so it cannot be combined with --org new");
3669
+ if (!opts.email || !opts.orgName || !opts.slug) throw new Error("--org new needs --email, --org-name and --slug");
3670
+ return {
3671
+ email: opts.email,
3672
+ orgName: opts.orgName,
3673
+ slug: opts.slug
3674
+ };
3675
+ }
3676
+ //#endregion
3677
+ //#region src/commands/identity-bind.ts
3678
+ /**
3679
+ * Whether `.rine` at `link` holds the project's own identity: a real folder, or
3680
+ * a link to a project's own store entry (`identity new --here` or `adopt` made
3681
+ * it), which bind and unbind leave alone.
3682
+ */
3683
+ function holdsOwnIdentity(link, existing) {
3684
+ return !existing.isSymbolicLink() || linksToProjectEntry(link);
3685
+ }
3686
+ /** How the `.rine` at `link`, which {@link holdsOwnIdentity}, holds it: as a real folder or as a link to its own entry. */
3687
+ function ownIdentityHeld(link, existing) {
3688
+ return existing.isSymbolicLink() ? `${link} links to this project's own identity` : `${link} is a real directory holding its own identity`;
3689
+ }
3690
+ function registerIdentityBind(identity, program) {
3691
+ identity.command("bind <name>").description("Make this directory use a named identity (links .rine to it)").action(withErrorHandler(program, (gOpts, name) => {
3692
+ checkName(name);
3693
+ requireLinkSupport("Binding", name);
3694
+ const store = storeEntryDir(name);
3695
+ if (!fs$1.statSync(store, { throwIfNoEntry: false })?.isDirectory()) throw new Error(`No identity named '${name}' in ${store}. Make it with: rine identity new ${name}`);
3696
+ if (readIdentityLoosely(store) === void 0) throw new Error(`'${name}' in ${store} has no readable ${IDENTITY_FILE}, so a project would ignore it. Make it with: rine identity new ${name}`);
3697
+ const link = projectLinkToMake();
3698
+ const existing = entryAt(link);
3699
+ if (existing !== void 0 && holdsOwnIdentity(link, existing)) throw new Error(`${ownIdentityHeld(link, existing)}. Move it away if you want to bind '${name}' here.`);
3700
+ if (existing !== void 0) {
3701
+ if (linkTarget(link) === fs$1.realpathSync(store)) {
3702
+ recordBoundDir(link);
3703
+ printMutationOk(`${link} already uses '${name}'`, gOpts.json);
3704
+ return;
3705
+ }
3706
+ const other = resolve(dirname(link), fs$1.readlinkSync(link));
3707
+ const agent = readIdentityLoosely(other)?.handle ?? "unknown agent";
3708
+ throw new Error(`${link} already uses the identity '${basename(other)}' (agent ${agent}). Run \`rine identity unbind\` here, then \`rine identity bind ${name}\`.`);
3709
+ }
3710
+ const unlisted = linkProject(store, link);
3711
+ if (unlisted !== void 0) printError(unlisted);
3712
+ try {
3713
+ recordBoundDir(link);
3714
+ } catch (error) {
3715
+ fs$1.unlinkSync(link);
3716
+ throw error;
3717
+ }
3718
+ printMutationOk(`${link} now uses '${name}'`, gOpts.json);
3719
+ }));
3720
+ }
3721
+ function registerIdentityUnbind(identity, program) {
3722
+ identity.command("unbind").description("Stop this directory using a named identity (removes the .rine link)").action(withErrorHandler(program, (gOpts) => {
3723
+ const link = projectLinkPath();
3724
+ const existing = entryAt(link);
3725
+ if (existing === void 0) {
3726
+ printMutationOk("Nothing to unbind: this directory has no .rine", gOpts.json);
3727
+ return;
3728
+ }
3729
+ if (holdsOwnIdentity(link, existing)) throw new Error(`${ownIdentityHeld(link, existing)}, not a link to a named one. It is left as it is.`);
3730
+ forgetBoundDir(link);
3731
+ fs$1.unlinkSync(link);
3732
+ printMutationOk(`Removed ${link}; the identity itself is kept`, gOpts.json);
3733
+ }));
3734
+ }
3735
+ //#endregion
3736
+ //#region src/commands/identity-restore.ts
3737
+ const TWO_DIRS_NOTICE = "Two directories now hold this agent. Running both at once corrupts its group state: use one, or move the agent instead with --move.";
3738
+ function noRootRefusal(ownerDir) {
3739
+ return `There is no org root in ${ownerDir}, so nothing here can create or restore an agent. Point RINE_OWNER_DIR at the directory that holds root.key, or use --org new.`;
3740
+ }
3741
+ /** Refuse a `--move` that would leave the source dir without an identity. */
3742
+ function assertMovable(dir, agent) {
3743
+ if (defaultAgentId(dir.path) === agent.id) throw new Error(`${dir.shown} acts as ${agent.name} through its default profile, so moving it would leave that directory with no identity.`);
3744
+ }
3745
+ /**
3746
+ * Take over an existing agent in `target`: its keys are re-derived from the org
3747
+ * root and checked against the server, never copied from another dir, and its
3748
+ * closed-group seats are taken again.
3749
+ */
3750
+ async function restoreAgent(client, source, target, ref, move) {
3751
+ const org = loadOrgFromOwner(source.ownerDir);
3752
+ if (org === void 0) throw new Error(noRootRefusal(source.ownerDir));
3753
+ const agent = await findOrgAgent(client, ref);
3754
+ if (move) assertMovable(source.dir, agent);
3755
+ const { closedGroups } = await restoreAgentInto(client, org, target, agent);
3756
+ if (move) removeAgentKeys(source.dir.path, agent.id);
3757
+ return {
3758
+ agent,
3759
+ closedGroups
3760
+ };
3761
+ }
3762
+ //#endregion
3763
+ //#region src/phrase-display.ts
3764
+ /** The one place the words reach a screen: framed, on a terminal. */
3765
+ function printFramedPhrase(ownerDir, heading) {
3766
+ const rule = "=".repeat(72);
3767
+ console.log([
3768
+ rule,
3769
+ heading,
3770
+ readOwnerPhrase(ownerDir),
3771
+ `Also saved to: ${join(ownerDir, PHRASE_FILE)}`,
3772
+ PHRASE_INSTRUCTION,
3773
+ rule
3774
+ ].join("\n"));
3775
+ }
3776
+ /**
3777
+ * Tell the owner where the phrase is. On a terminal and outside `--json` the
3778
+ * words are shown once; anywhere else only the file path is printed, so the
3779
+ * phrase cannot reach a log, a pipe or a model context.
3780
+ */
3781
+ function announcePhrase(opts) {
3782
+ if (process.stdout.isTTY === true && !opts.json) {
3783
+ printFramedPhrase(opts.ownerDir, "Recovery phrase (shown once)");
3784
+ return;
3785
+ }
3786
+ (opts.json ? process.stderr : process.stdout).write(`Recovery phrase file: ${opts.phrasePath}\n${PHRASE_INSTRUCTION}\n`);
3787
+ }
3788
+ //#endregion
3789
+ //#region src/commands/register-org.ts
3790
+ const TERMS_NOTICE = "By registering, you accept the rine terms of service and privacy policy:\n https://rine.network/terms.html\n https://rine.network/privacy.html\n";
3791
+ /** Register a new org under `dirs`; the notice goes to stderr, progress to stderr under `--json`. */
3792
+ async function registerOrg$1(apiUrl, dirs, profile, params, json) {
3793
+ process.stderr.write(TERMS_NOTICE);
3794
+ const progress = json ? process.stderr : process.stdout;
3795
+ const reg = await performRegistration(apiUrl, dirs, profile, params, (pct) => progress.write(`\rSolving PoW challenge: ${pct}%`));
3796
+ progress.write("\rSolving PoW challenge: 100%\n");
3797
+ announcePhrase({
3798
+ ownerDir: dirs.ownerDir,
3799
+ phrasePath: reg.phrase_path,
3800
+ json
3801
+ });
3802
+ return reg;
3803
+ }
3804
+ //#endregion
3805
+ //#region src/commands/identity-new-org.ts
3806
+ /**
3807
+ * Register a new org for an identity dir. Its root goes to its own owner dir
3808
+ * under the owner store, which is refused inside a git tree, so a repository
3809
+ * never holds it. Returns the org's dirs and an admin client signing as it.
3810
+ */
3811
+ async function registerNewOrg(target, opts, json) {
3812
+ if (!validateSlug(opts.slug)) throw new Error("Invalid slug: must be 2-32 lowercase alphanumeric characters or hyphens, no leading/trailing hyphen");
3813
+ const dirs = {
3814
+ configDir: target,
3815
+ ownerDir: ownerStoreDir(opts.slug)
3816
+ };
3817
+ assertOwnerDirAllowed(dirs.ownerDir, configDirAt(target));
3818
+ const apiUrl = resolveApiUrl();
3819
+ const reg = await registerOrg$1(apiUrl, dirs, DEFAULT_PROFILE, {
3820
+ email: opts.email,
3821
+ slug: opts.slug,
3822
+ name: opts.orgName
3823
+ }, json);
3824
+ const { client } = buildTierClient({
3825
+ dirs,
3826
+ apiUrl
3827
+ });
3828
+ return {
3829
+ dirs,
3830
+ client: client.asAdmin(),
3831
+ orgId: reg.org_id
3832
+ };
3833
+ }
3834
+ //#endregion
3835
+ //#region src/commands/identity-store-entry.ts
3836
+ const taken = (path) => entryAt(path) !== void 0;
3837
+ /** Where the identity is made, refusing a place that is taken. */
3838
+ function targetFor(name, here) {
3839
+ if (here) {
3840
+ requireLinkSupport("--here", name);
3841
+ const link = projectLinkToMake();
3842
+ if (taken(link)) throw new Error(`${link} already exists. Remove or move it first.`);
3843
+ return {
3844
+ name,
3845
+ link
3846
+ };
3847
+ }
3848
+ const store = storeEntryDir(name);
3849
+ if (taken(store)) throw new Error(`An identity named '${name}' already exists at ${store}`);
3850
+ return { name };
3851
+ }
3852
+ /**
3853
+ * Make the store entry (for `--here`, a project entry of its own) and, for
3854
+ * `--here`, link the project to it; neither is left half made.
3855
+ */
3856
+ function makeDir(target) {
3857
+ const above = fs$1.mkdirSync(identityStoreDir(), {
3858
+ recursive: true,
3859
+ mode: 448
3860
+ });
3861
+ if (target.link === void 0) {
3862
+ const store = storeEntryDir(target.name);
3863
+ fs$1.mkdirSync(store, { mode: 448 });
3864
+ return { store };
3865
+ }
3866
+ const store = claimProjectEntry(target.name);
3867
+ try {
3868
+ const unlisted = linkProject(store, target.link);
3869
+ if (unlisted !== void 0) printError(unlisted);
3870
+ } catch (error) {
3871
+ fs$1.rmdirSync(store);
3872
+ throw error;
3873
+ }
3874
+ return {
3875
+ store,
3876
+ above
3877
+ };
3878
+ }
3879
+ /**
3880
+ * Undo {@link makeDir} when making the identity failed before it held any keys
3881
+ * worth keeping. For `--here`, the dirs it made above the entry go too, while
3882
+ * they are empty, so a failed `--here` leaves nothing behind.
3883
+ */
3884
+ function unmakeDir(target, made) {
3885
+ if (target.link !== void 0 && entryAt(target.link) !== void 0) fs$1.unlinkSync(target.link);
3886
+ fs$1.rmSync(made.store, {
3887
+ recursive: true,
3888
+ force: true
3889
+ });
3890
+ if (made.above === void 0) return;
3891
+ try {
3892
+ for (let at = identityStoreDir();; at = dirname(at)) {
3893
+ fs$1.rmdirSync(at);
3894
+ if (at === made.above) return;
3895
+ }
3896
+ } catch {}
3897
+ }
3898
+ /**
3899
+ * Mark the new identity in `store` and, for `--here`, record the project link.
3900
+ * The store entry holds the keys, so with `--here` a failure of either step keeps
3901
+ * the entry and the link and says how to finish; returns whether the link is
3902
+ * recorded. Without `--here` a failure throws.
3903
+ */
3904
+ function settle(target, store, markers, confirm) {
3905
+ try {
3906
+ writeIdentityMarkers(store, markers);
3907
+ if (target.link !== void 0) recordBoundDir(target.link);
3908
+ return true;
3909
+ } catch (error) {
3910
+ if (target.link === void 0) throw error;
3911
+ printError(`${target.link} holds the new identity and its keys, but recording it as yours failed: ${formatError(error)}\nOnce that is fixed, run here: ${ADOPT_COMMAND} --confirm ${confirm}`);
3912
+ process.exitCode = 1;
3913
+ return false;
3914
+ }
3915
+ }
3916
+ //#endregion
3917
+ //#region src/commands/identity-new.ts
3918
+ async function makeIdentity(gOpts, name, target, opts, newOrg, source) {
3919
+ if (newOrg !== void 0) {
3920
+ const { dirs, client, orgId } = await registerNewOrg(target, newOrg, gOpts.json);
3921
+ try {
3922
+ return {
3923
+ agent: await performAgentCreation(client, dirs, DEFAULT_PROFILE, {
3924
+ name,
3925
+ into: target
3926
+ }),
3927
+ ownerDir: dirs.ownerDir,
3928
+ orgId
3929
+ };
3930
+ } catch (error) {
3931
+ const reason = formatError(error);
3932
+ throw new Error(`${reason}\nThe org is registered and its root is kept in ${dirs.ownerDir}; recover the agent from there.`);
3933
+ }
3934
+ }
3935
+ const current = custodyDirsOf(source);
3936
+ if (!hasRoot(current.ownerDir)) throw new Error(noRootRefusal(current.ownerDir));
3937
+ const client = buildTierClient({
3938
+ dirs: current,
3939
+ apiUrl: resolveApiUrl(),
3940
+ profile: gOpts.profile
3941
+ }).client.asAdmin();
3942
+ const ownerDir = readIdentityLoosely(current.configDir)?.owner_dir;
3943
+ if (opts.agent !== void 0) {
3944
+ const restored = await restoreAgent(client, {
3945
+ dir: source,
3946
+ ownerDir: current.ownerDir
3947
+ }, target, opts.agent, opts.move === true);
3948
+ return {
3949
+ agent: restored.agent,
3950
+ ownerDir,
3951
+ closedGroups: restored.closedGroups
3952
+ };
3953
+ }
3954
+ return {
3955
+ agent: await performAgentCreation(client, current, DEFAULT_PROFILE, {
3956
+ name,
3957
+ into: target
3958
+ }),
3959
+ ownerDir
3960
+ };
3961
+ }
3962
+ function report(gOpts, name, path, made, opts, bound) {
3963
+ const { agent } = made;
3964
+ if (gOpts.json) {
3965
+ printJson({
3966
+ name,
3967
+ path,
3968
+ agent_id: agent.id,
3969
+ handle: agent.handle,
3970
+ org_id: made.orgId ?? null,
3971
+ owner_dir: made.ownerDir ?? null,
3972
+ closed_groups: made.closedGroups ?? [],
3973
+ ...!bound && { bound: false }
3974
+ });
3975
+ return;
3976
+ }
3977
+ printTable([
3978
+ {
3979
+ Field: "Identity",
3980
+ Value: name
3981
+ },
3982
+ {
3983
+ Field: "Path",
3984
+ Value: path
3985
+ },
3986
+ {
3987
+ Field: "Agent",
3988
+ Value: agent.handle ?? agent.name
3989
+ },
3990
+ {
3991
+ Field: "Agent ID",
3992
+ Value: agent.id
3993
+ }
3994
+ ]);
3995
+ if (opts.agent !== void 0 && !opts.move) console.log(TWO_DIRS_NOTICE);
3996
+ if (!opts.here) console.log(`Use it in a project with: rine identity bind ${name}`);
3997
+ }
3998
+ function registerIdentityNew(identity, program) {
3999
+ identity.command("new <name>").description("Make a named identity: a new agent under this org, or under a new org").option("--here", "also bind it here: link ./.rine of this project to it").option("--org <which>", `'${OrgChoice.New}' registers a new org for this identity`).option("--email <email>", "contact email, for --org new").option("--org-name <name>", "name of the new org, for --org new").option("--slug <slug>", "slug of the new org, for --org new").option("--agent <existing>", "take over an existing agent (id, handle or name) instead of creating one").option("--move", "with --agent: also remove its keys from the directory you run this in").action(withErrorHandler(program, async (gOpts, name, opts) => {
4000
+ const newOrg = checkFlags(name, opts);
4001
+ const target = targetFor(name, opts.here);
4002
+ if (opts.here) readBoundDirs();
4003
+ const source = resolveConfigDir();
4004
+ const dir = makeDir(target);
4005
+ let made;
4006
+ try {
4007
+ made = await makeIdentity(gOpts, name, dir.store, opts, newOrg, source);
4008
+ } catch (error) {
4009
+ unmakeDir(target, dir);
4010
+ throw error;
4011
+ }
4012
+ const bound = settle(target, dir.store, {
4013
+ handle: made.agent.handle,
4014
+ ownerDir: made.ownerDir
4015
+ }, made.agent.handle ?? made.agent.id);
4016
+ report(gOpts, name, target.link ?? dir.store, made, opts, bound);
4017
+ }));
4018
+ }
4019
+ //#endregion
4020
+ //#region src/commands/identity-show.ts
4021
+ /** Where an identity in the store sits when it is not the one this process acts from. */
4022
+ const STORE_SOURCE = "store";
4023
+ function realOrSelf(path) {
4024
+ try {
4025
+ return fs$1.realpathSync(path);
4026
+ } catch {
4027
+ return path;
4028
+ }
4029
+ }
4030
+ /** The target of `.rine` when the current dir is a symlink (a bound identity). */
4031
+ function bindTarget(dir) {
4032
+ try {
4033
+ return fs$1.lstatSync(dir).isSymbolicLink() ? fs$1.readlinkSync(dir) : void 0;
4034
+ } catch {
4035
+ return;
4036
+ }
4037
+ }
4038
+ /** A listed identity shown at `path`, its files read at `readAt`. */
4039
+ function listedFrom(name, path, source, current, readAt = path) {
4040
+ return {
4041
+ name,
4042
+ path,
4043
+ source,
4044
+ handle: readIdentityLoosely(readAt)?.handle ?? null,
4045
+ agent_id: defaultAgentId(readAt),
4046
+ registered: isRegistered(readAt),
4047
+ current
4048
+ };
4049
+ }
4050
+ /** The store's identities and the dir this process acts from, with no request and no root read. */
4051
+ function listIdentities(dir) {
4052
+ const here = realOrSelf(dir.path);
4053
+ let currentListed = false;
4054
+ const entries = storeNames().map((name) => {
4055
+ const path = storeEntryDir(name);
4056
+ const current = realOrSelf(path) === here;
4057
+ currentListed ||= current;
4058
+ return listedFrom(name, current ? dir.shown : path, current ? dir.source : STORE_SOURCE, current, path);
4059
+ });
4060
+ return currentListed ? entries : [listedFrom(null, dir.shown, dir.source, true, dir.path), ...entries];
4061
+ }
4062
+ function registerIdentityShow(identity, program) {
4063
+ identity.command("show").description("Show which identity this directory acts as, and where it came from").action(withErrorHandler(program, (gOpts) => {
4064
+ const dir = resolveConfigDir();
4065
+ const facts = dirFacts(authDirsOf(dir), dir, gOpts.profile);
4066
+ const profile = getProfile(dir.path, gOpts.profile ?? DEFAULT_PROFILE);
4067
+ const file = readIdentityLoosely(dir.path);
4068
+ const boundTo = bindTarget(dir.shown);
4069
+ if (gOpts.json) {
4070
+ printJson({
4071
+ ...facts,
4072
+ handle: file?.handle ?? null,
4073
+ org_id: profile?.org_id ?? null,
4074
+ bound_to: boundTo ?? null
4075
+ });
4076
+ return;
4077
+ }
4078
+ printTable([
4079
+ ...dirFactRows(facts),
4080
+ {
4081
+ Field: "Agent",
4082
+ Value: facts.tiers.agent ?? "-"
4083
+ },
4084
+ {
4085
+ Field: "Handle",
4086
+ Value: file?.handle ?? "-"
4087
+ },
4088
+ {
4089
+ Field: "Org",
4090
+ Value: profile?.org_id ?? "-"
4091
+ },
4092
+ ...boundTo === void 0 ? [] : [{
4093
+ Field: "Bound to",
4094
+ Value: boundTo
4095
+ }]
4096
+ ]);
4097
+ }));
4098
+ }
4099
+ function registerIdentityList(identity, program) {
4100
+ identity.command("list").description("List the named identities on this machine and the one in use").action(withErrorHandler(program, (gOpts) => {
4101
+ const identities = listIdentities(resolveConfigDir());
4102
+ if (gOpts.json) {
4103
+ printJson({ identities });
4104
+ return;
4105
+ }
4106
+ printTable(identities.map((entry) => ({
4107
+ Name: entry.name ?? "-",
4108
+ Path: entry.path,
4109
+ Source: entry.source,
4110
+ Handle: entry.handle ?? "-",
4111
+ Agent: entry.agent_id ?? "-",
4112
+ Registered: entry.registered ? "yes" : "no",
4113
+ Current: entry.current ? "*" : ""
4114
+ })));
4115
+ }));
4116
+ }
4117
+ //#endregion
4118
+ //#region src/commands/identity.ts
4119
+ function registerIdentity(program) {
4120
+ const identity = program.command("identity").description("Which identity this directory acts as, and the named ones on this machine");
4121
+ registerIdentityShow(identity, program);
4122
+ registerIdentityList(identity, program);
4123
+ registerIdentityNew(identity, program);
4124
+ registerIdentityBind(identity, program);
4125
+ registerIdentityUnbind(identity, program);
4126
+ registerIdentityAdopt(identity, program);
3046
4127
  }
3047
4128
  //#endregion
3048
4129
  //#region src/commands/keys-rotate-report.ts
@@ -3102,7 +4183,8 @@ function invalidReason(data) {
3102
4183
  }
3103
4184
  }
3104
4185
  function registerKeysTransfer(keys, program) {
3105
- 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) => {
4186
+ keys.command("export").description("Export private keys to a file").addOption(actorOption()).requiredOption("--output <file>", "Output file path").action(withClient(program, async ({ gOpts, dir, dirs, actingAgent }, opts) => {
4187
+ const { configDir } = dirs;
3106
4188
  const agentId = await actingAgent();
3107
4189
  if (!agentKeysExist(configDir, agentId)) {
3108
4190
  printError(`No keys found for agent ${agentId}`);
@@ -3111,7 +4193,7 @@ function registerKeysTransfer(keys, program) {
3111
4193
  }
3112
4194
  const orgId = orgIdOfAgent(configDir, agentId);
3113
4195
  if (orgId === void 0) {
3114
- printError(`Cannot tell which org agent ${agentId} belongs to: no profile in ${configDir} names it`);
4196
+ printError(`Cannot tell which org agent ${agentId} belongs to: no profile in ${dir.shown} names it`);
3115
4197
  process.exitCode = 1;
3116
4198
  return;
3117
4199
  }
@@ -3140,7 +4222,7 @@ function registerKeysTransfer(keys, program) {
3140
4222
  process.exitCode = 2;
3141
4223
  return;
3142
4224
  }
3143
- saveAgentKeys(resolveConfigDir(), data.agent_id, agentKeysFromPrivate({
4225
+ saveAgentKeys(resolveConfigDir().path, data.agent_id, agentKeysFromPrivate({
3144
4226
  signing: fromBase64Url(data.signing_private_key),
3145
4227
  encryption: fromBase64Url(data.encryption_private_key),
3146
4228
  pqSeed: fromBase64Url(data.pq_encryption_seed),
@@ -3174,7 +4256,7 @@ async function verifyServerKeys(client, configDir, agentId) {
3174
4256
  }
3175
4257
  function registerKeys(program) {
3176
4258
  const keys = program.command("keys").description("E2EE key management");
3177
- keys.command("status").description("Show E2EE key status for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, configDir, actingAgent, agents }) => {
4259
+ keys.command("status").description("Show E2EE key status for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent, agents }) => {
3178
4260
  const agentId = await actingAgent();
3179
4261
  const handle = (await agents()).find((a) => a.id === agentId)?.handle ?? "unknown";
3180
4262
  const hasLocal = agentKeysExist(configDir, agentId);
@@ -3244,13 +4326,11 @@ function registerKeys(program) {
3244
4326
  }
3245
4327
  ]);
3246
4328
  }));
3247
- keys.command("rotate").description("Rotate E2EE keys for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, configDir, ownerDir, actingAgent }) => {
4329
+ keys.command("rotate").description("Rotate E2EE keys for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, dirs, actingAgent }) => {
4330
+ const { configDir } = dirs;
3248
4331
  const agentId = await actingAgent();
3249
4332
  if (agentKeysExist(configDir, agentId)) backupKeys(configDir, agentId);
3250
- const report = await rotateAgentWithSeats(client, {
3251
- configDir,
3252
- ownerDir
3253
- }, agentId);
4333
+ const report = await rotateAgentWithSeats(client, dirs, agentId);
3254
4334
  await verifyServerKeys(client, configDir, agentId);
3255
4335
  printRotationReport(agentId, report, gOpts.json);
3256
4336
  }));
@@ -3435,15 +4515,19 @@ async function openMessage(opts) {
3435
4515
  }
3436
4516
  const groupId = data.group_id;
3437
4517
  try {
4518
+ const result = await decryptGroupMessageWithRecovery(client, configDir, agentId, groupId, data.encrypted_payload, fromAgentId, data.created_at);
3438
4519
  return {
3439
- result: await decryptGroupMessageWithRecovery(client, configDir, agentId, groupId, data.encrypted_payload, fromAgentId, data.created_at),
3440
- refusal: null
4520
+ result,
4521
+ refusal: null,
4522
+ catchUp: reportedCatchUp(result).catch_up
3441
4523
  };
3442
4524
  } catch (err) {
3443
4525
  const forgedStatus = groupAuthenticityStatus(err) ?? void 0;
4526
+ const { catch_up: catchUp } = recoveredCatchUp(err);
3444
4527
  return {
3445
4528
  refusal: refusalFor(err, groupId),
3446
- forgedStatus
4529
+ forgedStatus,
4530
+ catchUp
3447
4531
  };
3448
4532
  }
3449
4533
  }
@@ -3491,7 +4575,7 @@ function refusalFor(err, groupId) {
3491
4575
  */
3492
4576
  /** Register `read` on the `message` command group. */
3493
4577
  function addReadCommand(parent, program) {
3494
- 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)")).option("--peek", "Read without marking the message delivered (it stays new)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, messageId, opts) => {
4578
+ 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)")).option("--peek", "Read without marking the message delivered (it stays new)").action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent }, messageId, opts) => {
3495
4579
  const agentId = await actingAgent();
3496
4580
  const data = await client.get(`/messages/${messageId}`, void 0, withPeekHeader(void 0, true));
3497
4581
  const fromAgentId = data.from_agent_id;
@@ -3507,6 +4591,8 @@ function addReadCommand(parent, program) {
3507
4591
  if (opened) {
3508
4592
  const decResult = opened.result;
3509
4593
  if (refusal !== null && !gOpts.json) printError(refusal.message);
4594
+ const note = gOpts.json ? null : catchUpNote(opened.catchUp);
4595
+ if (note) printError(note);
3510
4596
  if (decResult) {
3511
4597
  if (ingestSenderKeyDistribution(configDir, agentId, data.type, decResult)) printText("Sender key ingested");
3512
4598
  if (gOpts.json) printJson({
@@ -3515,17 +4601,15 @@ function addReadCommand(parent, program) {
3515
4601
  signature_verified: decResult.verified,
3516
4602
  verification_status: decResult.verificationStatus,
3517
4603
  sender_kid: decResult.senderKid,
3518
- ...decResult.catchUp ? { catch_up: decResult.catchUp } : {}
4604
+ ...catchUpFields(opened.catchUp)
3519
4605
  });
3520
- else {
3521
- if (decResult.catchUp?.evicted) printError(MLS_EVICTED_BY_COMMIT);
3522
- printTable([openedRow(data, verifiedMark(decResult.verificationStatus), decResult.plaintext?.slice(0, 200) ?? THREAD_UNAVAILABLE)]);
3523
- }
4606
+ else printTable([openedRow(data, verifiedMark(decResult.verificationStatus), decResult.plaintext?.slice(0, 200) ?? THREAD_UNAVAILABLE)]);
3524
4607
  return;
3525
4608
  }
3526
4609
  }
3527
4610
  if (gOpts.json) printJson({
3528
4611
  ...jsonRow(data),
4612
+ ...catchUpFields(opened?.catchUp),
3529
4613
  ...refusal !== null ? {
3530
4614
  decrypt_error: refusal.message,
3531
4615
  decrypt_error_code: refusal.code
@@ -3592,7 +4676,7 @@ function resolvePayload(payload, payloadFile) {
3592
4676
  /** `rine reply` — answer one message, sealed for its sender. */
3593
4677
  /** Register `reply` on the `message` command group. */
3594
4678
  function addReplyCommand(parent, program) {
3595
- 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) => {
4679
+ 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, dirs: { configDir }, actingAgent }, messageId, opts) => {
3596
4680
  const result = resolvePayload(opts.payload, opts.payloadFile);
3597
4681
  if ("error" in result) {
3598
4682
  printError(result.error);
@@ -3783,7 +4867,8 @@ async function resolveSendGroup(ctx, to, groupNamedById) {
3783
4867
  /** Register `send` on the `message` command group. */
3784
4868
  function registerSend(parent, program) {
3785
4869
  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) => {
3786
- const { client, gOpts, configDir, actingAgent } = ctx;
4870
+ const { client, gOpts, actingAgent } = ctx;
4871
+ const { configDir } = ctx.dirs;
3787
4872
  const result = resolvePayload(opts.payload, opts.payloadFile);
3788
4873
  if ("error" in result) {
3789
4874
  printError(result.error);
@@ -3833,17 +4918,23 @@ function addMessageCommands(parent, program) {
3833
4918
  registerSend(parent, program);
3834
4919
  addInboxCommand(parent, program);
3835
4920
  addReplyCommand(parent, program);
3836
- 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)").option("--hide-control", HIDE_CONTROL_HELP).action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, conversationId, opts) => {
4921
+ 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)").option("--hide-control", HIDE_CONTROL_HELP).action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent }, conversationId, opts) => {
3837
4922
  const ref = resolveThreadRef({
3838
4923
  group: opts.group,
3839
4924
  conversationId
3840
4925
  }, THREAD_REF_SURFACES.cli);
3841
4926
  const agentId = await actingAgent();
3842
- const entries = withoutControlFrames(await decryptThreadRows(configDir, agentId, (await readThreadPage(client, ref, {
4927
+ const { entries: bare, catchUp } = splitThreadCatchUp(await decryptThreadRows(configDir, agentId, (await readThreadPage(client, ref, {
3843
4928
  ...opts.limit ? { limit: opts.limit } : {},
3844
4929
  extraHeaders: { [ACTING_AGENT_HEADER]: agentId }
3845
- })).messages ?? [], client, null), opts.hideControl);
3846
- if (gOpts.json) printJson(entries);
4930
+ })).messages ?? [], client, null));
4931
+ const entries = withoutControlFrames(bare, opts.hideControl);
4932
+ const note = catchUpNote(catchUp);
4933
+ if (note) printError(note);
4934
+ if (gOpts.json) printJson(catchUp && entries[0] ? [{
4935
+ ...entries[0],
4936
+ ...catchUpFields(catchUp)
4937
+ }, ...entries.slice(1)] : entries);
3847
4938
  else printTable(entries.map(threadRow));
3848
4939
  }));
3849
4940
  }
@@ -3852,38 +4943,13 @@ function registerMessages(program) {
3852
4943
  addMessageCommands(program.command("message").description("Message operations (aliases: send/read/inbox/reply)"), program);
3853
4944
  }
3854
4945
  //#endregion
3855
- //#region src/phrase-display.ts
3856
- /** The one place the words reach a screen: framed, on a terminal. */
3857
- function printFramedPhrase(ownerDir, heading) {
3858
- const rule = "=".repeat(72);
3859
- console.log([
3860
- rule,
3861
- heading,
3862
- readOwnerPhrase(ownerDir),
3863
- `Also saved to: ${join(ownerDir, PHRASE_FILE)}`,
3864
- PHRASE_INSTRUCTION,
3865
- rule
3866
- ].join("\n"));
3867
- }
3868
- /**
3869
- * Tell the owner where the phrase is. On a terminal and outside `--json` the
3870
- * words are shown once; anywhere else only the file path is printed, so the
3871
- * phrase cannot reach a log, a pipe or a model context.
3872
- */
3873
- function announcePhrase(opts) {
3874
- if (process.stdout.isTTY === true && !opts.json) {
3875
- printFramedPhrase(opts.ownerDir, "Recovery phrase (shown once)");
3876
- return;
3877
- }
3878
- (opts.json ? process.stderr : process.stdout).write(`Recovery phrase file: ${opts.phrasePath}\n${PHRASE_INSTRUCTION}\n`);
3879
- }
3880
- //#endregion
3881
4946
  //#region src/commands/onboard.ts
3882
4947
  function registerOnboard(program) {
3883
4948
  program.command("onboard").description("Register a new organisation and create your first agent").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organisation name").requiredOption("--slug <slug>", "Organisation 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("--exposure <preset>", EXPOSURE_OPTION_HELP).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) => {
3884
4949
  const exposure = exposurePreset(opts.exposure);
3885
4950
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
3886
- const dirs = resolveDirs();
4951
+ const dir = resolveConfigDir();
4952
+ const dirs = custodyDirsOf(dir);
3887
4953
  const apiUrl = resolveApiUrl();
3888
4954
  if (!validateSlug(opts.slug)) {
3889
4955
  printError("Invalid slug: must be 2-32 lowercase alphanumeric characters or hyphens, no leading/trailing hyphen");
@@ -3891,9 +4957,13 @@ function registerOnboard(program) {
3891
4957
  return;
3892
4958
  }
3893
4959
  if (resolveAuth(dirs, gOpts.profile) !== void 0) {
3894
- const { client } = await createClient(apiUrl, gOpts.profile);
4960
+ const { client } = await createClient({
4961
+ apiUrl,
4962
+ dir,
4963
+ profile: gOpts.profile
4964
+ });
3895
4965
  const { org } = await client.get("/whoami");
3896
- const agents = await client.get("/agents");
4966
+ const agents = await client.asAdmin().get("/agents");
3897
4967
  if (gOpts.json) printJson({
3898
4968
  status: "already_registered",
3899
4969
  org,
@@ -3909,22 +4979,16 @@ function registerOnboard(program) {
3909
4979
  }
3910
4980
  return;
3911
4981
  }
3912
- process.stderr.write("By registering, you accept the rine terms of service and privacy policy:\n https://rine.network/terms.html\n https://rine.network/privacy.html\n");
3913
- const progressStream = gOpts.json ? process.stderr : process.stdout;
3914
- const reg = await performRegistration(apiUrl, dirs, profile, {
4982
+ const reg = await registerOrg$1(apiUrl, dirs, profile, {
3915
4983
  email: opts.email,
3916
4984
  slug: opts.slug,
3917
4985
  name: opts.name
3918
- }, (pct) => {
3919
- progressStream.write(`\rSolving PoW challenge: ${pct}%`);
4986
+ }, gOpts.json);
4987
+ const { client } = await createClient({
4988
+ apiUrl,
4989
+ dir,
4990
+ profile: gOpts.profile
3920
4991
  });
3921
- progressStream.write("\rSolving PoW challenge: 100%\n");
3922
- announcePhrase({
3923
- ownerDir: dirs.ownerDir,
3924
- phrasePath: reg.phrase_path,
3925
- json: gOpts.json
3926
- });
3927
- const { client } = await createClient(apiUrl, gOpts.profile);
3928
4992
  const agent = await performAgentCreation(client, dirs, profile, {
3929
4993
  name: opts.agentName,
3930
4994
  humanOversight: opts.humanOversight,
@@ -3943,7 +5007,7 @@ function registerOnboard(program) {
3943
5007
  poll_url: agent.poll_url,
3944
5008
  identity: agent.identity,
3945
5009
  identity_error: agent.identityError,
3946
- config_dir: dirs.configDir,
5010
+ config_dir: dir.shown,
3947
5011
  owner_dir: dirs.ownerDir
3948
5012
  });
3949
5013
  else {
@@ -4003,9 +5067,9 @@ const NO_ROOT = "Creating a branch needs this org's root key (root.key in the ow
4003
5067
  function registerOrgBranch(org, program) {
4004
5068
  const branch = org.command("branch").description("Delegate a subtree of this org to a partner; branch names are public, never put a customer name or a secret in one");
4005
5069
  registerBranchHold(branch, program);
4006
- branch.command("create <name>").description("Create a branch and seal its bundle to a recipient key").requiredOption("--to <recipient-key>", "The partner's recipient key").option("--out <file>", "Where to write the sealed bundle").option("--words-confirmed", "Skip the interactive word comparison").action(withClient(program, async ({ client, gOpts, ownerDir }, name, opts) => {
5070
+ branch.command("create <name>").description("Create a branch and seal its bundle to a recipient key").requiredOption("--to <recipient-key>", "The partner's recipient key").option("--out <file>", "Where to write the sealed bundle").option("--words-confirmed", "Skip the interactive word comparison").action(withClient(program, async ({ client, gOpts, custody }, name, opts) => {
4007
5071
  assertBranchName(name);
4008
- const org = loadOrgFromOwner(ownerDir);
5072
+ const org = loadOrgFromOwner(custody().ownerDir);
4009
5073
  if (org === void 0) {
4010
5074
  printError(NO_ROOT);
4011
5075
  process.exitCode = 2;
@@ -4085,13 +5149,14 @@ async function createWithKey(ctx, opts, publicKey) {
4085
5149
  else printText(created(delegate));
4086
5150
  }
4087
5151
  async function create(ctx, opts) {
4088
- const { client, gOpts, configDir, ownerDir, auth } = ctx;
5152
+ const { client, gOpts, dirs, custody, auth } = ctx;
5153
+ const { configDir } = dirs;
4089
5154
  if (!NAME_RE.test(opts.name)) throw new Error("--name must be lowercase letters, digits and dashes, at most 32 characters.");
4090
5155
  if (opts.publicKey !== void 0) return createWithKey(ctx, opts, opts.publicKey);
4091
5156
  const scopes = parseScopes(opts.scope);
4092
5157
  const orgId = auth?.orgId;
4093
5158
  if (orgId === void 0) throw new Error("Sign in as the organisation to create a delegated key.");
4094
- if (getProfile(configDir, opts.name) ?? getProfile(ownerDir, opts.name)) throw new Error(`A profile named '${opts.name}' already exists.`);
5159
+ if (getProfile(configDir, opts.name) ?? getProfile(custody().ownerDir, opts.name)) throw new Error(`A profile named '${opts.name}' already exists.`);
4095
5160
  const key = newDelegateKey();
4096
5161
  const delegate = await createDelegate(client, opts.name, scopes, key.publicKey);
4097
5162
  try {
@@ -5390,11 +6455,11 @@ function registerOrgRecover(org, program) {
5390
6455
  org.command("recover").description("Rebuild this device from the 24-word recovery phrase").option("--owner-only", "Write only the org root and profile into the owner directory: no request, no leaf keys, no group reseat").action(withErrorHandler(program, async (gOpts, opts) => {
5391
6456
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
5392
6457
  if (opts.ownerOnly) {
5393
- await restoreOwnerOnly(resolveDirs(), profile, gOpts.json);
6458
+ await restoreOwnerOnly(resolveCustodyDirs(), profile, gOpts.json);
5394
6459
  return;
5395
6460
  }
5396
6461
  const phrase = await readPhrase();
5397
- const report = await performRecovery(resolveApiUrl(), resolveDirs(), profile, phrase, (words) => (gOpts.json ? console.error : console.log)(`Org verification words: ${words}`));
6462
+ const report = await performRecovery(resolveApiUrl(), resolveCustodyDirs(), profile, phrase, (words) => (gOpts.json ? console.error : console.log)(`Org verification words: ${words}`));
5398
6463
  if (gOpts.json) printJson(report);
5399
6464
  else renderReport(report);
5400
6465
  if (report.agents.some((agent) => agent.status === "mismatch")) process.exitCode = 1;
@@ -5405,7 +6470,7 @@ function registerOrgRecover(org, program) {
5405
6470
  process.exitCode = 2;
5406
6471
  return;
5407
6472
  }
5408
- printFramedPhrase(resolveDirs().ownerDir, "Recovery phrase");
6473
+ printFramedPhrase(resolveCustodyDirs().ownerDir, "Recovery phrase");
5409
6474
  }));
5410
6475
  }
5411
6476
  //#endregion
@@ -5583,42 +6648,56 @@ function registerOrg(program) {
5583
6648
  }));
5584
6649
  }
5585
6650
  //#endregion
6651
+ //#region src/commands/pay-confirm.ts
6652
+ /** True when the payment may go ahead: no reason to ask, or a person said yes. */
6653
+ async function confirmPayment(reason, req, payeeAgentId) {
6654
+ if (reason === null) return true;
6655
+ if (process.stdin.isTTY !== true) {
6656
+ printError(`Payment refused (${reason}): ${PAY_CONFIRM_WHY[reason]}. Approve it by running 'rine pay' in a terminal.`);
6657
+ return false;
6658
+ }
6659
+ console.error(`This payment needs your yes: ${PAY_CONFIRM_WHY[reason]}.`);
6660
+ console.error(` Amount: ${requirementAmount(req)} (atomic units)`);
6661
+ console.error(` Asset: ${req.asset}`);
6662
+ console.error(` Network: ${req.network}`);
6663
+ console.error(` Payee: agent ${payeeAgentId}, wallet ${req.payTo}`);
6664
+ const yes = await promptConfirm("Pay this quote?");
6665
+ if (!yes) printError("Payment not sent.");
6666
+ return yes;
6667
+ }
6668
+ //#endregion
6669
+ //#region src/commands/pay-preflight.ts
6670
+ /** Exit codes of a refused payment: the message is no quote, or the quote cannot be paid from here. */
6671
+ const NOT_A_QUOTE_EXIT = 2;
6672
+ const UNPAYABLE_EXIT = 1;
6673
+ /** The payee agent id of a payable quote, or the refusal. */
6674
+ function payPreflight(message, messageId, payerAgentId, configDir) {
6675
+ const refuse = (text, exitCode = UNPAYABLE_EXIT) => ({ refusal: {
6676
+ message: text,
6677
+ exitCode
6678
+ } });
6679
+ if (message.type !== X402_MESSAGE_TYPE.PAYMENT_REQUIRED) return refuse(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT_REQUIRED}. Nothing to pay.`, NOT_A_QUOTE_EXIT);
6680
+ const payeeAgentId = message.from_agent_id;
6681
+ if (!payeeAgentId) return refuse("Cannot pay: the quote has no resolvable sender agent.");
6682
+ if (payeeAgentId === payerAgentId) return refuse("Cannot pay your own quote.");
6683
+ if (message.to_agent_id && message.to_agent_id !== payerAgentId) return refuse(`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.`);
6684
+ if (!agentKeysExist(configDir, payerAgentId)) return refuse(`No E2EE keys for agent ${payerAgentId}. Run 'rine org recover' to restore this agent's keys.`);
6685
+ if (!walletKeyExists(configDir, payerAgentId)) return refuse(`No payment wallet for agent ${payerAgentId}. Run 'rine wallet create' first.`);
6686
+ return { payeeAgentId };
6687
+ }
6688
+ //#endregion
5586
6689
  //#region src/commands/pay.ts
5587
6690
  function registerPay(program) {
5588
- 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) => {
6691
+ 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, dirs: { configDir }, actingAgent }, messageId, opts) => {
5589
6692
  const payerAgentId = await actingAgent();
5590
6693
  const message = await client.get(`/messages/${messageId}`);
5591
- if (message.type !== X402_MESSAGE_TYPE.PAYMENT_REQUIRED) {
5592
- printError(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT_REQUIRED}. Nothing to pay.`);
5593
- process.exitCode = 2;
5594
- return;
5595
- }
5596
- const payeeAgentId = message.from_agent_id;
5597
- if (!payeeAgentId) {
5598
- printError("Cannot pay: the quote has no resolvable sender agent.");
5599
- process.exitCode = 1;
5600
- return;
5601
- }
5602
- if (payeeAgentId === payerAgentId) {
5603
- printError("Cannot pay your own quote.");
5604
- process.exitCode = 1;
5605
- return;
5606
- }
5607
- if (message.to_agent_id && message.to_agent_id !== payerAgentId) {
5608
- 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.`);
5609
- process.exitCode = 1;
5610
- return;
5611
- }
5612
- if (!agentKeysExist(configDir, payerAgentId)) {
5613
- printError(`No E2EE keys for agent ${payerAgentId}. Run 'rine org recover' to restore this agent's keys.`);
5614
- process.exitCode = 1;
5615
- return;
5616
- }
5617
- if (!walletKeyExists(configDir, payerAgentId)) {
5618
- printError(`No payment wallet for agent ${payerAgentId}. Run 'rine wallet create' first.`);
5619
- process.exitCode = 1;
6694
+ const checked = payPreflight(message, messageId, payerAgentId, configDir);
6695
+ if ("refusal" in checked) {
6696
+ printError(checked.refusal.message);
6697
+ process.exitCode = checked.refusal.exitCode;
5620
6698
  return;
5621
6699
  }
6700
+ const { payeeAgentId } = checked;
5622
6701
  const decrypted = await decryptMessage(configDir, payerAgentId, message.encrypted_payload, client, payeeAgentId, payerAgentId, message.created_at);
5623
6702
  let pr;
5624
6703
  try {
@@ -5629,30 +6708,27 @@ function registerPay(program) {
5629
6708
  process.exitCode = 1;
5630
6709
  return;
5631
6710
  }
5632
- const policy = loadPolicy(configDir, payerAgentId);
6711
+ const mode = spendPolicyModeFromEnv();
6712
+ const read = await loadPolicyWithTrust(configDir, payerAgentId, client, mode);
6713
+ const policy = read.policy;
5633
6714
  const dailySpent = readDailySpent(configDir, payerAgentId);
5634
6715
  try {
5635
6716
  const requirement = selectRequirement(pr, policy, dailySpent);
5636
- if (opts.autoPay) {
5637
- if (!policy || !isAutoPayable(policy, requirement)) {
5638
- printError("Quote exceeds the auto-pay threshold. Run 'rine pay' without --auto-pay to approve it manually.");
5639
- process.exitCode = 1;
5640
- return;
5641
- }
6717
+ if (opts.autoPay && !(policy && isAutoPayable(policy, requirement))) {
6718
+ printError("Quote exceeds the auto-pay threshold. Run 'rine pay' without --auto-pay to approve it manually.");
6719
+ process.exitCode = 1;
6720
+ return;
6721
+ }
6722
+ if (!await confirmPayment(paymentConfirmReason(read, requirement, mode, { repay: opts.force === true }), requirement, payeeAgentId)) {
6723
+ process.exitCode = 1;
6724
+ return;
5642
6725
  }
5643
6726
  const walletKey = loadWalletKey(configDir, payerAgentId);
5644
6727
  const built = buildPaymentMessage(buildPaymentPayload(pr, requirement, walletKey, { quoteMessageId: messageId }), { emitMarker: opts.marker !== false });
5645
- const encrypted = await sealForAgent(client, configDir, {
6728
+ const body = await sealedX402Body(client, configDir, {
5646
6729
  senderAgentId: payerAgentId,
5647
6730
  recipientAgentId: payeeAgentId
5648
- }, built.payload);
5649
- const body = {
5650
- type: built.type,
5651
- content_type: built.content_type,
5652
- payload_schema: built.payload_schema,
5653
- ...encrypted
5654
- };
5655
- if (built.metadata) body.metadata = built.metadata;
6731
+ }, built);
5656
6732
  await reserveSpend(configDir, payerAgentId, policy, requirement, {
5657
6733
  messageId,
5658
6734
  force: opts.force
@@ -5706,7 +6782,7 @@ function registerPay(program) {
5706
6782
  //#endregion
5707
6783
  //#region src/commands/poll-token.ts
5708
6784
  function registerPollToken(program) {
5709
- 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) => {
6785
+ 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, dirs: { configDir }, actingAgent }, opts) => {
5710
6786
  const agentId = await actingAgent();
5711
6787
  if (opts.revoke) {
5712
6788
  await client.delete(`/agents/${agentId}/poll-token`);
@@ -5736,23 +6812,12 @@ function registerPollToken(program) {
5736
6812
  function registerRegister(program) {
5737
6813
  program.command("register").description("Register a new organisation (two-step PoW flow). Writes the org root key and recovery phrase to the owner directory").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organisation name").requiredOption("--slug <slug>", "Organisation slug").action(withErrorHandler(program, async (gOpts, opts) => {
5738
6814
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
5739
- const dirs = resolveDirs();
5740
- const apiUrl = resolveApiUrl();
5741
- process.stderr.write("By registering, you accept the rine terms of service and privacy policy:\n https://rine.network/terms.html\n https://rine.network/privacy.html\n");
5742
- const progressStream = gOpts.json ? process.stderr : process.stdout;
5743
- const reg = await performRegistration(apiUrl, dirs, profile, {
6815
+ const dirs = resolveCustodyDirs();
6816
+ const reg = await registerOrg$1(resolveApiUrl(), dirs, profile, {
5744
6817
  email: opts.email,
5745
6818
  slug: opts.slug,
5746
6819
  name: opts.name
5747
- }, (pct) => {
5748
- progressStream.write(`\rSolving PoW challenge: ${pct}%`);
5749
- });
5750
- progressStream.write("\rSolving PoW challenge: 100%\n");
5751
- announcePhrase({
5752
- ownerDir: dirs.ownerDir,
5753
- phrasePath: reg.phrase_path,
5754
- json: gOpts.json
5755
- });
6820
+ }, gOpts.json);
5756
6821
  if (gOpts.json) printJson({
5757
6822
  org_id: reg.org_id,
5758
6823
  org_words: reg.org_words,
@@ -5767,483 +6832,111 @@ function registerRegister(program) {
5767
6832
  }));
5768
6833
  }
5769
6834
  //#endregion
5770
- //#region src/commands/relay-lifecycle.ts
5771
- /**
5772
- * The relay's lifecycle events: one `{event: "lifecycle", data}` JSON line on
5773
- * stdout under `--json`, nothing otherwise. Events name states and never carry
5774
- * a request body or the hook secret.
5775
- */
5776
- function emitLifecycle$1(json, data) {
5777
- if (json) console.log(JSON.stringify({
5778
- event: "lifecycle",
5779
- data
5780
- }));
5781
- }
5782
- /** How long a paused relay waits between attempts to re-bind. */
5783
- const PAUSED_RETRY_MS = 3e4;
5784
- /** The sentence logged, and carried in the event, when the agent is held. */
5785
- const PAUSED_MESSAGE = `tunnel paused: the agent is suspended; retrying every ${PAUSED_RETRY_MS / 1e3} s`;
5786
- //#endregion
5787
- //#region src/commands/relay-cert.ts
5788
- /**
5789
- * The zero-trust wildcard a relay holds: issued on each (re)connect and
5790
- * re-checked on a standing timer, so a relay that stays connected past the
5791
- * renewal window still renews.
5792
- */
5793
- const RENEWAL_CHECK_INTERVAL_MS = 720 * 60 * 1e3;
5794
- function relayCert(deps) {
5795
- const { configDir, agentId, client, options, json, isStopped } = deps;
5796
- let lastDeps;
5797
- let certHandle;
5798
- let certBusy = false;
5799
- let renewalTimer;
5800
- const issue = async (handle, issueDeps) => {
5801
- certBusy = true;
5802
- try {
5803
- return await ensureCert({
5804
- handle,
5805
- agentId,
5806
- delegationId: handle,
5807
- configDir,
5808
- options,
5809
- deps: issueDeps
5810
- });
5811
- } finally {
5812
- certBusy = false;
5813
- }
5814
- };
5815
- const maybeRenewCert = async () => {
5816
- if (isStopped() || certBusy || !certHandle || !lastDeps) return;
5817
- const meta = loadMeta(configDir, certHandle, options);
5818
- if (!meta || !renewalDueWithJitter(meta, certHandle, Date.now())) return;
5819
- try {
5820
- await issue(certHandle, lastDeps);
5821
- emitLifecycle$1(json, {
5822
- state: "cert_renewed",
5823
- handle: certHandle
5824
- });
5825
- } catch (err) {
5826
- emitLifecycle$1(json, {
5827
- state: "cert_renew_error",
5828
- handle: certHandle,
5829
- reason: err instanceof Error ? err.message : String(err)
5830
- });
5831
- }
5832
- };
5833
- return {
5834
- async ensure(handle) {
5835
- certHandle = handle;
5836
- lastDeps = await buildIssueCertDeps({
5837
- configDir,
5838
- options,
5839
- http: client,
5840
- agentId
5841
- });
5842
- return issue(handle, lastDeps);
5843
- },
5844
- release() {
5845
- certHandle = void 0;
5846
- },
5847
- startRenewalTimer() {
5848
- if (renewalTimer) return;
5849
- renewalTimer = setInterval(() => {
5850
- maybeRenewCert();
5851
- }, RENEWAL_CHECK_INTERVAL_MS);
5852
- renewalTimer.unref?.();
5853
- },
5854
- stop() {
5855
- if (renewalTimer) clearInterval(renewalTimer);
5856
- }
5857
- };
5858
- }
5859
- //#endregion
5860
6835
  //#region src/commands/relay-hook.ts
5861
6836
  /**
5862
- * The relay's view of its hook: the options that name it, the server row it
5863
- * resolves to, the secret that verifies it and the DNS it must be delivered on.
6837
+ * The relay's view of its hook as the CLI knows it: the options that name it and
6838
+ * the secret that verifies it. The server row, the tier and the DNS check live
6839
+ * in rine-core's `runRelay`.
5864
6840
  */
5865
6841
  /**
5866
6842
  * Resolve the HMAC secret: --secret-env > --secret-file > the persisted file.
5867
6843
  * Returns "" (after a stderr warning naming the three sources tried) when none is
5868
6844
  * found. An empty secret is NOT safe to run with: an attacker who controls the
5869
6845
  * body can compute `HMAC("", body)` and forge a "verified" self-send, so the
5870
- * caller (runRelayLoop) HARD-REFUSES to start on an empty result — the relay never
6846
+ * caller (relay.ts) HARD-REFUSES to start on an empty result — the relay never
5871
6847
  * enters the reconnect loop or opens the listener without a secret.
5872
6848
  */
5873
- function resolveSecret(opts, configDir, agentId) {
6849
+ function resolveSecret(opts, dir, agentId) {
5874
6850
  if (opts.secretEnv) {
5875
6851
  const v = process.env[opts.secretEnv];
5876
6852
  if (v) return v.trim();
5877
6853
  }
5878
6854
  if (opts.secretFile) return readFileSync(opts.secretFile, "utf-8").trim();
5879
- const stored = loadHookSecret(configDir, agentId, opts.hook);
6855
+ const stored = loadHookSecret(dir.path, agentId, opts.hook);
5880
6856
  if (stored) return stored;
5881
- process.stderr.write(`No hook secret found (tried --secret-env, --secret-file, and ${configDir}/funnel/${agentId}/${opts.hook}.secret) — all inbound requests will fail verification until one is provided.\n`);
6857
+ process.stderr.write(`No hook secret found (tried --secret-env, --secret-file, and ${dir.shown}/funnel/${agentId}/${opts.hook}.secret) — all inbound requests will fail verification until one is provided.\n`);
5882
6858
  return "";
5883
6859
  }
5884
6860
  /**
5885
- * The server hook row — the SINGLE source of truth, used VERBATIM. Its
5886
- * `hostname` (the zero-trust `{hook}.{agentLabel}.hook.rine.network` form) goes
5887
- * into the BIND and (via its agent label) the cert CN/SAN; its `control_ws_url`
5888
- * is the broker control-WS endpoint the relay dials; its `termination` is the
5889
- * tier. NEITHER is reconstructed client-side: a fabricated name matches no
5890
- * funnel_hook row (BIND would NAK, the cert would never match GitHub's TLS), and
5891
- * the API base resolves to the primary IP / Caddy, which has no funnel route. On
5892
- * a missing row or a transient lookup failure we THROW so the loop backs off and
5893
- * retries.
5894
- */
5895
- async function resolveHook(client, agentId, hookName) {
5896
- const hook = (await client.get(`/agents/${agentId}/funnel/hooks`, {}))?.items?.find((h) => h.hook_name === hookName);
5897
- if (!hook?.hostname || !hook.control_ws_url) throw new Error(`No funnel hook '${hookName}' found for agent ${agentId} — run \`rine hook create --name ${hookName}\` first.`);
5898
- return hook;
5899
- }
5900
- /**
5901
- * Fatal — this build implements the zero-trust and shared-edge tiers; an UNKNOWN
5902
- * `termination` value from a newer backend is thrown (not retried) so the relay
5903
- * never enters a backoff loop it cannot escape. Upgrade the CLI to serve it.
5904
- */
5905
- var UnsupportedTierError = class extends Error {
5906
- constructor(tier) {
5907
- super(`This hook uses a TLS-termination mode ('${tier}') this relay build does not support. Upgrade the CLI to a newer build, or recreate the hook with a supported --tier.`);
5908
- this.name = "UnsupportedTierError";
5909
- }
5910
- };
5911
- /**
5912
- * Assert the zero-trust hostname resolves to an A record before
5913
- * declaring the listener ready. The per-agent `*.{agentLabel}.hook` A is a
5914
- * DELIVERY prerequisite written best-effort by the backend; a
5915
- * healthy cert does NOT imply a routable name (DNS-01 validates the independent
5916
- * challenge TXT). Non-fatal — emit a loud `dns_a_missing` event and continue (the
5917
- * cert is valid and the backend self-heals the A on the next ZT-hook create), so
5918
- * a missing A is surfaced rather than a silent black hole.
5919
- */
5920
- async function assertAgentARecord(hostname, json) {
5921
- try {
5922
- if ((await resolve4(hostname)).length === 0) emitLifecycle$1(json, {
5923
- state: "dns_a_missing",
5924
- hostname
5925
- });
5926
- } catch {
5927
- emitLifecycle$1(json, {
5928
- state: "dns_a_missing",
5929
- hostname
5930
- });
5931
- }
5932
- }
5933
- /**
5934
- * Parse --port into a valid TCP port. `0` is accepted as "OS-assign an ephemeral
5935
- * port", never coerced to the default; a non-integer or out-of-range value
5936
- * throws a clear error rather than silently falling back. The default flag
5937
- * value "8443" parses straight through.
6861
+ * The CLI's words for a refusal `runRelay` threw before the relay started: the core
6862
+ * sentences are surface-neutral, so the two that name a CLI remedy are reworded here.
5938
6863
  */
5939
- function parsePort(raw) {
5940
- const port = Number(raw);
5941
- if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`Invalid --port '${raw}': expected an integer 0-65535.`);
5942
- return port;
5943
- }
5944
- //#endregion
5945
- //#region src/commands/relay-reconnect.ts
5946
- /** How the relay loop reads a dropped or refused tunnel, and how it waits to retry. */
5947
- /**
5948
- * End the relay on a revoked binding. It does NOT revoke or wipe the per-agent wildcard: that is
5949
- * SHARED across every other live hook of the agent, so wiping it would kill all of them. The kill
5950
- * switch is server-side DNS+route teardown; the relay just exits.
5951
- */
5952
- function exitRevoked(cert, json) {
5953
- cert.stop();
5954
- emitLifecycle$1(json, { state: "tunnel_revoked" });
5955
- process.exitCode = 1;
5956
- }
5957
- function isRevoked(err) {
5958
- return typeof err === "object" && err !== null && err.revoked === true;
5959
- }
5960
- /** Emit an error reconnect, wait its jittered delay, and return the next backoff. */
5961
- async function reconnectAfterError(json, attempt, backoff, afterEmit) {
5962
- const delay = jitteredDelayMs(backoff);
5963
- emitLifecycle$1(json, {
5964
- state: "tunnel_reconnecting",
5965
- attempt: attempt + 1,
5966
- backoff_ms: delay,
5967
- reason: "error"
5968
- });
5969
- afterEmit?.();
5970
- await sleep(delay);
5971
- return nextReconnectBackoffSeconds(backoff);
5972
- }
5973
- /**
5974
- * Resolve when the tunnel WS closes (carrying the classified close so the caller
5975
- * can pick clean-vs-error reconnect) OR the stop handed to `setStop` runs on
5976
- * SIGINT (resolves `undefined`; the caller's `stopped` flag short-circuits
5977
- * before the reconnect branch). A 4423 close (the agent is held) rejects.
5978
- */
5979
- function waitForClose(tunnel, isStopped, setStop) {
5980
- return new Promise((resolve, reject) => {
5981
- if (isStopped()) return resolve(void 0);
5982
- tunnel.onClose((close) => close.code === CLOSE_SUSPENDED ? reject(new TunnelBindError(BindNakReason.Suspended)) : resolve(close));
5983
- setStop(() => {
5984
- tunnel.close();
5985
- resolve(void 0);
5986
- });
5987
- });
5988
- }
5989
- function isHoldRefusal(err) {
5990
- return err instanceof RineApiError && holdOf(err.status, err.body) !== void 0;
5991
- }
5992
- /** What the relay does after a failed bind or a dropped tunnel. */
5993
- const RelayFailure = {
5994
- Paused: "paused",
5995
- Revoked: "revoked",
5996
- Retry: "retry"
5997
- };
5998
- /**
5999
- * Confirm a revocation NAK once with a freshly minted token, because an older broker or server
6000
- * reports a held agent as revoked. A mint refused with a hold code means held. A mint that
6001
- * succeeds, or one the server refuses outright (a 4xx other than a throttle), leaves the NAK
6002
- * standing. A network fault, a 429 or a 5xx says nothing about the binding, so the relay retries.
6003
- */
6004
- async function confirmRevoked(mint) {
6005
- try {
6006
- await mint({ force: true });
6007
- } catch (mintErr) {
6008
- if (isHoldRefusal(mintErr)) return RelayFailure.Paused;
6009
- return mintErr instanceof RineApiError && isRefusalStatus(mintErr.status) ? RelayFailure.Revoked : RelayFailure.Retry;
6010
- }
6011
- return RelayFailure.Revoked;
6012
- }
6013
- /** Sort a failure: a `suspended` NAK and a hold-coded refusal say held directly. */
6014
- async function classifyFailure$1(err, mint) {
6015
- if (isRevoked(err)) return confirmRevoked(mint);
6016
- return err instanceof TunnelBindError && err.reason === BindNakReason.Suspended || isHoldRefusal(err) ? RelayFailure.Paused : RelayFailure.Retry;
6017
- }
6018
- /**
6019
- * Announce the pause and wait [`PAUSED_RETRY_MS`] before the next attempt, or until the
6020
- * stop handed to `setStop` runs on SIGINT.
6021
- */
6022
- async function pauseTunnel(json, setStop) {
6023
- emitLifecycle$1(json, {
6024
- state: "tunnel_paused",
6025
- message: PAUSED_MESSAGE
6026
- });
6027
- if (!json) process.stderr.write(`${PAUSED_MESSAGE}\n`);
6028
- await new Promise((resolve) => {
6029
- const timer = setTimeout(resolve, PAUSED_RETRY_MS);
6030
- setStop(() => {
6031
- clearTimeout(timer);
6032
- resolve();
6033
- });
6034
- });
6035
- setStop(void 0);
6036
- }
6037
- /** Classify `err`, and run the pause when it says the agent is held. */
6038
- async function settleFailure(err, mint, json, setStop) {
6039
- const failure = await classifyFailure$1(err, mint);
6040
- if (failure === RelayFailure.Paused) await pauseTunnel(json, setStop);
6041
- return failure;
6042
- }
6043
- //#endregion
6044
- //#region src/commands/relay-tier.ts
6045
- /** How a hook's request bytes reach the relay, decided once per connect by its tier. */
6046
- /**
6047
- * Branch ONCE on the tier, BEFORE any label/FQDN derivation: the zero-trust
6048
- * agentLabel deriver hard-codes `.hook.rine.network`, so a shared-edge `.edge`
6049
- * host must never reach it. Zero-trust defers its TLS listener to AFTER the
6050
- * tunnel connects (the lazy `ref` holder — orchestration order:
6051
- * cert→tunnel→listener, safe because no OPEN arrives before the holder is
6052
- * populated); shared-edge has no listener, so its `openLocalPipe` factory is
6053
- * ready immediately.
6054
- */
6055
- async function prepareTier(hook, onRequest, cert, json) {
6056
- const { hostname } = hook;
6057
- if (hook.termination === "shared_edge") {
6058
- cert.release();
6059
- const openLocalPipe = makeEdgePipeFactory({ onRequest });
6060
- emitLifecycle$1(json, {
6061
- state: "shared_edge_ready",
6062
- hostname
6063
- });
6064
- return {
6065
- openLocalPipe,
6066
- listen: async () => {}
6067
- };
6068
- }
6069
- if (hook.termination !== "zero_trust") throw new UnsupportedTierError(hook.termination);
6070
- const ztCert = await cert.ensure(agentLabel(hostname));
6071
- emitLifecycle$1(json, {
6072
- state: "cert_ready",
6073
- hostname
6074
- });
6075
- const ref = {};
6076
- return {
6077
- openLocalPipe: (frame) => {
6078
- if (!ref.live) throw new Error("listener not ready");
6079
- return ref.live.openLocalPipe(frame);
6080
- },
6081
- async listen(port, onListening) {
6082
- const live = await startTlsListener({
6083
- port,
6084
- certPem: ztCert.certPem,
6085
- keyPem: ztCert.keyPem,
6086
- onRequest
6087
- });
6088
- ref.live = live;
6089
- onListening(live);
6090
- await assertAgentARecord(hostname, json);
6091
- emitLifecycle$1(json, {
6092
- state: "listener_ready",
6093
- port: live.port
6094
- });
6095
- cert.startRenewalTimer();
6096
- }
6097
- };
6098
- }
6099
- //#endregion
6100
- //#region src/commands/relay-loop.ts
6101
- /** The `rine relay` reconnect loop: cert, tunnel, listener, per-request handler. */
6102
- async function runRelayLoop(ctx) {
6103
- const { opts, gOpts, configDir, agentId, client, token: mintToken } = ctx;
6104
- const json = gOpts.json;
6105
- const port = parsePort(opts.port);
6106
- const secret = resolveSecret(opts, configDir, agentId);
6107
- if (secret.length === 0) {
6108
- printError(`No hook secret resolved for '${opts.hook}' — refusing to start. Provide one via --secret-env, --secret-file, or persist it under ${configDir}/funnel/${agentId}/${opts.hook}.secret.`);
6109
- process.exitCode = 2;
6110
- return;
6111
- }
6112
- const options = { staging: opts.staging };
6113
- let backoff = 1;
6114
- let attempt = 0;
6115
- let stopped = false;
6116
- let paused = false;
6117
- const refreshMargin = jitteredRefreshMargin();
6118
- const cert = relayCert({
6119
- configDir,
6120
- agentId,
6121
- client,
6122
- options,
6123
- json,
6124
- isStopped: () => stopped
6125
- });
6126
- const idempotency = new IdempotencyStore();
6127
- let stopConnection;
6128
- process.on("SIGINT", () => {
6129
- stopped = true;
6130
- process.exitCode = 0;
6131
- cert.stop();
6132
- stopConnection?.();
6133
- });
6134
- while (!stopped) {
6135
- attempt++;
6136
- let listener;
6137
- try {
6138
- const hook = await resolveHook(client, agentId, opts.hook);
6139
- const { hostname, control_ws_url: controlWsUrl } = hook;
6140
- const onRequest = (req) => handleWebhookRequest({
6141
- configDir,
6142
- agentId,
6143
- hookName: opts.hook,
6144
- secret,
6145
- client,
6146
- idempotency,
6147
- emitLifecycle: (ev) => json && console.log(JSON.stringify(ev))
6148
- }, req);
6149
- const tier = await prepareTier(hook, onRequest, cert, json);
6150
- const tunnel = await connectTunnel({
6151
- controlWsUrl,
6152
- token: await mintToken({
6153
- refreshMargin,
6154
- force: paused
6155
- }),
6156
- agentId,
6157
- hostname,
6158
- openLocalPipe: tier.openLocalPipe
6159
- });
6160
- emitLifecycle$1(json, { state: "tunnel_connected" });
6161
- await tier.listen(port, (live) => {
6162
- listener = live;
6163
- });
6164
- backoff = 1;
6165
- paused = false;
6166
- const close = await waitForClose(tunnel, () => stopped, (stop) => {
6167
- stopConnection = stop;
6168
- });
6169
- stopConnection = void 0;
6170
- tunnel.close();
6171
- listener?.close();
6172
- if (stopped) break;
6173
- if (close?.clean !== false) {
6174
- emitLifecycle$1(json, {
6175
- state: "tunnel_reconnecting",
6176
- attempt: attempt + 1,
6177
- backoff_ms: 0,
6178
- reason: "server_close"
6179
- });
6180
- backoff = 1;
6181
- } else backoff = await reconnectAfterError(json, attempt, backoff);
6182
- } catch (err) {
6183
- listener?.close();
6184
- if (stopped) break;
6185
- if (err instanceof UnsupportedTierError) {
6186
- cert.stop();
6187
- printError(err.message);
6188
- process.exitCode = 2;
6189
- return;
6190
- }
6191
- const failure = await settleFailure(err, mintToken, json, (stop) => {
6192
- stopConnection = stop;
6193
- });
6194
- if (failure === RelayFailure.Paused) {
6195
- paused = true;
6196
- continue;
6197
- }
6198
- if (failure === RelayFailure.Revoked) return exitRevoked(cert, json);
6199
- backoff = await reconnectAfterError(json, attempt, backoff, () => {
6200
- if (opts.verbose) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, error): ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
6201
- });
6202
- }
6203
- }
6204
- cert.stop();
6205
- emitLifecycle$1(json, {
6206
- state: "stopped",
6207
- reason: "signal"
6208
- });
6864
+ function relayRefusal(err, opts, dir, agentId) {
6865
+ if (err instanceof EmptyHookSecretError) return `No hook secret resolved for '${opts.hook}' — refusing to start. Provide one via --secret-env, --secret-file, or persist it under ${dir.shown}/funnel/${agentId}/${opts.hook}.secret.`;
6866
+ if (err instanceof UnsupportedTierError) return `${err.message} Upgrade the CLI to a newer build, or recreate the hook with a supported --tier.`;
6867
+ return err.message;
6209
6868
  }
6210
6869
  //#endregion
6211
6870
  //#region src/commands/relay.ts
6212
6871
  /**
6213
6872
  * `rine relay`, the long-lived inbound webhook funnel daemon. This module
6214
6873
  * registers the command, builds the client (as stream.ts does, not through
6215
- * withClient), resolves the acting agent and refuses to start without its
6216
- * identity keys, then hands over to relay-loop.ts, which installs the SIGINT
6217
- * handler and runs the reconnect loop. Each (re)connect runs four steps IN
6218
- * ORDER: (1) cert provision/renew (relay-cert) → (2) control WS + mux tunnel →
6219
- * (3) local TLS-terminating listener (relay-tier) → (4) per-request
6220
- * verify/encrypt/post (rine-core's relay adapter). relay-hook resolves the
6221
- * hook row, its secret and its A record; relay-reconnect classifies a dropped
6222
- * tunnel and waits out the backoff; relay-lifecycle emits the lifecycle
6223
- * events, which NEVER carry a body. None of these modules holds inline ACME,
6224
- * mux framing or crypto: they call the rine-core funnel entry points.
6225
- */
6874
+ * withClient), resolves the acting agent, refuses to start without its identity
6875
+ * keys or a hook secret, then hands over to rine-core's `runRelay`, which owns
6876
+ * the reconnect loop (cert → tunnel → listener → per-request handler). The CLI
6877
+ * is the process edge: it turns SIGINT into an abort, prints the relay's
6878
+ * events (lifecycle events NEVER carry a body) and maps its outcome to the exit
6879
+ * code.
6880
+ */
6881
+ /** Where the relay's events go: JSON lines on stdout under `--json`, the pause notice and `--verbose` errors on stderr. */
6882
+ function eventPrinter(json, verbose) {
6883
+ return (event) => {
6884
+ switch (event.type) {
6885
+ case "lifecycle":
6886
+ if (json) console.log(JSON.stringify({
6887
+ event: "lifecycle",
6888
+ data: event.data
6889
+ }));
6890
+ else if (event.data.state === "tunnel_paused") process.stderr.write(`${event.data.message}\n`);
6891
+ return;
6892
+ case "request":
6893
+ if (json) console.log(JSON.stringify(event.event));
6894
+ return;
6895
+ case "reconnect_error": if (verbose) process.stderr.write(`Reconnecting (attempt ${event.attempt}, error): ${event.error instanceof Error ? event.error.stack ?? event.error.message : String(event.error)}\n`);
6896
+ }
6897
+ };
6898
+ }
6226
6899
  function registerRelay(program) {
6227
6900
  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 environment variable").option("--staging", "Use the Let's Encrypt staging CA (dev)").option("--verbose", "Verbose reconnect logging").action(async (opts, command) => {
6228
6901
  try {
6902
+ if (refuseHookName(opts.hook, hookNamePatternError(opts.hook))) return;
6229
6903
  const gOpts = program.opts();
6230
- const configDir = resolveConfigDir();
6231
- const { client, token } = await createClient(resolveApiUrl(), gOpts.profile);
6904
+ const { client, dir, tokenFor } = await createClient({
6905
+ apiUrl: resolveApiUrl(),
6906
+ profile: gOpts.profile,
6907
+ refreshMargin: jitteredRefreshMargin()
6908
+ });
6232
6909
  const { actingAgent } = actorLadder(namedActor(command, gOpts), client);
6233
6910
  const agentId = await actingAgent();
6234
- if (!agentKeysExist(configDir, agentId)) {
6235
- printError(`Agent identity keys not found under ${configDir}/keys/${agentId}/ — register first.`);
6911
+ if (!agentKeysExist(dir.path, agentId)) {
6912
+ printError(missingKeysMessage(dir.shown, agentId));
6236
6913
  process.exitCode = 2;
6237
6914
  return;
6238
6915
  }
6239
- await runRelayLoop({
6240
- opts,
6241
- gOpts,
6242
- configDir,
6243
- agentId,
6244
- client,
6245
- token
6246
- });
6916
+ const port = parsePort(opts.port, "--port");
6917
+ const secret = resolveSecret(opts, dir, agentId);
6918
+ const controller = new AbortController();
6919
+ process.on("SIGINT", () => controller.abort());
6920
+ try {
6921
+ const { reason } = await runRelay({
6922
+ configDir: dir.path,
6923
+ agentId,
6924
+ client,
6925
+ hookName: opts.hook,
6926
+ port,
6927
+ secret,
6928
+ staging: opts.staging,
6929
+ signal: controller.signal,
6930
+ onEvent: eventPrinter(gOpts.json, opts.verbose),
6931
+ mintToken: tokenFor(agentId),
6932
+ seams: relaySeams(core, resolve4)
6933
+ });
6934
+ process.exitCode = reason === "stopped" ? 0 : 1;
6935
+ } catch (err) {
6936
+ if (!(err instanceof RelayFatalError)) throw err;
6937
+ printError(relayRefusal(err, opts, dir, agentId));
6938
+ process.exitCode = 2;
6939
+ }
6247
6940
  } catch (err) {
6248
6941
  printError(err instanceof Error ? err.message : String(err));
6249
6942
  process.exitCode = 1;
@@ -6460,12 +7153,14 @@ async function openStreamMessage(dataStr, agentId, configDir, client) {
6460
7153
  let result;
6461
7154
  let unavailable = null;
6462
7155
  let forgedStatus;
7156
+ let thrown;
6463
7157
  const fromAgentId = data.from_agent_id;
6464
7158
  const attempted = Boolean(!undecodable && cleartext === null && data.encrypted_payload && fromAgentId && agentKeysExist(configDir, agentId));
6465
7159
  if (attempted && data.encrypted_payload && fromAgentId) {
6466
7160
  if (isGroupEncryptionVersion(data.encryption_version) && data.group_id) try {
6467
7161
  result = await decryptGroupMessageWithRecovery(client, configDir, agentId, data.group_id, data.encrypted_payload, fromAgentId, data.created_at);
6468
7162
  } catch (err) {
7163
+ thrown = err;
6469
7164
  forgedStatus = groupAuthenticityStatus(err) ?? void 0;
6470
7165
  unavailable = asSenderKeyUnavailable(err, data.group_id);
6471
7166
  }
@@ -6474,13 +7169,15 @@ async function openStreamMessage(dataStr, agentId, configDir, client) {
6474
7169
  } catch {}
6475
7170
  if (result && !isAuthenticityFailure(result.verificationStatus) && result.plaintext !== void 0) ingestSenderKeyDistribution(configDir, agentId, data.type ?? "", result);
6476
7171
  }
7172
+ const { catch_up: catchUp } = result ? reportedCatchUp(result) : recoveredCatchUp(thrown);
6477
7173
  return {
6478
7174
  data,
6479
7175
  cleartext,
6480
7176
  attempted,
6481
7177
  result,
6482
7178
  forgedStatus,
6483
- unavailable
7179
+ unavailable,
7180
+ catchUp
6484
7181
  };
6485
7182
  }
6486
7183
  /**
@@ -6540,6 +7237,8 @@ async function settleAndPrint(env, dataStr) {
6540
7237
  const opened = await openStreamMessage(dataStr, env.agentId, env.configDir, env.client);
6541
7238
  const row = opened.data;
6542
7239
  if (row.id && isSettledMessage(opened)) env.acks.add(row.id);
7240
+ const catchUp = catchUpNote(opened.catchUp);
7241
+ if (catchUp) printError(catchUp);
6543
7242
  if (env.json) return;
6544
7243
  const rendered = renderOpened(opened, env.explain);
6545
7244
  if (rendered.notice !== null) printError(rendered.notice);
@@ -6676,9 +7375,13 @@ function registerStream(program) {
6676
7375
  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)").option("--hide-control", STREAM_HIDE_CONTROL_HELP).action(async (opts, command) => {
6677
7376
  try {
6678
7377
  const gOpts = program.opts();
6679
- const configDir = resolveConfigDir();
6680
7378
  const apiUrl = resolveApiUrl();
6681
- const { client, token: mintToken } = await createClient(apiUrl, gOpts.profile);
7379
+ const { client, dir, tokenFor } = await createClient({
7380
+ apiUrl,
7381
+ profile: gOpts.profile,
7382
+ refreshMargin: jitteredRefreshMargin()
7383
+ });
7384
+ const configDir = dir.path;
6682
7385
  const { actingAgent } = actorLadder(namedActor(command, gOpts), client);
6683
7386
  const agentId = await actingAgent();
6684
7387
  let url = `${apiUrl}/agents/${agentId}/stream`;
@@ -6688,7 +7391,6 @@ function registerStream(program) {
6688
7391
  let backoff = 1;
6689
7392
  let attempt = 0;
6690
7393
  let mintFresh = false;
6691
- const refreshMargin = jitteredRefreshMargin();
6692
7394
  const explain = senderKeyExplainer();
6693
7395
  const env = createStreamEnv({
6694
7396
  json: Boolean(gOpts.json),
@@ -6700,6 +7402,7 @@ function registerStream(program) {
6700
7402
  client,
6701
7403
  explain
6702
7404
  });
7405
+ const mintToken = tokenFor(agentId);
6703
7406
  const stop = listenForStop();
6704
7407
  while (!stop.stopped) {
6705
7408
  attempt++;
@@ -6714,10 +7417,7 @@ function registerStream(program) {
6714
7417
  stopping: stop.signal
6715
7418
  });
6716
7419
  try {
6717
- const token = await mintToken({
6718
- refreshMargin,
6719
- force: mintFresh
6720
- });
7420
+ const token = await mintToken({ force: mintFresh });
6721
7421
  mintFresh = false;
6722
7422
  const headers = withPeekHeader({
6723
7423
  Authorization: `Bearer ${token}`,
@@ -8797,8 +9497,9 @@ async function releaseIdentity(identity) {
8797
9497
  }
8798
9498
  /** The org id comes from the root itself, never from a server answer. */
8799
9499
  function resolveIdentity(input = {}) {
8800
- const configDir = input.configDir ?? resolveConfigDir();
8801
- const ownerDir = input.ownerDir ?? resolveOwnerDir();
9500
+ const dir = input.configDir === void 0 ? resolveConfigDir() : configDirAt(input.configDir);
9501
+ const configDir = dir.path;
9502
+ const ownerDir = input.ownerDir ?? resolveOwnerDir(dir);
8802
9503
  if (hasRoot(ownerDir)) {
8803
9504
  const key = ReadKey.fromOwnerDir(ownerDir);
8804
9505
  const bucket = new TokenBucket();
@@ -11096,13 +11797,62 @@ function registerVerifyIdentity(program) {
11096
11797
  }));
11097
11798
  }
11098
11799
  //#endregion
11099
- //#region src/commands/wallet.ts
11800
+ //#region src/commands/wallet-policy-set.ts
11801
+ /** Printed when the policy could not be signed here. */
11802
+ const UNSIGNED_NOTE = "policy saved unsigned; sign it from a machine holding the org root";
11803
+ /** Printed after core's refusal to replace a signed policy without the org root. */
11804
+ const FORCE_HINT = "Pass --force to replace it with an unsigned policy.";
11100
11805
  function csv(raw) {
11101
11806
  return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
11102
11807
  }
11808
+ /** Write `policy` unsigned; a signed one on disk is replaced only when `force` is set. */
11809
+ function saveUnsigned(dirs, agentId, policy, force) {
11810
+ if (force) {
11811
+ savePolicy(dirs.configDir, agentId, policy);
11812
+ return;
11813
+ }
11814
+ try {
11815
+ savePolicyUnlessSigned(dirs.configDir, agentId, policy);
11816
+ } catch (err) {
11817
+ const signed = readStoredPolicy(dirs.configDir, agentId).kind === StoredPolicyKind.Signed;
11818
+ if (err instanceof X402Error && signed) throw new Error(`${err.message}. ${FORCE_HINT}`);
11819
+ throw err;
11820
+ }
11821
+ }
11822
+ /** Save `policy` for `agentId`, signed when the owner dir holds that agent's org root. */
11823
+ function saveForAgent(dirs, agentId, policy, force) {
11824
+ const org = dirs.agentOnly === true ? void 0 : loadOrgFromOwner(dirs.ownerDir);
11825
+ if (org === void 0 || org.orgId !== orgIdOfAgent(dirs.configDir, agentId)) {
11826
+ saveUnsigned(dirs, agentId, policy, force);
11827
+ return false;
11828
+ }
11829
+ saveSignedPolicy(dirs.configDir, agentId, signPolicy(policy, agentId, org.ed25519.privateKey));
11830
+ return true;
11831
+ }
11832
+ function registerWalletPolicySet(policy, program) {
11833
+ policy.command("set").description("Set the spend policy (all caps are decimal major-unit strings); signed by the org when its root is here").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").option("--no-auto-pay", "Never pay without asking, even below the threshold").option("--allow-repay", "Allow paying a quote already paid today again").option("--force", "Replace a signed policy with an unsigned one when the org root is not here").action(withClient(program, async ({ gOpts, dirs, actingAgent }, opts) => {
11834
+ const signed = saveForAgent(dirs, await actingAgent(), {
11835
+ perTxCap: opts.perTxCap,
11836
+ dailyCap: opts.dailyCap,
11837
+ allowedAssets: csv(opts.allowedAssets),
11838
+ allowedNetworks: csv(opts.allowedNetworks),
11839
+ autoPayThreshold: opts.autoPayThreshold,
11840
+ autoPay: opts.autoPay,
11841
+ allowRepay: opts.allowRepay === true
11842
+ }, opts.force === true);
11843
+ if (!signed) console.error(UNSIGNED_NOTE);
11844
+ if (gOpts.json) printJson({
11845
+ ok: true,
11846
+ signed
11847
+ });
11848
+ else printSuccess(signed ? "Spend policy updated and signed by the org" : "Spend policy updated");
11849
+ }));
11850
+ }
11851
+ //#endregion
11852
+ //#region src/commands/wallet.ts
11103
11853
  function registerWallet(program) {
11104
11854
  const wallet = program.command("wallet").description("Manage the agent payment wallet and spend policy (x402)");
11105
- wallet.command("create").description("Create a payment wallet for an agent (refuses to overwrite)").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
11855
+ wallet.command("create").description("Create a payment wallet for an agent (refuses to overwrite)").addOption(actorOption()).action(withClient(program, async ({ gOpts, dirs: { configDir }, actingAgent }) => {
11106
11856
  const agentId = await actingAgent();
11107
11857
  if (walletKeyExists(configDir, agentId)) {
11108
11858
  printError(`Wallet already exists for agent ${agentId}. The private key is never overwritten.`);
@@ -11122,7 +11872,7 @@ function registerWallet(program) {
11122
11872
  Value: address
11123
11873
  }]);
11124
11874
  }));
11125
- wallet.command("address").description("Print an agent's payment wallet address").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
11875
+ wallet.command("address").description("Print an agent's payment wallet address").addOption(actorOption()).action(withClient(program, async ({ gOpts, dirs: { configDir }, actingAgent }) => {
11126
11876
  const agentId = await actingAgent();
11127
11877
  if (!walletKeyExists(configDir, agentId)) {
11128
11878
  printError(`No wallet for agent ${agentId}. Run 'rine wallet create' first.`);
@@ -11136,7 +11886,7 @@ function registerWallet(program) {
11136
11886
  });
11137
11887
  else printTable([{ "Wallet address": address }]);
11138
11888
  }));
11139
- wallet.command("policy").description("Show the effective spend policy (deny-by-default when unset)").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
11889
+ registerWalletPolicySet(wallet.command("policy").description("Show the effective spend policy (deny-by-default when unset)").addOption(actorOption()).action(withClient(program, async ({ gOpts, dirs: { configDir }, actingAgent }) => {
11140
11890
  const agentId = await actingAgent();
11141
11891
  const p = loadPolicy(configDir, agentId);
11142
11892
  if (gOpts.json) {
@@ -11183,16 +11933,7 @@ function registerWallet(program) {
11183
11933
  Value: p.allowedNetworks.join(", ") || "—"
11184
11934
  }
11185
11935
  ]);
11186
- })).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) => {
11187
- savePolicy(configDir, await actingAgent(), {
11188
- perTxCap: opts.perTxCap,
11189
- dailyCap: opts.dailyCap,
11190
- allowedAssets: csv(opts.allowedAssets),
11191
- allowedNetworks: csv(opts.allowedNetworks),
11192
- autoPayThreshold: opts.autoPayThreshold
11193
- });
11194
- printMutationOk("Spend policy updated", gOpts.json);
11195
- }));
11936
+ })), program);
11196
11937
  }
11197
11938
  //#endregion
11198
11939
  //#region src/commands/webhook.ts
@@ -11265,29 +12006,37 @@ function registerWebhook(program) {
11265
12006
  }));
11266
12007
  }
11267
12008
  //#endregion
11268
- //#region src/main.ts
12009
+ //#region src/program.ts
11269
12010
  const { version } = createRequire(import.meta.url)("../package.json");
11270
- const program = new Command("rine").version(version).description("rine.network CLI — messaging infrastructure for AI agents").option("--profile <name>", "profile to use (default: the owner's org profile, else \"default\")").option("--json", "output as JSON").option("--as <agent>", "which agent is acting — the retired spelling of --agent (name, handle, or agent ID)");
11271
- registerAuth(program);
11272
- registerRegister(program);
11273
- registerOnboard(program);
11274
- registerOrg(program);
11275
- registerAgent(program);
11276
- registerAgentProfile(program);
11277
- registerMessages(program);
11278
- registerGroup(program);
11279
- registerDiscover(program);
11280
- registerWebhook(program);
11281
- registerHook(program);
11282
- registerWallet(program);
11283
- registerPay(program);
11284
- registerFulfill(program);
11285
- registerKeys(program);
11286
- registerStream(program);
11287
- registerTui(program);
11288
- registerRelay(program);
11289
- registerPollToken(program);
11290
- registerVerifyIdentity(program);
11291
- program.parse();
12011
+ function buildProgram() {
12012
+ const program = new Command("rine").version(version).description("rine.network CLI — messaging infrastructure for AI agents").option("--profile <name>", "profile to use (default: the owner's org profile, else \"default\")").option("--json", "output as JSON").option("--as <agent>", "which agent is acting — the retired spelling of --agent (name, handle, or agent ID)");
12013
+ registerAuth(program);
12014
+ registerRegister(program);
12015
+ registerOnboard(program);
12016
+ registerOrg(program);
12017
+ registerAgent(program);
12018
+ registerAgentProfile(program);
12019
+ registerMessages(program);
12020
+ registerGroup(program);
12021
+ registerDiscover(program);
12022
+ registerWebhook(program);
12023
+ registerHook(program);
12024
+ registerWallet(program);
12025
+ registerPay(program);
12026
+ registerFulfill(program);
12027
+ registerKeys(program);
12028
+ registerStream(program);
12029
+ registerTui(program);
12030
+ registerRelay(program);
12031
+ registerPollToken(program);
12032
+ registerVerifyIdentity(program);
12033
+ registerIdentity(program);
12034
+ registerCatalog(program);
12035
+ refuseOutsideAgentTier(program);
12036
+ return program;
12037
+ }
12038
+ //#endregion
12039
+ //#region src/main.ts
12040
+ buildProgram().parse();
11292
12041
  //#endregion
11293
12042
  export {};