primcli 3.0.0-preview.22 → 3.0.0-preview.23

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,15 +1,15 @@
1
- import { $ as replyInteractionWarning, $t as oneDomainAtATimeError, A as describeWake, An as displayedRoleKey, At as connectNextSteps, B as wakeRecipientField, Bn as setKnownCommands, Bt as FOCUS_ENV, C as withApproval, Cn as refreshStoredCliCredentials, Ct as sendWaitClampNotice, D as openBrowser, Dn as CliOrgRefusedError, Dt as thrownErrorExitCode, E as listenForCopyHotkey, En as selectedOrgFromEnv, Et as successfulSendOutcome, F as sentInThread, Fn as roleKeyText, Ft as currentMailSessionKey, G as pendingMailPath, Gt as focusFlagValues, H as claimPendingMail, Ht as NO_FOCUS, I as serverMuted, In as switchCurrentOrg, It as detectAgentRuntime, J as removePendingMail, Jt as focusProfile, K as readPendingMail, Kt as focusFlags, L as serverRelationship, Ln as routeWarningLines, Lt as detectRuntimeSession, M as formatMailWakeLine, Mn as isBuiltInRoleKey, Mt as generatedAgentName, N as latestOwnOutbound, Nn as revokeUserLogin, Nt as identitySuggestions, O as explainPendingMailNotFound, On as RESTRICTED_ROLE_NOTE, P as readThreadContext, Pn as roleKeyLabel, Pt as loadSkillLine, Q as replyExpectation, Qt as normalizeDomainNames, Rn as sanitizeForTerminal, Rt as runtimeSessionVariableList, S as terminalApprovalIo, Sn as createCliApiClient, St as sendOutcomeExitCode, T as formatBrowserLoginInstructions, Tn as resolveCliApiRequestConfig, Tt as serializeErrorPayload, U as clearConsumedPendingMail, Ut as countFromMeta, V as wakeRelationship, Vn as operationManifest, Vt as FOCUS_SERVER_SUPPORT, W as clearReadPendingMail, Wt as focusEmptyHint, X as interactionNextActions, Xt as loadSavedFocus, Y as interactionHumanLine, Yt as joinNames, Z as readEmailInteraction, Zt as manyDomainsSupported, _ as BROWSER_FLAG_DESCRIPTION, _n as ATTACHMENT_WAIT_MAX_MS, _t as formatSendRecordFailureSummary, a as createOperationCommand, an as withFocusMeta, at as assertValidIdempotencyKey, b as approveThenRerunHint, bt as sendErrorMessage, c as formatErrorPayload, cn as withFlagSuggestion, ct as checkPriorReplies, d as networkErrorHint, dn as readCallerMailFor, dt as excludeSignalReplies, en as queryScopesItself, f as readTextFileFlag, fn as formatFact, ft as followUpCommandPrefix, g as writeErrorWithHints, gn as ATTACHMENT_WAIT_FLAG_DESCRIPTION, gt as formatSendFailureSummary, h as surfaceUnauthorizedHint, hn as withBooleanFlagValues, ht as formatPriorRepliesWarning, i as TIME_FLAG_DESCRIPTION, in as saveFocus, it as apiResultHttpStatus, j as displayAddress, jn as fetchCliOrgs, k as bareAddress, kn as credentialsFromUserLogin, kt as cliInvocation, l as hasControlCharacter$1, ln as emptyEmailListHint, lt as classifySendError, m as runWithTiming, mn as fetchBoundedPages, mt as formatPriorRepliesCheckSkipped, n as API_ERROR_CODES, nn as resolveDomainNames, nt as MAX_SEND_WAIT_TIMEOUT_MS, o as extractErrorCode, on as withoutFocus, ot as buildFollowUpCommand, p as refusesCredential, pn as isEmailId, pt as formatDeletedEarlierSendNotice, q as recordPendingMail, qt as focusForCorpus, r as PAGED_LIMIT_MAX, rn as resolveFocus, rt as SEND_OUTCOME_HELP, s as extractErrorPayload, sn as writeFocusLine, st as buildThrownSendFailureEnvelope, t as API_BASE_URL_FLAG_DESCRIPTION, tn as readDomainsOrRefusal, tt as IDEMPOTENCY_KEY_FLAG_DESCRIPTION, u as isGrantRefusal, un as mailReach, ut as deriveSendIdempotencyKey, v as STEP_UP_HEADER$1, vn as withAttachmentWait, vt as priorRepliesThatWentOut, w as canOfferCopyHotkey, wn as refuseOrgSelectionForProfile, wt as sentHistoryWindowStart, x as promptLine$2, xn as createAuthenticatedCliApiClient, xt as sendIdentityFields, y as STEP_UP_TOKEN_FLAG_DESCRIPTION, yn as ConnectedAgentKeyRequiredError, yt as reportSendCommandResult, z as wakeReadCommand, zn as shownLine, zt as formatAlreadySentNotice } from "../api-command-Dm1BKxOr.js";
1
+ import { $ as replyInteractionWarning, $t as resolveDomainNames, A as describeWake, An as revokeUserLogin, At as connectNextSteps, B as wakeRecipientField, Bt as countFromMeta, C as withApproval, Cn as selectedOrgFromEnv, Ct as sendWaitClampNotice, D as openBrowser, Dn as displayedRoleKey, Dt as thrownErrorExitCode, E as listenForCopyHotkey, En as credentialsFromUserLogin, Et as successfulSendOutcome, F as sentInThread, Fn as sanitizeForTerminal, Ft as currentMailSessionKey, G as pendingMailPath, Gt as focusProfile, H as claimPendingMail, Ht as focusFlagValues, I as serverMuted, In as shownLine, It as formatAlreadySentNotice, J as removePendingMail, Jt as manyDomainsSupported, K as readPendingMail, Kt as joinNames, L as serverRelationship, Ln as setKnownCommands, Lt as FOCUS_ENV, M as formatMailWakeLine, Mn as roleKeyText, Mt as generatedAgentName, N as latestOwnOutbound, Nn as switchCurrentOrg, Nt as identitySuggestions, O as explainPendingMailNotFound, On as fetchCliOrgs, P as readThreadContext, Pn as routeWarningLines, Pt as loadSkillLine, Q as replyExpectation, Qt as readDomainsOrRefusal, Rn as operationManifest, Rt as FOCUS_SERVER_SUPPORT, S as terminalApprovalIo, Sn as resolveCliApiRequestConfig, St as sendOutcomeExitCode, T as formatBrowserLoginInstructions, Tn as RESTRICTED_ROLE_NOTE, Tt as serializeErrorPayload, U as clearConsumedPendingMail, Ut as focusFlags, V as wakeRelationship, Vt as focusEmptyHint, W as clearReadPendingMail, Wt as focusForCorpus, X as interactionNextActions, Xt as oneDomainAtATimeError, Y as interactionHumanLine, Yt as normalizeDomainNames, Z as readEmailInteraction, Zt as queryScopesItself, _ as BROWSER_FLAG_DESCRIPTION, _t as formatSendRecordFailureSummary, a as createOperationCommand, an as withFlagSuggestion, at as assertValidIdempotencyKey, b as approveThenRerunHint, bn as refreshStoredCliCredentials, bt as sendErrorMessage, c as formatErrorPayload, cn as readCallerMailFor, ct as checkPriorReplies, d as networkErrorHint, dn as fetchBoundedPages, dt as excludeSignalReplies, en as resolveFocus, f as readTextFileFlag, fn as withBooleanFlagValues, ft as followUpCommandPrefix, g as writeErrorWithHints, gn as ConnectedAgentKeyRequiredError, gt as formatSendFailureSummary, h as surfaceUnauthorizedHint, hn as withAttachmentWait, ht as formatPriorRepliesWarning, i as TIME_FLAG_DESCRIPTION, in as writeFocusLine, it as apiResultHttpStatus, j as displayAddress, jn as roleKeyLabel, k as bareAddress, kn as isBuiltInRoleKey, kt as cliInvocation, l as hasControlCharacter$1, ln as formatFact, lt as classifySendError, m as runWithTiming, mn as ATTACHMENT_WAIT_MAX_MS, mt as formatPriorRepliesCheckSkipped, n as API_ERROR_CODES, nn as withFocusMeta, nt as MAX_SEND_WAIT_TIMEOUT_MS, o as extractErrorCode, on as emptyEmailListHint, ot as buildFollowUpCommand, p as refusesCredential, pn as ATTACHMENT_WAIT_FLAG_DESCRIPTION, pt as formatDeletedEarlierSendNotice, q as recordPendingMail, qt as loadSavedFocus, r as PAGED_LIMIT_MAX, rn as withoutFocus, rt as SEND_OUTCOME_HELP, s as extractErrorPayload, sn as mailReach, st as buildThrownSendFailureEnvelope, t as API_BASE_URL_FLAG_DESCRIPTION, tn as saveFocus, tt as IDEMPOTENCY_KEY_FLAG_DESCRIPTION, u as isGrantRefusal, un as isEmailId, ut as deriveSendIdempotencyKey, v as STEP_UP_HEADER$1, vn as createAuthenticatedCliApiClient, vt as priorRepliesThatWentOut, w as canOfferCopyHotkey, wn as CliOrgRefusedError, wt as sentHistoryWindowStart, x as promptLine$2, xn as refuseOrgSelectionForProfile, xt as sendIdentityFields, y as STEP_UP_TOKEN_FLAG_DESCRIPTION, yn as createCliApiClient, yt as reportSendCommandResult, z as wakeReadCommand, zt as NO_FOCUS } from "../api-command-CP8ir5Pv.js";
2
2
  import { a as canonicalCommandId, c as operationCommandId, i as canonicalCliText, l as retiredCommandTarget, n as COMMAND_RENAMES, o as canonicalCommands, s as canonicalOperation, t as COMMAND_PAIR_RENAMES } from "../cli-command-names-DteMqL-H.js";
