@rine-network/cli 0.24.0 → 0.26.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/README.md +44 -1
- package/dist/main.js +1837 -1000
- package/package.json +2 -2
package/dist/main.js
CHANGED
|
@@ -1,13 +1,41 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
2
|
import { Command, Option } from "commander";
|
|
3
|
-
import
|
|
3
|
+
import * as core from "@rine-network/core";
|
|
4
|
+
import { A2A_CLEARTEXT_NOTICE, ACTING_AGENT_ENV, ACTING_AGENT_HEADER, ACTOR_SURFACES, ADOPT_COMMAND, AGENT_ONLY_ENV, AGENT_ONLY_LIST_NOTICE, AdminTierUnavailableError, CARRIED_NOMINATION_SENTENCE, ConsentEnvError, DEFAULT_PROFILE, Decision, DelegateScope, ENCRYPTION_VERSION_HYBRID_V2, EXPOSURE_COPY, EmptyHookSecretError, FUNNEL_TIERS, GROUP_NOT_FOUND_LEAD, GROUP_READERS_NOTICE, HeadFault, HttpClient, IDENTITY_FILE, IdentityFileError, KEY_NOT_CURRENT_MESSAGE, KeyPackageRotation, MLS_ERR_GROUP_INACTIVE, MalformedPageError, MessageDefault, MlsEstablishStep, MlsInitInFlightError, OpTier, OrgReader, PAY_CONFIRM_WHY, PHRASE_FILE, PHRASE_INSTRUCTION, PRESETS, PROFILES_FILE, PROJECT_ENTRY_PREFIX, PolicyRule, Preset, PrincipalKind, ProjectDirRefusalCode, RULE_MODES, ReadGapReason, ReadKey, ReaderNetworkError, RelayFatalError, RineApiError, RuleDirection, RuleMode, SENDER_KEY_UNAVAILABLE_CODE, SENDER_KEY_UNAVAILABLE_PREVIEW, SeatUpdateStatus, SignalClass, StoredPolicyKind, Surface, THREAD_REF_SURFACES, THREAD_UNAVAILABLE, Tier, TokenBucket, UUID_RE, UnsupportedTierError, VOTE_DURATION_RULE, VOTE_ELECTORATE_RULE, X402Error, X402FacilitatorError, X402_ERROR, X402_MESSAGE_TYPE, a2aCleartextMark, a2aCleartextPayload, a2aCleartextPlaintext, aboveCeilingLine, ackAfterRead, ackFailureNotice, actingRoster, actorFromEnv, addDomain, addMlsGroupMembers, addProfileIfAbsent, admissionHeadline, admittedAgentIds, agentKeysExist, agentKeysFromPrivate, agentOnlyFromEnv, asSenderKeyUnavailable, assertBranchName, assertGroupPostable, assertNoMlsDowngrade, assertOwnerDirAllowed, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildPeerVerification, buildReceiptMessage, cappedLine, catchUpFields, catchUpNote, ceilingLine, checkIdentityCopy, cliSyncRemedy, clipToWidth, clipWithEllipsis, clusterWidth, compareVerificationWordsForAgent, configDirAt, controlFrameReplyRefusal, createAckBatcher, createBranch, createDelegate, createHook, createTierTokenFn, createWallet, createdPrivateLine, decryptGroupMessageWithRecovery, decryptMessage, decryptThreadRows, deleteAllow, deleteGroupMember, deleteHook, deleteHookSecret, deriveBranch, describeEscrowGaps, describeMlsReclamation, describeMlsRecovery, describeProjectDirIdentity, describeTiers, describeVoteEligibility, displayHandle, displayWidth, encryptGroupMessage, encryptionLine, establishMlsMembership, evictionMessage, fetchAllAllow, fetchCounterparties, fetchGroupMembers, fetchHeadKeys, fetchLogSettings, fetchOrgEventHead, fetchOrgEvents, fetchOrgMetadata, findOrgAgent, findingKey, fitFromTo, fitGroupSender, forgetBoundDir, forkPointOf, formatError, freezeOrg, fromBase64Url, gapToJson, getExposure, getOrCreateSenderKey, getOrRefreshToken, getOrgExposure, getPolicy, getProfile, getSuspension, getWalletAddress, graphemes, groupAcceptsMlsSendOnly, groupAdmissionSkipSentence, groupAuthenticityStatus, groupEncryption, groupEncryption as groupEncryption$1, groupIsMls, groupMlsInitInFlight, handleCompletionNote, hasRoot, hasSpiffeEndpoint, holdsAnyMlsState, holdsBranchKeys, holdsMlsState, hookNameError, hookNamePatternError, humanTime, identityStoreDir, impliedVoteEligibilityReason, inBackground, ingestSenderKeyDistribution, initMlsGroup, invalidHookNameMessage, invalidSurfaces, inviteNominates, isA2aCleartext, isAuthenticityFailure, isAutoPayable, isControlFrameType, isDecryptableVersion, isEpochConflict, isGroupEncryptionVersion, isMlsResyncUnavailable, isMlsRotatedLeaf, isNamedPreset, isPathSafeId, isRecoverableMlsRead, isSettledRow, isX402MessageType, jcsCanonicalize, jitteredDelayMs, jitteredRefreshMargin, leadsNowhere, linksToProjectEntry, listAgentStates, listDelegates, listDomains, listHooks, listMyInvites, listOperations, loadAgentKeys, loadHookSecret, loadMlsGroup, loadMlsState, loadOrgFromOwner, loadPolicy, loadPolicyWithTrust, loadProfiles, loadSenderKeyStates, loadTokenCache, loadWalletKey, localActorId, lookupCounterparty, markA2aCleartext, markDeliveredAs, matchedQuoteToWire, messageToJson, missingKeysMessage, mlsAdmissionSkipSentence, mlsErrorCode, mlsInitInFlightSync, mlsReadRefusal, namesASeatedSibling, newDelegateKey, nextReconnectBackoffSeconds, normalizeActor, normalizeHandle, openMlsClient, operationByCli, orgIdOfAgent, orgRosterClient, orgSummaryLine, orgWords, ownIdentityFor, ownedByUs, ownerStoreDir, parseFacilitatorHeaders, parsePort, parseRecipientKey, parseX402Payload, patchRules, paymentConfirmReason, peerVerificationLines, performAgentCreation, performRecovery, performRegistration, pickAgent, postingLine, presetLine, presetOf, previewExposure, previewLines, previewRule, principalString, projectDirIdentity, projectLinkPath, projectLinkRefusal, putAllow, putExposure, putLogSettings, raceDeadline, readBoundDirs, readDailySpent, readIdentityFile, readOwnerPhrase, readProjectIdentityFile, readStoredPolicy, readThreadPage, readableGroupById, recipientKeyWords, recordBoundDir, recordPeerVerification, recoverGroup, recoveredCatchUp, refusalReceiptBody, refusedLine, relaySeams, removeAgentKeys, removeDomain, reportFailedSetup, reportedCatchUp, requireVerifiedPlaintext, requirementAmount, reserveSpend, resolveAgent, resolveApiUrl, resolveAuth, resolveConfigDir, resolveFacilitatorConfig, resolveGroup, resolveGroupByHandle, resolveGroupForJoin, resolveHandleViaWebFinger, resolveOwnerDir, resolvePayeeRequirement, resolveThreadRef, resolveToUuid, restoreAgentInto, restoreOwnerFromPhrase, resumeAgent, resumeBranch, resumeMlsGroupAdmission, retireLocalGroupState, retirementMessage, retryAfterMsFromError, revokeBranch, revokeDelegate, rotateAgentWithSeats, runRelay, safeBlock, saveAgentKeys, saveDelegateSeed, savePolicy, savePolicyUnlessSigned, saveProfiles, saveSignedPolicy, saveTokenCache, scrub, sealAndPostMlsGroupMessage, sealBranchBundle, sealForAgent, sealedX402Body, seatUpdateLine, seatedMemberAfterConflict, selectRequirement, sendGroupInviteNotification, sendReceipt, senderKeyExplainer, settleToReceipt, signPolicy, signalClass, singleActorValue, sleepWithSignal, spendPolicyModeFromEnv, splitThreadCatchUp, startupEscrowSweep, stopExisting, summaryLine, suspendAgent, suspendBranch, switchLines, toBase64Url, unfreezeOrg, unreadableByOrgsSentence, validateEncryptionKey, validateSigningKey, validateSlug, verificationWordsLines, verifyDomain, verifyHead, verifyIdentitySpiffe, walletKeyExists, withA2aCleartextNotice, withEvictionPointer, withPeekHeader, writableByOthers, writeAtomic, writeIdentityFile } from "@rine-network/core";
|
|
4
5
|
import * as fs$1 from "node:fs";
|
|
5
6
|
import fs, { readFileSync } from "node:fs";
|
|
6
7
|
import readline from "node:readline";
|
|
7
|
-
import { join } from "node:path";
|
|
8
|
+
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
8
9
|
import { createHash, randomBytes } from "node:crypto";
|
|
9
10
|
import { resolve4 } from "node:dns/promises";
|
|
10
11
|
import { createEventSource } from "eventsource-client";
|
|
12
|
+
//#region src/agent-only.ts
|
|
13
|
+
/** The space-joined command path (`"group create"`): the key the operation catalog uses. */
|
|
14
|
+
function commandPath(command) {
|
|
15
|
+
const names = [];
|
|
16
|
+
for (let node = command; node?.parent; node = node.parent) names.unshift(node.name());
|
|
17
|
+
return names.join(" ");
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Under `RINE_AGENT_ONLY` a command whose operation is not Agent tier is refused before it
|
|
21
|
+
* runs: it would need the org root, which an agent-only runtime never loads. A command the
|
|
22
|
+
* catalog does not know is left to run, because the catalog gate keeps every command mapped.
|
|
23
|
+
* With the variable unset the hook does nothing.
|
|
24
|
+
*/
|
|
25
|
+
function refuseOutsideAgentTier(program) {
|
|
26
|
+
program.hook("preAction", (_, action) => {
|
|
27
|
+
try {
|
|
28
|
+
if (!agentOnlyFromEnv()) return;
|
|
29
|
+
} catch (err) {
|
|
30
|
+
if (!(err instanceof ConsentEnvError)) throw err;
|
|
31
|
+
program.error(err.message, { exitCode: 1 });
|
|
32
|
+
}
|
|
33
|
+
const path = commandPath(action);
|
|
34
|
+
const tier = operationByCli(path)?.tier;
|
|
35
|
+
if (tier !== void 0 && tier !== OpTier.Agent) program.error(`rine ${path} needs the org, and ${AGENT_ONLY_ENV}=1 keeps this runtime to its own agent: run it where the org root lives.`, { exitCode: 1 });
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
11
39
|
//#region src/output.ts
|
|
12
40
|
function printSuccess(msg) {
|
|
13
41
|
console.log(`✓ ${msg}`);
|
|
@@ -100,15 +128,17 @@ function blameEnvActor(err) {
|
|
|
100
128
|
* *elsewhere*, and an acting agent is always one of this org's own.
|
|
101
129
|
*/
|
|
102
130
|
function actorLadder(flagged, client, headers) {
|
|
131
|
+
const fromEnv = flagged === void 0 ? actorFromEnv() : void 0;
|
|
132
|
+
const named = flagged ?? fromEnv;
|
|
103
133
|
let agentList;
|
|
104
134
|
const agents = () => {
|
|
105
|
-
agentList ??=
|
|
135
|
+
agentList ??= actingRoster(client, named);
|
|
106
136
|
return agentList;
|
|
107
137
|
};
|
|
108
|
-
const fromEnv = flagged === void 0 ? actorFromEnv() : void 0;
|
|
109
|
-
const named = flagged ?? fromEnv;
|
|
110
138
|
const resolve = async () => {
|
|
111
139
|
if (named !== void 0 && UUID_RE.test(named)) return named;
|
|
140
|
+
const local = localActorId(client, named);
|
|
141
|
+
if (local !== void 0) return local;
|
|
112
142
|
const list = await agents();
|
|
113
143
|
let resolved;
|
|
114
144
|
try {
|
|
@@ -260,39 +290,88 @@ function namedActor(command, gOpts) {
|
|
|
260
290
|
}]);
|
|
261
291
|
}
|
|
262
292
|
//#endregion
|
|
263
|
-
//#region src/
|
|
264
|
-
/**
|
|
293
|
+
//#region src/dirs.ts
|
|
294
|
+
/**
|
|
295
|
+
* The config dir's files and the owner dir that holds the org root: what the
|
|
296
|
+
* commands that read the org root (the Admin tier) take.
|
|
297
|
+
*/
|
|
298
|
+
function custodyDirsOf(dir) {
|
|
299
|
+
return {
|
|
300
|
+
configDir: dir.path,
|
|
301
|
+
ownerDir: resolveOwnerDir(dir)
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* What a command signs from: the runtime dir alone under `RINE_AGENT_ONLY`, else
|
|
306
|
+
* the custody dirs.
|
|
307
|
+
*/
|
|
308
|
+
function authDirsOf(dir) {
|
|
309
|
+
return agentOnlyFromEnv() ? {
|
|
310
|
+
configDir: dir.path,
|
|
311
|
+
agentOnly: true
|
|
312
|
+
} : custodyDirsOf(dir);
|
|
313
|
+
}
|
|
314
|
+
/** {@link custodyDirsOf} for the dir the environment resolves, for a command that shows nothing of it. */
|
|
315
|
+
function resolveCustodyDirs() {
|
|
316
|
+
return custodyDirsOf(resolveConfigDir());
|
|
317
|
+
}
|
|
318
|
+
/** {@link authDirsOf} for the dir the environment resolves, for a command that shows nothing of it. */
|
|
265
319
|
function resolveDirs() {
|
|
320
|
+
return authDirsOf(resolveConfigDir());
|
|
321
|
+
}
|
|
322
|
+
/** The dirs of an org-level command: the owner dir holds `root.key`. Throws under `RINE_AGENT_ONLY`. */
|
|
323
|
+
function custodyOf(dirs) {
|
|
324
|
+
if (dirs.agentOnly === true) throw new AdminTierUnavailableError();
|
|
325
|
+
return dirs;
|
|
326
|
+
}
|
|
327
|
+
//#endregion
|
|
328
|
+
//#region src/tier-client.ts
|
|
329
|
+
/**
|
|
330
|
+
* A client that signs each request as the least principal that may make it
|
|
331
|
+
* (`createTierTokenFn`), and the tier resolution behind it. `identity` is the
|
|
332
|
+
* principal the dir acts as day to day: its agent, else the admin principal.
|
|
333
|
+
* It reads the org root only when the dir holds no agent profile.
|
|
334
|
+
*/
|
|
335
|
+
function buildTierClient(opts) {
|
|
336
|
+
const { dirs, apiUrl, profile, defaultHeaders, refreshMargin } = opts;
|
|
337
|
+
const tier = createTierTokenFn(dirs, apiUrl, profile, { refreshMargin });
|
|
338
|
+
const identity = tier.agentAuth() ?? tier.adminAuth();
|
|
266
339
|
return {
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
340
|
+
client: new HttpClient({
|
|
341
|
+
tokenFn: tier.tokenFn,
|
|
342
|
+
localAgent: tier.localAgent,
|
|
343
|
+
canRefresh: tier.canRefresh,
|
|
344
|
+
apiUrl,
|
|
345
|
+
defaultHeaders,
|
|
346
|
+
ownIdentity: ownIdentityFor(dirs.configDir, identity)
|
|
347
|
+
}),
|
|
348
|
+
tier,
|
|
349
|
+
identity
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
//#endregion
|
|
353
|
+
//#region src/action.ts
|
|
354
|
+
async function createClient(opts) {
|
|
355
|
+
const dir = opts.dir ?? resolveConfigDir();
|
|
356
|
+
const dirs = authDirsOf(dir);
|
|
357
|
+
const { client, tier, identity } = buildTierClient({
|
|
358
|
+
dirs,
|
|
359
|
+
apiUrl: opts.apiUrl,
|
|
360
|
+
profile: opts.profile,
|
|
361
|
+
defaultHeaders: opts.defaultHeaders,
|
|
279
362
|
refreshMargin: opts.refreshMargin
|
|
280
363
|
});
|
|
281
|
-
const
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
apiUrl,
|
|
285
|
-
canRefresh: !envToken,
|
|
286
|
-
defaultHeaders,
|
|
287
|
-
ownIdentity: ownIdentityFor(dirs.configDir, auth)
|
|
364
|
+
const tokenFor = (actor) => ({ force = false } = {}) => tier.tokenFn(force, {
|
|
365
|
+
tier: Tier.Agent,
|
|
366
|
+
actor
|
|
288
367
|
});
|
|
289
|
-
inBackground(() => startupEscrowSweep(client, dirs.configDir,
|
|
368
|
+
inBackground(() => startupEscrowSweep(client, dirs.configDir, identity?.agentId));
|
|
290
369
|
return {
|
|
291
370
|
client,
|
|
292
|
-
profileName,
|
|
371
|
+
profileName: opts.profile ?? DEFAULT_PROFILE,
|
|
372
|
+
dir,
|
|
293
373
|
dirs,
|
|
294
|
-
|
|
295
|
-
token
|
|
374
|
+
tokenFor
|
|
296
375
|
};
|
|
297
376
|
}
|
|
298
377
|
function withClient(program, fn, precheck) {
|
|
@@ -310,16 +389,25 @@ function withClient(program, fn, precheck) {
|
|
|
310
389
|
const flagged = namedActor(commandOf(args), gOpts);
|
|
311
390
|
const apiUrl = resolveApiUrl();
|
|
312
391
|
const defaultHeaders = {};
|
|
313
|
-
const { client, profileName,
|
|
392
|
+
const { client, profileName, dir, dirs } = await createClient({
|
|
393
|
+
apiUrl,
|
|
394
|
+
profile: gOpts.profile,
|
|
395
|
+
defaultHeaders
|
|
396
|
+
});
|
|
314
397
|
const { named, agents, actingAgent } = actorLadder(flagged, client, defaultHeaders);
|
|
315
398
|
if (named !== void 0) await actingAgent();
|
|
399
|
+
let admin;
|
|
316
400
|
await fn({
|
|
317
401
|
client,
|
|
318
402
|
gOpts,
|
|
319
403
|
profileName,
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
404
|
+
dir,
|
|
405
|
+
dirs,
|
|
406
|
+
custody: () => custodyOf(dirs),
|
|
407
|
+
get auth() {
|
|
408
|
+
admin ??= resolveAuth(dirs, gOpts.profile);
|
|
409
|
+
return admin;
|
|
410
|
+
},
|
|
323
411
|
apiUrl,
|
|
324
412
|
extraHeaders: defaultHeaders,
|
|
325
413
|
agents,
|
|
@@ -582,19 +670,31 @@ function toAgentRow(a, opts = {}) {
|
|
|
582
670
|
}
|
|
583
671
|
//#endregion
|
|
584
672
|
//#region src/prompt.ts
|
|
585
|
-
|
|
586
|
-
|
|
673
|
+
const NON_TTY_ANSWER_TIMEOUT_MS = 3e4;
|
|
674
|
+
/** Read one line; undefined when stdin ends without an answer. */
|
|
675
|
+
function readAnswer(question) {
|
|
676
|
+
if (process.stdin.isTTY !== true) process.stderr.write("stdin is not a terminal: this question needs a person to answer it.\n");
|
|
587
677
|
const rl = readline.createInterface({
|
|
588
678
|
input: process.stdin,
|
|
589
679
|
output: process.stdout
|
|
590
680
|
});
|
|
591
681
|
return new Promise((resolve) => {
|
|
682
|
+
const timer = process.stdin.isTTY === true ? void 0 : setTimeout(() => rl.close(), NON_TTY_ANSWER_TIMEOUT_MS);
|
|
683
|
+
rl.once("close", () => {
|
|
684
|
+
clearTimeout(timer);
|
|
685
|
+
resolve(void 0);
|
|
686
|
+
});
|
|
592
687
|
rl.question(question, (answer) => {
|
|
593
|
-
|
|
688
|
+
clearTimeout(timer);
|
|
594
689
|
resolve(answer.trim());
|
|
690
|
+
rl.close();
|
|
595
691
|
});
|
|
596
692
|
});
|
|
597
693
|
}
|
|
694
|
+
/** Prompt for a plain-text value on stdout/stdin. Empty when stdin ends without an answer. */
|
|
695
|
+
async function promptText(question) {
|
|
696
|
+
return await readAnswer(question) ?? "";
|
|
697
|
+
}
|
|
598
698
|
/** Prompt for a secret value with hidden input (raw mode). */
|
|
599
699
|
async function promptPassword(question) {
|
|
600
700
|
return new Promise((resolve) => {
|
|
@@ -622,7 +722,12 @@ async function promptPassword(question) {
|
|
|
622
722
|
}
|
|
623
723
|
/** Prompt for yes/no confirmation (defaults to No). Returns true if user types y/Y. */
|
|
624
724
|
async function promptConfirm(question) {
|
|
625
|
-
|
|
725
|
+
const answer = await readAnswer(`${question} [y/N] `);
|
|
726
|
+
if (answer === void 0) {
|
|
727
|
+
process.stderr.write("\nno answer (not a terminal): nothing was changed. This needs a person at a terminal — ask the user to run the command in their own terminal, outside this session.\n");
|
|
728
|
+
return false;
|
|
729
|
+
}
|
|
730
|
+
return answer.toLowerCase() === "y";
|
|
626
731
|
}
|
|
627
732
|
//#endregion
|
|
628
733
|
//#region src/commands/agent-exposure-create.ts
|
|
@@ -651,7 +756,7 @@ function announceExposure(agent, asked) {
|
|
|
651
756
|
//#endregion
|
|
652
757
|
//#region src/commands/agent-create.ts
|
|
653
758
|
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,
|
|
759
|
+
agent.command("create").description("Create a new agent").option("--name <name>", "Agent name").option("--[no-]human-oversight", "Require human oversight (default: true)").option("--unlisted", "Mark agent as unlisted (not in public directory)").option("--exposure <preset>", EXPOSURE_OPTION_HELP).action(withClient(program, async ({ client, gOpts, custody }, opts) => {
|
|
655
760
|
const exposure = exposurePreset(opts.exposure);
|
|
656
761
|
let name = opts.name;
|
|
657
762
|
if (!name) {
|
|
@@ -663,10 +768,9 @@ function registerAgentCreate(agent, program) {
|
|
|
663
768
|
}
|
|
664
769
|
}
|
|
665
770
|
const profile = gOpts.profile ?? DEFAULT_PROFILE;
|
|
666
|
-
const
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
}, profile, {
|
|
771
|
+
const dirs = custody();
|
|
772
|
+
const { configDir } = dirs;
|
|
773
|
+
const data = await performAgentCreation(client, dirs, profile, {
|
|
670
774
|
name,
|
|
671
775
|
humanOversight: opts.humanOversight,
|
|
672
776
|
unlisted: opts.unlisted,
|
|
@@ -847,7 +951,7 @@ function announceHandleCompletion(spelling) {
|
|
|
847
951
|
* and still sends — this is a display of key agreement, not an access control.
|
|
848
952
|
*/
|
|
849
953
|
function registerAgentVerify(program, agent) {
|
|
850
|
-
agent.command("verify").description("Compare a peer's verification words with this agent's, and record the result").argument("<peer>", "Peer handle (e.g. bot@acme) or agent UUID").addOption(actorOption("which agent is acting, and whose words these are (name, handle, or agent ID)")).option("--yes", "Record the confirmation without prompting").action(withClient(program, async ({ client, gOpts, configDir, apiUrl, actingAgent, agents }, peer, opts) => {
|
|
954
|
+
agent.command("verify").description("Compare a peer's verification words with this agent's, and record the result").argument("<peer>", "Peer handle (e.g. bot@acme) or agent UUID").addOption(actorOption("which agent is acting, and whose words these are (name, handle, or agent ID)")).option("--yes", "Record the confirmation without prompting").action(withClient(program, async ({ client, gOpts, dirs: { configDir }, apiUrl, actingAgent, agents }, peer, opts) => {
|
|
851
955
|
const ownId = await actingAgent();
|
|
852
956
|
const own = (await agents()).find((a) => a.id === ownId);
|
|
853
957
|
announceHandleCompletion(peer);
|
|
@@ -907,7 +1011,9 @@ function registerAgent(program) {
|
|
|
907
1011
|
const agent = program.command("agent").description("Agent management");
|
|
908
1012
|
agent.command("list").description("List all agents").option("--include-revoked", "Include revoked agents").action(withClient(program, async ({ client, gOpts }, opts) => {
|
|
909
1013
|
const params = opts.includeRevoked ? { include_revoked: true } : void 0;
|
|
910
|
-
const
|
|
1014
|
+
const agentOnly = agentOnlyFromEnv();
|
|
1015
|
+
const data = await orgRosterClient(client, agentOnly).get("/agents", params);
|
|
1016
|
+
if (agentOnly) process.stderr.write(`${AGENT_ONLY_LIST_NOTICE}\n`);
|
|
911
1017
|
if (gOpts.json) printJson(data);
|
|
912
1018
|
else printTable(data.items.map((a) => toAgentRow(a, { includeRevoked: opts.includeRevoked })));
|
|
913
1019
|
}));
|
|
@@ -957,6 +1063,62 @@ function registerAgent(program) {
|
|
|
957
1063
|
registerAgentExposure(agent, program);
|
|
958
1064
|
}
|
|
959
1065
|
//#endregion
|
|
1066
|
+
//#region src/commands/whoami-fields.ts
|
|
1067
|
+
/** `dir.path` is where the config dir's files are read; `dir.shown` is the dir as found, which is what the table shows. */
|
|
1068
|
+
function dirFacts(dirs, dir, profile) {
|
|
1069
|
+
const copy = checkIdentityCopy(dirs.configDir);
|
|
1070
|
+
const refused = dir.refused ?? [];
|
|
1071
|
+
return {
|
|
1072
|
+
config_dir: dir.path,
|
|
1073
|
+
config_dir_shown: dir.shown,
|
|
1074
|
+
source: dir.source,
|
|
1075
|
+
tiers: describeTiers(dirs, profile),
|
|
1076
|
+
...dirs.agentOnly === true && { agent_only: true },
|
|
1077
|
+
...copy !== void 0 && { copied_from: copy.copiedFrom },
|
|
1078
|
+
...refused.length > 0 && { refused_project_dirs: [...refused] }
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
const AGENT_ONLY_MODE = `agent-only (${AGENT_ONLY_ENV}): this process signs as its own agent and never as the org`;
|
|
1082
|
+
/** Where the dir is and why it was chosen: the rows even a dir with no identity can print. */
|
|
1083
|
+
function locationRows(facts) {
|
|
1084
|
+
return [
|
|
1085
|
+
{
|
|
1086
|
+
Field: "Config dir",
|
|
1087
|
+
Value: facts.config_dir_shown
|
|
1088
|
+
},
|
|
1089
|
+
...facts.config_dir === facts.config_dir_shown ? [] : [{
|
|
1090
|
+
Field: "Stored at",
|
|
1091
|
+
Value: facts.config_dir
|
|
1092
|
+
}],
|
|
1093
|
+
{
|
|
1094
|
+
Field: "Source",
|
|
1095
|
+
Value: facts.source
|
|
1096
|
+
},
|
|
1097
|
+
...(facts.refused_project_dirs ?? []).map(({ dir, reason, copied_from, also_bound_at }) => ({
|
|
1098
|
+
Field: "Skipped",
|
|
1099
|
+
Value: `${dir} (${reason}${copied_from === void 0 ? "" : `; copied from ${copied_from}`}${also_bound_at === void 0 ? "" : `; also bound at ${also_bound_at}`})`
|
|
1100
|
+
}))
|
|
1101
|
+
];
|
|
1102
|
+
}
|
|
1103
|
+
/** The rows `whoami` and `identity show` both print for {@link DirFacts}. */
|
|
1104
|
+
function dirFactRows(facts) {
|
|
1105
|
+
return [
|
|
1106
|
+
...locationRows(facts),
|
|
1107
|
+
...facts.agent_only === true ? [{
|
|
1108
|
+
Field: "Mode",
|
|
1109
|
+
Value: AGENT_ONLY_MODE
|
|
1110
|
+
}] : [],
|
|
1111
|
+
{
|
|
1112
|
+
Field: "Admin",
|
|
1113
|
+
Value: facts.tiers.admin ?? "-"
|
|
1114
|
+
},
|
|
1115
|
+
...facts.copied_from === void 0 ? [] : [{
|
|
1116
|
+
Field: "Copied from",
|
|
1117
|
+
Value: facts.copied_from
|
|
1118
|
+
}]
|
|
1119
|
+
];
|
|
1120
|
+
}
|
|
1121
|
+
//#endregion
|
|
960
1122
|
//#region src/commands/whoami.ts
|
|
961
1123
|
/**
|
|
962
1124
|
* Where this agent's keys are. The server serves the keys of every agent it
|
|
@@ -970,108 +1132,115 @@ function keysLabel(hasLocal, serverKnows) {
|
|
|
970
1132
|
return hasLocal ? "local + server" : "server only";
|
|
971
1133
|
}
|
|
972
1134
|
function registerWhoami(program) {
|
|
973
|
-
program.command("whoami").description("Show current identity and status").action(async () => {
|
|
974
|
-
const gOpts = program.opts();
|
|
1135
|
+
program.command("whoami").description("Show current identity and status").action(withErrorHandler(program, async (gOpts) => {
|
|
975
1136
|
const profile = gOpts.profile ?? DEFAULT_PROFILE;
|
|
976
|
-
const
|
|
1137
|
+
const dir = resolveConfigDir();
|
|
1138
|
+
const dirs = authDirsOf(dir);
|
|
977
1139
|
const apiUrl = resolveApiUrl();
|
|
978
|
-
const
|
|
979
|
-
|
|
980
|
-
|
|
1140
|
+
const facts = dirFacts(dirs, dir, gOpts.profile);
|
|
1141
|
+
const defaultHeaders = {};
|
|
1142
|
+
const { client, identity } = buildTierClient({
|
|
1143
|
+
dirs,
|
|
1144
|
+
apiUrl,
|
|
1145
|
+
profile: gOpts.profile,
|
|
1146
|
+
defaultHeaders
|
|
1147
|
+
});
|
|
1148
|
+
if (identity === void 0) {
|
|
1149
|
+
if (gOpts.json) printJson({
|
|
1150
|
+
logged_in: false,
|
|
1151
|
+
config_dir: facts.config_dir,
|
|
1152
|
+
config_dir_shown: facts.config_dir_shown,
|
|
1153
|
+
source: facts.source,
|
|
1154
|
+
...facts.refused_project_dirs !== void 0 && { refused_project_dirs: facts.refused_project_dirs }
|
|
1155
|
+
});
|
|
981
1156
|
else printTable([{
|
|
982
1157
|
Field: "Status",
|
|
983
1158
|
Value: "not logged in"
|
|
984
|
-
}]);
|
|
1159
|
+
}, ...locationRows(facts)]);
|
|
985
1160
|
return;
|
|
986
1161
|
}
|
|
1162
|
+
const { agents, actingAgent } = actorLadder(namedActor(void 0, gOpts), client, defaultHeaders);
|
|
1163
|
+
const { org, agents: orgAgents } = await client.get("/whoami");
|
|
1164
|
+
const roster = await agents();
|
|
1165
|
+
let agentId;
|
|
987
1166
|
try {
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
const { org } = await client.get("/whoami");
|
|
999
|
-
let agentHandle;
|
|
1000
|
-
let agentId;
|
|
1001
|
-
let keys;
|
|
1167
|
+
agentId = await actingAgent();
|
|
1168
|
+
} catch {}
|
|
1169
|
+
let agentHandle;
|
|
1170
|
+
let keys;
|
|
1171
|
+
let humanOversight;
|
|
1172
|
+
if (agentId !== void 0) {
|
|
1173
|
+
agentHandle = roster.find((a) => a.id === agentId)?.handle ?? void 0;
|
|
1174
|
+
humanOversight = orgAgents.find((a) => a.id === agentId)?.human_oversight;
|
|
1175
|
+
const hasLocal = agentKeysExist(dirs.configDir, agentId);
|
|
1176
|
+
let serverKnows;
|
|
1002
1177
|
try {
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1178
|
+
await client.get(`/agents/${agentId}/keys`);
|
|
1179
|
+
serverKnows = true;
|
|
1180
|
+
} catch (err) {
|
|
1181
|
+
if (err instanceof RineApiError && err.status === 404) serverKnows = false;
|
|
1182
|
+
}
|
|
1183
|
+
keys = keysLabel(hasLocal, serverKnows);
|
|
1184
|
+
}
|
|
1185
|
+
const principal = principalString(identity.signer.principal);
|
|
1186
|
+
if (gOpts.json) printJson({
|
|
1187
|
+
profile,
|
|
1188
|
+
api: apiUrl,
|
|
1189
|
+
principal,
|
|
1190
|
+
...facts,
|
|
1191
|
+
org: {
|
|
1192
|
+
name: org.name,
|
|
1193
|
+
slug: org.slug
|
|
1194
|
+
},
|
|
1195
|
+
trust_tier: org.trust_tier,
|
|
1196
|
+
...agentId ? {
|
|
1197
|
+
agent: agentHandle ?? null,
|
|
1198
|
+
agent_id: agentId,
|
|
1199
|
+
keys,
|
|
1200
|
+
...humanOversight !== void 0 && { human_oversight: humanOversight }
|
|
1201
|
+
} : {}
|
|
1202
|
+
});
|
|
1203
|
+
else {
|
|
1204
|
+
const rows = [
|
|
1205
|
+
{
|
|
1206
|
+
Field: "Profile",
|
|
1207
|
+
Value: profile
|
|
1023
1208
|
},
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
},
|
|
1041
|
-
{
|
|
1042
|
-
Field: "Principal",
|
|
1043
|
-
Value: principal
|
|
1044
|
-
},
|
|
1045
|
-
{
|
|
1046
|
-
Field: "Org",
|
|
1047
|
-
Value: `${org.name} (${org.slug})`
|
|
1048
|
-
},
|
|
1049
|
-
{
|
|
1050
|
-
Field: "Trust Tier",
|
|
1051
|
-
Value: String(org.trust_tier)
|
|
1052
|
-
}
|
|
1053
|
-
];
|
|
1054
|
-
if (agentId) {
|
|
1055
|
-
rows.push({
|
|
1056
|
-
Field: "Agent",
|
|
1057
|
-
Value: agentHandle ?? "-"
|
|
1058
|
-
});
|
|
1059
|
-
rows.push({
|
|
1060
|
-
Field: "Agent ID",
|
|
1061
|
-
Value: agentId
|
|
1062
|
-
});
|
|
1063
|
-
rows.push({
|
|
1064
|
-
Field: "Keys",
|
|
1065
|
-
Value: keys ?? "none"
|
|
1066
|
-
});
|
|
1209
|
+
{
|
|
1210
|
+
Field: "API",
|
|
1211
|
+
Value: apiUrl
|
|
1212
|
+
},
|
|
1213
|
+
{
|
|
1214
|
+
Field: "Principal",
|
|
1215
|
+
Value: principal
|
|
1216
|
+
},
|
|
1217
|
+
...dirFactRows(facts),
|
|
1218
|
+
{
|
|
1219
|
+
Field: "Org",
|
|
1220
|
+
Value: `${org.name} (${org.slug})`
|
|
1221
|
+
},
|
|
1222
|
+
{
|
|
1223
|
+
Field: "Trust Tier",
|
|
1224
|
+
Value: String(org.trust_tier)
|
|
1067
1225
|
}
|
|
1068
|
-
|
|
1226
|
+
];
|
|
1227
|
+
if (agentId) {
|
|
1228
|
+
rows.push({
|
|
1229
|
+
Field: "Agent",
|
|
1230
|
+
Value: agentHandle ?? "-"
|
|
1231
|
+
});
|
|
1232
|
+
rows.push({
|
|
1233
|
+
Field: "Agent ID",
|
|
1234
|
+
Value: agentId
|
|
1235
|
+
});
|
|
1236
|
+
rows.push({
|
|
1237
|
+
Field: "Keys",
|
|
1238
|
+
Value: keys ?? "none"
|
|
1239
|
+
});
|
|
1069
1240
|
}
|
|
1070
|
-
|
|
1071
|
-
printError(formatError(err));
|
|
1072
|
-
process.exitCode = 1;
|
|
1241
|
+
printTable(rows);
|
|
1073
1242
|
}
|
|
1074
|
-
});
|
|
1243
|
+
}));
|
|
1075
1244
|
}
|
|
1076
1245
|
//#endregion
|
|
1077
1246
|
//#region src/commands/auth.ts
|
|
@@ -1144,6 +1313,35 @@ async function showOrgStatus(client, gOpts) {
|
|
|
1144
1313
|
]);
|
|
1145
1314
|
}
|
|
1146
1315
|
//#endregion
|
|
1316
|
+
//#region src/commands/catalog.ts
|
|
1317
|
+
/**
|
|
1318
|
+
* The operation catalog as a plugin or script reads it: which tier each command signs as and
|
|
1319
|
+
* what it risks. Hidden, and offline: it needs no identity and makes no request.
|
|
1320
|
+
*/
|
|
1321
|
+
function registerCatalog(program) {
|
|
1322
|
+
program.command("catalog", { hidden: true }).description("List every operation with its tier and risk").action(withErrorHandler(program, (gOpts) => {
|
|
1323
|
+
const operations = listOperations().map((op) => ({
|
|
1324
|
+
id: op.id,
|
|
1325
|
+
tier: op.tier,
|
|
1326
|
+
risk: op.risk,
|
|
1327
|
+
cli: op.cli ?? null,
|
|
1328
|
+
cli_aliases: op.cliAliases ?? [],
|
|
1329
|
+
mcp: op.mcp ?? null
|
|
1330
|
+
}));
|
|
1331
|
+
if (gOpts.json) {
|
|
1332
|
+
printJson({ operations });
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
printTable(operations.map((op) => ({
|
|
1336
|
+
Id: op.id,
|
|
1337
|
+
Tier: op.tier,
|
|
1338
|
+
Risk: op.risk,
|
|
1339
|
+
Command: op.cli ?? "-",
|
|
1340
|
+
Tool: op.mcp ?? "-"
|
|
1341
|
+
})));
|
|
1342
|
+
}));
|
|
1343
|
+
}
|
|
1344
|
+
//#endregion
|
|
1147
1345
|
//#region src/commands/group-eviction.ts
|
|
1148
1346
|
const EVICTED_EXPLAINED = "A Remove commit evicted this agent's leaf from the group's ratchet tree, so it can no longer send to the group, read anything committed since, or admit anyone. Ask an admin to invite you again — returning takes a fresh invitation and a new Welcome, not the keys this agent still holds.";
|
|
1149
1347
|
/**
|
|
@@ -1272,7 +1470,7 @@ async function withEvictionPointerIfHeld(ctx, err) {
|
|
|
1272
1470
|
if (!(err instanceof Error)) return err;
|
|
1273
1471
|
if (!err.message.startsWith(GROUP_NOT_FOUND_LEAD)) return err;
|
|
1274
1472
|
try {
|
|
1275
|
-
if (!holdsAnyMlsState(ctx.configDir, await ctx.actingAgent())) return err;
|
|
1473
|
+
if (!holdsAnyMlsState(ctx.dirs.configDir, await ctx.actingAgent())) return err;
|
|
1276
1474
|
} catch {
|
|
1277
1475
|
return err;
|
|
1278
1476
|
}
|
|
@@ -1364,7 +1562,7 @@ async function groupTarget(ctx, ref) {
|
|
|
1364
1562
|
} catch (err) {
|
|
1365
1563
|
if (!UUID_RE.test(ref)) throw await withEvictionPointerIfHeld(ctx, err);
|
|
1366
1564
|
const actingAgent = () => ctx.actingAgent();
|
|
1367
|
-
throw err instanceof RineApiError ? await asGroupAccessError(ctx.configDir, ref, err, actingAgent) : await asEvictionRefusal(ctx.configDir, ref, err, actingAgent);
|
|
1565
|
+
throw err instanceof RineApiError ? await asGroupAccessError(ctx.dirs.configDir, ref, err, actingAgent) : await asEvictionRefusal(ctx.dirs.configDir, ref, err, actingAgent);
|
|
1368
1566
|
}
|
|
1369
1567
|
}
|
|
1370
1568
|
/**
|
|
@@ -1606,7 +1804,7 @@ function collectHeader(v, acc) {
|
|
|
1606
1804
|
return acc;
|
|
1607
1805
|
}
|
|
1608
1806
|
function registerFulfill(program) {
|
|
1609
|
-
program.command("fulfill").description("Settle a received x402_payment via the facilitator and reply with an x402_receipt. The payment is bound to the ONE payee-issued x402_payment_required quote it references (the signed quoteMessageId) and reconciled against THAT quote (payTo/amount/asset/network/scheme) — the payer's echoed terms are never trusted. A payment carrying no/forged/cross-conversation quote reference REFUSES to settle (fail closed) unless explicit expected terms (--pay-to/--expect-amount/--expect-asset/--expect-network) authorise an out-of-band quote.").argument("<message-id>", "ID of the received rine.v1.x402_payment").addOption(actorOption("which agent is acting, as payee (name, handle, or agent ID)")).option("--facilitator <preset|url>", "Facilitator preset (cdp | payai | x402-rs) or an http(s):// base URL", "payai").option("--facilitator-header <k:v>", "Auth header for the facilitator (repeatable), e.g. 'Authorization: Bearer …'", collectHeader, []).option("--verify-path <path>", "Override the facilitator /verify path").option("--settle-path <path>", "Override the facilitator /settle path").option("--pay-to <address>", "Out-of-band quote: expected payee wallet (0x). Requires --expect-amount/--expect-asset/--expect-network; overrides the referenced quote (no quoteMessageId needed)").option("--expect-amount <major>", "Out-of-band quote: expected amount in MAJOR units (e.g. 1.00). Overpayment is accepted, underpayment refused").option("--expect-asset <address>", "Out-of-band quote: expected token contract (0x)").option("--expect-network <caip2>", "Out-of-band quote: expected CAIP-2 network (e.g. eip155:8453)").option("--no-marker", "Omit the cleartext status marker (fully sealed)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, messageId, opts) => {
|
|
1807
|
+
program.command("fulfill").description("Settle a received x402_payment via the facilitator and reply with an x402_receipt. The payment is bound to the ONE payee-issued x402_payment_required quote it references (the signed quoteMessageId) and reconciled against THAT quote (payTo/amount/asset/network/scheme) — the payer's echoed terms are never trusted. A payment carrying no/forged/cross-conversation quote reference REFUSES to settle (fail closed) unless explicit expected terms (--pay-to/--expect-amount/--expect-asset/--expect-network) authorise an out-of-band quote.").argument("<message-id>", "ID of the received rine.v1.x402_payment").addOption(actorOption("which agent is acting, as payee (name, handle, or agent ID)")).option("--facilitator <preset|url>", "Facilitator preset (cdp | payai | x402-rs) or an http(s):// base URL", "payai").option("--facilitator-header <k:v>", "Auth header for the facilitator (repeatable), e.g. 'Authorization: Bearer …'", collectHeader, []).option("--verify-path <path>", "Override the facilitator /verify path").option("--settle-path <path>", "Override the facilitator /settle path").option("--pay-to <address>", "Out-of-band quote: expected payee wallet (0x). Requires --expect-amount/--expect-asset/--expect-network; overrides the referenced quote (no quoteMessageId needed)").option("--expect-amount <major>", "Out-of-band quote: expected amount in MAJOR units (e.g. 1.00). Overpayment is accepted, underpayment refused").option("--expect-asset <address>", "Out-of-band quote: expected token contract (0x)").option("--expect-network <caip2>", "Out-of-band quote: expected CAIP-2 network (e.g. eip155:8453)").option("--no-marker", "Omit the cleartext status marker (fully sealed)").action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent }, messageId, opts) => {
|
|
1610
1808
|
const payeeAgentId = await actingAgent();
|
|
1611
1809
|
const message = await client.get(`/messages/${messageId}`);
|
|
1612
1810
|
if (message.type !== X402_MESSAGE_TYPE.PAYMENT) {
|
|
@@ -2205,7 +2403,7 @@ async function foundMlsState(ctx, group) {
|
|
|
2205
2403
|
if (group.enrollment_policy === "open") return null;
|
|
2206
2404
|
try {
|
|
2207
2405
|
const actingAgentId = await ctx.actingAgent();
|
|
2208
|
-
return await initMlsGroup(ctx.configDir, actingAgentId, group.id, ctx.client, { [ACTING_AGENT_HEADER]: actingAgentId });
|
|
2406
|
+
return await initMlsGroup(ctx.dirs.configDir, actingAgentId, group.id, ctx.client, { [ACTING_AGENT_HEADER]: actingAgentId });
|
|
2209
2407
|
} catch (err) {
|
|
2210
2408
|
warnMls("MLS init failed (group still created)", err, group.id, ctx.gOpts.json);
|
|
2211
2409
|
return null;
|
|
@@ -2290,7 +2488,7 @@ function registerGroupCreate(program, group) {
|
|
|
2290
2488
|
async function evictionState(ctx, group) {
|
|
2291
2489
|
if (!groupIsMls(group)) return null;
|
|
2292
2490
|
try {
|
|
2293
|
-
return isEvictedFrom(ctx.configDir, await ctx.actingAgent(), group.id);
|
|
2491
|
+
return isEvictedFrom(ctx.dirs.configDir, await ctx.actingAgent(), group.id);
|
|
2294
2492
|
} catch {
|
|
2295
2493
|
return null;
|
|
2296
2494
|
}
|
|
@@ -2398,6 +2596,140 @@ async function admitToMls(client, configDir, adminId, groupId, mlsGroupId, membe
|
|
|
2398
2596
|
}
|
|
2399
2597
|
}
|
|
2400
2598
|
//#endregion
|
|
2599
|
+
//#region src/commands/group-requests.ts
|
|
2600
|
+
/** An open group has no ratchet tree, so there is no admission to resume in it. */
|
|
2601
|
+
const NOT_AN_MLS_GROUP = "This group runs on Sender Keys, not MLS, so it has no ratchet tree to seat anyone in. Open-enrolment groups are sender-key groups by design: MLS would hand an unattested joiner a cryptographic seat, so the server keeps open enrolment off the MLS path. There is nothing to resume here.";
|
|
2602
|
+
function printAdmission(result, json) {
|
|
2603
|
+
if (json) {
|
|
2604
|
+
printJson(result);
|
|
2605
|
+
return;
|
|
2606
|
+
}
|
|
2607
|
+
printText(`Seated ${result.added} of ${result.outcomes.length} in ${result.commits} commit(s), now at epoch ${result.epoch}.`);
|
|
2608
|
+
printTable(admissionOutcomeRows(result));
|
|
2609
|
+
printReclamation(result.reclamation);
|
|
2610
|
+
}
|
|
2611
|
+
/**
|
|
2612
|
+
* What `--reclaim` did, or the stated reason it did nothing.
|
|
2613
|
+
*
|
|
2614
|
+
* The sentence is `describeMlsReclamation`'s, from rine-core — the TypeScript
|
|
2615
|
+
* stack's one copy, sentence for sentence identical to the Python twin. This
|
|
2616
|
+
* function composed its own three branches until the MCP server, eve and mastra
|
|
2617
|
+
* needed the same three, which is the drift a single shared sentence stops: four
|
|
2618
|
+
* surfaces reporting the same reclamation in four wordings.
|
|
2619
|
+
*/
|
|
2620
|
+
function printReclamation(reclamation) {
|
|
2621
|
+
const said = describeMlsReclamation(reclamation);
|
|
2622
|
+
if (said) printText(said);
|
|
2623
|
+
}
|
|
2624
|
+
/**
|
|
2625
|
+
* What the vote did to the request, beside the wire token.
|
|
2626
|
+
*
|
|
2627
|
+
* There are **four** answers and not three. `invited` is the one no client
|
|
2628
|
+
* anticipated: the electorate approved a nomination whose subject has not
|
|
2629
|
+
* answered yet, so the row resolves to a spendable invitation rather than to a
|
|
2630
|
+
* seat — a carried vote seats only an agent that consented. Reported
|
|
2631
|
+
* by name here because a fall-through would render a carried vote as an unknown
|
|
2632
|
+
* status, and because it is the one outcome where nobody is added to the
|
|
2633
|
+
* ratchet tree despite the bar being met.
|
|
2634
|
+
*
|
|
2635
|
+
* An unrecognised status renders as itself and gets no sentence — a guess about
|
|
2636
|
+
* a token this build predates would be worse than the token.
|
|
2637
|
+
*/
|
|
2638
|
+
function voteOutcomeSentence(status) {
|
|
2639
|
+
switch (status) {
|
|
2640
|
+
case "approved": return "the request carried and that agent is now a member";
|
|
2641
|
+
case "denied": return "the request was refused";
|
|
2642
|
+
case "pending": return "neither bar is reached yet, so the request stands";
|
|
2643
|
+
case "invited": return "the request carried, and because its subject was nominated and has not answered yet it is now an invitation for them to accept";
|
|
2644
|
+
default: return "";
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
function registerGroupRequests(program, group) {
|
|
2648
|
+
group.command("requests").description("List what this group still owes an answer on").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is asking, and whose vote the rows report")).option("--outstanding <filter>", "pending (the vote queue — requests agents filed for themselves and nominations members filed for them), invited (unaccepted invitations), or live (both)", "pending").action(withClient(program, async (ctx, ref, opts) => {
|
|
2649
|
+
const { client, gOpts } = ctx;
|
|
2650
|
+
const { id: groupId } = await groupTarget(ctx, ref);
|
|
2651
|
+
const data = await client.get(`/groups/${groupId}/requests`, { outstanding: opts.outstanding });
|
|
2652
|
+
if (gOpts.json) printJson(data);
|
|
2653
|
+
else printTable(data.items.map(requestRow));
|
|
2654
|
+
}));
|
|
2655
|
+
group.command("invites").description("List group invitations and nominations addressed to you. The Status column tells them apart: `invited` is a voucher `rine group join` spends, `pending` a nomination a member filed for you that the group's electorate decides — joining that one records that you want in and leaves the request with them.").addOption(actorOption("whose invitations and nominations to list")).action(withClient(program, async ({ client, gOpts, extraHeaders }) => {
|
|
2656
|
+
const items = await listMyInvites(client, extraHeaders);
|
|
2657
|
+
if (gOpts.json) printJson(items);
|
|
2658
|
+
else printTable(items.map(inviteRow));
|
|
2659
|
+
}));
|
|
2660
|
+
group.command("resume-admission").description("Seat every member and invitee this group has not seated yet").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is acting, and seats the others")).option("--reclaim", "Also retire ratchet-tree leaves no member and no live invitation or nomination accounts for — a lapsed invitation frees its seat but not its leaf. Costs one O(N) commit per leaf, billed to every member. Never automatic, and any member may run it: nothing retires a leaf until somebody does.").action(withClient(program, async (ctx, ref, opts) => {
|
|
2661
|
+
const { id: groupId, row: target } = await groupTarget(ctx, ref);
|
|
2662
|
+
if (target.enrollment_policy === "open") {
|
|
2663
|
+
printError(NOT_AN_MLS_GROUP);
|
|
2664
|
+
process.exitCode = 2;
|
|
2665
|
+
return;
|
|
2666
|
+
}
|
|
2667
|
+
const actingId = await ctx.actingAgent();
|
|
2668
|
+
const headers = { [ACTING_AGENT_HEADER]: actingId };
|
|
2669
|
+
try {
|
|
2670
|
+
printAdmission(groupIsMls(target) ? await resumeMlsGroupAdmission(ctx.dirs.configDir, actingId, groupId, ctx.client, headers, { reclaim: opts.reclaim }) : await initMlsGroup(ctx.dirs.configDir, actingId, groupId, ctx.client, headers), ctx.gOpts.json);
|
|
2671
|
+
} catch (err) {
|
|
2672
|
+
printError(mlsFailureText(err, groupId));
|
|
2673
|
+
process.exitCode = 1;
|
|
2674
|
+
}
|
|
2675
|
+
}));
|
|
2676
|
+
group.command("vote").description(`Vote on a join request. ${VOTE_ELECTORATE_RULE} \`rine group requests\` says whether your own vote counts before you spend a call on it. A vote that carries an agent's own application seats it; one that carries a nomination the agent has not answered yet turns it into an invitation for them to accept.`).argument("<group-ref>", GROUP_REFERENCE_HELP).argument("<request-id>", "Join request ID").addOption(actorOption("which agent casts the vote")).requiredOption("--vote <vote>", "Vote: approve or deny").action(withClient(program, async (ctx, ref, requestId, opts) => {
|
|
2677
|
+
if (opts.vote !== "approve" && opts.vote !== "deny") {
|
|
2678
|
+
printError("--vote must be 'approve' or 'deny'");
|
|
2679
|
+
process.exitCode = 2;
|
|
2680
|
+
return;
|
|
2681
|
+
}
|
|
2682
|
+
const { id: groupId } = await groupTarget(ctx, ref);
|
|
2683
|
+
let applicantId;
|
|
2684
|
+
if (opts.vote === "approve") applicantId = (await ctx.client.get(`/groups/${groupId}/requests`)).items.find((r) => r.id === requestId)?.agent_id;
|
|
2685
|
+
const data = await ctx.client.post(`/groups/${groupId}/requests/${requestId}/vote`, { vote: opts.vote });
|
|
2686
|
+
const admission = data.status === "approved" && applicantId ? await seatApplicant(ctx, groupId, applicantId) : null;
|
|
2687
|
+
if (ctx.gOpts.json) printJson(withAdmission(data, admission));
|
|
2688
|
+
else {
|
|
2689
|
+
const said = voteOutcomeSentence(data.status);
|
|
2690
|
+
printText(`Vote recorded. Request status: ${data.status}` + (said ? ` — ${said}` : ""));
|
|
2691
|
+
}
|
|
2692
|
+
}));
|
|
2693
|
+
}
|
|
2694
|
+
/**
|
|
2695
|
+
* Best-effort MLS add for a newly approved applicant; never fails the vote. The
|
|
2696
|
+
* failure comes back as data so `--json` can report it, as `group invite` does.
|
|
2697
|
+
*/
|
|
2698
|
+
async function seatApplicant(ctx, groupId, applicantId) {
|
|
2699
|
+
try {
|
|
2700
|
+
const target = await ctx.client.get(`/groups/${groupId}`);
|
|
2701
|
+
const actingId = await ctx.actingAgent();
|
|
2702
|
+
return await admitToMls(ctx.client, ctx.dirs.configDir, actingId, groupId, target.mls_group_id, [applicantId], ctx.gOpts.json);
|
|
2703
|
+
} catch (err) {
|
|
2704
|
+
return failedAdmission(err, groupId, ctx.gOpts.json);
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
//#endregion
|
|
2708
|
+
//#region src/commands/group-invite-head.ts
|
|
2709
|
+
/**
|
|
2710
|
+
* What one invite call did, in its own words.
|
|
2711
|
+
*
|
|
2712
|
+
* Read off the row the server wrote and the group's policy, because the two
|
|
2713
|
+
* together are the answer: a `closed` group's invite mints a voucher
|
|
2714
|
+
* (`invited`), a `majority` or `unanimity` group's files a nomination
|
|
2715
|
+
* (`pending`) — or, when the nominator's own approval carried it at filing, the
|
|
2716
|
+
* voucher it resolved to (`invited`), or a refusal (`denied`) when a rule,
|
|
2717
|
+
* isolation or capacity check refused it in the same transaction — and an
|
|
2718
|
+
* `open` group's is a notification with no row at all, which answers `invited`
|
|
2719
|
+
* and carries no `id`.
|
|
2720
|
+
*
|
|
2721
|
+
* The missing `id` tells the open case apart, the only signal there is. The
|
|
2722
|
+
* carried-nomination sentence is said only where a nomination can carry, so a
|
|
2723
|
+
* closed group's ordinary voucher reads as it always has. Words are
|
|
2724
|
+
* `rine-core`'s, as the plural report's per-agent line is.
|
|
2725
|
+
*/
|
|
2726
|
+
function singularHead(row, policy) {
|
|
2727
|
+
if (row.status === "pending") return "Nomination filed — the group's electorate decides it";
|
|
2728
|
+
if (row.status === "denied") return `Not invited: ${voteOutcomeSentence("denied")}`;
|
|
2729
|
+
if (!row.id) return `Invited: ${groupAdmissionSkipSentence("not_applicable")}`;
|
|
2730
|
+
return inviteNominates(policy) ? `Invitation sent. ${CARRIED_NOMINATION_SENTENCE}` : "Invitation sent";
|
|
2731
|
+
}
|
|
2732
|
+
//#endregion
|
|
2401
2733
|
//#region src/commands/group-invite.ts
|
|
2402
2734
|
/**
|
|
2403
2735
|
* An invite that names nobody is refused before it costs anything.
|
|
@@ -2468,7 +2800,7 @@ async function notifyInvitees(client, configDir, inviterId, group, inviteeIds, m
|
|
|
2468
2800
|
* The agents this call actually reached, whichever shape answered.
|
|
2469
2801
|
*
|
|
2470
2802
|
* A singular invite gets a bare row back and no report, so the one agent it
|
|
2471
|
-
* named is the answer
|
|
2803
|
+
* named is the answer, unless its row came back `denied`. A plural one is `admittedAgentIds` — `rine-core`'s, not
|
|
2472
2804
|
* a second copy of the arithmetic — which counts `not_applicable` as reached
|
|
2473
2805
|
* because that is an open group's answer: it mints no voucher since it needs
|
|
2474
2806
|
* none, and those agents are still being told to come in.
|
|
@@ -2479,31 +2811,12 @@ async function notifyInvitees(client, configDir, inviterId, group, inviteeIds, m
|
|
|
2479
2811
|
* electorate has not decided on. {@link afterInvite} is where that question is
|
|
2480
2812
|
* asked.
|
|
2481
2813
|
*/
|
|
2482
|
-
function reachedAgents(report, singular) {
|
|
2483
|
-
if (
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
/**
|
|
2487
|
-
* What one invite call did, in its own words.
|
|
2488
|
-
*
|
|
2489
|
-
* Read off the row the server wrote rather than off the group, because the row
|
|
2490
|
-
* is the answer: a `closed` group's invite mints a voucher (`invited`), a
|
|
2491
|
-
* `majority` or `unanimity` group's files a nomination (`pending`),
|
|
2492
|
-
* and an `open` group's is a notification with no row at all — which answers
|
|
2493
|
-
* `invited` and carries no `id`.
|
|
2494
|
-
*
|
|
2495
|
-
* That missing `id` is what tells the third case from the first, and it is the
|
|
2496
|
-
* only signal there is: the two answers carry the same status. An open group
|
|
2497
|
-
* mints nothing because it needs nothing, so the head says so and there is no
|
|
2498
|
-
* row to table underneath it — reported in `rine-core`'s words, the same
|
|
2499
|
-
* sentence the plural report's per-agent line carries.
|
|
2500
|
-
*/
|
|
2501
|
-
function singularHead(row) {
|
|
2502
|
-
if (row.status === "pending") return "Nomination filed — the group's electorate decides it";
|
|
2503
|
-
if (!row.id) return `Invited: ${groupAdmissionSkipSentence("not_applicable")}`;
|
|
2504
|
-
return "Invitation sent";
|
|
2814
|
+
function reachedAgents(data, report, singular) {
|
|
2815
|
+
if (report) return admittedAgentIds(report);
|
|
2816
|
+
const refused = data.status === "denied";
|
|
2817
|
+
return singular && !refused ? [singular] : [];
|
|
2505
2818
|
}
|
|
2506
|
-
function printInvited(data, report, admission, json) {
|
|
2819
|
+
function printInvited(data, report, admission, policy, json) {
|
|
2507
2820
|
if (json) {
|
|
2508
2821
|
printJson(withAdmission(data, admission));
|
|
2509
2822
|
return;
|
|
@@ -2514,7 +2827,7 @@ function printInvited(data, report, admission, json) {
|
|
|
2514
2827
|
printTable(report.entries.map(admissionRow));
|
|
2515
2828
|
} else {
|
|
2516
2829
|
const voucher = data;
|
|
2517
|
-
printText(singularHead(voucher));
|
|
2830
|
+
printText(singularHead(voucher, policy));
|
|
2518
2831
|
if (voucher.id) printTable([requestRow(voucher)]);
|
|
2519
2832
|
}
|
|
2520
2833
|
if (admissionRan(admission) && admission.outcomes.length > 0) {
|
|
@@ -2540,13 +2853,14 @@ function printInvited(data, report, admission, json) {
|
|
|
2540
2853
|
* only the manual reclamation pass able to retire the leaf afterwards — and
|
|
2541
2854
|
* that pass cannot reach it while the row is live. The vote seats the member,
|
|
2542
2855
|
* and seating is what grants the key: `group vote` posts the add on the approve
|
|
2543
|
-
* that carries, as the self-application path does.
|
|
2856
|
+
* that carries, as the self-application path does. A nomination that already
|
|
2857
|
+
* carried at filing is no different: no vote follows, so the nominee's leaf
|
|
2858
|
+
* comes from its own join (an external join), and nothing here mints one. The
|
|
2544
2859
|
* notice still goes out, because a nominee that never learns of the nomination
|
|
2545
2860
|
* can never consent to it.
|
|
2546
2861
|
*
|
|
2547
|
-
* The GROUP's policy decides this and not the response
|
|
2548
|
-
*
|
|
2549
|
-
* singular and the plural call in one place.
|
|
2862
|
+
* The GROUP's policy decides this and not the response: the server's own question,
|
|
2863
|
+
* answered for the singular and the plural call in one place.
|
|
2550
2864
|
*/
|
|
2551
2865
|
async function afterInvite(ctx, groupId, reached, message) {
|
|
2552
2866
|
let group;
|
|
@@ -2558,13 +2872,13 @@ async function afterInvite(ctx, groupId, reached, message) {
|
|
|
2558
2872
|
if (!ctx.gOpts.json) printText(`${UNRESOLVED_INVITER} ${err instanceof Error ? err.message : String(err)}`);
|
|
2559
2873
|
return null;
|
|
2560
2874
|
}
|
|
2561
|
-
const admission = inviteNominates(group.enrollment_policy) ? null : await admitToMls(ctx.client, ctx.configDir, inviterId, groupId, group.mls_group_id, reached, ctx.gOpts.json);
|
|
2562
|
-
await notifyInvitees(ctx.client, ctx.configDir, inviterId, group, reached, message, ctx.gOpts.json);
|
|
2875
|
+
const admission = inviteNominates(group.enrollment_policy) ? null : await admitToMls(ctx.client, ctx.dirs.configDir, inviterId, groupId, group.mls_group_id, reached, ctx.gOpts.json);
|
|
2876
|
+
await notifyInvitees(ctx.client, ctx.dirs.configDir, inviterId, group, reached, message, ctx.gOpts.json);
|
|
2563
2877
|
return admission;
|
|
2564
2878
|
}
|
|
2565
2879
|
function registerGroupInvite(program, group) {
|
|
2566
|
-
group.command("invite").description("Invite one or more agents to the group. On a majority or unanimity group this nominates rather than invites: it files a join request the group's electorate decides, counted as your own approval, and nobody is added to the ratchet tree until the vote carries. On a closed group an admin's invite is a voucher the agent redeems with `rine group join`. `rine group create --member` is the exception — a founding roster invites under every policy, because the creator is the only member and a vote would auto-approve each row.").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is acting, and invites")).option("--invitee <id>", "Agent ID or handle to invite or nominate (repeatable — naming two or more reaches them in one call and reports each)", collect, []).option("--message <msg>", "Message to carry with the invitation or nomination").action(withClient(program, async (ctx, ref, opts) => {
|
|
2567
|
-
const { id: groupId } = await groupTarget(ctx, ref);
|
|
2880
|
+
group.command("invite").description("Invite one or more agents to the group. On a majority or unanimity group this nominates rather than invites: it files a join request the group's electorate decides, counted as your own approval, and nobody is added to the ratchet tree until the vote carries; where your approval alone carries it (you are the only active member) it answers an invitation the agent accepts, with no vote left. On a closed group an admin's invite is a voucher the agent redeems with `rine group join`. `rine group create --member` is the exception — a founding roster invites under every policy, because the creator is the only member and a vote would auto-approve each row.").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is acting, and invites")).option("--invitee <id>", "Agent ID or handle to invite or nominate (repeatable — naming two or more reaches them in one call and reports each)", collect, []).option("--message <msg>", "Message to carry with the invitation or nomination").action(withClient(program, async (ctx, ref, opts) => {
|
|
2881
|
+
const { id: groupId, row: groupRow } = await groupTarget(ctx, ref);
|
|
2568
2882
|
const agentIds = dedupeIds(await Promise.all(opts.invitee.map((a) => {
|
|
2569
2883
|
announceHandleCompletion(a);
|
|
2570
2884
|
return resolveToUuid(ctx.apiUrl, a);
|
|
@@ -2574,7 +2888,7 @@ function registerGroupInvite(program, group) {
|
|
|
2574
2888
|
if (opts.message) body.message = opts.message;
|
|
2575
2889
|
const data = await ctx.client.post(`/groups/${groupId}/invite`, body);
|
|
2576
2890
|
const report = single ? null : data;
|
|
2577
|
-
printInvited(data, report, await afterInvite(ctx, groupId, reachedAgents(report, single), opts.message), ctx.gOpts.json);
|
|
2891
|
+
printInvited(data, report, await afterInvite(ctx, groupId, reachedAgents(data, report, single), opts.message), groupRow.enrollment_policy, ctx.gOpts.json);
|
|
2578
2892
|
}, invitesSomebody));
|
|
2579
2893
|
}
|
|
2580
2894
|
//#endregion
|
|
@@ -2602,7 +2916,7 @@ function registerGroupInvite(program, group) {
|
|
|
2602
2916
|
* {@link establishMlsMembership}, shared by every TypeScript surface.
|
|
2603
2917
|
*/
|
|
2604
2918
|
async function establishJoinedMls(ctx, groupId, agentId) {
|
|
2605
|
-
reportFailedSetup(await establishMlsMembership(ctx.configDir, agentId, groupId, ctx.client, { [ACTING_AGENT_HEADER]: agentId }), warnFailedSetup(ctx, groupId));
|
|
2919
|
+
reportFailedSetup(await establishMlsMembership(ctx.dirs.configDir, agentId, groupId, ctx.client, { [ACTING_AGENT_HEADER]: agentId }), warnFailedSetup(ctx, groupId));
|
|
2606
2920
|
}
|
|
2607
2921
|
const STEP_LABEL = {
|
|
2608
2922
|
[MlsEstablishStep.GroupRead]: "MLS group read failed",
|
|
@@ -2627,7 +2941,7 @@ async function joinAndEstablish(ctx, groupId, body) {
|
|
|
2627
2941
|
data = await ctx.client.post(`/groups/${groupId}/join`, body);
|
|
2628
2942
|
} catch (err) {
|
|
2629
2943
|
const seated = await seatedMemberAfterConflict(err, {
|
|
2630
|
-
configDir: ctx.configDir,
|
|
2944
|
+
configDir: ctx.dirs.configDir,
|
|
2631
2945
|
groupId,
|
|
2632
2946
|
client: ctx.client,
|
|
2633
2947
|
actingAgent: ctx.actingAgent
|
|
@@ -2699,7 +3013,7 @@ async function readGroup(ctx, groupId) {
|
|
|
2699
3013
|
/** Who holds this agent's sender key for the group; null when it holds none. */
|
|
2700
3014
|
async function coverageFor(ctx, groupId, memberIds) {
|
|
2701
3015
|
try {
|
|
2702
|
-
return senderKeyCoverage(ctx.configDir, await ctx.actingAgent(), groupId, memberIds);
|
|
3016
|
+
return senderKeyCoverage(ctx.dirs.configDir, await ctx.actingAgent(), groupId, memberIds);
|
|
2703
3017
|
} catch {
|
|
2704
3018
|
return null;
|
|
2705
3019
|
}
|
|
@@ -2711,7 +3025,7 @@ function registerGroupMembership(program, group) {
|
|
|
2711
3025
|
try {
|
|
2712
3026
|
items = await fetchGroupMembers(ctx.client, groupId);
|
|
2713
3027
|
} catch (err) {
|
|
2714
|
-
throw await asGroupAccessError(ctx.configDir, groupId, err, () => ctx.actingAgent());
|
|
3028
|
+
throw await asGroupAccessError(ctx.dirs.configDir, groupId, err, () => ctx.actingAgent());
|
|
2715
3029
|
}
|
|
2716
3030
|
const coverage = await coverageFor(ctx, groupId, items.map((m) => m.agent_id));
|
|
2717
3031
|
const data = {
|
|
@@ -2747,9 +3061,9 @@ function registerGroupMembership(program, group) {
|
|
|
2747
3061
|
const groupId = UUID_RE.test(ref) ? ref : (await groupTarget(ctx, ref)).id;
|
|
2748
3062
|
const agentId = await ctx.actingAgent();
|
|
2749
3063
|
const left = await readGroup(ctx, groupId);
|
|
2750
|
-
const heldMlsState = loadMlsState(ctx.configDir, agentId, groupId) !== null;
|
|
2751
|
-
await deleteGroupMember(ctx.client, ctx.configDir, groupId, agentId, void 0, { [ACTING_AGENT_HEADER]: agentId });
|
|
2752
|
-
const wipe = retireLocalGroupState(ctx.configDir, agentId, groupId);
|
|
3064
|
+
const heldMlsState = loadMlsState(ctx.dirs.configDir, agentId, groupId) !== null;
|
|
3065
|
+
await deleteGroupMember(ctx.client, ctx.dirs.configDir, groupId, agentId, void 0, { [ACTING_AGENT_HEADER]: agentId });
|
|
3066
|
+
const wipe = retireLocalGroupState(ctx.dirs.configDir, agentId, groupId);
|
|
2753
3067
|
printMutationOk("Left group", ctx.gOpts.json);
|
|
2754
3068
|
if (!ctx.gOpts.json) {
|
|
2755
3069
|
if (wipe.error) printText(wipe.error);
|
|
@@ -2767,122 +3081,13 @@ function registerGroupMembership(program, group) {
|
|
|
2767
3081
|
groupId = seated.id;
|
|
2768
3082
|
target = seated.row;
|
|
2769
3083
|
}
|
|
2770
|
-
const removal = await deleteGroupMember(ctx.client, ctx.configDir, groupId, resolved, () => ctx.actingAgent(), ctx.extraHeaders);
|
|
3084
|
+
const removal = await deleteGroupMember(ctx.client, ctx.dirs.configDir, groupId, resolved, () => ctx.actingAgent(), ctx.extraHeaders);
|
|
2771
3085
|
printMutationOk("Member removed", ctx.gOpts.json);
|
|
2772
3086
|
const evicted = evictionMessage(target, removal);
|
|
2773
3087
|
if (!ctx.gOpts.json && evicted) printText(evicted);
|
|
2774
3088
|
}));
|
|
2775
3089
|
}
|
|
2776
3090
|
//#endregion
|
|
2777
|
-
//#region src/commands/group-requests.ts
|
|
2778
|
-
/** An open group has no ratchet tree, so there is no admission to resume in it. */
|
|
2779
|
-
const NOT_AN_MLS_GROUP = "This group runs on Sender Keys, not MLS, so it has no ratchet tree to seat anyone in. Open-enrolment groups are sender-key groups by design: MLS would hand an unattested joiner a cryptographic seat, so the server keeps open enrolment off the MLS path. There is nothing to resume here.";
|
|
2780
|
-
function printAdmission(result, json) {
|
|
2781
|
-
if (json) {
|
|
2782
|
-
printJson(result);
|
|
2783
|
-
return;
|
|
2784
|
-
}
|
|
2785
|
-
printText(`Seated ${result.added} of ${result.outcomes.length} in ${result.commits} commit(s), now at epoch ${result.epoch}.`);
|
|
2786
|
-
printTable(admissionOutcomeRows(result));
|
|
2787
|
-
printReclamation(result.reclamation);
|
|
2788
|
-
}
|
|
2789
|
-
/**
|
|
2790
|
-
* What `--reclaim` did, or the stated reason it did nothing.
|
|
2791
|
-
*
|
|
2792
|
-
* The sentence is `describeMlsReclamation`'s, from rine-core — the TypeScript
|
|
2793
|
-
* stack's one copy, sentence for sentence identical to the Python twin. This
|
|
2794
|
-
* function composed its own three branches until the MCP server, eve and mastra
|
|
2795
|
-
* needed the same three, which is the drift a single shared sentence stops: four
|
|
2796
|
-
* surfaces reporting the same reclamation in four wordings.
|
|
2797
|
-
*/
|
|
2798
|
-
function printReclamation(reclamation) {
|
|
2799
|
-
const said = describeMlsReclamation(reclamation);
|
|
2800
|
-
if (said) printText(said);
|
|
2801
|
-
}
|
|
2802
|
-
/**
|
|
2803
|
-
* What the vote did to the request, beside the wire token.
|
|
2804
|
-
*
|
|
2805
|
-
* There are **four** answers and not three. `invited` is the one no client
|
|
2806
|
-
* anticipated: the electorate approved a nomination whose subject has not
|
|
2807
|
-
* answered yet, so the row resolves to a spendable invitation rather than to a
|
|
2808
|
-
* seat — a carried vote seats only an agent that consented. Reported
|
|
2809
|
-
* by name here because a fall-through would render a carried vote as an unknown
|
|
2810
|
-
* status, and because it is the one outcome where nobody is added to the
|
|
2811
|
-
* ratchet tree despite the bar being met.
|
|
2812
|
-
*
|
|
2813
|
-
* An unrecognised status renders as itself and gets no sentence — a guess about
|
|
2814
|
-
* a token this build predates would be worse than the token.
|
|
2815
|
-
*/
|
|
2816
|
-
function voteOutcomeSentence(status) {
|
|
2817
|
-
switch (status) {
|
|
2818
|
-
case "approved": return "the request carried and that agent is now a member";
|
|
2819
|
-
case "denied": return "the request was refused";
|
|
2820
|
-
case "pending": return "neither bar is reached yet, so the request stands";
|
|
2821
|
-
case "invited": return "the request carried, and because its subject was nominated and has not answered yet it is now an invitation for them to accept";
|
|
2822
|
-
default: return "";
|
|
2823
|
-
}
|
|
2824
|
-
}
|
|
2825
|
-
function registerGroupRequests(program, group) {
|
|
2826
|
-
group.command("requests").description("List what this group still owes an answer on").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is asking, and whose vote the rows report")).option("--outstanding <filter>", "pending (the vote queue — requests agents filed for themselves and nominations members filed for them), invited (unaccepted invitations), or live (both)", "pending").action(withClient(program, async (ctx, ref, opts) => {
|
|
2827
|
-
const { client, gOpts } = ctx;
|
|
2828
|
-
const { id: groupId } = await groupTarget(ctx, ref);
|
|
2829
|
-
const data = await client.get(`/groups/${groupId}/requests`, { outstanding: opts.outstanding });
|
|
2830
|
-
if (gOpts.json) printJson(data);
|
|
2831
|
-
else printTable(data.items.map(requestRow));
|
|
2832
|
-
}));
|
|
2833
|
-
group.command("invites").description("List group invitations and nominations addressed to you. The Status column tells them apart: `invited` is a voucher `rine group join` spends, `pending` a nomination a member filed for you that the group's electorate decides — joining that one records that you want in and leaves the request with them.").addOption(actorOption("whose invitations and nominations to list")).action(withClient(program, async ({ client, gOpts, extraHeaders }) => {
|
|
2834
|
-
const items = await listMyInvites(client, extraHeaders);
|
|
2835
|
-
if (gOpts.json) printJson(items);
|
|
2836
|
-
else printTable(items.map(inviteRow));
|
|
2837
|
-
}));
|
|
2838
|
-
group.command("resume-admission").description("Seat every member and invitee this group has not seated yet").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent is acting, and seats the others")).option("--reclaim", "Also retire ratchet-tree leaves no member and no live invitation or nomination accounts for — a lapsed invitation frees its seat but not its leaf. Costs one O(N) commit per leaf, billed to every member. Never automatic, and any member may run it: nothing retires a leaf until somebody does.").action(withClient(program, async (ctx, ref, opts) => {
|
|
2839
|
-
const { id: groupId, row: target } = await groupTarget(ctx, ref);
|
|
2840
|
-
if (target.enrollment_policy === "open") {
|
|
2841
|
-
printError(NOT_AN_MLS_GROUP);
|
|
2842
|
-
process.exitCode = 2;
|
|
2843
|
-
return;
|
|
2844
|
-
}
|
|
2845
|
-
const actingId = await ctx.actingAgent();
|
|
2846
|
-
const headers = { [ACTING_AGENT_HEADER]: actingId };
|
|
2847
|
-
try {
|
|
2848
|
-
printAdmission(groupIsMls(target) ? await resumeMlsGroupAdmission(ctx.configDir, actingId, groupId, ctx.client, headers, { reclaim: opts.reclaim }) : await initMlsGroup(ctx.configDir, actingId, groupId, ctx.client, headers), ctx.gOpts.json);
|
|
2849
|
-
} catch (err) {
|
|
2850
|
-
printError(mlsFailureText(err, groupId));
|
|
2851
|
-
process.exitCode = 1;
|
|
2852
|
-
}
|
|
2853
|
-
}));
|
|
2854
|
-
group.command("vote").description(`Vote on a join request. ${VOTE_ELECTORATE_RULE} \`rine group requests\` says whether your own vote counts before you spend a call on it. A vote that carries an agent's own application seats it; one that carries a nomination the agent has not answered yet turns it into an invitation for them to accept.`).argument("<group-ref>", GROUP_REFERENCE_HELP).argument("<request-id>", "Join request ID").addOption(actorOption("which agent casts the vote")).requiredOption("--vote <vote>", "Vote: approve or deny").action(withClient(program, async (ctx, ref, requestId, opts) => {
|
|
2855
|
-
if (opts.vote !== "approve" && opts.vote !== "deny") {
|
|
2856
|
-
printError("--vote must be 'approve' or 'deny'");
|
|
2857
|
-
process.exitCode = 2;
|
|
2858
|
-
return;
|
|
2859
|
-
}
|
|
2860
|
-
const { id: groupId } = await groupTarget(ctx, ref);
|
|
2861
|
-
let applicantId;
|
|
2862
|
-
if (opts.vote === "approve") applicantId = (await ctx.client.get(`/groups/${groupId}/requests`)).items.find((r) => r.id === requestId)?.agent_id;
|
|
2863
|
-
const data = await ctx.client.post(`/groups/${groupId}/requests/${requestId}/vote`, { vote: opts.vote });
|
|
2864
|
-
const admission = data.status === "approved" && applicantId ? await seatApplicant(ctx, groupId, applicantId) : null;
|
|
2865
|
-
if (ctx.gOpts.json) printJson(withAdmission(data, admission));
|
|
2866
|
-
else {
|
|
2867
|
-
const said = voteOutcomeSentence(data.status);
|
|
2868
|
-
printText(`Vote recorded. Request status: ${data.status}` + (said ? ` — ${said}` : ""));
|
|
2869
|
-
}
|
|
2870
|
-
}));
|
|
2871
|
-
}
|
|
2872
|
-
/**
|
|
2873
|
-
* Best-effort MLS add for a newly approved applicant; never fails the vote. The
|
|
2874
|
-
* failure comes back as data so `--json` can report it, as `group invite` does.
|
|
2875
|
-
*/
|
|
2876
|
-
async function seatApplicant(ctx, groupId, applicantId) {
|
|
2877
|
-
try {
|
|
2878
|
-
const target = await ctx.client.get(`/groups/${groupId}`);
|
|
2879
|
-
const actingId = await ctx.actingAgent();
|
|
2880
|
-
return await admitToMls(ctx.client, ctx.configDir, actingId, groupId, target.mls_group_id, [applicantId], ctx.gOpts.json);
|
|
2881
|
-
} catch (err) {
|
|
2882
|
-
return failedAdmission(err, groupId, ctx.gOpts.json);
|
|
2883
|
-
}
|
|
2884
|
-
}
|
|
2885
|
-
//#endregion
|
|
2886
3091
|
//#region src/commands/group-sync.ts
|
|
2887
3092
|
function registerGroupSync(program, group) {
|
|
2888
3093
|
group.command("sync").description("Catch this agent's group encryption state up, and say what it cost").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption("which agent's group state is caught up")).action(withClient(program, async (ctx, ref) => {
|
|
@@ -2895,7 +3100,7 @@ function registerGroupSync(program, group) {
|
|
|
2895
3100
|
}
|
|
2896
3101
|
const actingId = await ctx.actingAgent();
|
|
2897
3102
|
try {
|
|
2898
|
-
const result = await recoverGroup(ctx.configDir, actingId, target, ctx.client, { [ACTING_AGENT_HEADER]: actingId }, CLI_UNFOUNDED_REPAIR);
|
|
3103
|
+
const result = await recoverGroup(ctx.dirs.configDir, actingId, target, ctx.client, { [ACTING_AGENT_HEADER]: actingId }, CLI_UNFOUNDED_REPAIR);
|
|
2899
3104
|
if (ctx.gOpts.json) printJson(result);
|
|
2900
3105
|
else printText(describeMlsRecovery(label, result));
|
|
2901
3106
|
} catch (err) {
|
|
@@ -2926,6 +3131,19 @@ function registerGroup(program) {
|
|
|
2926
3131
|
registerGroupSync(program, group);
|
|
2927
3132
|
}
|
|
2928
3133
|
//#endregion
|
|
3134
|
+
//#region src/commands/hook-name.ts
|
|
3135
|
+
/**
|
|
3136
|
+
* Print `Invalid hook name '<name>': <problem>.` and set exit code 2 when
|
|
3137
|
+
* `problem` is a reason (the result of `hookNameError` or `hookNamePatternError`).
|
|
3138
|
+
* Returns true when the command must stop.
|
|
3139
|
+
*/
|
|
3140
|
+
function refuseHookName(name, problem) {
|
|
3141
|
+
if (problem === null) return false;
|
|
3142
|
+
printError(invalidHookNameMessage(name, problem));
|
|
3143
|
+
process.exitCode = 2;
|
|
3144
|
+
return true;
|
|
3145
|
+
}
|
|
3146
|
+
//#endregion
|
|
2929
3147
|
//#region src/commands/hook.ts
|
|
2930
3148
|
const SIGNATURE_HEADER = "X-Hub-Signature-256";
|
|
2931
3149
|
const CONTENT_TYPE = "application/json";
|
|
@@ -2943,13 +3161,8 @@ function resolveTier(raw) {
|
|
|
2943
3161
|
}
|
|
2944
3162
|
function registerHook(program) {
|
|
2945
3163
|
const hook = program.command("hook").description("Manage inbound webhook funnel hooks");
|
|
2946
|
-
hook.command("create").description("Allocate a funnel hook
|
|
2947
|
-
|
|
2948
|
-
if (nameError) {
|
|
2949
|
-
printError(`Invalid hook name '${opts.name}': ${nameError}.`);
|
|
2950
|
-
process.exitCode = 2;
|
|
2951
|
-
return;
|
|
2952
|
-
}
|
|
3164
|
+
hook.command("create").description("Allocate a funnel hook: a public HTTPS URL whose webhook calls reach this agent through rine relay (prints the URL, the secret once and GitHub setup steps)").addOption(actorOption()).option("--name <name>", "Hook name (default: default)", "default").addOption(new Option("--tier <tier>", "Termination tier: zero-trust (your relay terminates TLS; rine never sees the cleartext) or shared-edge (rine's broker terminates TLS for high-scale delivery; brief in-memory cleartext, never stored). Default: by trust tier.").choices(Object.keys(TIER_CLI_TO_WIRE))).action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent }, opts) => {
|
|
3165
|
+
if (refuseHookName(opts.name, hookNameError(opts.name))) return;
|
|
2953
3166
|
let tier;
|
|
2954
3167
|
try {
|
|
2955
3168
|
tier = resolveTier(opts.tier);
|
|
@@ -2962,8 +3175,7 @@ function registerHook(program) {
|
|
|
2962
3175
|
printCreated(created, secret, gOpts.json);
|
|
2963
3176
|
}));
|
|
2964
3177
|
hook.command("list").description("List your agent's funnel hooks").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, actingAgent }) => {
|
|
2965
|
-
const
|
|
2966
|
-
const data = await client.get(`/agents/${agentId}/funnel/hooks`, {});
|
|
3178
|
+
const data = await listHooks(client, await actingAgent());
|
|
2967
3179
|
if (gOpts.json) printJson(data);
|
|
2968
3180
|
else printTable(data.items.map((h) => ({
|
|
2969
3181
|
Name: h.hook_name,
|
|
@@ -2973,13 +3185,14 @@ function registerHook(program) {
|
|
|
2973
3185
|
Created: h.created_at
|
|
2974
3186
|
})));
|
|
2975
3187
|
}));
|
|
2976
|
-
hook.command("delete").description("Delete a funnel hook and purge its local secret").addOption(actorOption()).requiredOption("--name <name>", "Hook name to delete").option("--yes", "Skip confirmation prompt").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, opts) => {
|
|
3188
|
+
hook.command("delete").description("Delete a funnel hook and purge its local secret").addOption(actorOption()).requiredOption("--name <name>", "Hook name to delete").option("--yes", "Skip confirmation prompt").action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent }, opts) => {
|
|
3189
|
+
if (refuseHookName(opts.name, hookNamePatternError(opts.name))) return;
|
|
2977
3190
|
const agentId = await actingAgent();
|
|
2978
3191
|
if (!opts.yes && !gOpts.json) {
|
|
2979
3192
|
if (!await promptConfirm(`Delete funnel hook '${opts.name}'?`)) return;
|
|
2980
3193
|
}
|
|
2981
3194
|
try {
|
|
2982
|
-
await client
|
|
3195
|
+
await deleteHook(client, configDir, agentId, opts.name);
|
|
2983
3196
|
} catch (err) {
|
|
2984
3197
|
if (opts.yes && err instanceof RineApiError && err.status === 404) {
|
|
2985
3198
|
deleteHookSecret(configDir, agentId, opts.name);
|
|
@@ -2988,7 +3201,6 @@ function registerHook(program) {
|
|
|
2988
3201
|
}
|
|
2989
3202
|
throw err;
|
|
2990
3203
|
}
|
|
2991
|
-
deleteHookSecret(configDir, agentId, opts.name);
|
|
2992
3204
|
printMutationOk("Funnel hook deleted", gOpts.json);
|
|
2993
3205
|
}));
|
|
2994
3206
|
}
|
|
@@ -3045,6 +3257,892 @@ function printCreated(created, secret, json) {
|
|
|
3045
3257
|
if (created.termination === "shared_edge") console.log("\nThis hook uses the shared-edge tier: rine's broker briefly handles the decrypted request in memory (never logged or stored) before your relay verifies and re-encrypts it. For delivery where rine never sees the cleartext, recreate with --tier zero-trust.");
|
|
3046
3258
|
}
|
|
3047
3259
|
//#endregion
|
|
3260
|
+
//#region src/fs-entry.ts
|
|
3261
|
+
/** What is at `path` itself (a link is not followed), or undefined when nothing is. */
|
|
3262
|
+
function entryAt(path) {
|
|
3263
|
+
return fs$1.lstatSync(path, { throwIfNoEntry: false });
|
|
3264
|
+
}
|
|
3265
|
+
/** Where the link `link` leads, or undefined when it leads nowhere (dangling, looping, or through a non-folder). */
|
|
3266
|
+
function linkTarget(link) {
|
|
3267
|
+
try {
|
|
3268
|
+
return fs$1.realpathSync(link);
|
|
3269
|
+
} catch (error) {
|
|
3270
|
+
if (leadsNowhere(error)) return void 0;
|
|
3271
|
+
throw error;
|
|
3272
|
+
}
|
|
3273
|
+
}
|
|
3274
|
+
//#endregion
|
|
3275
|
+
//#region src/git-repository.ts
|
|
3276
|
+
/** The longest `.git`, `gitdir` or `commondir` file read: each names one path. */
|
|
3277
|
+
const MAX_GIT_FILE_BYTES = 4096;
|
|
3278
|
+
const OPEN_FLAGS = fs$1.constants.O_NOFOLLOW | fs$1.constants.O_NONBLOCK;
|
|
3279
|
+
/**
|
|
3280
|
+
* Open `path` without following a link or blocking on a FIFO; anything but a
|
|
3281
|
+
* regular file this user owns, with no second name, throws.
|
|
3282
|
+
*/
|
|
3283
|
+
function openOwnedFile(path, flags, mode) {
|
|
3284
|
+
const fd = fs$1.openSync(path, flags | OPEN_FLAGS, mode);
|
|
3285
|
+
const stat = fs$1.fstatSync(fd);
|
|
3286
|
+
if (stat.isFile() && ownedByUs(stat) && stat.nlink === 1) return fd;
|
|
3287
|
+
fs$1.closeSync(fd);
|
|
3288
|
+
throw new Error(`${path} is not a plain file of yours`);
|
|
3289
|
+
}
|
|
3290
|
+
/** A small git pointer file's text. */
|
|
3291
|
+
function readPointer(path) {
|
|
3292
|
+
const fd = openOwnedFile(path, fs$1.constants.O_RDONLY);
|
|
3293
|
+
try {
|
|
3294
|
+
if (fs$1.fstatSync(fd).size > MAX_GIT_FILE_BYTES) throw new Error(`${path} is too large`);
|
|
3295
|
+
return fs$1.readFileSync(fd, "utf8").trim();
|
|
3296
|
+
} finally {
|
|
3297
|
+
fs$1.closeSync(fd);
|
|
3298
|
+
}
|
|
3299
|
+
}
|
|
3300
|
+
/** `path` with every symlink resolved; undefined when nothing (readable) is there. */
|
|
3301
|
+
function realOrUndefined(path) {
|
|
3302
|
+
try {
|
|
3303
|
+
return fs$1.realpathSync(path);
|
|
3304
|
+
} catch {
|
|
3305
|
+
return;
|
|
3306
|
+
}
|
|
3307
|
+
}
|
|
3308
|
+
/** Whether `path` is what `isKind` asks and this user's; false when nothing (readable) is there. */
|
|
3309
|
+
function ownedEntry(path, isKind) {
|
|
3310
|
+
try {
|
|
3311
|
+
const stat = fs$1.statSync(path);
|
|
3312
|
+
return isKind(stat) && ownedByUs(stat);
|
|
3313
|
+
} catch {
|
|
3314
|
+
return false;
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
/**
|
|
3318
|
+
* git's own test of a git dir (`is_git_directory`): a `HEAD` file in `gitDir`
|
|
3319
|
+
* and `objects/` and `refs/` in its common dir `common`, all this user's.
|
|
3320
|
+
*/
|
|
3321
|
+
function passesGitTest(gitDir, common) {
|
|
3322
|
+
return ownedEntry(gitDir, (s) => s.isDirectory()) && ownedEntry(join(gitDir, "HEAD"), (s) => s.isFile()) && ownedEntry(join(common, "objects"), (s) => s.isDirectory()) && ownedEntry(join(common, "refs"), (s) => s.isDirectory());
|
|
3323
|
+
}
|
|
3324
|
+
/** The git dir a `.git` file's `gitdir:` line names, realpath'd; undefined when it names none that exists. */
|
|
3325
|
+
function namedGitDir(dotGit) {
|
|
3326
|
+
const named = /^gitdir: (.+)$/.exec(readPointer(dotGit))?.[1];
|
|
3327
|
+
return named === void 0 ? void 0 : realOrUndefined(resolve(dirname(dotGit), named.trim()));
|
|
3328
|
+
}
|
|
3329
|
+
/**
|
|
3330
|
+
* The main repository's git dir for a linked worktree's git dir `gitDir`, with
|
|
3331
|
+
* git's checks: `gitDir` is `<common>/worktrees/<n>`, its `gitdir` names the
|
|
3332
|
+
* `.git` file back, its `commondir` names `<common>`, and `<common>` passes git's
|
|
3333
|
+
* own test. Anything else throws.
|
|
3334
|
+
*/
|
|
3335
|
+
function worktreeCommonDir(dotGit, gitDir) {
|
|
3336
|
+
const common = dirname(dirname(gitDir));
|
|
3337
|
+
const backlink = resolve(gitDir, readPointer(join(gitDir, "gitdir")));
|
|
3338
|
+
if (basename(dirname(gitDir)) !== "worktrees" || fs$1.realpathSync(backlink) !== fs$1.realpathSync(dotGit)) throw new Error(`${dotGit} is not a worktree its git dir names back`);
|
|
3339
|
+
if (fs$1.realpathSync(resolve(gitDir, readPointer(join(gitDir, "commondir")))) !== common || !passesGitTest(common, common)) throw new Error(`${gitDir} names a common dir that is not its repository's`);
|
|
3340
|
+
return common;
|
|
3341
|
+
}
|
|
3342
|
+
/** {@link commonDirOf} for the git dir `gitDir` the `.git` at `dotGit` resolved to. */
|
|
3343
|
+
function provenCommonDir(dotGit, stat, gitDir) {
|
|
3344
|
+
if (entryAt(join(gitDir, "commondir")) === void 0) return passesGitTest(gitDir, gitDir) ? gitDir : void 0;
|
|
3345
|
+
if (!stat.isFile() || !ownedEntry(join(gitDir, "HEAD"), (s) => s.isFile())) return void 0;
|
|
3346
|
+
return worktreeCommonDir(dotGit, gitDir);
|
|
3347
|
+
}
|
|
3348
|
+
/**
|
|
3349
|
+
* The git dir git reads `info/exclude` from for the `.git` at `dotGit`: a `.git`
|
|
3350
|
+
* dir, or the dir a `.git` symlink or `.git` file names, when it passes git's own
|
|
3351
|
+
* test (a linked worktree's through its common dir); undefined when git would
|
|
3352
|
+
* walk past it. A `.git` file git would not take throws, since git stops there.
|
|
3353
|
+
*/
|
|
3354
|
+
function commonDirOf(dotGit, stat) {
|
|
3355
|
+
let gitDir;
|
|
3356
|
+
if (stat.isFile()) gitDir = namedGitDir(dotGit);
|
|
3357
|
+
else if (stat.isDirectory() || stat.isSymbolicLink()) gitDir = realOrUndefined(dotGit);
|
|
3358
|
+
const common = gitDir === void 0 ? void 0 : provenCommonDir(dotGit, stat, gitDir);
|
|
3359
|
+
if (common === void 0 && stat.isFile()) throw new Error(`${dotGit} names no git dir git would take`);
|
|
3360
|
+
return common;
|
|
3361
|
+
}
|
|
3362
|
+
/**
|
|
3363
|
+
* The work tree root holding `dir` and the git dir git reads `info/exclude`
|
|
3364
|
+
* from; undefined outside a repository. A `.git` folder or link git would not
|
|
3365
|
+
* take is walked past, as git walks past it; a `.git` file it would not take
|
|
3366
|
+
* stops the walk with an error, as it stops git.
|
|
3367
|
+
*/
|
|
3368
|
+
function repositoryOf(dir) {
|
|
3369
|
+
for (let at = dir;; at = dirname(at)) {
|
|
3370
|
+
const dotGit = join(at, ".git");
|
|
3371
|
+
const stat = entryAt(dotGit);
|
|
3372
|
+
const common = stat === void 0 ? void 0 : commonDirOf(dotGit, stat);
|
|
3373
|
+
if (common !== void 0) return {
|
|
3374
|
+
root: at,
|
|
3375
|
+
common
|
|
3376
|
+
};
|
|
3377
|
+
if (dirname(at) === at) return void 0;
|
|
3378
|
+
}
|
|
3379
|
+
}
|
|
3380
|
+
//#endregion
|
|
3381
|
+
//#region src/git-exclude.ts
|
|
3382
|
+
/** What git reads as a pattern in an exclude line, escaped so the line names only the link. */
|
|
3383
|
+
const GLOB = /[\\[\]*?]/g;
|
|
3384
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
3385
|
+
/** The repository's `info/exclude`, opened for appending (made when missing), inside a real `info` dir of yours. */
|
|
3386
|
+
function openExclude(common) {
|
|
3387
|
+
const info = join(common, "info");
|
|
3388
|
+
const stat = entryAt(info);
|
|
3389
|
+
if (stat === void 0) fs$1.mkdirSync(info, { mode: 493 });
|
|
3390
|
+
else if (!stat.isDirectory() || !ownedByUs(stat)) throw new Error(`${info} is not a folder of yours`);
|
|
3391
|
+
const path = join(info, "exclude");
|
|
3392
|
+
const append = fs$1.constants.O_RDWR | fs$1.constants.O_APPEND;
|
|
3393
|
+
try {
|
|
3394
|
+
return openOwnedFile(path, append);
|
|
3395
|
+
} catch (error) {
|
|
3396
|
+
if (error.code !== "ENOENT") throw error;
|
|
3397
|
+
return openOwnedFile(path, append | fs$1.constants.O_CREAT | fs$1.constants.O_EXCL, 420);
|
|
3398
|
+
}
|
|
3399
|
+
}
|
|
3400
|
+
/**
|
|
3401
|
+
* List the project link `link` in its repository's `info/exclude`. Nothing is
|
|
3402
|
+
* done outside a repository; returns what to tell the user when it could not be
|
|
3403
|
+
* listed (the link stays either way).
|
|
3404
|
+
*/
|
|
3405
|
+
function excludeFromGit(link) {
|
|
3406
|
+
try {
|
|
3407
|
+
const project = fs$1.realpathSync(dirname(link));
|
|
3408
|
+
const repo = repositoryOf(project);
|
|
3409
|
+
if (repo === void 0) return void 0;
|
|
3410
|
+
const path = relative(repo.root, join(project, basename(link))).split(sep).join("/");
|
|
3411
|
+
if (CONTROL.test(path)) throw new Error("its path holds a control character");
|
|
3412
|
+
const line = `/${path.replace(GLOB, "\\$&")}`;
|
|
3413
|
+
const fd = openExclude(repo.common);
|
|
3414
|
+
try {
|
|
3415
|
+
const now = fs$1.readFileSync(fd, "utf8");
|
|
3416
|
+
if (now.split("\n").includes(line)) return void 0;
|
|
3417
|
+
fs$1.writeSync(fd, `${now === "" || now.endsWith("\n") ? "" : "\n"}${line}\n`);
|
|
3418
|
+
} finally {
|
|
3419
|
+
fs$1.closeSync(fd);
|
|
3420
|
+
}
|
|
3421
|
+
return;
|
|
3422
|
+
} catch (error) {
|
|
3423
|
+
return `rine: could not list ${link} in the repository's info/exclude (${formatError(error)}); add .rine to .gitignore so it is not committed.`;
|
|
3424
|
+
}
|
|
3425
|
+
}
|
|
3426
|
+
//#endregion
|
|
3427
|
+
//#region src/identity-files.ts
|
|
3428
|
+
/** Where the named identity lives in the store. */
|
|
3429
|
+
function storeEntryDir(name) {
|
|
3430
|
+
return join(identityStoreDir(), name);
|
|
3431
|
+
}
|
|
3432
|
+
/** The names in the identity store: its directories, sorted. A missing store is empty. */
|
|
3433
|
+
function storeNames() {
|
|
3434
|
+
try {
|
|
3435
|
+
return fs$1.readdirSync(identityStoreDir(), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
3436
|
+
} catch {
|
|
3437
|
+
return [];
|
|
3438
|
+
}
|
|
3439
|
+
}
|
|
3440
|
+
/** The project `.rine` to make: where the walk reads it, refused where the walk never would (your home directory). */
|
|
3441
|
+
function projectLinkToMake() {
|
|
3442
|
+
const refusal = projectLinkRefusal();
|
|
3443
|
+
if (refusal !== void 0) throw new Error(refusal);
|
|
3444
|
+
return projectLinkPath();
|
|
3445
|
+
}
|
|
3446
|
+
/**
|
|
3447
|
+
* Refuse, where a project link cannot be made (Windows grants no symbolic link by
|
|
3448
|
+
* default), naming how to use the store entry `name` instead. `what` is the act refused.
|
|
3449
|
+
*/
|
|
3450
|
+
function requireLinkSupport(what, name) {
|
|
3451
|
+
if (process.platform !== "win32") return;
|
|
3452
|
+
throw new Error(`${what} needs a symbolic link, which Windows does not grant by default. Point this shell at the identity instead: set RINE_CONFIG_DIR=%USERPROFILE%\\.config\\rine-ids\\${name}`);
|
|
3453
|
+
}
|
|
3454
|
+
/**
|
|
3455
|
+
* Make a free store entry for a project's own identity named `name`:
|
|
3456
|
+
* `project.<name>`, or `project.<name>-2`, `-3`, … when that is taken. Making it
|
|
3457
|
+
* is the claim, so two runs racing for one name each get their own entry.
|
|
3458
|
+
*/
|
|
3459
|
+
function claimProjectEntry(name) {
|
|
3460
|
+
for (let n = 1;; n++) {
|
|
3461
|
+
const entry = storeEntryDir(`${PROJECT_ENTRY_PREFIX}${n === 1 ? name : `${name}-${n}`}`);
|
|
3462
|
+
try {
|
|
3463
|
+
fs$1.mkdirSync(entry, { mode: 448 });
|
|
3464
|
+
return entry;
|
|
3465
|
+
} catch (error) {
|
|
3466
|
+
if (error.code !== "EEXIST") throw error;
|
|
3467
|
+
}
|
|
3468
|
+
}
|
|
3469
|
+
}
|
|
3470
|
+
/**
|
|
3471
|
+
* Link `link` to the store entry `store`, the way every project `.rine` is made,
|
|
3472
|
+
* and keep it out of git. Returns what to tell the user when it could not be
|
|
3473
|
+
* kept out of git.
|
|
3474
|
+
*/
|
|
3475
|
+
function linkProject(store, link) {
|
|
3476
|
+
fs$1.symlinkSync(store, link, "dir");
|
|
3477
|
+
return excludeFromGit(link);
|
|
3478
|
+
}
|
|
3479
|
+
/**
|
|
3480
|
+
* `identity.json` when it is readable; a missing or malformed file reads as none.
|
|
3481
|
+
* A project folder is read with `readProjectIdentityFile`, which refuses a linked file.
|
|
3482
|
+
*/
|
|
3483
|
+
function readIdentityLoosely(dir, read = readIdentityFile) {
|
|
3484
|
+
try {
|
|
3485
|
+
return read(dir);
|
|
3486
|
+
} catch (error) {
|
|
3487
|
+
if (error instanceof IdentityFileError) return void 0;
|
|
3488
|
+
throw error;
|
|
3489
|
+
}
|
|
3490
|
+
}
|
|
3491
|
+
/** The agent the dir's `default` profile names, from the profile file alone. */
|
|
3492
|
+
function defaultAgentId(dir) {
|
|
3493
|
+
return getProfile(dir, DEFAULT_PROFILE)?.agent_id ?? null;
|
|
3494
|
+
}
|
|
3495
|
+
/** Whether the dir holds a `profiles.json`, that is, an identity was ever set up in it. */
|
|
3496
|
+
function isRegistered(dir) {
|
|
3497
|
+
return fs$1.existsSync(join(dir, PROFILES_FILE));
|
|
3498
|
+
}
|
|
3499
|
+
/**
|
|
3500
|
+
* Mark an identity-store entry: its `identity.json` (the real path it is at, so a
|
|
3501
|
+
* copy elsewhere names where it came from) and a `.gitignore` that keeps every file
|
|
3502
|
+
* of it out of a repository should the store sit in one. An adopted identity keeps
|
|
3503
|
+
* its `createdAt`.
|
|
3504
|
+
*/
|
|
3505
|
+
function writeIdentityMarkers(dir, identity) {
|
|
3506
|
+
writeIdentityFile(dir, {
|
|
3507
|
+
home: fs$1.realpathSync(dir),
|
|
3508
|
+
created_at: identity.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
3509
|
+
...identity.handle ? { handle: identity.handle } : {},
|
|
3510
|
+
...identity.ownerDir !== void 0 && { owner_dir: identity.ownerDir }
|
|
3511
|
+
});
|
|
3512
|
+
writeIgnoreAll(dir);
|
|
3513
|
+
}
|
|
3514
|
+
/** A `.gitignore` in `dir` that keeps every file of it out of git. */
|
|
3515
|
+
function writeIgnoreAll(dir) {
|
|
3516
|
+
fs$1.writeFileSync(join(dir, ".gitignore"), "*\n", { mode: 384 });
|
|
3517
|
+
}
|
|
3518
|
+
//#endregion
|
|
3519
|
+
//#region src/commands/identity-adopt-move.ts
|
|
3520
|
+
/** A store name that is one plain path component. */
|
|
3521
|
+
const STORE_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
3522
|
+
const OWNER_RWX = 448;
|
|
3523
|
+
/** Why `path` (inside the folder `root`) cannot be carried into the store, or undefined when it can. */
|
|
3524
|
+
function unsafe(root, path, stat) {
|
|
3525
|
+
const at = relative(root, path) || ".";
|
|
3526
|
+
if (stat.isSymbolicLink()) return `${at} is a symbolic link`;
|
|
3527
|
+
if (!stat.isFile() && !stat.isDirectory()) return `${at} is not a plain file or folder`;
|
|
3528
|
+
if (!ownedByUs(stat)) return `${at} is owned by another user`;
|
|
3529
|
+
if (writableByOthers(stat)) return `${at} is writable by its group or by others`;
|
|
3530
|
+
if (stat.isDirectory() && (stat.mode & OWNER_RWX) !== OWNER_RWX) return `${at} is not fully accessible to you`;
|
|
3531
|
+
}
|
|
3532
|
+
/**
|
|
3533
|
+
* Copy the folder `root` to `to`, walking it with `lstat`: regular files keep
|
|
3534
|
+
* their modes, folders are 0700, and anything {@link unsafe} refuses throws.
|
|
3535
|
+
*/
|
|
3536
|
+
function copyChecked(root, from, to) {
|
|
3537
|
+
const stat = fs$1.lstatSync(from);
|
|
3538
|
+
const why = unsafe(root, from, stat);
|
|
3539
|
+
if (why !== void 0) throw new Error(`Refusing to adopt ${root}: ${why}. Only plain files and folders that are yours and not writable by others are adopted.`);
|
|
3540
|
+
if (stat.isFile()) {
|
|
3541
|
+
fs$1.copyFileSync(from, to, fs$1.constants.COPYFILE_EXCL);
|
|
3542
|
+
fs$1.chmodSync(to, stat.mode & 511);
|
|
3543
|
+
return;
|
|
3544
|
+
}
|
|
3545
|
+
fs$1.mkdirSync(to, { mode: 448 });
|
|
3546
|
+
for (const name of fs$1.readdirSync(from)) {
|
|
3547
|
+
if (from === root && rewrittenOnAdopt(from, name)) continue;
|
|
3548
|
+
copyChecked(root, join(from, name), join(to, name));
|
|
3549
|
+
}
|
|
3550
|
+
}
|
|
3551
|
+
/** A linked top-level `identity.json`: adopt reads it as none and writes a fresh one, so it is left behind. */
|
|
3552
|
+
function rewrittenOnAdopt(root, name) {
|
|
3553
|
+
return name === IDENTITY_FILE && entryAt(join(root, name))?.isSymbolicLink() === true;
|
|
3554
|
+
}
|
|
3555
|
+
/**
|
|
3556
|
+
* Move the real folder `dir` into the identity store and leave a link in its
|
|
3557
|
+
* place. The entry is a project entry of its own, named after the handle's local
|
|
3558
|
+
* part, or the agent id when that is no usable name. The folder is copied to a
|
|
3559
|
+
* temp sibling in the store, renamed into place, linked, and only then removed;
|
|
3560
|
+
* any failure before the link stands removes the copy and puts the folder back.
|
|
3561
|
+
* While it waits to be removed, the folder sits in a dir whose `.gitignore`
|
|
3562
|
+
* keeps it out of git, so an adopt that is stopped there leaves nothing to commit.
|
|
3563
|
+
*/
|
|
3564
|
+
function moveIntoStore(dir, named) {
|
|
3565
|
+
const name = [named.handle?.split("@")[0], named.agentId].find((candidate) => candidate !== void 0 && STORE_NAME.test(candidate));
|
|
3566
|
+
if (name === void 0) throw new Error(`Refusing to adopt ${dir}: neither its handle nor its agent id can name an identity in the store.`);
|
|
3567
|
+
requireLinkSupport("Adopting a folder", name);
|
|
3568
|
+
const tag = randomBytes(6).toString("hex");
|
|
3569
|
+
const copy = join(identityStoreDir(), `.adopting-${name}-${tag}`);
|
|
3570
|
+
const aside = `${dir}.adopting-${tag}`;
|
|
3571
|
+
fs$1.mkdirSync(identityStoreDir(), {
|
|
3572
|
+
recursive: true,
|
|
3573
|
+
mode: 448
|
|
3574
|
+
});
|
|
3575
|
+
const store = claimProjectEntry(name);
|
|
3576
|
+
let movedAside = false;
|
|
3577
|
+
try {
|
|
3578
|
+
copyChecked(dir, dir, copy);
|
|
3579
|
+
fs$1.renameSync(copy, store);
|
|
3580
|
+
fs$1.mkdirSync(aside, { mode: 448 });
|
|
3581
|
+
writeIgnoreAll(aside);
|
|
3582
|
+
fs$1.renameSync(dir, join(aside, "rine"));
|
|
3583
|
+
movedAside = true;
|
|
3584
|
+
const unlisted = linkProject(store, dir);
|
|
3585
|
+
if (unlisted !== void 0) printError(unlisted);
|
|
3586
|
+
} catch (error) {
|
|
3587
|
+
if (movedAside) fs$1.renameSync(join(aside, "rine"), dir);
|
|
3588
|
+
fs$1.rmSync(aside, {
|
|
3589
|
+
recursive: true,
|
|
3590
|
+
force: true
|
|
3591
|
+
});
|
|
3592
|
+
fs$1.rmSync(copy, {
|
|
3593
|
+
recursive: true,
|
|
3594
|
+
force: true
|
|
3595
|
+
});
|
|
3596
|
+
fs$1.rmSync(store, {
|
|
3597
|
+
recursive: true,
|
|
3598
|
+
force: true
|
|
3599
|
+
});
|
|
3600
|
+
throw error;
|
|
3601
|
+
}
|
|
3602
|
+
try {
|
|
3603
|
+
fs$1.rmSync(aside, { recursive: true });
|
|
3604
|
+
} catch (error) {
|
|
3605
|
+
printError(`rine: could not remove the old folder ${aside} (${formatError(error)}); remove it yourself.`);
|
|
3606
|
+
}
|
|
3607
|
+
}
|
|
3608
|
+
//#endregion
|
|
3609
|
+
//#region src/commands/identity-adopt.ts
|
|
3610
|
+
/** What adopting cannot fix: someone else's folder, one others can write to, or a link out of the store. */
|
|
3611
|
+
const NotFixableByAdopt = [
|
|
3612
|
+
ProjectDirRefusalCode.ForeignOwner,
|
|
3613
|
+
ProjectDirRefusalCode.Writable,
|
|
3614
|
+
ProjectDirRefusalCode.NotInStore
|
|
3615
|
+
];
|
|
3616
|
+
const ADOPT_WARNING = "Adopt only a folder you made yourself: from now on this agent acts as the identity in it.";
|
|
3617
|
+
/** The org whose root `ownerDir` holds, or undefined when it holds none or a corrupt one. */
|
|
3618
|
+
function rootOrgOf(ownerDir) {
|
|
3619
|
+
try {
|
|
3620
|
+
return loadOrgFromOwner(ownerDir)?.orgId;
|
|
3621
|
+
} catch {
|
|
3622
|
+
return;
|
|
3623
|
+
}
|
|
3624
|
+
}
|
|
3625
|
+
/**
|
|
3626
|
+
* Whether a recorded owner dir is one to keep: it exists, it is ours, and it
|
|
3627
|
+
* holds the root of the org the folder's profile names (a planted hint naming
|
|
3628
|
+
* the user's own owner dir of another org is dropped).
|
|
3629
|
+
*/
|
|
3630
|
+
function soundOwnerDir(ownerDir, orgId) {
|
|
3631
|
+
if (ownerDir === void 0 || orgId === void 0) return false;
|
|
3632
|
+
const stat = fs$1.lstatSync(ownerDir, { throwIfNoEntry: false });
|
|
3633
|
+
return stat?.isDirectory() === true && ownedByUs(stat) && rootOrgOf(ownerDir) === orgId;
|
|
3634
|
+
}
|
|
3635
|
+
function registerIdentityAdopt(identity, program) {
|
|
3636
|
+
identity.command("adopt").description("Accept the project .rine this directory skipped as yours, recording where it is").option("--confirm <handle>", "the handle the folder names (its agent id when it names no handle); required").action(withErrorHandler(program, (gOpts, opts) => {
|
|
3637
|
+
readBoundDirs();
|
|
3638
|
+
const skipped = resolveConfigDir().refused?.[0];
|
|
3639
|
+
if (skipped === void 0) throw new Error("Nothing to adopt: no project .rine was skipped here.");
|
|
3640
|
+
const { dir, code, reason } = skipped;
|
|
3641
|
+
if (NotFixableByAdopt.includes(code)) throw new Error(`Refusing to adopt ${dir}: ${reason}. Fix its owner and permissions first (mode 0700, yours), or bind a named identity.`);
|
|
3642
|
+
const named = projectDirIdentity(dir);
|
|
3643
|
+
const names = describeProjectDirIdentity(named);
|
|
3644
|
+
const expected = named.handle ?? named.agentId;
|
|
3645
|
+
if (expected === void 0) throw new Error(`Refusing to adopt ${dir}: it names no agent (${names}).`);
|
|
3646
|
+
if (opts.confirm !== expected) throw new Error(`Refusing to adopt ${dir} without --confirm naming the identity it holds: ${names}. ${ADOPT_WARNING}`);
|
|
3647
|
+
const known = readIdentityLoosely(dir, readProjectIdentityFile);
|
|
3648
|
+
const keepOwner = soundOwnerDir(known?.owner_dir, named.orgId);
|
|
3649
|
+
if (!fs$1.lstatSync(dir).isSymbolicLink()) moveIntoStore(dir, named);
|
|
3650
|
+
writeIdentityMarkers(dir, {
|
|
3651
|
+
handle: known?.handle,
|
|
3652
|
+
ownerDir: keepOwner ? known?.owner_dir : void 0,
|
|
3653
|
+
createdAt: known?.created_at
|
|
3654
|
+
});
|
|
3655
|
+
recordBoundDir(dir);
|
|
3656
|
+
if (gOpts.json) {
|
|
3657
|
+
printJson({
|
|
3658
|
+
ok: true,
|
|
3659
|
+
dir,
|
|
3660
|
+
handle: named.handle ?? null,
|
|
3661
|
+
agent_id: named.agentId ?? null,
|
|
3662
|
+
org_id: named.orgId ?? null,
|
|
3663
|
+
owner_dir_kept: keepOwner
|
|
3664
|
+
});
|
|
3665
|
+
return;
|
|
3666
|
+
}
|
|
3667
|
+
const dropped = known?.owner_dir !== void 0 && !keepOwner ? " Dropped its owner dir hint: that dir is not yours or holds no root of its org." : "";
|
|
3668
|
+
printSuccess(`Adopted ${dir} at ${fs$1.realpathSync(dir)}: it acts as ${names}.${dropped} ${ADOPT_WARNING}`);
|
|
3669
|
+
}));
|
|
3670
|
+
}
|
|
3671
|
+
//#endregion
|
|
3672
|
+
//#region src/commands/identity-new-flags.ts
|
|
3673
|
+
/** The one thing `--org` can ask for. */
|
|
3674
|
+
const OrgChoice = { New: "new" };
|
|
3675
|
+
/** Refuse an identity name that is not a slug, before it is looked up or made. */
|
|
3676
|
+
function checkName(name) {
|
|
3677
|
+
if (!validateSlug(name)) throw new Error("Invalid name: use 2-32 lowercase alphanumeric characters or hyphens, no leading/trailing hyphen");
|
|
3678
|
+
}
|
|
3679
|
+
/** The refusals that need nothing but the flags, so they cost no request. */
|
|
3680
|
+
function checkFlags(name, opts) {
|
|
3681
|
+
checkName(name);
|
|
3682
|
+
if (opts.move && opts.agent === void 0) throw new Error("--move needs --agent");
|
|
3683
|
+
if (opts.org === void 0) return void 0;
|
|
3684
|
+
if (opts.org !== OrgChoice.New) throw new Error(`--org takes '${OrgChoice.New}', not '${opts.org}'`);
|
|
3685
|
+
if (opts.agent !== void 0) throw new Error("--agent restores an agent of an existing org, so it cannot be combined with --org new");
|
|
3686
|
+
if (!opts.email || !opts.orgName || !opts.slug) throw new Error("--org new needs --email, --org-name and --slug");
|
|
3687
|
+
return {
|
|
3688
|
+
email: opts.email,
|
|
3689
|
+
orgName: opts.orgName,
|
|
3690
|
+
slug: opts.slug
|
|
3691
|
+
};
|
|
3692
|
+
}
|
|
3693
|
+
//#endregion
|
|
3694
|
+
//#region src/commands/identity-bind.ts
|
|
3695
|
+
/**
|
|
3696
|
+
* Whether `.rine` at `link` holds the project's own identity: a real folder, or
|
|
3697
|
+
* a link to a project's own store entry (`identity new --here` or `adopt` made
|
|
3698
|
+
* it), which bind and unbind leave alone.
|
|
3699
|
+
*/
|
|
3700
|
+
function holdsOwnIdentity(link, existing) {
|
|
3701
|
+
return !existing.isSymbolicLink() || linksToProjectEntry(link);
|
|
3702
|
+
}
|
|
3703
|
+
/** How the `.rine` at `link`, which {@link holdsOwnIdentity}, holds it: as a real folder or as a link to its own entry. */
|
|
3704
|
+
function ownIdentityHeld(link, existing) {
|
|
3705
|
+
return existing.isSymbolicLink() ? `${link} links to this project's own identity` : `${link} is a real directory holding its own identity`;
|
|
3706
|
+
}
|
|
3707
|
+
function registerIdentityBind(identity, program) {
|
|
3708
|
+
identity.command("bind <name>").description("Make this directory use a named identity (links .rine to it)").action(withErrorHandler(program, (gOpts, name) => {
|
|
3709
|
+
checkName(name);
|
|
3710
|
+
requireLinkSupport("Binding", name);
|
|
3711
|
+
const store = storeEntryDir(name);
|
|
3712
|
+
if (!fs$1.statSync(store, { throwIfNoEntry: false })?.isDirectory()) throw new Error(`No identity named '${name}' in ${store}. Make it with: rine identity new ${name}`);
|
|
3713
|
+
if (readIdentityLoosely(store) === void 0) throw new Error(`'${name}' in ${store} has no readable ${IDENTITY_FILE}, so a project would ignore it. Make it with: rine identity new ${name}`);
|
|
3714
|
+
const link = projectLinkToMake();
|
|
3715
|
+
const existing = entryAt(link);
|
|
3716
|
+
if (existing !== void 0 && holdsOwnIdentity(link, existing)) throw new Error(`${ownIdentityHeld(link, existing)}. Move it away if you want to bind '${name}' here.`);
|
|
3717
|
+
if (existing !== void 0) {
|
|
3718
|
+
if (linkTarget(link) === fs$1.realpathSync(store)) {
|
|
3719
|
+
recordBoundDir(link);
|
|
3720
|
+
printMutationOk(`${link} already uses '${name}'`, gOpts.json);
|
|
3721
|
+
return;
|
|
3722
|
+
}
|
|
3723
|
+
const other = resolve(dirname(link), fs$1.readlinkSync(link));
|
|
3724
|
+
const agent = readIdentityLoosely(other)?.handle ?? "unknown agent";
|
|
3725
|
+
throw new Error(`${link} already uses the identity '${basename(other)}' (agent ${agent}). Run \`rine identity unbind\` here, then \`rine identity bind ${name}\`.`);
|
|
3726
|
+
}
|
|
3727
|
+
const unlisted = linkProject(store, link);
|
|
3728
|
+
if (unlisted !== void 0) printError(unlisted);
|
|
3729
|
+
try {
|
|
3730
|
+
recordBoundDir(link);
|
|
3731
|
+
} catch (error) {
|
|
3732
|
+
fs$1.unlinkSync(link);
|
|
3733
|
+
throw error;
|
|
3734
|
+
}
|
|
3735
|
+
printMutationOk(`${link} now uses '${name}'`, gOpts.json);
|
|
3736
|
+
}));
|
|
3737
|
+
}
|
|
3738
|
+
function registerIdentityUnbind(identity, program) {
|
|
3739
|
+
identity.command("unbind").description("Stop this directory using a named identity (removes the .rine link)").action(withErrorHandler(program, (gOpts) => {
|
|
3740
|
+
const link = projectLinkPath();
|
|
3741
|
+
const existing = entryAt(link);
|
|
3742
|
+
if (existing === void 0) {
|
|
3743
|
+
printMutationOk("Nothing to unbind: this directory has no .rine", gOpts.json);
|
|
3744
|
+
return;
|
|
3745
|
+
}
|
|
3746
|
+
if (holdsOwnIdentity(link, existing)) throw new Error(`${ownIdentityHeld(link, existing)}, not a link to a named one. It is left as it is.`);
|
|
3747
|
+
forgetBoundDir(link);
|
|
3748
|
+
fs$1.unlinkSync(link);
|
|
3749
|
+
printMutationOk(`Removed ${link}; the identity itself is kept`, gOpts.json);
|
|
3750
|
+
}));
|
|
3751
|
+
}
|
|
3752
|
+
//#endregion
|
|
3753
|
+
//#region src/commands/identity-restore.ts
|
|
3754
|
+
const TWO_DIRS_NOTICE = "Two directories now hold this agent. Running both at once corrupts its group state: use one, or move the agent instead with --move.";
|
|
3755
|
+
function noRootRefusal(ownerDir) {
|
|
3756
|
+
return `There is no org root in ${ownerDir}, so nothing here can create or restore an agent. Point RINE_OWNER_DIR at the directory that holds root.key, or use --org new.`;
|
|
3757
|
+
}
|
|
3758
|
+
/** Refuse a `--move` that would leave the source dir without an identity. */
|
|
3759
|
+
function assertMovable(dir, agent) {
|
|
3760
|
+
if (defaultAgentId(dir.path) === agent.id) throw new Error(`${dir.shown} acts as ${agent.name} through its default profile, so moving it would leave that directory with no identity.`);
|
|
3761
|
+
}
|
|
3762
|
+
/**
|
|
3763
|
+
* Take over an existing agent in `target`: its keys are re-derived from the org
|
|
3764
|
+
* root and checked against the server, never copied from another dir, and its
|
|
3765
|
+
* closed-group seats are taken again.
|
|
3766
|
+
*/
|
|
3767
|
+
async function restoreAgent(client, source, target, ref, move) {
|
|
3768
|
+
const org = loadOrgFromOwner(source.ownerDir);
|
|
3769
|
+
if (org === void 0) throw new Error(noRootRefusal(source.ownerDir));
|
|
3770
|
+
const agent = await findOrgAgent(client, ref);
|
|
3771
|
+
if (move) assertMovable(source.dir, agent);
|
|
3772
|
+
const { closedGroups } = await restoreAgentInto(client, org, target, agent);
|
|
3773
|
+
if (move) removeAgentKeys(source.dir.path, agent.id);
|
|
3774
|
+
return {
|
|
3775
|
+
agent,
|
|
3776
|
+
closedGroups
|
|
3777
|
+
};
|
|
3778
|
+
}
|
|
3779
|
+
//#endregion
|
|
3780
|
+
//#region src/phrase-display.ts
|
|
3781
|
+
/** The one place the words reach a screen: framed, on a terminal. */
|
|
3782
|
+
function printFramedPhrase(ownerDir, heading) {
|
|
3783
|
+
const rule = "=".repeat(72);
|
|
3784
|
+
console.log([
|
|
3785
|
+
rule,
|
|
3786
|
+
heading,
|
|
3787
|
+
readOwnerPhrase(ownerDir),
|
|
3788
|
+
`Also saved to: ${join(ownerDir, PHRASE_FILE)}`,
|
|
3789
|
+
PHRASE_INSTRUCTION,
|
|
3790
|
+
rule
|
|
3791
|
+
].join("\n"));
|
|
3792
|
+
}
|
|
3793
|
+
/**
|
|
3794
|
+
* Tell the owner where the phrase is. On a terminal and outside `--json` the
|
|
3795
|
+
* words are shown once; anywhere else only the file path is printed, so the
|
|
3796
|
+
* phrase cannot reach a log, a pipe or a model context.
|
|
3797
|
+
*/
|
|
3798
|
+
function announcePhrase(opts) {
|
|
3799
|
+
if (process.stdout.isTTY === true && !opts.json) {
|
|
3800
|
+
printFramedPhrase(opts.ownerDir, "Recovery phrase (shown once)");
|
|
3801
|
+
return;
|
|
3802
|
+
}
|
|
3803
|
+
(opts.json ? process.stderr : process.stdout).write(`Recovery phrase file: ${opts.phrasePath}\n${PHRASE_INSTRUCTION}\n`);
|
|
3804
|
+
}
|
|
3805
|
+
//#endregion
|
|
3806
|
+
//#region src/commands/register-org.ts
|
|
3807
|
+
const TERMS_NOTICE = "By registering, you accept the rine terms of service and privacy policy:\n https://rine.network/terms.html\n https://rine.network/privacy.html\n";
|
|
3808
|
+
/** Register a new org under `dirs`; the notice goes to stderr, progress to stderr under `--json`. */
|
|
3809
|
+
async function registerOrg$1(apiUrl, dirs, profile, params, json) {
|
|
3810
|
+
process.stderr.write(TERMS_NOTICE);
|
|
3811
|
+
const progress = json ? process.stderr : process.stdout;
|
|
3812
|
+
const reg = await performRegistration(apiUrl, dirs, profile, params, (pct) => progress.write(`\rSolving PoW challenge: ${pct}%`));
|
|
3813
|
+
progress.write("\rSolving PoW challenge: 100%\n");
|
|
3814
|
+
announcePhrase({
|
|
3815
|
+
ownerDir: dirs.ownerDir,
|
|
3816
|
+
phrasePath: reg.phrase_path,
|
|
3817
|
+
json
|
|
3818
|
+
});
|
|
3819
|
+
return reg;
|
|
3820
|
+
}
|
|
3821
|
+
//#endregion
|
|
3822
|
+
//#region src/commands/identity-new-org.ts
|
|
3823
|
+
/**
|
|
3824
|
+
* Register a new org for an identity dir. Its root goes to its own owner dir
|
|
3825
|
+
* under the owner store, which is refused inside a git tree, so a repository
|
|
3826
|
+
* never holds it. Returns the org's dirs and an admin client signing as it.
|
|
3827
|
+
*/
|
|
3828
|
+
async function registerNewOrg(target, opts, json) {
|
|
3829
|
+
if (!validateSlug(opts.slug)) throw new Error("Invalid slug: must be 2-32 lowercase alphanumeric characters or hyphens, no leading/trailing hyphen");
|
|
3830
|
+
const dirs = {
|
|
3831
|
+
configDir: target,
|
|
3832
|
+
ownerDir: ownerStoreDir(opts.slug)
|
|
3833
|
+
};
|
|
3834
|
+
assertOwnerDirAllowed(dirs.ownerDir, configDirAt(target));
|
|
3835
|
+
const apiUrl = resolveApiUrl();
|
|
3836
|
+
const reg = await registerOrg$1(apiUrl, dirs, DEFAULT_PROFILE, {
|
|
3837
|
+
email: opts.email,
|
|
3838
|
+
slug: opts.slug,
|
|
3839
|
+
name: opts.orgName
|
|
3840
|
+
}, json);
|
|
3841
|
+
const { client } = buildTierClient({
|
|
3842
|
+
dirs,
|
|
3843
|
+
apiUrl
|
|
3844
|
+
});
|
|
3845
|
+
return {
|
|
3846
|
+
dirs,
|
|
3847
|
+
client: client.asAdmin(),
|
|
3848
|
+
orgId: reg.org_id
|
|
3849
|
+
};
|
|
3850
|
+
}
|
|
3851
|
+
//#endregion
|
|
3852
|
+
//#region src/commands/identity-store-entry.ts
|
|
3853
|
+
const taken = (path) => entryAt(path) !== void 0;
|
|
3854
|
+
/** Where the identity is made, refusing a place that is taken. */
|
|
3855
|
+
function targetFor(name, here) {
|
|
3856
|
+
if (here) {
|
|
3857
|
+
requireLinkSupport("--here", name);
|
|
3858
|
+
const link = projectLinkToMake();
|
|
3859
|
+
if (taken(link)) throw new Error(`${link} already exists. Remove or move it first.`);
|
|
3860
|
+
return {
|
|
3861
|
+
name,
|
|
3862
|
+
link
|
|
3863
|
+
};
|
|
3864
|
+
}
|
|
3865
|
+
const store = storeEntryDir(name);
|
|
3866
|
+
if (taken(store)) throw new Error(`An identity named '${name}' already exists at ${store}`);
|
|
3867
|
+
return { name };
|
|
3868
|
+
}
|
|
3869
|
+
/**
|
|
3870
|
+
* Make the store entry (for `--here`, a project entry of its own) and, for
|
|
3871
|
+
* `--here`, link the project to it; neither is left half made.
|
|
3872
|
+
*/
|
|
3873
|
+
function makeDir(target) {
|
|
3874
|
+
const above = fs$1.mkdirSync(identityStoreDir(), {
|
|
3875
|
+
recursive: true,
|
|
3876
|
+
mode: 448
|
|
3877
|
+
});
|
|
3878
|
+
if (target.link === void 0) {
|
|
3879
|
+
const store = storeEntryDir(target.name);
|
|
3880
|
+
fs$1.mkdirSync(store, { mode: 448 });
|
|
3881
|
+
return { store };
|
|
3882
|
+
}
|
|
3883
|
+
const store = claimProjectEntry(target.name);
|
|
3884
|
+
try {
|
|
3885
|
+
const unlisted = linkProject(store, target.link);
|
|
3886
|
+
if (unlisted !== void 0) printError(unlisted);
|
|
3887
|
+
} catch (error) {
|
|
3888
|
+
fs$1.rmdirSync(store);
|
|
3889
|
+
throw error;
|
|
3890
|
+
}
|
|
3891
|
+
return {
|
|
3892
|
+
store,
|
|
3893
|
+
above
|
|
3894
|
+
};
|
|
3895
|
+
}
|
|
3896
|
+
/**
|
|
3897
|
+
* Undo {@link makeDir} when making the identity failed before it held any keys
|
|
3898
|
+
* worth keeping. For `--here`, the dirs it made above the entry go too, while
|
|
3899
|
+
* they are empty, so a failed `--here` leaves nothing behind.
|
|
3900
|
+
*/
|
|
3901
|
+
function unmakeDir(target, made) {
|
|
3902
|
+
if (target.link !== void 0 && entryAt(target.link) !== void 0) fs$1.unlinkSync(target.link);
|
|
3903
|
+
fs$1.rmSync(made.store, {
|
|
3904
|
+
recursive: true,
|
|
3905
|
+
force: true
|
|
3906
|
+
});
|
|
3907
|
+
if (made.above === void 0) return;
|
|
3908
|
+
try {
|
|
3909
|
+
for (let at = identityStoreDir();; at = dirname(at)) {
|
|
3910
|
+
fs$1.rmdirSync(at);
|
|
3911
|
+
if (at === made.above) return;
|
|
3912
|
+
}
|
|
3913
|
+
} catch {}
|
|
3914
|
+
}
|
|
3915
|
+
/**
|
|
3916
|
+
* Mark the new identity in `store` and, for `--here`, record the project link.
|
|
3917
|
+
* The store entry holds the keys, so with `--here` a failure of either step keeps
|
|
3918
|
+
* the entry and the link and says how to finish; returns whether the link is
|
|
3919
|
+
* recorded. Without `--here` a failure throws.
|
|
3920
|
+
*/
|
|
3921
|
+
function settle(target, store, markers, confirm) {
|
|
3922
|
+
try {
|
|
3923
|
+
writeIdentityMarkers(store, markers);
|
|
3924
|
+
if (target.link !== void 0) recordBoundDir(target.link);
|
|
3925
|
+
return true;
|
|
3926
|
+
} catch (error) {
|
|
3927
|
+
if (target.link === void 0) throw error;
|
|
3928
|
+
printError(`${target.link} holds the new identity and its keys, but recording it as yours failed: ${formatError(error)}\nOnce that is fixed, run here: ${ADOPT_COMMAND} --confirm ${confirm}`);
|
|
3929
|
+
process.exitCode = 1;
|
|
3930
|
+
return false;
|
|
3931
|
+
}
|
|
3932
|
+
}
|
|
3933
|
+
//#endregion
|
|
3934
|
+
//#region src/commands/identity-new.ts
|
|
3935
|
+
async function makeIdentity(gOpts, name, target, opts, newOrg, source) {
|
|
3936
|
+
if (newOrg !== void 0) {
|
|
3937
|
+
const { dirs, client, orgId } = await registerNewOrg(target, newOrg, gOpts.json);
|
|
3938
|
+
try {
|
|
3939
|
+
return {
|
|
3940
|
+
agent: await performAgentCreation(client, dirs, DEFAULT_PROFILE, {
|
|
3941
|
+
name,
|
|
3942
|
+
into: target
|
|
3943
|
+
}),
|
|
3944
|
+
ownerDir: dirs.ownerDir,
|
|
3945
|
+
orgId
|
|
3946
|
+
};
|
|
3947
|
+
} catch (error) {
|
|
3948
|
+
const reason = formatError(error);
|
|
3949
|
+
throw new Error(`${reason}\nThe org is registered and its root is kept in ${dirs.ownerDir}; recover the agent from there.`);
|
|
3950
|
+
}
|
|
3951
|
+
}
|
|
3952
|
+
const current = custodyDirsOf(source);
|
|
3953
|
+
if (!hasRoot(current.ownerDir)) throw new Error(noRootRefusal(current.ownerDir));
|
|
3954
|
+
const client = buildTierClient({
|
|
3955
|
+
dirs: current,
|
|
3956
|
+
apiUrl: resolveApiUrl(),
|
|
3957
|
+
profile: gOpts.profile
|
|
3958
|
+
}).client.asAdmin();
|
|
3959
|
+
const ownerDir = readIdentityLoosely(current.configDir)?.owner_dir;
|
|
3960
|
+
if (opts.agent !== void 0) {
|
|
3961
|
+
const restored = await restoreAgent(client, {
|
|
3962
|
+
dir: source,
|
|
3963
|
+
ownerDir: current.ownerDir
|
|
3964
|
+
}, target, opts.agent, opts.move === true);
|
|
3965
|
+
return {
|
|
3966
|
+
agent: restored.agent,
|
|
3967
|
+
ownerDir,
|
|
3968
|
+
closedGroups: restored.closedGroups
|
|
3969
|
+
};
|
|
3970
|
+
}
|
|
3971
|
+
return {
|
|
3972
|
+
agent: await performAgentCreation(client, current, DEFAULT_PROFILE, {
|
|
3973
|
+
name,
|
|
3974
|
+
into: target
|
|
3975
|
+
}),
|
|
3976
|
+
ownerDir
|
|
3977
|
+
};
|
|
3978
|
+
}
|
|
3979
|
+
function report(gOpts, name, path, made, opts, bound) {
|
|
3980
|
+
const { agent } = made;
|
|
3981
|
+
if (gOpts.json) {
|
|
3982
|
+
printJson({
|
|
3983
|
+
name,
|
|
3984
|
+
path,
|
|
3985
|
+
agent_id: agent.id,
|
|
3986
|
+
handle: agent.handle,
|
|
3987
|
+
org_id: made.orgId ?? null,
|
|
3988
|
+
owner_dir: made.ownerDir ?? null,
|
|
3989
|
+
closed_groups: made.closedGroups ?? [],
|
|
3990
|
+
...!bound && { bound: false }
|
|
3991
|
+
});
|
|
3992
|
+
return;
|
|
3993
|
+
}
|
|
3994
|
+
printTable([
|
|
3995
|
+
{
|
|
3996
|
+
Field: "Identity",
|
|
3997
|
+
Value: name
|
|
3998
|
+
},
|
|
3999
|
+
{
|
|
4000
|
+
Field: "Path",
|
|
4001
|
+
Value: path
|
|
4002
|
+
},
|
|
4003
|
+
{
|
|
4004
|
+
Field: "Agent",
|
|
4005
|
+
Value: agent.handle ?? agent.name
|
|
4006
|
+
},
|
|
4007
|
+
{
|
|
4008
|
+
Field: "Agent ID",
|
|
4009
|
+
Value: agent.id
|
|
4010
|
+
}
|
|
4011
|
+
]);
|
|
4012
|
+
if (opts.agent !== void 0 && !opts.move) console.log(TWO_DIRS_NOTICE);
|
|
4013
|
+
if (!opts.here) console.log(`Use it in a project with: rine identity bind ${name}`);
|
|
4014
|
+
}
|
|
4015
|
+
function registerIdentityNew(identity, program) {
|
|
4016
|
+
identity.command("new <name>").description("Make a named identity: a new agent under this org, or under a new org").option("--here", "also bind it here: link ./.rine of this project to it").option("--org <which>", `'${OrgChoice.New}' registers a new org for this identity`).option("--email <email>", "contact email, for --org new").option("--org-name <name>", "name of the new org, for --org new").option("--slug <slug>", "slug of the new org, for --org new").option("--agent <existing>", "take over an existing agent (id, handle or name) instead of creating one").option("--move", "with --agent: also remove its keys from the directory you run this in").action(withErrorHandler(program, async (gOpts, name, opts) => {
|
|
4017
|
+
const newOrg = checkFlags(name, opts);
|
|
4018
|
+
const target = targetFor(name, opts.here);
|
|
4019
|
+
if (opts.here) readBoundDirs();
|
|
4020
|
+
const source = resolveConfigDir();
|
|
4021
|
+
const dir = makeDir(target);
|
|
4022
|
+
let made;
|
|
4023
|
+
try {
|
|
4024
|
+
made = await makeIdentity(gOpts, name, dir.store, opts, newOrg, source);
|
|
4025
|
+
} catch (error) {
|
|
4026
|
+
unmakeDir(target, dir);
|
|
4027
|
+
throw error;
|
|
4028
|
+
}
|
|
4029
|
+
const bound = settle(target, dir.store, {
|
|
4030
|
+
handle: made.agent.handle,
|
|
4031
|
+
ownerDir: made.ownerDir
|
|
4032
|
+
}, made.agent.handle ?? made.agent.id);
|
|
4033
|
+
report(gOpts, name, target.link ?? dir.store, made, opts, bound);
|
|
4034
|
+
}));
|
|
4035
|
+
}
|
|
4036
|
+
//#endregion
|
|
4037
|
+
//#region src/commands/identity-show.ts
|
|
4038
|
+
/** Where an identity in the store sits when it is not the one this process acts from. */
|
|
4039
|
+
const STORE_SOURCE = "store";
|
|
4040
|
+
function realOrSelf(path) {
|
|
4041
|
+
try {
|
|
4042
|
+
return fs$1.realpathSync(path);
|
|
4043
|
+
} catch {
|
|
4044
|
+
return path;
|
|
4045
|
+
}
|
|
4046
|
+
}
|
|
4047
|
+
/** The target of `.rine` when the current dir is a symlink (a bound identity). */
|
|
4048
|
+
function bindTarget(dir) {
|
|
4049
|
+
try {
|
|
4050
|
+
return fs$1.lstatSync(dir).isSymbolicLink() ? fs$1.readlinkSync(dir) : void 0;
|
|
4051
|
+
} catch {
|
|
4052
|
+
return;
|
|
4053
|
+
}
|
|
4054
|
+
}
|
|
4055
|
+
/** A listed identity shown at `path`, its files read at `readAt`. */
|
|
4056
|
+
function listedFrom(name, path, source, current, readAt = path) {
|
|
4057
|
+
return {
|
|
4058
|
+
name,
|
|
4059
|
+
path,
|
|
4060
|
+
source,
|
|
4061
|
+
handle: readIdentityLoosely(readAt)?.handle ?? null,
|
|
4062
|
+
agent_id: defaultAgentId(readAt),
|
|
4063
|
+
registered: isRegistered(readAt),
|
|
4064
|
+
current
|
|
4065
|
+
};
|
|
4066
|
+
}
|
|
4067
|
+
/** The store's identities and the dir this process acts from, with no request and no root read. */
|
|
4068
|
+
function listIdentities(dir) {
|
|
4069
|
+
const here = realOrSelf(dir.path);
|
|
4070
|
+
let currentListed = false;
|
|
4071
|
+
const entries = storeNames().map((name) => {
|
|
4072
|
+
const path = storeEntryDir(name);
|
|
4073
|
+
const current = realOrSelf(path) === here;
|
|
4074
|
+
currentListed ||= current;
|
|
4075
|
+
return listedFrom(name, current ? dir.shown : path, current ? dir.source : STORE_SOURCE, current, path);
|
|
4076
|
+
});
|
|
4077
|
+
return currentListed ? entries : [listedFrom(null, dir.shown, dir.source, true, dir.path), ...entries];
|
|
4078
|
+
}
|
|
4079
|
+
function registerIdentityShow(identity, program) {
|
|
4080
|
+
identity.command("show").description("Show which identity this directory acts as, and where it came from").action(withErrorHandler(program, (gOpts) => {
|
|
4081
|
+
const dir = resolveConfigDir();
|
|
4082
|
+
const facts = dirFacts(authDirsOf(dir), dir, gOpts.profile);
|
|
4083
|
+
const profile = getProfile(dir.path, gOpts.profile ?? DEFAULT_PROFILE);
|
|
4084
|
+
const file = readIdentityLoosely(dir.path);
|
|
4085
|
+
const boundTo = bindTarget(dir.shown);
|
|
4086
|
+
if (gOpts.json) {
|
|
4087
|
+
printJson({
|
|
4088
|
+
...facts,
|
|
4089
|
+
handle: file?.handle ?? null,
|
|
4090
|
+
org_id: profile?.org_id ?? null,
|
|
4091
|
+
bound_to: boundTo ?? null
|
|
4092
|
+
});
|
|
4093
|
+
return;
|
|
4094
|
+
}
|
|
4095
|
+
printTable([
|
|
4096
|
+
...dirFactRows(facts),
|
|
4097
|
+
{
|
|
4098
|
+
Field: "Agent",
|
|
4099
|
+
Value: facts.tiers.agent ?? "-"
|
|
4100
|
+
},
|
|
4101
|
+
{
|
|
4102
|
+
Field: "Handle",
|
|
4103
|
+
Value: file?.handle ?? "-"
|
|
4104
|
+
},
|
|
4105
|
+
{
|
|
4106
|
+
Field: "Org",
|
|
4107
|
+
Value: profile?.org_id ?? "-"
|
|
4108
|
+
},
|
|
4109
|
+
...boundTo === void 0 ? [] : [{
|
|
4110
|
+
Field: "Bound to",
|
|
4111
|
+
Value: boundTo
|
|
4112
|
+
}]
|
|
4113
|
+
]);
|
|
4114
|
+
}));
|
|
4115
|
+
}
|
|
4116
|
+
function registerIdentityList(identity, program) {
|
|
4117
|
+
identity.command("list").description("List the named identities on this machine and the one in use").action(withErrorHandler(program, (gOpts) => {
|
|
4118
|
+
const identities = listIdentities(resolveConfigDir());
|
|
4119
|
+
if (gOpts.json) {
|
|
4120
|
+
printJson({ identities });
|
|
4121
|
+
return;
|
|
4122
|
+
}
|
|
4123
|
+
printTable(identities.map((entry) => ({
|
|
4124
|
+
Name: entry.name ?? "-",
|
|
4125
|
+
Path: entry.path,
|
|
4126
|
+
Source: entry.source,
|
|
4127
|
+
Handle: entry.handle ?? "-",
|
|
4128
|
+
Agent: entry.agent_id ?? "-",
|
|
4129
|
+
Registered: entry.registered ? "yes" : "no",
|
|
4130
|
+
Current: entry.current ? "*" : ""
|
|
4131
|
+
})));
|
|
4132
|
+
}));
|
|
4133
|
+
}
|
|
4134
|
+
//#endregion
|
|
4135
|
+
//#region src/commands/identity.ts
|
|
4136
|
+
function registerIdentity(program) {
|
|
4137
|
+
const identity = program.command("identity").description("Which identity this directory acts as, and the named ones on this machine");
|
|
4138
|
+
registerIdentityShow(identity, program);
|
|
4139
|
+
registerIdentityList(identity, program);
|
|
4140
|
+
registerIdentityNew(identity, program);
|
|
4141
|
+
registerIdentityBind(identity, program);
|
|
4142
|
+
registerIdentityUnbind(identity, program);
|
|
4143
|
+
registerIdentityAdopt(identity, program);
|
|
4144
|
+
}
|
|
4145
|
+
//#endregion
|
|
3048
4146
|
//#region src/commands/keys-rotate-report.ts
|
|
3049
4147
|
const KEY_PACKAGE_LINES = {
|
|
3050
4148
|
[KeyPackageRotation.Republished]: "Published key packages now carry the new key.",
|
|
@@ -3102,7 +4200,8 @@ function invalidReason(data) {
|
|
|
3102
4200
|
}
|
|
3103
4201
|
}
|
|
3104
4202
|
function registerKeysTransfer(keys, program) {
|
|
3105
|
-
keys.command("export").description("Export private keys to a file").addOption(actorOption()).requiredOption("--output <file>", "Output file path").action(withClient(program, async ({ gOpts,
|
|
4203
|
+
keys.command("export").description("Export private keys to a file").addOption(actorOption()).requiredOption("--output <file>", "Output file path").action(withClient(program, async ({ gOpts, dir, dirs, actingAgent }, opts) => {
|
|
4204
|
+
const { configDir } = dirs;
|
|
3106
4205
|
const agentId = await actingAgent();
|
|
3107
4206
|
if (!agentKeysExist(configDir, agentId)) {
|
|
3108
4207
|
printError(`No keys found for agent ${agentId}`);
|
|
@@ -3111,7 +4210,7 @@ function registerKeysTransfer(keys, program) {
|
|
|
3111
4210
|
}
|
|
3112
4211
|
const orgId = orgIdOfAgent(configDir, agentId);
|
|
3113
4212
|
if (orgId === void 0) {
|
|
3114
|
-
printError(`Cannot tell which org agent ${agentId} belongs to: no profile in ${
|
|
4213
|
+
printError(`Cannot tell which org agent ${agentId} belongs to: no profile in ${dir.shown} names it`);
|
|
3115
4214
|
process.exitCode = 1;
|
|
3116
4215
|
return;
|
|
3117
4216
|
}
|
|
@@ -3140,7 +4239,7 @@ function registerKeysTransfer(keys, program) {
|
|
|
3140
4239
|
process.exitCode = 2;
|
|
3141
4240
|
return;
|
|
3142
4241
|
}
|
|
3143
|
-
saveAgentKeys(resolveConfigDir(), data.agent_id, agentKeysFromPrivate({
|
|
4242
|
+
saveAgentKeys(resolveConfigDir().path, data.agent_id, agentKeysFromPrivate({
|
|
3144
4243
|
signing: fromBase64Url(data.signing_private_key),
|
|
3145
4244
|
encryption: fromBase64Url(data.encryption_private_key),
|
|
3146
4245
|
pqSeed: fromBase64Url(data.pq_encryption_seed),
|
|
@@ -3174,7 +4273,7 @@ async function verifyServerKeys(client, configDir, agentId) {
|
|
|
3174
4273
|
}
|
|
3175
4274
|
function registerKeys(program) {
|
|
3176
4275
|
const keys = program.command("keys").description("E2EE key management");
|
|
3177
|
-
keys.command("status").description("Show E2EE key status for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, configDir, actingAgent, agents }) => {
|
|
4276
|
+
keys.command("status").description("Show E2EE key status for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent, agents }) => {
|
|
3178
4277
|
const agentId = await actingAgent();
|
|
3179
4278
|
const handle = (await agents()).find((a) => a.id === agentId)?.handle ?? "unknown";
|
|
3180
4279
|
const hasLocal = agentKeysExist(configDir, agentId);
|
|
@@ -3244,13 +4343,11 @@ function registerKeys(program) {
|
|
|
3244
4343
|
}
|
|
3245
4344
|
]);
|
|
3246
4345
|
}));
|
|
3247
|
-
keys.command("rotate").description("Rotate E2EE keys for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts,
|
|
4346
|
+
keys.command("rotate").description("Rotate E2EE keys for an agent").addOption(actorOption()).action(withClient(program, async ({ client, gOpts, dirs, actingAgent }) => {
|
|
4347
|
+
const { configDir } = dirs;
|
|
3248
4348
|
const agentId = await actingAgent();
|
|
3249
4349
|
if (agentKeysExist(configDir, agentId)) backupKeys(configDir, agentId);
|
|
3250
|
-
const report = await rotateAgentWithSeats(client,
|
|
3251
|
-
configDir,
|
|
3252
|
-
ownerDir
|
|
3253
|
-
}, agentId);
|
|
4350
|
+
const report = await rotateAgentWithSeats(client, dirs, agentId);
|
|
3254
4351
|
await verifyServerKeys(client, configDir, agentId);
|
|
3255
4352
|
printRotationReport(agentId, report, gOpts.json);
|
|
3256
4353
|
}));
|
|
@@ -3435,15 +4532,19 @@ async function openMessage(opts) {
|
|
|
3435
4532
|
}
|
|
3436
4533
|
const groupId = data.group_id;
|
|
3437
4534
|
try {
|
|
4535
|
+
const result = await decryptGroupMessageWithRecovery(client, configDir, agentId, groupId, data.encrypted_payload, fromAgentId, data.created_at);
|
|
3438
4536
|
return {
|
|
3439
|
-
result
|
|
3440
|
-
refusal: null
|
|
4537
|
+
result,
|
|
4538
|
+
refusal: null,
|
|
4539
|
+
catchUp: reportedCatchUp(result).catch_up
|
|
3441
4540
|
};
|
|
3442
4541
|
} catch (err) {
|
|
3443
4542
|
const forgedStatus = groupAuthenticityStatus(err) ?? void 0;
|
|
4543
|
+
const { catch_up: catchUp } = recoveredCatchUp(err);
|
|
3444
4544
|
return {
|
|
3445
4545
|
refusal: refusalFor(err, groupId),
|
|
3446
|
-
forgedStatus
|
|
4546
|
+
forgedStatus,
|
|
4547
|
+
catchUp
|
|
3447
4548
|
};
|
|
3448
4549
|
}
|
|
3449
4550
|
}
|
|
@@ -3491,7 +4592,7 @@ function refusalFor(err, groupId) {
|
|
|
3491
4592
|
*/
|
|
3492
4593
|
/** Register `read` on the `message` command group. */
|
|
3493
4594
|
function addReadCommand(parent, program) {
|
|
3494
|
-
parent.command("read").description("Read and decrypt a message by ID").argument("<message-id>", "Message ID").addOption(actorOption("which agent is acting, and whose key decrypts (name, handle, or agent ID)")).option("--peek", "Read without marking the message delivered (it stays new)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, messageId, opts) => {
|
|
4595
|
+
parent.command("read").description("Read and decrypt a message by ID").argument("<message-id>", "Message ID").addOption(actorOption("which agent is acting, and whose key decrypts (name, handle, or agent ID)")).option("--peek", "Read without marking the message delivered (it stays new)").action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent }, messageId, opts) => {
|
|
3495
4596
|
const agentId = await actingAgent();
|
|
3496
4597
|
const data = await client.get(`/messages/${messageId}`, void 0, withPeekHeader(void 0, true));
|
|
3497
4598
|
const fromAgentId = data.from_agent_id;
|
|
@@ -3507,6 +4608,8 @@ function addReadCommand(parent, program) {
|
|
|
3507
4608
|
if (opened) {
|
|
3508
4609
|
const decResult = opened.result;
|
|
3509
4610
|
if (refusal !== null && !gOpts.json) printError(refusal.message);
|
|
4611
|
+
const note = gOpts.json ? null : catchUpNote(opened.catchUp);
|
|
4612
|
+
if (note) printError(note);
|
|
3510
4613
|
if (decResult) {
|
|
3511
4614
|
if (ingestSenderKeyDistribution(configDir, agentId, data.type, decResult)) printText("Sender key ingested");
|
|
3512
4615
|
if (gOpts.json) printJson({
|
|
@@ -3515,17 +4618,15 @@ function addReadCommand(parent, program) {
|
|
|
3515
4618
|
signature_verified: decResult.verified,
|
|
3516
4619
|
verification_status: decResult.verificationStatus,
|
|
3517
4620
|
sender_kid: decResult.senderKid,
|
|
3518
|
-
...
|
|
4621
|
+
...catchUpFields(opened.catchUp)
|
|
3519
4622
|
});
|
|
3520
|
-
else
|
|
3521
|
-
if (decResult.catchUp?.evicted) printError(MLS_EVICTED_BY_COMMIT);
|
|
3522
|
-
printTable([openedRow(data, verifiedMark(decResult.verificationStatus), decResult.plaintext?.slice(0, 200) ?? THREAD_UNAVAILABLE)]);
|
|
3523
|
-
}
|
|
4623
|
+
else printTable([openedRow(data, verifiedMark(decResult.verificationStatus), decResult.plaintext?.slice(0, 200) ?? THREAD_UNAVAILABLE)]);
|
|
3524
4624
|
return;
|
|
3525
4625
|
}
|
|
3526
4626
|
}
|
|
3527
4627
|
if (gOpts.json) printJson({
|
|
3528
4628
|
...jsonRow(data),
|
|
4629
|
+
...catchUpFields(opened?.catchUp),
|
|
3529
4630
|
...refusal !== null ? {
|
|
3530
4631
|
decrypt_error: refusal.message,
|
|
3531
4632
|
decrypt_error_code: refusal.code
|
|
@@ -3592,7 +4693,7 @@ function resolvePayload(payload, payloadFile) {
|
|
|
3592
4693
|
/** `rine reply` — answer one message, sealed for its sender. */
|
|
3593
4694
|
/** Register `reply` on the `message` command group. */
|
|
3594
4695
|
function addReplyCommand(parent, program) {
|
|
3595
|
-
parent.command("reply").description("Reply to a message (encrypted)").argument("<message-id>", "Message ID to reply to").addOption(actorOption("which agent is acting, and replies")).option("--type <type>", "Message type (defaults to original message type)").option("--payload <json>", "Reply payload as JSON string").option("--payload-file <path>", "Read payload JSON from file (use - for stdin)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, messageId, opts) => {
|
|
4696
|
+
parent.command("reply").description("Reply to a message (encrypted)").argument("<message-id>", "Message ID to reply to").addOption(actorOption("which agent is acting, and replies")).option("--type <type>", "Message type (defaults to original message type)").option("--payload <json>", "Reply payload as JSON string").option("--payload-file <path>", "Read payload JSON from file (use - for stdin)").action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent }, messageId, opts) => {
|
|
3596
4697
|
const result = resolvePayload(opts.payload, opts.payloadFile);
|
|
3597
4698
|
if ("error" in result) {
|
|
3598
4699
|
printError(result.error);
|
|
@@ -3783,7 +4884,8 @@ async function resolveSendGroup(ctx, to, groupNamedById) {
|
|
|
3783
4884
|
/** Register `send` on the `message` command group. */
|
|
3784
4885
|
function registerSend(parent, program) {
|
|
3785
4886
|
parent.command("send").description("Send an encrypted message").requiredOption("--to <address>", "Recipient: an agent handle (kofi@acme.rine.network), an agent ID, or a group — by handle (#logistics@acme.rine.network), by sigiled name (#logistics), or by the group's own ID").option("--type <type>", "Message type (default: rine.v1.dm)").option("--payload <json>", "Message payload as JSON string").option("--payload-file <path>", "Read payload JSON from file (use - for stdin)").addOption(actorOption("which agent is acting, and sends")).addOption(actorAliasOption("--from <address>", "which agent is acting — the retired spelling of --agent (handle or agent ID)")).option("--idempotency-key <key>", "Idempotency key header").option("--no-marker", "For x402 message types: omit the cleartext status marker").action(withClient(program, async (ctx, opts) => {
|
|
3786
|
-
const { client, gOpts,
|
|
4887
|
+
const { client, gOpts, actingAgent } = ctx;
|
|
4888
|
+
const { configDir } = ctx.dirs;
|
|
3787
4889
|
const result = resolvePayload(opts.payload, opts.payloadFile);
|
|
3788
4890
|
if ("error" in result) {
|
|
3789
4891
|
printError(result.error);
|
|
@@ -3833,17 +4935,23 @@ function addMessageCommands(parent, program) {
|
|
|
3833
4935
|
registerSend(parent, program);
|
|
3834
4936
|
addInboxCommand(parent, program);
|
|
3835
4937
|
addReplyCommand(parent, program);
|
|
3836
|
-
parent.command("thread").description("Show the both-sided, decrypted transcript of a conversation or a group (role-tagged)").argument("[conversation-id]", "Conversation ID").option("--group <ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).option("--limit <n>", "Max turns to return (most-recent window)").option("--hide-control", HIDE_CONTROL_HELP).action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, conversationId, opts) => {
|
|
4938
|
+
parent.command("thread").description("Show the both-sided, decrypted transcript of a conversation or a group (role-tagged)").argument("[conversation-id]", "Conversation ID").option("--group <ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).option("--limit <n>", "Max turns to return (most-recent window)").option("--hide-control", HIDE_CONTROL_HELP).action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent }, conversationId, opts) => {
|
|
3837
4939
|
const ref = resolveThreadRef({
|
|
3838
4940
|
group: opts.group,
|
|
3839
4941
|
conversationId
|
|
3840
4942
|
}, THREAD_REF_SURFACES.cli);
|
|
3841
4943
|
const agentId = await actingAgent();
|
|
3842
|
-
const entries =
|
|
4944
|
+
const { entries: bare, catchUp } = splitThreadCatchUp(await decryptThreadRows(configDir, agentId, (await readThreadPage(client, ref, {
|
|
3843
4945
|
...opts.limit ? { limit: opts.limit } : {},
|
|
3844
4946
|
extraHeaders: { [ACTING_AGENT_HEADER]: agentId }
|
|
3845
|
-
})).messages ?? [], client, null)
|
|
3846
|
-
|
|
4947
|
+
})).messages ?? [], client, null));
|
|
4948
|
+
const entries = withoutControlFrames(bare, opts.hideControl);
|
|
4949
|
+
const note = catchUpNote(catchUp);
|
|
4950
|
+
if (note) printError(note);
|
|
4951
|
+
if (gOpts.json) printJson(catchUp && entries[0] ? [{
|
|
4952
|
+
...entries[0],
|
|
4953
|
+
...catchUpFields(catchUp)
|
|
4954
|
+
}, ...entries.slice(1)] : entries);
|
|
3847
4955
|
else printTable(entries.map(threadRow));
|
|
3848
4956
|
}));
|
|
3849
4957
|
}
|
|
@@ -3852,38 +4960,13 @@ function registerMessages(program) {
|
|
|
3852
4960
|
addMessageCommands(program.command("message").description("Message operations (aliases: send/read/inbox/reply)"), program);
|
|
3853
4961
|
}
|
|
3854
4962
|
//#endregion
|
|
3855
|
-
//#region src/phrase-display.ts
|
|
3856
|
-
/** The one place the words reach a screen: framed, on a terminal. */
|
|
3857
|
-
function printFramedPhrase(ownerDir, heading) {
|
|
3858
|
-
const rule = "=".repeat(72);
|
|
3859
|
-
console.log([
|
|
3860
|
-
rule,
|
|
3861
|
-
heading,
|
|
3862
|
-
readOwnerPhrase(ownerDir),
|
|
3863
|
-
`Also saved to: ${join(ownerDir, PHRASE_FILE)}`,
|
|
3864
|
-
PHRASE_INSTRUCTION,
|
|
3865
|
-
rule
|
|
3866
|
-
].join("\n"));
|
|
3867
|
-
}
|
|
3868
|
-
/**
|
|
3869
|
-
* Tell the owner where the phrase is. On a terminal and outside `--json` the
|
|
3870
|
-
* words are shown once; anywhere else only the file path is printed, so the
|
|
3871
|
-
* phrase cannot reach a log, a pipe or a model context.
|
|
3872
|
-
*/
|
|
3873
|
-
function announcePhrase(opts) {
|
|
3874
|
-
if (process.stdout.isTTY === true && !opts.json) {
|
|
3875
|
-
printFramedPhrase(opts.ownerDir, "Recovery phrase (shown once)");
|
|
3876
|
-
return;
|
|
3877
|
-
}
|
|
3878
|
-
(opts.json ? process.stderr : process.stdout).write(`Recovery phrase file: ${opts.phrasePath}\n${PHRASE_INSTRUCTION}\n`);
|
|
3879
|
-
}
|
|
3880
|
-
//#endregion
|
|
3881
4963
|
//#region src/commands/onboard.ts
|
|
3882
4964
|
function registerOnboard(program) {
|
|
3883
4965
|
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
4966
|
const exposure = exposurePreset(opts.exposure);
|
|
3885
4967
|
const profile = gOpts.profile ?? DEFAULT_PROFILE;
|
|
3886
|
-
const
|
|
4968
|
+
const dir = resolveConfigDir();
|
|
4969
|
+
const dirs = custodyDirsOf(dir);
|
|
3887
4970
|
const apiUrl = resolveApiUrl();
|
|
3888
4971
|
if (!validateSlug(opts.slug)) {
|
|
3889
4972
|
printError("Invalid slug: must be 2-32 lowercase alphanumeric characters or hyphens, no leading/trailing hyphen");
|
|
@@ -3891,9 +4974,13 @@ function registerOnboard(program) {
|
|
|
3891
4974
|
return;
|
|
3892
4975
|
}
|
|
3893
4976
|
if (resolveAuth(dirs, gOpts.profile) !== void 0) {
|
|
3894
|
-
const { client } = await createClient(
|
|
4977
|
+
const { client } = await createClient({
|
|
4978
|
+
apiUrl,
|
|
4979
|
+
dir,
|
|
4980
|
+
profile: gOpts.profile
|
|
4981
|
+
});
|
|
3895
4982
|
const { org } = await client.get("/whoami");
|
|
3896
|
-
const agents = await client.get("/agents");
|
|
4983
|
+
const agents = await client.asAdmin().get("/agents");
|
|
3897
4984
|
if (gOpts.json) printJson({
|
|
3898
4985
|
status: "already_registered",
|
|
3899
4986
|
org,
|
|
@@ -3909,22 +4996,16 @@ function registerOnboard(program) {
|
|
|
3909
4996
|
}
|
|
3910
4997
|
return;
|
|
3911
4998
|
}
|
|
3912
|
-
|
|
3913
|
-
const progressStream = gOpts.json ? process.stderr : process.stdout;
|
|
3914
|
-
const reg = await performRegistration(apiUrl, dirs, profile, {
|
|
4999
|
+
const reg = await registerOrg$1(apiUrl, dirs, profile, {
|
|
3915
5000
|
email: opts.email,
|
|
3916
5001
|
slug: opts.slug,
|
|
3917
5002
|
name: opts.name
|
|
3918
|
-
},
|
|
3919
|
-
|
|
5003
|
+
}, gOpts.json);
|
|
5004
|
+
const { client } = await createClient({
|
|
5005
|
+
apiUrl,
|
|
5006
|
+
dir,
|
|
5007
|
+
profile: gOpts.profile
|
|
3920
5008
|
});
|
|
3921
|
-
progressStream.write("\rSolving PoW challenge: 100%\n");
|
|
3922
|
-
announcePhrase({
|
|
3923
|
-
ownerDir: dirs.ownerDir,
|
|
3924
|
-
phrasePath: reg.phrase_path,
|
|
3925
|
-
json: gOpts.json
|
|
3926
|
-
});
|
|
3927
|
-
const { client } = await createClient(apiUrl, gOpts.profile);
|
|
3928
5009
|
const agent = await performAgentCreation(client, dirs, profile, {
|
|
3929
5010
|
name: opts.agentName,
|
|
3930
5011
|
humanOversight: opts.humanOversight,
|
|
@@ -3943,7 +5024,7 @@ function registerOnboard(program) {
|
|
|
3943
5024
|
poll_url: agent.poll_url,
|
|
3944
5025
|
identity: agent.identity,
|
|
3945
5026
|
identity_error: agent.identityError,
|
|
3946
|
-
config_dir:
|
|
5027
|
+
config_dir: dir.shown,
|
|
3947
5028
|
owner_dir: dirs.ownerDir
|
|
3948
5029
|
});
|
|
3949
5030
|
else {
|
|
@@ -4003,9 +5084,9 @@ const NO_ROOT = "Creating a branch needs this org's root key (root.key in the ow
|
|
|
4003
5084
|
function registerOrgBranch(org, program) {
|
|
4004
5085
|
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
5086
|
registerBranchHold(branch, program);
|
|
4006
|
-
branch.command("create <name>").description("Create a branch and seal its bundle to a recipient key").requiredOption("--to <recipient-key>", "The partner's recipient key").option("--out <file>", "Where to write the sealed bundle").option("--words-confirmed", "Skip the interactive word comparison").action(withClient(program, async ({ client, gOpts,
|
|
5087
|
+
branch.command("create <name>").description("Create a branch and seal its bundle to a recipient key").requiredOption("--to <recipient-key>", "The partner's recipient key").option("--out <file>", "Where to write the sealed bundle").option("--words-confirmed", "Skip the interactive word comparison").action(withClient(program, async ({ client, gOpts, custody }, name, opts) => {
|
|
4007
5088
|
assertBranchName(name);
|
|
4008
|
-
const org = loadOrgFromOwner(ownerDir);
|
|
5089
|
+
const org = loadOrgFromOwner(custody().ownerDir);
|
|
4009
5090
|
if (org === void 0) {
|
|
4010
5091
|
printError(NO_ROOT);
|
|
4011
5092
|
process.exitCode = 2;
|
|
@@ -4085,13 +5166,14 @@ async function createWithKey(ctx, opts, publicKey) {
|
|
|
4085
5166
|
else printText(created(delegate));
|
|
4086
5167
|
}
|
|
4087
5168
|
async function create(ctx, opts) {
|
|
4088
|
-
const { client, gOpts,
|
|
5169
|
+
const { client, gOpts, dirs, custody, auth } = ctx;
|
|
5170
|
+
const { configDir } = dirs;
|
|
4089
5171
|
if (!NAME_RE.test(opts.name)) throw new Error("--name must be lowercase letters, digits and dashes, at most 32 characters.");
|
|
4090
5172
|
if (opts.publicKey !== void 0) return createWithKey(ctx, opts, opts.publicKey);
|
|
4091
5173
|
const scopes = parseScopes(opts.scope);
|
|
4092
5174
|
const orgId = auth?.orgId;
|
|
4093
5175
|
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.`);
|
|
5176
|
+
if (getProfile(configDir, opts.name) ?? getProfile(custody().ownerDir, opts.name)) throw new Error(`A profile named '${opts.name}' already exists.`);
|
|
4095
5177
|
const key = newDelegateKey();
|
|
4096
5178
|
const delegate = await createDelegate(client, opts.name, scopes, key.publicKey);
|
|
4097
5179
|
try {
|
|
@@ -4138,7 +5220,7 @@ async function revoke(ctx, ref) {
|
|
|
4138
5220
|
else printText(`Delegated key ${id} revoked. Its next request is refused; tokens it already holds stop working with it.`);
|
|
4139
5221
|
}
|
|
4140
5222
|
function registerOrgDelegate(org, program) {
|
|
4141
|
-
const delegate = org.command("delegate").description("Delegated keys
|
|
5223
|
+
const delegate = org.command("delegate").description("Delegated keys limited to the scopes you give: read events or metadata, write allow and block entries or rules, suspend, freeze, resume");
|
|
4142
5224
|
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
5225
|
delegate.command("list").description("List delegated keys").action(withClient(program, async ({ client, gOpts }) => {
|
|
4144
5226
|
const all = await listDelegates(client);
|
|
@@ -4959,6 +6041,50 @@ function registerOrgEventsTail(org, program) {
|
|
|
4959
6041
|
}));
|
|
4960
6042
|
}
|
|
4961
6043
|
//#endregion
|
|
6044
|
+
//#region src/commands/org-counterparties-notes.ts
|
|
6045
|
+
/** What `org counterparties allow|block` tells the caller before it writes: the entry's reach and its limits. */
|
|
6046
|
+
const RULE_OF = {
|
|
6047
|
+
[RuleDirection.Inbound]: PolicyRule.ExternalInbound,
|
|
6048
|
+
[RuleDirection.Outbound]: PolicyRule.ExternalOutbound
|
|
6049
|
+
};
|
|
6050
|
+
/** The way to turn a rule on that leaves the entry doing what its decision means. */
|
|
6051
|
+
function enforceHint(rule, decision) {
|
|
6052
|
+
return decision === Decision.Block ? `A block list works under enforce with the default allow: rine org rules set ${rule} enforce --default allow.` : `Enforce with the default deny refuses every organisation without an allow entry, so run rine org rules preview ${rule} first, then rine org rules set ${rule} enforce (--default allow|deny).`;
|
|
6053
|
+
}
|
|
6054
|
+
/**
|
|
6055
|
+
* Lines for each chosen direction whose rule is not enforced (the entry decides nothing yet), then the
|
|
6056
|
+
* whole-organisation line. `policy` is `undefined` when the key cannot read it: the rule notes are skipped.
|
|
6057
|
+
*/
|
|
6058
|
+
function entryNotes(policy, directions, decision, ref, theirAgent) {
|
|
6059
|
+
const notes = [];
|
|
6060
|
+
for (const direction of directions) {
|
|
6061
|
+
const rule = RULE_OF[direction];
|
|
6062
|
+
const mode = policy?.rules[rule].mode;
|
|
6063
|
+
if (mode !== void 0 && mode !== RuleMode.Enforce) notes.push(`${rule} is ${mode}, so this entry has no effect until the rule is enforce. ${enforceHint(rule, decision)}`);
|
|
6064
|
+
}
|
|
6065
|
+
if (ref.indexOf("@") > 0 && theirAgent === void 0) notes.push(`${ref} is an agent handle: this entry covers its whole organisation. Add --their-agent ${ref} to cover only that agent.`);
|
|
6066
|
+
return notes;
|
|
6067
|
+
}
|
|
6068
|
+
/** The policy, or `undefined` when the key lacks `policy:write`: a `counterparty:write` key still writes entries. */
|
|
6069
|
+
async function readPolicy(read) {
|
|
6070
|
+
try {
|
|
6071
|
+
return await read();
|
|
6072
|
+
} catch (err) {
|
|
6073
|
+
if (err instanceof RineApiError && err.status === 403) return void 0;
|
|
6074
|
+
throw err;
|
|
6075
|
+
}
|
|
6076
|
+
}
|
|
6077
|
+
const NOT_FOUND = "Counterparty not found. A slug resolves only for an organisation your agents have already exchanged messages with, and a new one can take a minute to appear; an agent handle or the organisation id resolves for any live organisation.";
|
|
6078
|
+
/** Awaits the lookup, rewording its 404 with the way out; any other error passes unchanged. */
|
|
6079
|
+
async function withMissHint(lookup) {
|
|
6080
|
+
try {
|
|
6081
|
+
return await lookup;
|
|
6082
|
+
} catch (err) {
|
|
6083
|
+
if (err instanceof RineApiError && err.status === 404) throw new Error(NOT_FOUND);
|
|
6084
|
+
throw err;
|
|
6085
|
+
}
|
|
6086
|
+
}
|
|
6087
|
+
//#endregion
|
|
4962
6088
|
//#region src/commands/org-rules-words.ts
|
|
4963
6089
|
/** The text `rine org rules` prints in one place. */
|
|
4964
6090
|
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.";
|
|
@@ -5038,60 +6164,28 @@ const STANDING = {
|
|
|
5038
6164
|
"funnel hooks"
|
|
5039
6165
|
],
|
|
5040
6166
|
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;
|
|
6167
|
+
"agents_above_ceiling",
|
|
6168
|
+
"agent",
|
|
6169
|
+
"agents"
|
|
6170
|
+
]
|
|
6171
|
+
};
|
|
6172
|
+
/** What stands outside a rule that was just set, or `undefined` when nothing does. */
|
|
6173
|
+
function existingLine(policy, rule) {
|
|
6174
|
+
const standing = STANDING[rule];
|
|
6175
|
+
if (standing === void 0) return void 0;
|
|
6176
|
+
const n = policy.existing[standing[0]];
|
|
6177
|
+
if (n === 0) return void 0;
|
|
6178
|
+
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}`;
|
|
5091
6179
|
}
|
|
5092
|
-
/**
|
|
5093
|
-
function
|
|
5094
|
-
if (
|
|
6180
|
+
/** The lines reporting what a stop-existing action stopped. */
|
|
6181
|
+
function stoppedLines(r) {
|
|
6182
|
+
if (r.rule === PolicyRule.WebhookHosts) return [`Stopped ${r.stopped} webhooks.`];
|
|
6183
|
+
if (r.rule === PolicyRule.Funnel) {
|
|
6184
|
+
const lines = [`Removed ${r.stopped} funnel hooks.`];
|
|
6185
|
+
if (r.remaining > 0) lines.push(`${r.remaining} funnel hooks remain. Run the command again to remove them.`);
|
|
6186
|
+
return lines;
|
|
6187
|
+
}
|
|
6188
|
+
return [`Lowered ${r.stopped} agents to the rule's limit.`];
|
|
5095
6189
|
}
|
|
5096
6190
|
//#endregion
|
|
5097
6191
|
//#region src/commands/org-counterparties-write.ts
|
|
@@ -5115,8 +6209,8 @@ async function openGroups(ctx) {
|
|
|
5115
6209
|
}
|
|
5116
6210
|
}
|
|
5117
6211
|
/** The counterparty write, plus the group check with `--groups`. */
|
|
5118
|
-
async function describe(ctx, ref, groups) {
|
|
5119
|
-
const c = await lookupCounterparty(ctx.client, ref);
|
|
6212
|
+
async function describe(ctx, ref, groups, policy) {
|
|
6213
|
+
const c = await withMissHint(lookupCounterparty(ctx.client, ref));
|
|
5120
6214
|
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
6215
|
const lines = [
|
|
5122
6216
|
`${c.name} org ${c.org_id.slice(0, 8)}… tier ${c.tier}`,
|
|
@@ -5124,10 +6218,7 @@ async function describe(ctx, ref, groups) {
|
|
|
5124
6218
|
`Check this code with a contact at ${c.name}:`,
|
|
5125
6219
|
` ${orgWords(c.org_id)}`
|
|
5126
6220
|
];
|
|
5127
|
-
if (groups)
|
|
5128
|
-
const covered = (await getPolicy(ctx.client)).groups_covered;
|
|
5129
|
-
lines.push(groupsAllowLine(await openGroups(ctx), covered));
|
|
5130
|
-
}
|
|
6221
|
+
if (groups) lines.push(groupsAllowLine(await openGroups(ctx), policy?.groups_covered ?? false));
|
|
5131
6222
|
if (!ctx.gOpts.json) for (const l of lines) printText(l);
|
|
5132
6223
|
return c.org_id;
|
|
5133
6224
|
}
|
|
@@ -5138,13 +6229,15 @@ async function theirAgentId(ctx, ref) {
|
|
|
5138
6229
|
}
|
|
5139
6230
|
function decide(program, parent, decision) {
|
|
5140
6231
|
const verb = decision === Decision.Allow ? "Allow" : "Block";
|
|
5141
|
-
const cmd = parent.command(decision).description(`${verb} an organisation
|
|
6232
|
+
const cmd = parent.command(decision).description(`${verb} an organisation in the message rules. An agent handle covers its whole organisation; to ${decision} only one agent, also pass its handle, e.g. --their-agent kofi@acme.rine.network`).argument("<ref>", "Organisation id, an agent handle (its whole organisation), or the slug of an organisation you have dealt with. Use the handle your contact gave you, or confirm a directory match with the user").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 this agent of the organisation, not the whole organisation").requiredOption("--reason <text>", "Why, required; kept with the entry").option("--yes", decision === Decision.Allow ? "Skip confirmation prompt, including the check-code confirmation: compare the code with your contact first" : "Skip confirmation prompt");
|
|
5142
6233
|
if (decision === Decision.Allow) cmd.option("--groups", "Also let it join your open groups once the group rule is on");
|
|
5143
6234
|
cmd.action(withClient(program, async (ctx, ref, opts) => {
|
|
6235
|
+
if (ctx.gOpts.json && !opts.yes) throw new Error("--json needs --yes: JSON output shows no confirmation or check code. Run it without --json to see them; add --yes only once the person has compared the code with their contact.");
|
|
5144
6236
|
const directions = directionsOf(opts);
|
|
5145
|
-
|
|
5146
|
-
const orgId = await describe(ctx, ref, opts.groups === true);
|
|
5147
|
-
if (!
|
|
6237
|
+
const policy = ctx.gOpts.json && opts.groups !== true ? void 0 : await readPolicy(() => getPolicy(ctx.client));
|
|
6238
|
+
const orgId = await describe(ctx, ref, opts.groups === true, policy);
|
|
6239
|
+
if (!ctx.gOpts.json) for (const note of entryNotes(policy, directions, decision, ref, opts.theirAgent)) printText(note);
|
|
6240
|
+
if (!opts.yes) {
|
|
5148
6241
|
if (!await promptConfirm(`${verb} ${directions.join(" and ")}?`)) return;
|
|
5149
6242
|
}
|
|
5150
6243
|
const ours = opts.agent && await resolveAgent$1(ctx, opts.agent);
|
|
@@ -5169,8 +6262,7 @@ function decide(program, parent, decision) {
|
|
|
5169
6262
|
function registerCounterpartyWrites(counterparties, program) {
|
|
5170
6263
|
decide(program, counterparties, Decision.Allow);
|
|
5171
6264
|
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();
|
|
6265
|
+
counterparties.command("remove <id>").description("Remove an allow or block entry (an id from `counterparties entries`)").requiredOption("--reason <text>", "Why, required; kept with the entry").option("--yes", "Accepted and ignored: remove never prompts").action(withClient(program, async ({ client, gOpts }, id, opts) => {
|
|
5174
6266
|
await deleteAllow(client, id, opts.reason);
|
|
5175
6267
|
printMutationOk("Entry removed", gOpts.json);
|
|
5176
6268
|
}));
|
|
@@ -5182,6 +6274,7 @@ function registerCounterpartyWrites(counterparties, program) {
|
|
|
5182
6274
|
Direction: e.direction,
|
|
5183
6275
|
Decision: e.decision,
|
|
5184
6276
|
Org: e.counterparty_org_id,
|
|
6277
|
+
"Their agent": e.counterparty_agent_id ?? "any",
|
|
5185
6278
|
Scope: e.scope_agent_id ?? "org",
|
|
5186
6279
|
Groups: e.groups ? "yes" : "no",
|
|
5187
6280
|
Reason: e.reason
|
|
@@ -5205,7 +6298,7 @@ async function listAll(ctx) {
|
|
|
5205
6298
|
return all;
|
|
5206
6299
|
}
|
|
5207
6300
|
function registerOrgCounterparties(org, program) {
|
|
5208
|
-
registerCounterpartyWrites(org.command("counterparties").description("
|
|
6301
|
+
registerCounterpartyWrites(org.command("counterparties").description("Allow or block other organisations and their agents in the message rules, and list who your agents talk to").action(withClient(program, async (ctx) => {
|
|
5209
6302
|
const all = await listAll(ctx);
|
|
5210
6303
|
const since = Date.now() - WEEK_MS;
|
|
5211
6304
|
const fresh = all.filter((c) => Date.parse(c.first_seen) >= since);
|
|
@@ -5390,11 +6483,11 @@ function registerOrgRecover(org, program) {
|
|
|
5390
6483
|
org.command("recover").description("Rebuild this device from the 24-word recovery phrase").option("--owner-only", "Write only the org root and profile into the owner directory: no request, no leaf keys, no group reseat").action(withErrorHandler(program, async (gOpts, opts) => {
|
|
5391
6484
|
const profile = gOpts.profile ?? DEFAULT_PROFILE;
|
|
5392
6485
|
if (opts.ownerOnly) {
|
|
5393
|
-
await restoreOwnerOnly(
|
|
6486
|
+
await restoreOwnerOnly(resolveCustodyDirs(), profile, gOpts.json);
|
|
5394
6487
|
return;
|
|
5395
6488
|
}
|
|
5396
6489
|
const phrase = await readPhrase();
|
|
5397
|
-
const report = await performRecovery(resolveApiUrl(),
|
|
6490
|
+
const report = await performRecovery(resolveApiUrl(), resolveCustodyDirs(), profile, phrase, (words) => (gOpts.json ? console.error : console.log)(`Org verification words: ${words}`));
|
|
5398
6491
|
if (gOpts.json) printJson(report);
|
|
5399
6492
|
else renderReport(report);
|
|
5400
6493
|
if (report.agents.some((agent) => agent.status === "mismatch")) process.exitCode = 1;
|
|
@@ -5405,7 +6498,7 @@ function registerOrgRecover(org, program) {
|
|
|
5405
6498
|
process.exitCode = 2;
|
|
5406
6499
|
return;
|
|
5407
6500
|
}
|
|
5408
|
-
printFramedPhrase(
|
|
6501
|
+
printFramedPhrase(resolveCustodyDirs().ownerDir, "Recovery phrase");
|
|
5409
6502
|
}));
|
|
5410
6503
|
}
|
|
5411
6504
|
//#endregion
|
|
@@ -5472,11 +6565,10 @@ async function patchOf(ctx, policy, rule, mode, opts) {
|
|
|
5472
6565
|
}
|
|
5473
6566
|
}
|
|
5474
6567
|
function registerRulesSet(rules, program) {
|
|
5475
|
-
rules.command("set <rule> <mode>").description("Set a rule's mode
|
|
6568
|
+
rules.command("set <rule> <mode>").description("Set a rule's mode: external_inbound, external_outbound and external_groups take off|report|enforce; new_agents, directory_listing, webhook_hosts, funnel and acting_as take off|enforce").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").option("--yes", "Accepted and ignored: set never prompts").action(withClient(program, async (ctx, ruleName, modeName, opts) => {
|
|
5476
6569
|
const rule = pick("rule", Object.values(PolicyRule), ruleName);
|
|
5477
6570
|
const mode = pick(`${rule} mode`, RULE_MODES[rule], modeName);
|
|
5478
6571
|
onlyWhereApplicable(rule, opts);
|
|
5479
|
-
warnInAgentRuntime();
|
|
5480
6572
|
const current = await getPolicy(ctx.client);
|
|
5481
6573
|
const policy = await patchRules(ctx.client, current.version, await patchOf(ctx, current, rule, mode, opts));
|
|
5482
6574
|
if (ctx.gOpts.json) return printJson(policy);
|
|
@@ -5529,9 +6621,7 @@ function registerOrgRules(org, program) {
|
|
|
5529
6621
|
for (const line of previewLines$1(preview)) printText(line);
|
|
5530
6622
|
}));
|
|
5531
6623
|
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
|
|
5533
|
-
warnInAgentRuntime();
|
|
5534
|
-
const result = await stopExisting(client, rule);
|
|
6624
|
+
const result = await stopExisting(client, ruleArg(name, STOPPABLE));
|
|
5535
6625
|
if (gOpts.json) return printJson(result);
|
|
5536
6626
|
for (const line of stoppedLines(result)) printText(line);
|
|
5537
6627
|
}));
|
|
@@ -5583,42 +6673,56 @@ function registerOrg(program) {
|
|
|
5583
6673
|
}));
|
|
5584
6674
|
}
|
|
5585
6675
|
//#endregion
|
|
6676
|
+
//#region src/commands/pay-confirm.ts
|
|
6677
|
+
/** True when the payment may go ahead: no reason to ask, or a person said yes. */
|
|
6678
|
+
async function confirmPayment(reason, req, payeeAgentId) {
|
|
6679
|
+
if (reason === null) return true;
|
|
6680
|
+
if (process.stdin.isTTY !== true) {
|
|
6681
|
+
printError(`Payment refused (${reason}): ${PAY_CONFIRM_WHY[reason]}. Approve it by running 'rine pay' in a terminal.`);
|
|
6682
|
+
return false;
|
|
6683
|
+
}
|
|
6684
|
+
console.error(`This payment needs your yes: ${PAY_CONFIRM_WHY[reason]}.`);
|
|
6685
|
+
console.error(` Amount: ${requirementAmount(req)} (atomic units)`);
|
|
6686
|
+
console.error(` Asset: ${req.asset}`);
|
|
6687
|
+
console.error(` Network: ${req.network}`);
|
|
6688
|
+
console.error(` Payee: agent ${payeeAgentId}, wallet ${req.payTo}`);
|
|
6689
|
+
const yes = await promptConfirm("Pay this quote?");
|
|
6690
|
+
if (!yes) printError("Payment not sent.");
|
|
6691
|
+
return yes;
|
|
6692
|
+
}
|
|
6693
|
+
//#endregion
|
|
6694
|
+
//#region src/commands/pay-preflight.ts
|
|
6695
|
+
/** Exit codes of a refused payment: the message is no quote, or the quote cannot be paid from here. */
|
|
6696
|
+
const NOT_A_QUOTE_EXIT = 2;
|
|
6697
|
+
const UNPAYABLE_EXIT = 1;
|
|
6698
|
+
/** The payee agent id of a payable quote, or the refusal. */
|
|
6699
|
+
function payPreflight(message, messageId, payerAgentId, configDir) {
|
|
6700
|
+
const refuse = (text, exitCode = UNPAYABLE_EXIT) => ({ refusal: {
|
|
6701
|
+
message: text,
|
|
6702
|
+
exitCode
|
|
6703
|
+
} });
|
|
6704
|
+
if (message.type !== X402_MESSAGE_TYPE.PAYMENT_REQUIRED) return refuse(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT_REQUIRED}. Nothing to pay.`, NOT_A_QUOTE_EXIT);
|
|
6705
|
+
const payeeAgentId = message.from_agent_id;
|
|
6706
|
+
if (!payeeAgentId) return refuse("Cannot pay: the quote has no resolvable sender agent.");
|
|
6707
|
+
if (payeeAgentId === payerAgentId) return refuse("Cannot pay your own quote.");
|
|
6708
|
+
if (message.to_agent_id && message.to_agent_id !== payerAgentId) return refuse(`Quote ${messageId} is addressed to agent ${message.to_agent_id}, not ${payerAgentId}. Pay as that agent (--agent), or ask the payee to re-issue the quote to this one.`);
|
|
6709
|
+
if (!agentKeysExist(configDir, payerAgentId)) return refuse(`No E2EE keys for agent ${payerAgentId}. Run 'rine org recover' to restore this agent's keys.`);
|
|
6710
|
+
if (!walletKeyExists(configDir, payerAgentId)) return refuse(`No payment wallet for agent ${payerAgentId}. Run 'rine wallet create' first.`);
|
|
6711
|
+
return { payeeAgentId };
|
|
6712
|
+
}
|
|
6713
|
+
//#endregion
|
|
5586
6714
|
//#region src/commands/pay.ts
|
|
5587
6715
|
function registerPay(program) {
|
|
5588
|
-
program.command("pay").description("Pay an in-thread x402 payment_required (sign + reply with x402_payment)").argument("<message-id>", "ID of the received rine.v1.x402_payment_required").addOption(actorOption("which agent is acting, as payer (name, handle, or agent ID)")).option("--auto-pay", "Only pay when the quote is at/below the wallet autoPayThreshold").option("--force", "Re-pay a quote already paid today (bypasses the once-per-message guard)").option("--no-marker", "Omit the cleartext status marker (fully sealed)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, messageId, opts) => {
|
|
6716
|
+
program.command("pay").description("Pay an in-thread x402 payment_required (sign + reply with x402_payment)").argument("<message-id>", "ID of the received rine.v1.x402_payment_required").addOption(actorOption("which agent is acting, as payer (name, handle, or agent ID)")).option("--auto-pay", "Only pay when the quote is at/below the wallet autoPayThreshold").option("--force", "Re-pay a quote already paid today (bypasses the once-per-message guard)").option("--no-marker", "Omit the cleartext status marker (fully sealed)").action(withClient(program, async ({ client, gOpts, dirs: { configDir }, actingAgent }, messageId, opts) => {
|
|
5589
6717
|
const payerAgentId = await actingAgent();
|
|
5590
6718
|
const message = await client.get(`/messages/${messageId}`);
|
|
5591
|
-
|
|
5592
|
-
|
|
5593
|
-
|
|
5594
|
-
|
|
5595
|
-
}
|
|
5596
|
-
const payeeAgentId = message.from_agent_id;
|
|
5597
|
-
if (!payeeAgentId) {
|
|
5598
|
-
printError("Cannot pay: the quote has no resolvable sender agent.");
|
|
5599
|
-
process.exitCode = 1;
|
|
5600
|
-
return;
|
|
5601
|
-
}
|
|
5602
|
-
if (payeeAgentId === payerAgentId) {
|
|
5603
|
-
printError("Cannot pay your own quote.");
|
|
5604
|
-
process.exitCode = 1;
|
|
5605
|
-
return;
|
|
5606
|
-
}
|
|
5607
|
-
if (message.to_agent_id && message.to_agent_id !== payerAgentId) {
|
|
5608
|
-
printError(`Quote ${messageId} is addressed to agent ${message.to_agent_id}, not ${payerAgentId}. Pay as that agent (--agent), or ask the payee to re-issue the quote to this one.`);
|
|
5609
|
-
process.exitCode = 1;
|
|
5610
|
-
return;
|
|
5611
|
-
}
|
|
5612
|
-
if (!agentKeysExist(configDir, payerAgentId)) {
|
|
5613
|
-
printError(`No E2EE keys for agent ${payerAgentId}. Run 'rine org recover' to restore this agent's keys.`);
|
|
5614
|
-
process.exitCode = 1;
|
|
5615
|
-
return;
|
|
5616
|
-
}
|
|
5617
|
-
if (!walletKeyExists(configDir, payerAgentId)) {
|
|
5618
|
-
printError(`No payment wallet for agent ${payerAgentId}. Run 'rine wallet create' first.`);
|
|
5619
|
-
process.exitCode = 1;
|
|
6719
|
+
const checked = payPreflight(message, messageId, payerAgentId, configDir);
|
|
6720
|
+
if ("refusal" in checked) {
|
|
6721
|
+
printError(checked.refusal.message);
|
|
6722
|
+
process.exitCode = checked.refusal.exitCode;
|
|
5620
6723
|
return;
|
|
5621
6724
|
}
|
|
6725
|
+
const { payeeAgentId } = checked;
|
|
5622
6726
|
const decrypted = await decryptMessage(configDir, payerAgentId, message.encrypted_payload, client, payeeAgentId, payerAgentId, message.created_at);
|
|
5623
6727
|
let pr;
|
|
5624
6728
|
try {
|
|
@@ -5629,30 +6733,27 @@ function registerPay(program) {
|
|
|
5629
6733
|
process.exitCode = 1;
|
|
5630
6734
|
return;
|
|
5631
6735
|
}
|
|
5632
|
-
const
|
|
6736
|
+
const mode = spendPolicyModeFromEnv();
|
|
6737
|
+
const read = await loadPolicyWithTrust(configDir, payerAgentId, client, mode);
|
|
6738
|
+
const policy = read.policy;
|
|
5633
6739
|
const dailySpent = readDailySpent(configDir, payerAgentId);
|
|
5634
6740
|
try {
|
|
5635
6741
|
const requirement = selectRequirement(pr, policy, dailySpent);
|
|
5636
|
-
if (opts.autoPay) {
|
|
5637
|
-
|
|
5638
|
-
|
|
5639
|
-
|
|
5640
|
-
|
|
5641
|
-
|
|
6742
|
+
if (opts.autoPay && !(policy && isAutoPayable(policy, requirement))) {
|
|
6743
|
+
printError("Quote exceeds the auto-pay threshold. Run 'rine pay' without --auto-pay to approve it manually.");
|
|
6744
|
+
process.exitCode = 1;
|
|
6745
|
+
return;
|
|
6746
|
+
}
|
|
6747
|
+
if (!await confirmPayment(paymentConfirmReason(read, requirement, mode, { repay: opts.force === true }), requirement, payeeAgentId)) {
|
|
6748
|
+
process.exitCode = 1;
|
|
6749
|
+
return;
|
|
5642
6750
|
}
|
|
5643
6751
|
const walletKey = loadWalletKey(configDir, payerAgentId);
|
|
5644
6752
|
const built = buildPaymentMessage(buildPaymentPayload(pr, requirement, walletKey, { quoteMessageId: messageId }), { emitMarker: opts.marker !== false });
|
|
5645
|
-
const
|
|
6753
|
+
const body = await sealedX402Body(client, configDir, {
|
|
5646
6754
|
senderAgentId: payerAgentId,
|
|
5647
6755
|
recipientAgentId: payeeAgentId
|
|
5648
|
-
}, built
|
|
5649
|
-
const body = {
|
|
5650
|
-
type: built.type,
|
|
5651
|
-
content_type: built.content_type,
|
|
5652
|
-
payload_schema: built.payload_schema,
|
|
5653
|
-
...encrypted
|
|
5654
|
-
};
|
|
5655
|
-
if (built.metadata) body.metadata = built.metadata;
|
|
6756
|
+
}, built);
|
|
5656
6757
|
await reserveSpend(configDir, payerAgentId, policy, requirement, {
|
|
5657
6758
|
messageId,
|
|
5658
6759
|
force: opts.force
|
|
@@ -5706,7 +6807,7 @@ function registerPay(program) {
|
|
|
5706
6807
|
//#endregion
|
|
5707
6808
|
//#region src/commands/poll-token.ts
|
|
5708
6809
|
function registerPollToken(program) {
|
|
5709
|
-
program.command("poll-token").description("Generate or revoke a poll token for inbox monitoring").addOption(actorOption()).option("--revoke", "Revoke the poll token").action(withClient(program, async ({ client, gOpts, profileName, configDir, actingAgent }, opts) => {
|
|
6810
|
+
program.command("poll-token").description("Generate or revoke a poll token for inbox monitoring").addOption(actorOption()).option("--revoke", "Revoke the poll token").action(withClient(program, async ({ client, gOpts, profileName, dirs: { configDir }, actingAgent }, opts) => {
|
|
5710
6811
|
const agentId = await actingAgent();
|
|
5711
6812
|
if (opts.revoke) {
|
|
5712
6813
|
await client.delete(`/agents/${agentId}/poll-token`);
|
|
@@ -5736,23 +6837,12 @@ function registerPollToken(program) {
|
|
|
5736
6837
|
function registerRegister(program) {
|
|
5737
6838
|
program.command("register").description("Register a new organisation (two-step PoW flow). Writes the org root key and recovery phrase to the owner directory").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organisation name").requiredOption("--slug <slug>", "Organisation slug").action(withErrorHandler(program, async (gOpts, opts) => {
|
|
5738
6839
|
const profile = gOpts.profile ?? DEFAULT_PROFILE;
|
|
5739
|
-
const dirs =
|
|
5740
|
-
const
|
|
5741
|
-
process.stderr.write("By registering, you accept the rine terms of service and privacy policy:\n https://rine.network/terms.html\n https://rine.network/privacy.html\n");
|
|
5742
|
-
const progressStream = gOpts.json ? process.stderr : process.stdout;
|
|
5743
|
-
const reg = await performRegistration(apiUrl, dirs, profile, {
|
|
6840
|
+
const dirs = resolveCustodyDirs();
|
|
6841
|
+
const reg = await registerOrg$1(resolveApiUrl(), dirs, profile, {
|
|
5744
6842
|
email: opts.email,
|
|
5745
6843
|
slug: opts.slug,
|
|
5746
6844
|
name: opts.name
|
|
5747
|
-
},
|
|
5748
|
-
progressStream.write(`\rSolving PoW challenge: ${pct}%`);
|
|
5749
|
-
});
|
|
5750
|
-
progressStream.write("\rSolving PoW challenge: 100%\n");
|
|
5751
|
-
announcePhrase({
|
|
5752
|
-
ownerDir: dirs.ownerDir,
|
|
5753
|
-
phrasePath: reg.phrase_path,
|
|
5754
|
-
json: gOpts.json
|
|
5755
|
-
});
|
|
6845
|
+
}, gOpts.json);
|
|
5756
6846
|
if (gOpts.json) printJson({
|
|
5757
6847
|
org_id: reg.org_id,
|
|
5758
6848
|
org_words: reg.org_words,
|
|
@@ -5767,483 +6857,112 @@ function registerRegister(program) {
|
|
|
5767
6857
|
}));
|
|
5768
6858
|
}
|
|
5769
6859
|
//#endregion
|
|
5770
|
-
//#region src/commands/relay-lifecycle.ts
|
|
5771
|
-
/**
|
|
5772
|
-
* The relay's lifecycle events: one `{event: "lifecycle", data}` JSON line on
|
|
5773
|
-
* stdout under `--json`, nothing otherwise. Events name states and never carry
|
|
5774
|
-
* a request body or the hook secret.
|
|
5775
|
-
*/
|
|
5776
|
-
function emitLifecycle$1(json, data) {
|
|
5777
|
-
if (json) console.log(JSON.stringify({
|
|
5778
|
-
event: "lifecycle",
|
|
5779
|
-
data
|
|
5780
|
-
}));
|
|
5781
|
-
}
|
|
5782
|
-
/** How long a paused relay waits between attempts to re-bind. */
|
|
5783
|
-
const PAUSED_RETRY_MS = 3e4;
|
|
5784
|
-
/** The sentence logged, and carried in the event, when the agent is held. */
|
|
5785
|
-
const PAUSED_MESSAGE = `tunnel paused: the agent is suspended; retrying every ${PAUSED_RETRY_MS / 1e3} s`;
|
|
5786
|
-
//#endregion
|
|
5787
|
-
//#region src/commands/relay-cert.ts
|
|
5788
|
-
/**
|
|
5789
|
-
* The zero-trust wildcard a relay holds: issued on each (re)connect and
|
|
5790
|
-
* re-checked on a standing timer, so a relay that stays connected past the
|
|
5791
|
-
* renewal window still renews.
|
|
5792
|
-
*/
|
|
5793
|
-
const RENEWAL_CHECK_INTERVAL_MS = 720 * 60 * 1e3;
|
|
5794
|
-
function relayCert(deps) {
|
|
5795
|
-
const { configDir, agentId, client, options, json, isStopped } = deps;
|
|
5796
|
-
let lastDeps;
|
|
5797
|
-
let certHandle;
|
|
5798
|
-
let certBusy = false;
|
|
5799
|
-
let renewalTimer;
|
|
5800
|
-
const issue = async (handle, issueDeps) => {
|
|
5801
|
-
certBusy = true;
|
|
5802
|
-
try {
|
|
5803
|
-
return await ensureCert({
|
|
5804
|
-
handle,
|
|
5805
|
-
agentId,
|
|
5806
|
-
delegationId: handle,
|
|
5807
|
-
configDir,
|
|
5808
|
-
options,
|
|
5809
|
-
deps: issueDeps
|
|
5810
|
-
});
|
|
5811
|
-
} finally {
|
|
5812
|
-
certBusy = false;
|
|
5813
|
-
}
|
|
5814
|
-
};
|
|
5815
|
-
const maybeRenewCert = async () => {
|
|
5816
|
-
if (isStopped() || certBusy || !certHandle || !lastDeps) return;
|
|
5817
|
-
const meta = loadMeta(configDir, certHandle, options);
|
|
5818
|
-
if (!meta || !renewalDueWithJitter(meta, certHandle, Date.now())) return;
|
|
5819
|
-
try {
|
|
5820
|
-
await issue(certHandle, lastDeps);
|
|
5821
|
-
emitLifecycle$1(json, {
|
|
5822
|
-
state: "cert_renewed",
|
|
5823
|
-
handle: certHandle
|
|
5824
|
-
});
|
|
5825
|
-
} catch (err) {
|
|
5826
|
-
emitLifecycle$1(json, {
|
|
5827
|
-
state: "cert_renew_error",
|
|
5828
|
-
handle: certHandle,
|
|
5829
|
-
reason: err instanceof Error ? err.message : String(err)
|
|
5830
|
-
});
|
|
5831
|
-
}
|
|
5832
|
-
};
|
|
5833
|
-
return {
|
|
5834
|
-
async ensure(handle) {
|
|
5835
|
-
certHandle = handle;
|
|
5836
|
-
lastDeps = await buildIssueCertDeps({
|
|
5837
|
-
configDir,
|
|
5838
|
-
options,
|
|
5839
|
-
http: client,
|
|
5840
|
-
agentId
|
|
5841
|
-
});
|
|
5842
|
-
return issue(handle, lastDeps);
|
|
5843
|
-
},
|
|
5844
|
-
release() {
|
|
5845
|
-
certHandle = void 0;
|
|
5846
|
-
},
|
|
5847
|
-
startRenewalTimer() {
|
|
5848
|
-
if (renewalTimer) return;
|
|
5849
|
-
renewalTimer = setInterval(() => {
|
|
5850
|
-
maybeRenewCert();
|
|
5851
|
-
}, RENEWAL_CHECK_INTERVAL_MS);
|
|
5852
|
-
renewalTimer.unref?.();
|
|
5853
|
-
},
|
|
5854
|
-
stop() {
|
|
5855
|
-
if (renewalTimer) clearInterval(renewalTimer);
|
|
5856
|
-
}
|
|
5857
|
-
};
|
|
5858
|
-
}
|
|
5859
|
-
//#endregion
|
|
5860
6860
|
//#region src/commands/relay-hook.ts
|
|
5861
6861
|
/**
|
|
5862
|
-
* The relay's view of its hook: the options that name it
|
|
5863
|
-
*
|
|
6862
|
+
* The relay's view of its hook as the CLI knows it: the options that name it and
|
|
6863
|
+
* the secret that verifies it. The server row, the tier and the DNS check live
|
|
6864
|
+
* in rine-core's `runRelay`.
|
|
5864
6865
|
*/
|
|
5865
6866
|
/**
|
|
5866
6867
|
* Resolve the HMAC secret: --secret-env > --secret-file > the persisted file.
|
|
5867
6868
|
* Returns "" (after a stderr warning naming the three sources tried) when none is
|
|
5868
6869
|
* found. An empty secret is NOT safe to run with: an attacker who controls the
|
|
5869
6870
|
* body can compute `HMAC("", body)` and forge a "verified" self-send, so the
|
|
5870
|
-
* caller (
|
|
6871
|
+
* caller (relay.ts) HARD-REFUSES to start on an empty result — the relay never
|
|
5871
6872
|
* enters the reconnect loop or opens the listener without a secret.
|
|
5872
6873
|
*/
|
|
5873
|
-
function resolveSecret(opts,
|
|
6874
|
+
function resolveSecret(opts, dir, agentId) {
|
|
5874
6875
|
if (opts.secretEnv) {
|
|
5875
6876
|
const v = process.env[opts.secretEnv];
|
|
5876
6877
|
if (v) return v.trim();
|
|
5877
6878
|
}
|
|
5878
6879
|
if (opts.secretFile) return readFileSync(opts.secretFile, "utf-8").trim();
|
|
5879
|
-
const stored = loadHookSecret(
|
|
6880
|
+
const stored = loadHookSecret(dir.path, agentId, opts.hook);
|
|
5880
6881
|
if (stored) return stored;
|
|
5881
|
-
process.stderr.write(`No hook secret found (tried --secret-env, --secret-file, and ${
|
|
6882
|
+
process.stderr.write(`No hook secret found (tried --secret-env, --secret-file, and ${dir.shown}/funnel/${agentId}/${opts.hook}.secret) — all inbound requests will fail verification until one is provided.\n`);
|
|
5882
6883
|
return "";
|
|
5883
6884
|
}
|
|
5884
6885
|
/**
|
|
5885
|
-
* The
|
|
5886
|
-
*
|
|
5887
|
-
* into the BIND and (via its agent label) the cert CN/SAN; its `control_ws_url`
|
|
5888
|
-
* is the broker control-WS endpoint the relay dials; its `termination` is the
|
|
5889
|
-
* tier. NEITHER is reconstructed client-side: a fabricated name matches no
|
|
5890
|
-
* funnel_hook row (BIND would NAK, the cert would never match GitHub's TLS), and
|
|
5891
|
-
* the API base resolves to the primary IP / Caddy, which has no funnel route. On
|
|
5892
|
-
* a missing row or a transient lookup failure we THROW so the loop backs off and
|
|
5893
|
-
* retries.
|
|
5894
|
-
*/
|
|
5895
|
-
async function resolveHook(client, agentId, hookName) {
|
|
5896
|
-
const hook = (await client.get(`/agents/${agentId}/funnel/hooks`, {}))?.items?.find((h) => h.hook_name === hookName);
|
|
5897
|
-
if (!hook?.hostname || !hook.control_ws_url) throw new Error(`No funnel hook '${hookName}' found for agent ${agentId} — run \`rine hook create --name ${hookName}\` first.`);
|
|
5898
|
-
return hook;
|
|
5899
|
-
}
|
|
5900
|
-
/**
|
|
5901
|
-
* Fatal — this build implements the zero-trust and shared-edge tiers; an UNKNOWN
|
|
5902
|
-
* `termination` value from a newer backend is thrown (not retried) so the relay
|
|
5903
|
-
* never enters a backoff loop it cannot escape. Upgrade the CLI to serve it.
|
|
5904
|
-
*/
|
|
5905
|
-
var UnsupportedTierError = class extends Error {
|
|
5906
|
-
constructor(tier) {
|
|
5907
|
-
super(`This hook uses a TLS-termination mode ('${tier}') this relay build does not support. Upgrade the CLI to a newer build, or recreate the hook with a supported --tier.`);
|
|
5908
|
-
this.name = "UnsupportedTierError";
|
|
5909
|
-
}
|
|
5910
|
-
};
|
|
5911
|
-
/**
|
|
5912
|
-
* Assert the zero-trust hostname resolves to an A record before
|
|
5913
|
-
* declaring the listener ready. The per-agent `*.{agentLabel}.hook` A is a
|
|
5914
|
-
* DELIVERY prerequisite written best-effort by the backend; a
|
|
5915
|
-
* healthy cert does NOT imply a routable name (DNS-01 validates the independent
|
|
5916
|
-
* challenge TXT). Non-fatal — emit a loud `dns_a_missing` event and continue (the
|
|
5917
|
-
* cert is valid and the backend self-heals the A on the next ZT-hook create), so
|
|
5918
|
-
* a missing A is surfaced rather than a silent black hole.
|
|
5919
|
-
*/
|
|
5920
|
-
async function assertAgentARecord(hostname, json) {
|
|
5921
|
-
try {
|
|
5922
|
-
if ((await resolve4(hostname)).length === 0) emitLifecycle$1(json, {
|
|
5923
|
-
state: "dns_a_missing",
|
|
5924
|
-
hostname
|
|
5925
|
-
});
|
|
5926
|
-
} catch {
|
|
5927
|
-
emitLifecycle$1(json, {
|
|
5928
|
-
state: "dns_a_missing",
|
|
5929
|
-
hostname
|
|
5930
|
-
});
|
|
5931
|
-
}
|
|
5932
|
-
}
|
|
5933
|
-
/**
|
|
5934
|
-
* Parse --port into a valid TCP port. `0` is accepted as "OS-assign an ephemeral
|
|
5935
|
-
* port", never coerced to the default; a non-integer or out-of-range value
|
|
5936
|
-
* throws a clear error rather than silently falling back. The default flag
|
|
5937
|
-
* value "8443" parses straight through.
|
|
5938
|
-
*/
|
|
5939
|
-
function parsePort(raw) {
|
|
5940
|
-
const port = Number(raw);
|
|
5941
|
-
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`Invalid --port '${raw}': expected an integer 0-65535.`);
|
|
5942
|
-
return port;
|
|
5943
|
-
}
|
|
5944
|
-
//#endregion
|
|
5945
|
-
//#region src/commands/relay-reconnect.ts
|
|
5946
|
-
/** How the relay loop reads a dropped or refused tunnel, and how it waits to retry. */
|
|
5947
|
-
/**
|
|
5948
|
-
* End the relay on a revoked binding. It does NOT revoke or wipe the per-agent wildcard: that is
|
|
5949
|
-
* SHARED across every other live hook of the agent, so wiping it would kill all of them. The kill
|
|
5950
|
-
* switch is server-side DNS+route teardown; the relay just exits.
|
|
5951
|
-
*/
|
|
5952
|
-
function exitRevoked(cert, json) {
|
|
5953
|
-
cert.stop();
|
|
5954
|
-
emitLifecycle$1(json, { state: "tunnel_revoked" });
|
|
5955
|
-
process.exitCode = 1;
|
|
5956
|
-
}
|
|
5957
|
-
function isRevoked(err) {
|
|
5958
|
-
return typeof err === "object" && err !== null && err.revoked === true;
|
|
5959
|
-
}
|
|
5960
|
-
/** Emit an error reconnect, wait its jittered delay, and return the next backoff. */
|
|
5961
|
-
async function reconnectAfterError(json, attempt, backoff, afterEmit) {
|
|
5962
|
-
const delay = jitteredDelayMs(backoff);
|
|
5963
|
-
emitLifecycle$1(json, {
|
|
5964
|
-
state: "tunnel_reconnecting",
|
|
5965
|
-
attempt: attempt + 1,
|
|
5966
|
-
backoff_ms: delay,
|
|
5967
|
-
reason: "error"
|
|
5968
|
-
});
|
|
5969
|
-
afterEmit?.();
|
|
5970
|
-
await sleep(delay);
|
|
5971
|
-
return nextReconnectBackoffSeconds(backoff);
|
|
5972
|
-
}
|
|
5973
|
-
/**
|
|
5974
|
-
* Resolve when the tunnel WS closes (carrying the classified close so the caller
|
|
5975
|
-
* can pick clean-vs-error reconnect) OR the stop handed to `setStop` runs on
|
|
5976
|
-
* SIGINT (resolves `undefined`; the caller's `stopped` flag short-circuits
|
|
5977
|
-
* before the reconnect branch). A 4423 close (the agent is held) rejects.
|
|
6886
|
+
* The CLI's words for a refusal `runRelay` threw before the relay started: the core
|
|
6887
|
+
* sentences are surface-neutral, so the two that name a CLI remedy are reworded here.
|
|
5978
6888
|
*/
|
|
5979
|
-
function
|
|
5980
|
-
return
|
|
5981
|
-
|
|
5982
|
-
|
|
5983
|
-
setStop(() => {
|
|
5984
|
-
tunnel.close();
|
|
5985
|
-
resolve(void 0);
|
|
5986
|
-
});
|
|
5987
|
-
});
|
|
5988
|
-
}
|
|
5989
|
-
function isHoldRefusal(err) {
|
|
5990
|
-
return err instanceof RineApiError && holdOf(err.status, err.body) !== void 0;
|
|
5991
|
-
}
|
|
5992
|
-
/** What the relay does after a failed bind or a dropped tunnel. */
|
|
5993
|
-
const RelayFailure = {
|
|
5994
|
-
Paused: "paused",
|
|
5995
|
-
Revoked: "revoked",
|
|
5996
|
-
Retry: "retry"
|
|
5997
|
-
};
|
|
5998
|
-
/**
|
|
5999
|
-
* Confirm a revocation NAK once with a freshly minted token, because an older broker or server
|
|
6000
|
-
* reports a held agent as revoked. A mint refused with a hold code means held. A mint that
|
|
6001
|
-
* succeeds, or one the server refuses outright (a 4xx other than a throttle), leaves the NAK
|
|
6002
|
-
* standing. A network fault, a 429 or a 5xx says nothing about the binding, so the relay retries.
|
|
6003
|
-
*/
|
|
6004
|
-
async function confirmRevoked(mint) {
|
|
6005
|
-
try {
|
|
6006
|
-
await mint({ force: true });
|
|
6007
|
-
} catch (mintErr) {
|
|
6008
|
-
if (isHoldRefusal(mintErr)) return RelayFailure.Paused;
|
|
6009
|
-
return mintErr instanceof RineApiError && isRefusalStatus(mintErr.status) ? RelayFailure.Revoked : RelayFailure.Retry;
|
|
6010
|
-
}
|
|
6011
|
-
return RelayFailure.Revoked;
|
|
6012
|
-
}
|
|
6013
|
-
/** Sort a failure: a `suspended` NAK and a hold-coded refusal say held directly. */
|
|
6014
|
-
async function classifyFailure$1(err, mint) {
|
|
6015
|
-
if (isRevoked(err)) return confirmRevoked(mint);
|
|
6016
|
-
return err instanceof TunnelBindError && err.reason === BindNakReason.Suspended || isHoldRefusal(err) ? RelayFailure.Paused : RelayFailure.Retry;
|
|
6017
|
-
}
|
|
6018
|
-
/**
|
|
6019
|
-
* Announce the pause and wait [`PAUSED_RETRY_MS`] before the next attempt, or until the
|
|
6020
|
-
* stop handed to `setStop` runs on SIGINT.
|
|
6021
|
-
*/
|
|
6022
|
-
async function pauseTunnel(json, setStop) {
|
|
6023
|
-
emitLifecycle$1(json, {
|
|
6024
|
-
state: "tunnel_paused",
|
|
6025
|
-
message: PAUSED_MESSAGE
|
|
6026
|
-
});
|
|
6027
|
-
if (!json) process.stderr.write(`${PAUSED_MESSAGE}\n`);
|
|
6028
|
-
await new Promise((resolve) => {
|
|
6029
|
-
const timer = setTimeout(resolve, PAUSED_RETRY_MS);
|
|
6030
|
-
setStop(() => {
|
|
6031
|
-
clearTimeout(timer);
|
|
6032
|
-
resolve();
|
|
6033
|
-
});
|
|
6034
|
-
});
|
|
6035
|
-
setStop(void 0);
|
|
6036
|
-
}
|
|
6037
|
-
/** Classify `err`, and run the pause when it says the agent is held. */
|
|
6038
|
-
async function settleFailure(err, mint, json, setStop) {
|
|
6039
|
-
const failure = await classifyFailure$1(err, mint);
|
|
6040
|
-
if (failure === RelayFailure.Paused) await pauseTunnel(json, setStop);
|
|
6041
|
-
return failure;
|
|
6042
|
-
}
|
|
6043
|
-
//#endregion
|
|
6044
|
-
//#region src/commands/relay-tier.ts
|
|
6045
|
-
/** How a hook's request bytes reach the relay, decided once per connect by its tier. */
|
|
6046
|
-
/**
|
|
6047
|
-
* Branch ONCE on the tier, BEFORE any label/FQDN derivation: the zero-trust
|
|
6048
|
-
* agentLabel deriver hard-codes `.hook.rine.network`, so a shared-edge `.edge`
|
|
6049
|
-
* host must never reach it. Zero-trust defers its TLS listener to AFTER the
|
|
6050
|
-
* tunnel connects (the lazy `ref` holder — orchestration order:
|
|
6051
|
-
* cert→tunnel→listener, safe because no OPEN arrives before the holder is
|
|
6052
|
-
* populated); shared-edge has no listener, so its `openLocalPipe` factory is
|
|
6053
|
-
* ready immediately.
|
|
6054
|
-
*/
|
|
6055
|
-
async function prepareTier(hook, onRequest, cert, json) {
|
|
6056
|
-
const { hostname } = hook;
|
|
6057
|
-
if (hook.termination === "shared_edge") {
|
|
6058
|
-
cert.release();
|
|
6059
|
-
const openLocalPipe = makeEdgePipeFactory({ onRequest });
|
|
6060
|
-
emitLifecycle$1(json, {
|
|
6061
|
-
state: "shared_edge_ready",
|
|
6062
|
-
hostname
|
|
6063
|
-
});
|
|
6064
|
-
return {
|
|
6065
|
-
openLocalPipe,
|
|
6066
|
-
listen: async () => {}
|
|
6067
|
-
};
|
|
6068
|
-
}
|
|
6069
|
-
if (hook.termination !== "zero_trust") throw new UnsupportedTierError(hook.termination);
|
|
6070
|
-
const ztCert = await cert.ensure(agentLabel(hostname));
|
|
6071
|
-
emitLifecycle$1(json, {
|
|
6072
|
-
state: "cert_ready",
|
|
6073
|
-
hostname
|
|
6074
|
-
});
|
|
6075
|
-
const ref = {};
|
|
6076
|
-
return {
|
|
6077
|
-
openLocalPipe: (frame) => {
|
|
6078
|
-
if (!ref.live) throw new Error("listener not ready");
|
|
6079
|
-
return ref.live.openLocalPipe(frame);
|
|
6080
|
-
},
|
|
6081
|
-
async listen(port, onListening) {
|
|
6082
|
-
const live = await startTlsListener({
|
|
6083
|
-
port,
|
|
6084
|
-
certPem: ztCert.certPem,
|
|
6085
|
-
keyPem: ztCert.keyPem,
|
|
6086
|
-
onRequest
|
|
6087
|
-
});
|
|
6088
|
-
ref.live = live;
|
|
6089
|
-
onListening(live);
|
|
6090
|
-
await assertAgentARecord(hostname, json);
|
|
6091
|
-
emitLifecycle$1(json, {
|
|
6092
|
-
state: "listener_ready",
|
|
6093
|
-
port: live.port
|
|
6094
|
-
});
|
|
6095
|
-
cert.startRenewalTimer();
|
|
6096
|
-
}
|
|
6097
|
-
};
|
|
6098
|
-
}
|
|
6099
|
-
//#endregion
|
|
6100
|
-
//#region src/commands/relay-loop.ts
|
|
6101
|
-
/** The `rine relay` reconnect loop: cert, tunnel, listener, per-request handler. */
|
|
6102
|
-
async function runRelayLoop(ctx) {
|
|
6103
|
-
const { opts, gOpts, configDir, agentId, client, token: mintToken } = ctx;
|
|
6104
|
-
const json = gOpts.json;
|
|
6105
|
-
const port = parsePort(opts.port);
|
|
6106
|
-
const secret = resolveSecret(opts, configDir, agentId);
|
|
6107
|
-
if (secret.length === 0) {
|
|
6108
|
-
printError(`No hook secret resolved for '${opts.hook}' — refusing to start. Provide one via --secret-env, --secret-file, or persist it under ${configDir}/funnel/${agentId}/${opts.hook}.secret.`);
|
|
6109
|
-
process.exitCode = 2;
|
|
6110
|
-
return;
|
|
6111
|
-
}
|
|
6112
|
-
const options = { staging: opts.staging };
|
|
6113
|
-
let backoff = 1;
|
|
6114
|
-
let attempt = 0;
|
|
6115
|
-
let stopped = false;
|
|
6116
|
-
let paused = false;
|
|
6117
|
-
const refreshMargin = jitteredRefreshMargin();
|
|
6118
|
-
const cert = relayCert({
|
|
6119
|
-
configDir,
|
|
6120
|
-
agentId,
|
|
6121
|
-
client,
|
|
6122
|
-
options,
|
|
6123
|
-
json,
|
|
6124
|
-
isStopped: () => stopped
|
|
6125
|
-
});
|
|
6126
|
-
const idempotency = new IdempotencyStore();
|
|
6127
|
-
let stopConnection;
|
|
6128
|
-
process.on("SIGINT", () => {
|
|
6129
|
-
stopped = true;
|
|
6130
|
-
process.exitCode = 0;
|
|
6131
|
-
cert.stop();
|
|
6132
|
-
stopConnection?.();
|
|
6133
|
-
});
|
|
6134
|
-
while (!stopped) {
|
|
6135
|
-
attempt++;
|
|
6136
|
-
let listener;
|
|
6137
|
-
try {
|
|
6138
|
-
const hook = await resolveHook(client, agentId, opts.hook);
|
|
6139
|
-
const { hostname, control_ws_url: controlWsUrl } = hook;
|
|
6140
|
-
const onRequest = (req) => handleWebhookRequest({
|
|
6141
|
-
configDir,
|
|
6142
|
-
agentId,
|
|
6143
|
-
hookName: opts.hook,
|
|
6144
|
-
secret,
|
|
6145
|
-
client,
|
|
6146
|
-
idempotency,
|
|
6147
|
-
emitLifecycle: (ev) => json && console.log(JSON.stringify(ev))
|
|
6148
|
-
}, req);
|
|
6149
|
-
const tier = await prepareTier(hook, onRequest, cert, json);
|
|
6150
|
-
const tunnel = await connectTunnel({
|
|
6151
|
-
controlWsUrl,
|
|
6152
|
-
token: await mintToken({
|
|
6153
|
-
refreshMargin,
|
|
6154
|
-
force: paused
|
|
6155
|
-
}),
|
|
6156
|
-
agentId,
|
|
6157
|
-
hostname,
|
|
6158
|
-
openLocalPipe: tier.openLocalPipe
|
|
6159
|
-
});
|
|
6160
|
-
emitLifecycle$1(json, { state: "tunnel_connected" });
|
|
6161
|
-
await tier.listen(port, (live) => {
|
|
6162
|
-
listener = live;
|
|
6163
|
-
});
|
|
6164
|
-
backoff = 1;
|
|
6165
|
-
paused = false;
|
|
6166
|
-
const close = await waitForClose(tunnel, () => stopped, (stop) => {
|
|
6167
|
-
stopConnection = stop;
|
|
6168
|
-
});
|
|
6169
|
-
stopConnection = void 0;
|
|
6170
|
-
tunnel.close();
|
|
6171
|
-
listener?.close();
|
|
6172
|
-
if (stopped) break;
|
|
6173
|
-
if (close?.clean !== false) {
|
|
6174
|
-
emitLifecycle$1(json, {
|
|
6175
|
-
state: "tunnel_reconnecting",
|
|
6176
|
-
attempt: attempt + 1,
|
|
6177
|
-
backoff_ms: 0,
|
|
6178
|
-
reason: "server_close"
|
|
6179
|
-
});
|
|
6180
|
-
backoff = 1;
|
|
6181
|
-
} else backoff = await reconnectAfterError(json, attempt, backoff);
|
|
6182
|
-
} catch (err) {
|
|
6183
|
-
listener?.close();
|
|
6184
|
-
if (stopped) break;
|
|
6185
|
-
if (err instanceof UnsupportedTierError) {
|
|
6186
|
-
cert.stop();
|
|
6187
|
-
printError(err.message);
|
|
6188
|
-
process.exitCode = 2;
|
|
6189
|
-
return;
|
|
6190
|
-
}
|
|
6191
|
-
const failure = await settleFailure(err, mintToken, json, (stop) => {
|
|
6192
|
-
stopConnection = stop;
|
|
6193
|
-
});
|
|
6194
|
-
if (failure === RelayFailure.Paused) {
|
|
6195
|
-
paused = true;
|
|
6196
|
-
continue;
|
|
6197
|
-
}
|
|
6198
|
-
if (failure === RelayFailure.Revoked) return exitRevoked(cert, json);
|
|
6199
|
-
backoff = await reconnectAfterError(json, attempt, backoff, () => {
|
|
6200
|
-
if (opts.verbose) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, error): ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
|
|
6201
|
-
});
|
|
6202
|
-
}
|
|
6203
|
-
}
|
|
6204
|
-
cert.stop();
|
|
6205
|
-
emitLifecycle$1(json, {
|
|
6206
|
-
state: "stopped",
|
|
6207
|
-
reason: "signal"
|
|
6208
|
-
});
|
|
6889
|
+
function relayRefusal(err, opts, dir, agentId) {
|
|
6890
|
+
if (err instanceof EmptyHookSecretError) return `No hook secret resolved for '${opts.hook}' — refusing to start. Provide one via --secret-env, --secret-file, or persist it under ${dir.shown}/funnel/${agentId}/${opts.hook}.secret.`;
|
|
6891
|
+
if (err instanceof UnsupportedTierError) return `${err.message} Upgrade the CLI to a newer build, or recreate the hook with a supported --tier.`;
|
|
6892
|
+
return err.message;
|
|
6209
6893
|
}
|
|
6210
6894
|
//#endregion
|
|
6211
6895
|
//#region src/commands/relay.ts
|
|
6212
6896
|
/**
|
|
6213
6897
|
* `rine relay`, the long-lived inbound webhook funnel daemon. This module
|
|
6214
6898
|
* registers the command, builds the client (as stream.ts does, not through
|
|
6215
|
-
* withClient), resolves the acting agent
|
|
6216
|
-
*
|
|
6217
|
-
*
|
|
6218
|
-
*
|
|
6219
|
-
* (
|
|
6220
|
-
*
|
|
6221
|
-
|
|
6222
|
-
|
|
6223
|
-
|
|
6224
|
-
|
|
6225
|
-
|
|
6899
|
+
* withClient), resolves the acting agent, refuses to start without its identity
|
|
6900
|
+
* keys or a hook secret, then hands over to rine-core's `runRelay`, which owns
|
|
6901
|
+
* the reconnect loop (cert → tunnel → listener → per-request handler). The CLI
|
|
6902
|
+
* is the process edge: it turns SIGINT into an abort, prints the relay's
|
|
6903
|
+
* events (lifecycle events NEVER carry a body) and maps its outcome to the exit
|
|
6904
|
+
* code.
|
|
6905
|
+
*/
|
|
6906
|
+
/** Where the relay's events go: JSON lines on stdout under `--json`, the pause and stop notices and `--verbose` errors on stderr. */
|
|
6907
|
+
function eventPrinter(json, verbose, hookName) {
|
|
6908
|
+
return (event) => {
|
|
6909
|
+
switch (event.type) {
|
|
6910
|
+
case "lifecycle":
|
|
6911
|
+
if (json) console.log(JSON.stringify({
|
|
6912
|
+
event: "lifecycle",
|
|
6913
|
+
data: event.data
|
|
6914
|
+
}));
|
|
6915
|
+
else if (event.data.state === "tunnel_paused") process.stderr.write(`${event.data.message}\n`);
|
|
6916
|
+
else if (event.data.state === "tunnel_revoked") process.stderr.write(`relay stopped: the server no longer accepts hook '${hookName}' (it was deleted, or its binding was revoked). \`rine hook list\` shows this agent's hooks; \`rine hook create --name ${hookName}\` makes a new one.\n`);
|
|
6917
|
+
return;
|
|
6918
|
+
case "request":
|
|
6919
|
+
if (json) console.log(JSON.stringify(event.event));
|
|
6920
|
+
return;
|
|
6921
|
+
case "reconnect_error": if (verbose) process.stderr.write(`Reconnecting (attempt ${event.attempt}, error): ${event.error instanceof Error ? event.error.stack ?? event.error.message : String(event.error)}\n`);
|
|
6922
|
+
}
|
|
6923
|
+
};
|
|
6924
|
+
}
|
|
6226
6925
|
function registerRelay(program) {
|
|
6227
6926
|
program.command("relay").description("Run the inbound webhook funnel relay (long-lived foreground daemon)").addOption(actorOption()).option("--hook <name>", "Hook name to relay", "default").option("--port <n>", "Local TLS listener port", "8443").option("--secret-file <path>", "Read the HMAC secret from a file").option("--secret-env <VAR>", "Read the HMAC secret from an environment variable").option("--staging", "Use the Let's Encrypt staging CA (dev)").option("--verbose", "Verbose reconnect logging").action(async (opts, command) => {
|
|
6228
6927
|
try {
|
|
6928
|
+
if (refuseHookName(opts.hook, hookNamePatternError(opts.hook))) return;
|
|
6229
6929
|
const gOpts = program.opts();
|
|
6230
|
-
const
|
|
6231
|
-
|
|
6930
|
+
const { client, dir, tokenFor } = await createClient({
|
|
6931
|
+
apiUrl: resolveApiUrl(),
|
|
6932
|
+
profile: gOpts.profile,
|
|
6933
|
+
refreshMargin: jitteredRefreshMargin()
|
|
6934
|
+
});
|
|
6232
6935
|
const { actingAgent } = actorLadder(namedActor(command, gOpts), client);
|
|
6233
6936
|
const agentId = await actingAgent();
|
|
6234
|
-
if (!agentKeysExist(
|
|
6235
|
-
printError(
|
|
6937
|
+
if (!agentKeysExist(dir.path, agentId)) {
|
|
6938
|
+
printError(missingKeysMessage(dir.shown, agentId));
|
|
6236
6939
|
process.exitCode = 2;
|
|
6237
6940
|
return;
|
|
6238
6941
|
}
|
|
6239
|
-
|
|
6240
|
-
|
|
6241
|
-
|
|
6242
|
-
|
|
6243
|
-
|
|
6244
|
-
|
|
6245
|
-
|
|
6246
|
-
|
|
6942
|
+
const port = parsePort(opts.port, "--port");
|
|
6943
|
+
const secret = resolveSecret(opts, dir, agentId);
|
|
6944
|
+
const controller = new AbortController();
|
|
6945
|
+
process.on("SIGINT", () => controller.abort());
|
|
6946
|
+
try {
|
|
6947
|
+
const { reason } = await runRelay({
|
|
6948
|
+
configDir: dir.path,
|
|
6949
|
+
agentId,
|
|
6950
|
+
client,
|
|
6951
|
+
hookName: opts.hook,
|
|
6952
|
+
port,
|
|
6953
|
+
secret,
|
|
6954
|
+
staging: opts.staging,
|
|
6955
|
+
signal: controller.signal,
|
|
6956
|
+
onEvent: eventPrinter(gOpts.json, opts.verbose, opts.hook),
|
|
6957
|
+
mintToken: tokenFor(agentId),
|
|
6958
|
+
seams: relaySeams(core, resolve4)
|
|
6959
|
+
});
|
|
6960
|
+
process.exitCode = reason === "stopped" ? 0 : 1;
|
|
6961
|
+
} catch (err) {
|
|
6962
|
+
if (!(err instanceof RelayFatalError)) throw err;
|
|
6963
|
+
printError(relayRefusal(err, opts, dir, agentId));
|
|
6964
|
+
process.exitCode = 2;
|
|
6965
|
+
}
|
|
6247
6966
|
} catch (err) {
|
|
6248
6967
|
printError(err instanceof Error ? err.message : String(err));
|
|
6249
6968
|
process.exitCode = 1;
|
|
@@ -6347,6 +7066,15 @@ function saveStreamCursor(configDir, agentId, eventId) {
|
|
|
6347
7066
|
}
|
|
6348
7067
|
//#endregion
|
|
6349
7068
|
//#region src/commands/stream-lifecycle.ts
|
|
7069
|
+
/** The `--json` line format, for `stream --help`. */
|
|
7070
|
+
const STREAM_JSON_HELP = `
|
|
7071
|
+
With --json, stdout is one JSON object per line:
|
|
7072
|
+
{"event":"message","id":"<event id>","data":"<message row as a JSON string>"}
|
|
7073
|
+
{"event":"heartbeat","id":...,"data":"..."} (left out with --monitor)
|
|
7074
|
+
{"event":"lifecycle","data":{"state":"connecting|connected|reconnecting|stopped", ...}}
|
|
7075
|
+
The message row is inside "data" and is a string: parse it a second time to read
|
|
7076
|
+
its "id", "type", "sender_handle" and "created_at". With --monitor, lifecycle
|
|
7077
|
+
lines go to stderr and stdout carries message lines only.`;
|
|
6350
7078
|
/** One lifecycle event, on stdout (JSON mode) or stderr (`--monitor`, so stdout stays messages only). */
|
|
6351
7079
|
function emitLifecycle(gOpts, monitor, data) {
|
|
6352
7080
|
if (gOpts.json) {
|
|
@@ -6460,12 +7188,14 @@ async function openStreamMessage(dataStr, agentId, configDir, client) {
|
|
|
6460
7188
|
let result;
|
|
6461
7189
|
let unavailable = null;
|
|
6462
7190
|
let forgedStatus;
|
|
7191
|
+
let thrown;
|
|
6463
7192
|
const fromAgentId = data.from_agent_id;
|
|
6464
7193
|
const attempted = Boolean(!undecodable && cleartext === null && data.encrypted_payload && fromAgentId && agentKeysExist(configDir, agentId));
|
|
6465
7194
|
if (attempted && data.encrypted_payload && fromAgentId) {
|
|
6466
7195
|
if (isGroupEncryptionVersion(data.encryption_version) && data.group_id) try {
|
|
6467
7196
|
result = await decryptGroupMessageWithRecovery(client, configDir, agentId, data.group_id, data.encrypted_payload, fromAgentId, data.created_at);
|
|
6468
7197
|
} catch (err) {
|
|
7198
|
+
thrown = err;
|
|
6469
7199
|
forgedStatus = groupAuthenticityStatus(err) ?? void 0;
|
|
6470
7200
|
unavailable = asSenderKeyUnavailable(err, data.group_id);
|
|
6471
7201
|
}
|
|
@@ -6474,13 +7204,15 @@ async function openStreamMessage(dataStr, agentId, configDir, client) {
|
|
|
6474
7204
|
} catch {}
|
|
6475
7205
|
if (result && !isAuthenticityFailure(result.verificationStatus) && result.plaintext !== void 0) ingestSenderKeyDistribution(configDir, agentId, data.type ?? "", result);
|
|
6476
7206
|
}
|
|
7207
|
+
const { catch_up: catchUp } = result ? reportedCatchUp(result) : recoveredCatchUp(thrown);
|
|
6477
7208
|
return {
|
|
6478
7209
|
data,
|
|
6479
7210
|
cleartext,
|
|
6480
7211
|
attempted,
|
|
6481
7212
|
result,
|
|
6482
7213
|
forgedStatus,
|
|
6483
|
-
unavailable
|
|
7214
|
+
unavailable,
|
|
7215
|
+
catchUp
|
|
6484
7216
|
};
|
|
6485
7217
|
}
|
|
6486
7218
|
/**
|
|
@@ -6540,6 +7272,8 @@ async function settleAndPrint(env, dataStr) {
|
|
|
6540
7272
|
const opened = await openStreamMessage(dataStr, env.agentId, env.configDir, env.client);
|
|
6541
7273
|
const row = opened.data;
|
|
6542
7274
|
if (row.id && isSettledMessage(opened)) env.acks.add(row.id);
|
|
7275
|
+
const catchUp = catchUpNote(opened.catchUp);
|
|
7276
|
+
if (catchUp) printError(catchUp);
|
|
6543
7277
|
if (env.json) return;
|
|
6544
7278
|
const rendered = renderOpened(opened, env.explain);
|
|
6545
7279
|
if (rendered.notice !== null) printError(rendered.notice);
|
|
@@ -6673,12 +7407,16 @@ async function exitWhenFlushed(code, flushWaitMs = FLUSH_WAIT_MS) {
|
|
|
6673
7407
|
//#endregion
|
|
6674
7408
|
//#region src/commands/stream.ts
|
|
6675
7409
|
function registerStream(program) {
|
|
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) => {
|
|
7410
|
+
program.command("stream").description("Stream incoming messages via SSE").addHelpText("after", STREAM_JSON_HELP).addOption(actorOption("which agent is acting, and whose messages stream (name, handle, or agent ID)")).option("--verbose", "Show heartbeats and reconnect details").option("--persistent", "Disable server-side connection timeout").option("--heartbeat-timeout <seconds>", "Seconds of silence before reconnecting (default: 70)", "70").option("--monitor", "Suppress non-message stdout (for CC plugin monitors)").option("--hide-control", STREAM_HIDE_CONTROL_HELP).action(async (opts, command) => {
|
|
6677
7411
|
try {
|
|
6678
7412
|
const gOpts = program.opts();
|
|
6679
|
-
const configDir = resolveConfigDir();
|
|
6680
7413
|
const apiUrl = resolveApiUrl();
|
|
6681
|
-
const { client,
|
|
7414
|
+
const { client, dir, tokenFor } = await createClient({
|
|
7415
|
+
apiUrl,
|
|
7416
|
+
profile: gOpts.profile,
|
|
7417
|
+
refreshMargin: jitteredRefreshMargin()
|
|
7418
|
+
});
|
|
7419
|
+
const configDir = dir.path;
|
|
6682
7420
|
const { actingAgent } = actorLadder(namedActor(command, gOpts), client);
|
|
6683
7421
|
const agentId = await actingAgent();
|
|
6684
7422
|
let url = `${apiUrl}/agents/${agentId}/stream`;
|
|
@@ -6688,7 +7426,6 @@ function registerStream(program) {
|
|
|
6688
7426
|
let backoff = 1;
|
|
6689
7427
|
let attempt = 0;
|
|
6690
7428
|
let mintFresh = false;
|
|
6691
|
-
const refreshMargin = jitteredRefreshMargin();
|
|
6692
7429
|
const explain = senderKeyExplainer();
|
|
6693
7430
|
const env = createStreamEnv({
|
|
6694
7431
|
json: Boolean(gOpts.json),
|
|
@@ -6700,6 +7437,7 @@ function registerStream(program) {
|
|
|
6700
7437
|
client,
|
|
6701
7438
|
explain
|
|
6702
7439
|
});
|
|
7440
|
+
const mintToken = tokenFor(agentId);
|
|
6703
7441
|
const stop = listenForStop();
|
|
6704
7442
|
while (!stop.stopped) {
|
|
6705
7443
|
attempt++;
|
|
@@ -6714,10 +7452,7 @@ function registerStream(program) {
|
|
|
6714
7452
|
stopping: stop.signal
|
|
6715
7453
|
});
|
|
6716
7454
|
try {
|
|
6717
|
-
const token = await mintToken({
|
|
6718
|
-
refreshMargin,
|
|
6719
|
-
force: mintFresh
|
|
6720
|
-
});
|
|
7455
|
+
const token = await mintToken({ force: mintFresh });
|
|
6721
7456
|
mintFresh = false;
|
|
6722
7457
|
const headers = withPeekHeader({
|
|
6723
7458
|
Authorization: `Bearer ${token}`,
|
|
@@ -8797,8 +9532,9 @@ async function releaseIdentity(identity) {
|
|
|
8797
9532
|
}
|
|
8798
9533
|
/** The org id comes from the root itself, never from a server answer. */
|
|
8799
9534
|
function resolveIdentity(input = {}) {
|
|
8800
|
-
const
|
|
8801
|
-
const
|
|
9535
|
+
const dir = input.configDir === void 0 ? resolveConfigDir() : configDirAt(input.configDir);
|
|
9536
|
+
const configDir = dir.path;
|
|
9537
|
+
const ownerDir = input.ownerDir ?? resolveOwnerDir(dir);
|
|
8802
9538
|
if (hasRoot(ownerDir)) {
|
|
8803
9539
|
const key = ReadKey.fromOwnerDir(ownerDir);
|
|
8804
9540
|
const bucket = new TokenBucket();
|
|
@@ -11096,13 +11832,62 @@ function registerVerifyIdentity(program) {
|
|
|
11096
11832
|
}));
|
|
11097
11833
|
}
|
|
11098
11834
|
//#endregion
|
|
11099
|
-
//#region src/commands/wallet.ts
|
|
11835
|
+
//#region src/commands/wallet-policy-set.ts
|
|
11836
|
+
/** Printed when the policy could not be signed here. */
|
|
11837
|
+
const UNSIGNED_NOTE = "policy saved unsigned; sign it from a machine holding the org root";
|
|
11838
|
+
/** Printed after core's refusal to replace a signed policy without the org root. */
|
|
11839
|
+
const FORCE_HINT = "Pass --force to replace it with an unsigned policy.";
|
|
11100
11840
|
function csv(raw) {
|
|
11101
11841
|
return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
|
|
11102
11842
|
}
|
|
11843
|
+
/** Write `policy` unsigned; a signed one on disk is replaced only when `force` is set. */
|
|
11844
|
+
function saveUnsigned(dirs, agentId, policy, force) {
|
|
11845
|
+
if (force) {
|
|
11846
|
+
savePolicy(dirs.configDir, agentId, policy);
|
|
11847
|
+
return;
|
|
11848
|
+
}
|
|
11849
|
+
try {
|
|
11850
|
+
savePolicyUnlessSigned(dirs.configDir, agentId, policy);
|
|
11851
|
+
} catch (err) {
|
|
11852
|
+
const signed = readStoredPolicy(dirs.configDir, agentId).kind === StoredPolicyKind.Signed;
|
|
11853
|
+
if (err instanceof X402Error && signed) throw new Error(`${err.message}. ${FORCE_HINT}`);
|
|
11854
|
+
throw err;
|
|
11855
|
+
}
|
|
11856
|
+
}
|
|
11857
|
+
/** Save `policy` for `agentId`, signed when the owner dir holds that agent's org root. */
|
|
11858
|
+
function saveForAgent(dirs, agentId, policy, force) {
|
|
11859
|
+
const org = dirs.agentOnly === true ? void 0 : loadOrgFromOwner(dirs.ownerDir);
|
|
11860
|
+
if (org === void 0 || org.orgId !== orgIdOfAgent(dirs.configDir, agentId)) {
|
|
11861
|
+
saveUnsigned(dirs, agentId, policy, force);
|
|
11862
|
+
return false;
|
|
11863
|
+
}
|
|
11864
|
+
saveSignedPolicy(dirs.configDir, agentId, signPolicy(policy, agentId, org.ed25519.privateKey));
|
|
11865
|
+
return true;
|
|
11866
|
+
}
|
|
11867
|
+
function registerWalletPolicySet(policy, program) {
|
|
11868
|
+
policy.command("set").description("Set the spend policy (all caps are decimal major-unit strings); signed by the org when its root is here").addOption(actorOption()).requiredOption("--per-tx-cap <amount>", "Max per-transaction spend, e.g. 5.00").requiredOption("--daily-cap <amount>", "Max total spend per UTC day, e.g. 50.00").requiredOption("--allowed-assets <list>", "Comma-separated assets (symbols e.g. EURC or 0x contract addresses)").requiredOption("--allowed-networks <list>", "Comma-separated CAIP-2 networks, e.g. eip155:8453").option("--auto-pay-threshold <amount>", "Auto-pay ceiling for 'rine pay --auto-pay' (default 0 = never auto-pay)", "0").option("--no-auto-pay", "Never pay without asking, even below the threshold").option("--allow-repay", "Allow paying a quote already paid today again").option("--force", "Replace a signed policy with an unsigned one when the org root is not here").action(withClient(program, async ({ gOpts, dirs, actingAgent }, opts) => {
|
|
11869
|
+
const signed = saveForAgent(dirs, await actingAgent(), {
|
|
11870
|
+
perTxCap: opts.perTxCap,
|
|
11871
|
+
dailyCap: opts.dailyCap,
|
|
11872
|
+
allowedAssets: csv(opts.allowedAssets),
|
|
11873
|
+
allowedNetworks: csv(opts.allowedNetworks),
|
|
11874
|
+
autoPayThreshold: opts.autoPayThreshold,
|
|
11875
|
+
autoPay: opts.autoPay,
|
|
11876
|
+
allowRepay: opts.allowRepay === true
|
|
11877
|
+
}, opts.force === true);
|
|
11878
|
+
if (!signed) console.error(UNSIGNED_NOTE);
|
|
11879
|
+
if (gOpts.json) printJson({
|
|
11880
|
+
ok: true,
|
|
11881
|
+
signed
|
|
11882
|
+
});
|
|
11883
|
+
else printSuccess(signed ? "Spend policy updated and signed by the org" : "Spend policy updated");
|
|
11884
|
+
}));
|
|
11885
|
+
}
|
|
11886
|
+
//#endregion
|
|
11887
|
+
//#region src/commands/wallet.ts
|
|
11103
11888
|
function registerWallet(program) {
|
|
11104
11889
|
const wallet = program.command("wallet").description("Manage the agent payment wallet and spend policy (x402)");
|
|
11105
|
-
wallet.command("create").description("Create a payment wallet for an agent (refuses to overwrite)").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
|
|
11890
|
+
wallet.command("create").description("Create a payment wallet for an agent (refuses to overwrite)").addOption(actorOption()).action(withClient(program, async ({ gOpts, dirs: { configDir }, actingAgent }) => {
|
|
11106
11891
|
const agentId = await actingAgent();
|
|
11107
11892
|
if (walletKeyExists(configDir, agentId)) {
|
|
11108
11893
|
printError(`Wallet already exists for agent ${agentId}. The private key is never overwritten.`);
|
|
@@ -11122,7 +11907,7 @@ function registerWallet(program) {
|
|
|
11122
11907
|
Value: address
|
|
11123
11908
|
}]);
|
|
11124
11909
|
}));
|
|
11125
|
-
wallet.command("address").description("Print an agent's payment wallet address").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
|
|
11910
|
+
wallet.command("address").description("Print an agent's payment wallet address").addOption(actorOption()).action(withClient(program, async ({ gOpts, dirs: { configDir }, actingAgent }) => {
|
|
11126
11911
|
const agentId = await actingAgent();
|
|
11127
11912
|
if (!walletKeyExists(configDir, agentId)) {
|
|
11128
11913
|
printError(`No wallet for agent ${agentId}. Run 'rine wallet create' first.`);
|
|
@@ -11136,7 +11921,7 @@ function registerWallet(program) {
|
|
|
11136
11921
|
});
|
|
11137
11922
|
else printTable([{ "Wallet address": address }]);
|
|
11138
11923
|
}));
|
|
11139
|
-
wallet.command("policy").description("Show the effective spend policy (deny-by-default when unset)").addOption(actorOption()).action(withClient(program, async ({ gOpts, configDir, actingAgent }) => {
|
|
11924
|
+
registerWalletPolicySet(wallet.command("policy").description("Show the effective spend policy (deny-by-default when unset)").addOption(actorOption()).action(withClient(program, async ({ gOpts, dirs: { configDir }, actingAgent }) => {
|
|
11140
11925
|
const agentId = await actingAgent();
|
|
11141
11926
|
const p = loadPolicy(configDir, agentId);
|
|
11142
11927
|
if (gOpts.json) {
|
|
@@ -11183,16 +11968,51 @@ function registerWallet(program) {
|
|
|
11183
11968
|
Value: p.allowedNetworks.join(", ") || "—"
|
|
11184
11969
|
}
|
|
11185
11970
|
]);
|
|
11186
|
-
}))
|
|
11187
|
-
|
|
11188
|
-
|
|
11189
|
-
|
|
11190
|
-
|
|
11191
|
-
|
|
11192
|
-
|
|
11193
|
-
|
|
11194
|
-
|
|
11195
|
-
|
|
11971
|
+
})), program);
|
|
11972
|
+
}
|
|
11973
|
+
//#endregion
|
|
11974
|
+
//#region src/commands/runtime-warning.ts
|
|
11975
|
+
/**
|
|
11976
|
+
* Detect that the CLI runs inside an agent runtime, so a command that signs with the org key
|
|
11977
|
+
* can warn first. Warn, never block: the command still runs. One table of markers; each is an environment
|
|
11978
|
+
* variable that runtime sets for the processes it starts (the OpenClaw and Hermes rigs and
|
|
11979
|
+
* Claude Code in `compose.openclaw.yml`, `compose.hermes.yml` and `compose.cc.yml`).
|
|
11980
|
+
*/
|
|
11981
|
+
const RUNTIME_MARKERS = [
|
|
11982
|
+
{
|
|
11983
|
+
runtime: "Claude Code",
|
|
11984
|
+
vars: ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT"]
|
|
11985
|
+
},
|
|
11986
|
+
{
|
|
11987
|
+
runtime: "OpenClaw",
|
|
11988
|
+
vars: ["OPENCLAW_STATE_DIR", "OPENCLAW_CONFIG_PATH"]
|
|
11989
|
+
},
|
|
11990
|
+
{
|
|
11991
|
+
runtime: "Hermes",
|
|
11992
|
+
vars: ["HERMES_HOME", "HERMES_SESSION_KEY"]
|
|
11993
|
+
}
|
|
11994
|
+
];
|
|
11995
|
+
/** The two commands that create the org key: there is no other machine to run them from yet. */
|
|
11996
|
+
const KEY_CREATING = new Set(["register", "onboard"]);
|
|
11997
|
+
/** The warning printed before a command that signs with the org key, inside an agent runtime. */
|
|
11998
|
+
const orgKeyWarning = (runtime, path) => `This looks like an agent's environment (${runtime}). rine ${path} signs with your org key, and an agent with a shell here can read that key. Run org-key commands from a machine that runs no agents: https://docs.rine.network/how-to/org-rules/`;
|
|
11999
|
+
/** The runtime whose marker is set (non-empty) in `env`, or `undefined` in a plain shell. */
|
|
12000
|
+
function runtimeOf(env = process.env) {
|
|
12001
|
+
return RUNTIME_MARKERS.find((m) => m.vars.some((v) => env[v]))?.runtime;
|
|
12002
|
+
}
|
|
12003
|
+
/**
|
|
12004
|
+
* Before every Admin-tier command except the two that create the org key, print the warning
|
|
12005
|
+
* on stderr when a runtime marker is set. It runs before the action body, so before any
|
|
12006
|
+
* confirmation, and prints under `--yes` and `--json` too; stdout is untouched.
|
|
12007
|
+
*/
|
|
12008
|
+
function warnBeforeOrgKey(program) {
|
|
12009
|
+
program.hook("preAction", (_, action) => {
|
|
12010
|
+
const runtime = runtimeOf();
|
|
12011
|
+
if (runtime === void 0) return;
|
|
12012
|
+
const path = commandPath(action);
|
|
12013
|
+
if (KEY_CREATING.has(path)) return;
|
|
12014
|
+
if (operationByCli(path)?.tier === OpTier.Admin) printError(orgKeyWarning(runtime, path));
|
|
12015
|
+
});
|
|
11196
12016
|
}
|
|
11197
12017
|
//#endregion
|
|
11198
12018
|
//#region src/commands/webhook.ts
|
|
@@ -11265,29 +12085,46 @@ function registerWebhook(program) {
|
|
|
11265
12085
|
}));
|
|
11266
12086
|
}
|
|
11267
12087
|
//#endregion
|
|
11268
|
-
//#region src/
|
|
12088
|
+
//#region src/program.ts
|
|
11269
12089
|
const { version } = createRequire(import.meta.url)("../package.json");
|
|
11270
|
-
|
|
11271
|
-
|
|
11272
|
-
|
|
11273
|
-
|
|
11274
|
-
|
|
11275
|
-
|
|
11276
|
-
|
|
11277
|
-
|
|
11278
|
-
|
|
11279
|
-
|
|
11280
|
-
|
|
11281
|
-
|
|
11282
|
-
|
|
11283
|
-
|
|
11284
|
-
|
|
11285
|
-
|
|
11286
|
-
|
|
11287
|
-
|
|
11288
|
-
|
|
11289
|
-
|
|
11290
|
-
|
|
11291
|
-
program
|
|
12090
|
+
/** Printed above `Usage:` on the root help, so the first screen names what an agent looks for. */
|
|
12091
|
+
const HELP_HEAD = `rine: end-to-end encrypted messaging between AI agents.
|
|
12092
|
+
Docs: https://docs.rine.network/ · For AI agents: https://rine.network/skill.md
|
|
12093
|
+
Who may message your agents: rine org rules, rine org counterparties. What an agent shows: rine agent exposure.
|
|
12094
|
+
Delegated keys: rine org delegate. Spend policy: rine wallet policy. Verify a peer: rine agent verify.
|
|
12095
|
+
Watch for new messages: rine stream. Org-wide reader: rine tui.
|
|
12096
|
+
`;
|
|
12097
|
+
function buildProgram() {
|
|
12098
|
+
const program = new Command("rine").version(version).description("rine.network CLI — messaging infrastructure for AI agents").option("--profile <name>", "profile to use (default: the owner's org profile, else \"default\")").option("--json", "output as JSON").option("--as <agent>", "which agent is acting — the retired spelling of --agent (name, handle, or agent ID)");
|
|
12099
|
+
program.addHelpText("before", HELP_HEAD);
|
|
12100
|
+
registerAuth(program);
|
|
12101
|
+
registerRegister(program);
|
|
12102
|
+
registerOnboard(program);
|
|
12103
|
+
registerOrg(program);
|
|
12104
|
+
registerAgent(program);
|
|
12105
|
+
registerAgentProfile(program);
|
|
12106
|
+
registerMessages(program);
|
|
12107
|
+
registerGroup(program);
|
|
12108
|
+
registerDiscover(program);
|
|
12109
|
+
registerWebhook(program);
|
|
12110
|
+
registerHook(program);
|
|
12111
|
+
registerWallet(program);
|
|
12112
|
+
registerPay(program);
|
|
12113
|
+
registerFulfill(program);
|
|
12114
|
+
registerKeys(program);
|
|
12115
|
+
registerStream(program);
|
|
12116
|
+
registerTui(program);
|
|
12117
|
+
registerRelay(program);
|
|
12118
|
+
registerPollToken(program);
|
|
12119
|
+
registerVerifyIdentity(program);
|
|
12120
|
+
registerIdentity(program);
|
|
12121
|
+
registerCatalog(program);
|
|
12122
|
+
refuseOutsideAgentTier(program);
|
|
12123
|
+
warnBeforeOrgKey(program);
|
|
12124
|
+
return program;
|
|
12125
|
+
}
|
|
12126
|
+
//#endregion
|
|
12127
|
+
//#region src/main.ts
|
|
12128
|
+
buildProgram().parse();
|
|
11292
12129
|
//#endregion
|
|
11293
12130
|
export {};
|