@primitivedotdev/cli 3.0.0-preview.22 → 3.0.0-preview.24

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-p-qsR7e6.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-DR1570cm.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-DiuUnquY.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-B7crrlba.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-7tV4fkDC.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,149 @@ 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
+ if (meta.manage_url) this.log(`Manage / extend / promote: ${meta.manage_url}`);
7294
+ this.log(`This pass expires automatically. Only run \`${revokeCommand}\` if explicitly asked to revoke access early.`);
7295
+ return;
7296
+ }
7297
+ const claimed = await claimAccessPassRemote({
7298
+ token,
7299
+ apiBaseUrl
7300
+ });
7301
+ const stored = {
7302
+ version: 1,
7303
+ auth_method: "agent_pass",
7304
+ api_key: claimed.api_key,
7305
+ api_base_url: claimed.api_base_url,
7306
+ pass_id: claimed.pass_id,
7307
+ key_id: claimed.key_id,
7308
+ label: claimed.label,
7309
+ mode: claimed.mode,
7310
+ ...claimed.purpose ? { purpose: claimed.purpose } : {},
7311
+ ...claimed.profile_hint ? { profile_hint: claimed.profile_hint } : {},
7312
+ ...claimed.mcp_url ? { mcp_url: claimed.mcp_url } : {},
7313
+ ...claimed.manage_url ? { manage_url: claimed.manage_url } : {},
7314
+ expires_at: claimed.expires_at,
7315
+ slice_summary: claimed.slice_summary,
7316
+ claimed_at: (/* @__PURE__ */ new Date()).toISOString(),
7317
+ revoked_at: null,
7318
+ token_sha256: tokenHash,
7319
+ binding: slot.binding
7320
+ };
7321
+ saveAgentPass({
7322
+ configDir: this.config.configDir,
7323
+ pass: stored,
7324
+ slotPath: slot.path
7325
+ });
7326
+ const meta = agentPassMetadata(stored);
7327
+ if (flags.json) {
7328
+ this.log(JSON.stringify({
7329
+ status: "connected",
7330
+ pass: meta,
7331
+ preview: claimed.preview,
7332
+ guide: claimed.guide,
7333
+ revoke_command: revokeCommand
7334
+ }));
7335
+ return;
7336
+ }
7337
+ this.log(`Connected with Access Pass "${meta.label}" (${meta.mode}).`);
7338
+ this.log(`Bound to: ${formatBinding(stored)}`);
7339
+ this.log(`Expires at: ${meta.expires_at}`);
7340
+ if (meta.slice_summary) this.log(`Scope: ${meta.slice_summary}`);
7341
+ if (meta.manage_url) this.log(`Manage / extend / promote: ${meta.manage_url}`);
7342
+ if (typeof claimed.guide === "string" && claimed.guide.trim()) {
7343
+ this.log("");
7344
+ this.log(claimed.guide.trim());
7345
+ } else if (claimed.guide && typeof claimed.guide === "object") {
7346
+ this.log("");
7347
+ this.log(JSON.stringify(claimed.guide, null, 2));
7348
+ }
7349
+ if (claimed.preview) {
7350
+ this.log("");
7351
+ this.log(`Preview: ${JSON.stringify(claimed.preview)}`);
7352
+ }
7353
+ this.log("");
7354
+ this.log(`This pass expires automatically. Do not auto-revoke after answering; only run \`${revokeCommand}\` if the user explicitly asks to end access.`);
7355
+ } catch (error) {
7356
+ const message = error instanceof AgentPassAuthError || error instanceof Error ? error.message : String(error);
7357
+ throw new Errors.CLIError(message, { exit: 1 });
7358
+ }
7359
+ }
7360
+ };
7064
7361
  // src/oclif/commands/contact-request-shared.ts
7065
7362
  async function contactCommandContext(command, flags, purpose = "Contact requests") {
7066
7363
  const { apiClient, auth } = await createAuthenticatedCliApiClient({
@@ -7497,6 +7794,86 @@ var CreditsBalanceCommand = class CreditsBalanceCommand extends Command {
7497
7794
  });
7498
7795
  }
7499
7796
  };