3
3
  import { ignoreArgumentStdin } from "./command-stdin.js";
4
4
  import { a as runStreamingJson, i as jsonOutputRequested, n as captureOutput, o as thrownErrorBody, r as guardJsonOutputCommands, t as JSON_OUTPUT_FLAG } from "../json-output-BMZrLH47.js";
5
5
  import { $ as AUTOMATED_VALUES, $n as stopRepeatFromEmail, $t as getThread, A as collectNewAcceptedEmails, At as downloadSentAttachmentArchiveMember, B as REPLY_STATE_UNSUPPORTED_CODE, Bn as runWakeSchedule, Cn as listSentAttachmentArchiveMembers, Ct as deleteMemory, D as transientFailure, Dn as listWakeSchedules, Dt as downloadEmailAttachmentArchiveMember, E as retryingOperation, En as listWakeDispatches, Et as deleteWakeSchedule, F as lateMailReread, Fn as reorderRoutes, G as formatAwaitingCell, Gn as sendEmail, Gt as getKey, H as assertAwaitingFilterRows, Hn as searchEmails, Ht as getFunctionRouting, I as sinceFromFlags, In as replyToEmail, It as getConversation, J as isAwaitingRejectedError, Jn as setMemory, Jt as getOutboundStatus, K as formatRepliesCell, Kn as setFunctionRoute, Kt as getMemory, L as sleep$3, Ln as resendAgentSignupVerification, Lt as getCreditBalance, M as encodeReceivedAtSearchCursor, Mt as getAccessMode, N as fetchEmailSearchPage, Nn as redeemCreditCode, Nt as getAccount, O as waitOutRetryAfter, On as pollCliLogin, Ot as downloadEmailAttachmentByFilename, P as filtersFromFlags, Pn as removeDefaultNetworkMember, Pt as getAgentContactPolicy, Q as AUTOMATED_FLAG_DESCRIPTION, Qn as startCliLogin, Qt as getSentEmail, R as AWAITING_FLAG_DESCRIPTION, Rn as revokeCredential, Rt as getDefaultNetworkAgent, S as describeApiFailure, Sn as listRoutes, T as retryTransient, Tn as listWakeAuthorizations, Tt as deleteWakeAuthorization, U as awaitingRejectedError, Un as searchMemories, Ut as getFunctionTestRunTrace, V as ReplyStateUnsupportedError, Vt as getFunction, W as ensureSearchReportsReplyState, Wn as semanticSearch, Wt as getInboxStatus, Xn as startAgentClaim, Xt as getRepeatingSend, Y as queryUsesAwaiting, Yn as simulateRoute, Yt as getOwnGrant, Z as AUTOMATED_FILTER_UNSUPPORTED_CODE, Zn as startAgentSignup, Zt as getSendFrom, _n as listKeys, _t as createKey, a as REPEAT_IDLE_MAX_MINUTES, an as listAgentContacts, ar as updateRepeatingSend, b as WaitDeadlineReached, bn as listRepeatingSends, bt as createWakeSchedule, cn as listDefaultNetworkAgents, cr as updateWakeSchedule, ct as addDefaultNetworkMember, d as parseRepeatTick, dn as listEmailAttachmentArchiveMembers, dr as whoami, dt as checkDefaultNetworkContactAdmission, en as getWakeSchedule, er as testFunction, et as AutomatedFilterUnsupportedError, f as preparePresenceAliveEmail, fn as listEmails, ft as checkSendability, g as isEmailReceivedEvent, gn as listGroups, gt as createFunction, hn as listFunctions, ht as createEndpoint, i as REPEAT_EVERY_MAX_MINUTES, ir as updateKey, j as cursorFromAcceptedRows, jt as downloadSentAttachmentByFilename, k as SINCE_VALUE_HELP, kn as pullWebhookEvent, l as parseInteractionEnvelope, ln as listDefaultNetworkMembers, lr as verifyAgentClaim, lt as cancelSentEmail, m as repeatStopCommand, mn as listFunctionLogs, mt as completeWebhookEvent, nn as leaveOrganization, nr as updateDefaultNetworkMember, nt as automatedRejectedError, o as REPEAT_MAX_SENDS_MAX, on as listAgentNetworks, or as updateRoute, ot as hasAutomatedVerdict, p as prepareSignalEmail, pn as listEndpoints, pt as cliLogout, q as hasReplyState, qn as setFunctionSecret, qt as getOrgRoutingTopology, rn as listActivityObjects, rr as updateFunction, s as buildRepeatStopBody, sr as updateWakeAuthorization, st as isAutomatedRejectedError, tr as unsetFunctionRoute, tt as assertAutomatedVerdict, u as parsePresenceEnvelope, un as listDomains, ur as verifyAgentSignup, ut as cancelSentEmailByIdempotencyKey, v as parseWebhookEvent, vn as listMailboxAccess, vt as createRoute, w as pauseForTransientFailure, wn as listSentEmails, wt as deleteRoute, x as backoffDelay, xn as listRoles, y as parseFromHeader, yn as listOrganizationPeople, yt as createWakeAuthorization, z as AWAITING_VALUES, zn as rotateKey, zt as getEmail } from "../repeats-Dj_o6c-X-x61TNLz-.js";
