@rine-network/cli 0.23.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.
- package/dist/main.js +1834 -113
- 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, ackAfterRead, ackFailureNotice, actorFromEnv, addMlsGroupMembers, admissionHeadline, admittedAgentIds, agentKeysExist, agentKeysFromPrivate, agentLabel, asSenderKeyUnavailable, assertBranchName, assertNoMlsDowngrade, buildIssueCertDeps, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildPeerVerification, buildReceiptMessage, cliSyncRemedy, clipToWidth, clipWithEllipsis, clusterWidth, compareVerificationWordsForAgent, connectTunnel, controlFrameReplyRefusal, createAckBatcher, 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, groupAuthenticityStatus, 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, isSettledRow, isX402MessageType, jitteredDelayMs, jitteredRefreshMargin, listMyInvites, loadAgentKeys, loadHookSecret, loadMeta, loadMlsGroup, loadMlsState, loadOrgFromOwner, loadPolicy, loadProfiles, loadSenderKeyStates, loadTokenCache, loadWalletKey, makeEdgePipeFactory, markA2aCleartext, markDeliveredAs, matchedQuoteToWire, messageToJson, mlsAdmissionSkipSentence, mlsErrorCode, mlsInitInFlightSync, mlsReadRefusal, namesASeatedSibling, nextReconnectBackoffSeconds, normalizeActor, normalizeHandle, openMlsClient, orgIdOfAgent, ownIdentityFor, parseFacilitatorHeaders, parseRecipientKey, parseX402Payload, peerVerificationLines, performAgentCreation, performRecovery, performRegistration, principalString, raceDeadline, 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, sleepWithSignal, 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);
|
|
@@ -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
|
|
@@ -2178,6 +2314,8 @@ 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
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) => {
|
|
@@ -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
|
|
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:
|
|
3382
|
+
items: items.map(jsonRow)
|
|
3221
3383
|
});
|
|
3222
3384
|
else {
|
|
3223
|
-
const rows =
|
|
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
|
}
|
|
@@ -3504,6 +3666,7 @@ function x402SendExtras(type, payload, emitMarker) {
|
|
|
3504
3666
|
async function sealForGroup(client, configDir, senderAgentId, group, payload, body) {
|
|
3505
3667
|
const mlsOnly = groupAcceptsMlsSendOnly(group);
|
|
3506
3668
|
assertNoMlsDowngrade(configDir, senderAgentId, group.id, mlsOnly);
|
|
3669
|
+
assertGroupPostable(group);
|
|
3507
3670
|
if (mlsOnly) {
|
|
3508
3671
|
if (group.mls_group_id == null) throw new MlsInitInFlightError(group.handle);
|
|
3509
3672
|
return (sendFields) => sealAndPostMlsGroupMessage({
|
|
@@ -3670,16 +3833,16 @@ function addMessageCommands(parent, program) {
|
|
|
3670
3833
|
registerSend(parent, program);
|
|
3671
3834
|
addInboxCommand(parent, program);
|
|
3672
3835
|
addReplyCommand(parent, program);
|
|
3673
|
-
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) => {
|
|
3674
3837
|
const ref = resolveThreadRef({
|
|
3675
3838
|
group: opts.group,
|
|
3676
3839
|
conversationId
|
|
3677
3840
|
}, THREAD_REF_SURFACES.cli);
|
|
3678
3841
|
const agentId = await actingAgent();
|
|
3679
|
-
const entries = await decryptThreadRows(configDir, agentId, (await readThreadPage(client, ref, {
|
|
3842
|
+
const entries = withoutControlFrames(await decryptThreadRows(configDir, agentId, (await readThreadPage(client, ref, {
|
|
3680
3843
|
...opts.limit ? { limit: opts.limit } : {},
|
|
3681
3844
|
extraHeaders: { [ACTING_AGENT_HEADER]: agentId }
|
|
3682
|
-
})).messages ?? [], client);
|
|
3845
|
+
})).messages ?? [], client, null), opts.hideControl);
|
|
3683
3846
|
if (gOpts.json) printJson(entries);
|
|
3684
3847
|
else printTable(entries.map(threadRow));
|
|
3685
3848
|
}));
|
|
@@ -3717,7 +3880,8 @@ function announcePhrase(opts) {
|
|
|
3717
3880
|
//#endregion
|
|
3718
3881
|
//#region src/commands/onboard.ts
|
|
3719
3882
|
function registerOnboard(program) {
|
|
3720
|
-
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("--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);
|
|
3721
3885
|
const profile = gOpts.profile ?? DEFAULT_PROFILE;
|
|
3722
3886
|
const dirs = resolveDirs();
|
|
3723
3887
|
const apiUrl = resolveApiUrl();
|
|
@@ -3765,6 +3929,7 @@ function registerOnboard(program) {
|
|
|
3765
3929
|
name: opts.agentName,
|
|
3766
3930
|
humanOversight: opts.humanOversight,
|
|
3767
3931
|
unlisted: opts.unlisted,
|
|
3932
|
+
exposure,
|
|
3768
3933
|
verifyIdentity: opts.verifyIdentity || Boolean(opts.svid) || hasSpiffeEndpoint(),
|
|
3769
3934
|
svid: opts.svid
|
|
3770
3935
|
});
|
|
@@ -3788,6 +3953,7 @@ function registerOnboard(program) {
|
|
|
3788
3953
|
})]);
|
|
3789
3954
|
console.log(`Org verification words: ${reg.org_words}`);
|
|
3790
3955
|
console.log(`\nAgent '${agent.name}' created — reachable at ${agent.handle}`);
|
|
3956
|
+
announceExposure(agent, exposure);
|
|
3791
3957
|
for (const line of verificationWordsLines(verification)) console.log(line);
|
|
3792
3958
|
if (agent.poll_url) console.log(`Poll URL: ${agent.poll_url}`);
|
|
3793
3959
|
if (agent.identity) console.log(`SPIFFE identity verified: ${agent.identity.spiffe_id} (trust tier ${agent.identity.trust_tier})`);
|
|
@@ -3799,10 +3965,44 @@ function registerOnboard(program) {
|
|
|
3799
3965
|
}));
|
|
3800
3966
|
}
|
|
3801
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
|
|
3802
4001
|
//#region src/commands/org-branch.ts
|
|
3803
4002
|
const NO_ROOT = "Creating a branch needs this org's root key (root.key in the owner directory). A delegate cannot create branches.";
|
|
3804
4003
|
function registerOrgBranch(org, program) {
|
|
3805
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");
|
|
4005
|
+
registerBranchHold(branch, program);
|
|
3806
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) => {
|
|
3807
4007
|
assertBranchName(name);
|
|
3808
4008
|
const org = loadOrgFromOwner(ownerDir);
|
|
@@ -3865,6 +4065,1259 @@ function registerOrgBranch(org, program) {
|
|
|
3865
4065
|
}));
|
|
3866
4066
|
}
|
|
3867
4067
|
//#endregion
|
|
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;
|
|
4106
|
+
}
|
|
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}.`);
|
|
4116
|
+
}
|
|
4117
|
+
function row(d) {
|
|
4118
|
+
return {
|
|
4119
|
+
Name: d.name,
|
|
4120
|
+
ID: d.id,
|
|
4121
|
+
Scopes: d.scopes.join(","),
|
|
4122
|
+
Created: d.created_at,
|
|
4123
|
+
Revoked: d.revoked_at ?? ""
|
|
4124
|
+
};
|
|
4125
|
+
}
|
|
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));
|
|
4149
|
+
}
|
|
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
|
|
3868
5321
|
//#region src/commands/org-recover.ts
|
|
3869
5322
|
/** Read the phrase without ever letting it reach argv or an echoed prompt. */
|
|
3870
5323
|
async function readPhrase() {
|
|
@@ -3956,6 +5409,134 @@ function registerOrgRecover(org, program) {
|
|
|
3956
5409
|
}));
|
|
3957
5410
|
}
|
|
3958
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
|
|
3959
5540
|
//#region src/commands/org.ts
|
|
3960
5541
|
function renderOrg(data, opts) {
|
|
3961
5542
|
if (opts.json) {
|
|
@@ -3974,6 +5555,15 @@ function registerOrg(program) {
|
|
|
3974
5555
|
const org = program.command("org").description("Organisation management");
|
|
3975
5556
|
registerOrgRecover(org, program);
|
|
3976
5557
|
registerOrgBranch(org, program);
|
|
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);
|
|
3977
5567
|
org.command("get").description("Get organisation details").action(withClient(program, async ({ client, gOpts }) => {
|
|
3978
5568
|
const { org: data } = await client.get("/whoami");
|
|
3979
5569
|
renderOrg(data, gOpts);
|
|
@@ -4189,6 +5779,10 @@ function emitLifecycle$1(json, data) {
|
|
|
4189
5779
|
data
|
|
4190
5780
|
}));
|
|
4191
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`;
|
|
4192
5786
|
//#endregion
|
|
4193
5787
|
//#region src/commands/relay-cert.ts
|
|
4194
5788
|
/**
|
|
@@ -4350,6 +5944,16 @@ function parsePort(raw) {
|
|
|
4350
5944
|
//#endregion
|
|
4351
5945
|
//#region src/commands/relay-reconnect.ts
|
|
4352
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
|
+
}
|
|
4353
5957
|
function isRevoked(err) {
|
|
4354
5958
|
return typeof err === "object" && err !== null && err.revoked === true;
|
|
4355
5959
|
}
|
|
@@ -4370,18 +5974,72 @@ async function reconnectAfterError(json, attempt, backoff, afterEmit) {
|
|
|
4370
5974
|
* Resolve when the tunnel WS closes (carrying the classified close so the caller
|
|
4371
5975
|
* can pick clean-vs-error reconnect) OR the stop handed to `setStop` runs on
|
|
4372
5976
|
* SIGINT (resolves `undefined`; the caller's `stopped` flag short-circuits
|
|
4373
|
-
* before the reconnect branch).
|
|
5977
|
+
* before the reconnect branch). A 4423 close (the agent is held) rejects.
|
|
4374
5978
|
*/
|
|
4375
5979
|
function waitForClose(tunnel, isStopped, setStop) {
|
|
4376
|
-
return new Promise((resolve) => {
|
|
5980
|
+
return new Promise((resolve, reject) => {
|
|
4377
5981
|
if (isStopped()) return resolve(void 0);
|
|
4378
|
-
tunnel.onClose((close) => resolve(close));
|
|
5982
|
+
tunnel.onClose((close) => close.code === CLOSE_SUSPENDED ? reject(new TunnelBindError(BindNakReason.Suspended)) : resolve(close));
|
|
4379
5983
|
setStop(() => {
|
|
4380
5984
|
tunnel.close();
|
|
4381
5985
|
resolve(void 0);
|
|
4382
5986
|
});
|
|
4383
5987
|
});
|
|
4384
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
|
+
}
|
|
4385
6043
|
//#endregion
|
|
4386
6044
|
//#region src/commands/relay-tier.ts
|
|
4387
6045
|
/** How a hook's request bytes reach the relay, decided once per connect by its tier. */
|
|
@@ -4455,6 +6113,7 @@ async function runRelayLoop(ctx) {
|
|
|
4455
6113
|
let backoff = 1;
|
|
4456
6114
|
let attempt = 0;
|
|
4457
6115
|
let stopped = false;
|
|
6116
|
+
let paused = false;
|
|
4458
6117
|
const refreshMargin = jitteredRefreshMargin();
|
|
4459
6118
|
const cert = relayCert({
|
|
4460
6119
|
configDir,
|
|
@@ -4490,7 +6149,10 @@ async function runRelayLoop(ctx) {
|
|
|
4490
6149
|
const tier = await prepareTier(hook, onRequest, cert, json);
|
|
4491
6150
|
const tunnel = await connectTunnel({
|
|
4492
6151
|
controlWsUrl,
|
|
4493
|
-
token: await mintToken({
|
|
6152
|
+
token: await mintToken({
|
|
6153
|
+
refreshMargin,
|
|
6154
|
+
force: paused
|
|
6155
|
+
}),
|
|
4494
6156
|
agentId,
|
|
4495
6157
|
hostname,
|
|
4496
6158
|
openLocalPipe: tier.openLocalPipe
|
|
@@ -4500,6 +6162,7 @@ async function runRelayLoop(ctx) {
|
|
|
4500
6162
|
listener = live;
|
|
4501
6163
|
});
|
|
4502
6164
|
backoff = 1;
|
|
6165
|
+
paused = false;
|
|
4503
6166
|
const close = await waitForClose(tunnel, () => stopped, (stop) => {
|
|
4504
6167
|
stopConnection = stop;
|
|
4505
6168
|
});
|
|
@@ -4525,12 +6188,14 @@ async function runRelayLoop(ctx) {
|
|
|
4525
6188
|
process.exitCode = 2;
|
|
4526
6189
|
return;
|
|
4527
6190
|
}
|
|
4528
|
-
|
|
4529
|
-
|
|
4530
|
-
|
|
4531
|
-
|
|
4532
|
-
|
|
6191
|
+
const failure = await settleFailure(err, mintToken, json, (stop) => {
|
|
6192
|
+
stopConnection = stop;
|
|
6193
|
+
});
|
|
6194
|
+
if (failure === RelayFailure.Paused) {
|
|
6195
|
+
paused = true;
|
|
6196
|
+
continue;
|
|
4533
6197
|
}
|
|
6198
|
+
if (failure === RelayFailure.Revoked) return exitRevoked(cert, json);
|
|
4534
6199
|
backoff = await reconnectAfterError(json, attempt, backoff, () => {
|
|
4535
6200
|
if (opts.verbose) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, error): ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
|
|
4536
6201
|
});
|
|
@@ -4588,20 +6253,43 @@ function registerRelay(program) {
|
|
|
4588
6253
|
//#endregion
|
|
4589
6254
|
//#region src/commands/stream-connection.ts
|
|
4590
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
|
+
/**
|
|
4591
6267
|
* One SSE connection, watched by a heartbeat timer: silence for
|
|
4592
|
-
* `heartbeatTimeoutMs` closes it, as do a server close and a stop request.
|
|
6268
|
+
* `heartbeatTimeoutMs` closes it, as do a server close and a stop request. A non-2xx
|
|
6269
|
+
* response rejects `closed` and ends the connection.
|
|
4593
6270
|
*/
|
|
4594
6271
|
function openStreamConnection({ url, headers, heartbeatTimeoutMs, onMessage }) {
|
|
4595
6272
|
let heartbeatTimer;
|
|
4596
6273
|
let settle = () => {};
|
|
4597
|
-
|
|
6274
|
+
let refuse = () => {};
|
|
6275
|
+
const closed = new Promise((resolve, reject) => {
|
|
4598
6276
|
settle = resolve;
|
|
6277
|
+
refuse = reject;
|
|
4599
6278
|
});
|
|
4600
6279
|
const end = (reason, closeSource) => {
|
|
4601
6280
|
if (heartbeatTimer) clearTimeout(heartbeatTimer);
|
|
4602
6281
|
if (closeSource) es.close();
|
|
4603
6282
|
settle(reason);
|
|
4604
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
|
+
};
|
|
4605
6293
|
const resetHeartbeatTimer = () => {
|
|
4606
6294
|
if (heartbeatTimer) clearTimeout(heartbeatTimer);
|
|
4607
6295
|
heartbeatTimer = setTimeout(() => end("heartbeat_timeout", true), heartbeatTimeoutMs);
|
|
@@ -4609,6 +6297,7 @@ function openStreamConnection({ url, headers, heartbeatTimeoutMs, onMessage }) {
|
|
|
4609
6297
|
const es = createEventSource({
|
|
4610
6298
|
url,
|
|
4611
6299
|
headers,
|
|
6300
|
+
fetch: refusingFetch,
|
|
4612
6301
|
onMessage: (event) => {
|
|
4613
6302
|
resetHeartbeatTimer();
|
|
4614
6303
|
onMessage(event);
|
|
@@ -4727,19 +6416,23 @@ function renderOpened({ data, cleartext, attempted, result, forgedStatus, unavai
|
|
|
4727
6416
|
const ts = (data.created_at ?? "").slice(0, 19) || "?";
|
|
4728
6417
|
const sender = data.sender_handle ?? String(data.from_agent_id ?? "?");
|
|
4729
6418
|
const msgType = data.type ?? "?";
|
|
6419
|
+
const control = isControlFrameType(data.type ?? "");
|
|
4730
6420
|
const target = data.group_handle ? `${data.group_handle} (${msgType})` : msgType;
|
|
4731
6421
|
let preview = cleartext ?? "[encrypted]";
|
|
4732
6422
|
let notice = null;
|
|
4733
6423
|
const verdict = result?.verificationStatus ?? forgedStatus;
|
|
4734
6424
|
if (verdict && isAuthenticityFailure(verdict)) preview = verdict === "sender-mismatch" ? "[✗ sender mismatch]" : "[✗ invalid signature]";
|
|
4735
|
-
else if (result?.plaintext !== void 0)
|
|
4736
|
-
|
|
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) {
|
|
4737
6429
|
preview = data.id ? `${SENDER_KEY_UNAVAILABLE_PREVIEW} rine message read ${data.id}` : SENDER_KEY_UNAVAILABLE_PREVIEW;
|
|
4738
6430
|
notice = explain(unavailable.message).notice;
|
|
4739
6431
|
} else if (attempted && isDecryptableVersion(data.encryption_version)) preview = "[decrypt failed]";
|
|
4740
6432
|
return {
|
|
4741
6433
|
line: `[${ts}] ${sender} → ${target}: ${preview}`,
|
|
4742
|
-
notice
|
|
6434
|
+
notice,
|
|
6435
|
+
control
|
|
4743
6436
|
};
|
|
4744
6437
|
}
|
|
4745
6438
|
//#endregion
|
|
@@ -4842,6 +6535,7 @@ async function closeStreamEnv(env, inFlightWaitMs = IN_FLIGHT_WAIT_MS) {
|
|
|
4842
6535
|
/** Open the row, queue its ack when it settled, and print it in human mode. */
|
|
4843
6536
|
async function settleAndPrint(env, dataStr) {
|
|
4844
6537
|
let line;
|
|
6538
|
+
let control = false;
|
|
4845
6539
|
try {
|
|
4846
6540
|
const opened = await openStreamMessage(dataStr, env.agentId, env.configDir, env.client);
|
|
4847
6541
|
const row = opened.data;
|
|
@@ -4850,16 +6544,18 @@ async function settleAndPrint(env, dataStr) {
|
|
|
4850
6544
|
const rendered = renderOpened(opened, env.explain);
|
|
4851
6545
|
if (rendered.notice !== null) printError(rendered.notice);
|
|
4852
6546
|
line = rendered.line;
|
|
6547
|
+
control = rendered.control;
|
|
4853
6548
|
} catch {
|
|
4854
6549
|
if (env.json) return;
|
|
4855
6550
|
line = `[message] ${dataStr.slice(0, 80)}`;
|
|
4856
6551
|
}
|
|
4857
|
-
console.log(line);
|
|
6552
|
+
if (!(env.hideControl && control)) console.log(line);
|
|
4858
6553
|
}
|
|
4859
6554
|
function handleStreamEvent(env, { event, data, id }) {
|
|
4860
6555
|
if (event === "heartbeat") env.acks.flush();
|
|
4861
6556
|
if (env.json) {
|
|
4862
|
-
|
|
6557
|
+
const hidden = env.hideControl && event === "message" && isControlEventData(data);
|
|
6558
|
+
if ((!env.monitor || event === "message") && !hidden) console.log(messageEventLine(event, id, data));
|
|
4863
6559
|
} else if (event === "heartbeat" && env.verbose) process.stderr.write(`[heartbeat] ${data}\n`);
|
|
4864
6560
|
if (event === "message") {
|
|
4865
6561
|
const settling = settleAndPrint(env, data);
|
|
@@ -4867,13 +6563,16 @@ function handleStreamEvent(env, { event, data, id }) {
|
|
|
4867
6563
|
settling.finally(() => env.inFlight.delete(settling));
|
|
4868
6564
|
}
|
|
4869
6565
|
}
|
|
4870
|
-
|
|
4871
|
-
|
|
6566
|
+
function backoffAfter({ backoff, startedAt }) {
|
|
6567
|
+
return Date.now() - startedAt >= 3e4 ? 1 : backoff;
|
|
6568
|
+
}
|
|
4872
6569
|
/**
|
|
4873
6570
|
* Say why a connection ended and wait out the backoff. Returns the backoff for
|
|
4874
6571
|
* the next attempt, or null when the stream was stopped.
|
|
4875
6572
|
*/
|
|
4876
|
-
async function afterDisconnect(reason,
|
|
6573
|
+
async function afterDisconnect(reason, ctx) {
|
|
6574
|
+
const { gOpts, monitor, attempt, stopping } = ctx;
|
|
6575
|
+
const backoff = backoffAfter(ctx);
|
|
4877
6576
|
if (reason === "signal") {
|
|
4878
6577
|
emitLifecycle(gOpts, monitor, {
|
|
4879
6578
|
state: "stopped",
|
|
@@ -4893,20 +6592,24 @@ async function afterDisconnect(reason, { gOpts, monitor, attempt, backoff, stopp
|
|
|
4893
6592
|
await sleepWithSignal(jittered, stopping);
|
|
4894
6593
|
return nextReconnectBackoffSeconds(backoff);
|
|
4895
6594
|
}
|
|
6595
|
+
const jittered = jitteredDelayMs(backoff);
|
|
4896
6596
|
emitLifecycle(gOpts, monitor, {
|
|
4897
6597
|
state: "reconnecting",
|
|
4898
6598
|
reason: "server_close",
|
|
4899
6599
|
attempt: attempt + 1,
|
|
4900
|
-
backoff_ms:
|
|
6600
|
+
backoff_ms: jittered
|
|
4901
6601
|
});
|
|
4902
6602
|
if (!gOpts.json) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, server close)...\n`);
|
|
4903
|
-
|
|
6603
|
+
await sleepWithSignal(jittered, stopping);
|
|
6604
|
+
return nextReconnectBackoffSeconds(backoff);
|
|
4904
6605
|
}
|
|
4905
6606
|
/**
|
|
4906
6607
|
* Say that an attempt failed and wait out the backoff. Returns the backoff for
|
|
4907
6608
|
* the next attempt, or null when the failure was the stop itself.
|
|
4908
6609
|
*/
|
|
4909
|
-
async function afterError(err, stopped,
|
|
6610
|
+
async function afterError(err, stopped, ctx) {
|
|
6611
|
+
const { gOpts, monitor, verbose, attempt, stopping } = ctx;
|
|
6612
|
+
const backoff = backoffAfter(ctx);
|
|
4910
6613
|
if (stopped) {
|
|
4911
6614
|
emitLifecycle(gOpts, monitor, {
|
|
4912
6615
|
state: "stopped",
|
|
@@ -4970,7 +6673,7 @@ async function exitWhenFlushed(code, flushWaitMs = FLUSH_WAIT_MS) {
|
|
|
4970
6673
|
//#endregion
|
|
4971
6674
|
//#region src/commands/stream.ts
|
|
4972
6675
|
function registerStream(program) {
|
|
4973
|
-
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) => {
|
|
4974
6677
|
try {
|
|
4975
6678
|
const gOpts = program.opts();
|
|
4976
6679
|
const configDir = resolveConfigDir();
|
|
@@ -4984,12 +6687,14 @@ function registerStream(program) {
|
|
|
4984
6687
|
let lastEventId = loadStreamCursor(configDir, agentId);
|
|
4985
6688
|
let backoff = 1;
|
|
4986
6689
|
let attempt = 0;
|
|
6690
|
+
let mintFresh = false;
|
|
4987
6691
|
const refreshMargin = jitteredRefreshMargin();
|
|
4988
6692
|
const explain = senderKeyExplainer();
|
|
4989
6693
|
const env = createStreamEnv({
|
|
4990
6694
|
json: Boolean(gOpts.json),
|
|
4991
6695
|
monitor: opts.monitor,
|
|
4992
6696
|
verbose: opts.verbose,
|
|
6697
|
+
hideControl: opts.hideControl,
|
|
4993
6698
|
agentId,
|
|
4994
6699
|
configDir,
|
|
4995
6700
|
client,
|
|
@@ -4998,17 +6703,24 @@ function registerStream(program) {
|
|
|
4998
6703
|
const stop = listenForStop();
|
|
4999
6704
|
while (!stop.stopped) {
|
|
5000
6705
|
attempt++;
|
|
6706
|
+
const startedAt = Date.now();
|
|
5001
6707
|
const reconnect = () => ({
|
|
5002
6708
|
gOpts,
|
|
5003
6709
|
monitor: opts.monitor,
|
|
5004
6710
|
verbose: opts.verbose,
|
|
5005
6711
|
attempt,
|
|
5006
6712
|
backoff,
|
|
6713
|
+
startedAt,
|
|
5007
6714
|
stopping: stop.signal
|
|
5008
6715
|
});
|
|
5009
6716
|
try {
|
|
6717
|
+
const token = await mintToken({
|
|
6718
|
+
refreshMargin,
|
|
6719
|
+
force: mintFresh
|
|
6720
|
+
});
|
|
6721
|
+
mintFresh = false;
|
|
5010
6722
|
const headers = withPeekHeader({
|
|
5011
|
-
Authorization: `Bearer ${
|
|
6723
|
+
Authorization: `Bearer ${token}`,
|
|
5012
6724
|
Accept: "text/event-stream"
|
|
5013
6725
|
}, true);
|
|
5014
6726
|
if (lastEventId) headers["Last-Event-ID"] = lastEventId;
|
|
@@ -5052,6 +6764,7 @@ function registerStream(program) {
|
|
|
5052
6764
|
if (next === null) break;
|
|
5053
6765
|
backoff = next;
|
|
5054
6766
|
} catch (err) {
|
|
6767
|
+
mintFresh = err instanceof StreamHttpError && err.status === 401;
|
|
5055
6768
|
const next = await afterError(err, stop.stopped, reconnect());
|
|
5056
6769
|
if (next === null) break;
|
|
5057
6770
|
backoff = next;
|
|
@@ -6595,15 +8308,19 @@ var RowBook = class {
|
|
|
6595
8308
|
this.#findings.clear();
|
|
6596
8309
|
this.#newestMicros = null;
|
|
6597
8310
|
}
|
|
6598
|
-
/**
|
|
6599
|
-
|
|
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) {
|
|
6600
8317
|
const changed = [];
|
|
6601
8318
|
const ceiling = (nowMs + FUTURE_CLAMP_MS) * 1e3;
|
|
6602
8319
|
for (const message of page.items) {
|
|
6603
8320
|
const micros = Math.min(message.row.createdAtMicros, ceiling);
|
|
6604
8321
|
this.#newestMicros = Math.max(this.#newestMicros ?? micros, micros);
|
|
6605
8322
|
const shown = this.#fold(message);
|
|
6606
|
-
if (shown !== null) changed.push(shown);
|
|
8323
|
+
if (shown !== null && !(hideControl && isControlFrameType(message.row.type))) changed.push(shown);
|
|
6607
8324
|
}
|
|
6608
8325
|
const findings = page.findings.filter((finding) => {
|
|
6609
8326
|
const key = findingKey(finding);
|
|
@@ -6828,7 +8545,7 @@ var Poller = class {
|
|
|
6828
8545
|
}
|
|
6829
8546
|
/** Fold a page into what is known; returns the messages the view has not seen in this form. */
|
|
6830
8547
|
#absorb(page) {
|
|
6831
|
-
const seen = this.#book.absorb(page, this.#now());
|
|
8548
|
+
const seen = this.#book.absorb(page, this.#now(), this.#options.hideControl);
|
|
6832
8549
|
for (const finding of seen.findings) this.#emit({
|
|
6833
8550
|
type: "finding",
|
|
6834
8551
|
finding
|
|
@@ -9048,6 +10765,7 @@ async function runApp(deps) {
|
|
|
9048
10765
|
reader: identity.reader,
|
|
9049
10766
|
bucket: identity.bucket,
|
|
9050
10767
|
pollS: deps.pollS,
|
|
10768
|
+
hideControl: deps.hideControl,
|
|
9051
10769
|
emit: (event) => {
|
|
9052
10770
|
bridge.onPoll(event);
|
|
9053
10771
|
if (!closing && event.type === "page" && event.kind === PageKind.Poll) watch(orgs?.retry());
|
|
@@ -9282,6 +11000,7 @@ async function runFeed(options, deps) {
|
|
|
9282
11000
|
emit,
|
|
9283
11001
|
now,
|
|
9284
11002
|
pollS: options.pollS,
|
|
11003
|
+
hideControl: options.hideControl,
|
|
9285
11004
|
filter: {
|
|
9286
11005
|
agentId: options.agent,
|
|
9287
11006
|
groupId: options.group
|
|
@@ -9330,6 +11049,7 @@ async function runTui(opts, profile) {
|
|
|
9330
11049
|
host,
|
|
9331
11050
|
pollS,
|
|
9332
11051
|
ascii: opts.ascii === true,
|
|
11052
|
+
hideControl: opts.hideControl,
|
|
9333
11053
|
env: process.env,
|
|
9334
11054
|
stdin: process.stdin,
|
|
9335
11055
|
stdout: process.stdout,
|
|
@@ -9339,6 +11059,7 @@ async function runTui(opts, profile) {
|
|
|
9339
11059
|
agent: opts.agent ?? null,
|
|
9340
11060
|
group: opts.group ?? null,
|
|
9341
11061
|
pollS,
|
|
11062
|
+
hideControl: opts.hideControl,
|
|
9342
11063
|
once: opts.once === true,
|
|
9343
11064
|
before: opts.before ?? null,
|
|
9344
11065
|
host
|
|
@@ -9353,7 +11074,7 @@ async function runTui(opts, profile) {
|
|
|
9353
11074
|
}
|
|
9354
11075
|
}
|
|
9355
11076
|
function registerTui(program) {
|
|
9356
|
-
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) => {
|
|
9357
11078
|
process.exitCode = await runTui(opts, program.opts().profile);
|
|
9358
11079
|
});
|
|
9359
11080
|
}
|