primcli 1.54.0 → 1.55.1

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.
@@ -1,14 +1,14 @@
1
- import { A as saveActiveChatState, C as resolveCliAuth, D as deleteChatState, E as chatStatePath, F as agentProfilesDirectory, H as requireDefaultLoginProfile, M as AgentConnectionSetupError, N as agentProfileDirectory, O as loadActiveChatState, P as agentProfileName, R as loadConnectedAgentProfile, T as saveSignupCredentials, W as PrimitiveApiClient, _ as deleteCliCredentials, a as normalizeCliEnvironmentName, b as hasStoredCliLogin, c as resolveConfigEnvironment, g as credentialsPath, h as credentialsLockPath, i as loadCliConfig, j as AGENT_PROFILE_ENV, k as loadChatConversationByLocalId, l as saveCliConfig, m as cliAccessTokenExpiresAt, n as deleteCliConfig, o as redactCliEnvironment, p as acquireCliCredentialsLock, r as emptyCliConfig, s as removeCliEnvironment, u as upsertCliEnvironment, v as deleteCliCredentialsLock, w as saveCliCredentials, x as loadCliCredentials, y as detectPrimitiveKeyEnvMisname } from "../cli-config-DGrZCUfw.js";
2
- import { $ as apiResultHttpStatus, $n as resendAgentSignupVerification, $t as createEndpoint, A as readThreadContext, At as formatAlreadySentNotice, B as pendingMailPath, Bn as listSentEmails, Bt as expectedAutomatedVerdicts, C as queryUsesAwaiting, Cn as getOrgRoutingTopology, Ct as cliInvocation, D as displayAddress, Dn as getWakeSchedule, Dt as identitySuggestions, E as describeWake, En as getThread, Et as generatedAgentName, F as wakeReadCommand, Fn as listEndpoints, Ft as AUTOMATED_VALUES, G as interactionNextActions, Gn as pullWebhookEvent, Gt as createAuthenticatedCliApiClient, H as recordPendingMail, Hn as listWakeDispatches, Ht as isAutomatedRejectedError, I as wakeRecipientField, In as listFunctionLogs, It as AutomatedFilterUnsupportedError, J as replyInteractionWarning, Jt as resolveCliApiRequestConfig, K as readEmailInteraction, Kt as createCliApiClient, L as wakeRelationship, Ln as listFunctions, Lt as assertAutomatedVerdict, M as serverMuted, Mn as listDefaultNetworkMembers, Mt as withFlagSuggestion, N as serverRelationship, Nn as listDomains, Nt as AUTOMATED_FILTER_UNSUPPORTED_CODE, O as formatMailWakeLine, On as listAgentContacts, Ot as loadSkillLine, Pn as listEmails, Pt as AUTOMATED_FLAG_DESCRIPTION, Q as SEND_OUTCOME_HELP, Qn as replyToEmail, Qt as completeWebhookEvent, R as clearConsumedPendingMail, Rn as listRepeatingSends, Rt as automatedRejectedError, S as isAwaitingRejectedError, Sn as getMemory, Sr as verifyAgentSignup, T as bareAddress, Tn as getSentEmail, U as removePendingMail, Un as listWakeSchedules, Ut as queryUsesAutomated, V as readPendingMail, Vn as listWakeAuthorizations, Vt as hasAutomatedVerdict, W as interactionHumanLine, Wn as pollCliLogin, X as IDEMPOTENCY_KEY_FLAG_DESCRIPTION, Xn as removeDefaultNetworkMember, Xt as checkDefaultNetworkContactAdmission, Yn as redeemCreditCode, Yt as addDefaultNetworkMember, Z as MAX_SEND_WAIT_TIMEOUT_MS, Zn as reorderRoutes, Zt as cliLogout, _ as awaitingRejectedError, _n as getEmail, _r as updateRepeatingSend, _t as sendWaitClampNotice, a as extractErrorCode, ar as setFunctionRoute, at as deriveSendIdempotencyKey, b as formatRepliesCell, bn as getFunctionTestRunTrace, br as updateWakeSchedule, bt as successfulSendOutcome, c as readTextFileFlag, cn as deleteWakeAuthorization, cr as simulateRoute, ct as formatDeletedEarlierSendNotice, d as writeErrorWithHints, dn as getAccount, dr as startCliLogin, dt as formatSendFailureSummary, en as createFunction, er as runWakeSchedule, et as assertValidIdempotencyKey, f as AWAITING_FLAG_DESCRIPTION, fn as getAgentContactPolicy, fr as stopRepeatFromEmail, ft as formatSendRecordFailureSummary, g as assertAwaitingFilterRows, gn as getDefaultNetworkAgent, gr as updateFunction, gt as sendOutcomeExitCode, h as ReplyStateUnsupportedError, hn as getCreditBalance, hr as updateDefaultNetworkMember, ht as sendIdentityFields, i as createOperationCommand, ir as sendEmail, it as classifySendError, j as sentInThread, jn as listDefaultNetworkAgents, jt as writeIdempotentReplayBannerIfReplay, k as latestOwnOutbound, kn as listAgentNetworks, kt as currentMailSessionKey, l as runWithTiming, ln as deleteWakeSchedule, lr as startAgentClaim, lt as formatPriorRepliesCheckSkipped, m as REPLY_STATE_UNSUPPORTED_CODE, mn as getConversation, mr as unsetFunctionRoute, mt as reportSendCommandResult, n as API_ERROR_CODES, nn as createWakeAuthorization, nr as searchMemories, nt as buildThrownSendFailureEnvelope, o as extractErrorPayload, on as deleteMemory, or as setFunctionSecret, ot as excludeSignalReplies, p as AWAITING_VALUES, pr as testFunction, pt as priorRepliesThatWentOut, q as replyExpectation, qt as refreshStoredCliCredentials, r as TIME_FLAG_DESCRIPTION, rn as createWakeSchedule, rr as semanticSearch, rt as checkPriorReplies, s as formatErrorPayload, sn as deleteRoute, sr as setMemory, st as followUpCommandPrefix, t as API_BASE_URL_FLAG_DESCRIPTION, tn as createRoute, tr as searchEmails, tt as buildFollowUpCommand, u as surfaceUnauthorizedHint, ur as startAgentSignup, ut as formatPriorRepliesWarning, v as ensureSearchReportsReplyState, vn as getFunction, vr as updateRoute, vt as sentHistoryWindowStart, w as explainPendingMailNotFound, wn as getRepeatingSend, wt as connectNextSteps, x as hasReplyState, xn as getInboxStatus, xr as verifyAgentClaim, xt as thrownErrorExitCode, y as formatAwaitingCell, yn as getFunctionRouting, yr as updateWakeAuthorization, yt as serializeErrorPayload, z as clearReadPendingMail, zn as listRoutes, zt as ensureSearchReportsAutomated } from "../api-command-C_Fn9Zef.js";
3
- import { S as resolveListenSubscription, _ as acquireListenLock, a as mailLockBusy, c as mailTime, d as readMailJson, f as removeMailFile, g as ListenStateError, h as writeMailJson, i as mailId, l as privateMailDirectory, m as withMailLock, o as mailObject, u as privateMailPermissions, x as normalizeListenOrigin, y as listenIdentity } from "../shared-mail-files-SPPcis9g.js";
4
- import { _ as detectAgentRuntime, a as NotificationRetryError, b as installedVersion, c as readConversationStatusContent, d as defaultSessionSocket, f as NativeSessionDisconnectedError, g as connectSkillTarget, h as NotificationOutcomeUnknownError, i as notificationReceiptPage, l as SESSION_UUID$1, m as NativeSessionNotLoadedError, n as notificationSenders, o as isRoutineNotificationContent, p as NativeSessionError, r as openSessionNotifications, s as notificationPartReader, t as notificationScope, v as installConnectSkill, x as readBundledConnectSkill, y as installedConnectSkillFile } from "../notify-session-DhV0DLAA.js";
5
- import { $ as describeSessionHookItem, A as evaluateContactPolicy, B as agentInvitationHash, C as RECEIVER_MODES, D as NETWORK_ADMISSION_PENDING_RETRY_MS, E as ContactPolicyReadRetryError, F as ContactsApiError, G as saveConnectionName, H as readAgentInvitation, I as contactAddress, J as recordHookMailCheck, K as savedReceiver, L as contactAgentAddress, M as AddressNotesApiError, N as addressNoteTarget, O as NetworkAdmissionPendingError, P as runAddressNotesRequest, Q as describeSessionHookChange, R as runContactRequest, S as runAgentConnect, T as verificationReplySubmitted, U as receiverStatusCommand, V as connectAgent, W as refusalAfterReplacement, X as claudeConfigDir, Y as boundSessionProfiles, Z as currentCliLocation, _ as disconnectAgent, _t as withOwnerMemberAddress, a as endSession, at as readClaudeSettings, b as invitationProfileName, c as pendingSessionDisconnects, ct as writeClaudeSettings, d as registerSession, dt as jsonIndentation, et as ensureHookLauncher, f as retryPendingDisconnects, ft as readManagedFile, g as AgentDisconnectError, gt as refreshOwnerMemberAddressPeriodically, h as enrollmentResumes, ht as readHookLauncherWarning, i as connectedProfilesForSession, it as inspectClaudeHooks, j as canonicalContactSelector, k as createNotificationContactPolicy, l as psProcessInfo, lt as MachineFileError, m as enrollAgent, mt as writeManagedFile, n as OMP_MAIN, nt as findOnPath, o as headlessClaudeRun, ot as repairClaudeHooks, p as runDetached, pt as upsertManagedBlock, q as installClaudeWakeHook, r as agentConnectionState, rt as hasMachineSessionHooks, st as samePath, t as MACHINE_RUNTIMES, tt as ephemeralCliReason, u as readClaudeHookInput, ut as inspectManagedBlock, v as connectWarnings, w as externalReceivingState, x as pollCheckCommand, y as defaultAgentProfileName, z as agentConnectionStatus } from "../machine-session-Do3mw2_w.js";
6
- import { a as scopedChatSenderTrust, i as readBeforeDeadline, n as isPlainChatReply, o as presenceDisposition, r as isScopedChatReply, s as readPresenceProjection, t as isConnectedChatCredential } from "../scoped-chat-BrLq4dXH.js";
7
- import { c as startBackgroundListen, i as backgroundListenToken, l as stopBackgroundListen, o as runBackgroundListen, r as backgroundListenStatus, u as verifyBackgroundListenTarget } from "../listen-background-CMfxkeVP.js";
8
- import { a as REPEAT_IDLE_MAX_MINUTES, d as parseRepeatTick, f as preparePresenceAliveEmail, g as isEmailReceivedEvent, i as REPEAT_EVERY_MAX_MINUTES, l as parseInteractionEnvelope$1, m as repeatStopCommand, o as REPEAT_MAX_SENDS_MAX, p as prepareSignalEmail, s as buildRepeatStopBody, u as parsePresenceEnvelope, v as parseWebhookEvent, y as parseFromHeader } from "../repeats-D2xtLium-DmtVD6ol.js";
9
- import { a as ensureSharedMailSubscription, c as reserveSharedMailSubscription, d as otherParticipants, f as EventConnection, h as pushFile, i as sharedMailScope, l as followEmailConversation, m as pullFile, n as reconcileChatSend, o as createSharedMailWaiter, p as EventReceiverError, r as openSharedMailReceiver, s as openSharedMailStore, t as sendSignal, u as readConversationFollow } from "../signal-command-CqfODMCp.js";
1
+ import { a as REPEAT_IDLE_MAX_MINUTES, d as parseRepeatTick, f as preparePresenceAliveEmail, g as isEmailReceivedEvent, i as REPEAT_EVERY_MAX_MINUTES, l as parseInteractionEnvelope$1, m as repeatStopCommand, o as REPEAT_MAX_SENDS_MAX, p as prepareSignalEmail, s as buildRepeatStopBody, u as parsePresenceEnvelope, v as parseWebhookEvent, y as parseFromHeader } from "../repeats-x4QM2yoG-De3MV3st.js";
2
+ import { A as saveActiveChatState, C as resolveCliAuth, D as deleteChatState, E as chatStatePath, F as agentProfilesDirectory, H as requireDefaultLoginProfile, M as AgentConnectionSetupError, N as agentProfileDirectory, O as loadActiveChatState, P as agentProfileName, R as loadConnectedAgentProfile, T as saveSignupCredentials, W as PrimitiveApiClient, _ as deleteCliCredentials, a as normalizeCliEnvironmentName, b as hasStoredCliLogin, c as resolveConfigEnvironment, g as credentialsPath, h as credentialsLockPath, i as loadCliConfig, j as AGENT_PROFILE_ENV, k as loadChatConversationByLocalId, l as saveCliConfig, m as cliAccessTokenExpiresAt, n as deleteCliConfig, o as redactCliEnvironment, p as acquireCliCredentialsLock, r as emptyCliConfig, s as removeCliEnvironment, u as upsertCliEnvironment, v as deleteCliCredentialsLock, w as saveCliCredentials, x as loadCliCredentials, y as detectPrimitiveKeyEnvMisname } from "../cli-config-DMszFbGn.js";
3
+ import { $ as apiResultHttpStatus, $n as resendAgentSignupVerification, $t as createEndpoint, A as readThreadContext, At as formatAlreadySentNotice, B as pendingMailPath, Bn as listSentEmails, Bt as expectedAutomatedVerdicts, C as queryUsesAwaiting, Cn as getOrgRoutingTopology, Ct as cliInvocation, D as displayAddress, Dn as getWakeSchedule, Dt as identitySuggestions, E as describeWake, En as getThread, Et as generatedAgentName, F as wakeReadCommand, Fn as listEndpoints, Ft as AUTOMATED_VALUES, G as interactionNextActions, Gn as pullWebhookEvent, Gt as createAuthenticatedCliApiClient, H as recordPendingMail, Hn as listWakeDispatches, Ht as isAutomatedRejectedError, I as wakeRecipientField, In as listFunctionLogs, It as AutomatedFilterUnsupportedError, J as replyInteractionWarning, Jt as resolveCliApiRequestConfig, K as readEmailInteraction, Kt as createCliApiClient, L as wakeRelationship, Ln as listFunctions, Lt as assertAutomatedVerdict, M as serverMuted, Mn as listDefaultNetworkMembers, Mt as withFlagSuggestion, N as serverRelationship, Nn as listDomains, Nt as AUTOMATED_FILTER_UNSUPPORTED_CODE, O as formatMailWakeLine, On as listAgentContacts, Ot as loadSkillLine, Pn as listEmails, Pt as AUTOMATED_FLAG_DESCRIPTION, Q as SEND_OUTCOME_HELP, Qn as replyToEmail, Qt as completeWebhookEvent, R as clearConsumedPendingMail, Rn as listRepeatingSends, Rt as automatedRejectedError, S as isAwaitingRejectedError, Sn as getMemory, Sr as verifyAgentSignup, T as bareAddress, Tn as getSentEmail, U as removePendingMail, Un as listWakeSchedules, Ut as queryUsesAutomated, V as readPendingMail, Vn as listWakeAuthorizations, Vt as hasAutomatedVerdict, W as interactionHumanLine, Wn as pollCliLogin, X as IDEMPOTENCY_KEY_FLAG_DESCRIPTION, Xn as removeDefaultNetworkMember, Xt as checkDefaultNetworkContactAdmission, Yn as redeemCreditCode, Yt as addDefaultNetworkMember, Z as MAX_SEND_WAIT_TIMEOUT_MS, Zn as reorderRoutes, Zt as cliLogout, _ as awaitingRejectedError, _n as getEmail, _r as updateRepeatingSend, _t as sendWaitClampNotice, a as extractErrorCode, ar as setFunctionRoute, at as deriveSendIdempotencyKey, b as formatRepliesCell, bn as getFunctionTestRunTrace, br as updateWakeSchedule, bt as successfulSendOutcome, c as readTextFileFlag, cn as deleteWakeAuthorization, cr as simulateRoute, ct as formatDeletedEarlierSendNotice, d as writeErrorWithHints, dn as getAccount, dr as startCliLogin, dt as formatSendFailureSummary, en as createFunction, er as runWakeSchedule, et as assertValidIdempotencyKey, f as AWAITING_FLAG_DESCRIPTION, fn as getAgentContactPolicy, fr as stopRepeatFromEmail, ft as formatSendRecordFailureSummary, g as assertAwaitingFilterRows, gn as getDefaultNetworkAgent, gr as updateFunction, gt as sendOutcomeExitCode, h as ReplyStateUnsupportedError, hn as getCreditBalance, hr as updateDefaultNetworkMember, ht as sendIdentityFields, i as createOperationCommand, ir as sendEmail, it as classifySendError, j as sentInThread, jn as listDefaultNetworkAgents, jt as writeIdempotentReplayBannerIfReplay, k as latestOwnOutbound, kn as listAgentNetworks, kt as currentMailSessionKey, l as runWithTiming, ln as deleteWakeSchedule, lr as startAgentClaim, lt as formatPriorRepliesCheckSkipped, m as REPLY_STATE_UNSUPPORTED_CODE, mn as getConversation, mr as unsetFunctionRoute, mt as reportSendCommandResult, n as API_ERROR_CODES, nn as createWakeAuthorization, nr as searchMemories, nt as buildThrownSendFailureEnvelope, o as extractErrorPayload, on as deleteMemory, or as setFunctionSecret, ot as excludeSignalReplies, p as AWAITING_VALUES, pr as testFunction, pt as priorRepliesThatWentOut, q as replyExpectation, qt as refreshStoredCliCredentials, r as TIME_FLAG_DESCRIPTION, rn as createWakeSchedule, rr as semanticSearch, rt as checkPriorReplies, s as formatErrorPayload, sn as deleteRoute, sr as setMemory, st as followUpCommandPrefix, t as API_BASE_URL_FLAG_DESCRIPTION, tn as createRoute, tr as searchEmails, tt as buildFollowUpCommand, u as surfaceUnauthorizedHint, ur as startAgentSignup, ut as formatPriorRepliesWarning, v as ensureSearchReportsReplyState, vn as getFunction, vr as updateRoute, vt as sentHistoryWindowStart, w as explainPendingMailNotFound, wn as getRepeatingSend, wt as connectNextSteps, x as hasReplyState, xn as getInboxStatus, xr as verifyAgentClaim, xt as thrownErrorExitCode, y as formatAwaitingCell, yn as getFunctionRouting, yr as updateWakeAuthorization, yt as serializeErrorPayload, z as clearReadPendingMail, zn as listRoutes, zt as ensureSearchReportsAutomated } from "../api-command-0FiEAuQi.js";
4
+ import { S as resolveListenSubscription, _ as acquireListenLock, a as mailLockBusy, c as mailTime, d as readMailJson, f as removeMailFile, g as ListenStateError, h as writeMailJson, i as mailId, l as privateMailDirectory, m as withMailLock, o as mailObject, u as privateMailPermissions, x as normalizeListenOrigin, y as listenIdentity } from "../shared-mail-files-MwlVE90c.js";
5
+ import { _ as detectAgentRuntime, a as NotificationRetryError, b as installedVersion, c as readConversationStatusContent, d as defaultSessionSocket, f as NativeSessionDisconnectedError, g as connectSkillTarget, h as NotificationOutcomeUnknownError, i as notificationReceiptPage, l as SESSION_UUID$1, m as NativeSessionNotLoadedError, n as notificationSenders, o as isRoutineNotificationContent, p as NativeSessionError, r as openSessionNotifications, s as notificationPartReader, t as notificationScope, v as installConnectSkill, x as readBundledConnectSkill, y as installedConnectSkillFile } from "../notify-session-BGzeKcQO.js";
6
+ import { $ as describeSessionHookItem, A as evaluateContactPolicy, B as agentInvitationHash, C as RECEIVER_MODES, D as NETWORK_ADMISSION_PENDING_RETRY_MS, E as ContactPolicyReadRetryError, F as ContactsApiError, G as saveConnectionName, H as readAgentInvitation, I as contactAddress, J as recordHookMailCheck, K as savedReceiver, L as contactAgentAddress, M as AddressNotesApiError, N as addressNoteTarget, O as NetworkAdmissionPendingError, P as runAddressNotesRequest, Q as describeSessionHookChange, R as runContactRequest, S as runAgentConnect, T as verificationReplySubmitted, U as receiverStatusCommand, V as connectAgent, W as refusalAfterReplacement, X as claudeConfigDir, Y as boundSessionProfiles, Z as currentCliLocation, _ as disconnectAgent, _t as withOwnerMemberAddress, a as endSession, at as readClaudeSettings, b as invitationProfileName, c as pendingSessionDisconnects, ct as writeClaudeSettings, d as registerSession, dt as jsonIndentation, et as ensureHookLauncher, f as retryPendingDisconnects, ft as readManagedFile, g as AgentDisconnectError, gt as refreshOwnerMemberAddressPeriodically, h as enrollmentResumes, ht as readHookLauncherWarning, i as connectedProfilesForSession, it as inspectClaudeHooks, j as canonicalContactSelector, k as createNotificationContactPolicy, l as psProcessInfo, lt as MachineFileError, m as enrollAgent, mt as writeManagedFile, n as OMP_MAIN, nt as findOnPath, o as headlessClaudeRun, ot as repairClaudeHooks, p as runDetached, pt as upsertManagedBlock, q as installClaudeWakeHook, r as agentConnectionState, rt as hasMachineSessionHooks, st as samePath, t as MACHINE_RUNTIMES, tt as ephemeralCliReason, u as readClaudeHookInput, ut as inspectManagedBlock, v as connectWarnings, w as externalReceivingState, x as pollCheckCommand, y as defaultAgentProfileName, z as agentConnectionStatus } from "../machine-session-CufQfBvp.js";
7
+ import { a as scopedChatSenderTrust, i as readBeforeDeadline, n as isPlainChatReply, o as presenceDisposition, r as isScopedChatReply, s as readPresenceProjection, t as isConnectedChatCredential } from "../scoped-chat-C7cpIxVS.js";
8
+ import { c as startBackgroundListen, i as backgroundListenToken, l as stopBackgroundListen, o as runBackgroundListen, r as backgroundListenStatus, u as verifyBackgroundListenTarget } from "../listen-background--0peztKE.js";
9
+ import { a as ensureSharedMailSubscription, c as reserveSharedMailSubscription, d as otherParticipants, f as EventConnection, i as sharedMailScope, l as followEmailConversation, n as reconcileChatSend, o as createSharedMailWaiter, p as EventReceiverError, r as openSharedMailReceiver, s as openSharedMailStore, t as sendSignal, u as readConversationFollow } from "../signal-command-COQff2Vq.js";
10
10
  import { autoSignalEligible, dispatchAutoRead, dispatchAutoWorking, haltAutoWorking, isSentSignal, restoreAutoWorking } from "./auto-signals.js";