6
- import { C as readBundledConnectSkill, S as installedVersion, _ as NotificationOutcomeUnknownError, a as NotificationRetryError, b as installSkill, c as readConversationStatusContent, d as SESSION_UUID$1, g as NativeSessionNotLoadedError, h as NativeSessionError, i as notificationReceiptPage, l as createListenHandler, m as NativeSessionDisconnectedError, n as notificationSenders, o as isRoutineNotificationContent, p as defaultSessionSocket, r as openSessionNotifications, s as notificationPartReader, t as notificationScope, u as readableDelivery, v as bundledSkillNames, w as readBundledSkill, x as installedConnectSkillFile, y as connectSkillTarget } from "../notify-session-DHQbjXOq.js";
7
- import { A as AGENT_ADDRESS_ENV, C as saveCliCredentials, D as loadActiveChatState, E as deleteChatState, F as agentProfilesDirectory, H as requireDefaultLoginProfile, M as AgentConnectionSetupError, N as agentProfileDirectory, O as loadChatConversationByLocalId, P as agentProfileName, R as loadConnectedAgentProfile, S as resolveCliAuth, T as chatStatePath, W as PrimitiveApiClient, _ as deleteCliCredentials, a as normalizeCliEnvironmentName, b as loadCliCredentials, c as resolveConfigEnvironment, g as credentialsPath, h as credentialsLockPath, i as loadCliConfig, j as AGENT_PROFILE_ENV, k as saveActiveChatState, 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 saveSignupCredentials, y as detectPrimitiveKeyEnvMisname } from "../cli-config-Ms_0vNjq.js";
6
+ import { C as readBundledConnectSkill, S as installedVersion, _ as NotificationOutcomeUnknownError, a as NotificationRetryError, b as installSkill, c as readConversationStatusContent, d as SESSION_UUID$1, g as NativeSessionNotLoadedError, h as NativeSessionError, i as notificationReceiptPage, l as createListenHandler, m as NativeSessionDisconnectedError, n as notificationSenders, o as isRoutineNotificationContent, p as defaultSessionSocket, r as openSessionNotifications, s as notificationPartReader, t as notificationScope, u as readableDelivery, v as bundledSkillNames, w as readBundledSkill, x as installedConnectSkillFile, y as connectSkillTarget } from "../notify-session-Dx54UpkT.js";
7
+ import { $ as loadCachedAgentPassByToken, A as saveActiveChatState, C as resolveCliAuth, D as deleteChatState, E as chatStatePath, F as agentProfileName, G as AGENT_PASS_PROFILE_ENV, I as agentProfilesDirectory, J as agentPassTokenSha256, K as AgentPassAuthError, M as AGENT_PROFILE_ENV, N as AgentConnectionSetupError, O as loadActiveChatState, P as agentProfileDirectory, T as saveSignupCredentials, U as requireDefaultLoginProfile, X as deleteAgentPass, Y as claimAccessPassRemote, Z as isAgentPassExpired, _ as credentialsPath, a as normalizeCliEnvironmentName, at as detectAgentRuntime, b as detectPrimitiveKeyEnvMisname, c as removeCliEnvironment, ct as PrimitiveApiClient, d as upsertCliEnvironment, et as parseAccessPassInput, g as credentialsLockPath, h as cliAccessTokenExpiresAt, i as loadCliConfig, it as saveAgentPass, j as AGENT_ADDRESS_ENV, k as loadChatConversationByLocalId, l as resolveConfigEnvironment, m as acquireCliCredentialsLock, n as deleteCliConfig, nt as resolveAgentPassSlot, o as parseHeaderAssignment, ot as detectRuntimeSession, q as agentPassMetadata, r as emptyCliConfig, rt as revokeAccessPassRemote, s as redactCliEnvironment, st as runtimeSessionVariableList, tt as readAgentPassFile, u as saveCliConfig, v as deleteCliCredentials, w as saveCliCredentials, x as loadCliCredentials, y as deleteCliCredentialsLock, z as loadConnectedAgentProfile } from "../cli-config-DUQEYQ42.js";
8
8
  import { C as resolveListenSubscription, S as normalizeListenOrigin, _ 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, y as listenIdentity } from "../shared-mail-files-BAQSGxxz.js";
9
- import { $ as saveConnectionName, A as ContactPolicyReadRetryError, B as AddressNotesApiError, C as RECEIVER_MODES, Ct as upsertManagedBlock, D as registrationSummary, Dt as refreshOwnerMemberAddressPeriodically, E as failedSessionRegistration, Et as addSessionReceiver, F as canonicalContactSelector, G as contactAgentAddress, H as runAddressNotesRequest, I as AgentDisconnectError, J as agentInvitationHash, K as runContactRequest, L as claimOverRevokedSetup, M as NetworkAdmissionPendingError, N as createNotificationContactPolicy, O as registrationSummaryLine, Ot as withOwnerMemberAddress, P as evaluateContactPolicy, Q as refusalAfterReplacement, R as clearRevokedAddresses, S as runAgentConnect, St as readManagedFile, T as verificationReplySubmitted, Tt as readHookLauncherWarning, U as ContactsApiError, V as addressNoteTarget, W as contactAddress, X as readAgentInvitation, Y as connectAgent, Z as receiverStatusCommand, _ as enrollmentResumes, _t as samePath, a as endSession, at as boundSessionProfiles, b as invitationProfileName, bt as inspectManagedBlock, c as pendingSessionDisconnects, ct as describeSessionHookChange, d as registerSession, dt as ephemeralCliReason, et as savedReceiver, f as retryPendingDisconnects, ft as findOnPath, g as enrollAgent, gt as repairClaudeHooks, h as staleSessionAgents, ht as readClaudeSettings, i as connectedProfilesForSession, it as recordHookMailCheck, j as NETWORK_ADMISSION_PENDING_RETRY_MS, k as waitForRegistrations, l as psProcessInfo, lt as describeSessionHookItem, m as runDetached, mt as inspectClaudeHooks, n as OMP_MAIN, nt as releaseRegistrationsForProfile, o as headlessClaudeRun, ot as claudeConfigDir, p as revokeStaleSessionAgents, pt as hasMachineSessionHooks, q as agentConnectionStatus, r as agentConnectionState, rt as installClaudeWakeHook, st as currentCliLocation, t as HOOK_END_GRACE_MS, tt as MACHINE_RUNTIMES, u as readClaudeHookInput, ut as ensureHookLauncher, v as connectWarnings, vt as writeClaudeSettings, w as externalReceivingState, wt as writeManagedFile, x as pollCheckCommand, xt as jsonIndentation, y as defaultAgentProfileName, yt as MachineFileError, z as disconnectAgent } from "../machine-session-DPLiLNot.js";
9
+ import { $ as saveConnectionName, A as ContactPolicyReadRetryError, B as AddressNotesApiError, C as RECEIVER_MODES, Ct as upsertManagedBlock, D as registrationSummary, Dt as refreshOwnerMemberAddressPeriodically, E as failedSessionRegistration, Et as addSessionReceiver, F as canonicalContactSelector, G as contactAgentAddress, H as runAddressNotesRequest, I as AgentDisconnectError, J as agentInvitationHash, K as runContactRequest, L as claimOverRevokedSetup, M as NetworkAdmissionPendingError, N as createNotificationContactPolicy, O as registrationSummaryLine, Ot as withOwnerMemberAddress, P as evaluateContactPolicy, Q as refusalAfterReplacement, R as clearRevokedAddresses, S as runAgentConnect, St as readManagedFile, T as verificationReplySubmitted, Tt as readHookLauncherWarning, U as ContactsApiError, V as addressNoteTarget, W as contactAddress, X as readAgentInvitation, Y as connectAgent, Z as receiverStatusCommand, _ as enrollmentResumes, _t as samePath, a as endSession, at as boundSessionProfiles, b as invitationProfileName, bt as inspectManagedBlock, c as pendingSessionDisconnects, ct as describeSessionHookChange, d as registerSession, dt as ephemeralCliReason, et as savedReceiver, f as retryPendingDisconnects, ft as findOnPath, g as enrollAgent, gt as repairClaudeHooks, h as staleSessionAgents, ht as readClaudeSettings, i as connectedProfilesForSession, it as recordHookMailCheck, j as NETWORK_ADMISSION_PENDING_RETRY_MS, k as waitForRegistrations, l as psProcessInfo, lt as describeSessionHookItem, m as runDetached, mt as inspectClaudeHooks, n as OMP_MAIN, nt as releaseRegistrationsForProfile, o as headlessClaudeRun, ot as claudeConfigDir, p as revokeStaleSessionAgents, pt as hasMachineSessionHooks, q as agentConnectionStatus, r as agentConnectionState, rt as installClaudeWakeHook, st as currentCliLocation, t as HOOK_END_GRACE_MS, tt as MACHINE_RUNTIMES, u as readClaudeHookInput, ut as ensureHookLauncher, v as connectWarnings, vt as writeClaudeSettings, w as externalReceivingState, wt as writeManagedFile, x as pollCheckCommand, xt as jsonIndentation, y as defaultAgentProfileName, yt as MachineFileError, z as disconnectAgent } from "../machine-session-CE31cwx2.js";
10
10
  import { a as readBeforeDeadline, c as readPresenceProjection, i as readApiBeforeDeadline, n as isPlainChatReply, o as scopedChatSenderTrust, r as isScopedChatReply, s as presenceDisposition, t as isConnectedChatCredential } from "../scoped-chat-Bss3OjFI.js";
