@rine-network/cli 0.22.0 → 0.24.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 +2 -2
  2. package/dist/main.js +2240 -318
  3. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -1,10 +1,11 @@
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, DEFAULT_PROFILE, ENCRYPTION_VERSION_HYBRID_V2, FUNNEL_TIERS, GROUP_NOT_FOUND_LEAD, GROUP_READERS_NOTICE, HttpClient, IdempotencyStore, KEY_NOT_CURRENT_MESSAGE, KeyPackageRotation, MLS_ERR_GROUP_INACTIVE, MLS_EVICTED_BY_COMMIT, MalformedPageError, MlsEstablishStep, MlsInitInFlightError, OrgReader, PHRASE_FILE, PHRASE_INSTRUCTION, ReadGapReason, ReadKey, ReaderNetworkError, RineApiError, SENDER_KEY_UNAVAILABLE_CODE, SENDER_KEY_UNAVAILABLE_PREVIEW, SeatUpdateStatus, THREAD_REF_SURFACES, THREAD_UNAVAILABLE, TokenBucket, UUID_RE, VOTE_DURATION_RULE, VOTE_ELECTORATE_RULE, X402Error, X402FacilitatorError, X402_ERROR, X402_MESSAGE_TYPE, a2aCleartextMark, a2aCleartextPayload, a2aCleartextPlaintext, actorFromEnv, addMlsGroupMembers, admissionHeadline, admittedAgentIds, agentKeysExist, agentKeysFromPrivate, agentLabel, asSenderKeyUnavailable, assertBranchName, assertNoMlsDowngrade, buildIssueCertDeps, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildPeerVerification, buildReceiptMessage, cliSyncRemedy, clipToWidth, clipWithEllipsis, clusterWidth, compareVerificationWordsForAgent, connectTunnel, controlFrameReplyRefusal, createBranch, createHook, createWallet, decryptGroupMessageWithRecovery, decryptMessage, decryptThreadRows, deleteGroupMember, deleteHookSecret, deriveBranch, describeEscrowGaps, describeMlsReclamation, describeMlsRecovery, describeVoteEligibility, displayHandle, displayWidth, encryptGroupMessage, encryptionLine, ensureCert, establishMlsMembership, evictionMessage, fetchAgents, fetchGroupMembers, findingKey, fitFromTo, fitGroupSender, formatError, fromBase64Url, gapToJson, getOrCreateSenderKey, getOrRefreshToken, getWalletAddress, graphemes, groupAcceptsMlsSendOnly, groupAdmissionSkipSentence, groupEncryption, groupEncryption as groupEncryption$1, groupIsMls, groupMlsInitInFlight, handleCompletionNote, handleWebhookRequest, hasRoot, hasSpiffeEndpoint, holdsAnyMlsState, holdsBranchKeys, holdsMlsState, hookNameError, humanTime, impliedVoteEligibilityReason, inBackground, ingestSenderKeyDistribution, initMlsGroup, inviteNominates, isA2aCleartext, isAuthenticityFailure, isAutoPayable, isControlFrameType, isDecryptableVersion, isEpochConflict, isGroupEncryptionVersion, isMlsResyncUnavailable, isMlsRotatedLeaf, isPathSafeId, isRecoverableMlsRead, isX402MessageType, jitteredDelayMs, jitteredRefreshMargin, listMyInvites, loadAgentKeys, loadHookSecret, loadMeta, loadMlsGroup, loadMlsState, loadOrgFromOwner, loadPolicy, loadProfiles, loadSenderKeyStates, loadTokenCache, loadWalletKey, makeEdgePipeFactory, markA2aCleartext, matchedQuoteToWire, messageToJson, mlsAdmissionSkipSentence, mlsErrorCode, mlsInitInFlightSync, mlsReadRefusal, namesASeatedSibling, nextReconnectBackoffSeconds, normalizeActor, normalizeHandle, openMlsClient, orgIdOfAgent, ownIdentityFor, parseFacilitatorHeaders, parseRecipientKey, parseX402Payload, peerVerificationLines, performAgentCreation, performRecovery, performRegistration, principalString, readDailySpent, readOwnerPhrase, readThreadPage, readableGroupById, recipientKeyWords, recordPeerVerification, recoverGroup, refusalReceiptBody, renewalDueWithJitter, reportFailedSetup, requireVerifiedPlaintext, reserveSpend, resolveAgent, resolveApiUrl, resolveAuth, resolveConfigDir, resolveFacilitatorConfig, resolveGroup, resolveGroupByHandle, resolveGroupForJoin, resolveOwnerDir, resolvePayeeRequirement, resolveThreadRef, resolveToUuid, restoreOwnerFromPhrase, resumeMlsGroupAdmission, retireLocalGroupState, retirementMessage, retryAfterMsFromError, revokeBranch, rotateAgentWithSeats, safeBlock, saveAgentKeys, savePolicy, saveProfiles, saveTokenCache, scrub, sealAndPostMlsGroupMessage, sealBranchBundle, sealForAgent, seatUpdateLine, seatedMemberAfterConflict, selectRequirement, sendGroupInviteNotification, sendReceipt, senderKeyExplainer, settleToReceipt, singleActorValue, sleep, startTlsListener, startupEscrowSweep, toBase64Url, validateEncryptionKey, validateSigningKey, validateSlug, verificationWordsLines, verifyIdentitySpiffe, walletKeyExists, withA2aCleartextNotice, withEvictionPointer, withPeekHeader, writeAtomic } from "@rine-network/core";
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";
4
4
  import * as fs$1 from "node:fs";
5
5
  import fs, { readFileSync } from "node:fs";
6
6
  import readline from "node:readline";
7
7
  import { join } from "node:path";
8
+ import { createHash, randomBytes } from "node:crypto";
8
9
  import { resolve4 } from "node:dns/promises";
9
10
  import { createEventSource } from "eventsource-client";
10
11
  //#region src/output.ts
@@ -580,41 +581,6 @@ function toAgentRow(a, opts = {}) {
580
581
  return row;
581
582
  }
582
583
  //#endregion
583
- //#region src/handle-completion.ts
584
- /**
585
- * Tell the caller when the spelling they typed was not the spelling looked up.
586
- *
587
- * 🔴 `resolveToUuid` completes a short handle before it reaches
588
- * WebFinger — `kofi@acme` is looked up as `kofi@acme.rine.network` — and it
589
- * returns the resolved UUID, never the handle it resolved. So the substitution
590
- * is invisible at every call site by construction: the caller asked about one
591
- * agent and may be told about another, with nothing on either stream saying so.
592
- *
593
- * The completion itself is a good default and stays. What changes is that it
594
- * stops being silent.
595
- *
596
- * 🔴 STDERR, and deliberately NOT gated on `--json`: the machine reader is the
597
- * caller a silent rewrite harms most, and stdout stays byte-for-byte parseable
598
- * because the notice was never on it.
599
- *
600
- * 🔴 The SENTENCE is {@link handleCompletionNote}'s, in `@rine-network/core`,
601
- * and is not retyped here. Four surfaces say it and each renders it
602
- * differently — a stderr line here, a result key on `@rine-network/mcp`, a
603
- * result line on `rine-mastra` and `rine-eve` — so the bytes live in one place
604
- * and this module decides only where they go. That also keeps `normalizeHandle`
605
- * CALLED rather than restated: a second copy of the completion rule could
606
- * disagree with the lookup and announce a substitution that never happened.
607
- *
608
- * What that composer returns for a value with no `@`, or for a UUID, is
609
- * nothing — and this prints nothing, which is correct: `resolveToUuid` refuses
610
- * that arm outright rather than completing it, so there is no substitution to
611
- * report.
612
- */
613
- function announceHandleCompletion(spelling) {
614
- const note = handleCompletionNote(spelling);
615
- if (note !== void 0) printError(note);
616
- }
617
- //#endregion
618
584
  //#region src/prompt.ts
619
585
  /** Prompt for a plain-text value on stdout/stdin. */
620
586
  async function promptText(question) {
@@ -659,6 +625,213 @@ async function promptConfirm(question) {
659
625
  return (await promptText(`${question} [y/N] `)).toLowerCase() === "y";
660
626
  }
661
627
  //#endregion
628
+ //#region src/commands/agent-exposure-create.ts
629
+ const EXPOSURE_OPTION_HELP = "What the agent shows the outside: private, findable or listed";
630
+ /** The `--exposure` value as a preset, or an error naming the three. */
631
+ function exposurePreset(value) {
632
+ if (value === void 0) return void 0;
633
+ if (!isNamedPreset(value)) throw new Error(`--exposure takes private, findable or listed, not '${value}'.`);
634
+ return value;
635
+ }
636
+ /**
637
+ * After a create with `--exposure`: the summary of what the server set, in the server's own
638
+ * preset (its effective A2A is off until the card enables it), then the capped notice when the
639
+ * organisation's ceiling lowered it. Without the flag: the private notice when the agent came
640
+ * back Private.
641
+ */
642
+ function announceExposure(agent, asked) {
643
+ if (agent.exposure == null) return;
644
+ if (asked !== void 0) {
645
+ const preset = agent.preset ?? presetOf(agent.exposure, false);
646
+ printText(presetLine(agent.name, agent.exposure, preset));
647
+ const capped = cappedLine(asked, agent.preset);
648
+ if (capped !== null) printText(capped);
649
+ } else if (agent.preset === Preset.Private) printText(createdPrivateLine(agent.name));
650
+ }
651
+ //#endregion
652
+ //#region src/commands/agent-create.ts
653
+ 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) => {
655
+ const exposure = exposurePreset(opts.exposure);
656
+ let name = opts.name;
657
+ if (!name) {
658
+ name = await promptText("Agent name: ");
659
+ if (!name) {
660
+ printError("Agent name is required");
661
+ process.exitCode = 2;
662
+ return;
663
+ }
664
+ }
665
+ const profile = gOpts.profile ?? DEFAULT_PROFILE;
666
+ const data = await performAgentCreation(client, {
667
+ configDir,
668
+ ownerDir
669
+ }, profile, {
670
+ name,
671
+ humanOversight: opts.humanOversight,
672
+ unlisted: opts.unlisted,
673
+ exposure
674
+ });
675
+ const verification = compareVerificationWordsForAgent(configDir, data.id, data.verification_words);
676
+ if (gOpts.json) printJson({
677
+ ...data,
678
+ verification
679
+ });
680
+ else {
681
+ printTable([toAgentRow(data, {
682
+ includeCard: true,
683
+ verification
684
+ })]);
685
+ console.log(`\nAgent '${data.name}' created \u2014 reachable at ${data.handle}`);
686
+ announceExposure(data, exposure);
687
+ console.log("E2EE keys generated and stored locally.");
688
+ for (const line of verificationWordsLines(verification)) console.log(line);
689
+ if (data.poll_url) console.log(`Poll URL: ${data.poll_url}`);
690
+ if (data.identity) console.log(`SPIFFE identity verified: ${data.identity.spiffe_id} (trust tier ${data.identity.trust_tier})`);
691
+ }
692
+ if (data.identityError) {
693
+ printError(`Agent created, but SPIFFE identity verification failed: ${data.identityError}\nRetry with: rine verify-identity --agent ${data.id} --svid <jwt>`);
694
+ process.exitCode = 1;
695
+ }
696
+ }));
697
+ }
698
+ //#endregion
699
+ //#region src/commands/agent-suspend.ts
700
+ /** A delegated key may not list agents, so it finds them through the org's state list. */
701
+ async function candidates(ctx) {
702
+ if (ctx.auth?.signer.principal.kind === PrincipalKind.Delegate) return (await listAgentStates(ctx.client)).map((s) => ({
703
+ id: s.id,
704
+ name: "",
705
+ handle: s.handle
706
+ }));
707
+ return ctx.agents();
708
+ }
709
+ async function resolveAgent$1(ctx, ref) {
710
+ return pickAgent(UUID_RE.test(ref) ? [] : await candidates(ctx), ref);
711
+ }
712
+ function holdSentence(view, verb) {
713
+ if (!view.changed) return `Agent ${view.agent_id} was already ${verb}.`;
714
+ return `Agent ${view.agent_id} ${verb}.`;
715
+ }
716
+ async function change(ctx, ref, act, verb) {
717
+ const view = await act(ctx.client, await resolveAgent$1(ctx, ref));
718
+ if (ctx.gOpts.json) printJson(view);
719
+ else printText(holdSentence(view, verb));
720
+ }
721
+ function registerAgentSuspend(agent, program) {
722
+ agent.command("suspend <agent>").description("Stop an agent now; messages to it wait in its queue until it is resumed").action(withClient(program, (ctx, ref) => change(ctx, ref, suspendAgent, "suspended")));
723
+ agent.command("resume <agent>").description("Resume an agent suspended by your side").action(withClient(program, (ctx, ref) => change(ctx, ref, resumeAgent, "resumed")));
724
+ agent.command("suspension <agent>").description("Show whether an agent is held, and what waits behind the hold").action(withClient(program, async (ctx, ref) => {
725
+ const view = await getSuspension(ctx.client, await resolveAgent$1(ctx, ref));
726
+ if (ctx.gOpts.json) {
727
+ printJson(view);
728
+ return;
729
+ }
730
+ printText(`Hold: ${view.hold ?? "none"}`);
731
+ printText(`Messages waiting: ${view.queue_depth}`);
732
+ if (view.oldest_queued_at) printText(`Oldest waiting since: ${view.oldest_queued_at}`);
733
+ printText(`Webhook deliveries held: ${view.webhook_jobs_held}`);
734
+ printText(`Keys rotated since the suspension: ${view.rotated_since_suspension ? "yes" : "no"}`);
735
+ }));
736
+ }
737
+ //#endregion
738
+ //#region src/commands/agent-exposure.ts
739
+ /** The exposure lines and ceiling notices for one agent. */
740
+ function describe$1(name, view) {
741
+ const lines = [
742
+ summaryLine(name, view.exposure, view.a2a_available),
743
+ "",
744
+ ...switchLines(name, view)
745
+ ];
746
+ if (view.ceiling) lines.push("", ceilingLine(view.ceiling));
747
+ const above = aboveCeilingLine(name, view);
748
+ if (above) lines.push("", above);
749
+ return lines;
750
+ }
751
+ async function nameOf(ctx, id) {
752
+ return (await ctx.client.get(`/agents/${id}`)).name;
753
+ }
754
+ function flagValue(flag, value) {
755
+ if (value !== "on" && value !== "off") throw new Error(`--${flag} takes on or off, not '${value}'.`);
756
+ return value === "on";
757
+ }
758
+ /** The set a preset and the per-switch flags ask for; flags change the preset, or the current set. */
759
+ function targetOf(preset, opts, current) {
760
+ if (preset !== void 0 && !isNamedPreset(preset)) throw new Error(`The preset is one of ${Object.keys(PRESETS).join(", ")}, not '${preset}'.`);
761
+ const target = { ...preset === void 0 ? current : PRESETS[preset] };
762
+ let flagged = false;
763
+ for (const s of Object.values(Surface)) {
764
+ const value = opts[s];
765
+ if (value === void 0) continue;
766
+ target[s] = flagValue(s, value);
767
+ flagged = true;
768
+ }
769
+ if (preset === void 0 && !flagged) throw new Error("Give a preset (private, findable or listed) or at least one of --directory, --card, --a2a, --did.");
770
+ return target;
771
+ }
772
+ async function setExposure(ctx, ref, preset, opts) {
773
+ const id = await resolveAgent$1(ctx, ref);
774
+ const name = await nameOf(ctx, id);
775
+ const target = targetOf(preset, opts, (await getExposure(ctx.client, id)).exposure);
776
+ if (invalidSurfaces(target).length > 0) throw new Error(EXPOSURE_COPY.invalid);
777
+ const plan = await previewExposure(ctx.client, id, target);
778
+ if (plan.refused.length > 0) throw new Error(refusedLine(plan));
779
+ if (!ctx.gOpts.json) for (const line of previewLines(name, plan)) printText(line);
780
+ if (plan.turned_on.length + plan.turned_off.length === 0) return;
781
+ if (!opts.yes && !ctx.gOpts.json && !await promptConfirm("Apply?")) {
782
+ printText("Nothing changed.");
783
+ return;
784
+ }
785
+ const view = await putExposure(ctx.client, id, target);
786
+ if (ctx.gOpts.json) return printJson(view);
787
+ printText("");
788
+ for (const line of describe$1(name, view)) printText(line);
789
+ }
790
+ function registerAgentExposure(agent, program) {
791
+ agent.command("exposure [agent]").description("Show what an agent shows the outside, or change it with `exposure set`").addHelpText("after", `\n${EXPOSURE_COPY.help}`).action(withClient(program, async (ctx, ref) => {
792
+ if (ref === void 0) throw new Error("Name the agent: rine agent exposure <agent>.");
793
+ const id = await resolveAgent$1(ctx, ref);
794
+ const view = await getExposure(ctx.client, id);
795
+ if (ctx.gOpts.json) return printJson(view);
796
+ for (const line of describe$1(await nameOf(ctx, id), view)) printText(line);
797
+ })).command("set <agent> [preset]").description("Set an agent's exposure: private, findable, listed, or switch by switch").option("--directory <on|off>", "Directory listing").option("--card <on|off>", "Profile card").option("--a2a <on|off>", "A2A discovery").option("--did <on|off>", "DID document").option("--yes", "Skip the confirmation prompt").action(withClient(program, (ctx, ref, preset, opts) => setExposure(ctx, ref, preset, opts)));
798
+ }
799
+ //#endregion
800
+ //#region src/handle-completion.ts
801
+ /**
802
+ * Tell the caller when the spelling they typed was not the spelling looked up.
803
+ *
804
+ * 🔴 `resolveToUuid` completes a short handle before it reaches
805
+ * WebFinger — `kofi@acme` is looked up as `kofi@acme.rine.network` — and it
806
+ * returns the resolved UUID, never the handle it resolved. So the substitution
807
+ * is invisible at every call site by construction: the caller asked about one
808
+ * agent and may be told about another, with nothing on either stream saying so.
809
+ *
810
+ * The completion itself is a good default and stays. What changes is that it
811
+ * stops being silent.
812
+ *
813
+ * 🔴 STDERR, and deliberately NOT gated on `--json`: the machine reader is the
814
+ * caller a silent rewrite harms most, and stdout stays byte-for-byte parseable
815
+ * because the notice was never on it.
816
+ *
817
+ * 🔴 The SENTENCE is {@link handleCompletionNote}'s, in `@rine-network/core`,
818
+ * and is not retyped here. Four surfaces say it and each renders it
819
+ * differently — a stderr line here, a result key on `@rine-network/mcp`, a
820
+ * result line on `rine-mastra` and `rine-eve` — so the bytes live in one place
821
+ * and this module decides only where they go. That also keeps `normalizeHandle`
822
+ * CALLED rather than restated: a second copy of the completion rule could
823
+ * disagree with the lookup and announce a substitution that never happened.
824
+ *
825
+ * What that composer returns for a value with no `@`, or for a UUID, is
826
+ * nothing — and this prints nothing, which is correct: `resolveToUuid` refuses
827
+ * that arm outright rather than completing it, so there is no substitution to
828
+ * report.
829
+ */
830
+ function announceHandleCompletion(spelling) {
831
+ const note = handleCompletionNote(spelling);
832
+ if (note !== void 0) printError(note);
833
+ }
834
+ //#endregion
662
835
  //#region src/commands/agent-verify.ts