7797
+ // src/oclif/commands/disconnect.ts
7798
+ var DisconnectCommand = class DisconnectCommand extends Command {
7799
+ static summary = "Revoke and clear the active Primitive Access Pass";
7800
+ 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.";
7801
+ static examples = [
7802
+ "<%= config.bin %> disconnect",
7803
+ "<%= config.bin %> disconnect --profile invoices",
7804
+ "<%= config.bin %> disconnect --local-only --json"
7805
+ ];
7806
+ static flags = {
7807
+ profile: Flags.string({ description: "Disconnect a named Access Pass profile" }),
7808
+ "local-only": Flags.boolean({ description: "Delete the local Access Pass file without calling POST /v1/keys/me/revoke" }),
7809
+ json: Flags.boolean({ description: "Print disconnect status as JSON" })
7810
+ };
7811
+ async run() {
7812
+ const { flags } = await this.parse(DisconnectCommand);
7813
+ try {
7814
+ const slot = resolveAgentPassSlot({
7815
+ configDir: this.config.configDir,
7816
+ profile: flags.profile
7817
+ });
7818
+ let stored = null;
7819
+ let unreadableSlot = false;
7820
+ try {
7821
+ stored = readAgentPassFile(slot.path);
7822
+ } catch (error) {
7823
+ if (!flags["local-only"]) {
7824
+ const detail = error instanceof Error ? error.message : String(error);
7825
+ 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.`);
7826
+ }
7827
+ unreadableSlot = existsSync(slot.path);
7828
+ }
7829
+ if (!stored && !unreadableSlot) {
7830
+ if (flags.json) {
7831
+ this.log(JSON.stringify({
7832
+ status: "not_connected",
7833
+ binding: slot.binding,
7834
+ revoked: false
7835
+ }));
7836
+ return;
7837
+ }
7838
+ this.log("No active Access Pass is bound to this session.");
7839
+ return;
7840
+ }
7841
+ let revoked = false;
7842
+ let alreadyRevoked = false;
7843
+ if (!flags["local-only"] && stored) {
7844
+ const result = await revokeAccessPassRemote({
7845
+ apiKey: stored.api_key,
7846
+ apiBaseUrl: stored.api_base_url
7847
+ });
7848
+ revoked = result.revoked;
7849
+ alreadyRevoked = result.alreadyRevoked;
7850
+ }
7851
+ deleteAgentPass({
7852
+ configDir: this.config.configDir,
7853
+ slotPath: slot.path,
7854
+ tokenSha256: stored?.token_sha256 || void 0
7855
+ });
7856
+ if (flags.json) {
7857
+ this.log(JSON.stringify({
7858
+ status: "disconnected",
7859
+ label: stored?.label ?? null,
7860
+ binding: slot.binding,
7861
+ revoked,
7862
+ already_revoked: alreadyRevoked,
7863
+ local_only: Boolean(flags["local-only"])
7864
+ }));
7865
+ return;
7866
+ }
7867
+ const name = stored?.label ? ` "${stored.label}"` : "";
7868
+ if (flags["local-only"]) this.log(`Cleared local Access Pass${name} binding without contacting Primitive.`);
7869
+ else if (alreadyRevoked) this.log(`Disconnected Access Pass${name} (key was already expired or revoked on Primitive).`);
7870
+ else this.log(`Revoked and disconnected Access Pass${name}.`);
7871
+ } catch (error) {
7872
+ const message = error instanceof AgentPassAuthError || error instanceof Error ? error.message : String(error);
7873
+ throw new Errors.CLIError(message, { exit: 1 });
7874
+ }
7875
+ }
7876
+ };
7500
7877
  // src/oclif/commands/doctor.ts
7501
7878
  const MIN_NODE_MAJOR = 22;
7502
7879
  function renderRow({ label, outcome }) {
@@ -7748,6 +8125,34 @@ function checkReceiverStart(configDir, profileName) {
7748
8125
  return null;
7749
8126
  }
7750
8127
  }
8128
+ async function checkAgentPassGrant(apiBaseUrl, apiKey) {
8129
+ try {
8130
+ const response = await fetch(`${apiBaseUrl.replace(/\/+$/, "")}/whoami/grant`, {
8131
+ method: "GET",
8132
+ headers: {
8133
+ authorization: `Bearer ${apiKey}`,
8134
+ accept: "application/json"
8135
+ }
8136
+ });
8137
+ const payload = await response.json().catch(() => null);
8138
+ if (!response.ok) return {
8139
+ status: "fail",
8140
+ message: `Access Pass rejected by API (${payload?.error && typeof payload.error === "object" ? JSON.stringify(payload.error).slice(0, 300) : `HTTP ${response.status}`})`,
8141
+ hint: "The Access Pass may have expired or been revoked. Run `primitive disconnect --local-only` and reconnect with a fresh pass."
8142
+ };
8143
+ const perms = Array.isArray(payload?.data?.permissions) ? payload.data.permissions.length : null;
8144
+ return {
8145
+ status: "ok",
8146
+ message: perms !== null ? `verified via /whoami/grant (${perms} permission${perms === 1 ? "" : "s"})` : "verified via /whoami/grant"
8147
+ };
8148
+ } catch (error) {
8149
+ return {
8150
+ status: "fail",
8151
+ message: `Could not reach /whoami/grant: ${error instanceof Error ? error.message : String(error)}`,
8152
+ hint: "Check network connectivity and proxy settings."
8153
+ };
8154
+ }
8155
+ }
7751
8156
  var DoctorCommand = class DoctorCommand extends Command {
7752
8157
  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
8158
  static summary = "Check the local environment and live API for common problems";
@@ -7775,15 +8180,30 @@ var DoctorCommand = class DoctorCommand extends Command {
7775
8180
  label: "Proxy env",
7776
8181
  outcome: checkProxy()
7777
8182
  });
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 ? {
8183
+ let resolvedAuth = null;
8184
+ let authError = null;
8185
+ try {
8186
+ resolvedAuth = resolveCliAuth({
8187
+ apiKey: flags["api-key"],
8188
+ apiBaseUrl: flags["api-base-url"],
8189
+ configDir: this.config.configDir
8190
+ });
8191
+ } catch (error) {
8192
+ if (error instanceof AgentPassAuthError) authError = error.message;
8193
+ else throw error;
8194
+ }
8195
+ const connected = resolvedAuth?.connectedAgent;
8196
+ const activePass = resolvedAuth?.agentPass;
8197
+ const apiKeyCheck = authError ? {
8198
+ status: "fail",
8199
+ message: authError
8200
+ } : connected ? {
7784
8201
  status: "warn",
7785
8202
  message: `Saved connected profile ${connected.profileName} for ${connected.agentAddress} (offline; live authentication and receiving not verified)`,
7786
8203
  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.`
8204
+ } : activePass ? {
8205
+ status: "ok",
8206
+ message: `Access Pass "${activePass.label}" (${activePass.mode}, expires ${activePass.expires_at})`
7787
8207
  } : checkApiKey({
7788
8208
  apiKey: flags["api-key"],
7789
8209
  configDir: this.config.configDir
@@ -7798,23 +8218,31 @@ var DoctorCommand = class DoctorCommand extends Command {
7798
8218
  outcome: receiverStart
7799
8219
  });
7800
8220
  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);
8221
+ if (activePass && resolvedAuth?.apiKey) {
8222
+ const grantOutcome = await checkAgentPassGrant(resolvedAuth.apiBaseUrl, resolvedAuth.apiKey);
7808
8223
  rows.push({
7809
8224
  label: "API auth",
7810
- outcome: accountCheck.outcome
8225
+ outcome: grantOutcome
7811
8226
  });
7812
- if (accountCheck.outcome.status === "ok") {
7813
- const domainsOutcome = await checkDomains(apiClient);
8227
+ } else {
8228
+ const { apiClient, auth } = await createAuthenticatedCliApiClient({
8229
+ apiKey: flags["api-key"],
8230
+ apiBaseUrl: flags["api-base-url"],
8231
+ configDir: this.config.configDir
8232
+ });
8233
+ if (auth.apiKey !== void 0) {
8234
+ const accountCheck = await checkAccount(apiClient);
7814
8235
  rows.push({
7815
- label: "Domains",
7816
- outcome: domainsOutcome
8236
+ label: "API auth",
8237
+ outcome: accountCheck.outcome
7817
8238
  });
8239
+ if (accountCheck.outcome.status === "ok") {
8240
+ const domainsOutcome = await checkDomains(apiClient);
8241
+ rows.push({
8242
+ label: "Domains",
8243
+ outcome: domainsOutcome
8244
+ });
8245
+ }
7818
8246
  }
7819
8247
  }
7820
8248
  }
@@ -11076,8 +11504,8 @@ const PRIMITIVE_TEAM_AUTHOR = {
11076
11504
  name: "Primitive Team",
11077
11505
  url: "https://primitive.dev"
11078
11506
  };
11079
- const SDK_VERSION_RANGE = "^3.0.0-preview.22";
11080
- const CLI_VERSION_RANGE = "^3.0.0-preview.22";
11507
+ const SDK_VERSION_RANGE = "^3.0.0-preview.23";
11508
+ const CLI_VERSION_RANGE = "^3.0.0-preview.23";
11081
11509
  const ESBUILD_VERSION_RANGE = "^0.27.0";
11082
11510
  function renderHandler() {
11083
11511
  return `// env.PRIMITIVE_API_KEY, env.PRIMITIVE_WEBHOOK_SECRET, and
@@ -14078,6 +14506,46 @@ var WhoamiCommand = class WhoamiCommand extends Command {
14078
14506
  }, 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
14507
  return;
14080
14508
  }
14509
+ if (auth.agentPass) {
14510
+ const pass = auth.agentPass;
14511
+ let grant = null;
14512
+ const response = await fetch(`${auth.apiBaseUrl.replace(/\/+$/, "")}/whoami/grant`, {
14513
+ method: "GET",
14514
+ headers: {
14515
+ authorization: `Bearer ${auth.apiKey ?? ""}`,
14516
+ accept: "application/json"
14517
+ }
14518
+ });
14519
+ const payload = await response.json().catch(() => null);
14520
+ if (!response.ok) {
14521
+ const errorPayload = extractErrorPayload(payload ?? { message: `HTTP ${response.status}` });
14522
+ writeErrorWithHints(errorPayload);
14523
+ process.exitCode = 1;
14524
+ return;
14525
+ }
14526
+ grant = payload?.data ?? null;
14527
+ const revokeCommand = pass.binding.kind === "profile" ? `primitive disconnect --profile ${pass.binding.profile}` : "primitive disconnect";
14528
+ if (flags.json) {
14529
+ this.log(JSON.stringify({
14530
+ auth_method: "agent_pass",
14531
+ pass,
14532
+ grant,
14533
+ revoke_command: revokeCommand
14534
+ }, null, 2));
14535
+ return;
14536
+ }
14537
+ const perms = Array.isArray(grant?.permissions) ? grant.permissions.filter((p) => typeof p === "string") : [];
14538
+ const lines = [
14539
+ `Authenticated with Access Pass "${pass.label}" (${pass.mode})`,
14540
+ `Expires at: ${pass.expires_at}`,
14541
+ `API origin: ${auth.apiBaseUrl}`
14542
+ ];
14543
+ if (pass.slice_summary) lines.push(`Scope: ${pass.slice_summary}`);
14544
+ if (perms.length > 0) lines.push(`Permissions: ${perms.join(", ")}`);
14545
+ lines.push(`Disconnect and revoke: ${revokeCommand}`);
14546
+ this.log(lines.join("\n"));
14547
+ return;
14548
+ }
14081
14549
  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
14550
  if (flags.check !== void 0) {
14083
14551
  const check = flags.check.trim();
@@ -27157,6 +27625,9 @@ const rawCommands = {
27157
27625
  "org:secrets:list": OrgSecretsListCommand,
27158
27626
  "org:secrets:set": OrgSecretsSetCommand,
27159
27627
  "org:secrets:remove": OrgSecretsRemoveCommand,
27628
+ connect: ConnectCommand,
27629
+ disconnect: DisconnectCommand,
27630
+ api: ApiCommand,
27160
27631
  "payloads:push": PayloadsPushCommand,
27161
27632
  "payloads:pull": PayloadsPullCommand,
27162
27633
  "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-DiuUnquY.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-DR1570cm.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-DiuUnquY.js";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { homedir } from "node:os";