11
11
  import { autoSignalEligible, dispatchAutoRead, dispatchAutoWorking, haltAutoWorking, isSentSignal, readWorkingLease, restoreAutoWorking } from "./auto-signals.js";
12
- import { _ as EventConnection, a as ensureSharedMailSubscription, d as createSharedMailWaiter, f as openSharedMailStore, g as otherParticipants, h as readConversationFollow, i as sharedMailScope, l as KEY_REVOKED_MESSAGE, m as followEmailConversation, n as reconcileChatSend, p as reserveSharedMailSubscription, r as openSharedMailReceiver, s as AGENT_CONNECTION_REQUIRED_MESSAGE, t as sendSignal, u as isConnectedAgentKey, v as EventReceiverError } from "../signal-command-vIo4maG0.js";
12
+ import { _ as EventConnection, a as ensureSharedMailSubscription, d as createSharedMailWaiter, f as openSharedMailStore, g as otherParticipants, h as readConversationFollow, i as sharedMailScope, l as KEY_REVOKED_MESSAGE, m as followEmailConversation, n as reconcileChatSend, p as reserveSharedMailSubscription, r as openSharedMailReceiver, s as AGENT_CONNECTION_REQUIRED_MESSAGE, t as sendSignal, u as isConnectedAgentKey, v as EventReceiverError } from "../signal-command-CA55RTJh.js";
13
13
  import { a as backgroundListenStatus, c as runBackgroundListen, d as stopBackgroundListen, f as verifyBackgroundListenTarget, o as backgroundListenToken, r as backgroundListenConfiguration, u as startBackgroundListen } from "../listen-background-DyBYca28.js";
14
14
  import { ORG_SELECTION_ENV } from "./global-org-flag.js";
15
15
  import { n as createConfig, t as createClient } from "../client.gen-6rZvmHfx.js";
@@ -3105,6 +3105,160 @@ function endedClaimText(claim) {
3105
3105
  const text = claim.trim();
3106
3106
  return text !== "" && !/[\r\n]/.test(text) && text.length <= 500 ? text : "cleared";
3107
3107
  }