663
836
  /**
664
837
  * `rine agent verify <peer>` — the out-of-band compare/confirm flow.
@@ -732,46 +905,6 @@ function registerAgentVerify(program, agent) {
732
905
  //#region src/commands/agent.ts
733
906
  function registerAgent(program) {
734
907
  const agent = program.command("agent").description("Agent management");
735
- 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)").action(withClient(program, async ({ client, gOpts, configDir, ownerDir }, opts) => {
736
- let name = opts.name;
737
- if (!name) {
738
- name = await promptText("Agent name: ");
739
- if (!name) {
740
- printError("Agent name is required");
741
- process.exitCode = 2;
742
- return;
743
- }
744
- }
745
- const profile = gOpts.profile ?? DEFAULT_PROFILE;
746
- const data = await performAgentCreation(client, {
747
- configDir,
748
- ownerDir
749
- }, profile, {
750
- name,
751
- humanOversight: opts.humanOversight,
752
- unlisted: opts.unlisted
753
- });
754
- const verification = compareVerificationWordsForAgent(configDir, data.id, data.verification_words);
755
- if (gOpts.json) printJson({
756
- ...data,
757
- verification
758
- });
759
- else {
760
- printTable([toAgentRow(data, {
761
- includeCard: true,
762
- verification
763
- })]);
764
- console.log(`\nAgent '${data.name}' created \u2014 reachable at ${data.handle}`);
765
- console.log("E2EE keys generated and stored locally.");
766
- for (const line of verificationWordsLines(verification)) console.log(line);
767
- if (data.poll_url) console.log(`Poll URL: ${data.poll_url}`);
768
- if (data.identity) console.log(`SPIFFE identity verified: ${data.identity.spiffe_id} (trust tier ${data.identity.trust_tier})`);
769
- }
770
- if (data.identityError) {
771
- printError(`Agent created, but SPIFFE identity verification failed: ${data.identityError}\nRetry with: rine verify-identity --agent ${data.id} --svid <jwt>`);
772
- process.exitCode = 1;
773
- }
774
- }));
775
908
  agent.command("list").description("List all agents").option("--include-revoked", "Include revoked agents").action(withClient(program, async ({ client, gOpts }, opts) => {
776
909
  const params = opts.includeRevoked ? { include_revoked: true } : void 0;
777
910
  const data = await client.get("/agents", params);
@@ -787,14 +920,14 @@ function registerAgent(program) {
787
920
  "Outgoing Policy": data.outgoing_policy ?? "send_all"
788
921
  }]);
789
922
  }));
790
- agent.command("update").description("Update agent details").argument("<agent-id>", "Agent ID").option("--name <name>", "Agent name").option("--[no-]human-oversight", "Require human oversight").option("--incoming-policy <policy>", "Incoming message policy (accept_all|groups_only)").option("--outgoing-policy <policy>", "Outgoing message policy (send_all|groups_only)").action(withClient(program, async ({ client, gOpts }, agentId, opts) => {
923
+ agent.command("update").description("Update agent details").argument("<agent-id>", "Agent ID").option("--[no-]human-oversight", "Require human oversight").option("--unlisted", "Hide the agent from the directory").option("--no-unlisted", "List the agent in the directory again").option("--incoming-policy <policy>", "Incoming message policy (accept_all|groups_only)").option("--outgoing-policy <policy>", "Outgoing message policy (send_all|groups_only)").action(withClient(program, async ({ client, gOpts }, agentId, opts) => {
791
924
  const body = {};
792
- if (opts.name) body.name = opts.name;
793
925
  if (opts.humanOversight !== void 0) body.human_oversight = opts.humanOversight;
794
926
  if (opts.incomingPolicy) body.incoming_policy = opts.incomingPolicy;
795
927
  if (opts.outgoingPolicy) body.outgoing_policy = opts.outgoingPolicy;
928
+ if (opts.unlisted !== void 0) body.unlisted = opts.unlisted;
796
929
  if (Object.keys(body).length === 0) {
797
- printError("At least one of --name, --human-oversight, --incoming-policy, --outgoing-policy is required");
930
+ printError("At least one of --incoming-policy, --outgoing-policy, --human-oversight, --no-human-oversight, --unlisted or --no-unlisted is required");
798
931
  process.exitCode = 2;
799
932
  return;
800
933
  }
@@ -819,6 +952,9 @@ function registerAgent(program) {
819
952
  }
820
953
  }));
821
954
  registerAgentVerify(program, agent);
955
+ registerAgentCreate(agent, program);
956
+ registerAgentSuspend(agent, program);
957
+ registerAgentExposure(agent, program);
822
958
  }
823
959
  //#endregion
824
960
  //#region src/commands/whoami.ts
@@ -1270,7 +1406,7 @@ function registerDiscoverGroups(discover, program) {
1270
1406
  Name: g.name,
1271
1407
  Handle: g.handle,
1272
1408
  Description: g.description ?? "",
1273
- Enrollment: g.enrollment_policy,
1409
+ Enrolment: g.enrollment_policy,
1274
1410
  Members: g.member_count
1275
1411
  })));
1276
1412
  })).command("inspect").description("Inspect a public group").argument("<group-id>", DIRECTORY_GROUP_ID_HELP).action(withErrorHandler(program, async (gOpts, groupId) => {
@@ -1291,7 +1427,7 @@ function registerDiscoverGroups(discover, program) {
1291
1427
  Handle: data.handle,
1292
1428
  Description: data.description ?? "",
1293
1429
  "Org ID": data.org_id,
1294
- Enrollment: data.enrollment_policy,
1430
+ Enrolment: data.enrollment_policy,
1295
1431
  Members: data.member_count,
1296
1432
  Created: data.created_at
1297
1433
  }]);
@@ -1474,23 +1610,23 @@ function registerFulfill(program) {
1474
1610
  const payeeAgentId = await actingAgent();
1475
1611
  const message = await client.get(`/messages/${messageId}`);
1476
1612
  if (message.type !== X402_MESSAGE_TYPE.PAYMENT) {
1477
- printError(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT}. Nothing to fulfill.`);
1613
+ printError(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT}. Nothing to fulfil.`);
1478
1614
  process.exitCode = 2;
1479
1615
  return;
1480
1616
  }
1481
1617
  const payerAgentId = message.from_agent_id;
1482
1618
  if (!payerAgentId) {
1483
- printError("Cannot fulfill: the payment has no resolvable sender.");
1619
+ printError("Cannot fulfil: the payment has no resolvable sender.");
1484
1620
  process.exitCode = 1;
1485
1621
  return;
1486
1622
  }
1487
1623
  if (payeeAgentId === payerAgentId) {
1488
- printError("Cannot fulfill your own payment.");
1624
+ printError("Cannot fulfil your own payment.");
1489
1625
  process.exitCode = 1;
1490
1626
  return;
1491
1627
  }
1492
1628
  if (message.to_agent_id && message.to_agent_id !== payeeAgentId) {
1493
- printError(`Payment ${messageId} is addressed to agent ${message.to_agent_id}, not ${payeeAgentId}. Fulfill as that agent (--agent) — only the addressee holds the key that opens it.`);
1629
+ printError(`Payment ${messageId} is addressed to agent ${message.to_agent_id}, not ${payeeAgentId}. Fulfil as that agent (--agent) — only the addressee holds the key that opens it.`);
1494
1630
  process.exitCode = 1;
1495
1631
  return;
1496
1632
  }
@@ -1788,7 +1924,7 @@ function groupRow(g) {
1788
1924
  ID: g.id,
1789
1925
  Name: g.name,
1790
1926
  Handle: g.handle,
1791
- Enrollment: g.enrollment_policy,
1927
+ Enrolment: g.enrollment_policy,
1792
1928
  Visibility: g.visibility,
1793
1929
  Members: g.member_count,
1794
1930
  "Conversation ID": g.conversation_id ?? "(none — nothing has been said in this group yet)",
@@ -1811,7 +1947,7 @@ function groupDetailRow(g, handles) {
1811
1947
  Name: g.name,
1812
1948
  Handle: g.handle,
1813
1949
  Description: g.description ?? "",
1814
- Enrollment: g.enrollment_policy,
1950
+ Enrolment: g.enrollment_policy,
1815
1951
  Visibility: g.visibility,
1816
1952
  Isolated: g.isolated,
1817
1953
  "Vote Duration": g.vote_duration_hours,
@@ -2110,7 +2246,7 @@ function printCreated$1(group, roster, admission, json, handles) {
2110
2246
  }
2111
2247
  }
2112
2248
  function registerGroupCreate(program, group) {
2113
- group.command("create").description(`Create a new group. ${GROUP_READERS_NOTICE}`).requiredOption("--name <name>", "Group name (DNS-safe slug)").option("--description <desc>", DESCRIPTION_HELP).option("--enrollment <policy>", "Enrollment policy (open|closed|majority|unanimity). `open` runs Sender Keys, which are NOT post-quantum").option("--visibility <vis>", "Required. `public` lists the group at dir.rine.network and turns the join signal off; `private` does neither").option("--member <id>", "Invite an agent into the new group (repeatable). A roster invites — it never seats — and it invites under every enrollment policy, because you are the only member at founding and a vote would auto-approve each row", collect, []).option("--isolated", "Isolate group communication").option("--vote-duration <hours>", VOTE_DURATION_RULE).addOption(actorOption("which agent is acting, and founds the group")).action(withClient(program, async (ctx, opts) => {
2249
+ group.command("create").description(`Create a new group. ${GROUP_READERS_NOTICE}`).requiredOption("--name <name>", "Group name (DNS-safe slug)").option("--description <desc>", DESCRIPTION_HELP).option("--enrollment <policy>", "Enrolment policy (open|closed|majority|unanimity). `open` runs Sender Keys, which are NOT post-quantum").option("--visibility <vis>", "Required. `public` lists the group at dir.rine.network and turns the join signal off; `private` does neither").option("--member <id>", "Invite an agent into the new group (repeatable). A roster invites — it never seats — and it invites under every enrolment policy, because you are the only member at founding and a vote would auto-approve each row", collect, []).option("--isolated", "Isolate group communication").option("--vote-duration <hours>", VOTE_DURATION_RULE).addOption(actorOption("which agent is acting, and founds the group")).action(withClient(program, async (ctx, opts) => {
2114
2250
  const refusal = visibilityRefusal(opts.visibility);
2115
2251
  if (refusal) {
2116
2252
  printError(refusal);
@@ -2178,9 +2314,11 @@ function registerGroupCrud(program, group) {
2178
2314
  }
2179
2315
  printTable([groupDetailRow(data, data.member_agent_ids?.length ? await ownAgentHandles(ctx.agents) : void 0)]);
2180
2316
  printText(encryptionLine(data, CLI_UNFOUNDED_REPAIR));
2317
+ const posting = postingLine(data);
2318
+ if (posting) printText(posting);
2181
2319
  if (evicted) printText(`\n${evictedMessage(data.id)}`);
2182
2320
  }));
2183
- group.command("update").description("Update group settings").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).option("--description <desc>", DESCRIPTION_HELP).option("--enrollment <policy>", "Enrollment policy (open|closed|majority|unanimity)").option("--visibility <vis>", "`public` lists the group at dir.rine.network and turns the join signal off; `private` does neither").option("--vote-duration <hours>", VOTE_DURATION_RULE).action(withClient(program, async (ctx, ref, opts) => {
2321
+ group.command("update").description("Update group settings").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).option("--description <desc>", DESCRIPTION_HELP).option("--enrollment <policy>", "Enrolment policy (open|closed|majority|unanimity)").option("--visibility <vis>", "`public` lists the group at dir.rine.network and turns the join signal off; `private` does neither").option("--vote-duration <hours>", VOTE_DURATION_RULE).action(withClient(program, async (ctx, ref, opts) => {
2184
2322
  const { client, gOpts, actingAgent, agents } = ctx;
2185
2323
  const body = {};
2186
2324
  if (opts.description !== void 0) body.description = opts.description;
@@ -2638,7 +2776,7 @@ function registerGroupMembership(program, group) {
2638
2776
  //#endregion
2639
2777
  //#region src/commands/group-requests.ts
2640
2778
  /** An open group has no ratchet tree, so there is no admission to resume in it. */
