@rine-network/cli 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -2
  2. package/dist/main.js +389 -188
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -7,7 +7,7 @@ Command-line client for [rine.network](https://rine.network) — messaging infra
7
7
  Zero-install (Node 20+ required, no setup):
8
8
 
9
9
  ```sh
10
- npx @rine-network/cli --help
10
+ npx @rine-network/cli@latest --help
11
11
  ```
12
12
 
13
13
  Global install:
@@ -38,7 +38,7 @@ rine inbox
38
38
  Or with npx (no install needed):
39
39
 
40
40
  ```sh
41
- npx @rine-network/cli onboard --email you@yourdomain.com --name "My Org" --slug my-org --agent-name my-agent
41
+ npx @rine-network/cli@latest onboard --email you@yourdomain.com --name "My Org" --slug my-org --agent-name my-agent
42
42
  ```
43
43
 
44
44
  ## Commands
package/dist/main.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { Command, Option } from "commander";
3
- import { A2A_CLEARTEXT_NOTICE, ACTING_AGENT_ENV, ACTING_AGENT_HEADER, ACTOR_SURFACES, DEFAULT_PROFILE, ENCRYPTION_VERSION_HYBRID_V2, FUNNEL_TIERS, GROUP_NOT_FOUND_LEAD, GROUP_READERS_NOTICE, HttpClient, IdempotencyStore, KEY_NOT_CURRENT_MESSAGE, KeyPackageRotation, MLS_ERR_GROUP_INACTIVE, MLS_EVICTED_BY_COMMIT, MalformedPageError, MlsEstablishStep, MlsInitInFlightError, OrgReader, PHRASE_FILE, PHRASE_INSTRUCTION, ReadGapReason, ReadKey, ReaderNetworkError, RineApiError, SENDER_KEY_UNAVAILABLE_CODE, SENDER_KEY_UNAVAILABLE_PREVIEW, SeatUpdateStatus, THREAD_REF_SURFACES, THREAD_UNAVAILABLE, TokenBucket, UUID_RE, VOTE_DURATION_RULE, VOTE_ELECTORATE_RULE, X402Error, X402FacilitatorError, X402_ERROR, X402_MESSAGE_TYPE, a2aCleartextMark, a2aCleartextPayload, a2aCleartextPlaintext, actorFromEnv, addMlsGroupMembers, admissionHeadline, admittedAgentIds, agentKeysExist, agentKeysFromPrivate, agentLabel, asSenderKeyUnavailable, assertBranchName, assertNoMlsDowngrade, buildIssueCertDeps, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildPeerVerification, buildReceiptMessage, cliSyncRemedy, clipToWidth, clipWithEllipsis, clusterWidth, compareVerificationWordsForAgent, connectTunnel, controlFrameReplyRefusal, createBranch, createHook, createWallet, decryptGroupMessageWithRecovery, decryptMessage, decryptThreadRows, deleteGroupMember, deleteHookSecret, deriveBranch, describeEscrowGaps, describeMlsReclamation, describeMlsRecovery, describeVoteEligibility, displayHandle, displayWidth, encryptGroupMessage, encryptionLine, ensureCert, establishMlsMembership, evictionMessage, fetchAgents, fetchGroupMembers, findingKey, fitFromTo, fitGroupSender, formatError, fromBase64Url, gapToJson, getOrCreateSenderKey, getOrRefreshToken, getWalletAddress, graphemes, groupAcceptsMlsSendOnly, groupAdmissionSkipSentence, groupEncryption, groupEncryption as groupEncryption$1, groupIsMls, groupMlsInitInFlight, handleCompletionNote, handleWebhookRequest, hasRoot, hasSpiffeEndpoint, holdsAnyMlsState, holdsBranchKeys, holdsMlsState, hookNameError, humanTime, impliedVoteEligibilityReason, inBackground, ingestSenderKeyDistribution, initMlsGroup, inviteNominates, isA2aCleartext, isAuthenticityFailure, isAutoPayable, isControlFrameType, isDecryptableVersion, isEpochConflict, isGroupEncryptionVersion, isMlsResyncUnavailable, isMlsRotatedLeaf, isPathSafeId, isRecoverableMlsRead, isX402MessageType, jitteredDelayMs, jitteredRefreshMargin, listMyInvites, loadAgentKeys, loadHookSecret, loadMeta, loadMlsGroup, loadMlsState, loadOrgFromOwner, loadPolicy, loadProfiles, loadSenderKeyStates, loadTokenCache, loadWalletKey, makeEdgePipeFactory, markA2aCleartext, matchedQuoteToWire, messageToJson, mlsAdmissionSkipSentence, mlsErrorCode, mlsInitInFlightSync, mlsReadRefusal, namesASeatedSibling, nextReconnectBackoffSeconds, normalizeActor, normalizeHandle, openMlsClient, orgIdOfAgent, ownIdentityFor, parseFacilitatorHeaders, parseRecipientKey, parseX402Payload, peerVerificationLines, performAgentCreation, performRecovery, performRegistration, principalString, readDailySpent, readOwnerPhrase, readThreadPage, readableGroupById, recipientKeyWords, recordPeerVerification, recoverGroup, refusalReceiptBody, renewalDueWithJitter, reportFailedSetup, requireVerifiedPlaintext, reserveSpend, resolveAgent, resolveApiUrl, resolveAuth, resolveConfigDir, resolveFacilitatorConfig, resolveGroup, resolveGroupByHandle, resolveGroupForJoin, resolveOwnerDir, resolvePayeeRequirement, resolveThreadRef, resolveToUuid, restoreOwnerFromPhrase, resumeMlsGroupAdmission, retireLocalGroupState, retirementMessage, retryAfterMsFromError, revokeBranch, rotateAgentWithSeats, safeBlock, saveAgentKeys, savePolicy, saveProfiles, saveTokenCache, scrub, sealAndPostMlsGroupMessage, sealBranchBundle, sealForAgent, seatUpdateLine, seatedMemberAfterConflict, selectRequirement, sendGroupInviteNotification, sendReceipt, senderKeyExplainer, settleToReceipt, singleActorValue, sleep, startTlsListener, startupEscrowSweep, toBase64Url, validateEncryptionKey, validateSigningKey, validateSlug, verificationWordsLines, verifyIdentitySpiffe, walletKeyExists, withA2aCleartextNotice, withEvictionPointer, withPeekHeader, writeAtomic } from "@rine-network/core";
3
+ import { A2A_CLEARTEXT_NOTICE, ACTING_AGENT_ENV, ACTING_AGENT_HEADER, ACTOR_SURFACES, DEFAULT_PROFILE, ENCRYPTION_VERSION_HYBRID_V2, FUNNEL_TIERS, GROUP_NOT_FOUND_LEAD, GROUP_READERS_NOTICE, HttpClient, IdempotencyStore, KEY_NOT_CURRENT_MESSAGE, KeyPackageRotation, MLS_ERR_GROUP_INACTIVE, MLS_EVICTED_BY_COMMIT, MalformedPageError, MlsEstablishStep, MlsInitInFlightError, OrgReader, PHRASE_FILE, PHRASE_INSTRUCTION, ReadGapReason, ReadKey, ReaderNetworkError, RineApiError, SENDER_KEY_UNAVAILABLE_CODE, SENDER_KEY_UNAVAILABLE_PREVIEW, SeatUpdateStatus, THREAD_REF_SURFACES, THREAD_UNAVAILABLE, TokenBucket, UUID_RE, VOTE_DURATION_RULE, VOTE_ELECTORATE_RULE, X402Error, X402FacilitatorError, X402_ERROR, X402_MESSAGE_TYPE, a2aCleartextMark, a2aCleartextPayload, a2aCleartextPlaintext, ackAfterRead, ackFailureNotice, actorFromEnv, addMlsGroupMembers, admissionHeadline, admittedAgentIds, agentKeysExist, agentKeysFromPrivate, agentLabel, asSenderKeyUnavailable, assertBranchName, assertNoMlsDowngrade, buildIssueCertDeps, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildPeerVerification, buildReceiptMessage, cliSyncRemedy, clipToWidth, clipWithEllipsis, clusterWidth, compareVerificationWordsForAgent, connectTunnel, controlFrameReplyRefusal, createAckBatcher, createBranch, createHook, createWallet, decryptGroupMessageWithRecovery, decryptMessage, decryptThreadRows, deleteGroupMember, deleteHookSecret, deriveBranch, describeEscrowGaps, describeMlsReclamation, describeMlsRecovery, describeVoteEligibility, displayHandle, displayWidth, encryptGroupMessage, encryptionLine, ensureCert, establishMlsMembership, evictionMessage, fetchAgents, fetchGroupMembers, findingKey, fitFromTo, fitGroupSender, formatError, fromBase64Url, gapToJson, getOrCreateSenderKey, getOrRefreshToken, getWalletAddress, graphemes, groupAcceptsMlsSendOnly, groupAdmissionSkipSentence, groupAuthenticityStatus, groupEncryption, groupEncryption as groupEncryption$1, groupIsMls, groupMlsInitInFlight, handleCompletionNote, handleWebhookRequest, hasRoot, hasSpiffeEndpoint, holdsAnyMlsState, holdsBranchKeys, holdsMlsState, hookNameError, humanTime, impliedVoteEligibilityReason, inBackground, ingestSenderKeyDistribution, initMlsGroup, inviteNominates, isA2aCleartext, isAuthenticityFailure, isAutoPayable, isControlFrameType, isDecryptableVersion, isEpochConflict, isGroupEncryptionVersion, isMlsResyncUnavailable, isMlsRotatedLeaf, isPathSafeId, isRecoverableMlsRead, isSettledRow, isX402MessageType, jitteredDelayMs, jitteredRefreshMargin, listMyInvites, loadAgentKeys, loadHookSecret, loadMeta, loadMlsGroup, loadMlsState, loadOrgFromOwner, loadPolicy, loadProfiles, loadSenderKeyStates, loadTokenCache, loadWalletKey, makeEdgePipeFactory, markA2aCleartext, markDeliveredAs, matchedQuoteToWire, messageToJson, mlsAdmissionSkipSentence, mlsErrorCode, mlsInitInFlightSync, mlsReadRefusal, namesASeatedSibling, nextReconnectBackoffSeconds, normalizeActor, normalizeHandle, openMlsClient, orgIdOfAgent, ownIdentityFor, parseFacilitatorHeaders, parseRecipientKey, parseX402Payload, peerVerificationLines, performAgentCreation, performRecovery, performRegistration, principalString, raceDeadline, readDailySpent, readOwnerPhrase, readThreadPage, readableGroupById, recipientKeyWords, recordPeerVerification, recoverGroup, refusalReceiptBody, renewalDueWithJitter, reportFailedSetup, requireVerifiedPlaintext, reserveSpend, resolveAgent, resolveApiUrl, resolveAuth, resolveConfigDir, resolveFacilitatorConfig, resolveGroup, resolveGroupByHandle, resolveGroupForJoin, resolveOwnerDir, resolvePayeeRequirement, resolveThreadRef, resolveToUuid, restoreOwnerFromPhrase, resumeMlsGroupAdmission, retireLocalGroupState, retirementMessage, retryAfterMsFromError, revokeBranch, rotateAgentWithSeats, safeBlock, saveAgentKeys, savePolicy, saveProfiles, saveTokenCache, scrub, sealAndPostMlsGroupMessage, sealBranchBundle, sealForAgent, seatUpdateLine, seatedMemberAfterConflict, selectRequirement, sendGroupInviteNotification, sendReceipt, senderKeyExplainer, settleToReceipt, singleActorValue, sleep, sleepWithSignal, startTlsListener, startupEscrowSweep, toBase64Url, validateEncryptionKey, validateSigningKey, validateSlug, verificationWordsLines, verifyIdentitySpiffe, walletKeyExists, withA2aCleartextNotice, withEvictionPointer, withPeekHeader, writeAtomic } from "@rine-network/core";
4
4
  import * as fs$1 from "node:fs";
5
5
  import fs, { readFileSync } from "node:fs";
6
6
  import readline from "node:readline";
@@ -787,14 +787,14 @@ function registerAgent(program) {
787
787
  "Outgoing Policy": data.outgoing_policy ?? "send_all"
788
788
  }]);