11
- import { t as guardJsonOutputCommands } from "../json-output-Cf-GFeff.js";
11
+ import { t as guardJsonOutputCommands } from "../json-output-CEskSQJi.js";
12
12
  import { Args, Command, Errors, Flags, ux } from "@oclif/core";
13
13
  import { chmodSync, closeSync, constants, cpSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
14
14
  import { createHash, randomUUID, scryptSync } from "node:crypto";
@@ -35269,6 +35269,7 @@ function isMemoryJsonValue(value, seen = /* @__PURE__ */ new Set()) {
35269
35269
  */
35270
35270
  const CURSOR_FILE = "mail-check.json";
35271
35271
  var MailCheckApiError = class extends Error {
35272
+ payload;
35272
35273
  constructor(payload) {
35273
35274
  super("The mail check request failed.");
35274
35275
  this.payload = payload;
@@ -35421,6 +35422,333 @@ Requires a connected agent profile selected with ${AGENT_PROFILE_ENV}. Output is
35421
35422
  }
35422
35423
  };
35423
35424
  //#endregion
35425
+ //#region ../sdk-node/dist/payloads-BldLJXGd.js
35426
+ /**
35427
+ * Load a Node builtin at call time. Exported for direct testing of the
35428
+ * unavailable-module error path; production code goes through the typed
35429
+ * wrappers below.
35430
+ */
35431
+ async function loadBuiltin(specifier, operation) {
35432
+ let builtin;
35433
+ if (typeof process !== "undefined" && typeof process.getBuiltinModule === "function") try {
35434
+ builtin = process.getBuiltinModule(specifier);
35435
+ } catch {
35436
+ builtin = void 0;
35437
+ }
35438
+ if (builtin !== void 0 && builtin !== null) return builtin;
35439
+ try {
35440
+ return await import(specifier);
35441
+ } catch (cause) {
35442
+ throw new Error(`${operation} requires file system access, which this runtime does not provide. Pass in-memory bytes instead of a file path when running outside Node.js.`, { cause });
35443
+ }
35444
+ }
35445
+ /** `node:fs`, loaded lazily so Workers-style bundles never see the import. */
35446
+ function loadNodeFs(operation) {
35447
+ return loadBuiltin("node:fs", operation);
35448
+ }
35449
+ /** `node:fs/promises`, loaded lazily for the same reason as {@link loadNodeFs}. */
35450
+ function loadNodeFsPromises(operation) {
35451
+ return loadBuiltin("node:fs/promises", operation);
35452
+ }
35453
+ const CHUNK_SIZE = 67108864;
35454
+ const MANIFEST_VERSION = 1;
35455
+ const CHUNK_KDF_INFO = "payloads-chunk";
35456
+ const OBJECT_ID_BYTES = 16;
35457
+ const CEK_BYTES = 32;
35458
+ function subtle() {
35459
+ return globalThis.crypto.subtle;
35460
+ }
35461
+ const textEncoder = new TextEncoder();
35462
+ function randomBytes(length) {
35463
+ const out = new Uint8Array(length);
35464
+ globalThis.crypto.getRandomValues(out);
35465
+ return out;
35466
+ }
35467
+ function toHex(bytes) {
35468
+ let out = "";
35469
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
35470
+ return out;
35471
+ }
35472
+ function fromHex(hex) {
35473
+ if (hex.length % 2 !== 0) throw new Error("invalid hex: odd length");
35474
+ if (hex.length > 0 && !/^[0-9a-fA-F]+$/.test(hex)) throw new Error("invalid hex: non-hex character");
35475
+ const out = new Uint8Array(hex.length / 2);
35476
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
35477
+ return out;
35478
+ }
35479
+ async function contentHash(bytes) {
35480
+ return new Uint8Array(await subtle().digest("SHA-256", bytes));
35481
+ }
35482
+ async function contentHashHex(bytes) {
35483
+ return toHex(await contentHash(bytes));
35484
+ }
35485
+ /** Binary Merkle root over ordered hex leaf hashes (odd node promoted). */
35486
+ async function merkleRoot(leafHashesHex) {
35487
+ if (leafHashesHex.length === 0) return contentHashHex(/* @__PURE__ */ new Uint8Array(0));
35488
+ let level = leafHashesHex.map(fromHex);
35489
+ while (level.length > 1) {
35490
+ const next = [];
35491
+ for (let i = 0; i < level.length; i += 2) {
35492
+ const left = level[i];
35493
+ const right = i + 1 < level.length ? level[i + 1] : level[i];
35494
+ const combined = new Uint8Array(left.length + right.length);
35495
+ combined.set(left, 0);
35496
+ combined.set(right, left.length);
35497
+ next.push(await contentHash(combined));
35498
+ }
35499
+ level = next;
35500
+ }
35501
+ return toHex(level[0]);
35502
+ }
35503
+ async function deriveChunkKey(cek, index) {
35504
+ const baseKey = await subtle().importKey("raw", cek, "HKDF", false, ["deriveKey"]);
35505
+ const info = textEncoder.encode(`${CHUNK_KDF_INFO}:${index}`);
35506
+ return subtle().deriveKey({
35507
+ name: "HKDF",
35508
+ hash: "SHA-256",
35509
+ salt: /* @__PURE__ */ new Uint8Array(32),
35510
+ info
35511
+ }, baseKey, {
35512
+ name: "AES-GCM",
35513
+ length: 256
35514
+ }, false, ["encrypt", "decrypt"]);
35515
+ }
35516
+ function chunkNonce(index) {
35517
+ const nonce = /* @__PURE__ */ new Uint8Array(12);
35518
+ new DataView(nonce.buffer).setUint32(8, index >>> 0, false);
35519
+ return nonce;
35520
+ }
35521
+ function chunkAad(objectId, index) {
35522
+ const aad = new Uint8Array(objectId.length + 4);
35523
+ aad.set(objectId, 0);
35524
+ new DataView(aad.buffer).setUint32(objectId.length, index >>> 0, false);
35525
+ return aad;
35526
+ }
35527
+ async function encryptChunk(cek, objectId, index, plaintext) {
35528
+ const key = await deriveChunkKey(cek, index);
35529
+ const ct = await subtle().encrypt({
35530
+ name: "AES-GCM",
35531
+ iv: chunkNonce(index),
35532
+ additionalData: chunkAad(objectId, index)
35533
+ }, key, plaintext);
35534
+ return new Uint8Array(ct);
35535
+ }
35536
+ async function decryptChunk(cek, objectId, index, ciphertext) {
35537
+ const key = await deriveChunkKey(cek, index);
35538
+ const pt = await subtle().decrypt({
35539
+ name: "AES-GCM",
35540
+ iv: chunkNonce(index),
35541
+ additionalData: chunkAad(objectId, index)
35542
+ }, key, ciphertext);
35543
+ return new Uint8Array(pt);
35544
+ }
35545
+ function authHeaders(apiKey) {
35546
+ return { authorization: `Bearer ${apiKey}` };
35547
+ }
35548
+ function apiRoot(baseUrl) {
35549
+ let end = baseUrl.length;
35550
+ while (end > 0 && baseUrl.charCodeAt(end - 1) === 47) end--;
35551
+ return `${baseUrl.slice(0, end)}/v1/payloads`;
35552
+ }
35553
+ const DEFAULT_MAX_RETRIES = 6;
35554
+ const RETRYABLE_STATUS = /* @__PURE__ */ new Set([
35555
+ 429,
35556
+ 500,
35557
+ 502,
35558
+ 503,
35559
+ 504
35560
+ ]);
35561
+ function sleep$3(ms) {
35562
+ return new Promise((resolve) => setTimeout(resolve, ms));
35563
+ }
35564
+ /**
35565
+ * fetch with exponential backoff on transient failures. Request bodies here are
35566
+ * in-memory buffers/strings (never streams), so a retry can safely resend them.
35567
+ */
35568
+ async function retryingFetch(url, init, label, maxRetries = DEFAULT_MAX_RETRIES) {
35569
+ for (let attempt = 0;; attempt++) {
35570
+ let res;
35571
+ let networkError;
35572
+ try {
35573
+ res = await fetch(url, init);
35574
+ } catch (err) {
35575
+ networkError = err;
35576
+ }
35577
+ if (res && !RETRYABLE_STATUS.has(res.status)) return res;
35578
+ if (attempt >= maxRetries) {
35579
+ if (res) return res;
35580
+ throw new Error(`${label}: network error after ${attempt} retries: ${networkError?.message ?? networkError}`);
35581
+ }
35582
+ if (res) await res.text().catch(() => {});
35583
+ await sleep$3(Math.min(1e3 * 2 ** attempt, 15e3) + Math.floor(Math.random() * 250));
35584
+ }
35585
+ }
35586
+ async function initiate(opts, manifest) {
35587
+ const res = await retryingFetch(apiRoot(opts.baseUrl), {
35588
+ method: "POST",
35589
+ headers: {
35590
+ ...authHeaders(opts.apiKey),
35591
+ "content-type": "application/json"
35592
+ },
35593
+ body: JSON.stringify({ manifest })
35594
+ }, "initiate");
35595
+ if (!res.ok) throw new Error(`initiate failed: HTTP ${res.status} ${await res.text()}`);
35596
+ await res.text();
35597
+ }
35598
+ async function putChunk(opts, root, d, bytes) {
35599
+ const res = await retryingFetch(`${apiRoot(opts.baseUrl)}/${root}/chunks/${d.ciphertextHash}`, {
35600
+ method: "PUT",
35601
+ headers: {
35602
+ ...authHeaders(opts.apiKey),
35603
+ "content-type": "application/octet-stream"
35604
+ },
35605
+ body: bytes
35606
+ }, `chunk ${d.index} upload`);
35607
+ if (!res.ok) throw new Error(`chunk ${d.index} upload failed: HTTP ${res.status} ${await res.text()}`);
35608
+ await res.text();
35609
+ }
35610
+ async function finalize(opts, root) {
35611
+ const res = await retryingFetch(`${apiRoot(opts.baseUrl)}/${root}/finalize`, {
35612
+ method: "POST",
35613
+ headers: authHeaders(opts.apiKey)
35614
+ }, "finalize");
35615
+ if (!res.ok) throw new Error(`finalize failed: HTTP ${res.status} ${await res.text()}`);
35616
+ await res.text();
35617
+ }
35618
+ async function fetchManifest(opts, root) {
35619
+ const res = await retryingFetch(`${apiRoot(opts.baseUrl)}/${root}/manifest`, { headers: authHeaders(opts.apiKey) }, "get manifest");
35620
+ if (!res.ok) throw new Error(`get manifest failed: HTTP ${res.status} ${await res.text()}`);
35621
+ return (await res.json()).data.manifest;
35622
+ }
35623
+ async function getChunkBytes(opts, root, d) {
35624
+ const res = await retryingFetch(`${apiRoot(opts.baseUrl)}/${root}/chunks/${d.ciphertextHash}`, { headers: authHeaders(opts.apiKey) }, `get chunk ${d.index}`);
35625
+ if (!res.ok) throw new Error(`get chunk ${d.index} failed: HTTP ${res.status}`);
35626
+ return new Uint8Array(await res.arrayBuffer());
35627
+ }
35628
+ async function readWindow(fh, position, length) {
35629
+ const buf = Buffer.allocUnsafe(length);
35630
+ let read = 0;
35631
+ while (read < length) {
35632
+ const { bytesRead } = await fh.read(buf, read, length - read, position + read);
35633
+ if (bytesRead === 0) break;
35634
+ read += bytesRead;
35635
+ }
35636
+ return read === length ? buf : buf.subarray(0, read);
35637
+ }
35638
+ async function mapLimit(items, limit, fn) {
35639
+ let next = 0;
35640
+ let firstError;
35641
+ const worker = async () => {
35642
+ while (next < items.length && firstError === void 0) {
35643
+ const i = next++;
35644
+ try {
35645
+ await fn(items[i], i);
35646
+ } catch (err) {
35647
+ if (firstError === void 0) firstError = err;
35648
+ return;
35649
+ }
35650
+ }
35651
+ };
35652
+ await Promise.all(Array.from({ length: Math.min(limit, items.length || 1) }, () => worker()));
35653
+ if (firstError !== void 0) throw firstError;
35654
+ }
35655
+ /**
35656
+ * Stream a file up as a Primitive Payload. Two passes over the file (encrypt to
35657
+ * build the manifest, then encrypt again to upload) keep memory bounded to a few
35658
+ * chunks — the whole object is never resident. Returns the content address
35659
+ * (merkleRoot) and the hex CEK needed to download it.
35660
+ */
35661
+ async function pushFile(filePath, opts) {
35662
+ const { open, stat } = await loadNodeFsPromises("pushFile");
35663
+ const chunkSize = opts.chunkSize ?? CHUNK_SIZE;
35664
+ const concurrency = opts.concurrency ?? 3;
35665
+ const { size } = await stat(filePath);
35666
+ const cek = randomBytes(CEK_BYTES);
35667
+ const objectId = randomBytes(OBJECT_ID_BYTES);
35668
+ const chunkCount = size === 0 ? 0 : Math.ceil(size / chunkSize);
35669
+ const fh = await open(filePath, "r");
35670
+ try {
35671
+ const descriptors = [];
35672
+ for (let index = 0; index < chunkCount; index++) {
35673
+ const position = index * chunkSize;
35674
+ const length = Math.min(chunkSize, size - position);
35675
+ const plaintext = await readWindow(fh, position, length);
35676
+ const ciphertext = await encryptChunk(cek, objectId, index, plaintext);
35677
+ descriptors.push({
35678
+ index,
35679
+ ciphertextHash: await contentHashHex(ciphertext),
35680
+ plaintextSize: length,
35681
+ ciphertextSize: ciphertext.length
35682
+ });
35683
+ opts.onProgress?.("encrypt", index + 1, chunkCount);
35684
+ }
35685
+ const root = await merkleRoot(descriptors.map((d) => d.ciphertextHash));
35686
+ await initiate(opts, {
35687
+ version: MANIFEST_VERSION,
35688
+ objectId: toHex(objectId),
35689
+ chunkSize,
35690
+ totalPlaintextSize: size,
35691
+ chunkCount,
35692
+ chunks: descriptors,
35693
+ merkleRoot: root
35694
+ });
35695
+ let uploaded = 0;
35696
+ await mapLimit(descriptors, concurrency, async (d) => {
35697
+ const position = d.index * chunkSize;
35698
+ const plaintext = await readWindow(fh, position, d.plaintextSize);
35699
+ const ciphertext = await encryptChunk(cek, objectId, d.index, plaintext);
35700
+ await putChunk(opts, root, d, ciphertext);
35701
+ opts.onProgress?.("upload", ++uploaded, chunkCount);
35702
+ });
35703
+ await finalize(opts, root);
35704
+ return {
35705
+ merkleRoot: root,
35706
+ cek: toHex(cek),
35707
+ chunkCount,
35708
+ totalBytes: size
35709
+ };
35710
+ } finally {
35711
+ await fh.close();
35712
+ }
35713
+ }
35714
+ /**
35715
+ * Stream a Primitive Payload down to a file, verifying and decrypting one chunk
35716
+ * at a time (bounded memory). Every chunk is content-address-checked before
35717
+ * decryption, so a corrupt or substituted chunk throws.
35718
+ */
35719
+ async function pullFile(root, outPath, opts) {
35720
+ const { createWriteStream } = await loadNodeFs("pullFile");
35721
+ const { rm } = await loadNodeFsPromises("pullFile");
35722
+ const manifest = await fetchManifest(opts, root);
35723
+ const computedRoot = await merkleRoot(manifest.chunks.map((c) => c.ciphertextHash));
35724
+ if (computedRoot !== root) throw new Error(`manifest does not match the requested content address (got ${computedRoot})`);
35725
+ const cek = fromHex(opts.cek);
35726
+ const objectId = fromHex(manifest.objectId);
35727
+ const out = createWriteStream(outPath);
35728
+ let onWriteError = () => {};
35729
+ const writeErrored = new Promise((_, reject) => {
35730
+ onWriteError = reject;
35731
+ });
35732
+ writeErrored.catch(() => {});
35733
+ out.on("error", (err) => onWriteError(err));
35734
+ try {
35735
+ let done = 0;
35736
+ for (const d of manifest.chunks) {
35737
+ const ciphertext = await getChunkBytes(opts, root, d);
35738
+ if (await contentHashHex(ciphertext) !== d.ciphertextHash) throw new Error(`chunk ${d.index} failed integrity check`);
35739
+ const plaintext = await decryptChunk(cek, objectId, d.index, ciphertext);
35740
+ if (!out.write(plaintext)) await Promise.race([new Promise((resolve) => out.once("drain", resolve)), writeErrored]);
35741
+ opts.onProgress?.("download", ++done, manifest.chunkCount);
35742
+ }
35743
+ await Promise.race([new Promise((resolve) => out.end(resolve)), writeErrored]);
35744
+ } catch (err) {
35745
+ out.destroy();
35746
+ await rm(outPath, { force: true });
35747
+ throw err;
35748
+ }
35749
+ return manifest;
35750
+ }
35751
+ //#endregion
35424
35752
  //#region src/oclif/session-address-guard.ts
35425
35753
  /**
35426
35754
  * The session a connect or enroll runs in: the explicit --session, else the
@@ -35731,8 +36059,10 @@ var AgentConnectCommand = class AgentConnectCommand extends Command {
35731
36059
  };
35732
36060
  }
35733
36061
  if (!claimOnly) {
35734
- if (!session && !flags.resume) if (flags.profile) pollProfile = flags.profile;
35735
- else pollProfile = invitationProfileName(await readInvitationOnce());
36062
+ if (!session && !flags.resume) {
36063
+ if (flags.profile) pollProfile = flags.profile;
36064
+ else pollProfile = invitationProfileName(await readInvitationOnce());
36065
+ }
35736
36066
  const output = await runAgentConnect({
35737
36067
  configDir: this.config.configDir,
35738
36068
  packageRoot: this.config.root,
@@ -36345,6 +36675,8 @@ var AgentNotesDeleteCommand = class AgentNotesDeleteCommand extends Command {
36345
36675
  };
36346
36676
  const RENAME_UNSUPPORTED_MESSAGE = "This Primitive API does not support renaming yet. The display name was not changed.";
36347
36677
  var AgentRenameApiError = class extends Error {
36678
+ payload;
36679
+ status;
36348
36680
  constructor(payload, status) {
36349
36681
  super("Agent rename request failed.");
36350
36682
  this.payload = payload;
@@ -36880,8 +37212,9 @@ var AgentUpgradeCommand = class AgentUpgradeCommand extends Command {
36880
37212
  return;
36881
37213
  }
36882
37214
  process$1.stderr.write(`Verification code sent to ${email}.\n`);
37215
+ const code = flags.code ?? await promptRequired$1("Verification code: ");
36883
37216
  const verified = await verifyAgentClaim({
36884
- body: { verification_code: flags.code ?? await promptRequired$1("Verification code: ") },
37217
+ body: { verification_code: code },
36885
37218
  client: apiClient.client,
36886
37219
  responseStyle: "fields"
36887
37220
  });
@@ -36914,7 +37247,7 @@ async function promptRequired$1(question) {
36914
37247
  /** The address note that holds an agent's current work claim. */
36915
37248
  const WORKING_NOTE_NAME = "AGENT_WORKING";
36916
37249
  /** Default claim lifetime when --until is omitted. */
36917
- const DEFAULT_CLAIM_MS = 14400 * 1e3;
37250
+ const DEFAULT_CLAIM_MS = 144e5;
36918
37251
  /** Validate the claim text and expiry and build the stored note value. */
36919
37252
  function buildWorkingClaim(params) {
36920
37253
  const claim = params.claim.trim();
@@ -37037,14 +37370,14 @@ const STDIN_WAIT_MS = 3e4;
37037
37370
  const workingClaimStdin = { read: () => {
37038
37371
  if (process.stdin.isTTY) throw new Error("--stdin needs the claim piped in, not typed at a terminal.");
37039
37372
  const limit = 2002;
37040
- const buffer = Buffer.alloc(limit + 1);
37373
+ const buffer = Buffer.alloc(2003);
37041
37374
  const pause = new Int32Array(new SharedArrayBuffer(4));
37042
37375
  const deadline = Date.now() + STDIN_WAIT_MS;
37043
37376
  let length = 0;
37044
37377
  while (length <= limit) {
37045
37378
  let read = 0;
37046
37379
  try {
37047
- read = readSync(0, buffer, length, limit + 1 - length, null);
37380
+ read = readSync(0, buffer, length, 2003 - length, null);
37048
37381
  } catch (error) {
37049
37382
  const code = error.code;
37050
37383
  if (code === "EOF") break;
@@ -37376,6 +37709,7 @@ function reclaimStaleLock(path, previous, temporary, contender) {
37376
37709
  }
37377
37710
  }
37378
37711
  var ChatLockContentionError = class extends Error {
37712
+ holderPid;
37379
37713
  constructor(holderPid) {
37380
37714
  super(holderPid > 0 ? `Another \`primitive chat\` invocation (pid ${holderPid}) is in progress. Wait for it to finish, or kill it before retrying.` : "The chat lock holder could not be verified. Retry after the current invocation finishes.");
37381
37715
  this.holderPid = holderPid;
@@ -37520,7 +37854,7 @@ function saveChatReceipt(receipt) {
37520
37854
  }
37521
37855
  function parseReceipt(raw) {
37522
37856
  const value = JSON.parse(raw);
37523
- if (!value || value.version !== 1 || typeof value.request_hash !== "string" || typeof value.sent_at !== "string" || !Number.isFinite(Date.parse(value.sent_at)) || typeof value.completed !== "boolean" || value.reply !== void 0 && (!value.reply || typeof value.reply !== "object" || typeof value.reply.emailId !== "string" || !value.reply.emailId || typeof value.reply.requestId !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value.reply.requestId)) || value.idempotency_key !== void 0 && (typeof value.idempotency_key !== "string" || !/^[!-~]{1,255}$/.test(value.idempotency_key)) || value.send_attempted !== void 0 && typeof value.send_attempted !== "boolean" || value.sent !== null && (!value.sent || typeof value.sent.id !== "string" || !value.sent.id || typeof value.sent.status !== "string")) throw new Error("Invalid chat receipt");
37857
+ if (value?.version !== 1 || typeof value.request_hash !== "string" || typeof value.sent_at !== "string" || !Number.isFinite(Date.parse(value.sent_at)) || typeof value.completed !== "boolean" || value.reply !== void 0 && (!value.reply || typeof value.reply !== "object" || typeof value.reply.emailId !== "string" || !value.reply.emailId || typeof value.reply.requestId !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value.reply.requestId)) || value.idempotency_key !== void 0 && (typeof value.idempotency_key !== "string" || !/^[!-~]{1,255}$/.test(value.idempotency_key)) || value.send_attempted !== void 0 && typeof value.send_attempted !== "boolean" || value.sent !== null && (!value.sent || typeof value.sent.id !== "string" || !value.sent.id || typeof value.sent.status !== "string")) throw new Error("Invalid chat receipt");
37524
37858
  return value;
37525
37859
  }
37526
37860
  /**
@@ -37637,7 +37971,7 @@ function parseContactInteraction(bytes, now = Date.now()) {
37637
37971
  const result = parseInteractionEnvelope$1(bytes);
37638
37972
  if (result.status !== "valid") return null;
37639
37973
  const e = result.envelope;
37640
- if (e.protocol !== "primitive.contact" || e.protocol_version !== 1 || !["request", "accept"].includes(e.step) || typeof e.expires_at !== "string" || !Number.isFinite(Date.parse(e.expires_at)) || Date.parse(e.expires_at) <= now || Date.parse(e.expires_at) > now + 604800 * 1e3 || !e.payload || typeof e.payload !== "object" || Array.isArray(e.payload)) return null;
37974
+ if (e.protocol !== "primitive.contact" || e.protocol_version !== 1 || !["request", "accept"].includes(e.step) || typeof e.expires_at !== "string" || !Number.isFinite(Date.parse(e.expires_at)) || Date.parse(e.expires_at) <= now || Date.parse(e.expires_at) > now + 6048e5 || !e.payload || typeof e.payload !== "object" || Array.isArray(e.payload)) return null;
37641
37975
  const payload = e.payload;
37642
37976
  if (e.step === "request") {
37643
37977
  if (e.prev_step_id !== null || Object.keys(payload).length !== 1 || typeof payload.reason !== "string" || !payload.reason.trim() || Array.from(payload.reason).length > 2e3) return null;
@@ -37651,7 +37985,7 @@ async function readContactInteraction(detail, readPart, signal, now = Date.now()
37651
37985
  const canonical = parts.filter((part) => part.filename?.toLowerCase() === "interaction.json");
37652
37986
  if (canonical.length !== 1) return null;
37653
37987
  const part = canonical[0];
37654
- if (!part || part.content_type?.split(";")[0]?.trim().toLowerCase() !== "application/json" || !Number.isSafeInteger(part.part_index) || part.part_index === void 0 || part.part_index < 0 || !Number.isSafeInteger(part.size_bytes) || part.size_bytes < 1 || part.size_bytes > 8192 || typeof part.sha256 !== "string" || !/^[a-f0-9]{64}$/i.test(part.sha256)) return null;
37988
+ if (part?.content_type?.split(";")[0]?.trim().toLowerCase() !== "application/json" || !Number.isSafeInteger(part.part_index) || part.part_index === void 0 || part.part_index < 0 || !Number.isSafeInteger(part.size_bytes) || part.size_bytes < 1 || part.size_bytes > 8192 || typeof part.sha256 !== "string" || !/^[a-f0-9]{64}$/i.test(part.sha256)) return null;
37655
37989
  let bytes;
37656
37990
  try {
37657
37991
  bytes = await readPart(detail.id, part.part_index, signal);
@@ -38235,8 +38569,7 @@ async function enablePeer(context, peer, reason) {
38235
38569
  ...reason ? { purpose: reason } : {}
38236
38570
  });
38237
38571
  await policy.refresh(signal());
38238
- const allowed = await policy.admit(peer, (/* @__PURE__ */ new Date()).toISOString(), signal());
38239
- if (!allowed || allowed.kind !== "allowed") throw new Error("Contact notification permission changed. No contact email was sent; inspect the saved preference before retrying.");
38572
+ if ((await policy.admit(peer, (/* @__PURE__ */ new Date()).toISOString(), signal()))?.kind !== "allowed") throw new Error("Contact notification permission changed. No contact email was sent; inspect the saved preference before retrying.");
38240
38573
  }
38241
38574
  async function requestContact(context, options) {
38242
38575
  const peer = canonicalContactSelector({
@@ -38610,12 +38943,12 @@ function deriveSubject(body) {
38610
38943
  for (const line of body.split("\n")) {
38611
38944
  const trimmed = line.trim();
38612
38945
  if (!trimmed) continue;
38613
- return trimmed.length > SUBJECT_MAX_LENGTH ? `${trimmed.slice(0, SUBJECT_MAX_LENGTH - 3)}...` : trimmed;
38946
+ return trimmed.length > SUBJECT_MAX_LENGTH ? `${trimmed.slice(0, 197)}...` : trimmed;
38614
38947
  }
38615
38948
  return "Message";
38616
38949
  }
38617
38950
  const CHAT_SUBJECT_MAX_LENGTH = 60;
38618
- const TITLES$1 = new Set([
38951
+ const TITLES$1 = /* @__PURE__ */ new Set([
38619
38952
  "dr",
38620
38953
  "mr",
38621
38954
  "mrs",
@@ -38630,7 +38963,7 @@ const TITLES$1 = new Set([
38630
38963
  "approx",
38631
38964
  "fig"
38632
38965
  ]);
38633
- const ABBREVIATIONS = new Set([
38966
+ const ABBREVIATIONS = /* @__PURE__ */ new Set([
38634
38967
  "etc",
38635
38968
  "inc",
38636
38969
  "ltd",
@@ -38666,7 +38999,7 @@ function firstSentence(line) {
38666
38999
  function deriveChatSubject(body) {
38667
39000
  const sentence = firstSentence(deriveSubject(body));
38668
39001
  if (sentence.length <= CHAT_SUBJECT_MAX_LENGTH) return sentence;
38669
- const room = sentence.slice(0, CHAT_SUBJECT_MAX_LENGTH - 3);
39002
+ const room = sentence.slice(0, 57);
38670
39003
  const space = room.lastIndexOf(" ");
38671
39004
  return `${(space >= CHAT_SUBJECT_MAX_LENGTH / 2 ? room.slice(0, space) : room).replace(/[\s,;:.!?-]+$/, "")}...`;
38672
39005
  }
@@ -38888,6 +39221,8 @@ function chatSuccessText(message) {
38888
39221
  return chatColor("greenBright", message);
38889
39222
  }
38890
39223
  var ChatProgressIndicator = class {
39224
+ stream;
39225
+ now;
38891
39226
  currentMessage = null;
38892
39227
  frameIndex = 0;
38893
39228
  lastLineLength = 0;
@@ -39934,8 +40269,10 @@ var ChatCommand = class ChatCommand extends Command {
39934
40269
  this.chatProgress.priorReplies = priorReplies;
39935
40270
  if (!resumed) {
39936
40271
  const warning = priorReplies === null ? `Could not check whether you already replied to email ${parentReply.id} (the API returned no reply history). Prior-reply check skipped; sending the reply anyway.` : formatPriorRepliesWarning(priorReplies);
39937
- if (warning !== null) if (progress) progress.notice(warning);
39938
- else process.stderr.write(`${chatNoticeText(warning)}\n`);
40272
+ if (warning !== null) {
40273
+ if (progress) progress.notice(warning);
40274
+ else process.stderr.write(`${chatNoticeText(warning)}\n`);
40275
+ }
39939
40276
  }
39940
40277
  }
39941
40278
  if (resumed) progress?.start("Resuming the recorded send without sending again");
@@ -41561,7 +41898,7 @@ async function readTickPart(input) {
41561
41898
  if (detail.parsed?.status !== "complete") return null;
41562
41899
  const parts = (detail.parsed.attachments ?? []).filter((part) => part.filename?.toLowerCase() === "interaction.json");
41563
41900
  const part = parts.length === 1 ? parts[0] : void 0;
41564
- if (!part || part.content_type?.split(";")[0]?.trim().toLowerCase() !== "application/json" || part.part_index === void 0 || !Number.isSafeInteger(part.part_index) || part.part_index < 0 || !Number.isSafeInteger(part.size_bytes) || part.size_bytes <= 0 || part.size_bytes > 65536 || typeof part.sha256 !== "string" || !/^[a-f0-9]{64}$/i.test(part.sha256)) return null;
41901
+ if (part?.content_type?.split(";")[0]?.trim().toLowerCase() !== "application/json" || part.part_index === void 0 || !Number.isSafeInteger(part.part_index) || part.part_index < 0 || !Number.isSafeInteger(part.size_bytes) || part.size_bytes <= 0 || part.size_bytes > 65536 || typeof part.sha256 !== "string" || !/^[a-f0-9]{64}$/i.test(part.sha256)) return null;
41565
41902
  const readPart = input.readPart ?? notificationPartReader(async () => input.client);
41566
41903
  let bytes;
41567
41904
  try {
@@ -43617,7 +43954,7 @@ const PRIMITIVE_TEAM_AUTHOR = {
43617
43954
  url: "https://primitive.dev"
43618
43955
  };
43619
43956
  const SDK_VERSION_RANGE = "^1.35.0";
43620
- const CLI_VERSION_RANGE = "^1.54.0";
43957
+ const CLI_VERSION_RANGE = "^1.55.0";
43621
43958
  const ESBUILD_VERSION_RANGE = "^0.27.0";
43622
43959
  function renderHandler() {
43623
43960
  return `// env.PRIMITIVE_API_KEY, env.PRIMITIVE_WEBHOOK_SECRET, and
@@ -45052,7 +45389,7 @@ var FunctionsTemplatesCommand = class FunctionsTemplatesCommand extends Command
45052
45389
  //#endregion
45053
45390
  //#region src/oclif/commands/functions-test-function.ts
45054
45391
  const DEFAULT_WAIT_TIMEOUT_SECONDS$1 = 60;
45055
- const TERMINAL_TEST_TRACE_STATES = new Set([
45392
+ const TERMINAL_TEST_TRACE_STATES = /* @__PURE__ */ new Set([
45056
45393
  "completed",
45057
45394
  "failed",
45058
45395
  "send_failed"
@@ -45329,6 +45666,8 @@ const MAX_LONG_POLL_SECONDS = 30;
45329
45666
  const EPOCH_CURSOR = "1970-01-01T00:00:00.000000Z|00000000-0000-4000-8000-000000000000";
45330
45667
  /** An API call failed; carries the error payload for printing. */
45331
45668
  var InboxNextApiError = class extends Error {
45669
+ surface;
45670
+ payload;
45332
45671
  constructor(surface, payload) {
45333
45672
  super(`${surface} failed`);
45334
45673
  this.surface = surface;
@@ -45690,7 +46029,7 @@ function formatTranscript(result, bin) {
45690
46029
  ...conversation.messages.map((message, index) => formatMessage(message, index)),
45691
46030
  "",
45692
46031
  ...transcriptFooter(interaction, actions, email.id, bin),
45693
- `Then run \`${bin} inbox next\` again.`
46032
+ `Then run \`${followUpCommandPrefix(bin)} inbox next\` again.`
45694
46033
  ].join("\n");
45695
46034
  }
45696
46035
  /**
@@ -46224,8 +46563,8 @@ var InboxSetupCommand = class InboxSetupCommand extends Command {
46224
46563
  //#endregion
46225
46564
  //#region src/oclif/listen-handlers.ts
46226
46565
  const HANDLER_TIMEOUT_MS = 3e4;
46227
- const MAX_RESPONSE_BYTES = 1024 * 1024;
46228
- const FORWARDED_HEADERS = new Set([
46566
+ const MAX_RESPONSE_BYTES = 1048576;
46567
+ const FORWARDED_HEADERS = /* @__PURE__ */ new Set([
46229
46568
  "content-type",
46230
46569
  "user-agent",
46231
46570
  "primitive-signature",
@@ -46385,6 +46724,8 @@ function structuredErrorCode(body) {
46385
46724
  }
46386
46725
  }
46387
46726
  var ForwardFailure = class extends Error {
46727
+ statusCode;
46728
+ transportError;
46388
46729
  constructor(statusCode, transportError) {
46389
46730
  super("Webhook transport did not complete.");
46390
46731
  this.statusCode = statusCode;
@@ -46536,15 +46877,16 @@ const hash = (value) => createHash("sha256").update(value).digest("hex");
46536
46877
  const invalid = () => new ListenStateError("Contact request notice state is unavailable. Preserve it to avoid duplicate notices.");
46537
46878
  /** Stable across profile, credential and native-session changes in one config. */
46538
46879
  function openContactRequestNotices(configDir, identity) {
46539
- const directory = join(configDir, "contact-request-notices", hash(JSON.stringify([
46880
+ const key = hash(JSON.stringify([
46540
46881
  identity.apiBaseUrl,
46541
46882
  identity.orgId,
46542
46883
  identity.agentAddress
46543
- ])));
46884
+ ]));
46885
+ const directory = join(configDir, "contact-request-notices", key);
46544
46886
  privateMailDirectory(directory, true);
46545
46887
  const path = join(directory, "notices.json");
46546
46888
  function read() {
46547
- const raw = readMailJson(path, 512 * 1024);
46889
+ const raw = readMailJson(path, 524288);
46548
46890
  if (raw === null) return {
46549
46891
  activatedAt: null,
46550
46892
  notices: []
@@ -46712,13 +47054,14 @@ async function reserveConversationStatus(context, status, now = Date.now()) {
46712
47054
  const previous = retained.find((entry) => entry.key === key);
46713
47055
  const emailId = mailId(status.emailId);
46714
47056
  if (previous?.emailIds.includes(emailId)) return false;
47057
+ const next = [...retained.filter((entry) => entry.key !== key), {
47058
+ key,
47059
+ emailIds: [...previous?.emailIds ?? [], emailId].slice(-16),
47060
+ at: due ? now : previous?.at ?? now
47061
+ }].slice(-256);
46715
47062
  writeMailJson(path, {
46716
47063
  version: 1,
46717
- entries: [...retained.filter((entry) => entry.key !== key), {
46718
- key,
46719
- emailIds: [...previous?.emailIds ?? [], emailId].slice(-16),
46720
- at: due ? now : previous?.at ?? now
46721
- }].slice(-256)
47064
+ entries: next
46722
47065
  });
46723
47066
  return due;
46724
47067
  });
@@ -46843,7 +47186,8 @@ function openPresenceControls(options) {
46843
47186
  }
46844
47187
  const parsed = parsePresenceEnvelope(bytes);
46845
47188
  if (parsed.status !== "valid" || parsed.envelope.step !== "probe" || parsed.envelope.payload.address !== profile.agent_address) return "quiet";
46846
- const intentDirectory = join(directory, createHash("sha256").update(parsed.envelope.interaction_id).digest("hex"));
47189
+ const key = createHash("sha256").update(parsed.envelope.interaction_id).digest("hex");
47190
+ const intentDirectory = join(directory, key);
46847
47191
  privateMailDirectory(intentDirectory, true);
46848
47192
  let release;
46849
47193
  try {
@@ -47012,7 +47356,6 @@ function normalizePresenceText(text) {
47012
47356
  }
47013
47357
  //#endregion
47014
47358
  //#region src/oclif/thread-mutes.ts
47015
- const MAX_MUTES = 500;
47016
47359
  const SESSION = /^(?:claude|codex):[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
47017
47360
  var ThreadMuteStateError = class extends Error {};
47018
47361
  function mutePath(configDir, profileName) {
@@ -47063,7 +47406,7 @@ function isThreadMuted(configDir, profileName, threadId, sessionKey) {
47063
47406
  }
47064
47407
  async function update(configDir, profileName, change) {
47065
47408
  return withMailLock(lockDirectory(configDir, profileName), () => {
47066
- const next = change(readThreadMutes(configDir, profileName)).slice(-MAX_MUTES);
47409
+ const next = change(readThreadMutes(configDir, profileName)).slice(-500);
47067
47410
  writeMailJson(mutePath(configDir, profileName), {
47068
47411
  version: 1,
47069
47412
  threads: next
@@ -47421,8 +47764,10 @@ async function runSharedNotificationListen(options) {
47421
47764
  try {
47422
47765
  await reconcile(row);
47423
47766
  } catch (error) {
47424
- if (!(dispatchFailure instanceof NotificationOutcomeUnknownError)) if (error instanceof NotificationOutcomeUnknownError) dispatchFailure = error;
47425
- else dispatchFailure ??= error;
47767
+ if (!(dispatchFailure instanceof NotificationOutcomeUnknownError)) {
47768
+ if (error instanceof NotificationOutcomeUnknownError) dispatchFailure = error;
47769
+ else dispatchFailure ??= error;
47770
+ }
47426
47771
  }
47427
47772
  if (dispatchFailure !== void 0) throw dispatchFailure;
47428
47773
  return completed;
@@ -47498,6 +47843,9 @@ async function hydrateNotification(store, detail, peer) {
47498
47843
  //#region src/oclif/listen-runner.ts
47499
47844
  var ListenError = class extends Error {};
47500
47845
  var RequestFailure = class extends ListenError {
47846
+ status;
47847
+ code;
47848
+ retryAfter;
47501
47849
  constructor(status, code, retryAfter) {
47502
47850
  super(code === "agent_connection_scope_forbidden" ? "This operation is outside the connected address grant. Use inbound email events and this credential’s own subscription." : status === 401 || status === 403 ? "Listener authorization failed. Run primitive signin or check your API key and account permissions." : status === 409 && code === "subscription_conflict" ? "This subscription has different event filters. Omit --events to resume it, or use primitive listen --subscription new-subscription (add your --events selection)." : `Listener API request failed (HTTP ${status || "transport"}, ${code}).`);
47503
47851
  this.status = status;
@@ -49012,12 +49360,14 @@ function sleep(ms) {
49012
49360
  return new Promise((resolve) => setTimeout(resolve, ms));
49013
49361
  }
49014
49362
  function openBrowser(url) {
49015
- const child = spawn(process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open", process.platform === "win32" ? [
49363
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
49364
+ const args = process.platform === "win32" ? [
49016
49365
  "/c",
49017
49366
  "start",
49018
49367
  "",
49019
49368
  url
49020
- ] : [url], {
49369
+ ] : [url];
49370
+ const child = spawn(command, args, {
49021
49371
  detached: true,
49022
49372
  stdio: "ignore"
49023
49373
  });
@@ -49197,8 +49547,9 @@ var LoginCommand$1 = class extends Command {
49197
49547
  throw cliError$3(existingStatus.message);
49198
49548
  } else throw cliError$3(`Already logged in${existing.org_name ? ` for ${existing.org_name}` : ""}. Run \`primitive logout\` before logging in again.`);
49199
49549
  }
49550
+ const deviceName = flags["device-name"] ?? hostname();
49200
49551
  const started = await startCliLogin({
49201
- body: { device_name: flags["device-name"] ?? hostname() },
49552
+ body: { device_name: deviceName },
49202
49553
  client: apiClient.client,
49203
49554
  responseStyle: "fields"
49204
49555
  });
@@ -49410,10 +49761,12 @@ function writeSignupStatus(status) {
49410
49761
  }
49411
49762
  process$1.stdout.write(`Pending Primitive signup for ${status.email}.\n`);
49412
49763
  if (status.code_length !== null) process$1.stdout.write(`Verification code length: ${status.code_length}\n`);
49413
- if (status.expires_at) if (status.expired) process$1.stdout.write(`Expired at: ${status.expires_at}\n`);
49414
- else {
49415
- process$1.stdout.write(`Expires at: ${status.expires_at}\n`);
49416
- process$1.stdout.write(`Expires in: ${formatSignupSeconds(status.expires_in)}\n`);
49764
+ if (status.expires_at) {
49765
+ if (status.expired) process$1.stdout.write(`Expired at: ${status.expires_at}\n`);
49766
+ else {
49767
+ process$1.stdout.write(`Expires at: ${status.expires_at}\n`);
49768
+ process$1.stdout.write(`Expires in: ${formatSignupSeconds(status.expires_in)}\n`);
49769
+ }
49417
49770
  }
49418
49771
  if (status.resend_after !== null) process$1.stdout.write(`Resend after: ${formatSignupSeconds(status.resend_after)}\n`);
49419
49772
  if (status.confirm_command) process$1.stdout.write(`Confirm: ${status.confirm_command}\n`);
@@ -50543,7 +50896,8 @@ function backupStamp(now) {
50543
50896
  return now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
50544
50897
  }
50545
50898
  function runtimePresent(runtime, paths, env) {
50546
- return existsSync(runtime === "claude" ? paths.claudeDir : runtime === "codex" ? paths.codexHome : paths.ompRoot) || findOnPath(runtime, env) !== null;
50899
+ const directory = runtime === "claude" ? paths.claudeDir : runtime === "codex" ? paths.codexHome : paths.ompRoot;
50900
+ return existsSync(directory) || findOnPath(runtime, env) !== null;
50547
50901
  }
50548
50902
  function runtimePaths(env, home) {
50549
50903
  const ompRoot = resolve(home, env.PI_CONFIG_DIR || ".omp");
@@ -50732,9 +51086,11 @@ async function runMachineDoctor(options) {
50732
51086
  });
50733
51087
  },
50734
51088
  repair: () => {
50735
- const read = readManagedFile(path());
51089
+ const target = path();
51090
+ const read = readManagedFile(target);
50736
51091
  if (read.state === "invalid") return false;
50737
- const next = upsertManagedBlock(read.state === "present" ? read.text : "", managedInstructions(runtime, { skillBundled: loadBundle() !== null }));
51092
+ const text = read.state === "present" ? read.text : "";
51093
+ const next = upsertManagedBlock(text, managedInstructions(runtime, { skillBundled: loadBundle() !== null }));
50738
51094
  if (read.state === "present" && next === read.text) return false;
50739
51095
  writeManagedFile({
50740
51096
  read,
@@ -51667,6 +52023,7 @@ var MemoriesSearchCommand = class MemoriesSearchCommand extends Command {
51667
52023
  //#endregion
51668
52024
  //#region src/oclif/network.ts
51669
52025
  var NetworkApiError = class extends Error {
52026
+ payload;
51670
52027
  constructor(payload) {
51671
52028
  super("Network request failed.");
51672
52029
  this.payload = payload;
@@ -51739,13 +52096,14 @@ async function runNetworkRequest(client, request) {
51739
52096
  }))).data;
51740
52097
  if (request.action !== "set") throw new Error("Unknown network operation.");
51741
52098
  if (request.see === void 0 && request.beSeen === void 0) throw new Error("Pass --see on|off, --be-seen on|off, or both.");
52099
+ const body = {
52100
+ ...request.see === void 0 ? {} : { can_view: request.see === "on" },
52101
+ ...request.beSeen === void 0 ? {} : { is_listed: request.beSeen === "on" }
52102
+ };
51742
52103
  return (await response(updateDefaultNetworkMember({
51743
52104
  client,
51744
52105
  path,
51745
- body: {
51746
- ...request.see === void 0 ? {} : { can_view: request.see === "on" },
51747
- ...request.beSeen === void 0 ? {} : { is_listed: request.beSeen === "on" }
51748
- },
52106
+ body,
51749
52107
  responseStyle: "fields"
51750
52108
  }))).data;
51751
52109
  }
@@ -52746,7 +53104,7 @@ var X402Client = class {
52746
53104
  throw new X402Error(`non-JSON response (${res.status}) from ${path}: ${text.slice(0, 200)}`, res.status, text.slice(0, 500), { retryAfter });
52747
53105
  }
52748
53106
  if (!res.ok || json?.success === false) throw new X402Error(json?.error?.message ?? `request failed with ${res.status}`, res.status, json ?? text.slice(0, 500), { retryAfter });
52749
- if (!json || json.success !== true || json.data === void 0) throw new X402Error(`unexpected response shape (${res.status}) from ${path}: missing success/data envelope`, res.status, json ?? text.slice(0, 500), { retryAfter });
53107
+ if (json?.success !== true || json.data === void 0) throw new X402Error(`unexpected response shape (${res.status}) from ${path}: missing success/data envelope`, res.status, json ?? text.slice(0, 500), { retryAfter });
52750
53108
  return json.data;
52751
53109
  }
52752
53110
  /** Request a payment (payee side). Returns the challenge to hand to the payer. */
@@ -53165,9 +53523,9 @@ function usdcToBaseUnits(human) {
53165
53523
  /** Format token base units ("10000") back to a human USDC string ("0.01"). */
53166
53524
  function formatUsdc(baseUnits) {
53167
53525
  if (!/^\d+$/.test(baseUnits)) return baseUnits;
53168
- const padded = baseUnits.padStart(USDC_DECIMALS + 1, "0");
53169
- const whole = padded.slice(0, -USDC_DECIMALS);
53170
- const frac = padded.slice(-USDC_DECIMALS).replace(/0+$/, "");
53526
+ const padded = baseUnits.padStart(7, "0");
53527
+ const whole = padded.slice(0, -6);
53528
+ const frac = padded.slice(-6).replace(/0+$/, "");
53171
53529
  return frac ? `${whole}.${frac}` : whole;
53172
53530
  }
53173
53531
  /** Block-explorer URL for a settlement tx, or null for an unknown network/tx. */
@@ -53615,7 +53973,7 @@ var PaymentsPayEmailStepCommand = class PaymentsPayEmailStepCommand extends Comm
53615
53973
  /** The human-readable notice describing the async-settlement model. */
53616
53974
  const settlementWaitNotice = "Note: the payment has been SENT, but x402 settlement is asynchronous. --wait only confirms email delivery (SMTP 250), not on-chain settlement. The settle_tx hash arrives in a follow-up x402 settlement interaction email from the payee. Use --wait-settle to poll for it.";
53617
53975
  /** The steps a payer has already seen / sent, so a matching later step is the receipt. */
53618
- const NON_RECEIPT_STEPS = new Set(["challenge", "payment"]);
53976
+ const NON_RECEIPT_STEPS = /* @__PURE__ */ new Set(["challenge", "payment"]);
53619
53977
  /**
53620
53978
  * Best-effort extraction of a `settle_tx` from a receipt envelope. The exact
53621
53979
  * receipt wire shape is owned by the platform and not pinned in the SDK, so we
@@ -57813,7 +58171,7 @@ const DESCRIBE_OPERATION_ALIASES = {
57813
58171
  function resolveOperationAlias(id) {
57814
58172
  return DESCRIBE_OPERATION_ALIASES[id] ?? id;
57815
58173
  }
57816
- const OVERRIDDEN_OPERATION_IDS = new Set([
58174
+ const OVERRIDDEN_OPERATION_IDS = /* @__PURE__ */ new Set([
57817
58175
  "agent-connections:claim-agent-connection",
57818
58176
  "domains:download-domain-zone-file",
57819
58177
  "functions:test-function",