2641
- const NOT_AN_MLS_GROUP = "This group runs on Sender Keys, not MLS, so it has no ratchet tree to seat anyone in. Open-enrollment groups are sender-key groups by design: MLS would hand an unattested joiner a cryptographic seat, so the server keeps open enrollment off the MLS path. There is nothing to resume here.";
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.";
2642
2780
  function printAdmission(result, json) {
2643
2781
  if (json) {
2644
2782
  printJson(result);
@@ -3119,6 +3257,25 @@ function registerKeys(program) {
3119
3257
  registerKeysTransfer(keys, program);
3120
3258
  }
3121
3259
  //#endregion
3260
+ //#region src/commands/hide-control.ts
3261
+ /** Help text for `--hide-control` on the commands that only list messages. */
3262
+ const HIDE_CONTROL_HELP = "Omit group-key and group-invite control frames from the output (they are not marked read or changed)";
3263
+ /** Help text for `--hide-control` on `stream`, which marks every message it settles delivered. */
3264
+ const STREAM_HIDE_CONTROL_HELP = "Omit group-key and group-invite control frames from the output (they are still marked delivered once settled, like any other message)";
3265
+ /** `rows` without their control frames when `hide` is set, otherwise as they are. */
3266
+ function withoutControlFrames(rows, hide) {
3267
+ return hide ? rows.filter((row) => !isControlFrameType(row.type ?? "")) : rows;
3268
+ }
3269
+ /** Whether a streamed message event's data is a control frame; data that does not parse is not. */
3270
+ function isControlEventData(data) {
3271
+ try {
3272
+ const parsed = JSON.parse(data);
3273
+ return typeof parsed?.type === "string" && isControlFrameType(parsed.type);
3274
+ } catch {
3275
+ return false;
3276
+ }
3277
+ }
3278
+ //#endregion
3122
3279
  //#region src/commands/messages-rows.ts
3123
3280
  function msgFrom(m) {
3124
3281
  return m.sender_handle ?? m.from_agent_id ?? "";
@@ -3143,7 +3300,11 @@ function sendRow(m) {
3143
3300
  /** The posted message, as `send` and `reply` both print it. */
3144
3301
  function printSent(data, json) {
3145
3302
  if (json) printJson(data);
3146
- else printTable([sendRow(data)]);
3303
+ else {
3304
+ printTable([sendRow(data)]);
3305
+ const unreadable = unreadableByOrgsSentence(data.unreadable_by_orgs);
3306
+ if (unreadable) console.log(unreadable);
3307
+ }
3147
3308
  }
3148
3309
  /**
3149
3310
  * The columns for a table: every key any row carries, in first-seen order. An
@@ -3201,7 +3362,7 @@ function threadRow(e) {
3201
3362
  //#region src/commands/messages-inbox.ts
3202
3363
  /** Register `inbox` on the `message` command group. */
3203
3364
  function addInboxCommand(parent, program) {
3204
- parent.command("inbox").description("List inbox messages").addOption(actorOption()).option("--new", "Show only new (undelivered) messages").option("--delivered", "Show only delivered messages").option("--read", "Show only read messages").option("--limit <n>", "Maximum number of messages to return").option("--cursor <cursor>", "Pagination cursor").action(withClient(program, async ({ client, gOpts, actingAgent }, opts) => {
3365
+ parent.command("inbox").description("List inbox messages").addOption(actorOption()).option("--new", "Show only new (undelivered) messages").option("--delivered", "Show only delivered messages").option("--read", "Show only read messages").option("--limit <n>", "Maximum number of messages to return").option("--cursor <cursor>", "Pagination cursor").option("--hide-control", HIDE_CONTROL_HELP).action(withClient(program, async ({ client, gOpts, actingAgent }, opts) => {
3205
3366
  if ([
3206
3367
  opts.new,
3207
3368
  opts.delivered,
@@ -3215,12 +3376,13 @@ function addInboxCommand(parent, program) {
3215
3376
  if (opts.limit) params.limit = opts.limit;
3216
3377
  if (opts.cursor) params.cursor = opts.cursor;
3217
3378
  const data = await client.get(`/agents/${agentId}/messages`, params);
3379
+ const items = withoutControlFrames(data.items, opts.hideControl);
3218
3380
  if (gOpts.json) printJson({
3219
3381
  ...data,
3220
- items: data.items.map(jsonRow)
3382
+ items: items.map(jsonRow)
3221
3383
  });
3222
3384
  else {
3223
- const rows = data.items.map(inboxRow);
3385
+ const rows = items.map(inboxRow);
3224
3386
  printTable(rows, tableColumns(rows));
3225
3387
  if (data.next_cursor) printText(`Next cursor: ${data.next_cursor}`);
3226
3388
  }
@@ -3242,6 +3404,24 @@ function addInboxCommand(parent, program) {
3242
3404
  * two different outputs: stderr prose for a human, and a field on the `--json`
3243
3405
  * envelope for a program. A helper that printed could only serve one of them.
3244
3406
  */
3407
+ /**
3408
+ * Mark a fetched message delivered once reading it is settled: it opened, was
3409
+ * never ciphertext, or its author was refused. `opened` is null when no decrypt
3410
+ * was attempted (no keys, no authenticated sender). A failed mark is a stderr
3411
+ * warning and the read goes on; the message simply stays new.
3412
+ */
3413
+ async function markIfSettled(client, agentId, data, opened, peek) {
3414
+ const result = opened?.result;
3415
+ const verification_status = result?.verificationStatus ?? opened?.forgedStatus;
3416
+ const failure = await ackAfterRead(client, agentId, [data.id], {
3417
+ settled: isSettledRow({
3418
+ ...data,
3419
+ verification_status
3420
+ }, result?.plaintext !== void 0),
3421
+ peek
3422
+ });
3423
+ if (failure) printError(`Warning: could not mark ${data.id} delivered (${failure.message}); it stays new`);
3424
+ }
3245
3425
  /** Decrypt one message, dispatching on its encryption version. Never throws. */
3246
3426
  async function openMessage(opts) {
3247
3427
  const { client, configDir, agentId, data, fromAgentId } = opts;
@@ -3260,7 +3440,11 @@ async function openMessage(opts) {
3260
3440
  refusal: null
3261
3441
  };
3262
3442
  } catch (err) {
3263
- return { refusal: refusalFor(err, groupId) };
3443
+ const forgedStatus = groupAuthenticityStatus(err) ?? void 0;
3444
+ return {
3445
+ refusal: refusalFor(err, groupId),
3446
+ forgedStatus
3447
+ };
3264
3448
  }
3265
3449
  }
3266
3450
  /**
@@ -3309,20 +3493,19 @@ function refusalFor(err, groupId) {
3309
3493
  function addReadCommand(parent, program) {
3310
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) => {
3311
3495
  const agentId = await actingAgent();
3312
- const data = await client.get(`/messages/${messageId}`, void 0, withPeekHeader(void 0, opts.peek));
3496
+ const data = await client.get(`/messages/${messageId}`, void 0, withPeekHeader(void 0, true));
3313
3497
  const fromAgentId = data.from_agent_id;
3314
- const canDecrypt = fromAgentId !== void 0 && isDecryptableVersion(data.encryption_version) && agentKeysExist(configDir, agentId);
3315
- let refusal = null;
3316
- if (canDecrypt) {
3317
- const opened = await openMessage({
3318
- client,
3319
- configDir,
3320
- agentId,
3321
- data,
3322
- fromAgentId
3323
- });
3498
+ const opened = fromAgentId !== void 0 && isDecryptableVersion(data.encryption_version) && agentKeysExist(configDir, agentId) ? await openMessage({
3499
+ client,
3500
+ configDir,
3501
+ agentId,
3502
+ data,
3503
+ fromAgentId
3504
+ }) : null;
3505
+ await markIfSettled(client, agentId, data, opened, opts.peek);
3506
+ const refusal = opened?.refusal ?? null;
3507
+ if (opened) {
3324
3508
  const decResult = opened.result;
3325
- refusal = opened.refusal;
3326
3509
  if (refusal !== null && !gOpts.json) printError(refusal.message);
3327
3510
  if (decResult) {
3328
3511
  if (ingestSenderKeyDistribution(configDir, agentId, data.type, decResult)) printText("Sender key ingested");
@@ -3483,6 +3666,7 @@ function x402SendExtras(type, payload, emitMarker) {
3483
3666
  async function sealForGroup(client, configDir, senderAgentId, group, payload, body) {
3484
3667
  const mlsOnly = groupAcceptsMlsSendOnly(group);
3485
3668
  assertNoMlsDowngrade(configDir, senderAgentId, group.id, mlsOnly);
3669
+ assertGroupPostable(group);
3486
3670
  if (mlsOnly) {
3487
3671
  if (group.mls_group_id == null) throw new MlsInitInFlightError(group.handle);
3488
3672
  return (sendFields) => sealAndPostMlsGroupMessage({
@@ -3649,16 +3833,16 @@ function addMessageCommands(parent, program) {
3649
3833
  registerSend(parent, program);
3650
3834
  addInboxCommand(parent, program);
3651
3835
  addReplyCommand(parent, program);
3652
- parent.command("thread").description("Show the both-sided, decrypted transcript of a conversation or a group (role-tagged)").argument("[conversation-id]", "Conversation ID").option("--group <ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).option("--limit <n>", "Max turns to return (most-recent window)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, conversationId, opts) => {
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) => {
3653
3837
  const ref = resolveThreadRef({
3654
3838
  group: opts.group,
3655
3839
  conversationId
3656
3840
  }, THREAD_REF_SURFACES.cli);
3657
3841
  const agentId = await actingAgent();
3658
- const entries = await decryptThreadRows(configDir, agentId, (await readThreadPage(client, ref, {
3842
+ const entries = withoutControlFrames(await decryptThreadRows(configDir, agentId, (await readThreadPage(client, ref, {
3659
3843
  ...opts.limit ? { limit: opts.limit } : {},
3660
3844
  extraHeaders: { [ACTING_AGENT_HEADER]: agentId }
3661
- })).messages ?? [], client);
3845
+ })).messages ?? [], client, null), opts.hideControl);
3662
3846
  if (gOpts.json) printJson(entries);
3663
3847
  else printTable(entries.map(threadRow));
3664
3848
  }));
@@ -3696,7 +3880,8 @@ function announcePhrase(opts) {
3696
3880
  //#endregion
3697
3881
  //#region src/commands/onboard.ts
3698
3882
  function registerOnboard(program) {
3699
- program.command("onboard").description("Register a new organization and create your first agent").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organization name").requiredOption("--slug <slug>", "Organization slug").requiredOption("--agent-name <name>", "Name for the first agent").option("--[no-]human-oversight", "Require human oversight (default: true)").option("--unlisted", "Mark agent as unlisted (not in public directory)").option("--verify-identity", "After creating the agent, prove a SPIFFE identity (auto-runs when SPIFFE_ENDPOINT_SOCKET is set)").option("--svid <jwt>", "SPIFFE JWT-SVID to use for --verify-identity (when no Workload API auto-fetch is available)").action(withErrorHandler(program, async (gOpts, opts) => {
3883
+ 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
+ const exposure = exposurePreset(opts.exposure);
3700
3885
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
3701
3886
  const dirs = resolveDirs();
3702
3887
  const apiUrl = resolveApiUrl();
@@ -3744,6 +3929,7 @@ function registerOnboard(program) {
3744
3929
  name: opts.agentName,
3745
3930
  humanOversight: opts.humanOversight,
3746
3931
  unlisted: opts.unlisted,
3932
+ exposure,
3747
3933
  verifyIdentity: opts.verifyIdentity || Boolean(opts.svid) || hasSpiffeEndpoint(),
3748
3934
  svid: opts.svid
3749
3935
  });
@@ -3767,6 +3953,7 @@ function registerOnboard(program) {
3767
3953
  })]);
3768
3954
  console.log(`Org verification words: ${reg.org_words}`);
3769
3955
  console.log(`\nAgent '${agent.name}' created — reachable at ${agent.handle}`);
3956
+ announceExposure(agent, exposure);
3770
3957
  for (const line of verificationWordsLines(verification)) console.log(line);
3771
3958
  if (agent.poll_url) console.log(`Poll URL: ${agent.poll_url}`);
3772
3959
  if (agent.identity) console.log(`SPIFFE identity verified: ${agent.identity.spiffe_id} (trust tier ${agent.identity.trust_tier})`);
@@ -3778,11 +3965,45 @@ function registerOnboard(program) {
3778
3965
  }));
3779
3966
  }
3780
3967
  //#endregion
3968
+ //#region src/commands/org-freeze.ts
3969
+ function render$1(view, json, frozen) {
3970
+ if (json) {
3971
+ printJson(view);
3972
+ return;
3973
+ }
3974
+ const state = frozen ? "frozen" : "unfrozen";
3975
+ printText(view.changed ? `Organisation ${state}.` : `Organisation was already ${state}.`);
3976
+ }
3977
+ function registerOrgFreeze(org, program) {
3978
+ org.command("freeze").description("Stop every agent in the organisation at once").action(withClient(program, async ({ client, gOpts }) => {
3979
+ render$1(await freezeOrg(client), gOpts.json, true);
3980
+ }));
3981
+ org.command("unfreeze").description("Lift your organisation's freeze; agents you suspended one by one stay suspended").action(withClient(program, async ({ client, gOpts }) => {
3982
+ render$1(await unfreezeOrg(client), gOpts.json, false);
3983
+ }));
3984
+ }
3985
+ function renderBranch(view, json, state) {
3986
+ if (json) {
3987
+ printJson(view);
3988
+ return;
3989
+ }
3990
+ printText(view.changed ? `Branch '${view.name}' ${state}.` : `Branch '${view.name}' was already ${state}.`);
3991
+ }
3992
+ function registerBranchHold(branch, program) {
3993
+ branch.command("suspend <name>").description("Stop every agent in a branch at once; messages to them wait in their queues").action(withClient(program, async ({ client, gOpts }, name) => {
3994
+ renderBranch(await suspendBranch(client, name), gOpts.json, "suspended");
3995
+ }));
3996
+ branch.command("resume <name>").description("Resume a suspended branch; agents suspended one by one stay suspended").action(withClient(program, async ({ client, gOpts }, name) => {
3997
+ renderBranch(await resumeBranch(client, name), gOpts.json, "resumed");
3998
+ }));
3999
+ }
4000
+ //#endregion
3781
4001
  //#region src/commands/org-branch.ts
3782
- const NO_ROOT = "Creating a branch needs this org's root key (root.key in the owner dir). A delegate cannot create branches.";
4002
+ const NO_ROOT = "Creating a branch needs this org's root key (root.key in the owner directory). A delegate cannot create branches.";
3783
4003
  function registerOrgBranch(org, program) {
3784
4004
  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");
3785
- branch.command("create <name>").description("Create a branch and seal its bundle to a recipient key").requiredOption("--to <recipient-key>", "The fleet'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) => {
4005
+ 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) => {
3786
4007
  assertBranchName(name);
3787
4008
  const org = loadOrgFromOwner(ownerDir);
3788
4009
  if (org === void 0) {
@@ -3844,43 +4065,1296 @@ function registerOrgBranch(org, program) {
3844
4065
  }));
3845
4066
  }
3846
4067
  //#endregion
3847
- //#region src/commands/org-recover.ts
3848
- /** Read the phrase without ever letting it reach argv or an echoed prompt. */
3849
- async function readPhrase() {
3850
- if (process.stdin.isTTY !== true) {
3851
- const chunks = [];
3852
- for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
3853
- return Buffer.concat(chunks).toString("utf-8").trim();
4068
+ //#region src/commands/org-delegate.ts
4069
+ const NAME_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
4070
+ /** A 32-byte Ed25519 public key, base64url without padding. */
4071
+ const PUBLIC_KEY_RE = /^[A-Za-z0-9_-]{43}$/;
4072
+ function parseScopes(list) {
4073
+ const known = Object.values(DelegateScope);
4074
+ const scopes = list.split(",").map((s) => s.trim());
4075
+ const bad = scopes.filter((s) => !known.some((k) => k === s));
4076
+ if (scopes.length === 0 || bad.length > 0) throw new Error(`Unknown scope '${bad[0] ?? list}'. Scopes: ${known.join(", ")}.`);
4077
+ return [...new Set(scopes)];
4078
+ }
4079
+ const created = (d) => `Delegated key '${d.name}' created (${d.id}) with scopes: ${d.scopes.join(", ")}.`;
4080
+ /** Registers a key the caller holds elsewhere: no seed is saved and no profile is added. */
4081
+ async function createWithKey(ctx, opts, publicKey) {
4082
+ if (!PUBLIC_KEY_RE.test(publicKey)) throw new Error("--public-key must be a 32-byte Ed25519 public key in base64url, 43 characters.");
4083
+ const delegate = await createDelegate(ctx.client, opts.name, parseScopes(opts.scope), publicKey);
4084
+ if (ctx.gOpts.json) printJson(delegate);
4085
+ else printText(created(delegate));
4086
+ }
4087
+ async function create(ctx, opts) {
4088
+ const { client, gOpts, configDir, ownerDir, auth } = ctx;
4089
+ if (!NAME_RE.test(opts.name)) throw new Error("--name must be lowercase letters, digits and dashes, at most 32 characters.");
4090
+ if (opts.publicKey !== void 0) return createWithKey(ctx, opts, opts.publicKey);
4091
+ const scopes = parseScopes(opts.scope);
4092
+ const orgId = auth?.orgId;
4093
+ 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.`);
4095
+ const key = newDelegateKey();
4096
+ const delegate = await createDelegate(client, opts.name, scopes, key.publicKey);
4097
+ try {
4098
+ saveDelegateSeed(configDir, delegate.id, key.seed);
4099
+ addProfileIfAbsent(configDir, opts.name, {
4100
+ org_id: orgId,
4101
+ principal: `delegate:${delegate.id}`
4102
+ });
4103
+ } catch (err) {
4104
+ await revokeDelegate(client, delegate.id).catch(() => void 0);
4105
+ throw err;
3854
4106
  }
3855
- return (await promptPassword("Recovery phrase: ")).trim();
4107
+ if (gOpts.json) {
4108
+ printJson({
4109
+ ...delegate,
4110
+ profile: opts.name
4111
+ });
4112
+ return;
4113
+ }
4114
+ printText(created(delegate));
4115
+ printText(`Its private key is in this config directory; use it with --profile ${opts.name}.`);
3856
4116
  }
3857
- function agentRow(agent) {
4117
+ function row(d) {
3858
4118
  return {
3859
- "Agent ID": agent.agent_id,
3860
- Name: agent.name,
3861
- Branch: agent.branch,
3862
- "Key gen": agent.key_gen,
3863
- Status: agent.status,
3864
- Reason: agent.reason ?? ""
4119
+ Name: d.name,
4120
+ ID: d.id,
4121
+ Scopes: d.scopes.join(","),
4122
+ Created: d.created_at,
4123
+ Revoked: d.revoked_at ?? ""
3865
4124
  };
3866
4125
  }
3867
- function reseatRow(reseat) {
3868
- return {
3869
- "Agent ID": reseat.agent_id,
3870
- "Group ID": reseat.group_id ?? "",
3871
- Status: reseat.status,
3872
- Reason: reseat.reason ?? "",
3873
- "Escrow Pending": reseat.escrow_pending,
3874
- "Escrow Gaps": reseat.escrow.gaps.length,
3875
- "Escrow Gap Epochs": describeEscrowGaps(reseat.escrow.gaps),
3876
- "Escrow Deferral": reseat.escrow.deferral ?? "",
3877
- "Escrow Queued": reseat.escrow.queued,
3878
- "Escrow Dropped": reseat.escrow.dropped,
3879
- "Escrow Backlogged": reseat.escrow.backlogged
3880
- };
4126
+ async function revoke(ctx, ref) {
4127
+ let id = ref;
4128
+ if (!UUID_RE.test(ref)) {
4129
+ const hits = (await listDelegates(ctx.client)).filter((d) => d.name === ref && d.revoked_at === null);
4130
+ if (hits.length !== 1) throw new Error(`No live delegated key is named '${ref}'. Use its ID.`);
4131
+ id = hits[0].id;
4132
+ }
4133
+ await revokeDelegate(ctx.client, id);
4134
+ if (ctx.gOpts.json) printJson({
4135
+ id,
4136
+ revoked: true
4137
+ });
4138
+ else printText(`Delegated key ${id} revoked. Its next request is refused; tokens it already holds stop working with it.`);
4139
+ }
4140
+ function registerOrgDelegate(org, program) {
4141
+ const delegate = org.command("delegate").description("Delegated keys that may suspend, freeze or read events");
4142
+ delegate.command("create").description("Create a delegated key and a profile of the same name that signs with it").requiredOption("--name <name>", "Key and profile name").requiredOption("--scope <scopes>", "Comma-separated: events:read, metadata:read, suspend, freeze, resume, counterparty:write, policy:write").option("--public-key <base64url>", "Register this public key instead of generating one; no private key or profile is kept here").action(withClient(program, create));
4143
+ delegate.command("list").description("List delegated keys").action(withClient(program, async ({ client, gOpts }) => {
4144
+ const all = await listDelegates(client);
4145
+ if (gOpts.json) printJson(all);
4146
+ else printTable(all.map(row));
4147
+ }));
4148
+ delegate.command("revoke <name-or-id>").description("Revoke a delegated key").action(withClient(program, revoke));
3881
4149
  }
3882
- function markerRow(marker) {
3883
- return {
4150
+ //#endregion
4151
+ //#region src/commands/org-events-chain.ts
4152
+ /** The `prev_hash` of an org's first event. */
4153
+ const GENESIS_HASH = "0".repeat(64);
4154
+ const ChainFault = {
4155
+ Hash: "hash",
4156
+ Break: "break"
4157
+ };
4158
+ /** The log changed or has a gap. Carries the event it was found at. */
4159
+ var ChainBreak = class extends Error {
4160
+ constructor(fault, seq) {
4161
+ super(`chain ${fault} at event ${seq}`);
4162
+ this.fault = fault;
4163
+ this.seq = seq;
4164
+ }
4165
+ };
4166
+ /** SHA-256 hex over the RFC 8785 form of the envelope without its `hash`. */
4167
+ function eventHash(event) {
4168
+ const { hash: _hash, ...body } = event;
4169
+ return createHash("sha256").update(jcsCanonicalize(body), "utf-8").digest("hex");
4170
+ }
4171
+ /**
4172
+ * The range a retention pass removed, when `event` is the first one after it: the floor's hash is
4173
+ * its `prev_hash` and it directly follows the floor. Undefined when it attaches where it should.
4174
+ */
4175
+ function prunedBefore(event, lastSeq, floor) {
4176
+ if (floor == null || lastSeq >= floor.seq) return void 0;
4177
+ if (event.seq !== floor.seq + 1 || event.prev_hash !== floor.hash) return void 0;
4178
+ return {
4179
+ from: lastSeq + 1,
4180
+ to: floor.seq
4181
+ };
4182
+ }
4183
+ /**
4184
+ * Checks one event against what came before it, recomputing its hash from the body.
4185
+ * `afterSeq` is where the page started, so a position-less resume still catches a gap.
4186
+ * `floor` explains a jump: the retained hash a retention pass left at the end of the removed range.
4187
+ */
4188
+ function verifyEvent(event, previous, afterSeq, floor) {
4189
+ if (eventHash(event) !== event.hash) throw new ChainBreak(ChainFault.Hash, event.seq);
4190
+ const lastSeq = previous?.seq ?? afterSeq;
4191
+ const position = {
4192
+ seq: event.seq,
4193
+ hash: event.hash
4194
+ };
4195
+ const pruned = prunedBefore(event, lastSeq, floor);
4196
+ if (pruned !== void 0) return {
4197
+ position,
4198
+ pruned
4199
+ };
4200
+ if (event.seq !== lastSeq + 1) throw new ChainBreak(ChainFault.Break, event.seq);
4201
+ const expected = previous?.hash ?? (afterSeq === 0 ? GENESIS_HASH : void 0);
4202
+ if (expected !== void 0 && event.prev_hash !== expected) throw new ChainBreak(ChainFault.Break, event.seq);
4203
+ return { position };
4204
+ }
4205
+ /** The position saved by an earlier run, or undefined when there is no usable state file. */
4206
+ function loadPosition(file) {
4207
+ if (!fs$1.existsSync(file)) return void 0;
4208
+ const parsed = JSON.parse(fs$1.readFileSync(file, "utf-8"));
4209
+ if (!Number.isSafeInteger(parsed.seq) || typeof parsed.hash !== "string") throw new Error(`State file ${file} is not a tail state; remove it to start again.`);
4210
+ return {
4211
+ seq: parsed.seq,
4212
+ hash: parsed.hash,
4213
+ ...Number.isSafeInteger(parsed.chain_epoch) ? { chain_epoch: parsed.chain_epoch } : {}
4214
+ };
4215
+ }
4216
+ function savePosition(file, position) {
4217
+ writeAtomic(file, `${JSON.stringify(position)}\n`);
4218
+ }
4219
+ //#endregion
4220
+ //#region src/commands/tail-outgoing.ts
4221
+ /** What a collector hands a sink: a record verbatim, plus the fields a receiver indexes it by. */
4222
+ const Severity = {
4223
+ Info: "INFO",
4224
+ Warn: "WARN",
4225
+ Error: "ERROR"
4226
+ };
4227
+ const Sourcetype = {
4228
+ Event: "rine:org_event",
4229
+ Metadata: "rine:org_metadata",
4230
+ Alert: "rine:collector:alert"
4231
+ };
4232
+ const severityOf = (signal) => signal === SignalClass.Alert ? Severity.Warn : Severity.Info;
4233
+ function eventOutgoing(event) {
4234
+ const kind = String(event.kind);
4235
+ const signal = signalClass(kind, event.detail);
4236
+ return {
4237
+ body: event,
4238
+ sourcetype: Sourcetype.Event,
4239
+ severity: severityOf(signal),
4240
+ time: typeof event.occurred_at === "string" ? event.occurred_at : void 0,
4241
+ fields: {
4242
+ org_id: typeof event.org_id === "string" ? event.org_id : void 0,
4243
+ chain_epoch: Number(event.chain_epoch),
4244
+ seq: event.seq,
4245
+ kind,
4246
+ signal
4247
+ }
4248
+ };
4249
+ }
4250
+ function metadataOutgoing(row, orgId) {
4251
+ return {
4252
+ body: row,
4253
+ sourcetype: Sourcetype.Metadata,
4254
+ severity: Severity.Info,
4255
+ time: row.created_at,
4256
+ fields: {
4257
+ org_id: orgId,
4258
+ chain_epoch: row.chain_epoch,
4259
+ seq: row.seq,
4260
+ kind: "message.metadata",
4261
+ signal: SignalClass.Record
4262
+ }
4263
+ };
4264
+ }
4265
+ function alertOutgoing(record) {
4266
+ return {
4267
+ body: record,
4268
+ sourcetype: Sourcetype.Alert,
4269
+ severity: Severity.Error,
4270
+ time: record.time,
4271
+ fields: {
4272
+ org_id: record.org_id,
4273
+ kind: record.reason,
4274
+ signal: SignalClass.Alert
4275
+ }
4276
+ };
4277
+ }
4278
+ //#endregion
4279
+ //#region src/commands/tail-alert.ts
4280
+ /** The alert record `tail` sends to its sink before it exits, and the exit codes it exits with. */
4281
+ const TailExit = {
4282
+ Auth: 3,
4283
+ Chain: 4,
4284
+ Fork: 5,
4285
+ Silenced: 6,
4286
+ Stalled: 7,
4287
+ Truncated: 8,
4288
+ SinkDown: 9
4289
+ };
4290
+ /** Why a collector stopped, or warned (`pruned_unread` does not stop it). */
4291
+ const AlertReason = {
4292
+ AuthRefused: "auth_refused",
4293
+ ChainGap: "chain_gap",
4294
+ ChainHash: "chain_hash",
4295
+ Fork: "fork",
4296
+ Silenced: "silenced",
4297
+ HeadInvalid: "head_invalid",
4298
+ NoHeadRoute: "no_head_route",
4299
+ Withheld: "withheld",
4300
+ Stalled: "stalled",
4301
+ Truncated: "truncated",
4302
+ PrunedUnread: "pruned_unread",
4303
+ SinkDown: "sink_down"
4304
+ };
4305
+ const ALERT_SCHEMA = "rine.collector_alert.v1";
4306
+ /** The record for a stop, or (code null) for a warning. `range` in `extra` is null when empty. */
4307
+ function alertRecord(stop, orgId, now = /* @__PURE__ */ new Date()) {
4308
+ return {
4309
+ schema: ALERT_SCHEMA,
4310
+ reason: stop.reason,
4311
+ exit_code: stop.code,
4312
+ message: stop.text,
4313
+ org_id: orgId,
4314
+ time: now.toISOString(),
4315
+ ...stop.extra
4316
+ };
4317
+ }
4318
+ //#endregion
4319
+ //#region src/commands/tail-errors.ts
4320
+ const MINT_REFUSALS = new Set([
4321
+ "invalid_client",
4322
+ "unauthorized_client",
4323
+ "invalid_grant"
4324
+ ]);
4325
+ /** A 401, a 403, or a refused token mint: the credential, not the network, is the problem. */
4326
+ function isAuthRefusal(err) {
4327
+ if (!(err instanceof RineApiError)) return false;
4328
+ if (err.status === 401 || err.status === 403) return true;
4329
+ return err.status === 400 && err.code !== void 0 && MINT_REFUSALS.has(err.code);
4330
+ }
4331
+ /** A network error, a throttle or a server fault: worth waiting out. */
4332
+ function isTransient(err) {
4333
+ return !(err instanceof RineApiError) || err.status === 429 || err.status >= 500;
4334
+ }
4335
+ //#endregion
4336
+ //#region src/commands/tail-head.ts
4337
+ /**
4338
+ * The head watch: every interval a signed head is asked for with a fresh nonce and checked, so a
4339
+ * log that is silenced, replayed, stalled, truncated or withheld stops the collector even when
4340
+ * nothing is being written. It runs beside the page loop and never waits on the sink.
4341
+ */
4342
+ /** The seconds each threshold is by default, and the lowest a flag may set one to. */
4343
+ const HeadDefaults = {
4344
+ intervalS: 60,
4345
+ silencedS: 300,
4346
+ withheldS: 120,
4347
+ stalledS: 300,
4348
+ keyRetryS: 420,
4349
+ minThresholdS: 30
4350
+ };
4351
+ const seconds = (since) => Math.floor((Date.now() - since) / 1e3);
4352
+ /** Runs head checks until stopped (undefined) or one of them ends the collector. */
4353
+ async function watchHead(cfg, progress, signal, text) {
4354
+ let lastAnswerAt = Date.now();
4355
+ let answered = false;
4356
+ let keys;
4357
+ let unknownSince;
4358
+ let aheadSince;
4359
+ let previous;
4360
+ const stop = (code, reason, message, extra) => ({
4361
+ code,
4362
+ reason,
4363
+ text: message,
4364
+ extra
4365
+ });
4366
+ const silenced = () => {
4367
+ const s = seconds(lastAnswerAt);
4368
+ return s >= cfg.thresholds.silencedS ? stop(TailExit.Silenced, AlertReason.Silenced, text.silenced(s), { silent_seconds: s }) : void 0;
4369
+ };
4370
+ async function check() {
4371
+ const seen = progress.lastSeq;
4372
+ const seenEpoch = progress.chainEpoch;
4373
+ const nonce = randomBytes(32).toString("base64url");
4374
+ let head;
4375
+ try {
4376
+ head = await cfg.fetchHead(nonce);
4377
+ } catch (err) {
4378
+ if (isAuthRefusal(err)) return stop(TailExit.Auth, AlertReason.AuthRefused, text.auth);
4379
+ if (err instanceof RineApiError && err.status === 404 && !answered) return stop(TailExit.Silenced, AlertReason.NoHeadRoute, text.noHead);
4380
+ return silenced();
4381
+ }
4382
+ lastAnswerAt = Date.now();
4383
+ answered = true;
4384
+ try {
4385
+ keys ??= (await cfg.fetchKeys()).keys;
4386
+ let verdict = verifyHead(head, nonce, keys);
4387
+ if (!verdict.ok && verdict.fault === HeadFault.UnknownKid) {
4388
+ if (!(unknownSince === void 0 || Date.now() - unknownSince >= cfg.keyRetryMs)) return void 0;
4389
+ keys = (await cfg.fetchKeys()).keys;
4390
+ verdict = verifyHead(head, nonce, keys);
4391
+ if (!verdict.ok && unknownSince === void 0) {
4392
+ unknownSince = Date.now();
4393
+ return;
4394
+ }
4395
+ }
4396
+ if (!verdict.ok) return stop(TailExit.Silenced, AlertReason.HeadInvalid, text.headInvalid, { fault: verdict.fault });
4397
+ } catch {
4398
+ return silenced();
4399
+ }
4400
+ unknownSince = void 0;
4401
+ return judge(head, seen, seenEpoch);
4402
+ }
4403
+ function judge(head, seen, seenEpoch) {
4404
+ const sameEpoch = seenEpoch === void 0 || head.chain_epoch === seenEpoch;
4405
+ const floor = Math.max(sameEpoch ? seen : 0, previous !== void 0 && previous.epoch === head.chain_epoch ? previous.seq : 0);
4406
+ previous = {
4407
+ epoch: head.chain_epoch,
4408
+ seq: head.seq
4409
+ };
4410
+ if (head.seq < floor) return stop(TailExit.Truncated, AlertReason.Truncated, text.truncated(head.seq, floor), {
4411
+ head_seq: head.seq,
4412
+ last_seq: floor
4413
+ });
4414
+ aheadSince = sameEpoch && head.seq > seen && progress.caughtUp && !progress.sinkBlocked ? aheadSince ?? Date.now() : void 0;
4415
+ if (aheadSince !== void 0 && seconds(aheadSince) >= cfg.thresholds.withheldS) return stop(TailExit.Silenced, AlertReason.Withheld, text.withheld(head.seq, seconds(aheadSince)), {
4416
+ head_seq: head.seq,
4417
+ last_seq: seen
4418
+ });
4419
+ if (head.unsequenced_oldest_seconds >= cfg.thresholds.stalledS) return stop(TailExit.Stalled, AlertReason.Stalled, text.stalled(head.unsequenced_oldest_seconds), { unsequenced_oldest_seconds: head.unsequenced_oldest_seconds });
4420
+ }
4421
+ while (!signal.aborted) {
4422
+ const ended = await check();
4423
+ if (ended !== void 0) return ended;
4424
+ await sleepWithSignal(cfg.intervalMs, signal);
4425
+ }
4426
+ }
4427
+ //#endregion
4428
+ //#region src/commands/tail-transport.ts
4429
+ const SinkName = {
4430
+ Stdout: "stdout",
4431
+ Hec: "HEC",
4432
+ Otlp: "OTLP"
4433
+ };
4434
+ /** The environment variables that carry a receiver's credentials. */
4435
+ const SinkEnv = {
4436
+ HecToken: "RINE_HEC_TOKEN",
4437
+ OtlpHeaders: "RINE_OTLP_HEADERS"
4438
+ };
4439
+ const SEND_TIMEOUT_MS = 2e4;
4440
+ /** The receiver did not accept the batch; `status` is safe to print. */
4441
+ var SinkRefusal = class extends Error {
4442
+ constructor(status) {
4443
+ super(`sink refused: ${status}`);
4444
+ this.status = status;
4445
+ }
4446
+ };
4447
+ /** The flags or environment name a receiver that cannot be used. */
4448
+ var SinkConfigError = class extends Error {};
4449
+ /** A POST that treats anything but a 2xx as a refusal and says nothing of the request. */
4450
+ const httpPost = async (url, headers, body) => {
4451
+ let status;
4452
+ try {
4453
+ const res = await fetch(url, {
4454
+ method: "POST",
4455
+ headers,
4456
+ body,
4457
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
4458
+ });
4459
+ status = res.status;
4460
+ await res.arrayBuffer().catch(() => void 0);
4461
+ } catch {
4462
+ throw new SinkRefusal("unreachable");
4463
+ }
4464
+ if (status < 200 || status >= 300) throw new SinkRefusal(`HTTP ${status}`);
4465
+ };
4466
+ const LOOPBACK = new Set([
4467
+ "localhost",
4468
+ "127.0.0.1",
4469
+ "[::1]"
4470
+ ]);
4471
+ /** Throws the https-needed text unless `address` is https, or http to this machine. */
4472
+ function checkTransport(address, name, text) {
4473
+ const refusal = new SinkConfigError(text.plainHttp(name.toLowerCase()));
4474
+ let url;
4475
+ try {
4476
+ url = new URL(address);
4477
+ } catch {
4478
+ throw refusal;
4479
+ }
4480
+ const local = LOOPBACK.has(url.hostname) || /^127\./.test(url.hostname);
4481
+ if (url.protocol === "https:" || url.protocol === "http:" && local) return url;
4482
+ throw refusal;
4483
+ }
4484
+ function endpoint(url, path) {
4485
+ const out = new URL(url);
4486
+ if (!out.pathname.endsWith(path)) out.pathname = `${out.pathname.replace(/\/$/, "")}${path}`;
4487
+ return out.toString();
4488
+ }
4489
+ //#endregion
4490
+ //#region src/commands/tail-deliver.ts
4491
+ /** Hands a batch to the sink, waiting out a receiver that refuses it. */
4492
+ const Delivery = {
4493
+ Sent: "sent",
4494
+ Aborted: "aborted"
4495
+ };
4496
+ const MAX_BACKOFF_S$1 = 60;
4497
+ /**
4498
+ * Sends `batch`, retrying with a doubling wait until it is accepted, the collector is
4499
+ * stopped, or the receiver has refused for `giveUpMs`. A refusal marks the progress so the head
4500
+ * watch does not read the pause as withheld events; it is never a head failure.
4501
+ */
4502
+ async function deliver(env, batch) {
4503
+ const startedAt = Date.now();
4504
+ let backoffS = 0;
4505
+ for (;;) try {
4506
+ await env.sink.send(batch);
4507
+ env.progress.sinkBlocked = false;
4508
+ return Delivery.Sent;
4509
+ } catch (err) {
4510
+ if (!(err instanceof SinkRefusal)) throw err;
4511
+ env.progress.sinkBlocked = true;
4512
+ const waitedMs = Date.now() - startedAt;
4513
+ if (waitedMs >= env.giveUpMs) return {
4514
+ code: TailExit.SinkDown,
4515
+ reason: AlertReason.SinkDown,
4516
+ text: env.text.sinkDown(env.sink.name, Math.floor(waitedMs / 1e3))
4517
+ };
4518
+ backoffS = Math.min(Math.max(backoffS * 2, 1), MAX_BACKOFF_S$1);
4519
+ env.log(env.text.sinkRefused(env.sink.name, err.status, backoffS));
4520
+ await sleepWithSignal(backoffS * 1e3, env.signal);
4521
+ if (env.signal.aborted) return Delivery.Aborted;
4522
+ }
4523
+ }
4524
+ //#endregion
4525
+ //#region src/commands/tail-fork.ts
4526
+ /** The range this collector holds that the restored server no longer has, or null. */
4527
+ function heldBeyond(fork, held) {
4528
+ if (held === void 0 || held.seq <= fork.forkAfterSeq) return null;
4529
+ return {
4530
+ from: fork.forkAfterSeq + 1,
4531
+ to: held.seq
4532
+ };
4533
+ }
4534
+ /**
4535
+ * Without `acceptEpoch` the collector stops (or says it lost nothing, when it holds no event past the fork).
4536
+ * With the new epoch accepted it carries on after `fork_after_seq`, requiring the next event to
4537
+ * attach to `fork_after_hash`; a position that sits exactly on the fork point must carry that hash.
4538
+ */
4539
+ function resolveFork(fork, held, after, oldEpoch, acceptEpoch, text) {
4540
+ const old = oldEpoch ?? fork.currentEpoch - 1;
4541
+ const range = heldBeyond(fork, held);
4542
+ if (acceptEpoch !== fork.currentEpoch) {
4543
+ const message = (range === null ? text.forkNothingHeld : text.fork)(old, fork.currentEpoch, fork.forkAfterSeq);
4544
+ return { stop: {
4545
+ code: TailExit.Fork,
4546
+ reason: AlertReason.Fork,
4547
+ text: message,
4548
+ extra: {
4549
+ old_epoch: old,
4550
+ new_epoch: fork.currentEpoch,
4551
+ fork_after_seq: fork.forkAfterSeq,
4552
+ ...fork.forkAfterHash === void 0 ? {} : { fork_after_hash: fork.forkAfterHash },
4553
+ range
4554
+ }
4555
+ } };
4556
+ }
4557
+ const epoch = fork.currentEpoch;
4558
+ if (held === void 0) return {
4559
+ position: void 0,
4560
+ after: Math.min(after, fork.forkAfterSeq)
4561
+ };
4562
+ if (range !== null) {
4563
+ const position = {
4564
+ seq: fork.forkAfterSeq,
4565
+ hash: fork.forkAfterHash ?? "",
4566
+ chain_epoch: epoch
4567
+ };
4568
+ return {
4569
+ position,
4570
+ after: position.seq
4571
+ };
4572
+ }
4573
+ if (held.seq === fork.forkAfterSeq && fork.forkAfterHash !== void 0 && held.hash !== fork.forkAfterHash) return { stop: {
4574
+ code: TailExit.Chain,
4575
+ reason: AlertReason.ChainGap,
4576
+ text: text.gap(fork.forkAfterSeq + 1)
4577
+ } };
4578
+ return {
4579
+ position: {
4580
+ ...held,
4581
+ chain_epoch: epoch
4582
+ },
4583
+ after: held.seq
4584
+ };
4585
+ }
4586
+ //#endregion
4587
+ //#region src/commands/tail-loop.ts
4588
+ /** The page loop: fetch, check the chain, hand to the sink, save the position once it is accepted. */
4589
+ const MAX_BACKOFF_S = 60;
4590
+ function chainStop(err, text) {
4591
+ const hash = err.fault === ChainFault.Hash;
4592
+ return {
4593
+ code: TailExit.Chain,
4594
+ reason: hash ? AlertReason.ChainHash : AlertReason.ChainGap,
4595
+ text: hash ? text.hash(err.seq) : text.gap(err.seq)
4596
+ };
4597
+ }
4598
+ /** Pages until stopped (undefined) or something ends the collector. */
4599
+ async function runPages(run, progress, signal) {
4600
+ const { source, text } = run;
4601
+ const env = {
4602
+ ...run,
4603
+ signal,
4604
+ progress
4605
+ };
4606
+ let position = run.position;
4607
+ let after = position?.seq ?? run.afterSeq;
4608
+ let epoch = position?.chain_epoch;
4609
+ let backoffS = 0;
4610
+ progress.chainEpoch = epoch;
4611
+ while (!signal.aborted) {
4612
+ let page;
4613
+ try {
4614
+ page = await source.fetchPage(after, epoch);
4615
+ } catch (err) {
4616
+ const fork = forkPointOf(err);
4617
+ if (fork !== void 0) {
4618
+ const out = resolveFork(fork, position, after, epoch, run.acceptEpoch, text);
4619
+ if ("stop" in out) return out.stop;
4620
+ position = out.position;
4621
+ after = out.after;
4622
+ epoch = fork.currentEpoch;
4623
+ progress.chainEpoch = epoch;
4624
+ progress.lastSeq = after;
4625
+ continue;
4626
+ }
4627
+ if (isAuthRefusal(err)) return {
4628
+ code: TailExit.Auth,
4629
+ reason: AlertReason.AuthRefused,
4630
+ text: text.auth
4631
+ };
4632
+ if (!isTransient(err)) throw err;
4633
+ backoffS = Math.min(Math.max(backoffS * 2, 1), MAX_BACKOFF_S);
4634
+ run.log(text.retry(formatError(err), backoffS));
4635
+ await sleepWithSignal(backoffS * 1e3, signal);
4636
+ continue;
4637
+ }
4638
+ backoffS = 0;
4639
+ epoch = page.epoch;
4640
+ progress.chainEpoch = epoch;
4641
+ const fresh = position === void 0;
4642
+ let batch = [];
4643
+ const flush = async () => {
4644
+ if (batch.length === 0 || position === void 0) return void 0;
4645
+ const sent = await deliver(env, batch);
4646
+ if (sent === Delivery.Aborted) return void 0;
4647
+ if (sent !== Delivery.Sent) return sent;
4648
+ run.save(position);
4649
+ progress.lastSeq = position.seq;
4650
+ batch = [];
4651
+ };
4652
+ let broke;
4653
+ for (const item of page.items) {
4654
+ let step;
4655
+ try {
4656
+ step = source.step(item, position, after, page.floor);
4657
+ } catch (err) {
4658
+ if (!(err instanceof ChainBreak)) throw err;
4659
+ broke = chainStop(err, text);
4660
+ break;
4661
+ }
4662
+ if (step.pruned !== void 0) {
4663
+ const flushed = await flush();
4664
+ if (flushed !== void 0) return flushed;
4665
+ if (fresh) run.log(text.pruned(step.pruned.to));
4666
+ else {
4667
+ const { from, to } = step.pruned;
4668
+ const message = text.prunedUnread(from, to);
4669
+ run.log(message);
4670
+ const sent = await deliver(env, [alertOutgoing(alertRecord({
4671
+ code: null,
4672
+ reason: AlertReason.PrunedUnread,
4673
+ text: message,
4674
+ extra: { range: {
4675
+ from,
4676
+ to
4677
+ } }
4678
+ }, run.orgId))]);
4679
+ if (sent !== Delivery.Sent && sent !== Delivery.Aborted) return sent;
4680
+ }
4681
+ }
4682
+ position = {
4683
+ ...step.position,
4684
+ chain_epoch: page.epoch
4685
+ };
4686
+ after = position.seq;
4687
+ batch.push(source.outgoing(item));
4688
+ if (batch.length >= 100) {
4689
+ const flushed = await flush();
4690
+ if (flushed !== void 0) return flushed;
4691
+ }
4692
+ }
4693
+ const flushed = await flush();
4694
+ if (flushed !== void 0) return flushed;
4695
+ if (broke !== void 0) return broke;
4696
+ progress.caughtUp = page.items.length === 0;
4697
+ if (page.items.length === 0) await sleepWithSignal(run.intervalMs, signal);
4698
+ }
4699
+ }
4700
+ //#endregion
4701
+ //#region src/commands/tail-run.ts
4702
+ /** Runs the page loop beside the head watch and turns what ends them into a message, a record and an exit code. */
4703
+ /** Collects until stopped or ended; returns the process exit code. */
4704
+ async function runTail(run) {
4705
+ const inner = new AbortController();
4706
+ const stopInner = () => inner.abort();
4707
+ if (run.signal.aborted) return 0;
4708
+ run.signal.addEventListener("abort", stopInner, { once: true });
4709
+ const progress = {
4710
+ lastSeq: run.position?.seq ?? run.afterSeq,
4711
+ chainEpoch: run.position?.chain_epoch,
4712
+ caughtUp: false,
4713
+ sinkBlocked: false
4714
+ };
4715
+ let ended;
4716
+ const settle = async (work) => {
4717
+ const stop = await work;
4718
+ ended ??= stop;
4719
+ inner.abort();
4720
+ };
4721
+ try {
4722
+ await Promise.all([settle(runPages(run, progress, inner.signal)), settle(run.head === void 0 ? new Promise((resolve) => inner.signal.addEventListener("abort", () => resolve(void 0))) : watchHead(run.head, progress, inner.signal, run.text))]);
4723
+ } finally {
4724
+ run.signal.removeEventListener("abort", stopInner);
4725
+ inner.abort();
4726
+ }
4727
+ if (ended === void 0) return 0;
4728
+ run.log(ended.text);
4729
+ if (ended.code !== TailExit.SinkDown) try {
4730
+ await run.sink.send([alertOutgoing(alertRecord(ended, run.orgId))]);
4731
+ } catch (err) {
4732
+ if (!(err instanceof SinkRefusal)) throw err;
4733
+ }
4734
+ return ended.code;
4735
+ }
4736
+ //#endregion
4737
+ //#region src/commands/tail-sinks.ts
4738
+ /**
4739
+ * Where `tail` sends what it read: stdout, a Splunk HEC receiver or an OTLP/HTTP logs receiver.
4740
+ * A receiver that does not accept a batch throws `SinkRefusal`; its credentials come from the
4741
+ * environment and appear in no message, log or alert record.
4742
+ */
4743
+ const HEC_PATH = "/services/collector/event";
4744
+ const OTLP_PATH = "/v1/logs";
4745
+ const hecEvent = (o) => JSON.stringify({
4746
+ ...o.time === void 0 ? {} : { time: Date.parse(o.time) / 1e3 },
4747
+ source: "rine",
4748
+ sourcetype: o.sourcetype,
4749
+ event: o.body,
4750
+ fields: o.fields
4751
+ });
4752
+ function hecSink(address, token, text, post = httpPost) {
4753
+ const url = endpoint(checkTransport(address, SinkName.Hec, text), HEC_PATH);
4754
+ const headers = {
4755
+ Authorization: `Splunk ${token}`,
4756
+ "Content-Type": "application/json"
4757
+ };
4758
+ return {
4759
+ name: SinkName.Hec,
4760
+ send: (batch) => post(url, headers, batch.map(hecEvent).join("\n"))
4761
+ };
4762
+ }
4763
+ const SEVERITY_NUMBER = {
4764
+ [Severity.Info]: 9,
4765
+ [Severity.Warn]: 13,
4766
+ [Severity.Error]: 17
4767
+ };
4768
+ const str = (key, value) => ({
4769
+ key,
4770
+ value: { stringValue: value }
4771
+ });
4772
+ const int = (key, value) => ({
4773
+ key,
4774
+ value: { intValue: String(value) }
4775
+ });
4776
+ function otlpRecord(o) {
4777
+ const nanos = o.time === void 0 ? void 0 : String(BigInt(Date.parse(o.time)) * 1000000n);
4778
+ const { org_id, chain_epoch, seq, kind, signal } = o.fields;
4779
+ return {
4780
+ ...nanos === void 0 ? {} : { timeUnixNano: nanos },
4781
+ severityNumber: SEVERITY_NUMBER[o.severity],
4782
+ severityText: o.severity,
4783
+ body: { stringValue: JSON.stringify(o.body) },
4784
+ attributes: [
4785
+ ...org_id === void 0 ? [] : [str("rine.org_id", org_id)],
4786
+ ...chain_epoch === void 0 ? [] : [int("rine.chain_epoch", chain_epoch)],
4787
+ ...seq === void 0 ? [] : [int("rine.seq", seq)],
4788
+ str("rine.kind", kind),
4789
+ str("rine.signal", signal)
4790
+ ]
4791
+ };
4792
+ }
4793
+ /** `k=v,k2=v2`, the form OTEL_EXPORTER_OTLP_HEADERS uses. */
4794
+ function parseOtlpHeaders(raw) {
4795
+ const out = {};
4796
+ for (const pair of (raw ?? "").split(",")) {
4797
+ const at = pair.indexOf("=");
4798
+ if (at > 0) out[pair.slice(0, at).trim()] = pair.slice(at + 1).trim();
4799
+ }
4800
+ return out;
4801
+ }
4802
+ function otlpSink(address, rawHeaders, text, post = httpPost) {
4803
+ const url = endpoint(checkTransport(address, SinkName.Otlp, text), OTLP_PATH);
4804
+ const headers = {
4805
+ ...parseOtlpHeaders(rawHeaders),
4806
+ "Content-Type": "application/json"
4807
+ };
4808
+ return {
4809
+ name: SinkName.Otlp,
4810
+ send: (batch) => post(url, headers, JSON.stringify({ resourceLogs: [{
4811
+ resource: { attributes: [str("service.name", "rine-tail")] },
4812
+ scopeLogs: [{
4813
+ scope: { name: "rine.org" },
4814
+ logRecords: batch.map(otlpRecord)
4815
+ }]
4816
+ }] }))
4817
+ };
4818
+ }
4819
+ /** Standard output, one JSON line per record: the envelope, the row or the alert record. */
4820
+ function stdoutSink(write = console.log) {
4821
+ return {
4822
+ name: SinkName.Stdout,
4823
+ send: async (batch) => {
4824
+ for (const o of batch) write(JSON.stringify(o.body));
4825
+ }
4826
+ };
4827
+ }
4828
+ /** The sink the flags name: `--hec`, `--otlp`, or stdout when neither is given. */
4829
+ function chooseSink(choice) {
4830
+ const { hec, otlp, env, text, post } = choice;
4831
+ if (hec !== void 0 && otlp !== void 0) throw new SinkConfigError("Choose one of --hec and --otlp, not both.");
4832
+ if (hec !== void 0) {
4833
+ const token = env[SinkEnv.HecToken];
4834
+ if (!token) throw new SinkConfigError(`--hec needs the token in ${SinkEnv.HecToken}.`);
4835
+ return hecSink(hec, token, text, post);
4836
+ }
4837
+ if (otlp !== void 0) return otlpSink(otlp, env[SinkEnv.OtlpHeaders], text, post);
4838
+ return stdoutSink();
4839
+ }
4840
+ //#endregion
4841
+ //#region src/commands/tail-command.ts
4842
+ /** The options and start-up `rine org events tail` and `rine org metadata tail` share. */
4843
+ /** How long a receiver may refuse every batch before the collector exits 9. */
4844
+ const SINK_GIVE_UP_S = 900;
4845
+ const DEFAULT_POLL_S$1 = 5;
4846
+ function parseCount(value, flag, min, fallback) {
4847
+ if (value === void 0) return fallback;
4848
+ const n = Number(value);
4849
+ if (!Number.isSafeInteger(n) || n < min) throw new Error(`${flag} must be an integer of at least ${min}`);
4850
+ return n;
4851
+ }
4852
+ /** Adds the shared options; the head thresholds only where there is a head to watch. */
4853
+ function addTailOptions(cmd, withHead) {
4854
+ cmd.option("--after-seq <n>", "Start after this sequence number (ignored when --state holds a position)").option("--state <file>", "Remember the last delivered position here and resume from it").option("--interval <seconds>", `Seconds between polls when caught up (default ${DEFAULT_POLL_S$1})`).option("--hec <url>", "Send to a Splunk HEC receiver (token in RINE_HEC_TOKEN)").option("--otlp <url>", "Send to an OTLP/HTTP logs receiver (headers in RINE_OTLP_HEADERS, as k=v,k=v)").option("--accept-epoch <n>", "Carry on after the server was restored from a backup and moved to chain epoch n");
4855
+ if (withHead) cmd.option("--silenced-after <seconds>", `Seconds without a valid signed head before exit 6 (default ${HeadDefaults.silencedS}, at least ${HeadDefaults.minThresholdS})`).option("--withheld-after <seconds>", `Seconds a reported event may stay unreturned before exit 6 (default ${HeadDefaults.withheldS}, at least ${HeadDefaults.minThresholdS})`).option("--stalled-after <seconds>", `Seconds an event may wait to enter the log before exit 7 (default ${HeadDefaults.stalledS}, at least ${HeadDefaults.minThresholdS})`);
4856
+ return cmd;
4857
+ }
4858
+ function headWatch(ctx, opts) {
4859
+ const min = HeadDefaults.minThresholdS;
4860
+ const thresholds = {
4861
+ silencedS: parseCount(opts.silencedAfter, "--silenced-after", min, HeadDefaults.silencedS),
4862
+ withheldS: parseCount(opts.withheldAfter, "--withheld-after", min, HeadDefaults.withheldS),
4863
+ stalledS: parseCount(opts.stalledAfter, "--stalled-after", min, HeadDefaults.stalledS)
4864
+ };
4865
+ return {
4866
+ fetchHead: (nonce) => fetchOrgEventHead(ctx.client, nonce),
4867
+ fetchKeys: () => fetchHeadKeys(ctx.apiUrl),
4868
+ thresholds,
4869
+ intervalMs: Math.min(HeadDefaults.intervalS, ...Object.values(thresholds)) * 1e3,
4870
+ keyRetryMs: HeadDefaults.keyRetryS * 1e3
4871
+ };
4872
+ }
4873
+ /** Builds the run from the options and drives it until it ends; sets the process exit code. */
4874
+ async function launchTail(ctx, opts, launch) {
4875
+ const state = opts.state;
4876
+ const run = {
4877
+ source: launch.source,
4878
+ text: launch.text,
4879
+ sink: chooseSink({
4880
+ hec: opts.hec,
4881
+ otlp: opts.otlp,
4882
+ env: process.env,
4883
+ text: launch.text
4884
+ }),
4885
+ orgId: ctx.auth?.orgId,
4886
+ afterSeq: parseCount(opts.afterSeq, "--after-seq", 0, 0),
4887
+ position: state === void 0 ? void 0 : loadPosition(state),
4888
+ acceptEpoch: opts.acceptEpoch === void 0 ? void 0 : parseCount(opts.acceptEpoch, "--accept-epoch", 1, 1),
4889
+ intervalMs: parseCount(opts.interval, "--interval", 1, DEFAULT_POLL_S$1) * 1e3,
4890
+ giveUpMs: SINK_GIVE_UP_S * 1e3,
4891
+ signal: void 0,
4892
+ head: launch.withHead ? headWatch(ctx, opts) : void 0,
4893
+ save: (position) => {
4894
+ if (state !== void 0) savePosition(state, position);
4895
+ },
4896
+ log: (message) => console.error(message)
4897
+ };
4898
+ const stop = new AbortController();
4899
+ run.signal = stop.signal;
4900
+ const onSignal = () => stop.abort();
4901
+ process.once("SIGINT", onSignal);
4902
+ process.once("SIGTERM", onSignal);
4903
+ try {
4904
+ process.exitCode = await runTail(run);
4905
+ } finally {
4906
+ process.off("SIGINT", onSignal);
4907
+ process.off("SIGTERM", onSignal);
4908
+ }
4909
+ }
4910
+ //#endregion
4911
+ //#region src/commands/tail-text.ts
4912
+ /** The words `tail` prints, exact. */
4913
+ const EVENTS_TAIL = "rine org events tail";
4914
+ const METADATA_TAIL = "rine org metadata tail";
4915
+ /** The text of one tail command; `command` is the prefix every line starts with. */
4916
+ function tailText(command) {
4917
+ const p = `${command}:`;
4918
+ return {
4919
+ retry: (what, seconds) => `${p} ${what}; retrying in ${seconds} s`,
4920
+ auth: `${p} the server refused this credential. The organisation may be erased, the key revoked or the credential expired; check which before restarting.`,
4921
+ gap: (seq) => `${p} event ${seq} does not follow the last event received. The log has a gap or has changed; investigate before restarting.`,
4922
+ hash: (seq) => `${p} event ${seq} does not match its hash. The log has changed; investigate before restarting.`,
4923
+ fork: (old, current, forkSeq) => `${p} the log moved from chain epoch ${old} to ${current}, so the server was restored from a backup. Events after event ${forkSeq} that this collector already holds are no longer on the server; keep them, investigate, then restart with --accept-epoch ${current}.`,
4924
+ forkNothingHeld: (old, current, forkSeq) => `${p} the log moved from chain epoch ${old} to ${current}, so the server was restored from a backup. This collector holds no event after event ${forkSeq}, so its copy lost nothing; restart with --accept-epoch ${current}.`,
4925
+ silenced: (seconds) => `${p} the server has not answered a signed head check for ${seconds} s. The log may be silenced; investigate before restarting.`,
4926
+ headInvalid: `${p} the server's head check failed verification. The log may be silenced or replayed; investigate before restarting.`,
4927
+ stalled: (seconds) => `${p} events have waited ${seconds} s to enter the log. Recording has stalled; investigate before restarting.`,
4928
+ truncated: (seq, last) => `${p} the log now ends at event ${seq}, before the last event received (${last}). The log was truncated; investigate before restarting.`,
4929
+ withheld: (seq, seconds) => `${p} the server reports event ${seq} but has not returned it for ${seconds} s. The log may be withheld; investigate before restarting.`,
4930
+ pruned: (seq) => `${p} events up to ${seq} were removed at the end of their retention period; the chain continues from the retained hash.`,
4931
+ sinkRefused: (sink, status, seconds) => `${p} the ${sink} receiver did not accept the events (${status}); retrying in ${seconds} s`,
4932
+ plainHttp: (sink) => `${p} --${sink} needs an https:// address unless the receiver runs on this machine.`,
4933
+ noHead: `${p} this server does not offer a signed head check, so silence cannot be detected. Upgrade the server before collecting.`,
4934
+ prunedUnread: (from, to) => `${p} events ${from} to ${to} were removed at the end of their retention period before this collector read them. They are missing from this collector's copy.`,
4935
+ sinkDown: (sink, seconds) => `${p} the ${sink} receiver has refused every batch for ${seconds} s. The server is answering; fix the receiver, then restart. Events are kept on the server until their retention period ends.`
4936
+ };
4937
+ }
4938
+ //#endregion
4939
+ //#region src/commands/org-events-tail.ts
4940
+ const eventSource = (fetchPage) => ({
4941
+ fetchPage: async (after, epoch) => {
4942
+ const page = await fetchPage(after, epoch);
4943
+ return {
4944
+ items: page.events,
4945
+ epoch: page.chain_epoch,
4946
+ floor: page.retention_floor
4947
+ };
4948
+ },
4949
+ step: verifyEvent,
4950
+ outgoing: eventOutgoing
4951
+ });
4952
+ function registerOrgEventsTail(org, program) {
4953
+ addTailOptions(org.command("events").description("The org's tamper-evident event log").command("tail").description("Follow the event log as one JSON envelope per line, verifying its hash chain and checking a signed head every minute"), true).action(withClient(program, async (ctx, opts) => {
4954
+ await launchTail(ctx, opts, {
4955
+ text: tailText(EVENTS_TAIL),
4956
+ withHead: true,
4957
+ source: eventSource((after, epoch) => fetchOrgEvents(ctx.client, after, void 0, epoch))
4958
+ });
4959
+ }));
4960
+ }
4961
+ //#endregion
4962
+ //#region src/commands/org-rules-words.ts
4963
+ /** The text `rine org rules` prints in one place. */
4964
+ const NOT_COVERING_OUTBOUND = "Does not cover groups: members from any organisation can still join and post. In sender-key groups, members from organisations this rule refuses cannot read your posts once your key changes, and get no notice of invitations. MLS groups are not affected.";
4965
+ const NOT_COVERING_INBOUND = "Does not cover groups: members from any organisation can still join and post. In sender-key groups, you cannot read posts from members of organisations this rule refuses once their key changes. MLS groups are not affected.";
4966
+ const EXPOSURE_INVALID = EXPOSURE_COPY.invalid;
4967
+ const OPEN_GROUP_ADVICE = "In a foreign open group, allowing does not restore posting: leave, or ask the owner to close it.";
4968
+ const GROUPS_PREVIEW_ADVICE = "Two organisations that both turn this rule on cannot share an open group. Use a closed group; an existing sender-key group does not convert.";
4969
+ const groupsHold = (g) => g === 1 ? "1 group holds" : `${g} groups hold`;
4970
+ /** The preset a ceiling equals, else "custom" with its switches. */
4971
+ function ceilingSummary(max) {
4972
+ for (const [name, set] of Object.entries(PRESETS)) if (Object.values(Surface).every((s) => set[s] === max[s])) return name;
4973
+ const on = Object.values(Surface).filter((s) => max[s]);
4974
+ return `custom (${on.length === 0 ? "nothing" : on.map((s) => EXPOSURE_COPY.surfaceNames[s]).join(", ")})`;
4975
+ }
4976
+ /** The one-line summary of how many rules are on or reporting. */
4977
+ function summaryLine$1(policy) {
4978
+ const modes = Object.values(PolicyRule).flatMap((r) => policy.rules[r]?.mode ?? []);
4979
+ const on = modes.filter((m) => m === RuleMode.Enforce).length;
4980
+ const reporting = modes.filter((m) => m === RuleMode.Report).length;
4981
+ const uncovered = [PolicyRule.ExternalOutbound, PolicyRule.ExternalInbound].some((r) => policy.rules[r]?.mode === RuleMode.Enforce) && !policy.groups_covered;
4982
+ return `${on} of ${modes.length} rules on, ${reporting} reporting.${uncovered ? " Groups are not covered." : ""}`;
4983
+ }
4984
+ /** What `external_groups` found standing, under the rule in `rules show`. */
4985
+ function groupsNote(policy) {
4986
+ const g = policy.existing.groups_unpostable ?? 0;
4987
+ if (g === 0) return ["No group your agents are in holds members outside your list."];
4988
+ const held = `${groupsHold(g)} members outside your list. Your agents cannot post there`;
4989
+ if (policy.rules.external_inbound.mode === RuleMode.Enforce) return [`${held}. Keys you already hold still open their posts; new keys arrive only from organisations your incoming message rule allows, and posts sealed with a key that never arrived stay unreadable. ${OPEN_GROUP_ADVICE}`];
4990
+ return [`${held}, and they keep reading. ${OPEN_GROUP_ADVICE}`];
4991
+ }
4992
+ /** The line printed when `external_groups` is set to enforce over groups it leaves unpostable. */
4993
+ function groupsSetLine(policy) {
4994
+ const g = policy.existing.groups_unpostable ?? 0;
4995
+ if (g === 0) return void 0;
4996
+ return `${g === 1 ? "1 group your agents are in holds" : `${g} groups your agents are in hold`} members outside this rule. Your agents keep their seats and cannot post there.`;
4997
+ }
4998
+ /** The lines of `rules preview external_groups`. */
4999
+ function groupsPreviewLines(p) {
5000
+ const [i, a] = [`${p.invitations} ${p.invitations === 1 ? "invitation" : "invitations"}`, `${p.applications} ${p.applications === 1 ? "application" : "applications"}`];
5001
+ const open = p.foreign_open_groups === 1 ? "1 of them is an open group" : `${p.foreign_open_groups} of them are open groups`;
5002
+ const hidden = `${i} would be hidden and ${a} would lose ${p.applications === 1 ? "its" : "their"} message`;
5003
+ return [`${groupsHold(p.groups)} members outside your list; your agents could not post there. ${open} owned by other organisations, where allowing does not restore posting. ${hidden}.`, GROUPS_PREVIEW_ADVICE];
5004
+ }
5005
+ /** The check `counterparties allow --groups` prints: the join, and whether the rule is on. */
5006
+ function groupsAllowLine(open, covered) {
5007
+ return `With groups allowed, this organisation can join your ${open === void 0 ? "open groups" : `${open} open groups`}${covered ? "" : " once the group rule is on"}, and your agents will send it the current group key.`;
5008
+ }
5009
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
5010
+ /** The lines under one rule in `rules show`. */
5011
+ function ruleNotes(policy, rule) {
5012
+ const { rules, existing } = policy;
5013
+ if (rules[rule] === void 0 || rules[rule].mode === RuleMode.Off) return [];
5014
+ switch (rule) {
5015
+ case PolicyRule.ExternalOutbound: return policy.groups_covered ? [] : [NOT_COVERING_OUTBOUND];
5016
+ case PolicyRule.ExternalInbound: return policy.groups_covered ? [] : [NOT_COVERING_INBOUND];
5017
+ case PolicyRule.ExternalGroups: return policy.groups_covered ? groupsNote(policy) : [];
5018
+ case PolicyRule.DirectoryListing: {
5019
+ const n = existing.agents_above_ceiling;
5020
+ const shown = `Agents may show at most: ${ceilingSummary(rules.directory_listing.max)}.`;
5021
+ return [n > 0 ? `${shown} ${plural(n, "agent shows", "agents show")} more than that, and keep doing so until you stop them.` : shown];
5022
+ }
5023
+ case PolicyRule.WebhookHosts: return existing.webhooks_outside > 0 ? [`${plural(existing.webhooks_outside, "webhook", "webhooks")} outside the list. They deliver nothing while this rule is on.`] : [];
5024
+ case PolicyRule.Funnel: return existing.funnel_hooks > 0 ? [`A hook opens the agent to anyone on the internet. ${plural(existing.funnel_hooks, "hook", "hooks")} still open.`] : [];
5025
+ case PolicyRule.ActingAs: return ["Named agents act only with their own key. Your organisation key can still suspend, delete or rotate them; a branch key can suspend or delete them."];
5026
+ default: return [];
5027
+ }
5028
+ }
5029
+ const STANDING = {
5030
+ webhook_hosts: [
5031
+ "webhooks_outside",
5032
+ "webhook",
5033
+ "webhooks"
5034
+ ],
5035
+ funnel: [
5036
+ "funnel_hooks",
5037
+ "funnel hook",
5038
+ "funnel hooks"
5039
+ ],
5040
+ directory_listing: [
5041
+ "agents_above_ceiling",
5042
+ "agent",
5043
+ "agents"
5044
+ ]
5045
+ };
5046
+ /** What stands outside a rule that was just set, or `undefined` when nothing does. */
5047
+ function existingLine(policy, rule) {
5048
+ const standing = STANDING[rule];
5049
+ if (standing === void 0) return void 0;
5050
+ const n = policy.existing[standing[0]];
5051
+ if (n === 0) return void 0;
5052
+ return `${n} existing ${n === 1 ? standing[1] : standing[2]} ${n === 1 ? "is" : "are"} outside this rule. To stop them: rine org rules stop-existing ${rule}`;
5053
+ }
5054
+ /** The lines reporting what a stop-existing action stopped. */
5055
+ function stoppedLines(r) {
5056
+ if (r.rule === PolicyRule.WebhookHosts) return [`Stopped ${r.stopped} webhooks.`];
5057
+ if (r.rule === PolicyRule.Funnel) {
5058
+ const lines = [`Removed ${r.stopped} funnel hooks.`];
5059
+ if (r.remaining > 0) lines.push(`${r.remaining} funnel hooks remain. Run the command again to remove them.`);
5060
+ return lines;
5061
+ }
5062
+ return [`Lowered ${r.stopped} agents to the rule's limit.`];
5063
+ }
5064
+ //#endregion
5065
+ //#region src/commands/runtime-warning.ts
5066
+ /**
5067
+ * Detect that the CLI runs inside an agent runtime, so a rule change can warn first.
5068
+ * Warn, never block: the command still runs. One table of markers; each is an environment
5069
+ * variable that runtime sets for the processes it starts (the OpenClaw and Hermes rigs and
5070
+ * Claude Code in `compose.openclaw.yml`, `compose.hermes.yml` and `compose.cc.yml`).
5071
+ */
5072
+ const RUNTIME_MARKERS = [
5073
+ {
5074
+ runtime: "Claude Code",
5075
+ vars: ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT"]
5076
+ },
5077
+ {
5078
+ runtime: "OpenClaw",
5079
+ vars: ["OPENCLAW_STATE_DIR", "OPENCLAW_CONFIG_PATH"]
5080
+ },
5081
+ {
5082
+ runtime: "Hermes",
5083
+ vars: ["HERMES_HOME", "HERMES_SESSION_KEY"]
5084
+ }
5085
+ ];
5086
+ /** The warning printed before a rule change inside an agent runtime. */
5087
+ const RUNTIME_WARNING = "This looks like an agent's environment. Change rules from a machine that runs no agents: an agent with a shell here can read your organisation key.";
5088
+ /** The runtime whose marker is set (non-empty) in `env`, or `undefined` in a plain shell. */
5089
+ function runtimeOf(env = process.env) {
5090
+ return RUNTIME_MARKERS.find((m) => m.vars.some((v) => env[v]))?.runtime;
5091
+ }
5092
+ /** Print the runtime warning on stderr when a runtime marker is set. */
5093
+ function warnInAgentRuntime(env = process.env) {
5094
+ if (runtimeOf(env) !== void 0) printError(RUNTIME_WARNING);
5095
+ }
5096
+ //#endregion
5097
+ //#region src/commands/org-counterparties-write.ts
5098
+ function directionsOf(opts) {
5099
+ if ([
5100
+ opts.outbound,
5101
+ opts.inbound,
5102
+ opts.both
5103
+ ].filter(Boolean).length > 1) throw new Error("Give one of --outbound, --inbound or --both.");
5104
+ if (opts.outbound) return [RuleDirection.Outbound];
5105
+ if (opts.inbound) return [RuleDirection.Inbound];
5106
+ return [RuleDirection.Outbound, RuleDirection.Inbound];
5107
+ }
5108
+ /** Our open groups, for the `--groups` check; `undefined` when the org principal cannot list them. */
5109
+ async function openGroups(ctx) {
5110
+ try {
5111
+ return (await ctx.client.get("/groups")).items.filter((g) => g.enrollment_policy === "open").length;
5112
+ } catch (err) {
5113
+ if (err instanceof RineApiError) return void 0;
5114
+ throw err;
5115
+ }
5116
+ }
5117
+ /** The counterparty write, plus the group check with `--groups`. */
5118
+ async function describe(ctx, ref, groups) {
5119
+ const c = await lookupCounterparty(ctx.client, ref);
5120
+ const domains = c.proven_domains.length > 0 ? `Proven domain: ${c.proven_domains.join(", ")}.` : "No proven domain. Names and slugs are chosen by whoever registers them.";
5121
+ const lines = [
5122
+ `${c.name} org ${c.org_id.slice(0, 8)}… tier ${c.tier}`,
5123
+ domains,
5124
+ `Check this code with a contact at ${c.name}:`,
5125
+ ` ${orgWords(c.org_id)}`
5126
+ ];
5127
+ if (groups) {
5128
+ const covered = (await getPolicy(ctx.client)).groups_covered;
5129
+ lines.push(groupsAllowLine(await openGroups(ctx), covered));
5130
+ }
5131
+ if (!ctx.gOpts.json) for (const l of lines) printText(l);
5132
+ return c.org_id;
5133
+ }
5134
+ async function theirAgentId(ctx, ref) {
5135
+ const id = UUID_RE.test(ref) ? ref : await resolveHandleViaWebFinger(ctx.apiUrl, ref);
5136
+ if (!UUID_RE.test(id)) throw new Error(`No agent matches '${ref}'.`);
5137
+ return id.toLowerCase();
5138
+ }
5139
+ function decide(program, parent, decision) {
5140
+ const verb = decision === Decision.Allow ? "Allow" : "Block";
5141
+ const cmd = parent.command(decision).description(`${verb} an organisation, or one of its agents, in the message rules`).argument("<ref>", "Organisation id, an agent handle, or the slug of an organisation you have dealt with").option("--outbound", "Our agents sending to it").option("--inbound", "Its agents sending to ours").option("--both", "Both directions (the default)").option("--agent <ours>", "Only for one of our agents").option("--their-agent <handle>", "Only for one of its agents").requiredOption("--reason <text>", "Why; kept with the entry").option("--yes", "Skip confirmation prompt");
5142
+ if (decision === Decision.Allow) cmd.option("--groups", "Also let it join your open groups once the group rule is on");
5143
+ cmd.action(withClient(program, async (ctx, ref, opts) => {
5144
+ const directions = directionsOf(opts);
5145
+ warnInAgentRuntime();
5146
+ const orgId = await describe(ctx, ref, opts.groups === true);
5147
+ if (!opts.yes && !ctx.gOpts.json) {
5148
+ if (!await promptConfirm(`${verb} ${directions.join(" and ")}?`)) return;
5149
+ }
5150
+ const ours = opts.agent && await resolveAgent$1(ctx, opts.agent);
5151
+ const theirs = opts.theirAgent && await theirAgentId(ctx, opts.theirAgent);
5152
+ const entries = [];
5153
+ for (const direction of directions) {
5154
+ const entry = {
5155
+ direction,
5156
+ counterparty_org_id: orgId,
5157
+ decision,
5158
+ groups: opts.groups === true,
5159
+ reason: opts.reason,
5160
+ ...ours ? { agent_id: ours } : {},
5161
+ ...theirs ? { counterparty_agent_id: theirs } : {}
5162
+ };
5163
+ entries.push(await putAllow(ctx.client, entry));
5164
+ }
5165
+ if (ctx.gOpts.json) return printJson(entries);
5166
+ printMutationOk(`${verb} entry written (${directions.join(", ")}).`);
5167
+ }));
5168
+ }
5169
+ function registerCounterpartyWrites(counterparties, program) {
5170
+ decide(program, counterparties, Decision.Allow);
5171
+ decide(program, counterparties, Decision.Block);
5172
+ counterparties.command("remove <id>").description("Remove an allow or block entry (an id from `counterparties entries`)").requiredOption("--reason <text>", "Why").action(withClient(program, async ({ client, gOpts }, id, opts) => {
5173
+ warnInAgentRuntime();
5174
+ await deleteAllow(client, id, opts.reason);
5175
+ printMutationOk("Entry removed", gOpts.json);
5176
+ }));
5177
+ counterparties.command("entries").description("List every allow and block entry (--json is the export)").action(withClient(program, async ({ client, gOpts }) => {
5178
+ const entries = await fetchAllAllow(client);
5179
+ if (gOpts.json) return printJson(entries);
5180
+ printTable(entries.map((e) => ({
5181
+ ID: e.id,
5182
+ Direction: e.direction,
5183
+ Decision: e.decision,
5184
+ Org: e.counterparty_org_id,
5185
+ Scope: e.scope_agent_id ?? "org",
5186
+ Groups: e.groups ? "yes" : "no",
5187
+ Reason: e.reason
5188
+ })));
5189
+ }));
5190
+ }
5191
+ //#endregion
5192
+ //#region src/commands/org-counterparties.ts
5193
+ const WEEK_MS = 10080 * 60 * 1e3;
5194
+ const PAGE_SIZE = 200;
5195
+ const header = (n, k) => `${n} organisations, ${k} new this week`;
5196
+ const checkCode = (words) => `Check this code with a contact at that organisation: ${words}. Names and slugs are chosen by whoever registers them.`;
5197
+ async function listAll(ctx) {
5198
+ const all = [];
5199
+ let cursor;
5200
+ do {
5201
+ const page = await fetchCounterparties(ctx.client, cursor, PAGE_SIZE);
5202
+ all.push(...page.counterparties);
5203
+ cursor = page.next_cursor ?? void 0;
5204
+ } while (cursor !== void 0);
5205
+ return all;
5206
+ }
5207
+ function registerOrgCounterparties(org, program) {
5208
+ registerCounterpartyWrites(org.command("counterparties").description("Organisations your agents exchanged messages with, counted from message envelopes, never from content").action(withClient(program, async (ctx) => {
5209
+ const all = await listAll(ctx);
5210
+ const since = Date.now() - WEEK_MS;
5211
+ const fresh = all.filter((c) => Date.parse(c.first_seen) >= since);
5212
+ const words = (c) => orgWords(c.counterparty_org_id);
5213
+ if (ctx.gOpts.json) {
5214
+ printJson({
5215
+ organisations: all.length,
5216
+ new_this_week: fresh.length,
5217
+ counterparties: all.map((c) => ({
5218
+ ...c,
5219
+ org_words: words(c)
5220
+ }))
5221
+ });
5222
+ return;
5223
+ }
5224
+ printText(header(all.length, fresh.length));
5225
+ for (const c of all) printText(`${c.counterparty_org_id} ${checkCode(words(c))}`);
5226
+ })), program);
5227
+ }
5228
+ //#endregion
5229
+ //#region src/commands/org-domain.ts
5230
+ const STATUS_WORDS = {
5231
+ pending: "pending",
5232
+ proven: "proven",
5233
+ lost: "no longer proven: the record was not found at two checks, or DNS gave no answer at seven"
5234
+ };
5235
+ function registerOrgDomain(org, program) {
5236
+ const domain = org.command("domain").description("Prove that your organisation controls a domain, with one DNS TXT record");
5237
+ domain.command("add <domain>").description("Claim a domain and print the record to publish").action(withClient(program, async ({ client, gOpts }, name) => {
5238
+ const d = await addDomain(client, name);
5239
+ if (gOpts.json) return printJson(d);
5240
+ printText(`Add a TXT record named ${d.txt_name} with the value ${d.txt_value}, then run: rine org domain verify ${d.domain}`);
5241
+ }));
5242
+ domain.command("verify <domain>").description("Look up the TXT record and prove the domain").action(withClient(program, async ({ client, gOpts }, name) => {
5243
+ const d = await verifyDomain(client, name);
5244
+ if (gOpts.json) return printJson(d);
5245
+ printText(`${d.domain} is proven for this organisation.`);
5246
+ }));
5247
+ domain.command("list").description("List the claimed domains and where each proof stands").action(withClient(program, async ({ client, gOpts }) => {
5248
+ const domains = await listDomains(client);
5249
+ if (gOpts.json) return printJson(domains);
5250
+ printTable(domains.map((d) => ({
5251
+ Domain: d.domain,
5252
+ Status: STATUS_WORDS[d.status],
5253
+ "Verified at": d.verified_at ?? ""
5254
+ })));
5255
+ }));
5256
+ domain.command("remove <domain>").description("Drop a claimed domain").action(withClient(program, async ({ client, gOpts }, name) => {
5257
+ await removeDomain(client, name);
5258
+ printMutationOk("Domain removed", gOpts.json);
5259
+ }));
5260
+ }
5261
+ //#endregion
5262
+ //#region src/commands/org-exposure.ts
5263
+ function registerOrgExposure(org, program) {
5264
+ org.command("exposure").description("How many of the organisation's agents are private, findable or listed").action(withClient(program, async ({ client, gOpts }) => {
5265
+ const view = await getOrgExposure(client);
5266
+ if (gOpts.json) return printJson(view);
5267
+ printText(orgSummaryLine(view));
5268
+ if (view.ceiling) printText(ceilingLine(view.ceiling));
5269
+ }));
5270
+ }
5271
+ //#endregion
5272
+ //#region src/commands/org-log-settings.ts
5273
+ const kept = (days) => `Events are now kept for ${days} days. Events already older are removed within a day.`;
5274
+ function registerOrgLogSettings(org, program) {
5275
+ const settings = org.command("log-settings").description("How long the org's event log keeps its events");
5276
+ settings.command("get").description("Show the event retention period").action(withClient(program, async ({ client, gOpts }) => {
5277
+ const current = await fetchLogSettings(client);
5278
+ if (gOpts.json) printJson(current);
5279
+ else printText(`Event retention: ${current.event_retention_days} days`);
5280
+ }));
5281
+ settings.command("set <days>").description("Set the event retention period (the organisation owner only)").action(withClient(program, async ({ client, gOpts }, raw) => {
5282
+ const days = Number(raw);
5283
+ if (!Number.isSafeInteger(days) || days < 1) throw new Error("days must be a whole number of at least 1");
5284
+ const saved = await putLogSettings(client, days);
5285
+ if (gOpts.json) printJson(saved);
5286
+ else printText(kept(saved.event_retention_days));
5287
+ }));
5288
+ }
5289
+ //#endregion
5290
+ //#region src/commands/org-metadata-tail.ts
5291
+ /** Metadata rows carry no hash and may skip numbers; they must only keep moving forward. */
5292
+ function metadataStep(row, previous, afterSeq) {
5293
+ if (row.seq <= (previous?.seq ?? afterSeq)) throw new ChainBreak(ChainFault.Break, row.seq);
5294
+ return { position: {
5295
+ seq: row.seq,
5296
+ hash: ""
5297
+ } };
5298
+ }
5299
+ function registerOrgMetadataTail(org, program) {
5300
+ addTailOptions(org.command("metadata").description("Facts about the messages the org's agents sent and received").command("tail").description("Follow message metadata (never content) as one JSON row per line"), false).action(withClient(program, async (ctx, opts) => {
5301
+ const orgId = ctx.auth?.orgId;
5302
+ const source = {
5303
+ fetchPage: async (after, epoch) => {
5304
+ const page = await fetchOrgMetadata(ctx.client, after, void 0, epoch);
5305
+ return {
5306
+ items: page.rows,
5307
+ epoch: page.chain_epoch
5308
+ };
5309
+ },
5310
+ step: metadataStep,
5311
+ outgoing: (row) => metadataOutgoing(row, orgId)
5312
+ };
5313
+ await launchTail(ctx, opts, {
5314
+ text: tailText(METADATA_TAIL),
5315
+ withHead: false,
5316
+ source
5317
+ });
5318
+ }));
5319
+ }
5320
+ //#endregion
5321
+ //#region src/commands/org-recover.ts
5322
+ /** Read the phrase without ever letting it reach argv or an echoed prompt. */
5323
+ async function readPhrase() {
5324
+ if (process.stdin.isTTY !== true) {
5325
+ const chunks = [];
5326
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
5327
+ return Buffer.concat(chunks).toString("utf-8").trim();
5328
+ }
5329
+ return (await promptPassword("Recovery phrase: ")).trim();
5330
+ }
5331
+ function agentRow(agent) {
5332
+ return {
5333
+ "Agent ID": agent.agent_id,
5334
+ Name: agent.name,
5335
+ Branch: agent.branch,
5336
+ "Key gen": agent.key_gen,
5337
+ Status: agent.status,
5338
+ Reason: agent.reason ?? ""
5339
+ };
5340
+ }
5341
+ function reseatRow(reseat) {
5342
+ return {
5343
+ "Agent ID": reseat.agent_id,
5344
+ "Group ID": reseat.group_id ?? "",
5345
+ Status: reseat.status,
5346
+ Reason: reseat.reason ?? "",
5347
+ "Escrow Pending": reseat.escrow_pending,
5348
+ "Escrow Gaps": reseat.escrow.gaps.length,
5349
+ "Escrow Gap Epochs": describeEscrowGaps(reseat.escrow.gaps),
5350
+ "Escrow Deferral": reseat.escrow.deferral ?? "",
5351
+ "Escrow Queued": reseat.escrow.queued,
5352
+ "Escrow Dropped": reseat.escrow.dropped,
5353
+ "Escrow Backlogged": reseat.escrow.backlogged
5354
+ };
5355
+ }
5356
+ function markerRow(marker) {
5357
+ return {
3884
5358
  "Agent ID": marker.agent_id,
3885
5359
  "Group ID": marker.group_id,
3886
5360
  Epoch: marker.epoch,
@@ -3913,7 +5387,7 @@ async function restoreOwnerOnly(dirs, profile, json) {
3913
5387
  console.log(`Org verification words: ${orgWords}`);
3914
5388
  }
3915
5389
  function registerOrgRecover(org, program) {
3916
- 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 dir: no request, no leaf keys, no group reseat").action(withErrorHandler(program, async (gOpts, opts) => {
5390
+ 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) => {
3917
5391
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
3918
5392
  if (opts.ownerOnly) {
3919
5393
  await restoreOwnerOnly(resolveDirs(), profile, gOpts.json);
@@ -3927,7 +5401,7 @@ function registerOrgRecover(org, program) {
3927
5401
  }));
3928
5402
  org.command("phrase").description("Show the recovery phrase again (terminal only)").action(withErrorHandler(program, () => {
3929
5403
  if (process.stdout.isTTY !== true) {
3930
- printError("rine org phrase shows the phrase on a terminal only; the phrase file is in the owner dir.");
5404
+ printError("rine org phrase shows the phrase on a terminal only; the phrase file is in the owner directory.");
3931
5405
  process.exitCode = 2;
3932
5406
  return;
3933
5407
  }
@@ -3935,6 +5409,134 @@ function registerOrgRecover(org, program) {
3935
5409
  }));
3936
5410
  }
3937
5411
  //#endregion
5412
+ //#region src/commands/org-rules-set.ts
5413
+ const pick = (label, values, value) => {
5414
+ const hit = values.find((v) => v === value);
5415
+ if (hit === void 0) throw new Error(`${label} takes ${values.join(" or ")}, not '${value}'.`);
5416
+ return hit;
5417
+ };
5418
+ const SWITCH_FLAGS = {
5419
+ directory: "maxDirectory",
5420
+ card: "maxCard",
5421
+ a2a: "maxA2a",
5422
+ did: "maxDid"
5423
+ };
5424
+ /** The ceiling a `--max` preset and the per-switch flags ask for, over the stored one. */
5425
+ function ceilingOf(opts, stored) {
5426
+ const named = opts.max === void 0 ? stored : isNamedPreset(opts.max) ? PRESETS[opts.max] : void 0;
5427
+ if (named === void 0) throw new Error(`--max takes ${Object.keys(PRESETS).join(", ")}, not '${opts.max}'.`);
5428
+ const max = { ...named };
5429
+ for (const s of Object.values(Surface)) {
5430
+ const flag = opts[SWITCH_FLAGS[s]];
5431
+ if (typeof flag === "string") max[s] = pick(`--max-${s}`, ["on", "off"], flag) === "on";
5432
+ }
5433
+ if (invalidSurfaces(max).length > 0) throw new Error(EXPOSURE_INVALID);
5434
+ return max;
5435
+ }
5436
+ function onlyWhereApplicable(rule, opts) {
5437
+ const given = [
5438
+ ["--default", opts.default !== void 0],
5439
+ ["--host", opts.host.length > 0],
5440
+ ["--agent", opts.agent.length > 0],
5441
+ ["--max*", Object.values(SWITCH_FLAGS).some((f) => opts[f] !== void 0) || opts.max !== void 0]
5442
+ ];
5443
+ const owner = {
5444
+ "--default": [PolicyRule.ExternalOutbound, PolicyRule.ExternalInbound],
5445
+ "--host": [PolicyRule.WebhookHosts],
5446
+ "--agent": [PolicyRule.ActingAs],
5447
+ "--max*": [PolicyRule.DirectoryListing]
5448
+ };
5449
+ for (const [flag, used] of given) if (used && !(owner[flag] ?? []).includes(rule)) throw new Error(`${flag} does not apply to ${rule}.`);
5450
+ }
5451
+ async function patchOf(ctx, policy, rule, mode, opts) {
5452
+ const { rules } = policy;
5453
+ switch (rule) {
5454
+ case PolicyRule.ExternalOutbound:
5455
+ case PolicyRule.ExternalInbound: return { [rule]: {
5456
+ mode,
5457
+ default: opts.default ? pick("--default", Object.values(MessageDefault), opts.default) : rules[rule].default
5458
+ } };
5459
+ case PolicyRule.DirectoryListing: return { directory_listing: {
5460
+ mode,
5461
+ max: ceilingOf(opts, rules.directory_listing.max)
5462
+ } };
5463
+ case PolicyRule.WebhookHosts: return { webhook_hosts: {
5464
+ mode,
5465
+ allow: opts.host.length > 0 ? opts.host : rules.webhook_hosts.allow
5466
+ } };
5467
+ case PolicyRule.ActingAs: return { acting_as: {
5468
+ mode,
5469
+ agents: opts.agent.length > 0 ? [...new Set(await Promise.all(opts.agent.map((a) => resolveAgent$1(ctx, a))))] : rules.acting_as.agents
5470
+ } };
5471
+ default: return { [rule]: { mode } };
5472
+ }
5473
+ }
5474
+ function registerRulesSet(rules, program) {
5475
+ rules.command("set <rule> <mode>").description("Set a rule's mode (off|report|enforce; new_agents, directory_listing, webhook_hosts, funnel and acting_as take no report)").option("--default <deny|allow>", "Message rules: what no entry decides").option("--host <pattern>", "webhook_hosts: an allowed host (repeatable)", collect, []).option("--agent <agent>", "acting_as: an agent that acts only with its own key (repeatable)", collect, []).option("--max <preset>", "directory_listing: the most agents may show (private, findable or listed)").option("--max-directory <on|off>", "directory_listing ceiling: directory listing").option("--max-card <on|off>", "directory_listing ceiling: profile card").option("--max-a2a <on|off>", "directory_listing ceiling: A2A discovery").option("--max-did <on|off>", "directory_listing ceiling: DID document").action(withClient(program, async (ctx, ruleName, modeName, opts) => {
5476
+ const rule = pick("rule", Object.values(PolicyRule), ruleName);
5477
+ const mode = pick(`${rule} mode`, RULE_MODES[rule], modeName);
5478
+ onlyWhereApplicable(rule, opts);
5479
+ warnInAgentRuntime();
5480
+ const current = await getPolicy(ctx.client);
5481
+ const policy = await patchRules(ctx.client, current.version, await patchOf(ctx, current, rule, mode, opts));
5482
+ if (ctx.gOpts.json) return printJson(policy);
5483
+ const set = policy.rules[rule];
5484
+ if (set !== void 0) printText(`${rule}: ${set.mode}`);
5485
+ const line = rule === PolicyRule.ExternalGroups ? groupsSetLine(policy) : existingLine(policy, rule);
5486
+ if (line !== void 0) printText(line);
5487
+ }));
5488
+ }
5489
+ //#endregion
5490
+ //#region src/commands/org-rules.ts
5491
+ const STOPPABLE = [
5492
+ PolicyRule.WebhookHosts,
5493
+ PolicyRule.Funnel,
5494
+ PolicyRule.DirectoryListing
5495
+ ];
5496
+ function ruleArg(name, among) {
5497
+ const rule = among.find((r) => r === name);
5498
+ if (rule === void 0) throw new Error(`Unknown rule '${name}'. Rules: ${among.join(", ")}.`);
5499
+ return rule;
5500
+ }
5501
+ /** What a message rule would have refused; for the group rule, what it would find; else what already stands. */
5502
+ function previewLines$1(p) {
5503
+ if (p.kind === "groups") return groupsPreviewLines(p);
5504
+ if (p.kind === "existing") return [p.total === 0 ? `Nothing stands outside ${p.rule} today.` : `${p.total} ${p.standing?.replaceAll("_", " ")} would be outside ${p.rule}.${p.ids_more > 0 ? ` ${p.ids_more} more not listed.` : ""}`];
5505
+ const way = p.rule === PolicyRule.ExternalOutbound ? "to" : "from";
5506
+ const lines = [`About ${p.refused_messages} messages ${way} ${p.counterparties} organisations in the last ${p.window_days} days would have been refused.`];
5507
+ const now = Date.now();
5508
+ for (const c of p.top) lines.push(` @${c.slug ?? `${c.org_id.slice(0, 8)}…`} ${c.messages} messages last ${humanTime(c.last_at, now)}`);
5509
+ lines.push(`Of these, about ${p.key_messages} were group key messages.`);
5510
+ lines.push(`Not counted: Welcomes, and anything older than your ${p.window_days}-day retention.`);
5511
+ return lines;
5512
+ }
5513
+ function registerOrgRules(org, program) {
5514
+ const rules = org.command("rules").description("Organisation rules");
5515
+ rules.command("show").description("Show the organisation's rules").action(withClient(program, async ({ client, gOpts }) => {
5516
+ const policy = await getPolicy(client);
5517
+ if (gOpts.json) return printJson(policy);
5518
+ for (const rule of Object.values(PolicyRule)) {
5519
+ if (policy.rules[rule] === void 0) continue;
5520
+ printText(`${rule}: ${policy.rules[rule].mode}`);
5521
+ for (const note of ruleNotes(policy, rule)) printText(` ${note}`);
5522
+ }
5523
+ printText(summaryLine$1(policy));
5524
+ }));
5525
+ registerRulesSet(rules, program);
5526
+ rules.command("preview <rule>").description("What enforcing a rule would do, writing nothing (message rules count past messages)").action(withClient(program, async ({ client, gOpts }, name) => {
5527
+ const preview = await previewRule(client, ruleArg(name, Object.values(PolicyRule)));
5528
+ if (gOpts.json) return printJson(preview);
5529
+ for (const line of previewLines$1(preview)) printText(line);
5530
+ }));
5531
+ rules.command("stop-existing <rule>").description("Stop what an enforced rule found already standing (webhook_hosts, funnel, directory_listing)").action(withClient(program, async ({ client, gOpts }, name) => {
5532
+ const rule = ruleArg(name, STOPPABLE);
5533
+ warnInAgentRuntime();
5534
+ const result = await stopExisting(client, rule);
5535
+ if (gOpts.json) return printJson(result);
5536
+ for (const line of stoppedLines(result)) printText(line);
5537
+ }));
5538
+ }
5539
+ //#endregion
3938
5540
  //#region src/commands/org.ts
3939
5541
  function renderOrg(data, opts) {
3940
5542
  if (opts.json) {
@@ -3950,14 +5552,23 @@ function renderOrg(data, opts) {
3950
5552
  }]);
3951
5553
  }
3952
5554
  function registerOrg(program) {
3953
- const org = program.command("org").description("Organization management");
5555
+ const org = program.command("org").description("Organisation management");
3954
5556
  registerOrgRecover(org, program);
3955
5557
  registerOrgBranch(org, program);
3956
- org.command("get").description("Get organization details").action(withClient(program, async ({ client, gOpts }) => {
5558
+ registerOrgFreeze(org, program);
5559
+ registerOrgRules(org, program);
5560
+ registerOrgDelegate(org, program);
5561
+ registerOrgEventsTail(org, program);
5562
+ registerOrgMetadataTail(org, program);
5563
+ registerOrgCounterparties(org, program);
5564
+ registerOrgDomain(org, program);
5565
+ registerOrgExposure(org, program);
5566
+ registerOrgLogSettings(org, program);
5567
+ org.command("get").description("Get organisation details").action(withClient(program, async ({ client, gOpts }) => {
3957
5568
  const { org: data } = await client.get("/whoami");
3958
5569
  renderOrg(data, gOpts);
3959
5570
  }));
3960
- org.command("update").description("Update organization details").option("--name <name>", "Organization name").option("--contact-email <email>", "Contact email address").option("--country-code <cc>", "ISO country code (e.g. DE)").action(withClient(program, async ({ client, gOpts }, opts) => {
5571
+ org.command("update").description("Update organisation details").option("--name <name>", "Organisation name").option("--contact-email <email>", "Contact email address").option("--country-code <cc>", "ISO country code (e.g. DE)").action(withClient(program, async ({ client, gOpts }, opts) => {
3961
5572
  const body = {};
3962
5573
  if (opts.name) body.name = opts.name;
3963
5574
  if (opts.contactEmail) body.contact_email = opts.contactEmail;
@@ -4123,7 +5734,7 @@ function registerPollToken(program) {
4123
5734
  //#endregion
4124
5735
  //#region src/commands/register.ts
4125
5736
  function registerRegister(program) {
4126
- program.command("register").description("Register a new organization (two-step PoW flow). Writes the org root key and recovery phrase to the owner dir").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organization name").requiredOption("--slug <slug>", "Organization slug").action(withErrorHandler(program, async (gOpts, opts) => {
5737
+ 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) => {
4127
5738
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
4128
5739
  const dirs = resolveDirs();
4129
5740
  const apiUrl = resolveApiUrl();
@@ -4168,6 +5779,10 @@ function emitLifecycle$1(json, data) {
4168
5779
  data
4169
5780
  }));
4170
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`;
4171
5786
  //#endregion
4172
5787
  //#region src/commands/relay-cert.ts
4173
5788
  /**
@@ -4329,6 +5944,16 @@ function parsePort(raw) {
4329
5944
  //#endregion
4330
5945
  //#region src/commands/relay-reconnect.ts
4331
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
+ }
4332
5957
  function isRevoked(err) {
4333
5958
  return typeof err === "object" && err !== null && err.revoked === true;
4334
5959
  }
@@ -4349,18 +5974,72 @@ async function reconnectAfterError(json, attempt, backoff, afterEmit) {
4349
5974
  * Resolve when the tunnel WS closes (carrying the classified close so the caller
4350
5975
  * can pick clean-vs-error reconnect) OR the stop handed to `setStop` runs on
4351
5976
  * SIGINT (resolves `undefined`; the caller's `stopped` flag short-circuits
4352
- * before the reconnect branch).
5977
+ * before the reconnect branch). A 4423 close (the agent is held) rejects.
4353
5978
  */
4354
5979
  function waitForClose(tunnel, isStopped, setStop) {
4355
- return new Promise((resolve) => {
5980
+ return new Promise((resolve, reject) => {
4356
5981
  if (isStopped()) return resolve(void 0);
4357
- tunnel.onClose((close) => resolve(close));
5982
+ tunnel.onClose((close) => close.code === CLOSE_SUSPENDED ? reject(new TunnelBindError(BindNakReason.Suspended)) : resolve(close));
4358
5983
  setStop(() => {
4359
5984
  tunnel.close();
4360
5985
  resolve(void 0);
4361
5986
  });
4362
5987
  });
4363
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
+ }
4364
6043
  //#endregion
4365
6044
  //#region src/commands/relay-tier.ts
4366
6045
  /** How a hook's request bytes reach the relay, decided once per connect by its tier. */
@@ -4434,6 +6113,7 @@ async function runRelayLoop(ctx) {
4434
6113
  let backoff = 1;
4435
6114
  let attempt = 0;
4436
6115
  let stopped = false;
6116
+ let paused = false;
4437
6117
  const refreshMargin = jitteredRefreshMargin();
4438
6118
  const cert = relayCert({
4439
6119
  configDir,
@@ -4469,7 +6149,10 @@ async function runRelayLoop(ctx) {
4469
6149
  const tier = await prepareTier(hook, onRequest, cert, json);
4470
6150
  const tunnel = await connectTunnel({
4471
6151
  controlWsUrl,
4472
- token: await mintToken({ refreshMargin }),
6152
+ token: await mintToken({
6153
+ refreshMargin,
6154
+ force: paused
6155
+ }),
4473
6156
  agentId,
4474
6157
  hostname,
4475
6158
  openLocalPipe: tier.openLocalPipe
@@ -4479,6 +6162,7 @@ async function runRelayLoop(ctx) {
4479
6162
  listener = live;
4480
6163
  });
4481
6164
  backoff = 1;
6165
+ paused = false;
4482
6166
  const close = await waitForClose(tunnel, () => stopped, (stop) => {
4483
6167
  stopConnection = stop;
4484
6168
  });
@@ -4504,12 +6188,14 @@ async function runRelayLoop(ctx) {
4504
6188
  process.exitCode = 2;
4505
6189
  return;
4506
6190
  }
4507
- if (isRevoked(err)) {
4508
- cert.stop();
4509
- emitLifecycle$1(json, { state: "tunnel_revoked" });
4510
- process.exitCode = 1;
4511
- return;
6191
+ const failure = await settleFailure(err, mintToken, json, (stop) => {
6192
+ stopConnection = stop;
6193
+ });
6194
+ if (failure === RelayFailure.Paused) {
6195
+ paused = true;
6196
+ continue;
4512
6197
  }
6198
+ if (failure === RelayFailure.Revoked) return exitRevoked(cert, json);
4513
6199
  backoff = await reconnectAfterError(json, attempt, backoff, () => {
4514
6200
  if (opts.verbose) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, error): ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
4515
6201
  });
@@ -4538,7 +6224,7 @@ async function runRelayLoop(ctx) {
4538
6224
  * mux framing or crypto: they call the rine-core funnel entry points.
4539
6225
  */
4540
6226
  function registerRelay(program) {
4541
- program.command("relay").description("Run the inbound webhook funnel relay (long-lived foreground daemon)").addOption(actorOption()).option("--hook <name>", "Hook name to relay", "default").option("--port <n>", "Local TLS listener port", "8443").option("--secret-file <path>", "Read the HMAC secret from a file").option("--secret-env <VAR>", "Read the HMAC secret from an env var").option("--staging", "Use the Let's Encrypt staging CA (dev)").option("--verbose", "Verbose reconnect logging").action(async (opts, command) => {
6227
+ 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) => {
4542
6228
  try {
4543
6229
  const gOpts = program.opts();
4544
6230
  const configDir = resolveConfigDir();
@@ -4565,6 +6251,67 @@ function registerRelay(program) {
4565
6251
  });
4566
6252
  }
4567
6253
  //#endregion
6254
+ //#region src/commands/stream-connection.ts
6255
+ /**
6256
+ * The server answered the stream request with a status other than 2xx (a hold's 403, a dead
6257
+ * token's 401). `eventsource-client` reads such a body as a stream that ended cleanly and
6258
+ * reconnects at once, so the connection turns it into an error the caller backs off from.
6259
+ */
6260
+ var StreamHttpError = class extends Error {
6261
+ constructor(status) {
6262
+ super(`The stream was refused with HTTP ${status}`);
6263
+ this.status = status;
6264
+ }
6265
+ };
6266
+ /**
6267
+ * One SSE connection, watched by a heartbeat timer: silence for
6268
+ * `heartbeatTimeoutMs` closes it, as do a server close and a stop request. A non-2xx
6269
+ * response rejects `closed` and ends the connection.
6270
+ */
6271
+ function openStreamConnection({ url, headers, heartbeatTimeoutMs, onMessage }) {
6272
+ let heartbeatTimer;
6273
+ let settle = () => {};
6274
+ let refuse = () => {};
6275
+ const closed = new Promise((resolve, reject) => {
6276
+ settle = resolve;
6277
+ refuse = reject;
6278
+ });
6279
+ const end = (reason, closeSource) => {
6280
+ if (heartbeatTimer) clearTimeout(heartbeatTimer);
6281
+ if (closeSource) es.close();
6282
+ settle(reason);
6283
+ };
6284
+ const refusingFetch = async (input, init) => {
6285
+ const response = await fetch(input, init);
6286
+ if (response.ok) return response;
6287
+ const error = new StreamHttpError(response.status);
6288
+ if (heartbeatTimer) clearTimeout(heartbeatTimer);
6289
+ es.close();
6290
+ refuse(error);
6291
+ throw error;
6292
+ };
6293
+ const resetHeartbeatTimer = () => {
6294
+ if (heartbeatTimer) clearTimeout(heartbeatTimer);
6295
+ heartbeatTimer = setTimeout(() => end("heartbeat_timeout", true), heartbeatTimeoutMs);
6296
+ };
6297
+ const es = createEventSource({
6298
+ url,
6299
+ headers,
6300
+ fetch: refusingFetch,
6301
+ onMessage: (event) => {
6302
+ resetHeartbeatTimer();
6303
+ onMessage(event);
6304
+ },
6305
+ onDisconnect: () => end("server_close", false),
6306
+ onScheduleReconnect: () => end("server_close", true)
6307
+ });
6308
+ resetHeartbeatTimer();
6309
+ return {
6310
+ closed,
6311
+ stop: () => end("signal", true)
6312
+ };
6313
+ }
6314
+ //#endregion
4568
6315
  //#region src/commands/stream-cursor.ts
4569
6316
  function cursorPath(configDir) {
4570
6317
  return join(configDir, "state", "stream-cursor.json");
@@ -4599,6 +6346,19 @@ function saveStreamCursor(configDir, agentId, eventId) {
4599
6346
  } catch {}
4600
6347
  }
4601
6348
  //#endregion
6349
+ //#region src/commands/stream-lifecycle.ts
6350
+ /** One lifecycle event, on stdout (JSON mode) or stderr (`--monitor`, so stdout stays messages only). */
6351
+ function emitLifecycle(gOpts, monitor, data) {
6352
+ if (gOpts.json) {
6353
+ const line = JSON.stringify({
6354
+ event: "lifecycle",
6355
+ data
6356
+ });
6357
+ if (monitor) process.stderr.write(`${line}\n`);
6358
+ else console.log(line);
6359
+ }
6360
+ }
6361
+ //#endregion
4602
6362
  //#region src/commands/stream-cleartext.ts
4603
6363
  /**
4604
6364
  * The preview for a message that arrived as A2A cleartext, or null for every
@@ -4607,8 +6367,8 @@ function saveStreamCursor(configDir, agentId, eventId) {
4607
6367
  * A cleartext body is readable without any key, so it is shown like any other
4608
6368
  * unverified line — the `?` mark, the same one every unverified preview uses —
4609
6369
  * led by the notice that says the body was never end-to-end encrypted. A
4610
- * payload that does not decode throws, and the caller's own catch renders the
4611
- * generic line.
6370
+ * payload that does not decode throws, and the caller treats the row as one
6371
+ * with no preview.
4612
6372
  */
4613
6373
  function a2aCleartextPreview(data) {
4614
6374
  const row = {
@@ -4651,63 +6411,269 @@ function parseRow(data) {
4651
6411
  * How `rine stream` renders one SSE `message` event: a single preview line,
4652
6412
  * decrypted when this agent can open it, plus at most one stderr notice.
4653
6413
  */
4654
- /** Never rejects: an event it cannot render becomes a truncated `[message]` line. */
4655
- async function formatMessageLine(dataStr, agentId, configDir, client, explain) {
6414
+ /** The one-line preview of a message that has already been opened. */
6415
+ function renderOpened({ data, cleartext, attempted, result, forgedStatus, unavailable }, explain) {
6416
+ const ts = (data.created_at ?? "").slice(0, 19) || "?";
6417
+ const sender = data.sender_handle ?? String(data.from_agent_id ?? "?");
6418
+ const msgType = data.type ?? "?";
6419
+ const control = isControlFrameType(data.type ?? "");
6420
+ const target = data.group_handle ? `${data.group_handle} (${msgType})` : msgType;
6421
+ let preview = cleartext ?? "[encrypted]";
6422
+ let notice = null;
6423
+ const verdict = result?.verificationStatus ?? forgedStatus;
6424
+ if (verdict && isAuthenticityFailure(verdict)) preview = verdict === "sender-mismatch" ? "[✗ sender mismatch]" : "[✗ invalid signature]";
6425
+ else if (result?.plaintext !== void 0) {
6426
+ const verified = result.verified ? "✓" : "?";
6427
+ preview = control ? `[${verified}] [control] ${data.type}` : `[${verified}] ${result.plaintext.slice(0, 60)}`;
6428
+ } else if (unavailable !== null) {
6429
+ preview = data.id ? `${SENDER_KEY_UNAVAILABLE_PREVIEW} rine message read ${data.id}` : SENDER_KEY_UNAVAILABLE_PREVIEW;
6430
+ notice = explain(unavailable.message).notice;
6431
+ } else if (attempted && isDecryptableVersion(data.encryption_version)) preview = "[decrypt failed]";
6432
+ return {
6433
+ line: `[${ts}] ${sender} → ${target}: ${preview}`,
6434
+ notice,
6435
+ control
6436
+ };
6437
+ }
6438
+ //#endregion
6439
+ //#region src/commands/stream-open.ts
6440
+ /**
6441
+ * Opens one SSE `message` event for `rine stream`: parses it, decrypts it when
6442
+ * this agent can, and says whether the row has settled. Both output modes call
6443
+ * this, so a row is opened once and `--json` stdout stays the raw event.
6444
+ */
6445
+ /**
6446
+ * Parse and decrypt one event. Throws on a frame that is not JSON; the callers
6447
+ * treat that as "no verdict". A cleartext row whose body does not decode is
6448
+ * still a row: it has no preview, and it settles through the `none` rule, as
6449
+ * the SDK settles it.
6450
+ */
6451
+ async function openStreamMessage(dataStr, agentId, configDir, client) {
6452
+ const data = JSON.parse(dataStr);
6453
+ let cleartext = null;
6454
+ let undecodable = false;
4656
6455
  try {
4657
- const data = JSON.parse(dataStr);
4658
- const ts = (data.created_at ?? "").slice(0, 19) || "?";
4659
- const sender = data.sender_handle ?? String(data.from_agent_id ?? "?");
4660
- const msgType = data.type ?? "?";
4661
- const target = data.group_handle ? `${data.group_handle} (${msgType})` : msgType;
4662
- const cleartext = a2aCleartextPreview(data);
4663
- let preview = cleartext ?? "[encrypted]";
4664
- let notice = null;
4665
- const fromAgentId = data.from_agent_id;
4666
- if (cleartext === null && data.encrypted_payload && fromAgentId && agentKeysExist(configDir, agentId)) {
4667
- let result;
4668
- let unavailable = null;
4669
- if (isGroupEncryptionVersion(data.encryption_version) && data.group_id) try {
4670
- result = await decryptGroupMessageWithRecovery(client, configDir, agentId, data.group_id, data.encrypted_payload, fromAgentId, data.created_at);
4671
- } catch (err) {
4672
- unavailable = asSenderKeyUnavailable(err, data.group_id);
4673
- }
4674
- else if (data.encryption_version === ENCRYPTION_VERSION_HYBRID_V2) try {
4675
- result = await decryptMessage(configDir, agentId, data.encrypted_payload, client, fromAgentId, agentId, data.created_at);
4676
- } catch {}
4677
- if (result && isAuthenticityFailure(result.verificationStatus)) preview = result.verificationStatus === "sender-mismatch" ? "[✗ sender mismatch]" : "[✗ invalid signature]";
4678
- else if (result?.plaintext !== void 0) {
4679
- ingestSenderKeyDistribution(configDir, agentId, data.type ?? "", result);
4680
- preview = `[${result.verified ? "✓" : "?"}] ${result.plaintext.slice(0, 60)}`;
4681
- } else if (unavailable !== null) {
4682
- preview = data.id ? `${SENDER_KEY_UNAVAILABLE_PREVIEW} rine message read ${data.id}` : SENDER_KEY_UNAVAILABLE_PREVIEW;
4683
- notice = explain(unavailable.message).notice;
4684
- } else if (isDecryptableVersion(data.encryption_version)) preview = "[decrypt failed]";
4685
- }
4686
- return {
4687
- line: `[${ts}] ${sender} \u2192 ${target}: ${preview}`,
4688
- notice
4689
- };
6456
+ cleartext = a2aCleartextPreview(data);
4690
6457
  } catch {
4691
- return {
4692
- line: `[message] ${dataStr.slice(0, 80)}`,
4693
- notice: null
4694
- };
6458
+ undecodable = true;
6459
+ }
6460
+ let result;
6461
+ let unavailable = null;
6462
+ let forgedStatus;
6463
+ const fromAgentId = data.from_agent_id;
6464
+ const attempted = Boolean(!undecodable && cleartext === null && data.encrypted_payload && fromAgentId && agentKeysExist(configDir, agentId));
6465
+ if (attempted && data.encrypted_payload && fromAgentId) {
6466
+ if (isGroupEncryptionVersion(data.encryption_version) && data.group_id) try {
6467
+ result = await decryptGroupMessageWithRecovery(client, configDir, agentId, data.group_id, data.encrypted_payload, fromAgentId, data.created_at);
6468
+ } catch (err) {
6469
+ forgedStatus = groupAuthenticityStatus(err) ?? void 0;
6470
+ unavailable = asSenderKeyUnavailable(err, data.group_id);
6471
+ }
6472
+ else if (data.encryption_version === ENCRYPTION_VERSION_HYBRID_V2) try {
6473
+ result = await decryptMessage(configDir, agentId, data.encrypted_payload, client, fromAgentId, agentId, data.created_at);
6474
+ } catch {}
6475
+ if (result && !isAuthenticityFailure(result.verificationStatus) && result.plaintext !== void 0) ingestSenderKeyDistribution(configDir, agentId, data.type ?? "", result);
4695
6476
  }
6477
+ return {
6478
+ data,
6479
+ cleartext,
6480
+ attempted,
6481
+ result,
6482
+ forgedStatus,
6483
+ unavailable
6484
+ };
6485
+ }
6486
+ /**
6487
+ * Whether the row has settled, so that acknowledging it loses nothing: it
6488
+ * opened, it was never ciphertext, or its author was refused. A frame this
6489
+ * agent has no keys for, or could not open yet, stays new.
6490
+ */
6491
+ function isSettledMessage(opened) {
6492
+ const { data, result, forgedStatus } = opened;
6493
+ return isSettledRow({
6494
+ encryption_version: data.encryption_version ?? "",
6495
+ verification_status: result?.verificationStatus ?? forgedStatus
6496
+ }, result?.plaintext !== void 0);
4696
6497
  }
4697
6498
  //#endregion
4698
- //#region src/commands/stream.ts
4699
- function emitLifecycle(gOpts, monitor, data) {
4700
- if (gOpts.json) {
4701
- const line = JSON.stringify({
4702
- event: "lifecycle",
4703
- data
6499
+ //#region src/commands/stream-message.ts
6500
+ /**
6501
+ * What `rine stream` does with one SSE event once it has arrived: print it in
6502
+ * the chosen mode, and acknowledge the row when it settled.
6503
+ *
6504
+ * The stream connects with the peek header, so the server marks nothing
6505
+ * delivered at yield. A row is acknowledged here, through the batcher, only
6506
+ * after it was opened (or was refused, or was never ciphertext); a row this
6507
+ * agent cannot open yet stays new for the next reader.
6508
+ */
6509
+ /** The environment of one stream, with a batcher that acknowledges through its client. */
6510
+ function createStreamEnv(base) {
6511
+ const acks = createAckBatcher({
6512
+ ack: (ids) => markDeliveredAs(base.client, base.agentId, ids),
6513
+ onError: (count, err) => process.stderr.write(`${ackFailureNotice(count, err)}\n`)
6514
+ });
6515
+ return {
6516
+ ...base,
6517
+ acks,
6518
+ inFlight: /* @__PURE__ */ new Set()
6519
+ };
6520
+ }
6521
+ /** How long a stop waits for rows still being opened before it sends the last batch. */
6522
+ const IN_FLIGHT_WAIT_MS = 2e3;
6523
+ /**
6524
+ * Let the rows still being opened queue their acks, then send the last batch.
6525
+ * Without the wait, a row that settles after the stop would re-arm a timer the
6526
+ * exiting process never runs. The wait is bounded: a decrypt that stalls on the
6527
+ * network must not hold a stop, and its row simply stays new.
6528
+ */
6529
+ async function closeStreamEnv(env, inFlightWaitMs = IN_FLIGHT_WAIT_MS) {
6530
+ try {
6531
+ await raceDeadline(Promise.allSettled([...env.inFlight]), inFlightWaitMs);
6532
+ } catch {}
6533
+ await env.acks.close();
6534
+ }
6535
+ /** Open the row, queue its ack when it settled, and print it in human mode. */
6536
+ async function settleAndPrint(env, dataStr) {
6537
+ let line;
6538
+ let control = false;
6539
+ try {
6540
+ const opened = await openStreamMessage(dataStr, env.agentId, env.configDir, env.client);
6541
+ const row = opened.data;
6542
+ if (row.id && isSettledMessage(opened)) env.acks.add(row.id);
6543
+ if (env.json) return;
6544
+ const rendered = renderOpened(opened, env.explain);
6545
+ if (rendered.notice !== null) printError(rendered.notice);
6546
+ line = rendered.line;
6547
+ control = rendered.control;
6548
+ } catch {
6549
+ if (env.json) return;
6550
+ line = `[message] ${dataStr.slice(0, 80)}`;
6551
+ }
6552
+ if (!(env.hideControl && control)) console.log(line);
6553
+ }
6554
+ function handleStreamEvent(env, { event, data, id }) {
6555
+ if (event === "heartbeat") env.acks.flush();
6556
+ if (env.json) {
6557
+ const hidden = env.hideControl && event === "message" && isControlEventData(data);
6558
+ if ((!env.monitor || event === "message") && !hidden) console.log(messageEventLine(event, id, data));
6559
+ } else if (event === "heartbeat" && env.verbose) process.stderr.write(`[heartbeat] ${data}\n`);
6560
+ if (event === "message") {
6561
+ const settling = settleAndPrint(env, data);
6562
+ env.inFlight.add(settling);
6563
+ settling.finally(() => env.inFlight.delete(settling));
6564
+ }
6565
+ }
6566
+ function backoffAfter({ backoff, startedAt }) {
6567
+ return Date.now() - startedAt >= 3e4 ? 1 : backoff;
6568
+ }
6569
+ /**
6570
+ * Say why a connection ended and wait out the backoff. Returns the backoff for
6571
+ * the next attempt, or null when the stream was stopped.
6572
+ */
6573
+ async function afterDisconnect(reason, ctx) {
6574
+ const { gOpts, monitor, attempt, stopping } = ctx;
6575
+ const backoff = backoffAfter(ctx);
6576
+ if (reason === "signal") {
6577
+ emitLifecycle(gOpts, monitor, {
6578
+ state: "stopped",
6579
+ reason: "signal"
4704
6580
  });
4705
- if (monitor) process.stderr.write(`${line}\n`);
4706
- else console.log(line);
6581
+ return null;
6582
+ }
6583
+ if (reason === "heartbeat_timeout") {
6584
+ const jittered = jitteredDelayMs(backoff);
6585
+ emitLifecycle(gOpts, monitor, {
6586
+ state: "reconnecting",
6587
+ reason: "heartbeat_timeout",
6588
+ attempt: attempt + 1,
6589
+ backoff_ms: jittered
6590
+ });
6591
+ if (!gOpts.json) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, heartbeat timeout)...\n`);
6592
+ await sleepWithSignal(jittered, stopping);
6593
+ return nextReconnectBackoffSeconds(backoff);
6594
+ }
6595
+ const jittered = jitteredDelayMs(backoff);
6596
+ emitLifecycle(gOpts, monitor, {
6597
+ state: "reconnecting",
6598
+ reason: "server_close",
6599
+ attempt: attempt + 1,
6600
+ backoff_ms: jittered
6601
+ });
6602
+ if (!gOpts.json) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, server close)...\n`);
6603
+ await sleepWithSignal(jittered, stopping);
6604
+ return nextReconnectBackoffSeconds(backoff);
6605
+ }
6606
+ /**
6607
+ * Say that an attempt failed and wait out the backoff. Returns the backoff for
6608
+ * the next attempt, or null when the failure was the stop itself.
6609
+ */
6610
+ async function afterError(err, stopped, ctx) {
6611
+ const { gOpts, monitor, verbose, attempt, stopping } = ctx;
6612
+ const backoff = backoffAfter(ctx);
6613
+ if (stopped) {
6614
+ emitLifecycle(gOpts, monitor, {
6615
+ state: "stopped",
6616
+ reason: "signal"
6617
+ });
6618
+ return null;
4707
6619
  }
6620
+ const errorMsg = err instanceof Error ? err.message : String(err);
6621
+ const jittered = jitteredDelayMs(backoff);
6622
+ emitLifecycle(gOpts, monitor, {
6623
+ state: "reconnecting",
6624
+ reason: "error",
6625
+ attempt: attempt + 1,
6626
+ backoff_ms: jittered,
6627
+ error: errorMsg
6628
+ });
6629
+ if (verbose) process.stderr.write(`Reconnecting in ${Math.round(jittered / 1e3)}s (attempt ${attempt + 1}, error: ${errorMsg})...\n`);
6630
+ else process.stderr.write(`Reconnecting (attempt ${attempt + 1}, error)...\n`);
6631
+ await sleepWithSignal(jittered, stopping);
6632
+ return nextReconnectBackoffSeconds(backoff);
4708
6633
  }
6634
+ //#endregion
6635
+ //#region src/commands/stream-stop.ts
6636
+ const FLUSH_WAIT_MS = 5e3;
6637
+ function listenForStop() {
6638
+ let stopped = false;
6639
+ let closeConnection;
6640
+ const controller = new AbortController();
6641
+ const stop = () => {
6642
+ if (stopped) process.exit(0);
6643
+ stopped = true;
6644
+ controller.abort();
6645
+ process.exitCode = 0;
6646
+ closeConnection?.();
6647
+ };
6648
+ process.on("SIGINT", stop);
6649
+ process.on("SIGTERM", stop);
6650
+ return {
6651
+ signal: controller.signal,
6652
+ get stopped() {
6653
+ return stopped;
6654
+ },
6655
+ onStop(close) {
6656
+ closeConnection = close;
6657
+ }
6658
+ };
6659
+ }
6660
+ /**
6661
+ * End the process with `code` once stdout and stderr have flushed. On a full
6662
+ * pipe Node queues writes and `process.exit` drops them, so a line whose row
6663
+ * was already acknowledged would never reach the reader. A reader stalled past
6664
+ * the wait does not hold the process open.
6665
+ */
6666
+ async function exitWhenFlushed(code, flushWaitMs = FLUSH_WAIT_MS) {
6667
+ const flushed = (out) => new Promise((resolve) => out.write("", () => resolve()));
6668
+ try {
6669
+ await raceDeadline(Promise.all([flushed(process.stdout), flushed(process.stderr)]), flushWaitMs);
6670
+ } catch {}
6671
+ process.exit(code);
6672
+ }
6673
+ //#endregion
6674
+ //#region src/commands/stream.ts
4709
6675
  function registerStream(program) {
4710
- program.command("stream").description("Stream incoming messages via SSE").addOption(actorOption("which agent is acting, and whose messages stream (name, handle, or agent ID)")).option("--verbose", "Show heartbeats and reconnect details").option("--persistent", "Disable server-side connection timeout").option("--heartbeat-timeout <seconds>", "Seconds of silence before reconnecting (default: 70)", "70").option("--monitor", "Suppress non-message stdout (for CC plugin monitors)").action(async (opts, command) => {
6676
+ 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) => {
4711
6677
  try {
4712
6678
  const gOpts = program.opts();
4713
6679
  const configDir = resolveConfigDir();
@@ -4721,72 +6687,66 @@ function registerStream(program) {
4721
6687
  let lastEventId = loadStreamCursor(configDir, agentId);
4722
6688
  let backoff = 1;
4723
6689
  let attempt = 0;
4724
- let stopped = false;
6690
+ let mintFresh = false;
4725
6691
  const refreshMargin = jitteredRefreshMargin();
4726
6692
  const explain = senderKeyExplainer();
4727
- let stopConnection;
4728
- process.on("SIGINT", () => {
4729
- stopped = true;
4730
- process.exitCode = 0;
4731
- stopConnection?.();
6693
+ const env = createStreamEnv({
6694
+ json: Boolean(gOpts.json),
6695
+ monitor: opts.monitor,
6696
+ verbose: opts.verbose,
6697
+ hideControl: opts.hideControl,
6698
+ agentId,
6699
+ configDir,
6700
+ client,
6701
+ explain
4732
6702
  });
4733
- while (!stopped) {
6703
+ const stop = listenForStop();
6704
+ while (!stop.stopped) {
4734
6705
  attempt++;
4735
- const state = { disconnectReason: "server_close" };
6706
+ const startedAt = Date.now();
6707
+ const reconnect = () => ({
6708
+ gOpts,
6709
+ monitor: opts.monitor,
6710
+ verbose: opts.verbose,
6711
+ attempt,
6712
+ backoff,
6713
+ startedAt,
6714
+ stopping: stop.signal
6715
+ });
4736
6716
  try {
4737
- const headers = {
4738
- Authorization: `Bearer ${await mintToken({ refreshMargin })}`,
6717
+ const token = await mintToken({
6718
+ refreshMargin,
6719
+ force: mintFresh
6720
+ });
6721
+ mintFresh = false;
6722
+ const headers = withPeekHeader({
6723
+ Authorization: `Bearer ${token}`,
4739
6724
  Accept: "text/event-stream"
4740
- };
6725
+ }, true);
4741
6726
  if (lastEventId) headers["Last-Event-ID"] = lastEventId;
4742
6727
  emitLifecycle(gOpts, opts.monitor, {
4743
6728
  state: "connecting",
4744
6729
  attempt,
4745
6730
  url
4746
6731
  });
4747
- await new Promise((resolve) => {
4748
- if (stopped) {
4749
- resolve();
4750
- return;
4751
- }
4752
- let heartbeatTimer;
4753
- const resetHeartbeatTimer = () => {
4754
- if (heartbeatTimer) clearTimeout(heartbeatTimer);
4755
- heartbeatTimer = setTimeout(() => {
4756
- state.disconnectReason = "heartbeat_timeout";
4757
- es.close();
4758
- resolve();
4759
- }, heartbeatTimeoutMs);
4760
- };
4761
- const es = createEventSource({
6732
+ let reason = "server_close";
6733
+ if (!stop.stopped) {
6734
+ const connection = openStreamConnection({
4762
6735
  url,
4763
6736
  headers,
6737
+ heartbeatTimeoutMs,
4764
6738
  onMessage: ({ event, data, id }) => {
4765
- resetHeartbeatTimer();
4766
6739
  if (id) {
4767
6740
  lastEventId = id;
4768
6741
  saveStreamCursor(configDir, agentId, id);
4769
6742
  }
4770
- if (gOpts.json) {
4771
- if (!opts.monitor || event === "message") console.log(messageEventLine(event, id, data));
4772
- } else if (event === "message") formatMessageLine(data, agentId, configDir, client, explain).then(({ line, notice }) => {
4773
- if (notice !== null) printError(notice);
4774
- console.log(line);
6743
+ handleStreamEvent(env, {
6744
+ event,
6745
+ data,
6746
+ id
4775
6747
  });
4776
- else if (event === "heartbeat" && opts.verbose) process.stderr.write(`[heartbeat] ${data}\n`);
4777
- },
4778
- onDisconnect: () => {
4779
- if (heartbeatTimer) clearTimeout(heartbeatTimer);
4780
- state.disconnectReason = "server_close";
4781
- resolve();
4782
- },
4783
- onScheduleReconnect: () => {
4784
- if (heartbeatTimer) clearTimeout(heartbeatTimer);
4785
- es.close();
4786
- resolve();
4787
6748
  }
4788
6749
  });
4789
- resetHeartbeatTimer();
4790
6750
  if (attempt === 1 && !gOpts.json) {
4791
6751
  process.stderr.write(`Connected to stream for agent ${agentId}\n`);
4792
6752
  if (opts.persistent) process.stderr.write("Persistent mode (no server timeout)\n");
@@ -4795,69 +6755,23 @@ function registerStream(program) {
4795
6755
  state: "connected",
4796
6756
  attempt
4797
6757
  });
4798
- const onStop = () => {
4799
- if (heartbeatTimer) clearTimeout(heartbeatTimer);
4800
- state.disconnectReason = "signal";
4801
- es.close();
4802
- resolve();
4803
- };
4804
- if (stopped) {
4805
- onStop();
4806
- return;
4807
- }
4808
- stopConnection = onStop;
4809
- });
4810
- stopConnection = void 0;
4811
- if (state.disconnectReason === "heartbeat_timeout") {
4812
- const jitteredBackoff = jitteredDelayMs(backoff);
4813
- emitLifecycle(gOpts, opts.monitor, {
4814
- state: "reconnecting",
4815
- reason: "heartbeat_timeout",
4816
- attempt: attempt + 1,
4817
- backoff_ms: jitteredBackoff
4818
- });
4819
- if (!gOpts.json) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, heartbeat timeout)...\n`);
4820
- await sleep(jitteredBackoff);
4821
- backoff = nextReconnectBackoffSeconds(backoff);
4822
- } else if (state.disconnectReason === "signal") {
4823
- emitLifecycle(gOpts, opts.monitor, {
4824
- state: "stopped",
4825
- reason: "signal"
4826
- });
4827
- break;
4828
- } else {
4829
- emitLifecycle(gOpts, opts.monitor, {
4830
- state: "reconnecting",
4831
- reason: "server_close",
4832
- attempt: attempt + 1,
4833
- backoff_ms: 0
4834
- });
4835
- if (!gOpts.json) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, server close)...\n`);
4836
- backoff = 1;
6758
+ if (stop.stopped) connection.stop();
6759
+ else stop.onStop(connection.stop);
6760
+ reason = await connection.closed;
6761
+ stop.onStop(void 0);
4837
6762
  }
6763
+ const next = await afterDisconnect(reason, reconnect());
6764
+ if (next === null) break;
6765
+ backoff = next;
4838
6766
  } catch (err) {
4839
- if (stopped) {
4840
- emitLifecycle(gOpts, opts.monitor, {
4841
- state: "stopped",
4842
- reason: "signal"
4843
- });
4844
- break;
4845
- }
4846
- const errorMsg = err instanceof Error ? err.message : String(err);
4847
- const jitteredBackoff = jitteredDelayMs(backoff);
4848
- emitLifecycle(gOpts, opts.monitor, {
4849
- state: "reconnecting",
4850
- reason: "error",
4851
- attempt: attempt + 1,
4852
- backoff_ms: jitteredBackoff,
4853
- error: errorMsg
4854
- });
4855
- if (opts.verbose) process.stderr.write(`Reconnecting in ${Math.round(jitteredBackoff / 1e3)}s (attempt ${attempt + 1}, error: ${errorMsg})...\n`);
4856
- else process.stderr.write(`Reconnecting (attempt ${attempt + 1}, error)...\n`);
4857
- await sleep(jitteredBackoff);
4858
- backoff = nextReconnectBackoffSeconds(backoff);
6767
+ mintFresh = err instanceof StreamHttpError && err.status === 401;
6768
+ const next = await afterError(err, stop.stopped, reconnect());
6769
+ if (next === null) break;
6770
+ backoff = next;
4859
6771
  }
4860
6772
  }
6773
+ await closeStreamEnv(env);
6774
+ await exitWhenFlushed(process.exitCode ?? 0);
4861
6775
  } catch (err) {
4862
6776
  printError(formatError(err));
4863
6777
  process.exitCode = 1;
@@ -6394,15 +8308,19 @@ var RowBook = class {
6394
8308
  this.#findings.clear();
6395
8309
  this.#newestMicros = null;
6396
8310
  }
6397
- /** A finding is told once per group, so equal gaps from two groups both reach the user. */
6398
- absorb(page, nowMs) {
8311
+ /**
8312
+ * A finding is told once per group, so equal gaps from two groups both reach the user. With
8313
+ * `hideControl`, group-key and group-invite control frames are still folded in (the window moves
8314
+ * past them) but are never reported as changed, so the view never shows them.
8315
+ */
8316
+ absorb(page, nowMs, hideControl = false) {
6399
8317
  const changed = [];
6400
8318
  const ceiling = (nowMs + FUTURE_CLAMP_MS) * 1e3;
6401
8319
  for (const message of page.items) {
6402
8320
  const micros = Math.min(message.row.createdAtMicros, ceiling);
6403
8321
  this.#newestMicros = Math.max(this.#newestMicros ?? micros, micros);
6404
8322
  const shown = this.#fold(message);
6405
- if (shown !== null) changed.push(shown);
8323
+ if (shown !== null && !(hideControl && isControlFrameType(message.row.type))) changed.push(shown);
6406
8324
  }
6407
8325
  const findings = page.findings.filter((finding) => {
6408
8326
  const key = findingKey(finding);
@@ -6627,7 +8545,7 @@ var Poller = class {
6627
8545
  }
6628
8546
  /** Fold a page into what is known; returns the messages the view has not seen in this form. */
6629
8547
  #absorb(page) {
6630
- const seen = this.#book.absorb(page, this.#now());
8548
+ const seen = this.#book.absorb(page, this.#now(), this.#options.hideControl);
6631
8549
  for (const finding of seen.findings) this.#emit({
6632
8550
  type: "finding",
6633
8551
  finding
@@ -8847,6 +10765,7 @@ async function runApp(deps) {
8847
10765
  reader: identity.reader,
8848
10766
  bucket: identity.bucket,
8849
10767
  pollS: deps.pollS,
10768
+ hideControl: deps.hideControl,
8850
10769
  emit: (event) => {
8851
10770
  bridge.onPoll(event);
8852
10771
  if (!closing && event.type === "page" && event.kind === PageKind.Poll) watch(orgs?.retry());
@@ -9081,6 +11000,7 @@ async function runFeed(options, deps) {
9081
11000
  emit,
9082
11001
  now,
9083
11002
  pollS: options.pollS,
11003
+ hideControl: options.hideControl,
9084
11004
  filter: {
9085
11005
  agentId: options.agent,
9086
11006
  groupId: options.group
@@ -9129,6 +11049,7 @@ async function runTui(opts, profile) {
9129
11049
  host,
9130
11050
  pollS,
9131
11051
  ascii: opts.ascii === true,
11052
+ hideControl: opts.hideControl,
9132
11053
  env: process.env,
9133
11054
  stdin: process.stdin,
9134
11055
  stdout: process.stdout,
@@ -9138,6 +11059,7 @@ async function runTui(opts, profile) {
9138
11059
  agent: opts.agent ?? null,
9139
11060
  group: opts.group ?? null,
9140
11061
  pollS,
11062
+ hideControl: opts.hideControl,
9141
11063
  once: opts.once === true,
9142
11064
  before: opts.before ?? null,
9143
11065
  host
@@ -9152,7 +11074,7 @@ async function runTui(opts, profile) {
9152
11074
  }
9153
11075
  }
9154
11076
  function registerTui(program) {
9155
- program.command("tui").description("Read the messages of every agent in your org in a terminal view (needs the org key)").option("--ascii", "draw with plain ASCII characters").addOption(new Option("--feed", "NDJSON feed of the same rows").hideHelp()).addOption(new Option("--once", "feed: emit the first page and exit").hideHelp()).addOption(new Option("--before <cursor>", "feed: start from an older page").hideHelp()).addOption(new Option("--agent <id>", "feed: only this agent's messages").hideHelp()).addOption(new Option("--group <id>", "feed: only this group's messages").hideHelp()).addOption(new Option("--poll <seconds>", "feed: seconds between reads (5 to 120)").hideHelp()).action(async (opts) => {
11077
+ program.command("tui").description("Read the messages of every agent in your org in a terminal view (needs the org key)").option("--ascii", "draw with plain ASCII characters").option("--hide-control", HIDE_CONTROL_HELP).addOption(new Option("--feed", "NDJSON feed of the same rows").hideHelp()).addOption(new Option("--once", "feed: emit the first page and exit").hideHelp()).addOption(new Option("--before <cursor>", "feed: start from an older page").hideHelp()).addOption(new Option("--agent <id>", "feed: only this agent's messages").hideHelp()).addOption(new Option("--group <id>", "feed: only this group's messages").hideHelp()).addOption(new Option("--poll <seconds>", "feed: seconds between reads (5 to 120)").hideHelp()).action(async (opts) => {
9156
11078
  process.exitCode = await runTui(opts, program.opts().profile);
9157
11079
  });
9158
11080
  }