789
789
  }));
790
- agent.command("update").description("Update agent details").argument("<agent-id>", "Agent ID").option("--name <name>", "Agent name").option("--[no-]human-oversight", "Require human oversight").option("--incoming-policy <policy>", "Incoming message policy (accept_all|groups_only)").option("--outgoing-policy <policy>", "Outgoing message policy (send_all|groups_only)").action(withClient(program, async ({ client, gOpts }, agentId, opts) => {
790
+ agent.command("update").description("Update agent details").argument("<agent-id>", "Agent ID").option("--[no-]human-oversight", "Require human oversight").option("--unlisted", "Hide the agent from the directory").option("--no-unlisted", "List the agent in the directory again").option("--incoming-policy <policy>", "Incoming message policy (accept_all|groups_only)").option("--outgoing-policy <policy>", "Outgoing message policy (send_all|groups_only)").action(withClient(program, async ({ client, gOpts }, agentId, opts) => {
791
791
  const body = {};
792
- if (opts.name) body.name = opts.name;
793
792
  if (opts.humanOversight !== void 0) body.human_oversight = opts.humanOversight;
794
793
  if (opts.incomingPolicy) body.incoming_policy = opts.incomingPolicy;
795
794
  if (opts.outgoingPolicy) body.outgoing_policy = opts.outgoingPolicy;
795
+ if (opts.unlisted !== void 0) body.unlisted = opts.unlisted;
796
796
  if (Object.keys(body).length === 0) {
797
- printError("At least one of --name, --human-oversight, --incoming-policy, --outgoing-policy is required");
797
+ printError("At least one of --incoming-policy, --outgoing-policy, --human-oversight, --no-human-oversight, --unlisted or --no-unlisted is required");
798
798
  process.exitCode = 2;
799
799
  return;
800
800
  }
@@ -1270,7 +1270,7 @@ function registerDiscoverGroups(discover, program) {
1270
1270
  Name: g.name,
1271
1271
  Handle: g.handle,
1272
1272
  Description: g.description ?? "",
1273
- Enrollment: g.enrollment_policy,
1273
+ Enrolment: g.enrollment_policy,
1274
1274
  Members: g.member_count
1275
1275
  })));
1276
1276
  })).command("inspect").description("Inspect a public group").argument("<group-id>", DIRECTORY_GROUP_ID_HELP).action(withErrorHandler(program, async (gOpts, groupId) => {
@@ -1291,7 +1291,7 @@ function registerDiscoverGroups(discover, program) {
1291
1291
  Handle: data.handle,
1292
1292
  Description: data.description ?? "",
1293
1293
  "Org ID": data.org_id,
1294
- Enrollment: data.enrollment_policy,
1294
+ Enrolment: data.enrollment_policy,
1295
1295
  Members: data.member_count,
1296
1296
  Created: data.created_at
1297
1297
  }]);
@@ -1474,23 +1474,23 @@ function registerFulfill(program) {
1474
1474
  const payeeAgentId = await actingAgent();
1475
1475
  const message = await client.get(`/messages/${messageId}`);
1476
1476
  if (message.type !== X402_MESSAGE_TYPE.PAYMENT) {
1477
- printError(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT}. Nothing to fulfill.`);
1477
+ printError(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT}. Nothing to fulfil.`);
1478
1478
  process.exitCode = 2;
1479
1479
  return;
1480
1480
  }
1481
1481
  const payerAgentId = message.from_agent_id;
1482
1482
  if (!payerAgentId) {
1483
- printError("Cannot fulfill: the payment has no resolvable sender.");
1483
+ printError("Cannot fulfil: the payment has no resolvable sender.");
1484
1484
  process.exitCode = 1;
1485
1485
  return;
1486
1486
  }
1487
1487
  if (payeeAgentId === payerAgentId) {
1488
- printError("Cannot fulfill your own payment.");
1488
+ printError("Cannot fulfil your own payment.");
1489
1489
  process.exitCode = 1;
1490
1490
  return;
1491
1491
  }
1492
1492
  if (message.to_agent_id && message.to_agent_id !== payeeAgentId) {
1493
- printError(`Payment ${messageId} is addressed to agent ${message.to_agent_id}, not ${payeeAgentId}. Fulfill as that agent (--agent) — only the addressee holds the key that opens it.`);
1493
+ printError(`Payment ${messageId} is addressed to agent ${message.to_agent_id}, not ${payeeAgentId}. Fulfil as that agent (--agent) — only the addressee holds the key that opens it.`);
1494
1494
  process.exitCode = 1;
1495
1495
  return;
1496
1496
  }
@@ -1788,7 +1788,7 @@ function groupRow(g) {
1788
1788
  ID: g.id,
1789
1789
  Name: g.name,
1790
1790
  Handle: g.handle,
1791
- Enrollment: g.enrollment_policy,
1791
+ Enrolment: g.enrollment_policy,
1792
1792
  Visibility: g.visibility,
1793
1793
  Members: g.member_count,
1794
1794
  "Conversation ID": g.conversation_id ?? "(none — nothing has been said in this group yet)",
@@ -1811,7 +1811,7 @@ function groupDetailRow(g, handles) {
1811
1811
  Name: g.name,
1812
1812
  Handle: g.handle,
1813
1813
  Description: g.description ?? "",
1814
- Enrollment: g.enrollment_policy,
1814
+ Enrolment: g.enrollment_policy,
1815
1815
  Visibility: g.visibility,
1816
1816
  Isolated: g.isolated,
1817
1817
  "Vote Duration": g.vote_duration_hours,
@@ -2110,7 +2110,7 @@ function printCreated$1(group, roster, admission, json, handles) {
2110
2110
  }
2111
2111
  }
2112
2112
  function registerGroupCreate(program, group) {
2113
- group.command("create").description(`Create a new group. ${GROUP_READERS_NOTICE}`).requiredOption("--name <name>", "Group name (DNS-safe slug)").option("--description <desc>", DESCRIPTION_HELP).option("--enrollment <policy>", "Enrollment policy (open|closed|majority|unanimity). `open` runs Sender Keys, which are NOT post-quantum").option("--visibility <vis>", "Required. `public` lists the group at dir.rine.network and turns the join signal off; `private` does neither").option("--member <id>", "Invite an agent into the new group (repeatable). A roster invites — it never seats — and it invites under every enrollment policy, because you are the only member at founding and a vote would auto-approve each row", collect, []).option("--isolated", "Isolate group communication").option("--vote-duration <hours>", VOTE_DURATION_RULE).addOption(actorOption("which agent is acting, and founds the group")).action(withClient(program, async (ctx, opts) => {
2113
+ group.command("create").description(`Create a new group. ${GROUP_READERS_NOTICE}`).requiredOption("--name <name>", "Group name (DNS-safe slug)").option("--description <desc>", DESCRIPTION_HELP).option("--enrollment <policy>", "Enrolment policy (open|closed|majority|unanimity). `open` runs Sender Keys, which are NOT post-quantum").option("--visibility <vis>", "Required. `public` lists the group at dir.rine.network and turns the join signal off; `private` does neither").option("--member <id>", "Invite an agent into the new group (repeatable). A roster invites — it never seats — and it invites under every enrolment policy, because you are the only member at founding and a vote would auto-approve each row", collect, []).option("--isolated", "Isolate group communication").option("--vote-duration <hours>", VOTE_DURATION_RULE).addOption(actorOption("which agent is acting, and founds the group")).action(withClient(program, async (ctx, opts) => {
2114
2114
  const refusal = visibilityRefusal(opts.visibility);
2115
2115
  if (refusal) {
2116
2116
  printError(refusal);
@@ -2180,7 +2180,7 @@ function registerGroupCrud(program, group) {
2180
2180
  printText(encryptionLine(data, CLI_UNFOUNDED_REPAIR));
2181
2181
  if (evicted) printText(`\n${evictedMessage(data.id)}`);
2182
2182
  }));
2183
- group.command("update").description("Update group settings").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).option("--description <desc>", DESCRIPTION_HELP).option("--enrollment <policy>", "Enrollment policy (open|closed|majority|unanimity)").option("--visibility <vis>", "`public` lists the group at dir.rine.network and turns the join signal off; `private` does neither").option("--vote-duration <hours>", VOTE_DURATION_RULE).action(withClient(program, async (ctx, ref, opts) => {
2183
+ group.command("update").description("Update group settings").argument("<group-ref>", GROUP_REFERENCE_HELP).addOption(actorOption()).option("--description <desc>", DESCRIPTION_HELP).option("--enrollment <policy>", "Enrolment policy (open|closed|majority|unanimity)").option("--visibility <vis>", "`public` lists the group at dir.rine.network and turns the join signal off; `private` does neither").option("--vote-duration <hours>", VOTE_DURATION_RULE).action(withClient(program, async (ctx, ref, opts) => {
2184
2184
  const { client, gOpts, actingAgent, agents } = ctx;
2185
2185
  const body = {};
2186
2186
  if (opts.description !== void 0) body.description = opts.description;
@@ -2638,7 +2638,7 @@ function registerGroupMembership(program, group) {
2638
2638
  //#endregion
2639
2639
  //#region src/commands/group-requests.ts
2640
2640
  /** An open group has no ratchet tree, so there is no admission to resume in it. */
2641
- const NOT_AN_MLS_GROUP = "This group runs on Sender Keys, not MLS, so it has no ratchet tree to seat anyone in. Open-enrollment groups are sender-key groups by design: MLS would hand an unattested joiner a cryptographic seat, so the server keeps open enrollment off the MLS path. There is nothing to resume here.";
2641
+ const NOT_AN_MLS_GROUP = "This group runs on Sender Keys, not MLS, so it has no ratchet tree to seat anyone in. Open-enrolment groups are sender-key groups by design: MLS would hand an unattested joiner a cryptographic seat, so the server keeps open enrolment off the MLS path. There is nothing to resume here.";
2642
2642
  function printAdmission(result, json) {
2643
2643
  if (json) {
2644
2644
  printJson(result);
@@ -3242,6 +3242,24 @@ function addInboxCommand(parent, program) {
3242
3242
  * two different outputs: stderr prose for a human, and a field on the `--json`
3243
3243
  * envelope for a program. A helper that printed could only serve one of them.
3244
3244
  */
3245
+ /**
3246
+ * Mark a fetched message delivered once reading it is settled: it opened, was
3247
+ * never ciphertext, or its author was refused. `opened` is null when no decrypt
3248
+ * was attempted (no keys, no authenticated sender). A failed mark is a stderr
3249
+ * warning and the read goes on; the message simply stays new.
3250
+ */
3251
+ async function markIfSettled(client, agentId, data, opened, peek) {
3252
+ const result = opened?.result;
3253
+ const verification_status = result?.verificationStatus ?? opened?.forgedStatus;
3254
+ const failure = await ackAfterRead(client, agentId, [data.id], {
3255
+ settled: isSettledRow({
3256
+ ...data,
3257
+ verification_status
3258
+ }, result?.plaintext !== void 0),
3259
+ peek
3260
+ });
3261
+ if (failure) printError(`Warning: could not mark ${data.id} delivered (${failure.message}); it stays new`);
3262
+ }
3245
3263
  /** Decrypt one message, dispatching on its encryption version. Never throws. */
3246
3264
  async function openMessage(opts) {
3247
3265
  const { client, configDir, agentId, data, fromAgentId } = opts;
@@ -3260,7 +3278,11 @@ async function openMessage(opts) {
3260
3278
  refusal: null
3261
3279
  };
3262
3280
  } catch (err) {
3263
- return { refusal: refusalFor(err, groupId) };
3281
+ const forgedStatus = groupAuthenticityStatus(err) ?? void 0;
3282
+ return {
3283
+ refusal: refusalFor(err, groupId),
3284
+ forgedStatus
3285
+ };
3264
3286
  }
3265
3287
  }
3266
3288
  /**
@@ -3309,20 +3331,19 @@ function refusalFor(err, groupId) {
3309
3331
  function addReadCommand(parent, program) {
3310
3332
  parent.command("read").description("Read and decrypt a message by ID").argument("<message-id>", "Message ID").addOption(actorOption("which agent is acting, and whose key decrypts (name, handle, or agent ID)")).option("--peek", "Read without marking the message delivered (it stays new)").action(withClient(program, async ({ client, gOpts, configDir, actingAgent }, messageId, opts) => {
3311
3333
  const agentId = await actingAgent();
3312
- const data = await client.get(`/messages/${messageId}`, void 0, withPeekHeader(void 0, opts.peek));
3334
+ const data = await client.get(`/messages/${messageId}`, void 0, withPeekHeader(void 0, true));
3313
3335
  const fromAgentId = data.from_agent_id;
3314
- const canDecrypt = fromAgentId !== void 0 && isDecryptableVersion(data.encryption_version) && agentKeysExist(configDir, agentId);
3315
- let refusal = null;
3316
- if (canDecrypt) {
3317
- const opened = await openMessage({
3318
- client,
3319
- configDir,
3320
- agentId,
3321
- data,
3322
- fromAgentId
3323
- });
3336
+ const opened = fromAgentId !== void 0 && isDecryptableVersion(data.encryption_version) && agentKeysExist(configDir, agentId) ? await openMessage({
3337
+ client,
3338
+ configDir,
3339
+ agentId,
3340
+ data,
3341
+ fromAgentId
3342
+ }) : null;
3343
+ await markIfSettled(client, agentId, data, opened, opts.peek);
3344
+ const refusal = opened?.refusal ?? null;
3345
+ if (opened) {
3324
3346
  const decResult = opened.result;
3325
- refusal = opened.refusal;
3326
3347
  if (refusal !== null && !gOpts.json) printError(refusal.message);
3327
3348
  if (decResult) {
3328
3349
  if (ingestSenderKeyDistribution(configDir, agentId, data.type, decResult)) printText("Sender key ingested");
@@ -3696,7 +3717,7 @@ function announcePhrase(opts) {
3696
3717
  //#endregion
3697
3718
  //#region src/commands/onboard.ts
3698
3719
  function registerOnboard(program) {
3699
- program.command("onboard").description("Register a new organization and create your first agent").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organization name").requiredOption("--slug <slug>", "Organization slug").requiredOption("--agent-name <name>", "Name for the first agent").option("--[no-]human-oversight", "Require human oversight (default: true)").option("--unlisted", "Mark agent as unlisted (not in public directory)").option("--verify-identity", "After creating the agent, prove a SPIFFE identity (auto-runs when SPIFFE_ENDPOINT_SOCKET is set)").option("--svid <jwt>", "SPIFFE JWT-SVID to use for --verify-identity (when no Workload API auto-fetch is available)").action(withErrorHandler(program, async (gOpts, opts) => {
3720
+ program.command("onboard").description("Register a new organisation and create your first agent").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organisation name").requiredOption("--slug <slug>", "Organisation slug").requiredOption("--agent-name <name>", "Name for the first agent").option("--[no-]human-oversight", "Require human oversight (default: true)").option("--unlisted", "Mark agent as unlisted (not in public directory)").option("--verify-identity", "After creating the agent, prove a SPIFFE identity (auto-runs when SPIFFE_ENDPOINT_SOCKET is set)").option("--svid <jwt>", "SPIFFE JWT-SVID to use for --verify-identity (when no Workload API auto-fetch is available)").action(withErrorHandler(program, async (gOpts, opts) => {
3700
3721
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
3701
3722
  const dirs = resolveDirs();
3702
3723
  const apiUrl = resolveApiUrl();
@@ -3779,10 +3800,10 @@ function registerOnboard(program) {
3779
3800
  }
3780
3801
  //#endregion
3781
3802
  //#region src/commands/org-branch.ts
3782
- const NO_ROOT = "Creating a branch needs this org's root key (root.key in the owner dir). A delegate cannot create branches.";
3803
+ const NO_ROOT = "Creating a branch needs this org's root key (root.key in the owner directory). A delegate cannot create branches.";
3783
3804
  function registerOrgBranch(org, program) {
3784
3805
  const branch = org.command("branch").description("Delegate a subtree of this org to a partner; branch names are public, never put a customer name or a secret in one");
3785
- branch.command("create <name>").description("Create a branch and seal its bundle to a recipient key").requiredOption("--to <recipient-key>", "The fleet's recipient key").option("--out <file>", "Where to write the sealed bundle").option("--words-confirmed", "Skip the interactive word comparison").action(withClient(program, async ({ client, gOpts, ownerDir }, name, opts) => {
3806
+ branch.command("create <name>").description("Create a branch and seal its bundle to a recipient key").requiredOption("--to <recipient-key>", "The partner's recipient key").option("--out <file>", "Where to write the sealed bundle").option("--words-confirmed", "Skip the interactive word comparison").action(withClient(program, async ({ client, gOpts, ownerDir }, name, opts) => {
3786
3807
  assertBranchName(name);
3787
3808
  const org = loadOrgFromOwner(ownerDir);
3788
3809
  if (org === void 0) {
@@ -3913,7 +3934,7 @@ async function restoreOwnerOnly(dirs, profile, json) {
3913
3934
  console.log(`Org verification words: ${orgWords}`);
3914
3935
  }
3915
3936
  function registerOrgRecover(org, program) {
3916
- org.command("recover").description("Rebuild this device from the 24-word recovery phrase").option("--owner-only", "Write only the org root and profile into the owner dir: no request, no leaf keys, no group reseat").action(withErrorHandler(program, async (gOpts, opts) => {
3937
+ org.command("recover").description("Rebuild this device from the 24-word recovery phrase").option("--owner-only", "Write only the org root and profile into the owner directory: no request, no leaf keys, no group reseat").action(withErrorHandler(program, async (gOpts, opts) => {
3917
3938
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
3918
3939
  if (opts.ownerOnly) {
3919
3940
  await restoreOwnerOnly(resolveDirs(), profile, gOpts.json);
@@ -3927,7 +3948,7 @@ function registerOrgRecover(org, program) {
3927
3948
  }));
3928
3949
  org.command("phrase").description("Show the recovery phrase again (terminal only)").action(withErrorHandler(program, () => {
3929
3950
  if (process.stdout.isTTY !== true) {
3930
- printError("rine org phrase shows the phrase on a terminal only; the phrase file is in the owner dir.");
3951
+ printError("rine org phrase shows the phrase on a terminal only; the phrase file is in the owner directory.");
3931
3952
  process.exitCode = 2;
3932
3953
  return;
3933
3954
  }
@@ -3950,14 +3971,14 @@ function renderOrg(data, opts) {
3950
3971
  }]);
3951
3972
  }
3952
3973
  function registerOrg(program) {
3953
- const org = program.command("org").description("Organization management");
3974
+ const org = program.command("org").description("Organisation management");
3954
3975
  registerOrgRecover(org, program);
3955
3976
  registerOrgBranch(org, program);
3956
- org.command("get").description("Get organization details").action(withClient(program, async ({ client, gOpts }) => {
3977
+ org.command("get").description("Get organisation details").action(withClient(program, async ({ client, gOpts }) => {
3957
3978
  const { org: data } = await client.get("/whoami");
3958
3979
  renderOrg(data, gOpts);
3959
3980
  }));
3960
- org.command("update").description("Update organization details").option("--name <name>", "Organization name").option("--contact-email <email>", "Contact email address").option("--country-code <cc>", "ISO country code (e.g. DE)").action(withClient(program, async ({ client, gOpts }, opts) => {
3981
+ org.command("update").description("Update organisation details").option("--name <name>", "Organisation name").option("--contact-email <email>", "Contact email address").option("--country-code <cc>", "ISO country code (e.g. DE)").action(withClient(program, async ({ client, gOpts }, opts) => {
3961
3982
  const body = {};
3962
3983
  if (opts.name) body.name = opts.name;
3963
3984
  if (opts.contactEmail) body.contact_email = opts.contactEmail;
@@ -4123,7 +4144,7 @@ function registerPollToken(program) {
4123
4144
  //#endregion
4124
4145
  //#region src/commands/register.ts
4125
4146
  function registerRegister(program) {
4126
- program.command("register").description("Register a new organization (two-step PoW flow). Writes the org root key and recovery phrase to the owner dir").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organization name").requiredOption("--slug <slug>", "Organization slug").action(withErrorHandler(program, async (gOpts, opts) => {
4147
+ program.command("register").description("Register a new organisation (two-step PoW flow). Writes the org root key and recovery phrase to the owner directory").requiredOption("--email <email>", "Email address").requiredOption("--name <name>", "Organisation name").requiredOption("--slug <slug>", "Organisation slug").action(withErrorHandler(program, async (gOpts, opts) => {
4127
4148
  const profile = gOpts.profile ?? DEFAULT_PROFILE;
4128
4149
  const dirs = resolveDirs();
4129
4150
  const apiUrl = resolveApiUrl();
@@ -4538,7 +4559,7 @@ async function runRelayLoop(ctx) {
4538
4559
  * mux framing or crypto: they call the rine-core funnel entry points.
4539
4560
  */
4540
4561
  function registerRelay(program) {
4541
- program.command("relay").description("Run the inbound webhook funnel relay (long-lived foreground daemon)").addOption(actorOption()).option("--hook <name>", "Hook name to relay", "default").option("--port <n>", "Local TLS listener port", "8443").option("--secret-file <path>", "Read the HMAC secret from a file").option("--secret-env <VAR>", "Read the HMAC secret from an env var").option("--staging", "Use the Let's Encrypt staging CA (dev)").option("--verbose", "Verbose reconnect logging").action(async (opts, command) => {
4562
+ program.command("relay").description("Run the inbound webhook funnel relay (long-lived foreground daemon)").addOption(actorOption()).option("--hook <name>", "Hook name to relay", "default").option("--port <n>", "Local TLS listener port", "8443").option("--secret-file <path>", "Read the HMAC secret from a file").option("--secret-env <VAR>", "Read the HMAC secret from an environment variable").option("--staging", "Use the Let's Encrypt staging CA (dev)").option("--verbose", "Verbose reconnect logging").action(async (opts, command) => {
4542
4563
  try {
4543
4564
  const gOpts = program.opts();
4544
4565
  const configDir = resolveConfigDir();
@@ -4565,6 +4586,43 @@ function registerRelay(program) {
4565
4586
  });
4566
4587
  }
4567
4588
  //#endregion
4589
+ //#region src/commands/stream-connection.ts
4590
+ /**
4591
+ * One SSE connection, watched by a heartbeat timer: silence for
4592
+ * `heartbeatTimeoutMs` closes it, as do a server close and a stop request.
4593
+ */
4594
+ function openStreamConnection({ url, headers, heartbeatTimeoutMs, onMessage }) {
4595
+ let heartbeatTimer;
4596
+ let settle = () => {};
4597
+ const closed = new Promise((resolve) => {
4598
+ settle = resolve;
4599
+ });
4600
+ const end = (reason, closeSource) => {
4601
+ if (heartbeatTimer) clearTimeout(heartbeatTimer);
4602
+ if (closeSource) es.close();
4603
+ settle(reason);
4604
+ };
4605
+ const resetHeartbeatTimer = () => {
4606
+ if (heartbeatTimer) clearTimeout(heartbeatTimer);
4607
+ heartbeatTimer = setTimeout(() => end("heartbeat_timeout", true), heartbeatTimeoutMs);
4608
+ };
4609
+ const es = createEventSource({
4610
+ url,
4611
+ headers,
4612
+ onMessage: (event) => {
4613
+ resetHeartbeatTimer();
4614
+ onMessage(event);
4615
+ },
4616
+ onDisconnect: () => end("server_close", false),
4617
+ onScheduleReconnect: () => end("server_close", true)
4618
+ });
4619
+ resetHeartbeatTimer();
4620
+ return {
4621
+ closed,
4622
+ stop: () => end("signal", true)
4623
+ };
4624
+ }
4625
+ //#endregion
4568
4626
  //#region src/commands/stream-cursor.ts
4569
4627
  function cursorPath(configDir) {
4570
4628
  return join(configDir, "state", "stream-cursor.json");
@@ -4599,6 +4657,19 @@ function saveStreamCursor(configDir, agentId, eventId) {
4599
4657
  } catch {}
4600
4658
  }
4601
4659
  //#endregion
4660
+ //#region src/commands/stream-lifecycle.ts
4661
+ /** One lifecycle event, on stdout (JSON mode) or stderr (`--monitor`, so stdout stays messages only). */
4662
+ function emitLifecycle(gOpts, monitor, data) {
4663
+ if (gOpts.json) {
4664
+ const line = JSON.stringify({
4665
+ event: "lifecycle",
4666
+ data
4667
+ });
4668
+ if (monitor) process.stderr.write(`${line}\n`);
4669
+ else console.log(line);
4670
+ }
4671
+ }
4672
+ //#endregion
4602
4673
  //#region src/commands/stream-cleartext.ts
4603
4674
  /**
4604
4675
  * The preview for a message that arrived as A2A cleartext, or null for every
@@ -4607,8 +4678,8 @@ function saveStreamCursor(configDir, agentId, eventId) {
4607
4678
  * A cleartext body is readable without any key, so it is shown like any other
4608
4679
  * unverified line — the `?` mark, the same one every unverified preview uses —
4609
4680
  * led by the notice that says the body was never end-to-end encrypted. A
4610
- * payload that does not decode throws, and the caller's own catch renders the
4611
- * generic line.
4681
+ * payload that does not decode throws, and the caller treats the row as one
4682
+ * with no preview.
4612
4683
  */
4613
4684
  function a2aCleartextPreview(data) {
4614
4685
  const row = {
@@ -4651,61 +4722,253 @@ function parseRow(data) {
4651
4722
  * How `rine stream` renders one SSE `message` event: a single preview line,
4652
4723
  * decrypted when this agent can open it, plus at most one stderr notice.
4653
4724
  */
4654
- /** Never rejects: an event it cannot render becomes a truncated `[message]` line. */
4655
- async function formatMessageLine(dataStr, agentId, configDir, client, explain) {
4725
+ /** The one-line preview of a message that has already been opened. */
4726
+ function renderOpened({ data, cleartext, attempted, result, forgedStatus, unavailable }, explain) {
4727
+ const ts = (data.created_at ?? "").slice(0, 19) || "?";
4728
+ const sender = data.sender_handle ?? String(data.from_agent_id ?? "?");
4729
+ const msgType = data.type ?? "?";
4730
+ const target = data.group_handle ? `${data.group_handle} (${msgType})` : msgType;
4731
+ let preview = cleartext ?? "[encrypted]";
4732
+ let notice = null;
4733
+ const verdict = result?.verificationStatus ?? forgedStatus;
4734
+ if (verdict && isAuthenticityFailure(verdict)) preview = verdict === "sender-mismatch" ? "[✗ sender mismatch]" : "[✗ invalid signature]";
4735
+ else if (result?.plaintext !== void 0) preview = `[${result.verified ? "✓" : "?"}] ${result.plaintext.slice(0, 60)}`;
4736
+ else if (unavailable !== null) {
4737
+ preview = data.id ? `${SENDER_KEY_UNAVAILABLE_PREVIEW} rine message read ${data.id}` : SENDER_KEY_UNAVAILABLE_PREVIEW;
4738
+ notice = explain(unavailable.message).notice;
4739
+ } else if (attempted && isDecryptableVersion(data.encryption_version)) preview = "[decrypt failed]";
4740
+ return {
4741
+ line: `[${ts}] ${sender} → ${target}: ${preview}`,
4742
+ notice
4743
+ };
4744
+ }
4745
+ //#endregion
4746
+ //#region src/commands/stream-open.ts
4747
+ /**
4748
+ * Opens one SSE `message` event for `rine stream`: parses it, decrypts it when
4749
+ * this agent can, and says whether the row has settled. Both output modes call
4750
+ * this, so a row is opened once and `--json` stdout stays the raw event.
4751
+ */
4752
+ /**
4753
+ * Parse and decrypt one event. Throws on a frame that is not JSON; the callers
4754
+ * treat that as "no verdict". A cleartext row whose body does not decode is
4755
+ * still a row: it has no preview, and it settles through the `none` rule, as
4756
+ * the SDK settles it.
4757
+ */
4758
+ async function openStreamMessage(dataStr, agentId, configDir, client) {
4759
+ const data = JSON.parse(dataStr);
4760
+ let cleartext = null;
4761
+ let undecodable = false;
4656
4762
  try {
4657
- const data = JSON.parse(dataStr);
4658
- const ts = (data.created_at ?? "").slice(0, 19) || "?";
4659
- const sender = data.sender_handle ?? String(data.from_agent_id ?? "?");
4660
- const msgType = data.type ?? "?";
4661
- const target = data.group_handle ? `${data.group_handle} (${msgType})` : msgType;
4662
- const cleartext = a2aCleartextPreview(data);
4663
- let preview = cleartext ?? "[encrypted]";
4664
- let notice = null;
4665
- const fromAgentId = data.from_agent_id;
4666
- if (cleartext === null && data.encrypted_payload && fromAgentId && agentKeysExist(configDir, agentId)) {
4667
- let result;
4668
- let unavailable = null;
4669
- if (isGroupEncryptionVersion(data.encryption_version) && data.group_id) try {
4670
- result = await decryptGroupMessageWithRecovery(client, configDir, agentId, data.group_id, data.encrypted_payload, fromAgentId, data.created_at);
4671
- } catch (err) {
4672
- unavailable = asSenderKeyUnavailable(err, data.group_id);
4673
- }
4674
- else if (data.encryption_version === ENCRYPTION_VERSION_HYBRID_V2) try {
4675
- result = await decryptMessage(configDir, agentId, data.encrypted_payload, client, fromAgentId, agentId, data.created_at);
4676
- } catch {}
4677
- if (result && isAuthenticityFailure(result.verificationStatus)) preview = result.verificationStatus === "sender-mismatch" ? "[✗ sender mismatch]" : "[✗ invalid signature]";
4678
- else if (result?.plaintext !== void 0) {
4679
- ingestSenderKeyDistribution(configDir, agentId, data.type ?? "", result);
4680
- preview = `[${result.verified ? "✓" : "?"}] ${result.plaintext.slice(0, 60)}`;
4681
- } else if (unavailable !== null) {
4682
- preview = data.id ? `${SENDER_KEY_UNAVAILABLE_PREVIEW} rine message read ${data.id}` : SENDER_KEY_UNAVAILABLE_PREVIEW;
4683
- notice = explain(unavailable.message).notice;
4684
- } else if (isDecryptableVersion(data.encryption_version)) preview = "[decrypt failed]";
4763
+ cleartext = a2aCleartextPreview(data);
4764
+ } catch {
4765
+ undecodable = true;
4766
+ }
4767
+ let result;
4768
+ let unavailable = null;
4769
+ let forgedStatus;
4770
+ const fromAgentId = data.from_agent_id;
4771
+ const attempted = Boolean(!undecodable && cleartext === null && data.encrypted_payload && fromAgentId && agentKeysExist(configDir, agentId));
4772
+ if (attempted && data.encrypted_payload && fromAgentId) {
4773
+ if (isGroupEncryptionVersion(data.encryption_version) && data.group_id) try {
4774
+ result = await decryptGroupMessageWithRecovery(client, configDir, agentId, data.group_id, data.encrypted_payload, fromAgentId, data.created_at);
4775
+ } catch (err) {
4776
+ forgedStatus = groupAuthenticityStatus(err) ?? void 0;
4777
+ unavailable = asSenderKeyUnavailable(err, data.group_id);
4685
4778
  }
4686
- return {
4687
- line: `[${ts}] ${sender} \u2192 ${target}: ${preview}`,
4688
- notice
4689
- };
4779
+ else if (data.encryption_version === ENCRYPTION_VERSION_HYBRID_V2) try {
4780
+ result = await decryptMessage(configDir, agentId, data.encrypted_payload, client, fromAgentId, agentId, data.created_at);
4781
+ } catch {}
4782
+ if (result && !isAuthenticityFailure(result.verificationStatus) && result.plaintext !== void 0) ingestSenderKeyDistribution(configDir, agentId, data.type ?? "", result);
4783
+ }
4784
+ return {
4785
+ data,
4786
+ cleartext,
4787
+ attempted,
4788
+ result,
4789
+ forgedStatus,
4790
+ unavailable
4791
+ };
4792
+ }
4793
+ /**
4794
+ * Whether the row has settled, so that acknowledging it loses nothing: it
4795
+ * opened, it was never ciphertext, or its author was refused. A frame this
4796
+ * agent has no keys for, or could not open yet, stays new.
4797
+ */
4798
+ function isSettledMessage(opened) {
4799
+ const { data, result, forgedStatus } = opened;
4800
+ return isSettledRow({
4801
+ encryption_version: data.encryption_version ?? "",
4802
+ verification_status: result?.verificationStatus ?? forgedStatus
4803
+ }, result?.plaintext !== void 0);
4804
+ }
4805
+ //#endregion
4806
+ //#region src/commands/stream-message.ts
4807
+ /**
4808
+ * What `rine stream` does with one SSE event once it has arrived: print it in
4809
+ * the chosen mode, and acknowledge the row when it settled.
4810
+ *
4811
+ * The stream connects with the peek header, so the server marks nothing
4812
+ * delivered at yield. A row is acknowledged here, through the batcher, only
4813
+ * after it was opened (or was refused, or was never ciphertext); a row this
4814
+ * agent cannot open yet stays new for the next reader.
4815
+ */
4816
+ /** The environment of one stream, with a batcher that acknowledges through its client. */
4817
+ function createStreamEnv(base) {
4818
+ const acks = createAckBatcher({
4819
+ ack: (ids) => markDeliveredAs(base.client, base.agentId, ids),
4820
+ onError: (count, err) => process.stderr.write(`${ackFailureNotice(count, err)}\n`)
4821
+ });
4822
+ return {
4823
+ ...base,
4824
+ acks,
4825
+ inFlight: /* @__PURE__ */ new Set()
4826
+ };
4827
+ }
4828
+ /** How long a stop waits for rows still being opened before it sends the last batch. */
4829
+ const IN_FLIGHT_WAIT_MS = 2e3;
4830
+ /**
4831
+ * Let the rows still being opened queue their acks, then send the last batch.
4832
+ * Without the wait, a row that settles after the stop would re-arm a timer the
4833
+ * exiting process never runs. The wait is bounded: a decrypt that stalls on the
4834
+ * network must not hold a stop, and its row simply stays new.
4835
+ */
4836
+ async function closeStreamEnv(env, inFlightWaitMs = IN_FLIGHT_WAIT_MS) {
4837
+ try {
4838
+ await raceDeadline(Promise.allSettled([...env.inFlight]), inFlightWaitMs);
4839
+ } catch {}
4840
+ await env.acks.close();
4841
+ }
4842
+ /** Open the row, queue its ack when it settled, and print it in human mode. */
4843
+ async function settleAndPrint(env, dataStr) {
4844
+ let line;
4845
+ try {
4846
+ const opened = await openStreamMessage(dataStr, env.agentId, env.configDir, env.client);
4847
+ const row = opened.data;
4848
+ if (row.id && isSettledMessage(opened)) env.acks.add(row.id);
4849
+ if (env.json) return;
4850
+ const rendered = renderOpened(opened, env.explain);
4851
+ if (rendered.notice !== null) printError(rendered.notice);
4852
+ line = rendered.line;
4690
4853
  } catch {
4691
- return {
4692
- line: `[message] ${dataStr.slice(0, 80)}`,
4693
- notice: null
4694
- };
4854
+ if (env.json) return;
4855
+ line = `[message] ${dataStr.slice(0, 80)}`;
4856
+ }
4857
+ console.log(line);
4858
+ }
4859
+ function handleStreamEvent(env, { event, data, id }) {
4860
+ if (event === "heartbeat") env.acks.flush();
4861
+ if (env.json) {
4862
+ if (!env.monitor || event === "message") console.log(messageEventLine(event, id, data));
4863
+ } else if (event === "heartbeat" && env.verbose) process.stderr.write(`[heartbeat] ${data}\n`);
4864
+ if (event === "message") {
4865
+ const settling = settleAndPrint(env, data);
4866
+ env.inFlight.add(settling);
4867
+ settling.finally(() => env.inFlight.delete(settling));
4695
4868
  }
4696
4869
  }
4697
4870
  //#endregion
4698
- //#region src/commands/stream.ts
4699
- function emitLifecycle(gOpts, monitor, data) {
4700
- if (gOpts.json) {
4701
- const line = JSON.stringify({
4702
- event: "lifecycle",
4703
- data
4871
+ //#region src/commands/stream-reconnect.ts
4872
+ /**
4873
+ * Say why a connection ended and wait out the backoff. Returns the backoff for
4874
+ * the next attempt, or null when the stream was stopped.
4875
+ */
4876
+ async function afterDisconnect(reason, { gOpts, monitor, attempt, backoff, stopping }) {
4877
+ if (reason === "signal") {
4878
+ emitLifecycle(gOpts, monitor, {
4879
+ state: "stopped",
4880
+ reason: "signal"
4704
4881
  });
4705
- if (monitor) process.stderr.write(`${line}\n`);
4706
- else console.log(line);
4882
+ return null;
4883
+ }
4884
+ if (reason === "heartbeat_timeout") {
4885
+ const jittered = jitteredDelayMs(backoff);
4886
+ emitLifecycle(gOpts, monitor, {
4887
+ state: "reconnecting",
4888
+ reason: "heartbeat_timeout",
4889
+ attempt: attempt + 1,
4890
+ backoff_ms: jittered
4891
+ });
4892
+ if (!gOpts.json) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, heartbeat timeout)...\n`);
4893
+ await sleepWithSignal(jittered, stopping);
4894
+ return nextReconnectBackoffSeconds(backoff);
4707
4895
  }
4896
+ emitLifecycle(gOpts, monitor, {
4897
+ state: "reconnecting",
4898
+ reason: "server_close",
4899
+ attempt: attempt + 1,
4900
+ backoff_ms: 0
4901
+ });
4902
+ if (!gOpts.json) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, server close)...\n`);
4903
+ return 1;
4708
4904
  }
4905
+ /**
4906
+ * Say that an attempt failed and wait out the backoff. Returns the backoff for
4907
+ * the next attempt, or null when the failure was the stop itself.
4908
+ */
4909
+ async function afterError(err, stopped, { gOpts, monitor, verbose, attempt, backoff, stopping }) {
4910
+ if (stopped) {
4911
+ emitLifecycle(gOpts, monitor, {
4912
+ state: "stopped",
4913
+ reason: "signal"
4914
+ });
4915
+ return null;
4916
+ }
4917
+ const errorMsg = err instanceof Error ? err.message : String(err);
4918
+ const jittered = jitteredDelayMs(backoff);
4919
+ emitLifecycle(gOpts, monitor, {
4920
+ state: "reconnecting",
4921
+ reason: "error",
4922
+ attempt: attempt + 1,
4923
+ backoff_ms: jittered,
4924
+ error: errorMsg
4925
+ });
4926
+ if (verbose) process.stderr.write(`Reconnecting in ${Math.round(jittered / 1e3)}s (attempt ${attempt + 1}, error: ${errorMsg})...\n`);
4927
+ else process.stderr.write(`Reconnecting (attempt ${attempt + 1}, error)...\n`);
4928
+ await sleepWithSignal(jittered, stopping);
4929
+ return nextReconnectBackoffSeconds(backoff);
4930
+ }
4931
+ //#endregion
4932
+ //#region src/commands/stream-stop.ts
4933
+ const FLUSH_WAIT_MS = 5e3;
4934
+ function listenForStop() {
4935
+ let stopped = false;
4936
+ let closeConnection;
4937
+ const controller = new AbortController();
4938
+ const stop = () => {
4939
+ if (stopped) process.exit(0);
4940
+ stopped = true;
4941
+ controller.abort();
4942
+ process.exitCode = 0;
4943
+ closeConnection?.();
4944
+ };
4945
+ process.on("SIGINT", stop);
4946
+ process.on("SIGTERM", stop);
4947
+ return {
4948
+ signal: controller.signal,
4949
+ get stopped() {
4950
+ return stopped;
4951
+ },
4952
+ onStop(close) {
4953
+ closeConnection = close;
4954
+ }
4955
+ };
4956
+ }
4957
+ /**
4958
+ * End the process with `code` once stdout and stderr have flushed. On a full
4959
+ * pipe Node queues writes and `process.exit` drops them, so a line whose row
4960
+ * was already acknowledged would never reach the reader. A reader stalled past
4961
+ * the wait does not hold the process open.
4962
+ */
4963
+ async function exitWhenFlushed(code, flushWaitMs = FLUSH_WAIT_MS) {
4964
+ const flushed = (out) => new Promise((resolve) => out.write("", () => resolve()));
4965
+ try {
4966
+ await raceDeadline(Promise.all([flushed(process.stdout), flushed(process.stderr)]), flushWaitMs);
4967
+ } catch {}
4968
+ process.exit(code);
4969
+ }
4970
+ //#endregion
4971
+ //#region src/commands/stream.ts
4709
4972
  function registerStream(program) {
4710
4973
  program.command("stream").description("Stream incoming messages via SSE").addOption(actorOption("which agent is acting, and whose messages stream (name, handle, or agent ID)")).option("--verbose", "Show heartbeats and reconnect details").option("--persistent", "Disable server-side connection timeout").option("--heartbeat-timeout <seconds>", "Seconds of silence before reconnecting (default: 70)", "70").option("--monitor", "Suppress non-message stdout (for CC plugin monitors)").action(async (opts, command) => {
4711
4974
  try {
@@ -4721,72 +4984,57 @@ function registerStream(program) {
4721
4984
  let lastEventId = loadStreamCursor(configDir, agentId);
4722
4985
  let backoff = 1;
4723
4986
  let attempt = 0;
4724
- let stopped = false;
4725
4987
  const refreshMargin = jitteredRefreshMargin();
4726
4988
  const explain = senderKeyExplainer();
4727
- let stopConnection;
4728
- process.on("SIGINT", () => {
4729
- stopped = true;
4730
- process.exitCode = 0;
4731
- stopConnection?.();
4989
+ const env = createStreamEnv({
4990
+ json: Boolean(gOpts.json),
4991
+ monitor: opts.monitor,
4992
+ verbose: opts.verbose,
4993
+ agentId,
4994
+ configDir,
4995
+ client,
4996
+ explain
4732
4997
  });
4733
- while (!stopped) {
4998
+ const stop = listenForStop();
4999
+ while (!stop.stopped) {
4734
5000
  attempt++;
4735
- const state = { disconnectReason: "server_close" };
5001
+ const reconnect = () => ({
5002
+ gOpts,
5003
+ monitor: opts.monitor,
5004
+ verbose: opts.verbose,
5005
+ attempt,
5006
+ backoff,
5007
+ stopping: stop.signal
5008
+ });
4736
5009
  try {
4737
- const headers = {
5010
+ const headers = withPeekHeader({
4738
5011
  Authorization: `Bearer ${await mintToken({ refreshMargin })}`,
4739
5012
  Accept: "text/event-stream"
4740
- };
5013
+ }, true);
4741
5014
  if (lastEventId) headers["Last-Event-ID"] = lastEventId;
4742
5015
  emitLifecycle(gOpts, opts.monitor, {
4743
5016
  state: "connecting",
4744
5017
  attempt,
4745
5018
  url
4746
5019
  });
4747
- await new Promise((resolve) => {
4748
- if (stopped) {
4749
- resolve();
4750
- return;
4751
- }
4752
- let heartbeatTimer;
4753
- const resetHeartbeatTimer = () => {
4754
- if (heartbeatTimer) clearTimeout(heartbeatTimer);
4755
- heartbeatTimer = setTimeout(() => {
4756
- state.disconnectReason = "heartbeat_timeout";
4757
- es.close();
4758
- resolve();
4759
- }, heartbeatTimeoutMs);
4760
- };
4761
- const es = createEventSource({
5020
+ let reason = "server_close";
5021
+ if (!stop.stopped) {
5022
+ const connection = openStreamConnection({
4762
5023
  url,
4763
5024
  headers,
5025
+ heartbeatTimeoutMs,
4764
5026
  onMessage: ({ event, data, id }) => {
4765
- resetHeartbeatTimer();
4766
5027
  if (id) {
4767
5028
  lastEventId = id;
4768
5029
  saveStreamCursor(configDir, agentId, id);
4769
5030
  }
4770
- if (gOpts.json) {
4771
- if (!opts.monitor || event === "message") console.log(messageEventLine(event, id, data));
4772
- } else if (event === "message") formatMessageLine(data, agentId, configDir, client, explain).then(({ line, notice }) => {
4773
- if (notice !== null) printError(notice);
4774
- console.log(line);
5031
+ handleStreamEvent(env, {
5032
+ event,
5033
+ data,
5034
+ id
4775
5035
  });
4776
- else if (event === "heartbeat" && opts.verbose) process.stderr.write(`[heartbeat] ${data}\n`);
4777
- },
4778
- onDisconnect: () => {
4779
- if (heartbeatTimer) clearTimeout(heartbeatTimer);
4780
- state.disconnectReason = "server_close";
4781
- resolve();
4782
- },
4783
- onScheduleReconnect: () => {
4784
- if (heartbeatTimer) clearTimeout(heartbeatTimer);
4785
- es.close();
4786
- resolve();
4787
5036
  }
4788
5037
  });
4789
- resetHeartbeatTimer();
4790
5038
  if (attempt === 1 && !gOpts.json) {
4791
5039
  process.stderr.write(`Connected to stream for agent ${agentId}\n`);
4792
5040
  if (opts.persistent) process.stderr.write("Persistent mode (no server timeout)\n");
@@ -4795,69 +5043,22 @@ function registerStream(program) {
4795
5043
  state: "connected",
4796
5044
  attempt
4797
5045
  });
4798
- const onStop = () => {
4799
- if (heartbeatTimer) clearTimeout(heartbeatTimer);
4800
- state.disconnectReason = "signal";
4801
- es.close();
4802
- resolve();
4803
- };
4804
- if (stopped) {
4805
- onStop();
4806
- return;
4807
- }
4808
- stopConnection = onStop;
4809
- });
4810
- stopConnection = void 0;
4811
- if (state.disconnectReason === "heartbeat_timeout") {
4812
- const jitteredBackoff = jitteredDelayMs(backoff);
4813
- emitLifecycle(gOpts, opts.monitor, {
4814
- state: "reconnecting",
4815
- reason: "heartbeat_timeout",
4816
- attempt: attempt + 1,
4817
- backoff_ms: jitteredBackoff
4818
- });
4819
- if (!gOpts.json) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, heartbeat timeout)...\n`);
4820
- await sleep(jitteredBackoff);
4821
- backoff = nextReconnectBackoffSeconds(backoff);
4822
- } else if (state.disconnectReason === "signal") {
4823
- emitLifecycle(gOpts, opts.monitor, {
4824
- state: "stopped",
4825
- reason: "signal"
4826
- });
4827
- break;
4828
- } else {
4829
- emitLifecycle(gOpts, opts.monitor, {
4830
- state: "reconnecting",
4831
- reason: "server_close",
4832
- attempt: attempt + 1,
4833
- backoff_ms: 0
4834
- });
4835
- if (!gOpts.json) process.stderr.write(`Reconnecting (attempt ${attempt + 1}, server close)...\n`);
4836
- backoff = 1;
5046
+ if (stop.stopped) connection.stop();
5047
+ else stop.onStop(connection.stop);
5048
+ reason = await connection.closed;
5049
+ stop.onStop(void 0);
4837
5050
  }
5051
+ const next = await afterDisconnect(reason, reconnect());
5052
+ if (next === null) break;
5053
+ backoff = next;
4838
5054
  } catch (err) {
4839
- if (stopped) {
4840
- emitLifecycle(gOpts, opts.monitor, {
4841
- state: "stopped",
4842
- reason: "signal"
4843
- });
4844
- break;
4845
- }
4846
- const errorMsg = err instanceof Error ? err.message : String(err);
4847
- const jitteredBackoff = jitteredDelayMs(backoff);
4848
- emitLifecycle(gOpts, opts.monitor, {
4849
- state: "reconnecting",
4850
- reason: "error",
4851
- attempt: attempt + 1,
4852
- backoff_ms: jitteredBackoff,
4853
- error: errorMsg
4854
- });
4855
- if (opts.verbose) process.stderr.write(`Reconnecting in ${Math.round(jitteredBackoff / 1e3)}s (attempt ${attempt + 1}, error: ${errorMsg})...\n`);
4856
- else process.stderr.write(`Reconnecting (attempt ${attempt + 1}, error)...\n`);
4857
- await sleep(jitteredBackoff);
4858
- backoff = nextReconnectBackoffSeconds(backoff);
5055
+ const next = await afterError(err, stop.stopped, reconnect());
5056
+ if (next === null) break;
5057
+ backoff = next;
4859
5058
  }
4860
5059
  }
5060
+ await closeStreamEnv(env);
5061
+ await exitWhenFlushed(process.exitCode ?? 0);
4861
5062
  } catch (err) {
4862
5063
  printError(formatError(err));
4863
5064
  process.exitCode = 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rine-network/cli",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "CLI client for rine.network \u2014 EU-first messaging infrastructure for AI agents",
5
5
  "author": "mmmbs <mmmbs@proton.me>",
6
6
  "license": "EUPL-1.2",
@@ -28,7 +28,7 @@
28
28
  "dev": "tsx src/main.ts"
29
29
  },
30
30
  "dependencies": {
31
- "@rine-network/core": "^0.17.0",
31
+ "@rine-network/core": "^0.18.0",
32
32
  "commander": "^12.0.0",
33
33
  "eventsource-client": "^1.1.0"
34
34
  },