3108
+ // src/oclif/commands/api.ts
3109
+ const ALLOWED_METHODS = /* @__PURE__ */ new Set([
3110
+ "GET",
3111
+ "POST",
3112
+ "PUT",
3113
+ "PATCH",
3114
+ "DELETE",
3115
+ "HEAD"
3116
+ ]);
3117
+ function normalizeApiPath(rawPath) {
3118
+ const trimmed = rawPath.trim();
3119
+ if (!trimmed) throw new Errors.CLIError("API path must not be empty.", { exit: 1 });
3120
+ if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed) || trimmed.startsWith("//")) throw new Errors.CLIError("Pass a relative API path like /emails or /drafts, not a full URL.", { exit: 1 });
3121
+ const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
3122
+ let relative = withSlash;
3123
+ if (/^\/v1(?:$|[/?#])/.test(withSlash)) {
3124
+ const rest = withSlash.slice(3);
3125
+ relative = rest === "" || rest.startsWith("?") || rest.startsWith("#") ? `/${rest}` : rest;
3126
+ }
3127
+ const pathOnly = relative.split(/[?#]/, 1)[0] ?? "";
3128
+ let decodedPath;
3129
+ try {
3130
+ decodedPath = decodeURIComponent(pathOnly);
3131
+ } catch {
3132
+ throw new Errors.CLIError("API path contains invalid percent-encoding.", { exit: 1 });
3133
+ }
3134
+ const segments = decodedPath.split("/");
3135
+ if (segments.includes("..") || segments.includes(".")) throw new Errors.CLIError("API path must not contain relative dot segments (. or ..).", { exit: 1 });
3136
+ const resolved = new URL(`/v1${relative}`, "https://primitive.invalid");
3137
+ if (resolved.origin !== "https://primitive.invalid" || resolved.pathname !== "/v1" && !resolved.pathname.startsWith("/v1/")) throw new Errors.CLIError("API path must stay within /v1.", { exit: 1 });
3138
+ return relative;
3139
+ }
3140
+ async function readDataPayload(raw) {
3141
+ if (raw === "@-") {
3142
+ const chunks = [];
3143
+ for await (const chunk of process.stdin) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
3144
+ return Buffer.concat(chunks).toString("utf8");
3145
+ }
3146
+ if (raw.startsWith("@")) {
3147
+ const filePath = raw.slice(1);
3148
+ try {
3149
+ return readFileSync(filePath, "utf8");
3150
+ } catch (error) {
3151
+ const detail = error instanceof Error ? error.message : String(error);
3152
+ throw new Errors.CLIError(`Could not read request body from ${filePath}: ${detail}`, { exit: 1 });
3153
+ }
3154
+ }
3155
+ return raw;
3156
+ }
3157
+ var ApiCommand = class ApiCommand extends Command {
3158
+ static summary = "Send an authenticated request to the Primitive REST API";
3159
+ static description = "Make an authenticated HTTP request against the Primitive v1 API using the active session Access Pass, PRIMITIVE_API_KEY, or saved OAuth login. Useful for exploring new or beta endpoints such as /drafts and /email-rules/:id/dry-run without manually passing bearer tokens.";
3160
+ static examples = [
3161
+ "<%= config.bin %> api GET /emails?limit=10",
3162
+ "<%= config.bin %> api GET /drafts",
3163
+ `<%= config.bin %> api POST /emails/11111111-1111-4111-8111-111111111111/drafts -d '{"body_text":"Thanks for sending this over."}'`
3164
+ ];
3165
+ static args = {
3166
+ method: Args.string({
3167
+ description: "HTTP method (GET, POST, PUT, PATCH, DELETE, HEAD)",
3168
+ required: true
3169
+ }),
3170
+ path: Args.string({
3171
+ description: "API path relative to /v1 (for example /emails, /drafts, or /v1/drafts)",
3172
+ required: true
3173
+ })
3174
+ };
3175
+ static flags = {
3176
+ data: Flags.string({
3177
+ char: "d",
3178
+ description: "Request body as a JSON string, @path/to/file.json, or @- to read from stdin"
3179
+ }),
3180
+ header: Flags.string({
3181
+ char: "H",
3182
+ description: "Additional request header as name=value (repeatable; Authorization is managed automatically)",
3183
+ multiple: true
3184
+ }),
3185
+ "api-key": Flags.string({
3186
+ description: "Override the Primitive API key for this request",
3187
+ env: "PRIMITIVE_API_KEY"
3188
+ }),
3189
+ "api-base-url": Flags.string({
3190
+ description: "Override the API base URL",
3191
+ env: "PRIMITIVE_API_BASE_URL",
3192
+ hidden: true
3193
+ }),
3194
+ include: Flags.boolean({
3195
+ char: "i",
3196
+ description: "Include HTTP status line before the response body"
3197
+ }),
3198
+ json: Flags.boolean({ description: "Ensure stdout contains valid JSON (wraps non-JSON responses when needed)" })
3199
+ };
3200
+ async run() {
3201
+ const { args, flags } = await this.parse(ApiCommand);
3202
+ const method = args.method.trim().toUpperCase();
3203
+ if (!ALLOWED_METHODS.has(method)) throw new Errors.CLIError(`Unsupported HTTP method "${args.method}". Use one of: ${[...ALLOWED_METHODS].join(", ")}.`, { exit: 1 });
3204
+ const path = normalizeApiPath(args.path);
3205
+ const authenticated = await createAuthenticatedCliApiClient({
3206
+ apiBaseUrl: flags["api-base-url"],
3207
+ apiKey: flags["api-key"],
3208
+ configDir: this.config.configDir
3209
+ });
3210
+ if (!authenticated.auth.apiKey) throw new Errors.CLIError("No Primitive credential is active. Connect with `primitive connect <url>`, set PRIMITIVE_API_KEY, or run `primitive signin`.", { exit: 1 });
3211
+ if (flags.data !== void 0 && (method === "GET" || method === "HEAD")) throw new Errors.CLIError(`Request body (-d/--data) cannot be used with HTTP ${method}.`, { exit: 1 });
3212
+ const headers = {
3213
+ accept: "application/json",
3214
+ ...authenticated.auth.agentPass || authenticated.auth.connectedAgent ? {} : authenticated.requestConfig.headers ?? {}
3215
+ };
3216
+ for (const rawHeader of flags.header ?? []) {
3217
+ const [name, value] = parseHeaderAssignment(rawHeader);
3218
+ const lower = name.toLowerCase();
3219
+ if (lower === "authorization") throw new Errors.CLIError("Authorization header is managed automatically and cannot be overridden with -H.", { exit: 1 });
3220
+ for (const existingKey of Object.keys(headers)) if (existingKey.toLowerCase() === lower) delete headers[existingKey];
3221
+ headers[name] = value;
3222
+ }
3223
+ for (const existingKey of Object.keys(headers)) if (existingKey.toLowerCase() === "authorization") delete headers[existingKey];
3224
+ headers.authorization = `Bearer ${authenticated.auth.apiKey}`;
3225
+ let body;
3226
+ if (flags.data !== void 0) {
3227
+ body = await readDataPayload(flags.data);
3228
+ if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) headers["content-type"] = "application/json";
3229
+ }
3230
+ const url = `${authenticated.auth.apiBaseUrl.replace(/\/+$/, "")}${path}`;
3231
+ let response;
3232
+ try {
3233
+ response = await fetch(url, {
3234
+ method,
3235
+ headers,
3236
+ ...body !== void 0 ? { body } : {}
3237
+ });
3238
+ } catch (error) {
3239
+ const detail = error instanceof Error ? error.message : String(error);
3240
+ throw new Errors.CLIError(`API request failed: ${detail}`, { exit: 1 });
3241
+ }
3242
+ const rawBody = method === "HEAD" ? "" : await response.text();
3243
+ let parsedJson;
3244
+ let isJson = false;
3245
+ if (rawBody.trim().length > 0) try {
3246
+ parsedJson = JSON.parse(rawBody);
3247
+ isJson = true;
3248
+ } catch {
3249
+ isJson = false;
3250
+ }
3251
+ if (flags.include && !flags.json) this.log(`HTTP ${response.status} ${response.statusText}`.trim());
3252
+ if (isJson) this.log(JSON.stringify(parsedJson, null, 2));
3253
+ else if (flags.json) this.log(JSON.stringify({
3254
+ status: response.status,
3255
+ body: rawBody
3256
+ }));
3257
+ else if (rawBody.length > 0) process.stdout.write(rawBody.endsWith("\n") ? rawBody : `${rawBody}\n`);
3258
+ else if (!response.ok && !flags.include) this.log(`HTTP ${response.status} ${response.statusText}`.trim());
3259
+ if (!response.ok) process.exitCode = 1;
3260
+ }
3261
+ };
3108
3262
  // src/oclif/commands/billing.ts
3109
3263
  const BILLING_PAGE_PATH = "/app/settings/billing";
3110
3264
  const BILLING_CLI_NOTE = "Reading and managing billing from the CLI will come in a future release.";
@@ -7061,6 +7215,146 @@ var ConfigCommand = class extends ConfigListCommand {
7061
7215
  static summary = "Manage Primitive CLI request environments";
7062
7216
  static description = "Manage local Primitive CLI request environments for API endpoint overrides and request headers.";
7063
7217
  };
7218
+ // src/oclif/commands/connect.ts
7219
+ async function readStdinText() {
7220
+ if (process.stdin.isTTY) return "";
7221
+ const chunks = [];
7222
+ for await (const chunk of process.stdin) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
7223
+ return Buffer.concat(chunks).toString("utf8");
7224
+ }
7225
+ function formatBinding(pass) {
7226
+ if (pass.binding.kind === "session") return `${pass.binding.runtime} session ${pass.binding.session}`;
7227
+ if (pass.binding.kind === "profile") return `profile ${pass.binding.profile} (select with ${AGENT_PASS_PROFILE_ENV}=${pass.binding.profile})`;
7228
+ return "default local pass binding";
7229
+ }
7230
+ var ConnectCommand = class ConnectCommand extends Command {
7231
+ static summary = "Claim a Primitive Access Pass for this agent session";
7232
+ static description = "Claim a presigned Primitive Access Pass URL or pit_v1_ token, save the scoped credential locally with 0600 permissions bound to the active coding session (or --profile), and print the pass guide and scope summary without ever printing the secret API key. Re-running with the same pass reuses the local claim cache idempotently.";
7233
+ static examples = [
7234
+ "<%= config.bin %> connect https://api.primitive.dev/v1/access/pit_v1_example",
7235
+ "echo 'https://api.primitive.dev/v1/access/pit_v1_example' | <%= config.bin %> connect --json",
7236
+ "<%= config.bin %> connect --profile invoices pit_v1_example"
7237
+ ];
7238
+ static args = { pass: Args.string({
7239
+ description: "Presigned Access Pass URL (https://.../v1/access/pit_v1_...) or pit_v1_ token. Omit to read from piped stdin.",
7240
+ required: false
7241
+ }) };
7242
+ static flags = {
7243
+ profile: Flags.string({ description: "Bind the claimed pass to a named local profile instead of auto-detecting the active session" }),
7244
+ "api-base-url": Flags.string({
7245
+ description: "Override the API base URL when claiming a bare pit_v1_ token",
7246
+ env: "PRIMITIVE_API_BASE_URL",
7247
+ hidden: true
7248
+ }),
7249
+ json: Flags.boolean({ description: "Print safe pass metadata, preview, and guide as JSON (never prints the API key)" })
7250
+ };
7251
+ async run() {
7252
+ const { args, flags } = await this.parse(ConnectCommand);
7253
+ try {
7254
+ const rawInput = args.pass ?? await readStdinText();
7255
+ const { token, apiBaseUrl } = parseAccessPassInput(rawInput, flags["api-base-url"]);
7256
+ const slot = resolveAgentPassSlot({
7257
+ configDir: this.config.configDir,
7258
+ profile: flags.profile
7259
+ });
7260
+ const revokeCommand = slot.binding.kind === "profile" ? `primitive disconnect --profile ${slot.binding.profile}` : "primitive disconnect";
7261
+ const tokenHash = agentPassTokenSha256(token);
7262
+ try {
7263
+ const existing = readAgentPassFile(slot.path);
7264
+ if (existing && !isAgentPassExpired(existing) && existing.token_sha256 !== tokenHash) process.stderr.write(`Warning: replacing active Access Pass "${existing.label}" in this slot without revoking it. Run \`${revokeCommand}\` before connecting if you want to revoke the previous pass.\n`);
7265
+ } catch {}
7266
+ const cached = loadCachedAgentPassByToken({
7267
+ configDir: this.config.configDir,
7268
+ token
7269
+ });
7270
+ if (cached) {
7271
+ const rebound = {
7272
+ ...cached,
7273
+ binding: slot.binding
7274
+ };
7275
+ saveAgentPass({
7276
+ configDir: this.config.configDir,
7277
+ pass: rebound,
7278
+ slotPath: slot.path
7279
+ });
7280
+ const meta = agentPassMetadata(rebound);
7281
+ if (flags.json) {
7282
+ this.log(JSON.stringify({
7283
+ status: "reused",
7284
+ pass: meta,
7285
+ revoke_command: revokeCommand
7286
+ }));
7287
+ return;
7288
+ }
7289
+ this.log(`Reused saved Access Pass "${meta.label}" (${meta.mode}).`);
7290
+ this.log(`Bound to: ${formatBinding(rebound)}`);
7291
+ this.log(`Expires at: ${meta.expires_at}`);
7292
+ if (meta.slice_summary) this.log(`Scope: ${meta.slice_summary}`);
7293
+ this.log(`Run \`${revokeCommand}\` when finished to revoke this pass.`);
7294
+ return;
7295
+ }
7296
+ const claimed = await claimAccessPassRemote({
7297
+ token,
7298
+ apiBaseUrl
7299
+ });
7300
+ const stored = {
7301
+ version: 1,
7302
+ auth_method: "agent_pass",
7303
+ api_key: claimed.api_key,
7304
+ api_base_url: claimed.api_base_url,
7305
+ pass_id: claimed.pass_id,
7306
+ key_id: claimed.key_id,
7307
+ label: claimed.label,
7308
+ mode: claimed.mode,
7309
+ ...claimed.purpose ? { purpose: claimed.purpose } : {},
7310
+ ...claimed.profile_hint ? { profile_hint: claimed.profile_hint } : {},
7311
+ ...claimed.mcp_url ? { mcp_url: claimed.mcp_url } : {},
7312
+ expires_at: claimed.expires_at,
7313
+ slice_summary: claimed.slice_summary,
7314
+ claimed_at: (/* @__PURE__ */ new Date()).toISOString(),
7315
+ revoked_at: null,
7316
+ token_sha256: tokenHash,
7317
+ binding: slot.binding
7318
+ };
7319
+ saveAgentPass({
7320
+ configDir: this.config.configDir,
7321
+ pass: stored,
7322
+ slotPath: slot.path
7323
+ });
7324
+ const meta = agentPassMetadata(stored);
7325
+ if (flags.json) {
7326
+ this.log(JSON.stringify({
7327
+ status: "connected",
7328
+ pass: meta,
7329
+ preview: claimed.preview,
7330
+ guide: claimed.guide,
7331
+ revoke_command: revokeCommand
7332
+ }));
7333
+ return;
7334
+ }
7335
+ this.log(`Connected with Access Pass "${meta.label}" (${meta.mode}).`);
7336
+ this.log(`Bound to: ${formatBinding(stored)}`);
7337
+ this.log(`Expires at: ${meta.expires_at}`);
7338
+ if (meta.slice_summary) this.log(`Scope: ${meta.slice_summary}`);
7339
+ if (typeof claimed.guide === "string" && claimed.guide.trim()) {
7340
+ this.log("");
7341
+ this.log(claimed.guide.trim());
7342
+ } else if (claimed.guide && typeof claimed.guide === "object") {
7343
+ this.log("");
7344
+ this.log(JSON.stringify(claimed.guide, null, 2));
7345
+ }
7346
+ if (claimed.preview) {
7347
+ this.log("");
7348
+ this.log(`Preview: ${JSON.stringify(claimed.preview)}`);
7349
+ }
7350
+ this.log("");
7351
+ this.log(`When finished, revoke this pass with: ${revokeCommand}`);
7352
+ } catch (error) {
7353
+ const message = error instanceof AgentPassAuthError || error instanceof Error ? error.message : String(error);
7354
+ throw new Errors.CLIError(message, { exit: 1 });
7355
+ }
7356
+ }
7357
+ };
7064
7358
  // src/oclif/commands/contact-request-shared.ts
7065
7359
  async function contactCommandContext(command, flags, purpose = "Contact requests") {
7066
7360
  const { apiClient, auth } = await createAuthenticatedCliApiClient({
@@ -7497,6 +7791,86 @@ var CreditsBalanceCommand = class CreditsBalanceCommand extends Command {
7497
7791
  });
7498
7792
  }
7499
7793
  };
7794
+ // src/oclif/commands/disconnect.ts
7795
+ var DisconnectCommand = class DisconnectCommand extends Command {
7796
+ static summary = "Revoke and clear the active Primitive Access Pass";
7797
+ static description = "Revoke the Access Pass bound to the current coding session (or --profile) via POST /v1/keys/me/revoke and remove its local 0600 credential file. Use --local-only to clear an expired or unreadable local binding without contacting the API.";
7798
+ static examples = [
7799
+ "<%= config.bin %> disconnect",
7800
+ "<%= config.bin %> disconnect --profile invoices",
7801
+ "<%= config.bin %> disconnect --local-only --json"
7802
+ ];
7803
+ static flags = {
7804
+ profile: Flags.string({ description: "Disconnect a named Access Pass profile" }),
7805
+ "local-only": Flags.boolean({ description: "Delete the local Access Pass file without calling POST /v1/keys/me/revoke" }),
7806
+ json: Flags.boolean({ description: "Print disconnect status as JSON" })
7807
+ };
7808
+ async run() {
7809
+ const { flags } = await this.parse(DisconnectCommand);
7810
+ try {
7811
+ const slot = resolveAgentPassSlot({
7812
+ configDir: this.config.configDir,
7813
+ profile: flags.profile
7814
+ });
7815
+ let stored = null;
7816
+ let unreadableSlot = false;
7817
+ try {
7818
+ stored = readAgentPassFile(slot.path);
7819
+ } catch (error) {
7820
+ if (!flags["local-only"]) {
7821
+ const detail = error instanceof Error ? error.message : String(error);
7822
+ throw new AgentPassAuthError(`Saved Access Pass could not be read for remote revocation (${detail}). Revoke it in the Primitive dashboard or re-run with --local-only to delete the local file.`);
7823
+ }
7824
+ unreadableSlot = existsSync(slot.path);
7825
+ }
7826
+ if (!stored && !unreadableSlot) {
7827
+ if (flags.json) {
7828
+ this.log(JSON.stringify({
7829
+ status: "not_connected",
7830
+ binding: slot.binding,
7831
+ revoked: false
7832
+ }));
7833
+ return;
7834
+ }
7835
+ this.log("No active Access Pass is bound to this session.");
7836
+ return;
7837
+ }
7838
+ let revoked = false;
7839
+ let alreadyRevoked = false;
7840
+ if (!flags["local-only"] && stored) {
7841
+ const result = await revokeAccessPassRemote({
7842
+ apiKey: stored.api_key,
7843
+ apiBaseUrl: stored.api_base_url
7844
+ });
7845
+ revoked = result.revoked;
7846
+ alreadyRevoked = result.alreadyRevoked;
7847
+ }
7848
+ deleteAgentPass({
7849
+ configDir: this.config.configDir,
7850
+ slotPath: slot.path,
7851
+ tokenSha256: stored?.token_sha256 || void 0
7852
+ });
7853
+ if (flags.json) {
7854
+ this.log(JSON.stringify({
7855
+ status: "disconnected",
7856
+ label: stored?.label ?? null,
7857
+ binding: slot.binding,
7858
+ revoked,
7859
+ already_revoked: alreadyRevoked,
7860
+ local_only: Boolean(flags["local-only"])
7861
+ }));
7862
+ return;
7863
+ }
7864
+ const name = stored?.label ? ` "${stored.label}"` : "";
7865
+ if (flags["local-only"]) this.log(`Cleared local Access Pass${name} binding without contacting Primitive.`);
7866
+ else if (alreadyRevoked) this.log(`Disconnected Access Pass${name} (key was already expired or revoked on Primitive).`);
7867
+ else this.log(`Revoked and disconnected Access Pass${name}.`);
7868
+ } catch (error) {
7869
+ const message = error instanceof AgentPassAuthError || error instanceof Error ? error.message : String(error);
7870
+ throw new Errors.CLIError(message, { exit: 1 });
7871
+ }
7872
+ }
7873
+ };
7500
7874
  // src/oclif/commands/doctor.ts
7501
7875
  const MIN_NODE_MAJOR = 22;
7502
7876
  function renderRow({ label, outcome }) {
@@ -7748,6 +8122,34 @@ function checkReceiverStart(configDir, profileName) {
7748
8122
  return null;
7749
8123
  }
7750
8124
  }
8125
+ async function checkAgentPassGrant(apiBaseUrl, apiKey) {
8126
+ try {
8127
+ const response = await fetch(`${apiBaseUrl.replace(/\/+$/, "")}/whoami/grant`, {
8128
+ method: "GET",
8129
+ headers: {
8130
+ authorization: `Bearer ${apiKey}`,
8131
+ accept: "application/json"
8132
+ }
8133
+ });
8134
+ const payload = await response.json().catch(() => null);
8135
+ if (!response.ok) return {
8136
+ status: "fail",
8137
+ message: `Access Pass rejected by API (${payload?.error && typeof payload.error === "object" ? JSON.stringify(payload.error).slice(0, 300) : `HTTP ${response.status}`})`,
8138
+ hint: "The Access Pass may have expired or been revoked. Run `primitive disconnect --local-only` and reconnect with a fresh pass."
8139
+ };
8140
+ const perms = Array.isArray(payload?.data?.permissions) ? payload.data.permissions.length : null;
8141
+ return {
8142
+ status: "ok",
8143
+ message: perms !== null ? `verified via /whoami/grant (${perms} permission${perms === 1 ? "" : "s"})` : "verified via /whoami/grant"
8144
+ };
8145
+ } catch (error) {
8146
+ return {
8147
+ status: "fail",
8148
+ message: `Could not reach /whoami/grant: ${error instanceof Error ? error.message : String(error)}`,
8149
+ hint: "Check network connectivity and proxy settings."
8150
+ };
8151
+ }
8152
+ }
7751
8153
  var DoctorCommand = class DoctorCommand extends Command {
7752
8154
  static description = `Run a one-shot environment health check: Node version, proxy env, CLI auth resolution, /account reachability, and verified-domain status. With PRIMITIVE_AGENT_PROFILE selected, reports saved identity offline and points to whoami and exact listener status instead of account-only checks. Prints actionable hints for each warning or failure.`;
7753
8155
  static summary = "Check the local environment and live API for common problems";
@@ -7775,15 +8177,30 @@ var DoctorCommand = class DoctorCommand extends Command {
7775
8177
  label: "Proxy env",
7776
8178
  outcome: checkProxy()
7777
8179
  });
7778
- const connected = process.env["PRIMITIVE_AGENT_PROFILE"]?.trim() ? resolveCliAuth({
7779
- apiKey: flags["api-key"],
7780
- apiBaseUrl: flags["api-base-url"],
7781
- configDir: this.config.configDir
7782
- }).connectedAgent : void 0;
7783
- const apiKeyCheck = connected ? {
8180
+ let resolvedAuth = null;
8181
+ let authError = null;
8182
+ try {
8183
+ resolvedAuth = resolveCliAuth({
8184
+ apiKey: flags["api-key"],
8185
+ apiBaseUrl: flags["api-base-url"],
8186
+ configDir: this.config.configDir
8187
+ });
8188
+ } catch (error) {
8189
+ if (error instanceof AgentPassAuthError) authError = error.message;
8190
+ else throw error;
8191
+ }
8192
+ const connected = resolvedAuth?.connectedAgent;
8193
+ const activePass = resolvedAuth?.agentPass;
8194
+ const apiKeyCheck = authError ? {
8195
+ status: "fail",
8196
+ message: authError
8197
+ } : connected ? {
7784
8198
  status: "warn",
7785
8199
  message: `Saved connected profile ${connected.profileName} for ${connected.agentAddress} (offline; live authentication and receiving not verified)`,
7786
8200
  hint: `Use \`${AGENT_PROFILE_ENV}=${connected.profileName} ${cliInvocation(process.argv[1])} whoami --json\` for saved identity and \`${receiverStatusCommand(this.config.configDir, connected.profileName).command}\` for this profile's receiver.`
8201
+ } : activePass ? {
8202
+ status: "ok",
8203
+ message: `Access Pass "${activePass.label}" (${activePass.mode}, expires ${activePass.expires_at})`
7787
8204
  } : checkApiKey({
7788
8205
  apiKey: flags["api-key"],
7789
8206
  configDir: this.config.configDir
@@ -7798,23 +8215,31 @@ var DoctorCommand = class DoctorCommand extends Command {
7798
8215
  outcome: receiverStart
7799
8216
  });
7800
8217
  if (!connected && apiKeyCheck.status !== "fail") {
7801
- const { apiClient, auth } = await createAuthenticatedCliApiClient({
7802
- apiKey: flags["api-key"],
7803
- apiBaseUrl: flags["api-base-url"],
7804
- configDir: this.config.configDir
7805
- });
7806
- if (auth.apiKey !== void 0) {
7807
- const accountCheck = await checkAccount(apiClient);
8218
+ if (activePass && resolvedAuth?.apiKey) {
8219
+ const grantOutcome = await checkAgentPassGrant(resolvedAuth.apiBaseUrl, resolvedAuth.apiKey);
7808
8220
  rows.push({
7809
8221
  label: "API auth",
7810
- outcome: accountCheck.outcome
8222
+ outcome: grantOutcome
7811
8223
  });
7812
- if (accountCheck.outcome.status === "ok") {
7813
- const domainsOutcome = await checkDomains(apiClient);
8224
+ } else {
8225
+ const { apiClient, auth } = await createAuthenticatedCliApiClient({
8226
+ apiKey: flags["api-key"],
8227
+ apiBaseUrl: flags["api-base-url"],
8228
+ configDir: this.config.configDir
8229
+ });
8230
+ if (auth.apiKey !== void 0) {
8231
+ const accountCheck = await checkAccount(apiClient);
7814
8232
  rows.push({
7815
- label: "Domains",
7816
- outcome: domainsOutcome
8233
+ label: "API auth",
8234
+ outcome: accountCheck.outcome
7817
8235
  });
8236
+ if (accountCheck.outcome.status === "ok") {
8237
+ const domainsOutcome = await checkDomains(apiClient);
8238
+ rows.push({
8239
+ label: "Domains",
8240
+ outcome: domainsOutcome
8241
+ });
8242
+ }
7818
8243
  }
7819
8244
  }
7820
8245
  }
@@ -11076,8 +11501,8 @@ const PRIMITIVE_TEAM_AUTHOR = {
11076
11501
  name: "Primitive Team",
11077
11502
  url: "https://primitive.dev"
11078
11503
  };
11079
- const SDK_VERSION_RANGE = "^3.0.0-preview.22";
11080
- const CLI_VERSION_RANGE = "^3.0.0-preview.22";
11504
+ const SDK_VERSION_RANGE = "^3.0.0-preview.23";
11505
+ const CLI_VERSION_RANGE = "^3.0.0-preview.23";
11081
11506
  const ESBUILD_VERSION_RANGE = "^0.27.0";
11082
11507
  function renderHandler() {
11083
11508
  return `// env.PRIMITIVE_API_KEY, env.PRIMITIVE_WEBHOOK_SECRET, and
@@ -14078,6 +14503,46 @@ var WhoamiCommand = class WhoamiCommand extends Command {
14078
14503
  }, null, 2) : `${identity.agentAddress}\nSelected by: ${selectedBy}. Prefix a command with \`PRIMITIVE_AGENT_PROFILE=\` to run it as the member login instead.\nSaved connected-agent profile: ${identity.profileName}\nAgent address: ${identity.agentAddress}\nOwner personal address (send reports here): ${identity.ownerMemberAddress ?? "unknown; reply to the member who wrote to you"}\nControl address (setup and presence only): ${identity.ownerAddress}\nAPI origin: ${identity.apiBaseUrl}\n${guidance}\nSaved profile status: ${statusCommand}`);
14079
14504
  return;
14080
14505
  }
14506
+ if (auth.agentPass) {
14507
+ const pass = auth.agentPass;
14508
+ let grant = null;
14509
+ const response = await fetch(`${auth.apiBaseUrl.replace(/\/+$/, "")}/whoami/grant`, {
14510
+ method: "GET",
14511
+ headers: {
14512
+ authorization: `Bearer ${auth.apiKey ?? ""}`,
14513
+ accept: "application/json"
14514
+ }
14515
+ });
14516
+ const payload = await response.json().catch(() => null);
14517
+ if (!response.ok) {
14518
+ const errorPayload = extractErrorPayload(payload ?? { message: `HTTP ${response.status}` });
14519
+ writeErrorWithHints(errorPayload);
14520
+ process.exitCode = 1;
14521
+ return;
14522
+ }
14523
+ grant = payload?.data ?? null;
14524
+ const revokeCommand = pass.binding.kind === "profile" ? `primitive disconnect --profile ${pass.binding.profile}` : "primitive disconnect";
14525
+ if (flags.json) {
14526
+ this.log(JSON.stringify({
14527
+ auth_method: "agent_pass",
14528
+ pass,
14529
+ grant,
14530
+ revoke_command: revokeCommand
14531
+ }, null, 2));
14532
+ return;
14533
+ }
14534
+ const perms = Array.isArray(grant?.permissions) ? grant.permissions.filter((p) => typeof p === "string") : [];
14535
+ const lines = [
14536
+ `Authenticated with Access Pass "${pass.label}" (${pass.mode})`,
14537
+ `Expires at: ${pass.expires_at}`,
14538
+ `API origin: ${auth.apiBaseUrl}`
14539
+ ];
14540
+ if (pass.slice_summary) lines.push(`Scope: ${pass.slice_summary}`);
14541
+ if (perms.length > 0) lines.push(`Permissions: ${perms.join(", ")}`);
14542
+ lines.push(`Disconnect and revoke: ${revokeCommand}`);
14543
+ this.log(lines.join("\n"));
14544
+ return;
14545
+ }
14081
14546
  if (isConnectedChatCredential(auth.apiKey)) throw new Errors.CLIError("This connection credential cannot inspect an account. Select its saved profile with PRIMITIVE_AGENT_PROFILE to inspect the connected identity offline.", { exit: 1 });
14082
14547
  if (flags.check !== void 0) {
14083
14548
  const check = flags.check.trim();
@@ -27157,6 +27622,9 @@ const rawCommands = {
27157
27622
  "org:secrets:list": OrgSecretsListCommand,
27158
27623
  "org:secrets:set": OrgSecretsSetCommand,
27159
27624
  "org:secrets:remove": OrgSecretsRemoveCommand,
27625
+ connect: ConnectCommand,
27626
+ disconnect: DisconnectCommand,
27627
+ api: ApiCommand,
27160
27628
  "payloads:push": PayloadsPushCommand,
27161
27629
  "payloads:pull": PayloadsPullCommand,
27162
27630
  "functions:test": FunctionsTestFunctionCommand,
@@ -1,7 +1,6 @@
1
- import { N as agentProfileDirectory, P as agentProfileName, R as loadConnectedAgentProfile, j as AGENT_PROFILE_ENV } from "../cli-config-Ms_0vNjq.js";
1
+ import { F as agentProfileName, M as AGENT_PROFILE_ENV, P as agentProfileDirectory, at as detectAgentRuntime, z as loadConnectedAgentProfile } from "../cli-config-DUQEYQ42.js";
2
2
  import { a as backgroundListenStatus, i as backgroundListenRestartable, s as claimBackgroundListenRestart, t as BACKGROUND_LISTEN_RELAUNCH_ENV } from "../listen-background-DyBYca28.js";
3
- import { d as SESSION_UUID, t as notificationScope } from "../notify-session-DHQbjXOq.js";
4
- import { It as detectAgentRuntime } from "../api-command-Dm1BKxOr.js";
3
+ import { d as SESSION_UUID, t as notificationScope } from "../notify-session-Dx54UpkT.js";
5
4
  import { d as readMailJson } from "../shared-mail-files-BAQSGxxz.js";
6
5
  import { join } from "node:path";
7
6
  import { spawn } from "node:child_process";
@@ -1,4 +1,4 @@
1
- import { c as resolveConfigEnvironment, i as loadCliConfig, x as normalizeApiBaseUrl } from "../cli-config-Ms_0vNjq.js";
1
+ import { S as normalizeApiBaseUrl, i as loadCliConfig, l as resolveConfigEnvironment } from "../cli-config-DUQEYQ42.js";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { homedir } from "node:os";