@primitivedotdev/cli 3.0.0-preview.24 → 3.0.0-preview.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{api-command-p-qsR7e6.js → api-command-B-nuABGm.js} +3012 -179
- package/dist/{cli-command-names-DteMqL-H.js → cli-command-names-no0f7d7s.js} +7 -1
- package/dist/{cli-config-DiuUnquY.js → cli-config-CwZJQIcn.js} +330 -24
- package/dist/{machine-session-B7crrlba.js → machine-session-1utuweTi.js} +5 -5
- package/dist/{notify-session-DR1570cm.js → notify-session-CM4_ZYe9.js} +3 -3
- package/dist/oclif/auto-signal-worker.js +3 -3
- package/dist/oclif/auto-signals.js +1 -1
- package/dist/oclif/command-not-found.js +1 -1
- package/dist/oclif/index.js +1824 -164
- package/dist/oclif/receiver-heal.js +2 -2
- package/dist/oclif/root-signup-hint.js +1 -1
- package/dist/{repeats-Dj_o6c-X-x61TNLz-.js → repeats-Dj_o6c-X-CK1wU9lP.js} +128 -0
- package/dist/{scoped-chat-Bss3OjFI.js → scoped-chat-DN0qj4AY.js} +1 -1
- package/dist/{signal-command-7tV4fkDC.js → signal-command-D4ZIidPX.js} +4 -4
- package/package.json +5 -2
package/dist/oclif/index.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import { $ as
|
|
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-
|
|
1
|
+
import { $ as replyExpectation, $t as readDomainsOrRefusal, A as bareAddress, An as fetchCliOrgs, At as cliInvocation, B as wakeReadCommand, Bn as operationManifest, Bt as NO_FOCUS, C as terminalApprovalIo, Cn as refuseOrgSelectionForProfile, Ct as sendOutcomeExitCode, D as listenForCopyHotkey, Dn as RESTRICTED_ROLE_NOTE, Dt as successfulSendOutcome, E as formatBrowserLoginInstructions, En as CliOrgRefusedError, Et as serializeErrorPayload, F as readThreadContext, Fn as switchCurrentOrg, Ft as loadSkillLine, G as clearReadPendingMail, Gn as validateActivityReason, Gt as focusForCorpus, H as wakeRelationship, Hn as PRIMITIVE_RUN_ID_HEADER, Ht as focusEmptyHint, I as sentInThread, In as routeWarningLines, It as currentMailSessionKey, J as recordPendingMail, Jt as loadSavedFocus, K as pendingMailPath, Kn as validateActivityRunId, Kt as focusProfile, L as serverMuted, Ln as sanitizeForTerminal, Lt as formatAlreadySentNotice, M as displayAddress, Mn as revokeUserLogin, N as formatMailWakeLine, Nn as roleKeyLabel, Nt as generatedAgentName, O as openBrowser, On as credentialsFromUserLogin, Ot as thrownErrorExitCode, P as latestOwnOutbound, Pn as roleKeyText, Pt as identitySuggestions, Q as readEmailInteraction, Qt as queryScopesItself, R as serverRelationship, Rn as shownLine, Rt as FOCUS_ENV, S as promptLine$2, Sn as refreshStoredCliCredentials, St as sendIdentityFields, T as canOfferCopyHotkey, Tn as selectedOrgFromEnv, Tt as sentHistoryWindowStart, U as claimPendingMail, Un as attachActivityContextFlags, Ut as focusFlagValues, V as wakeRecipientField, Vn as PRIMITIVE_REASON_HEADER, Vt as countFromMeta, W as clearConsumedPendingMail, Wn as cliActivityHeadersFromEnv, Wt as focusFlags, X as interactionHumanLine, Xt as normalizeDomainNames, Y as removePendingMail, Yt as manyDomainsSupported, Z as interactionNextActions, Zt as oneDomainAtATimeError, _ as writeErrorWithHints, _n as ConnectedAgentKeyRequiredError, _t as formatSendFailureSummary, a as agentPassErrorHint, an as writeFocusLine, at as apiResultHttpStatus, b as STEP_UP_TOKEN_FLAG_DESCRIPTION, bn as createCliApiClient, bt as reportSendCommandResult, c as extractErrorPayload, cn as mailReach, ct as buildThrownSendFailureEnvelope, d as isGrantRefusal, dn as isEmailId, dt as deriveSendIdempotencyKey, en as resolveDomainNames, et as replyInteractionWarning, f as networkErrorHint, fn as fetchBoundedPages, ft as excludeSignalReplies, g as surfaceUnauthorizedHint, gn as withAttachmentWait, gt as formatPriorRepliesWarning, h as runWithTiming, hn as ATTACHMENT_WAIT_MAX_MS, ht as formatPriorRepliesCheckSkipped, i as TIME_FLAG_DESCRIPTION, in as withoutFocus, it as SEND_OUTCOME_HELP, j as describeWake, jn as isBuiltInRoleKey, jt as connectNextSteps, k as explainPendingMailNotFound, kn as displayedRoleKey, l as formatErrorPayload, ln as readCallerMailFor, lt as checkPriorReplies, m as refusesCredential, mn as ATTACHMENT_WAIT_FLAG_DESCRIPTION, mt as formatDeletedEarlierSendNotice, n as API_ERROR_CODES, nn as saveFocus, nt as IDEMPOTENCY_KEY_FLAG_DESCRIPTION, o as createOperationCommand, on as withFlagSuggestion, ot as assertValidIdempotencyKey, p as readTextFileFlag, pn as withBooleanFlagValues, pt as followUpCommandPrefix, q as readPendingMail, qt as joinNames, r as PAGED_LIMIT_MAX, rn as withFocusMeta, rt as MAX_SEND_WAIT_TIMEOUT_MS, s as extractErrorCode, sn as emptyEmailListHint, st as buildFollowUpCommand, t as API_BASE_URL_FLAG_DESCRIPTION, tn as resolveFocus, u as hasControlCharacter$1, un as formatFact, ut as classifySendError, v as BROWSER_FLAG_DESCRIPTION, vt as formatSendRecordFailureSummary, w as withApproval, wn as resolveCliApiRequestConfig, wt as sendWaitClampNotice, x as approveThenRerunHint, xn as mergeHeadersCaseInsensitive, xt as sendErrorMessage, y as STEP_UP_HEADER$1, yn as createAuthenticatedCliApiClient, yt as priorRepliesThatWentOut, zn as setKnownCommands, zt as FOCUS_SERVER_SUPPORT } from "../api-command-B-nuABGm.js";
|
|
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-no0f7d7s.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
|
-
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-
|
|
6
|
-
import { C as
|
|
7
|
-
import { $ as
|
|
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-CK1wU9lP.js";
|
|
6
|
+
import { C as installedVersion, S as installedConnectSkillFile, T as readBundledSkill, _ as NotificationOutcomeUnknownError, a as NotificationRetryError, b as connectSkillTarget, 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 CONNECT_SKILL_NAME, w as readBundledConnectSkill, x as installSkill, y as bundledSkillNames } from "../notify-session-CM4_ZYe9.js";
|
|
7
|
+
import { $ as agentPassMetadata, A as removeCliLockState, B as agentProfileDirectory, D as CliAuthLockedError, E as saveSignupCredentials, F as loadChatConversationByLocalId, G as loadConnectedAgentProfile, H as agentProfilesDirectory, I as saveActiveChatState, L as AGENT_ADDRESS_ENV, M as chatStatePath, N as deleteChatState, O as parseUnlockDurationSeconds, P as loadActiveChatState, Q as AgentPassAuthError, R as AGENT_PROFILE_ENV, S as loadCliCredentials, T as saveCliCredentials, V as agentProfileName, Y as requireDefaultLoginProfile, Z as AGENT_PASS_PROFILE_ENV, _ as credentialsPath, a as normalizeCliEnvironmentName, at as parseAccessPassInput, b as detectPrimitiveKeyEnvMisname, c as removeCliEnvironment, ct as revokeAccessPassRemote, d as upsertCliEnvironment, dt as detectAgentRuntime, et as agentPassTokenSha256, ft as detectRuntimeSession, g as credentialsLockPath, h as cliAccessTokenExpiresAt, i as loadCliConfig, it as loadCachedAgentPassByToken, j as writeCliLockState, k as readCliLockState, l as resolveConfigEnvironment, lt as saveAgentPass, m as acquireCliCredentialsLock, mt as PrimitiveApiClient, n as deleteCliConfig, nt as deleteAgentPass, o as parseHeaderAssignment, ot as readAgentPassFile, pt as runtimeSessionVariableList, r as emptyCliConfig, s as redactCliEnvironment, st as resolveAgentPassSlot, tt as claimAccessPassRemote, u as saveCliConfig, ut as syncAgentPassMetadataFromGrant, v as deleteCliCredentials, w as resolveCliAuth, x as hasStoredCliLogin, y as deleteCliCredentialsLock, z as AgentConnectionSetupError } from "../cli-config-CwZJQIcn.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-
|
|
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-
|
|
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-1utuweTi.js";
|
|
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-DN0qj4AY.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-
|
|
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-D4ZIidPX.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";
|
|
16
16
|
import { Args, Command, Errors, Flags, ux } from "@oclif/core";
|
|
17
17
|
import { appendFileSync, chmodSync, closeSync, constants, cpSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
18
18
|
import { createHash, randomUUID, scryptSync } from "node:crypto";
|
|
19
|
-
import path, { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
19
|
+
import path, { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
20
20
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
21
21
|
import { createInterface } from "node:readline/promises";
|
|
22
22
|
import { homedir, hostname } from "node:os";
|
|
@@ -3106,6 +3106,23 @@ function endedClaimText(claim) {
|
|
|
3106
3106
|
return text !== "" && !/[\r\n]/.test(text) && text.length <= 500 ? text : "cleared";
|
|
3107
3107
|
}
|
|
3108
3108
|
// src/oclif/commands/api.ts
|
|
3109
|
+
function parseApiHeaderFlag(raw) {
|
|
3110
|
+
const colonIdx = raw.indexOf(":");
|
|
3111
|
+
const eqIdx = raw.indexOf("=");
|
|
3112
|
+
if (colonIdx > 0 && (eqIdx === -1 || colonIdx < eqIdx)) {
|
|
3113
|
+
const name = raw.slice(0, colonIdx).trim();
|
|
3114
|
+
const value = raw.slice(colonIdx + 1).trim();
|
|
3115
|
+
if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(name)) throw new Errors.CLIError(`Invalid header name "${name}" in -H "${raw}".`, { exit: 2 });
|
|
3116
|
+
return [name, value];
|
|
3117
|
+
}
|
|
3118
|
+
return parseHeaderAssignment(raw);
|
|
3119
|
+
}
|
|
3120
|
+
const BLOCKED_CUSTOM_HEADERS = /* @__PURE__ */ new Set([
|
|
3121
|
+
"authorization",
|
|
3122
|
+
"cookie",
|
|
3123
|
+
"host",
|
|
3124
|
+
"proxy-authorization"
|
|
3125
|
+
]);
|
|
3109
3126
|
const ALLOWED_METHODS = /* @__PURE__ */ new Set([
|
|
3110
3127
|
"GET",
|
|
3111
3128
|
"POST",
|
|
@@ -3182,6 +3199,14 @@ var ApiCommand = class ApiCommand extends Command {
|
|
|
3182
3199
|
description: "Additional request header as name=value (repeatable; Authorization is managed automatically)",
|
|
3183
3200
|
multiple: true
|
|
3184
3201
|
}),
|
|
3202
|
+
query: Flags.string({
|
|
3203
|
+
char: "q",
|
|
3204
|
+
description: "Query parameter as key=value (repeatable; safely URL-encoded)",
|
|
3205
|
+
multiple: true
|
|
3206
|
+
}),
|
|
3207
|
+
reason: Flags.string({ description: "Short explanation sent as X-Primitive-Reason (also reads PRIMITIVE_REASON)" }),
|
|
3208
|
+
"run-id": Flags.string({ description: "Correlation ID sent as X-Primitive-Run-Id (also reads PRIMITIVE_RUN_ID)" }),
|
|
3209
|
+
"idempotency-key": Flags.string({ description: "Idempotency-Key header for safe retries" }),
|
|
3185
3210
|
"api-key": Flags.string({
|
|
3186
3211
|
description: "Override the Primitive API key for this request",
|
|
3187
3212
|
env: "PRIMITIVE_API_KEY"
|
|
@@ -3209,14 +3234,20 @@ var ApiCommand = class ApiCommand extends Command {
|
|
|
3209
3234
|
});
|
|
3210
3235
|
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
3236
|
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
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3237
|
+
const envActivityHeaders = cliActivityHeadersFromEnv();
|
|
3238
|
+
const explicitFlagsHeaders = {};
|
|
3239
|
+
if (flags.reason !== void 0) explicitFlagsHeaders[PRIMITIVE_REASON_HEADER] = validateActivityReason(flags.reason, "--reason");
|
|
3240
|
+
if (flags["run-id"] !== void 0) explicitFlagsHeaders[PRIMITIVE_RUN_ID_HEADER] = validateActivityRunId(flags["run-id"], "--run-id");
|
|
3241
|
+
if (flags["idempotency-key"] !== void 0) {
|
|
3242
|
+
const key = flags["idempotency-key"].trim();
|
|
3243
|
+
if (!key || key.length > 255 || !/^[\x21-\x7e]+$/.test(key)) throw new Errors.CLIError("--idempotency-key must be 1 to 255 printable ASCII characters without spaces.", { exit: 2 });
|
|
3244
|
+
explicitFlagsHeaders["Idempotency-Key"] = key;
|
|
3245
|
+
}
|
|
3246
|
+
const headers = mergeHeadersCaseInsensitive({ accept: "application/json" }, authenticated.auth.agentPass || authenticated.auth.connectedAgent ? void 0 : authenticated.requestConfig.headers, envActivityHeaders, explicitFlagsHeaders) ?? {};
|
|
3216
3247
|
for (const rawHeader of flags.header ?? []) {
|
|
3217
|
-
const [name, value] =
|
|
3248
|
+
const [name, value] = parseApiHeaderFlag(rawHeader);
|
|
3218
3249
|
const lower = name.toLowerCase();
|
|
3219
|
-
if (lower
|
|
3250
|
+
if (BLOCKED_CUSTOM_HEADERS.has(lower)) throw new Errors.CLIError(`${name} header is managed automatically and cannot be overridden with -H.`, { exit: 1 });
|
|
3220
3251
|
for (const existingKey of Object.keys(headers)) if (existingKey.toLowerCase() === lower) delete headers[existingKey];
|
|
3221
3252
|
headers[name] = value;
|
|
3222
3253
|
}
|
|
@@ -3227,12 +3258,19 @@ var ApiCommand = class ApiCommand extends Command {
|
|
|
3227
3258
|
body = await readDataPayload(flags.data);
|
|
3228
3259
|
if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) headers["content-type"] = "application/json";
|
|
3229
3260
|
}
|
|
3230
|
-
const
|
|
3261
|
+
const requestUrl = new URL(`${authenticated.auth.apiBaseUrl.replace(/\/+$/, "")}${path}`);
|
|
3262
|
+
for (const rawQuery of flags.query ?? []) {
|
|
3263
|
+
const eqIdx = rawQuery.indexOf("=");
|
|
3264
|
+
if (eqIdx <= 0) throw new Errors.CLIError(`Invalid --query value "${rawQuery}". Expected key=value.`, { exit: 2 });
|
|
3265
|
+
requestUrl.searchParams.append(rawQuery.slice(0, eqIdx), rawQuery.slice(eqIdx + 1));
|
|
3266
|
+
}
|
|
3231
3267
|
let response;
|
|
3232
3268
|
try {
|
|
3233
|
-
response = await fetch(
|
|
3269
|
+
response = await authenticated.fetch(requestUrl.toString(), {
|
|
3234
3270
|
method,
|
|
3235
3271
|
headers,
|
|
3272
|
+
redirect: "manual",
|
|
3273
|
+
signal: AbortSignal.timeout(3e4),
|
|
3236
3274
|
...body !== void 0 ? { body } : {}
|
|
3237
3275
|
});
|
|
3238
3276
|
} catch (error) {
|
|
@@ -3256,7 +3294,15 @@ var ApiCommand = class ApiCommand extends Command {
|
|
|
3256
3294
|
}));
|
|
3257
3295
|
else if (rawBody.length > 0) process.stdout.write(rawBody.endsWith("\n") ? rawBody : `${rawBody}\n`);
|
|
3258
3296
|
else if (!response.ok && !flags.include) this.log(`HTTP ${response.status} ${response.statusText}`.trim());
|
|
3259
|
-
if (!response.ok)
|
|
3297
|
+
if (!response.ok) {
|
|
3298
|
+
if (!flags.json && authenticated.auth.source === "agent-pass" && authenticated.auth.agentPass && (response.status === 401 || response.status === 403)) {
|
|
3299
|
+
const errPayload = extractErrorPayload(parsedJson ?? { message: `HTTP ${response.status}` });
|
|
3300
|
+
const code = extractErrorCode(errPayload) ?? (response.status === 401 ? "unauthorized" : "grant_forbidden");
|
|
3301
|
+
const hint = agentPassErrorHint(authenticated.auth.agentPass, code);
|
|
3302
|
+
if (hint) process.stderr.write(`${hint}\n`);
|
|
3303
|
+
}
|
|
3304
|
+
process.exitCode = 1;
|
|
3305
|
+
}
|
|
3260
3306
|
}
|
|
3261
3307
|
};
|
|
3262
3308
|
// src/oclif/commands/billing.ts
|
|
@@ -7243,7 +7289,6 @@ var ConnectCommand = class ConnectCommand extends Command {
|
|
|
7243
7289
|
profile: Flags.string({ description: "Bind the claimed pass to a named local profile instead of auto-detecting the active session" }),
|
|
7244
7290
|
"api-base-url": Flags.string({
|
|
7245
7291
|
description: "Override the API base URL when claiming a bare pit_v1_ token",
|
|
7246
|
-
env: "PRIMITIVE_API_BASE_URL",
|
|
7247
7292
|
hidden: true
|
|
7248
7293
|
}),
|
|
7249
7294
|
json: Flags.boolean({ description: "Print safe pass metadata, preview, and guide as JSON (never prints the API key)" })
|
|
@@ -7252,7 +7297,9 @@ var ConnectCommand = class ConnectCommand extends Command {
|
|
|
7252
7297
|
const { args, flags } = await this.parse(ConnectCommand);
|
|
7253
7298
|
try {
|
|
7254
7299
|
const rawInput = args.pass ?? await readStdinText();
|
|
7255
|
-
const
|
|
7300
|
+
const hasExplicitUrl = /https?:\/\//i.test(rawInput);
|
|
7301
|
+
const effectiveBaseUrlOverride = flags["api-base-url"] ?? (hasExplicitUrl ? void 0 : process.env.PRIMITIVE_API_BASE_URL);
|
|
7302
|
+
const { token, apiBaseUrl } = parseAccessPassInput(rawInput, effectiveBaseUrlOverride);
|
|
7256
7303
|
const slot = resolveAgentPassSlot({
|
|
7257
7304
|
configDir: this.config.configDir,
|
|
7258
7305
|
profile: flags.profile
|
|
@@ -7261,8 +7308,9 @@ var ConnectCommand = class ConnectCommand extends Command {
|
|
|
7261
7308
|
const tokenHash = agentPassTokenSha256(token);
|
|
7262
7309
|
try {
|
|
7263
7310
|
const existing = readAgentPassFile(slot.path);
|
|
7264
|
-
if (existing && !
|
|
7311
|
+
if (existing && !existing.revoked_at && 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
7312
|
} catch {}
|
|
7313
|
+
if (slot.binding.kind === "default" && (hasStoredCliLogin(this.config.configDir) || Boolean(process.env.PRIMITIVE_API_KEY?.trim()))) process.stderr.write("Note: No agent session ID was detected, so this Access Pass is active as the default local binding and overrides your global CLI auth until cleared. Use `--profile <name>` to isolate it, or `primitive disconnect --local-only` when done.\n");
|
|
7266
7314
|
const cached = loadCachedAgentPassByToken({
|
|
7267
7315
|
configDir: this.config.configDir,
|
|
7268
7316
|
token
|
|
@@ -7824,9 +7872,15 @@ var DisconnectCommand = class DisconnectCommand extends Command {
|
|
|
7824
7872
|
const detail = error instanceof Error ? error.message : String(error);
|
|
7825
7873
|
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
7874
|
}
|
|
7827
|
-
|
|
7875
|
+
try {
|
|
7876
|
+
lstatSync(slot.path);
|
|
7877
|
+
unreadableSlot = true;
|
|
7878
|
+
} catch {
|
|
7879
|
+
unreadableSlot = false;
|
|
7880
|
+
}
|
|
7828
7881
|
}
|
|
7829
7882
|
if (!stored && !unreadableSlot) {
|
|
7883
|
+
const scopeHint = slot.binding.kind === "session" ? "this session" : slot.binding.kind === "profile" ? `profile "${slot.binding.profile}"` : "this machine";
|
|
7830
7884
|
if (flags.json) {
|
|
7831
7885
|
this.log(JSON.stringify({
|
|
7832
7886
|
status: "not_connected",
|
|
@@ -7835,7 +7889,7 @@ var DisconnectCommand = class DisconnectCommand extends Command {
|
|
|
7835
7889
|
}));
|
|
7836
7890
|
return;
|
|
7837
7891
|
}
|
|
7838
|
-
this.log(
|
|
7892
|
+
this.log(`No active Access Pass is bound to ${scopeHint}.`);
|
|
7839
7893
|
return;
|
|
7840
7894
|
}
|
|
7841
7895
|
let revoked = false;
|
|
@@ -8125,31 +8179,51 @@ function checkReceiverStart(configDir, profileName) {
|
|
|
8125
8179
|
return null;
|
|
8126
8180
|
}
|
|
8127
8181
|
}
|
|
8128
|
-
async function checkAgentPassGrant(
|
|
8182
|
+
async function checkAgentPassGrant(params) {
|
|
8183
|
+
const { apiBaseUrl, apiKey, configDir, pass } = params;
|
|
8184
|
+
const disconnectCmd = pass.binding.kind === "profile" ? `primitive disconnect --profile ${pass.binding.profile} --local-only` : "primitive disconnect --local-only";
|
|
8129
8185
|
try {
|
|
8130
8186
|
const response = await fetch(`${apiBaseUrl.replace(/\/+$/, "")}/whoami/grant`, {
|
|
8131
8187
|
method: "GET",
|
|
8132
8188
|
headers: {
|
|
8189
|
+
...cliActivityHeadersFromEnv(),
|
|
8133
8190
|
authorization: `Bearer ${apiKey}`,
|
|
8134
8191
|
accept: "application/json"
|
|
8135
8192
|
}
|
|
8136
8193
|
});
|
|
8137
8194
|
const payload = await response.json().catch(() => null);
|
|
8138
|
-
if (!response.ok)
|
|
8139
|
-
|
|
8140
|
-
|
|
8141
|
-
|
|
8142
|
-
|
|
8143
|
-
|
|
8195
|
+
if (!response.ok) {
|
|
8196
|
+
const detail = payload?.error && typeof payload.error === "object" ? JSON.stringify(payload.error).slice(0, 300) : `HTTP ${response.status}`;
|
|
8197
|
+
const extendHint = pass.manage_url ? ` Ask the owner to extend it at ${pass.manage_url}?action=extend&add=4h, or run \`${disconnectCmd}\` to clear the binding.` : ` Run \`${disconnectCmd}\` and reconnect with a fresh pass.`;
|
|
8198
|
+
return {
|
|
8199
|
+
syncedPass: pass,
|
|
8200
|
+
outcome: {
|
|
8201
|
+
status: "fail",
|
|
8202
|
+
message: `Access Pass rejected by API (${detail})`,
|
|
8203
|
+
hint: `The Access Pass may have expired or been revoked.${extendHint}`
|
|
8204
|
+
}
|
|
8205
|
+
};
|
|
8206
|
+
}
|
|
8207
|
+
const { pass: syncedPass, permissions } = syncAgentPassMetadataFromGrant({
|
|
8208
|
+
configDir,
|
|
8209
|
+
pass,
|
|
8210
|
+
grantData: payload?.data ?? null
|
|
8211
|
+
});
|
|
8144
8212
|
return {
|
|
8145
|
-
|
|
8146
|
-
|
|
8213
|
+
syncedPass,
|
|
8214
|
+
outcome: {
|
|
8215
|
+
status: "ok",
|
|
8216
|
+
message: permissions.length > 0 ? `verified via /whoami/grant (${permissions.length} permission${permissions.length === 1 ? "" : "s"})` : "verified via /whoami/grant"
|
|
8217
|
+
}
|
|
8147
8218
|
};
|
|
8148
8219
|
} catch (error) {
|
|
8149
8220
|
return {
|
|
8150
|
-
|
|
8151
|
-
|
|
8152
|
-
|
|
8221
|
+
syncedPass: pass,
|
|
8222
|
+
outcome: {
|
|
8223
|
+
status: "fail",
|
|
8224
|
+
message: `Could not reach /whoami/grant: ${error instanceof Error ? error.message : String(error)}`,
|
|
8225
|
+
hint: "Check network connectivity and proxy settings."
|
|
8226
|
+
}
|
|
8153
8227
|
};
|
|
8154
8228
|
}
|
|
8155
8229
|
}
|
|
@@ -8180,6 +8254,22 @@ var DoctorCommand = class DoctorCommand extends Command {
|
|
|
8180
8254
|
label: "Proxy env",
|
|
8181
8255
|
outcome: checkProxy()
|
|
8182
8256
|
});
|
|
8257
|
+
const lockState = readCliLockState(this.config.configDir);
|
|
8258
|
+
if (lockState.status === "locked") rows.push({
|
|
8259
|
+
label: "Global auth lock",
|
|
8260
|
+
outcome: {
|
|
8261
|
+
status: "ok",
|
|
8262
|
+
message: `Locked since ${lockState.lockedAt} (only Access Passes and connected profiles allowed; unlock with \`primitive unlock --for 15m\`)`
|
|
8263
|
+
}
|
|
8264
|
+
});
|
|
8265
|
+
else if (lockState.status === "temporarily_unlocked") rows.push({
|
|
8266
|
+
label: "Global auth lock",
|
|
8267
|
+
outcome: {
|
|
8268
|
+
status: "warn",
|
|
8269
|
+
message: `Temporarily unlocked until ${lockState.unlockedUntil} (auto-relocks)`,
|
|
8270
|
+
hint: "Run `primitive lock` to re-lock earlier."
|
|
8271
|
+
}
|
|
8272
|
+
});
|
|
8183
8273
|
let resolvedAuth = null;
|
|
8184
8274
|
let authError = null;
|
|
8185
8275
|
try {
|
|
@@ -8189,7 +8279,7 @@ var DoctorCommand = class DoctorCommand extends Command {
|
|
|
8189
8279
|
configDir: this.config.configDir
|
|
8190
8280
|
});
|
|
8191
8281
|
} catch (error) {
|
|
8192
|
-
if (error instanceof AgentPassAuthError) authError = error.message;
|
|
8282
|
+
if (error instanceof AgentPassAuthError || error instanceof CliAuthLockedError) authError = error.message;
|
|
8193
8283
|
else throw error;
|
|
8194
8284
|
}
|
|
8195
8285
|
const connected = resolvedAuth?.connectedAgent;
|
|
@@ -8219,7 +8309,17 @@ var DoctorCommand = class DoctorCommand extends Command {
|
|
|
8219
8309
|
});
|
|
8220
8310
|
if (!connected && apiKeyCheck.status !== "fail") {
|
|
8221
8311
|
if (activePass && resolvedAuth?.apiKey) {
|
|
8222
|
-
const grantOutcome = await checkAgentPassGrant(
|
|
8312
|
+
const { outcome: grantOutcome, syncedPass } = await checkAgentPassGrant({
|
|
8313
|
+
apiBaseUrl: resolvedAuth.apiBaseUrl,
|
|
8314
|
+
apiKey: resolvedAuth.apiKey,
|
|
8315
|
+
configDir: this.config.configDir,
|
|
8316
|
+
pass: activePass
|
|
8317
|
+
});
|
|
8318
|
+
const authRow = rows.find((r) => r.label === "Auth");
|
|
8319
|
+
if (authRow) authRow.outcome = {
|
|
8320
|
+
status: "ok",
|
|
8321
|
+
message: `Access Pass "${syncedPass.label}" (${syncedPass.mode}, expires ${syncedPass.expires_at})`
|
|
8322
|
+
};
|
|
8223
8323
|
rows.push({
|
|
8224
8324
|
label: "API auth",
|
|
8225
8325
|
outcome: grantOutcome
|
|
@@ -8374,10 +8474,7 @@ var DomainsZoneFileCommand = class DomainsZoneFileCommand extends Command {
|
|
|
8374
8474
|
if (!domainId) throw new Errors.CLIError("Could not resolve a domain id.", { exit: 1 });
|
|
8375
8475
|
let response;
|
|
8376
8476
|
try {
|
|
8377
|
-
response = await fetch(zoneFileUrl(requestConfig.resolvedApiBaseUrl, domainId, flags["outbound-only"], flags["inbound-only"]), { headers: {
|
|
8378
|
-
...requestConfig.headers ?? {},
|
|
8379
|
-
...auth.apiKey ? { authorization: `Bearer ${auth.apiKey}` } : {}
|
|
8380
|
-
} });
|
|
8477
|
+
response = await fetch(zoneFileUrl(requestConfig.resolvedApiBaseUrl, domainId, flags["outbound-only"], flags["inbound-only"]), { headers: mergeHeadersCaseInsensitive(requestConfig.headers, cliActivityHeadersFromEnv(), auth.apiKey ? { authorization: `Bearer ${auth.apiKey}` } : void 0) ?? {} });
|
|
8381
8478
|
} catch (error) {
|
|
8382
8479
|
writeErrorWithHints(error);
|
|
8383
8480
|
process.exitCode = 1;
|
|
@@ -8709,6 +8806,151 @@ function noUnderstandingMessage(understanding) {
|
|
|
8709
8806
|
function isRecord$1(value) {
|
|
8710
8807
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
8711
8808
|
}
|
|
8809
|
+
// src/oclif/activity-api.ts
|
|
8810
|
+
const ACTIVITY_KINDS = [
|
|
8811
|
+
"action",
|
|
8812
|
+
"note",
|
|
8813
|
+
"handoff"
|
|
8814
|
+
];
|
|
8815
|
+
const ACTIVITY_STATUSES = [
|
|
8816
|
+
"started",
|
|
8817
|
+
"succeeded",
|
|
8818
|
+
"failed",
|
|
8819
|
+
"skipped",
|
|
8820
|
+
"needs_review"
|
|
8821
|
+
];
|
|
8822
|
+
const ACTIVITY_VISIBILITIES = ["thread", "actor_only"];
|
|
8823
|
+
const ACTIVITY_OWNERSHIPS = [
|
|
8824
|
+
"human",
|
|
8825
|
+
"personal_agent",
|
|
8826
|
+
"org_key",
|
|
8827
|
+
"function",
|
|
8828
|
+
"app",
|
|
8829
|
+
"system"
|
|
8830
|
+
];
|
|
8831
|
+
const TIMELINE_SOURCES = [
|
|
8832
|
+
"all",
|
|
8833
|
+
"primitive",
|
|
8834
|
+
"agent"
|
|
8835
|
+
];
|
|
8836
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
8837
|
+
const ACTION_SLUG_RE = /^[a-z0-9][a-z0-9._:-]{0,127}$/;
|
|
8838
|
+
const IDEMPOTENCY_KEY_RE = /^[\x21-\x7e]{1,255}$/;
|
|
8839
|
+
function assertUuid(value, label) {
|
|
8840
|
+
const trimmed = value.trim();
|
|
8841
|
+
if (!UUID_RE.test(trimmed)) throw new Errors.CLIError(`${label} must be a valid UUID.`, { exit: 2 });
|
|
8842
|
+
return trimmed.toLowerCase();
|
|
8843
|
+
}
|
|
8844
|
+
function assertHttpUrl(value, label) {
|
|
8845
|
+
const trimmed = value.trim();
|
|
8846
|
+
let parsed;
|
|
8847
|
+
try {
|
|
8848
|
+
parsed = new URL(trimmed);
|
|
8849
|
+
} catch {
|
|
8850
|
+
throw new Errors.CLIError(`${label} must be a valid http(s) URL.`, { exit: 2 });
|
|
8851
|
+
}
|
|
8852
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new Errors.CLIError(`${label} must use https:// or http://.`, { exit: 2 });
|
|
8853
|
+
if (trimmed.length > 2048) throw new Errors.CLIError(`${label} must be at most 2048 characters.`, { exit: 2 });
|
|
8854
|
+
return parsed.toString();
|
|
8855
|
+
}
|
|
8856
|
+
function formatActorLabel(actor) {
|
|
8857
|
+
const base = actor.label || actor.kind;
|
|
8858
|
+
if (actor.ownership !== "human" && actor.owner_label) return `${base} (${actor.ownership}, owner: ${actor.owner_label})`;
|
|
8859
|
+
return `${base} (${actor.ownership})`;
|
|
8860
|
+
}
|
|
8861
|
+
function formatTimelineItemLine(item) {
|
|
8862
|
+
const actor = formatActorLabel(item.actor);
|
|
8863
|
+
if (item.source === "primitive") {
|
|
8864
|
+
const reasonPart = item.reason ? ` | reason: ${item.reason}` : "";
|
|
8865
|
+
const runPart = item.run_id ? ` | run: ${item.run_id}` : "";
|
|
8866
|
+
return `${item.occurred_at} [verified] ${item.action} by ${actor}${reasonPart}${runPart}`;
|
|
8867
|
+
}
|
|
8868
|
+
const refPart = item.external_ref?.url ? ` | ${item.external_ref.label || item.external_ref.system}: ${item.external_ref.url}` : item.external_ref ? ` | ${item.external_ref.system}${item.external_ref.id ? `:${item.external_ref.id}` : ""}` : "";
|
|
8869
|
+
const privateTag = item.visibility === "actor_only" ? " [private]" : "";
|
|
8870
|
+
return `${item.occurred_at} [${item.status}]${privateTag} ${item.action} by ${actor} | ${item.summary}${refPart}`;
|
|
8871
|
+
}
|
|
8872
|
+
function sanitizeErrorText(text) {
|
|
8873
|
+
let clean = "";
|
|
8874
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
8875
|
+
const code = text.charCodeAt(i);
|
|
8876
|
+
if (code === 27 && text.charCodeAt(i + 1) === 91) {
|
|
8877
|
+
i += 2;
|
|
8878
|
+
while (i < text.length) {
|
|
8879
|
+
const seqCode = text.charCodeAt(i);
|
|
8880
|
+
if (seqCode >= 64 && seqCode <= 126) break;
|
|
8881
|
+
i += 1;
|
|
8882
|
+
}
|
|
8883
|
+
continue;
|
|
8884
|
+
}
|
|
8885
|
+
if (code === 10 || code === 13 || code === 9) clean += " ";
|
|
8886
|
+
else if (code >= 32 && code !== 127 && (code < 128 || code > 159)) clean += text[i];
|
|
8887
|
+
}
|
|
8888
|
+
return clean.replace(/\s+/g, " ").trim().slice(0, 400);
|
|
8889
|
+
}
|
|
8890
|
+
async function callActivityApi(options) {
|
|
8891
|
+
const authenticated = options.authenticated ?? await createAuthenticatedCliApiClient({
|
|
8892
|
+
configDir: options.configDir,
|
|
8893
|
+
apiKey: options.apiKey,
|
|
8894
|
+
apiBaseUrl: options.apiBaseUrl
|
|
8895
|
+
});
|
|
8896
|
+
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 });
|
|
8897
|
+
const baseUrl = authenticated.auth.apiBaseUrl.replace(/\/+$/, "");
|
|
8898
|
+
const url = new URL(`${baseUrl}${options.path}`);
|
|
8899
|
+
if (options.query) {
|
|
8900
|
+
for (const [key, value] of Object.entries(options.query)) if (value !== void 0 && String(value).length > 0) url.searchParams.set(key, String(value));
|
|
8901
|
+
}
|
|
8902
|
+
let serializedBody;
|
|
8903
|
+
if (options.body !== void 0) serializedBody = JSON.stringify(options.body);
|
|
8904
|
+
const headers = mergeHeadersCaseInsensitive({ accept: options.rawText ? "text/csv, application/json" : "application/json" }, options.headers, serializedBody !== void 0 ? { "content-type": "application/json" } : void 0) ?? {};
|
|
8905
|
+
let response;
|
|
8906
|
+
try {
|
|
8907
|
+
response = await authenticated.fetch(url.toString(), {
|
|
8908
|
+
method: options.method,
|
|
8909
|
+
headers,
|
|
8910
|
+
redirect: "manual",
|
|
8911
|
+
signal: AbortSignal.timeout(3e4),
|
|
8912
|
+
...serializedBody !== void 0 ? { body: serializedBody } : {}
|
|
8913
|
+
});
|
|
8914
|
+
} catch (error) {
|
|
8915
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
8916
|
+
throw new Errors.CLIError(`Primitive API request failed: ${detail}`, { exit: 1 });
|
|
8917
|
+
}
|
|
8918
|
+
const rawText = await response.text();
|
|
8919
|
+
if (!response.ok) {
|
|
8920
|
+
let message = `Primitive API returned HTTP ${response.status}.`;
|
|
8921
|
+
let code;
|
|
8922
|
+
try {
|
|
8923
|
+
const parsed = JSON.parse(rawText);
|
|
8924
|
+
code = parsed.error?.code;
|
|
8925
|
+
if (parsed.error?.message) message = parsed.error.message;
|
|
8926
|
+
} catch {
|
|
8927
|
+
const sanitized = sanitizeErrorText(rawText);
|
|
8928
|
+
if (sanitized) message = sanitized;
|
|
8929
|
+
}
|
|
8930
|
+
const hint = code === "grant_forbidden" ? " Check whether this credential holds mail.activity:read / mail.activity:write." : code === "access_reason_required" ? " Pass --reason \"...\" or set PRIMITIVE_REASON." : code === "feature_not_enabled" ? " Mail activity tracking is not enabled for this organization." : code === "activity_header_invalid" ? " Check --reason / PRIMITIVE_REASON (1-500 printable ASCII) and --run-id / PRIMITIVE_RUN_ID ([A-Za-z0-9._:/-], 1-128 chars)." : "";
|
|
8931
|
+
throw new Errors.CLIError(`${message}${hint}`, {
|
|
8932
|
+
exit: 1,
|
|
8933
|
+
...code ? { code } : {}
|
|
8934
|
+
});
|
|
8935
|
+
}
|
|
8936
|
+
if (options.rawText) return {
|
|
8937
|
+
data: void 0,
|
|
8938
|
+
text: rawText,
|
|
8939
|
+
headers: response.headers,
|
|
8940
|
+
status: response.status
|
|
8941
|
+
};
|
|
8942
|
+
let parsed;
|
|
8943
|
+
try {
|
|
8944
|
+
parsed = rawText ? JSON.parse(rawText) : null;
|
|
8945
|
+
} catch {
|
|
8946
|
+
throw new Errors.CLIError("Primitive API returned invalid JSON.", { exit: 1 });
|
|
8947
|
+
}
|
|
8948
|
+
return {
|
|
8949
|
+
data: parsed && typeof parsed === "object" && "data" in parsed ? parsed.data : parsed,
|
|
8950
|
+
headers: response.headers,
|
|
8951
|
+
status: response.status
|
|
8952
|
+
};
|
|
8953
|
+
}
|
|
8712
8954
|
// src/oclif/repeat-message.ts
|
|
8713
8955
|
const UUID$5 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
8714
8956
|
/** The server-verified repeat marker on an email read, if any. */
|
|
@@ -9284,6 +9526,27 @@ async function clearPendingAfterRead(configDir, emailId, known) {
|
|
|
9284
9526
|
} catch {}
|
|
9285
9527
|
}
|
|
9286
9528
|
const NO_SIGNAL_DESCRIPTION = "Do not report working to the sender, and stop a working report an earlier read of this email started; nothing is sent. Only a --context read reports working; on any other read this flag just stops the earlier report. By default, reading mail from the verified owner or a same-organization member (not another agent) that a receiver surfaced to this session reports working in the background until you answer (also disabled by PRIMITIVE_NO_AUTO_SIGNALS=1).";
|
|
9529
|
+
const WITH_ACTIVITY_DESCRIPTION = "Also fetch recent verified mail actions and shared agent work logs for this email's thread (requires mail.activity:read).";
|
|
9530
|
+
async function fetchEmailThreadActivity(command, threadId, flags, authenticated) {
|
|
9531
|
+
if (!threadId) return [];
|
|
9532
|
+
const validThreadId = assertUuid(threadId, "thread_id");
|
|
9533
|
+
return (await callActivityApi({
|
|
9534
|
+
configDir: command.config.configDir,
|
|
9535
|
+
apiKey: flags["api-key"],
|
|
9536
|
+
apiBaseUrl: flags["api-base-url"],
|
|
9537
|
+
authenticated,
|
|
9538
|
+
method: "GET",
|
|
9539
|
+
path: `/threads/${validThreadId}/timeline`,
|
|
9540
|
+
query: {
|
|
9541
|
+
source: "all",
|
|
9542
|
+
limit: 20
|
|
9543
|
+
}
|
|
9544
|
+
})).data.items;
|
|
9545
|
+
}
|
|
9546
|
+
function renderThreadActivitySection(items) {
|
|
9547
|
+
if (items.length === 0) return "\nThread Activity:\n (none recorded yet)";
|
|
9548
|
+
return `\nThread Activity:\n${items.map((item) => ` ${formatTimelineItemLine(item)}`).join("\n")}`;
|
|
9549
|
+
}
|
|
9287
9550
|
/**
|
|
9288
9551
|
* The line a brief ends with once it has started reporting working: the
|
|
9289
9552
|
* agent only knows whether it will act after reading, so the way out has to
|
|
@@ -9306,11 +9569,12 @@ function workingStopLine(command) {
|
|
|
9306
9569
|
async function runBrief(command, flags) {
|
|
9307
9570
|
await runWithTiming(flags.time === true, async () => {
|
|
9308
9571
|
if (flags["no-signal"]) await haltAutoWorking(command.config.configDir, { emailIds: [flags.id] }, "not_acting");
|
|
9309
|
-
const
|
|
9572
|
+
const authenticated = await createAuthenticatedCliApiClient({
|
|
9310
9573
|
configDir: command.config.configDir,
|
|
9311
9574
|
apiKey: flags["api-key"],
|
|
9312
9575
|
apiBaseUrl: flags["api-base-url"]
|
|
9313
9576
|
});
|
|
9577
|
+
const { apiClient, auth, baseUrlOverridden } = authenticated;
|
|
9314
9578
|
const result = await getEmail({
|
|
9315
9579
|
client: apiClient.client,
|
|
9316
9580
|
path: { id: flags.id },
|
|
@@ -9341,25 +9605,28 @@ async function runBrief(command, flags) {
|
|
|
9341
9605
|
isOwnSignal: (sentId) => isSentSignal(command.config.configDir, sentId),
|
|
9342
9606
|
signal: AbortSignal.timeout(3e4)
|
|
9343
9607
|
});
|
|
9608
|
+
const activities = flags["with-activity"] ? await fetchEmailThreadActivity(command, detail.thread_id, flags, authenticated) : void 0;
|
|
9344
9609
|
const stop = !flags["no-signal"] && detail.sender_connected_agent_verified !== true && dispatchAutoWorking({
|
|
9345
9610
|
configDir: command.config.configDir,
|
|
9346
9611
|
emailId: detail.id
|
|
9347
9612
|
}) || !flags["no-signal"] && workingStillRunning(readWorkingLease(command.config.configDir, detail.id)) ? workingStopCommand(detail.id, followUpCommandPrefix()) : null;
|
|
9348
|
-
command.log(flags.json ? JSON.stringify(
|
|
9613
|
+
command.log(flags.json ? JSON.stringify({
|
|
9349
9614
|
...brief,
|
|
9350
|
-
working_signal: { stop_command: stop }
|
|
9351
|
-
|
|
9615
|
+
...stop ? { working_signal: { stop_command: stop } } : {},
|
|
9616
|
+
...activities !== void 0 ? { activities } : {}
|
|
9617
|
+
}, null, 2) : `${renderEmailBrief(brief)}${activities !== void 0 ? renderThreadActivitySection(activities) : ""}${stop ? `\n${workingStopLine(stop)}` : ""}`);
|
|
9352
9618
|
await clearPendingAfterRead(command.config.configDir, detail.id, detail);
|
|
9353
9619
|
});
|
|
9354
9620
|
}
|
|
9355
9621
|
const ROUTE_MISSING_NOTICE = "Note: this server does not offer the readable read yet, so a local compact view was printed.\n";
|
|
9356
9622
|
async function runCompact(command, flags) {
|
|
9357
9623
|
await runWithTiming(flags.time === true, async () => {
|
|
9358
|
-
const
|
|
9624
|
+
const authenticated = await createAuthenticatedCliApiClient({
|
|
9359
9625
|
configDir: command.config.configDir,
|
|
9360
9626
|
apiKey: flags["api-key"],
|
|
9361
9627
|
apiBaseUrl: flags["api-base-url"]
|
|
9362
9628
|
});
|
|
9629
|
+
const { apiClient, auth, baseUrlOverridden } = authenticated;
|
|
9363
9630
|
const fail = async (error) => {
|
|
9364
9631
|
const payload = extractErrorPayload(error);
|
|
9365
9632
|
writeErrorWithHints(payload);
|
|
@@ -9378,7 +9645,11 @@ async function runCompact(command, flags) {
|
|
|
9378
9645
|
...flags.links !== void 0 ? { links: flags.links } : {}
|
|
9379
9646
|
});
|
|
9380
9647
|
if (readable.kind === "ok") {
|
|
9381
|
-
command
|
|
9648
|
+
const activities = flags["with-activity"] ? await fetchEmailThreadActivity(command, readable.data.thread_id, flags, authenticated) : void 0;
|
|
9649
|
+
command.log(JSON.stringify(activities !== void 0 ? {
|
|
9650
|
+
...readable.data,
|
|
9651
|
+
activities
|
|
9652
|
+
} : readable.data, null, 2));
|
|
9382
9653
|
await clearPendingAfterRead(command.config.configDir, readable.data.id, readable.data);
|
|
9383
9654
|
return;
|
|
9384
9655
|
}
|
|
@@ -9396,8 +9667,12 @@ async function runCompact(command, flags) {
|
|
|
9396
9667
|
await fail(result.error);
|
|
9397
9668
|
return;
|
|
9398
9669
|
}
|
|
9670
|
+
const activities = flags["with-activity"] ? await fetchEmailThreadActivity(command, detail.thread_id, flags, authenticated) : void 0;
|
|
9399
9671
|
process.stderr.write(ROUTE_MISSING_NOTICE);
|
|
9400
|
-
command.log(JSON.stringify(
|
|
9672
|
+
command.log(JSON.stringify(activities !== void 0 ? {
|
|
9673
|
+
...buildEmailCompact(detail),
|
|
9674
|
+
activities
|
|
9675
|
+
} : buildEmailCompact(detail), null, 2));
|
|
9401
9676
|
await clearPendingAfterRead(command.config.configDir, detail.id, detail);
|
|
9402
9677
|
});
|
|
9403
9678
|
}
|
|
@@ -9436,7 +9711,8 @@ function createEmailsGetCommand(base) {
|
|
|
9436
9711
|
description: LINKS_DESCRIPTION,
|
|
9437
9712
|
dependsOn: ["compact"]
|
|
9438
9713
|
}),
|
|
9439
|
-
"no-signal": Flags.boolean({ description: NO_SIGNAL_DESCRIPTION })
|
|
9714
|
+
"no-signal": Flags.boolean({ description: NO_SIGNAL_DESCRIPTION }),
|
|
9715
|
+
"with-activity": Flags.boolean({ description: WITH_ACTIVITY_DESCRIPTION })
|
|
9440
9716
|
};
|
|
9441
9717
|
async run() {
|
|
9442
9718
|
if (this.argv.includes("--brief")) {
|
|
@@ -9463,7 +9739,49 @@ function createEmailsGetCommand(base) {
|
|
|
9463
9739
|
await runCompact(this, parsed);
|
|
9464
9740
|
return;
|
|
9465
9741
|
}
|
|
9466
|
-
|
|
9742
|
+
if (parsed["with-activity"]) {
|
|
9743
|
+
await runWithTiming(parsed.time === true, async () => {
|
|
9744
|
+
const authenticated = await createAuthenticatedCliApiClient({
|
|
9745
|
+
configDir: this.config.configDir,
|
|
9746
|
+
apiKey: parsed["api-key"],
|
|
9747
|
+
apiBaseUrl: parsed["api-base-url"]
|
|
9748
|
+
});
|
|
9749
|
+
const { apiClient, auth, baseUrlOverridden } = authenticated;
|
|
9750
|
+
const result = await getEmail({
|
|
9751
|
+
client: apiClient.client,
|
|
9752
|
+
path: { id: parsed.id },
|
|
9753
|
+
responseStyle: "fields"
|
|
9754
|
+
});
|
|
9755
|
+
const detail = result.data?.data;
|
|
9756
|
+
if (result.error || !detail) {
|
|
9757
|
+
const payload = extractErrorPayload(result.error);
|
|
9758
|
+
writeErrorWithHints(payload);
|
|
9759
|
+
surfaceUnauthorizedHint({
|
|
9760
|
+
auth,
|
|
9761
|
+
baseUrlOverridden,
|
|
9762
|
+
configDir: this.config.configDir,
|
|
9763
|
+
payload
|
|
9764
|
+
});
|
|
9765
|
+
if (extractErrorCode(payload) === "not_found") await explainPendingMailNotFound(this.config.configDir, parsed.id);
|
|
9766
|
+
process.exitCode = 1;
|
|
9767
|
+
return;
|
|
9768
|
+
}
|
|
9769
|
+
const activities = await fetchEmailThreadActivity(this, detail.thread_id, parsed, authenticated);
|
|
9770
|
+
const enrichedDetail = {
|
|
9771
|
+
...detail,
|
|
9772
|
+
activities
|
|
9773
|
+
};
|
|
9774
|
+
const output = parsed.json ? {
|
|
9775
|
+
...result.data,
|
|
9776
|
+
success: true,
|
|
9777
|
+
data: enrichedDetail
|
|
9778
|
+
} : enrichedDetail;
|
|
9779
|
+
this.log(JSON.stringify(output, null, 2));
|
|
9780
|
+
await clearPendingAfterRead(this.config.configDir, detail.id, detail);
|
|
9781
|
+
});
|
|
9782
|
+
return;
|
|
9783
|
+
}
|
|
9784
|
+
this.argv = this.argv.filter((arg) => arg !== "--no-signal" && !arg.startsWith("--no-signal=") && arg !== "--with-activity" && !arg.startsWith("--with-activity="));
|
|
9467
9785
|
const before = process.exitCode;
|
|
9468
9786
|
await base.prototype.run.call(this);
|
|
9469
9787
|
if (process.exitCode === before || process.exitCode === 0) await clearPendingAfterRead(this.config.configDir, parsed.id);
|
|
@@ -11504,8 +11822,8 @@ const PRIMITIVE_TEAM_AUTHOR = {
|
|
|
11504
11822
|
name: "Primitive Team",
|
|
11505
11823
|
url: "https://primitive.dev"
|
|
11506
11824
|
};
|
|
11507
|
-
const SDK_VERSION_RANGE = "^3.0.0-preview.
|
|
11508
|
-
const CLI_VERSION_RANGE = "^3.0.0-preview.
|
|
11825
|
+
const SDK_VERSION_RANGE = "^3.0.0-preview.26";
|
|
11826
|
+
const CLI_VERSION_RANGE = "^3.0.0-preview.26";
|
|
11509
11827
|
const ESBUILD_VERSION_RANGE = "^0.27.0";
|
|
11510
11828
|
function renderHandler() {
|
|
11511
11829
|
return `// env.PRIMITIVE_API_KEY, env.PRIMITIVE_WEBHOOK_SECRET, and
|
|
@@ -14506,24 +14824,34 @@ var WhoamiCommand = class WhoamiCommand extends Command {
|
|
|
14506
14824
|
}, 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}`);
|
|
14507
14825
|
return;
|
|
14508
14826
|
}
|
|
14509
|
-
if (auth.agentPass) {
|
|
14510
|
-
|
|
14511
|
-
|
|
14512
|
-
|
|
14513
|
-
|
|
14514
|
-
|
|
14515
|
-
|
|
14516
|
-
|
|
14517
|
-
|
|
14518
|
-
|
|
14827
|
+
if (auth.agentPass && flags.check === void 0) {
|
|
14828
|
+
let response;
|
|
14829
|
+
try {
|
|
14830
|
+
response = await fetch(`${auth.apiBaseUrl.replace(/\/+$/, "")}/whoami/grant`, {
|
|
14831
|
+
method: "GET",
|
|
14832
|
+
headers: {
|
|
14833
|
+
...cliActivityHeadersFromEnv(),
|
|
14834
|
+
authorization: `Bearer ${auth.apiKey ?? ""}`,
|
|
14835
|
+
accept: "application/json"
|
|
14836
|
+
}
|
|
14837
|
+
});
|
|
14838
|
+
} catch (error) {
|
|
14839
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
14840
|
+
throw new Errors.CLIError(`Could not reach /whoami/grant: ${detail}`, { exit: 1 });
|
|
14841
|
+
}
|
|
14519
14842
|
const payload = await response.json().catch(() => null);
|
|
14520
14843
|
if (!response.ok) {
|
|
14521
14844
|
const errorPayload = extractErrorPayload(payload ?? { message: `HTTP ${response.status}` });
|
|
14522
|
-
writeErrorWithHints(errorPayload);
|
|
14845
|
+
writeErrorWithHints(errorPayload, response, { auth });
|
|
14523
14846
|
process.exitCode = 1;
|
|
14524
14847
|
return;
|
|
14525
14848
|
}
|
|
14526
|
-
grant = payload?.data ?? null;
|
|
14849
|
+
const grant = payload?.data ?? null;
|
|
14850
|
+
const { pass, permissions: perms } = syncAgentPassMetadataFromGrant({
|
|
14851
|
+
configDir: this.config.configDir,
|
|
14852
|
+
pass: auth.agentPass,
|
|
14853
|
+
grantData: grant
|
|
14854
|
+
});
|
|
14527
14855
|
const revokeCommand = pass.binding.kind === "profile" ? `primitive disconnect --profile ${pass.binding.profile}` : "primitive disconnect";
|
|
14528
14856
|
if (flags.json) {
|
|
14529
14857
|
this.log(JSON.stringify({
|
|
@@ -14534,13 +14862,13 @@ var WhoamiCommand = class WhoamiCommand extends Command {
|
|
|
14534
14862
|
}, null, 2));
|
|
14535
14863
|
return;
|
|
14536
14864
|
}
|
|
14537
|
-
const perms = Array.isArray(grant?.permissions) ? grant.permissions.filter((p) => typeof p === "string") : [];
|
|
14538
14865
|
const lines = [
|
|
14539
14866
|
`Authenticated with Access Pass "${pass.label}" (${pass.mode})`,
|
|
14540
14867
|
`Expires at: ${pass.expires_at}`,
|
|
14541
14868
|
`API origin: ${auth.apiBaseUrl}`
|
|
14542
14869
|
];
|
|
14543
14870
|
if (pass.slice_summary) lines.push(`Scope: ${pass.slice_summary}`);
|
|
14871
|
+
if (pass.manage_url) lines.push(`Manage / extend / promote: ${pass.manage_url}`);
|
|
14544
14872
|
if (perms.length > 0) lines.push(`Permissions: ${perms.join(", ")}`);
|
|
14545
14873
|
lines.push(`Disconnect and revoke: ${revokeCommand}`);
|
|
14546
14874
|
this.log(lines.join("\n"));
|
|
@@ -18506,6 +18834,74 @@ var ListenPendingCommand = class ListenPendingCommand extends Command {
|
|
|
18506
18834
|
}, null, 2));
|
|
18507
18835
|
}
|
|
18508
18836
|
};
|
|
18837
|
+
// src/oclif/commands/lock.ts
|
|
18838
|
+
var LockCommand = class LockCommand extends Command {
|
|
18839
|
+
static summary = "Lock global CLI credentials so agents must use scoped Access Passes";
|
|
18840
|
+
static description = "Blocks global OAuth login (credentials.json), ambient PRIMITIVE_API_KEY, and ad-hoc --api-key overrides until you run `primitive unlock` in an interactive terminal. Scoped Access Passes (`primitive connect <url>`) and connected agent profiles (PRIMITIVE_AGENT_PROFILE) continue to work normally while locked.";
|
|
18841
|
+
static examples = [
|
|
18842
|
+
"<%= config.bin %> lock",
|
|
18843
|
+
"<%= config.bin %> lock --reason 'Keep admin login safe from local agent sessions'",
|
|
18844
|
+
"<%= config.bin %> lock --status"
|
|
18845
|
+
];
|
|
18846
|
+
static flags = {
|
|
18847
|
+
reason: Flags.string({ description: "Optional note shown when a locked global credential is blocked" }),
|
|
18848
|
+
status: Flags.boolean({ description: "Show the current lock status without changing it" }),
|
|
18849
|
+
json: Flags.boolean({ description: "Print the lock status as JSON" })
|
|
18850
|
+
};
|
|
18851
|
+
async run() {
|
|
18852
|
+
const { flags } = await this.parse(LockCommand);
|
|
18853
|
+
try {
|
|
18854
|
+
if (flags.status) {
|
|
18855
|
+
const state = readCliLockState(this.config.configDir);
|
|
18856
|
+
if (flags.json) {
|
|
18857
|
+
this.log(JSON.stringify(state));
|
|
18858
|
+
return;
|
|
18859
|
+
}
|
|
18860
|
+
if (state.status === "locked") {
|
|
18861
|
+
this.log(`Global Primitive credentials are LOCKED (since ${state.lockedAt}).`);
|
|
18862
|
+
if (state.reason) this.log(`Reason: ${state.reason}`);
|
|
18863
|
+
this.log("Allowed while locked: scoped Access Passes (`primitive connect <url>`) and PRIMITIVE_AGENT_PROFILE.");
|
|
18864
|
+
this.log("To temporarily use your global login: `primitive unlock --for 15m`.");
|
|
18865
|
+
return;
|
|
18866
|
+
}
|
|
18867
|
+
if (state.status === "temporarily_unlocked") {
|
|
18868
|
+
this.log(`Global Primitive credentials are temporarily unlocked until ${state.unlockedUntil} (will auto-relock).`);
|
|
18869
|
+
this.log("Run `primitive lock` to re-lock immediately.");
|
|
18870
|
+
return;
|
|
18871
|
+
}
|
|
18872
|
+
this.log("Global Primitive credentials are unlocked.");
|
|
18873
|
+
this.log("Run `primitive lock` to prevent agent sessions from accidentally using your global login or PRIMITIVE_API_KEY.");
|
|
18874
|
+
return;
|
|
18875
|
+
}
|
|
18876
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
18877
|
+
const reason = flags.reason?.trim() || null;
|
|
18878
|
+
const record = {
|
|
18879
|
+
version: 1,
|
|
18880
|
+
locked: true,
|
|
18881
|
+
locked_at: nowIso,
|
|
18882
|
+
unlocked_until: null,
|
|
18883
|
+
...reason ? { reason } : {}
|
|
18884
|
+
};
|
|
18885
|
+
writeCliLockState(this.config.configDir, record);
|
|
18886
|
+
if (flags.json) {
|
|
18887
|
+
this.log(JSON.stringify({
|
|
18888
|
+
status: "locked",
|
|
18889
|
+
locked: true,
|
|
18890
|
+
locked_at: nowIso,
|
|
18891
|
+
reason
|
|
18892
|
+
}));
|
|
18893
|
+
return;
|
|
18894
|
+
}
|
|
18895
|
+
this.log("Locked global Primitive credentials on this machine.");
|
|
18896
|
+
this.log("Blocked: saved OAuth login, ambient PRIMITIVE_API_KEY, and ad-hoc --api-key overrides.");
|
|
18897
|
+
this.log("Allowed: scoped Access Passes (`primitive connect <url>`) and PRIMITIVE_AGENT_PROFILE.");
|
|
18898
|
+
this.log("When you need your global login in your terminal: run `primitive unlock --for 15m` (auto-relocks) or `primitive unlock`.");
|
|
18899
|
+
} catch (error) {
|
|
18900
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
18901
|
+
throw new Errors.CLIError(message, { exit: 1 });
|
|
18902
|
+
}
|
|
18903
|
+
}
|
|
18904
|
+
};
|
|
18509
18905
|
// src/oclif/commands/login.ts
|
|
18510
18906
|
const MAX_CLI_LOGIN_POLL_INTERVAL_SECONDS = 60;
|
|
18511
18907
|
/** How long a login waits for an in-flight agent registration on this machine. */
|
|
@@ -19785,6 +20181,10 @@ async function runLogoutWithCredentialLock(params) {
|
|
|
19785
20181
|
throw error;
|
|
19786
20182
|
}
|
|
19787
20183
|
const freshCredentials = authenticated.auth.credentials ?? credentials;
|
|
20184
|
+
if (authenticated.auth.source === "agent-pass" && authenticated.auth.agentPass) {
|
|
20185
|
+
const disconnectCmd = authenticated.auth.agentPass.binding.kind === "profile" ? `primitive disconnect --profile ${authenticated.auth.agentPass.binding.profile}` : "primitive disconnect";
|
|
20186
|
+
throw cliError$1(`An Access Pass ("${authenticated.auth.agentPass.label}") is active in this context. Run \`${disconnectCmd}\` to disconnect the Access Pass, or run \`primitive logout\` outside the bound session to log out of your saved Primitive CLI login.`);
|
|
20187
|
+
}
|
|
19788
20188
|
const result = await deps.cliLogout({
|
|
19789
20189
|
body: { key_id: freshCredentials.oauth_grant_id },
|
|
19790
20190
|
client: authenticated.apiClient.client,
|
|
@@ -21195,108 +21595,620 @@ var MachineDoctorCommand = class MachineDoctorCommand extends Command {
|
|
|
21195
21595
|
if (report.summary.fail || report.summary.warn) process.exitCode = 1;
|
|
21196
21596
|
}
|
|
21197
21597
|
};
|
|
21198
|
-
// src/oclif/commands/
|
|
21199
|
-
|
|
21200
|
-
|
|
21201
|
-
description: "Primitive API key override (defaults to PRIMITIVE_API_KEY or saved OAuth login credentials)",
|
|
21202
|
-
env: "PRIMITIVE_API_KEY"
|
|
21203
|
-
});
|
|
21204
|
-
const API_BASE_URL_FLAG$1 = Flags.string({
|
|
21205
|
-
description: API_BASE_URL_FLAG_DESCRIPTION,
|
|
21206
|
-
env: "PRIMITIVE_API_BASE_URL",
|
|
21207
|
-
hidden: true
|
|
21208
|
-
});
|
|
21209
|
-
const SCOPE_FLAGS = {
|
|
21210
|
-
function: Flags.string({
|
|
21211
|
-
description: "Function id (UUID) to scope this memory to. Function names are not accepted.",
|
|
21212
|
-
exclusive: ["org"]
|
|
21213
|
-
}),
|
|
21214
|
-
org: Flags.boolean({
|
|
21215
|
-
description: "Force org scope. Outside a function-authenticated request this is already the default.",
|
|
21216
|
-
exclusive: ["function"]
|
|
21217
|
-
})
|
|
21218
|
-
};
|
|
21219
|
-
function reportMemoryError(error, context) {
|
|
21220
|
-
const payload = extractErrorPayload(error);
|
|
21221
|
-
writeErrorWithHints(payload);
|
|
21222
|
-
surfaceUnauthorizedHint({
|
|
21223
|
-
...context,
|
|
21224
|
-
payload
|
|
21225
|
-
});
|
|
21226
|
-
process.exitCode = 1;
|
|
21227
|
-
}
|
|
21228
|
-
function printData(command, responseData) {
|
|
21229
|
-
const data = responseData?.data ?? null;
|
|
21230
|
-
command.log(JSON.stringify(data, null, 2));
|
|
21231
|
-
}
|
|
21232
|
-
const CONTROL_CHARACTERS$1 = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}]`);
|
|
21233
|
-
/**
|
|
21234
|
-
* The stderr line naming the next page's cursor. A memory key can hold a line
|
|
21235
|
-
* break or another control character, which would split or garble the line,
|
|
21236
|
-
* so such a cursor is printed JSON-encoded, with a note on how to pass it.
|
|
21237
|
-
*/
|
|
21238
|
-
function nextCursorLine(cursor) {
|
|
21239
|
-
if (!CONTROL_CHARACTERS$1.test(cursor)) return `next cursor: ${cursor}\n`;
|
|
21240
|
-
return `next cursor (JSON-encoded, it holds control characters; decode it before passing it to --cursor, or read meta.cursor with --json): ${JSON.stringify(cursor)}\n`;
|
|
21241
|
-
}
|
|
21242
|
-
function handleMemoryInputError(error) {
|
|
21243
|
-
if (!(error instanceof MemoryCliInputError)) return false;
|
|
21244
|
-
process.stderr.write(`${error.message}\n`);
|
|
21245
|
-
process.exitCode = 1;
|
|
21246
|
-
return true;
|
|
21247
|
-
}
|
|
21248
|
-
function nonEmptyFlag(value, name) {
|
|
21249
|
-
if (value === void 0) return void 0;
|
|
21250
|
-
if (value.trim().length === 0) throw new MemoryCliInputError(`${name} must be a non-empty string.`);
|
|
21251
|
-
return value;
|
|
21252
|
-
}
|
|
21253
|
-
function parseMemoryJson(source, label = "value") {
|
|
21598
|
+
// src/oclif/commands/mail-activity.ts
|
|
21599
|
+
const MAX_DATA_BYTES = 16384;
|
|
21600
|
+
function readUtf8File(filePath, label) {
|
|
21254
21601
|
try {
|
|
21255
|
-
|
|
21256
|
-
if (!isMemoryJsonValue(value)) return {
|
|
21257
|
-
kind: "error",
|
|
21258
|
-
message: `${label} must be valid JSON. Numbers must be finite, arrays must not be sparse, and values may not contain undefined, bigint, symbol, function, class instance, or cyclic entries.`
|
|
21259
|
-
};
|
|
21260
|
-
return {
|
|
21261
|
-
kind: "ok",
|
|
21262
|
-
value
|
|
21263
|
-
};
|
|
21602
|
+
return readFileSync(filePath, "utf8");
|
|
21264
21603
|
} catch (error) {
|
|
21265
|
-
|
|
21266
|
-
|
|
21267
|
-
message: `${label} must be valid JSON. Quote strings as JSON strings, for example '"hello"'. ${error instanceof Error ? error.message : String(error)}`
|
|
21268
|
-
};
|
|
21604
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
21605
|
+
throw new Errors.CLIError(`Could not read ${label} from ${filePath}: ${detail}`, { exit: 2 });
|
|
21269
21606
|
}
|
|
21270
21607
|
}
|
|
21271
|
-
function
|
|
21272
|
-
|
|
21273
|
-
|
|
21274
|
-
|
|
21275
|
-
};
|
|
21276
|
-
if (input.value !== void 0) return {
|
|
21277
|
-
kind: "ok",
|
|
21278
|
-
source: input.value,
|
|
21279
|
-
label: "value"
|
|
21280
|
-
};
|
|
21281
|
-
if (input.valueFile !== void 0) try {
|
|
21282
|
-
return {
|
|
21283
|
-
kind: "ok",
|
|
21284
|
-
source: input.readFile ? input.readFile(input.valueFile) : readTextFileFlag(input.valueFile, "--value-file"),
|
|
21285
|
-
label: `--value-file ${input.valueFile}`
|
|
21286
|
-
};
|
|
21608
|
+
function parseJsonObjectFlag(raw, label) {
|
|
21609
|
+
let parsed;
|
|
21610
|
+
try {
|
|
21611
|
+
parsed = JSON.parse(raw);
|
|
21287
21612
|
} catch (error) {
|
|
21288
|
-
|
|
21289
|
-
|
|
21290
|
-
|
|
21291
|
-
|
|
21292
|
-
|
|
21293
|
-
|
|
21294
|
-
|
|
21295
|
-
|
|
21296
|
-
|
|
21297
|
-
|
|
21298
|
-
|
|
21299
|
-
|
|
21613
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
21614
|
+
throw new Errors.CLIError(`${label} must be valid JSON: ${detail}`, { exit: 2 });
|
|
21615
|
+
}
|
|
21616
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Errors.CLIError(`${label} must be a JSON object.`, { exit: 2 });
|
|
21617
|
+
const bytes = Buffer.byteLength(JSON.stringify(parsed), "utf8");
|
|
21618
|
+
if (bytes > MAX_DATA_BYTES) throw new Errors.CLIError(`${label} exceeds the ${MAX_DATA_BYTES}-byte limit (${bytes} bytes).`, { exit: 2 });
|
|
21619
|
+
return parsed;
|
|
21620
|
+
}
|
|
21621
|
+
function buildExternalRef(flags) {
|
|
21622
|
+
const hasRefFlags = flags["ref-system"] !== void 0 || flags["ref-id"] !== void 0 || flags["ref-url"] !== void 0 || flags["ref-label"] !== void 0;
|
|
21623
|
+
if (flags["external-ref"] !== void 0 && hasRefFlags) throw new Errors.CLIError("Use either --external-ref or --ref-system/--ref-id/--ref-url/--ref-label, not both.", { exit: 2 });
|
|
21624
|
+
if (flags["external-ref"] !== void 0) {
|
|
21625
|
+
const obj = parseJsonObjectFlag(flags["external-ref"], "--external-ref");
|
|
21626
|
+
if (typeof obj.system !== "string" || !obj.system.trim()) throw new Errors.CLIError("--external-ref must include a non-empty string `system`.", { exit: 2 });
|
|
21627
|
+
const ref = { system: obj.system.trim() };
|
|
21628
|
+
if (typeof obj.id === "string" && obj.id.trim()) ref.id = obj.id.trim();
|
|
21629
|
+
if (typeof obj.url === "string" && obj.url.trim()) ref.url = assertHttpUrl(obj.url, "--external-ref.url");
|
|
21630
|
+
if (typeof obj.label === "string" && obj.label.trim()) ref.label = obj.label.trim();
|
|
21631
|
+
return ref;
|
|
21632
|
+
}
|
|
21633
|
+
if (!hasRefFlags) return void 0;
|
|
21634
|
+
if (!flags["ref-system"]?.trim()) throw new Errors.CLIError("--ref-system is required when setting --ref-id, --ref-url, or --ref-label.", { exit: 2 });
|
|
21635
|
+
const ref = { system: flags["ref-system"].trim() };
|
|
21636
|
+
if (flags["ref-id"]?.trim()) ref.id = flags["ref-id"].trim();
|
|
21637
|
+
if (flags["ref-url"]?.trim()) ref.url = assertHttpUrl(flags["ref-url"], "--ref-url");
|
|
21638
|
+
if (flags["ref-label"]?.trim()) ref.label = flags["ref-label"].trim();
|
|
21639
|
+
return ref;
|
|
21640
|
+
}
|
|
21641
|
+
function validateStatusCsv(raw) {
|
|
21642
|
+
const allowed = new Set(ACTIVITY_STATUSES);
|
|
21643
|
+
const parts = raw.split(",").map((p) => p.trim()).filter(Boolean);
|
|
21644
|
+
if (parts.length === 0 || !parts.every((p) => allowed.has(p))) throw new Errors.CLIError(`--status must be a comma-separated list of: ${ACTIVITY_STATUSES.join(", ")}.`, { exit: 2 });
|
|
21645
|
+
return parts.join(",");
|
|
21646
|
+
}
|
|
21647
|
+
const COMMON_API_FLAGS = {
|
|
21648
|
+
json: Flags.boolean({ description: "Output single-document JSON to stdout" }),
|
|
21649
|
+
time: Flags.boolean({ description: "Print request timing to stderr" }),
|
|
21650
|
+
"api-key": Flags.string({
|
|
21651
|
+
description: "Override the Primitive API key for this request",
|
|
21652
|
+
env: "PRIMITIVE_API_KEY"
|
|
21653
|
+
}),
|
|
21654
|
+
"api-base-url": Flags.string({
|
|
21655
|
+
description: "Override the API base URL",
|
|
21656
|
+
env: "PRIMITIVE_API_BASE_URL",
|
|
21657
|
+
hidden: true
|
|
21658
|
+
})
|
|
21659
|
+
};
|
|
21660
|
+
var ActivityLogCommand = class ActivityLogCommand extends Command {
|
|
21661
|
+
static summary = "Log an agent work note, external action outcome, or handoff";
|
|
21662
|
+
static description = "Record structured work on a Primitive email or thread so humans and other agents see what already happened. Supply a deterministic --idempotency-key per (thread, action) so retries update the same entry cleanly.";
|
|
21663
|
+
static examples = [`<%= config.bin %> activity log --email <email-id> --action brex.upload_invoice --status succeeded --summary "Uploaded Acme invoice #412 to Brex" --ref-system brex --ref-id inv_412 --idempotency-key brex.upload_invoice:v1`, `<%= config.bin %> activity log --thread <thread-id> --kind handoff --status needs_review --summary "Personal invoice detected; needs confirmation"`];
|
|
21664
|
+
static args = { summary: Args.string({
|
|
21665
|
+
description: "Optional positional summary (alternative to --summary)",
|
|
21666
|
+
required: false
|
|
21667
|
+
}) };
|
|
21668
|
+
static flags = {
|
|
21669
|
+
thread: Flags.string({ description: "Thread UUID to attach the activity to" }),
|
|
21670
|
+
email: Flags.string({ description: "Inbound email UUID to anchor the activity to (resolves its thread automatically when --thread is omitted)" }),
|
|
21671
|
+
"sent-email": Flags.string({ description: "Optional outbound sent email UUID related to this work" }),
|
|
21672
|
+
summary: Flags.string({
|
|
21673
|
+
char: "s",
|
|
21674
|
+
description: "One-line human-readable summary (1 to 1000 chars)"
|
|
21675
|
+
}),
|
|
21676
|
+
kind: Flags.string({
|
|
21677
|
+
description: "Entry kind: action, note, or handoff",
|
|
21678
|
+
options: [...ACTIVITY_KINDS]
|
|
21679
|
+
}),
|
|
21680
|
+
action: Flags.string({
|
|
21681
|
+
char: "a",
|
|
21682
|
+
description: "Dot-namespaced action verb (for example brex.upload_invoice)"
|
|
21683
|
+
}),
|
|
21684
|
+
status: Flags.string({
|
|
21685
|
+
description: "Outcome status: started, succeeded, failed, skipped, or needs_review",
|
|
21686
|
+
options: [...ACTIVITY_STATUSES]
|
|
21687
|
+
}),
|
|
21688
|
+
detail: Flags.string({ description: "Optional extended detail (up to 8000 chars)" }),
|
|
21689
|
+
"detail-file": Flags.string({ description: "Read extended detail text from a file" }),
|
|
21690
|
+
"ref-system": Flags.string({ description: "External system name (for example brex, salesforce, linear)" }),
|
|
21691
|
+
"ref-id": Flags.string({ description: "External record ID (requires --ref-system)" }),
|
|
21692
|
+
"ref-url": Flags.string({ description: "External record https:// URL (requires --ref-system)" }),
|
|
21693
|
+
"ref-label": Flags.string({ description: "Display label for the external link (requires --ref-system)" }),
|
|
21694
|
+
"external-ref": Flags.string({ description: "External reference as a JSON object (alternative to --ref-*)" }),
|
|
21695
|
+
data: Flags.string({ description: "Structured metadata JSON object (up to 16 KB)" }),
|
|
21696
|
+
"data-file": Flags.string({ description: "Read structured metadata JSON object from a file" }),
|
|
21697
|
+
"run-id": Flags.string({
|
|
21698
|
+
description: "Agent run correlation ID (defaults to PRIMITIVE_RUN_ID)",
|
|
21699
|
+
env: "PRIMITIVE_RUN_ID"
|
|
21700
|
+
}),
|
|
21701
|
+
"trace-url": Flags.string({ description: "Optional https:// URL to the agent execution trace" }),
|
|
21702
|
+
"idempotency-key": Flags.string({ description: "Deterministic key per (thread, action) so retries upsert in place" }),
|
|
21703
|
+
visibility: Flags.string({
|
|
21704
|
+
description: "Visibility: thread (default, shared) or actor_only (private)",
|
|
21705
|
+
options: [...ACTIVITY_VISIBILITIES]
|
|
21706
|
+
}),
|
|
21707
|
+
...COMMON_API_FLAGS
|
|
21708
|
+
};
|
|
21709
|
+
async run() {
|
|
21710
|
+
const { args, flags } = await this.parse(ActivityLogCommand);
|
|
21711
|
+
const summary = (flags.summary ?? args.summary ?? "").trim();
|
|
21712
|
+
if (!summary) throw new Errors.CLIError("Provide --summary \"...\" (or a positional summary argument).", { exit: 2 });
|
|
21713
|
+
if (summary.length > 1e3) throw new Errors.CLIError("--summary must be at most 1000 characters.", { exit: 2 });
|
|
21714
|
+
if (!flags.thread && !flags.email) throw new Errors.CLIError("Provide --thread <uuid> or --email <uuid>.", { exit: 2 });
|
|
21715
|
+
if (flags.detail !== void 0 && flags["detail-file"] !== void 0) throw new Errors.CLIError("Use either --detail or --detail-file, not both.", { exit: 2 });
|
|
21716
|
+
if (flags.data !== void 0 && flags["data-file"] !== void 0) throw new Errors.CLIError("Use either --data or --data-file, not both.", { exit: 2 });
|
|
21717
|
+
const threadId = flags.thread !== void 0 ? assertUuid(flags.thread, "--thread") : null;
|
|
21718
|
+
const emailId = flags.email !== void 0 ? assertUuid(flags.email, "--email") : null;
|
|
21719
|
+
const sentEmailId = flags["sent-email"] !== void 0 ? assertUuid(flags["sent-email"], "--sent-email") : void 0;
|
|
21720
|
+
if (flags.action !== void 0 && !ACTION_SLUG_RE.test(flags.action.trim())) throw new Errors.CLIError("--action must start with a lowercase letter or digit and use only a-z, 0-9, ., _, :, - (max 128 chars).", { exit: 2 });
|
|
21721
|
+
if (flags["idempotency-key"] !== void 0 && !IDEMPOTENCY_KEY_RE.test(flags["idempotency-key"].trim())) throw new Errors.CLIError("--idempotency-key must be 1 to 255 printable ASCII characters without spaces.", { exit: 2 });
|
|
21722
|
+
const detail = flags["detail-file"] !== void 0 ? readUtf8File(flags["detail-file"], "--detail-file") : flags.detail;
|
|
21723
|
+
if (detail !== void 0 && detail.length > 8e3) throw new Errors.CLIError("Detail must be at most 8000 characters.", { exit: 2 });
|
|
21724
|
+
const data = flags["data-file"] !== void 0 ? parseJsonObjectFlag(readUtf8File(flags["data-file"], "--data-file"), "--data-file") : flags.data !== void 0 ? parseJsonObjectFlag(flags.data, "--data") : void 0;
|
|
21725
|
+
const externalRef = buildExternalRef(flags);
|
|
21726
|
+
const runId = flags["run-id"] !== void 0 ? validateActivityRunId(flags["run-id"], "--run-id") : void 0;
|
|
21727
|
+
const traceUrl = flags["trace-url"] !== void 0 ? assertHttpUrl(flags["trace-url"], "--trace-url") : void 0;
|
|
21728
|
+
const body = {
|
|
21729
|
+
summary,
|
|
21730
|
+
...flags.kind ? { kind: flags.kind } : {},
|
|
21731
|
+
...flags.action ? { action: flags.action.trim() } : {},
|
|
21732
|
+
...flags.status ? { status: flags.status } : {},
|
|
21733
|
+
...detail !== void 0 ? { detail } : {},
|
|
21734
|
+
...sentEmailId ? { sent_email_id: sentEmailId } : {},
|
|
21735
|
+
...externalRef ? { external_ref: externalRef } : {},
|
|
21736
|
+
...data ? { data } : {},
|
|
21737
|
+
...runId ? { run_id: runId } : {},
|
|
21738
|
+
...traceUrl ? { trace_url: traceUrl } : {},
|
|
21739
|
+
...flags["idempotency-key"] ? { idempotency_key: flags["idempotency-key"].trim() } : {},
|
|
21740
|
+
...flags.visibility ? { visibility: flags.visibility } : {}
|
|
21741
|
+
};
|
|
21742
|
+
const path = threadId ? `/threads/${threadId}/activities` : `/emails/${emailId}/activities`;
|
|
21743
|
+
if (threadId && emailId) body.email_id = emailId;
|
|
21744
|
+
await runWithTiming(flags.time === true, async () => {
|
|
21745
|
+
const result = await callActivityApi({
|
|
21746
|
+
configDir: this.config.configDir,
|
|
21747
|
+
apiKey: flags["api-key"],
|
|
21748
|
+
apiBaseUrl: flags["api-base-url"],
|
|
21749
|
+
method: "POST",
|
|
21750
|
+
path,
|
|
21751
|
+
body
|
|
21752
|
+
});
|
|
21753
|
+
if (flags.json) {
|
|
21754
|
+
this.log(JSON.stringify(result.data, null, 2));
|
|
21755
|
+
return;
|
|
21756
|
+
}
|
|
21757
|
+
const a = result.data.activity;
|
|
21758
|
+
const verb = result.data.updated ? "Updated" : "Logged";
|
|
21759
|
+
this.log(`${verb} activity ${a.id} (rev ${a.revision}) [${a.status}] ${a.action} on thread ${a.thread_id}`);
|
|
21760
|
+
this.log(`Summary: ${a.summary}`);
|
|
21761
|
+
});
|
|
21762
|
+
}
|
|
21763
|
+
};
|
|
21764
|
+
var ActivityUpdateCommand = class ActivityUpdateCommand extends Command {
|
|
21765
|
+
static summary = "Update an existing thread activity (preserves status history)";
|
|
21766
|
+
static examples = [`<%= config.bin %> activity update <activity-id> --thread <thread-id> --status succeeded --summary "Verified invoice in Brex"`];
|
|
21767
|
+
static args = { activity_id: Args.string({
|
|
21768
|
+
description: "Activity UUID to update",
|
|
21769
|
+
required: true
|
|
21770
|
+
}) };
|
|
21771
|
+
static flags = {
|
|
21772
|
+
thread: Flags.string({
|
|
21773
|
+
description: "Thread UUID owning this activity",
|
|
21774
|
+
required: true
|
|
21775
|
+
}),
|
|
21776
|
+
status: Flags.string({
|
|
21777
|
+
description: "New status: started, succeeded, failed, skipped, or needs_review",
|
|
21778
|
+
options: [...ACTIVITY_STATUSES]
|
|
21779
|
+
}),
|
|
21780
|
+
summary: Flags.string({
|
|
21781
|
+
char: "s",
|
|
21782
|
+
description: "Updated summary (1 to 1000 chars)"
|
|
21783
|
+
}),
|
|
21784
|
+
detail: Flags.string({ description: "Updated detail text (up to 8000 chars)" }),
|
|
21785
|
+
"detail-file": Flags.string({ description: "Read updated detail text from a file" }),
|
|
21786
|
+
"clear-detail": Flags.boolean({ description: "Clear stored detail text (sets null)" }),
|
|
21787
|
+
"ref-system": Flags.string({ description: "External system name" }),
|
|
21788
|
+
"ref-id": Flags.string({ description: "External record ID" }),
|
|
21789
|
+
"ref-url": Flags.string({ description: "External record https:// URL" }),
|
|
21790
|
+
"ref-label": Flags.string({ description: "External record label" }),
|
|
21791
|
+
"external-ref": Flags.string({ description: "External reference JSON object" }),
|
|
21792
|
+
"clear-external-ref": Flags.boolean({ description: "Clear external_ref (sets null)" }),
|
|
21793
|
+
data: Flags.string({ description: "Replacement structured metadata JSON object" }),
|
|
21794
|
+
"data-file": Flags.string({ description: "Read replacement metadata JSON object from a file" }),
|
|
21795
|
+
"run-id": Flags.string({ description: "Updated run correlation ID" }),
|
|
21796
|
+
"clear-run-id": Flags.boolean({ description: "Clear run_id (sets null)" }),
|
|
21797
|
+
"trace-url": Flags.string({ description: "Updated https:// trace URL" }),
|
|
21798
|
+
"clear-trace-url": Flags.boolean({ description: "Clear trace_url (sets null)" }),
|
|
21799
|
+
visibility: Flags.string({
|
|
21800
|
+
description: "Updated visibility: thread or actor_only",
|
|
21801
|
+
options: [...ACTIVITY_VISIBILITIES]
|
|
21802
|
+
}),
|
|
21803
|
+
...COMMON_API_FLAGS
|
|
21804
|
+
};
|
|
21805
|
+
async run() {
|
|
21806
|
+
const { args, flags } = await this.parse(ActivityUpdateCommand);
|
|
21807
|
+
const activityId = assertUuid(args.activity_id, "activity_id");
|
|
21808
|
+
const threadId = assertUuid(flags.thread, "--thread");
|
|
21809
|
+
const body = {};
|
|
21810
|
+
if (flags.status) body.status = flags.status;
|
|
21811
|
+
if (flags.summary !== void 0) {
|
|
21812
|
+
const trimmed = flags.summary.trim();
|
|
21813
|
+
if (!trimmed || trimmed.length > 1e3) throw new Errors.CLIError("--summary must be 1 to 1000 characters.", { exit: 2 });
|
|
21814
|
+
body.summary = trimmed;
|
|
21815
|
+
}
|
|
21816
|
+
if (flags["detail-file"] !== void 0 && flags.detail !== void 0) throw new Errors.CLIError("Use either --detail or --detail-file, not both.", { exit: 2 });
|
|
21817
|
+
if (flags["clear-detail"] && (flags.detail !== void 0 || flags["detail-file"] !== void 0)) throw new Errors.CLIError("--clear-detail cannot be combined with --detail or --detail-file.", { exit: 2 });
|
|
21818
|
+
if (flags["clear-detail"]) body.detail = null;
|
|
21819
|
+
else if (flags["detail-file"] !== void 0 || flags.detail !== void 0) {
|
|
21820
|
+
const detailText = flags["detail-file"] !== void 0 ? readUtf8File(flags["detail-file"], "--detail-file") : flags.detail ?? "";
|
|
21821
|
+
if (detailText.length > 8e3) throw new Errors.CLIError("Detail must be at most 8000 characters.", { exit: 2 });
|
|
21822
|
+
body.detail = detailText;
|
|
21823
|
+
}
|
|
21824
|
+
const hasExternalRefFlag = flags["external-ref"] !== void 0 || flags["ref-system"] !== void 0 || flags["ref-id"] !== void 0 || flags["ref-url"] !== void 0 || flags["ref-label"] !== void 0;
|
|
21825
|
+
if (flags["clear-external-ref"] && hasExternalRefFlag) throw new Errors.CLIError("--clear-external-ref cannot be combined with --external-ref or --ref-* flags.", { exit: 2 });
|
|
21826
|
+
if (flags["clear-external-ref"]) body.external_ref = null;
|
|
21827
|
+
else {
|
|
21828
|
+
const ref = buildExternalRef(flags);
|
|
21829
|
+
if (ref) body.external_ref = ref;
|
|
21830
|
+
}
|
|
21831
|
+
if (flags["data-file"] !== void 0 && flags.data !== void 0) throw new Errors.CLIError("Use either --data or --data-file, not both.", { exit: 2 });
|
|
21832
|
+
if (flags["data-file"] !== void 0) body.data = parseJsonObjectFlag(readUtf8File(flags["data-file"], "--data-file"), "--data-file");
|
|
21833
|
+
else if (flags.data !== void 0) body.data = parseJsonObjectFlag(flags.data, "--data");
|
|
21834
|
+
if (flags["clear-run-id"] && flags["run-id"] !== void 0) throw new Errors.CLIError("--clear-run-id cannot be combined with --run-id.", { exit: 2 });
|
|
21835
|
+
if (flags["clear-run-id"]) body.run_id = null;
|
|
21836
|
+
else if (flags["run-id"] !== void 0) body.run_id = validateActivityRunId(flags["run-id"], "--run-id");
|
|
21837
|
+
if (flags["clear-trace-url"] && flags["trace-url"] !== void 0) throw new Errors.CLIError("--clear-trace-url cannot be combined with --trace-url.", { exit: 2 });
|
|
21838
|
+
if (flags["clear-trace-url"]) body.trace_url = null;
|
|
21839
|
+
else if (flags["trace-url"] !== void 0) body.trace_url = assertHttpUrl(flags["trace-url"], "--trace-url");
|
|
21840
|
+
if (flags.visibility) body.visibility = flags.visibility;
|
|
21841
|
+
if (Object.keys(body).length === 0) throw new Errors.CLIError("Provide at least one field to update.", { exit: 2 });
|
|
21842
|
+
await runWithTiming(flags.time === true, async () => {
|
|
21843
|
+
const result = await callActivityApi({
|
|
21844
|
+
configDir: this.config.configDir,
|
|
21845
|
+
apiKey: flags["api-key"],
|
|
21846
|
+
apiBaseUrl: flags["api-base-url"],
|
|
21847
|
+
method: "PATCH",
|
|
21848
|
+
path: `/threads/${threadId}/activities/${activityId}`,
|
|
21849
|
+
body
|
|
21850
|
+
});
|
|
21851
|
+
if (flags.json) {
|
|
21852
|
+
this.log(JSON.stringify(result.data, null, 2));
|
|
21853
|
+
return;
|
|
21854
|
+
}
|
|
21855
|
+
const a = result.data.activity;
|
|
21856
|
+
this.log(`Updated activity ${a.id} (rev ${a.revision}) [${a.status}] ${a.action}: ${a.summary}`);
|
|
21857
|
+
});
|
|
21858
|
+
}
|
|
21859
|
+
};
|
|
21860
|
+
var ActivityTimelineCommand = class ActivityTimelineCommand extends Command {
|
|
21861
|
+
static summary = "Show the merged timeline of verified Primitive actions and agent work for a thread";
|
|
21862
|
+
static examples = ["<%= config.bin %> activity timeline <thread-id>", "<%= config.bin %> activity timeline <thread-id> --source agent --json"];
|
|
21863
|
+
static args = { thread_id: Args.string({
|
|
21864
|
+
description: "Thread UUID to inspect",
|
|
21865
|
+
required: true
|
|
21866
|
+
}) };
|
|
21867
|
+
static flags = {
|
|
21868
|
+
source: Flags.string({
|
|
21869
|
+
description: "Filter by source: all (default), primitive, or agent",
|
|
21870
|
+
options: [...TIMELINE_SOURCES],
|
|
21871
|
+
default: "all"
|
|
21872
|
+
}),
|
|
21873
|
+
kind: Flags.string({
|
|
21874
|
+
description: "Filter agent entries by kind: action, note, or handoff",
|
|
21875
|
+
options: [...ACTIVITY_KINDS]
|
|
21876
|
+
}),
|
|
21877
|
+
status: Flags.string({ description: "Comma-separated status filter (for example failed,needs_review)" }),
|
|
21878
|
+
attention: Flags.boolean({ description: "Limit to failed and needs_review agent activities" }),
|
|
21879
|
+
action: Flags.string({ description: "Exact action name filter" }),
|
|
21880
|
+
"actor-ownership": Flags.string({
|
|
21881
|
+
description: "Filter by actor ownership class",
|
|
21882
|
+
options: [...ACTIVITY_OWNERSHIPS]
|
|
21883
|
+
}),
|
|
21884
|
+
"actor-id": Flags.string({ description: "Filter by specific actor UUID" }),
|
|
21885
|
+
"run-id": Flags.string({ description: "Filter by run_id" }),
|
|
21886
|
+
"include-private": Flags.boolean({ description: "Include other actors' actor_only rows (requires activity:read)" }),
|
|
21887
|
+
order: Flags.string({
|
|
21888
|
+
description: "Sort order: desc (default) or asc",
|
|
21889
|
+
options: ["desc", "asc"],
|
|
21890
|
+
default: "desc"
|
|
21891
|
+
}),
|
|
21892
|
+
limit: Flags.integer({
|
|
21893
|
+
description: "Items per page (1 to 200)",
|
|
21894
|
+
min: 1,
|
|
21895
|
+
max: 200,
|
|
21896
|
+
default: 50
|
|
21897
|
+
}),
|
|
21898
|
+
cursor: Flags.string({ description: "Pagination cursor from a previous response" }),
|
|
21899
|
+
...COMMON_API_FLAGS
|
|
21900
|
+
};
|
|
21901
|
+
async run() {
|
|
21902
|
+
const { args, flags } = await this.parse(ActivityTimelineCommand);
|
|
21903
|
+
const threadId = assertUuid(args.thread_id, "thread_id");
|
|
21904
|
+
const status = flags.status !== void 0 ? validateStatusCsv(flags.status) : void 0;
|
|
21905
|
+
const actorId = flags["actor-id"] !== void 0 ? assertUuid(flags["actor-id"], "--actor-id") : void 0;
|
|
21906
|
+
await runWithTiming(flags.time === true, async () => {
|
|
21907
|
+
const result = await callActivityApi({
|
|
21908
|
+
configDir: this.config.configDir,
|
|
21909
|
+
apiKey: flags["api-key"],
|
|
21910
|
+
apiBaseUrl: flags["api-base-url"],
|
|
21911
|
+
method: "GET",
|
|
21912
|
+
path: `/threads/${threadId}/timeline`,
|
|
21913
|
+
query: {
|
|
21914
|
+
source: flags.source,
|
|
21915
|
+
kind: flags.kind,
|
|
21916
|
+
status,
|
|
21917
|
+
attention: flags.attention ? "true" : void 0,
|
|
21918
|
+
action: flags.action,
|
|
21919
|
+
actor_ownership: flags["actor-ownership"],
|
|
21920
|
+
actor_id: actorId,
|
|
21921
|
+
run_id: flags["run-id"],
|
|
21922
|
+
include_private: flags["include-private"] ? "true" : void 0,
|
|
21923
|
+
order: flags.order,
|
|
21924
|
+
limit: flags.limit,
|
|
21925
|
+
cursor: flags.cursor
|
|
21926
|
+
}
|
|
21927
|
+
});
|
|
21928
|
+
if (flags.json) {
|
|
21929
|
+
this.log(JSON.stringify(result.data, null, 2));
|
|
21930
|
+
return;
|
|
21931
|
+
}
|
|
21932
|
+
if (result.data.items.length === 0) {
|
|
21933
|
+
this.log(`No activity recorded for thread ${threadId}.`);
|
|
21934
|
+
return;
|
|
21935
|
+
}
|
|
21936
|
+
for (const item of result.data.items) this.log(formatTimelineItemLine(item));
|
|
21937
|
+
if (result.data.next_cursor) process.stderr.write(`Next page: --cursor ${result.data.next_cursor}\n`);
|
|
21938
|
+
});
|
|
21939
|
+
}
|
|
21940
|
+
};
|
|
21941
|
+
var ActivityListCommand = class ActivityListCommand extends Command {
|
|
21942
|
+
static summary = "Search verified mail actions and agent work across threads in your scope";
|
|
21943
|
+
static examples = [
|
|
21944
|
+
"<%= config.bin %> activity list --attention",
|
|
21945
|
+
"<%= config.bin %> activity list --actor-ownership personal_agent --limit 25",
|
|
21946
|
+
"<%= config.bin %> activity list --run-id run_123 --json",
|
|
21947
|
+
"<%= config.bin %> activity list --format csv > mail-activity.csv"
|
|
21948
|
+
];
|
|
21949
|
+
static flags = {
|
|
21950
|
+
source: Flags.string({
|
|
21951
|
+
description: "Filter by source: all (default), primitive, or agent",
|
|
21952
|
+
options: [...TIMELINE_SOURCES],
|
|
21953
|
+
default: "all"
|
|
21954
|
+
}),
|
|
21955
|
+
thread: Flags.string({ description: "Filter to a thread UUID" }),
|
|
21956
|
+
email: Flags.string({ description: "Filter to an inbound email UUID" }),
|
|
21957
|
+
"sent-email": Flags.string({ description: "Filter to an outbound email UUID" }),
|
|
21958
|
+
kind: Flags.string({
|
|
21959
|
+
description: "Filter agent entries by kind: action, note, or handoff",
|
|
21960
|
+
options: [...ACTIVITY_KINDS]
|
|
21961
|
+
}),
|
|
21962
|
+
status: Flags.string({ description: "Comma-separated status filter" }),
|
|
21963
|
+
attention: Flags.boolean({ description: "Limit to failed and needs_review agent activities" }),
|
|
21964
|
+
action: Flags.string({ description: "Exact action name filter" }),
|
|
21965
|
+
"actor-kind": Flags.string({ description: "Filter by actor kind" }),
|
|
21966
|
+
"actor-ownership": Flags.string({
|
|
21967
|
+
description: "Filter by actor ownership class",
|
|
21968
|
+
options: [...ACTIVITY_OWNERSHIPS]
|
|
21969
|
+
}),
|
|
21970
|
+
"actor-id": Flags.string({ description: "Filter by actor UUID" }),
|
|
21971
|
+
"owner-user-id": Flags.string({ description: "Filter by human owner user UUID" }),
|
|
21972
|
+
"oauth-client-id": Flags.string({ description: "Filter by OAuth client ID" }),
|
|
21973
|
+
"run-id": Flags.string({ description: "Filter by run_id" }),
|
|
21974
|
+
"include-private": Flags.boolean({ description: "Include other actors' actor_only rows (requires activity:read)" }),
|
|
21975
|
+
since: Flags.string({ description: "ISO-8601 lower bound timestamp" }),
|
|
21976
|
+
until: Flags.string({ description: "ISO-8601 upper bound timestamp" }),
|
|
21977
|
+
format: Flags.string({
|
|
21978
|
+
description: "Output format: json (default) or csv",
|
|
21979
|
+
options: ["json", "csv"],
|
|
21980
|
+
default: "json"
|
|
21981
|
+
}),
|
|
21982
|
+
limit: Flags.integer({
|
|
21983
|
+
description: "Items per page (1 to 200)",
|
|
21984
|
+
min: 1,
|
|
21985
|
+
max: 200,
|
|
21986
|
+
default: 50
|
|
21987
|
+
}),
|
|
21988
|
+
cursor: Flags.string({ description: "Pagination cursor" }),
|
|
21989
|
+
...COMMON_API_FLAGS
|
|
21990
|
+
};
|
|
21991
|
+
async run() {
|
|
21992
|
+
const { flags } = await this.parse(ActivityListCommand);
|
|
21993
|
+
if (flags.format === "csv" && flags.json) throw new Errors.CLIError("Cannot combine --format csv with --json.", { exit: 2 });
|
|
21994
|
+
const status = flags.status !== void 0 ? validateStatusCsv(flags.status) : void 0;
|
|
21995
|
+
const query = {
|
|
21996
|
+
source: flags.source,
|
|
21997
|
+
thread_id: flags.thread !== void 0 ? assertUuid(flags.thread, "--thread") : void 0,
|
|
21998
|
+
email_id: flags.email !== void 0 ? assertUuid(flags.email, "--email") : void 0,
|
|
21999
|
+
sent_email_id: flags["sent-email"] !== void 0 ? assertUuid(flags["sent-email"], "--sent-email") : void 0,
|
|
22000
|
+
kind: flags.kind,
|
|
22001
|
+
status,
|
|
22002
|
+
attention: flags.attention ? "true" : void 0,
|
|
22003
|
+
action: flags.action,
|
|
22004
|
+
actor_kind: flags["actor-kind"],
|
|
22005
|
+
actor_ownership: flags["actor-ownership"],
|
|
22006
|
+
actor_id: flags["actor-id"] !== void 0 ? assertUuid(flags["actor-id"], "--actor-id") : void 0,
|
|
22007
|
+
owner_user_id: flags["owner-user-id"] !== void 0 ? assertUuid(flags["owner-user-id"], "--owner-user-id") : void 0,
|
|
22008
|
+
oauth_client_id: flags["oauth-client-id"],
|
|
22009
|
+
run_id: flags["run-id"],
|
|
22010
|
+
include_private: flags["include-private"] ? "true" : void 0,
|
|
22011
|
+
since: flags.since,
|
|
22012
|
+
until: flags.until,
|
|
22013
|
+
format: flags.format,
|
|
22014
|
+
limit: flags.limit,
|
|
22015
|
+
cursor: flags.cursor
|
|
22016
|
+
};
|
|
22017
|
+
await runWithTiming(flags.time === true, async () => {
|
|
22018
|
+
if (flags.format === "csv") {
|
|
22019
|
+
const result = await callActivityApi({
|
|
22020
|
+
configDir: this.config.configDir,
|
|
22021
|
+
apiKey: flags["api-key"],
|
|
22022
|
+
apiBaseUrl: flags["api-base-url"],
|
|
22023
|
+
method: "GET",
|
|
22024
|
+
path: "/activity/mail",
|
|
22025
|
+
query,
|
|
22026
|
+
rawText: true
|
|
22027
|
+
});
|
|
22028
|
+
process.stdout.write(result.text ?? "");
|
|
22029
|
+
const nextCursor = result.headers.get("x-next-cursor");
|
|
22030
|
+
if (nextCursor) process.stderr.write(`Next page: --cursor ${nextCursor}\n`);
|
|
22031
|
+
return;
|
|
22032
|
+
}
|
|
22033
|
+
const result = await callActivityApi({
|
|
22034
|
+
configDir: this.config.configDir,
|
|
22035
|
+
apiKey: flags["api-key"],
|
|
22036
|
+
apiBaseUrl: flags["api-base-url"],
|
|
22037
|
+
method: "GET",
|
|
22038
|
+
path: "/activity/mail",
|
|
22039
|
+
query
|
|
22040
|
+
});
|
|
22041
|
+
if (flags.json) {
|
|
22042
|
+
this.log(JSON.stringify(result.data, null, 2));
|
|
22043
|
+
return;
|
|
22044
|
+
}
|
|
22045
|
+
if (result.data.items.length === 0) {
|
|
22046
|
+
this.log("No mail activity matched these filters within your scope.");
|
|
22047
|
+
return;
|
|
22048
|
+
}
|
|
22049
|
+
for (const item of result.data.items) this.log(formatTimelineItemLine(item));
|
|
22050
|
+
if (result.data.next_cursor) process.stderr.write(`Next page: --cursor ${result.data.next_cursor}\n`);
|
|
22051
|
+
});
|
|
22052
|
+
}
|
|
22053
|
+
};
|
|
22054
|
+
var ActivityAgentsCommand = class ActivityAgentsCommand extends Command {
|
|
22055
|
+
static summary = "List deployed agents, keys, Functions, and apps with mail activity rollups";
|
|
22056
|
+
static examples = ["<%= config.bin %> activity agents", "<%= config.bin %> activity agents --actor-ownership personal_agent --json"];
|
|
22057
|
+
static flags = {
|
|
22058
|
+
"actor-ownership": Flags.string({
|
|
22059
|
+
description: "Filter by actor ownership class",
|
|
22060
|
+
options: [...ACTIVITY_OWNERSHIPS]
|
|
22061
|
+
}),
|
|
22062
|
+
"owner-user-id": Flags.string({ description: "Filter by human owner user UUID" }),
|
|
22063
|
+
"include-private": Flags.boolean({ description: "Include other actors' actor_only work (requires activity:read)" }),
|
|
22064
|
+
since: Flags.string({ description: "ISO-8601 lower bound timestamp" }),
|
|
22065
|
+
until: Flags.string({ description: "ISO-8601 upper bound timestamp" }),
|
|
22066
|
+
limit: Flags.integer({
|
|
22067
|
+
description: "Maximum actors to return (1 to 100)",
|
|
22068
|
+
min: 1,
|
|
22069
|
+
max: 100,
|
|
22070
|
+
default: 50
|
|
22071
|
+
}),
|
|
22072
|
+
...COMMON_API_FLAGS
|
|
22073
|
+
};
|
|
22074
|
+
async run() {
|
|
22075
|
+
const { flags } = await this.parse(ActivityAgentsCommand);
|
|
22076
|
+
const ownerUserId = flags["owner-user-id"] !== void 0 ? assertUuid(flags["owner-user-id"], "--owner-user-id") : void 0;
|
|
22077
|
+
await runWithTiming(flags.time === true, async () => {
|
|
22078
|
+
const result = await callActivityApi({
|
|
22079
|
+
configDir: this.config.configDir,
|
|
22080
|
+
apiKey: flags["api-key"],
|
|
22081
|
+
apiBaseUrl: flags["api-base-url"],
|
|
22082
|
+
method: "GET",
|
|
22083
|
+
path: "/activity/mail/actors",
|
|
22084
|
+
query: {
|
|
22085
|
+
actor_ownership: flags["actor-ownership"],
|
|
22086
|
+
owner_user_id: ownerUserId,
|
|
22087
|
+
include_private: flags["include-private"] ? "true" : void 0,
|
|
22088
|
+
since: flags.since,
|
|
22089
|
+
until: flags.until,
|
|
22090
|
+
limit: flags.limit
|
|
22091
|
+
}
|
|
22092
|
+
});
|
|
22093
|
+
if (flags.json) {
|
|
22094
|
+
this.log(JSON.stringify(result.data, null, 2));
|
|
22095
|
+
return;
|
|
22096
|
+
}
|
|
22097
|
+
if (result.data.actors.length === 0) {
|
|
22098
|
+
this.log("No agents or keys have recorded mail activity in your scope.");
|
|
22099
|
+
return;
|
|
22100
|
+
}
|
|
22101
|
+
for (const entry of result.data.actors) {
|
|
22102
|
+
const who = formatActorLabel(entry.actor);
|
|
22103
|
+
const rollup = `threads=${entry.threads_touched} verified=${entry.verified_events} work=${entry.work_total} (ok=${entry.work_succeeded} fail=${entry.work_failed} review=${entry.work_needs_review})`;
|
|
22104
|
+
const actions = entry.recent_actions.length > 0 ? ` | actions: ${entry.recent_actions.join(", ")}` : "";
|
|
22105
|
+
this.log(`${who} | ${rollup} | last=${entry.last_active_at}${actions}`);
|
|
22106
|
+
}
|
|
22107
|
+
});
|
|
22108
|
+
}
|
|
22109
|
+
};
|
|
22110
|
+
// src/oclif/commands/memories.ts
|
|
22111
|
+
var MemoryCliInputError = class extends Error {};
|
|
22112
|
+
const API_KEY_FLAG = Flags.string({
|
|
22113
|
+
description: "Primitive API key override (defaults to PRIMITIVE_API_KEY or saved OAuth login credentials)",
|
|
22114
|
+
env: "PRIMITIVE_API_KEY"
|
|
22115
|
+
});
|
|
22116
|
+
const API_BASE_URL_FLAG$1 = Flags.string({
|
|
22117
|
+
description: API_BASE_URL_FLAG_DESCRIPTION,
|
|
22118
|
+
env: "PRIMITIVE_API_BASE_URL",
|
|
22119
|
+
hidden: true
|
|
22120
|
+
});
|
|
22121
|
+
const SCOPE_FLAGS = {
|
|
22122
|
+
function: Flags.string({
|
|
22123
|
+
description: "Function id (UUID) to scope this memory to. Function names are not accepted.",
|
|
22124
|
+
exclusive: ["org"]
|
|
22125
|
+
}),
|
|
22126
|
+
org: Flags.boolean({
|
|
22127
|
+
description: "Force org scope. Outside a function-authenticated request this is already the default.",
|
|
22128
|
+
exclusive: ["function"]
|
|
22129
|
+
})
|
|
22130
|
+
};
|
|
22131
|
+
function reportMemoryError(error, context) {
|
|
22132
|
+
const payload = extractErrorPayload(error);
|
|
22133
|
+
writeErrorWithHints(payload);
|
|
22134
|
+
surfaceUnauthorizedHint({
|
|
22135
|
+
...context,
|
|
22136
|
+
payload
|
|
22137
|
+
});
|
|
22138
|
+
process.exitCode = 1;
|
|
22139
|
+
}
|
|
22140
|
+
function printData(command, responseData) {
|
|
22141
|
+
const data = responseData?.data ?? null;
|
|
22142
|
+
command.log(JSON.stringify(data, null, 2));
|
|
22143
|
+
}
|
|
22144
|
+
const CONTROL_CHARACTERS$1 = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}]`);
|
|
22145
|
+
/**
|
|
22146
|
+
* The stderr line naming the next page's cursor. A memory key can hold a line
|
|
22147
|
+
* break or another control character, which would split or garble the line,
|
|
22148
|
+
* so such a cursor is printed JSON-encoded, with a note on how to pass it.
|
|
22149
|
+
*/
|
|
22150
|
+
function nextCursorLine(cursor) {
|
|
22151
|
+
if (!CONTROL_CHARACTERS$1.test(cursor)) return `next cursor: ${cursor}\n`;
|
|
22152
|
+
return `next cursor (JSON-encoded, it holds control characters; decode it before passing it to --cursor, or read meta.cursor with --json): ${JSON.stringify(cursor)}\n`;
|
|
22153
|
+
}
|
|
22154
|
+
function handleMemoryInputError(error) {
|
|
22155
|
+
if (!(error instanceof MemoryCliInputError)) return false;
|
|
22156
|
+
process.stderr.write(`${error.message}\n`);
|
|
22157
|
+
process.exitCode = 1;
|
|
22158
|
+
return true;
|
|
22159
|
+
}
|
|
22160
|
+
function nonEmptyFlag(value, name) {
|
|
22161
|
+
if (value === void 0) return void 0;
|
|
22162
|
+
if (value.trim().length === 0) throw new MemoryCliInputError(`${name} must be a non-empty string.`);
|
|
22163
|
+
return value;
|
|
22164
|
+
}
|
|
22165
|
+
function parseMemoryJson(source, label = "value") {
|
|
22166
|
+
try {
|
|
22167
|
+
const value = JSON.parse(source);
|
|
22168
|
+
if (!isMemoryJsonValue(value)) return {
|
|
22169
|
+
kind: "error",
|
|
22170
|
+
message: `${label} must be valid JSON. Numbers must be finite, arrays must not be sparse, and values may not contain undefined, bigint, symbol, function, class instance, or cyclic entries.`
|
|
22171
|
+
};
|
|
22172
|
+
return {
|
|
22173
|
+
kind: "ok",
|
|
22174
|
+
value
|
|
22175
|
+
};
|
|
22176
|
+
} catch (error) {
|
|
22177
|
+
return {
|
|
22178
|
+
kind: "error",
|
|
22179
|
+
message: `${label} must be valid JSON. Quote strings as JSON strings, for example '"hello"'. ${error instanceof Error ? error.message : String(error)}`
|
|
22180
|
+
};
|
|
22181
|
+
}
|
|
22182
|
+
}
|
|
22183
|
+
function resolveMemoryValueSource(input) {
|
|
22184
|
+
if (input.value !== void 0 && input.valueFile !== void 0) return {
|
|
22185
|
+
kind: "error",
|
|
22186
|
+
message: "Provide the JSON value as either an argument or --value-file, not both."
|
|
22187
|
+
};
|
|
22188
|
+
if (input.value !== void 0) return {
|
|
22189
|
+
kind: "ok",
|
|
22190
|
+
source: input.value,
|
|
22191
|
+
label: "value"
|
|
22192
|
+
};
|
|
22193
|
+
if (input.valueFile !== void 0) try {
|
|
22194
|
+
return {
|
|
22195
|
+
kind: "ok",
|
|
22196
|
+
source: input.readFile ? input.readFile(input.valueFile) : readTextFileFlag(input.valueFile, "--value-file"),
|
|
22197
|
+
label: `--value-file ${input.valueFile}`
|
|
22198
|
+
};
|
|
22199
|
+
} catch (error) {
|
|
22200
|
+
return {
|
|
22201
|
+
kind: "error",
|
|
22202
|
+
message: error instanceof Error ? error.message : String(error)
|
|
22203
|
+
};
|
|
22204
|
+
}
|
|
22205
|
+
return {
|
|
22206
|
+
kind: "error",
|
|
22207
|
+
message: "Provide a JSON value argument or --value-file."
|
|
22208
|
+
};
|
|
22209
|
+
}
|
|
22210
|
+
function memoryScopeForBody(flags) {
|
|
22211
|
+
const functionId = nonEmptyFlag(flags.function, "--function");
|
|
21300
22212
|
if (functionId !== void 0) return {
|
|
21301
22213
|
type: "function",
|
|
21302
22214
|
id: functionId
|
|
@@ -25521,6 +26433,667 @@ var OtpResendCommand = class extends SigninOtpResendCommand {
|
|
|
25521
26433
|
return OTP_COPY;
|
|
25522
26434
|
}
|
|
25523
26435
|
};
|
|
26436
|
+
// src/oclif/skill-installer.ts
|
|
26437
|
+
const DEFAULT_LIVE_SKILL_NAME = "primitive";
|
|
26438
|
+
const SKILL_META_FILENAME = ".primitive-skill.json";
|
|
26439
|
+
const SKILL_ETAG_RE = /^[A-Za-z0-9._-]{1,128}$/;
|
|
26440
|
+
const MAX_SKILL_BYTES = 2097152;
|
|
26441
|
+
const MAX_META_BYTES = 65536;
|
|
26442
|
+
const SKILL_TARGETS = [
|
|
26443
|
+
"claude",
|
|
26444
|
+
"codex",
|
|
26445
|
+
"antigravity",
|
|
26446
|
+
"cursor",
|
|
26447
|
+
"openclaw",
|
|
26448
|
+
"agents"
|
|
26449
|
+
];
|
|
26450
|
+
const SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
26451
|
+
function validateSkillName(raw) {
|
|
26452
|
+
const trimmed = raw.trim().toLowerCase();
|
|
26453
|
+
if (!SKILL_NAME_RE.test(trimmed)) throw new Errors.CLIError("--name must be 1 to 63 lowercase letters, digits, or hyphens (starting with a letter or digit).", { exit: 2 });
|
|
26454
|
+
if (trimmed === "primitive-connect") throw new Errors.CLIError(`--name cannot be "${CONNECT_SKILL_NAME}", which is reserved for the bundled connection skill.`, { exit: 2 });
|
|
26455
|
+
return trimmed;
|
|
26456
|
+
}
|
|
26457
|
+
function userHome(env) {
|
|
26458
|
+
return env.HOME?.trim() || homedir();
|
|
26459
|
+
}
|
|
26460
|
+
function targetRootDir(target, options) {
|
|
26461
|
+
const home = userHome(options.env);
|
|
26462
|
+
if (options.project) switch (target) {
|
|
26463
|
+
case "claude": return join(options.cwd, ".claude", "skills");
|
|
26464
|
+
case "cursor": return join(options.cwd, ".cursor", "skills");
|
|
26465
|
+
case "openclaw": return join(options.cwd, "skills");
|
|
26466
|
+
case "codex":
|
|
26467
|
+
case "antigravity":
|
|
26468
|
+
case "agents": return join(options.cwd, ".agents", "skills");
|
|
26469
|
+
}
|
|
26470
|
+
switch (target) {
|
|
26471
|
+
case "claude": return join(resolve(options.env.CLAUDE_CONFIG_DIR || join(home, ".claude")), "skills");
|
|
26472
|
+
case "codex": return join(resolve(options.env.CODEX_HOME || join(home, ".codex")), "skills");
|
|
26473
|
+
case "antigravity": return join(home, ".gemini", "config", "skills");
|
|
26474
|
+
case "cursor": return join(home, ".cursor", "skills");
|
|
26475
|
+
case "openclaw": return join(home, ".openclaw", "skills");
|
|
26476
|
+
case "agents": return join(home, ".agents", "skills");
|
|
26477
|
+
}
|
|
26478
|
+
}
|
|
26479
|
+
function detectSkillTargets(options) {
|
|
26480
|
+
const env = options.env ?? process.env;
|
|
26481
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
26482
|
+
const home = userHome(env);
|
|
26483
|
+
const found = [];
|
|
26484
|
+
if (options.project) {
|
|
26485
|
+
found.push("agents");
|
|
26486
|
+
if (existsSync(join(cwd, ".claude"))) found.push("claude");
|
|
26487
|
+
if (existsSync(join(cwd, ".cursor"))) found.push("cursor");
|
|
26488
|
+
return found;
|
|
26489
|
+
}
|
|
26490
|
+
if (env.CLAUDE_CODE_SESSION_ID || existsSync(resolve(env.CLAUDE_CONFIG_DIR || join(home, ".claude")))) found.push("claude");
|
|
26491
|
+
if (env.CODEX_THREAD_ID || env.CODEX_SESSION_ID || existsSync(resolve(env.CODEX_HOME || join(home, ".codex")))) found.push("codex");
|
|
26492
|
+
if (existsSync(join(home, ".gemini", "config"))) found.push("antigravity");
|
|
26493
|
+
if (existsSync(join(home, ".cursor"))) found.push("cursor");
|
|
26494
|
+
if (existsSync(join(home, ".openclaw"))) found.push("openclaw");
|
|
26495
|
+
if (found.length === 0 || existsSync(join(home, ".agents"))) found.push("agents");
|
|
26496
|
+
return found;
|
|
26497
|
+
}
|
|
26498
|
+
function parseTargetSelectors(rawTargets) {
|
|
26499
|
+
if (!rawTargets || rawTargets.length === 0) return ["auto"];
|
|
26500
|
+
const valid = /* @__PURE__ */ new Set([
|
|
26501
|
+
...SKILL_TARGETS,
|
|
26502
|
+
"auto",
|
|
26503
|
+
"all"
|
|
26504
|
+
]);
|
|
26505
|
+
const out = [];
|
|
26506
|
+
for (const item of rawTargets) for (const part of item.split(",")) {
|
|
26507
|
+
const normalized = part.trim().toLowerCase();
|
|
26508
|
+
if (!normalized) continue;
|
|
26509
|
+
if (!valid.has(normalized)) throw new Errors.CLIError(`Unknown --target "${part.trim()}". Use one of: auto, all, ${SKILL_TARGETS.join(", ")}.`, { exit: 2 });
|
|
26510
|
+
out.push(normalized);
|
|
26511
|
+
}
|
|
26512
|
+
return out.length > 0 ? out : ["auto"];
|
|
26513
|
+
}
|
|
26514
|
+
function resolveSkillTargets(options) {
|
|
26515
|
+
const env = options.env ?? process.env;
|
|
26516
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
26517
|
+
const project = Boolean(options.project);
|
|
26518
|
+
const name = validateSkillName(options.name ?? "primitive");
|
|
26519
|
+
if (options.out !== void 0) {
|
|
26520
|
+
if (!options.out.trim()) throw new Errors.CLIError("--out must be a non-empty path.", { exit: 2 });
|
|
26521
|
+
const resolvedOut = resolve(cwd, options.out);
|
|
26522
|
+
const base = basename(resolvedOut);
|
|
26523
|
+
const hasTrailingSep = /[\\/]$/.test(options.out.trim());
|
|
26524
|
+
const existingDir = (() => {
|
|
26525
|
+
try {
|
|
26526
|
+
return lstatSync(resolvedOut).isDirectory();
|
|
26527
|
+
} catch {
|
|
26528
|
+
return false;
|
|
26529
|
+
}
|
|
26530
|
+
})();
|
|
26531
|
+
const ext = extname(base);
|
|
26532
|
+
const isFilePath = !hasTrailingSep && !existingDir && (base.toLowerCase() === "skill.md" || ext.length > 1 && !base.startsWith("."));
|
|
26533
|
+
const directory = isFilePath ? dirname(resolvedOut) : resolvedOut;
|
|
26534
|
+
if (basename(directory).toLowerCase() === "primitive-connect" || isFilePath && base.toLowerCase() === `primitive-connect.md`) throw new Errors.CLIError(`Refusing to write into "${CONNECT_SKILL_NAME}", which is reserved for the bundled connection skill.`, { exit: 2 });
|
|
26535
|
+
const filePath = isFilePath ? resolvedOut : join(resolvedOut, "SKILL.md");
|
|
26536
|
+
const home = resolve(userHome(env));
|
|
26537
|
+
const matchedHomeRoot = SKILL_TARGETS.map((t) => targetRootDir(t, {
|
|
26538
|
+
project: false,
|
|
26539
|
+
cwd,
|
|
26540
|
+
env
|
|
26541
|
+
})).find((rootDir) => isSubpath(rootDir, directory));
|
|
26542
|
+
const boundary = matchedHomeRoot ? matchedHomeRoot : isSubpath(cwd, directory) ? cwd : isSubpath(home, directory) ? home : dirname(directory);
|
|
26543
|
+
return [{
|
|
26544
|
+
target: "custom",
|
|
26545
|
+
directory,
|
|
26546
|
+
filePath,
|
|
26547
|
+
metaPath: join(directory, SKILL_META_FILENAME),
|
|
26548
|
+
boundary
|
|
26549
|
+
}];
|
|
26550
|
+
}
|
|
26551
|
+
const selectors = parseTargetSelectors(options.targets);
|
|
26552
|
+
const expanded = [];
|
|
26553
|
+
for (const selector of selectors) if (selector === "auto") expanded.push(...detectSkillTargets({
|
|
26554
|
+
project,
|
|
26555
|
+
cwd,
|
|
26556
|
+
env
|
|
26557
|
+
}));
|
|
26558
|
+
else if (selector === "all") expanded.push(...SKILL_TARGETS);
|
|
26559
|
+
else expanded.push(selector);
|
|
26560
|
+
const deduped = [];
|
|
26561
|
+
const seenDirs = /* @__PURE__ */ new Set();
|
|
26562
|
+
for (const target of expanded) {
|
|
26563
|
+
const rootDir = targetRootDir(target, {
|
|
26564
|
+
project,
|
|
26565
|
+
cwd,
|
|
26566
|
+
env
|
|
26567
|
+
});
|
|
26568
|
+
const directory = join(rootDir, name);
|
|
26569
|
+
if (seenDirs.has(directory)) continue;
|
|
26570
|
+
seenDirs.add(directory);
|
|
26571
|
+
const boundary = project ? cwd : rootDir;
|
|
26572
|
+
deduped.push({
|
|
26573
|
+
target,
|
|
26574
|
+
directory,
|
|
26575
|
+
filePath: join(directory, "SKILL.md"),
|
|
26576
|
+
metaPath: join(directory, SKILL_META_FILENAME),
|
|
26577
|
+
boundary
|
|
26578
|
+
});
|
|
26579
|
+
}
|
|
26580
|
+
return deduped;
|
|
26581
|
+
}
|
|
26582
|
+
function isSubpath(parent, child) {
|
|
26583
|
+
const rel = relative(parent, child);
|
|
26584
|
+
return rel !== "" && !rel.startsWith("..") && !rel.includes(`..${sep}`);
|
|
26585
|
+
}
|
|
26586
|
+
function sha256Text(content) {
|
|
26587
|
+
return createHash("sha256").update(content, "utf8").digest("hex");
|
|
26588
|
+
}
|
|
26589
|
+
function assertNoSymlinkAncestors(targetDir, boundary) {
|
|
26590
|
+
const resolvedDir = resolve(targetDir);
|
|
26591
|
+
const start = boundary && isSubpath(resolve(boundary), resolvedDir) ? resolve(boundary) : dirname(resolvedDir);
|
|
26592
|
+
try {
|
|
26593
|
+
if (!statSync(start).isDirectory()) throw new Errors.CLIError(`Expected directory at ${start}, found a non-directory entry.`, { exit: 1 });
|
|
26594
|
+
} catch (error) {
|
|
26595
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") try {
|
|
26596
|
+
if (lstatSync(start).isSymbolicLink()) throw new Errors.CLIError(`Refusing to traverse dangling symbolic link: ${start}`, { exit: 1 });
|
|
26597
|
+
} catch (lstatError) {
|
|
26598
|
+
if (!(lstatError && typeof lstatError === "object" && "code" in lstatError && lstatError.code === "ENOENT")) throw lstatError;
|
|
26599
|
+
}
|
|
26600
|
+
else throw error;
|
|
26601
|
+
}
|
|
26602
|
+
const rel = relative(start, resolvedDir);
|
|
26603
|
+
const segments = rel ? rel.split(sep).filter(Boolean) : [];
|
|
26604
|
+
let current = start;
|
|
26605
|
+
const checkPoints = segments.length > 0 ? segments : [""];
|
|
26606
|
+
for (const segment of checkPoints) {
|
|
26607
|
+
current = segment ? join(current, segment) : resolvedDir;
|
|
26608
|
+
try {
|
|
26609
|
+
const stat = lstatSync(current);
|
|
26610
|
+
if (stat.isSymbolicLink()) throw new Errors.CLIError(`Refusing to traverse symbolic link: ${current}`, { exit: 1 });
|
|
26611
|
+
if (!stat.isDirectory()) throw new Errors.CLIError(`Expected directory at ${current}, found a non-directory entry.`, { exit: 1 });
|
|
26612
|
+
} catch (error) {
|
|
26613
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") break;
|
|
26614
|
+
throw error;
|
|
26615
|
+
}
|
|
26616
|
+
}
|
|
26617
|
+
}
|
|
26618
|
+
function assertRegularFileOrMissing(filePath) {
|
|
26619
|
+
try {
|
|
26620
|
+
const stat = lstatSync(filePath);
|
|
26621
|
+
if (stat.isSymbolicLink()) throw new Errors.CLIError(`Refusing to write through symbolic link: ${filePath}`, { exit: 1 });
|
|
26622
|
+
if (!stat.isFile()) throw new Errors.CLIError(`Refusing to overwrite non-regular file: ${filePath}`, { exit: 1 });
|
|
26623
|
+
} catch (error) {
|
|
26624
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return;
|
|
26625
|
+
throw error;
|
|
26626
|
+
}
|
|
26627
|
+
}
|
|
26628
|
+
function hasConnectFrontmatter(content) {
|
|
26629
|
+
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
26630
|
+
if (!match) return false;
|
|
26631
|
+
return /^name:\s*["']?primitive-connect["']?\s*$/im.test(match[1] ?? "");
|
|
26632
|
+
}
|
|
26633
|
+
function applySkillFrontmatterName(markdown, normalizedName) {
|
|
26634
|
+
if (normalizedName === "primitive") return markdown;
|
|
26635
|
+
const match = markdown.match(/^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/);
|
|
26636
|
+
if (!match) return markdown;
|
|
26637
|
+
const [, open, body, close] = match;
|
|
26638
|
+
return `${open}${(body ?? "").replace(/^(name:\s*)(["']?)primitive\2(\s*)$/m, `$1$2${normalizedName}$2$3`)}${close}${markdown.slice(match[0].length)}`;
|
|
26639
|
+
}
|
|
26640
|
+
function isSkillFilePresent(target) {
|
|
26641
|
+
try {
|
|
26642
|
+
assertNoSymlinkAncestors(target.directory, target.boundary);
|
|
26643
|
+
const stat = lstatSync(target.filePath);
|
|
26644
|
+
return !stat.isSymbolicLink() && stat.isFile();
|
|
26645
|
+
} catch {
|
|
26646
|
+
return false;
|
|
26647
|
+
}
|
|
26648
|
+
}
|
|
26649
|
+
function readInstalledSkillMeta(target) {
|
|
26650
|
+
try {
|
|
26651
|
+
assertNoSymlinkAncestors(target.directory, target.boundary);
|
|
26652
|
+
const dirStat = lstatSync(target.directory);
|
|
26653
|
+
if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) return null;
|
|
26654
|
+
const fileStat = lstatSync(target.filePath);
|
|
26655
|
+
if (fileStat.isSymbolicLink() || !fileStat.isFile() || fileStat.size > MAX_SKILL_BYTES) return null;
|
|
26656
|
+
const metaStat = lstatSync(target.metaPath);
|
|
26657
|
+
if (metaStat.isSymbolicLink() || !metaStat.isFile() || metaStat.size > MAX_META_BYTES) return null;
|
|
26658
|
+
const raw = JSON.parse(readFileSync(target.metaPath, "utf8"));
|
|
26659
|
+
if (typeof raw.etag !== "string" || !SKILL_ETAG_RE.test(raw.etag) || typeof raw.sha256 !== "string" || typeof raw.name !== "string") return null;
|
|
26660
|
+
if (sha256Text(readFileSync(target.filePath, "utf8")) !== raw.sha256) return null;
|
|
26661
|
+
return {
|
|
26662
|
+
name: raw.name,
|
|
26663
|
+
version: typeof raw.version === "string" ? raw.version : "1",
|
|
26664
|
+
etag: raw.etag,
|
|
26665
|
+
sha256: raw.sha256,
|
|
26666
|
+
api_base_url: typeof raw.api_base_url === "string" ? raw.api_base_url : "",
|
|
26667
|
+
org_id: typeof raw.org_id === "string" ? raw.org_id : "",
|
|
26668
|
+
auth_method: typeof raw.auth_method === "string" ? raw.auth_method : null,
|
|
26669
|
+
installed_at: typeof raw.installed_at === "string" ? raw.installed_at : ""
|
|
26670
|
+
};
|
|
26671
|
+
} catch {
|
|
26672
|
+
return null;
|
|
26673
|
+
}
|
|
26674
|
+
}
|
|
26675
|
+
function writeFileAtomically(filePath, content, boundary) {
|
|
26676
|
+
const parent = dirname(filePath);
|
|
26677
|
+
assertNoSymlinkAncestors(parent, boundary);
|
|
26678
|
+
mkdirSync(parent, {
|
|
26679
|
+
recursive: true,
|
|
26680
|
+
mode: 448
|
|
26681
|
+
});
|
|
26682
|
+
assertNoSymlinkAncestors(parent, boundary);
|
|
26683
|
+
assertRegularFileOrMissing(filePath);
|
|
26684
|
+
const tempPath = join(parent, `.tmp-${basename(filePath)}-${randomUUID()}`);
|
|
26685
|
+
try {
|
|
26686
|
+
writeFileSync(tempPath, content, {
|
|
26687
|
+
encoding: "utf8",
|
|
26688
|
+
mode: 384,
|
|
26689
|
+
flag: "wx"
|
|
26690
|
+
});
|
|
26691
|
+
renameSync(tempPath, filePath);
|
|
26692
|
+
} catch (error) {
|
|
26693
|
+
rmSync(tempPath, { force: true });
|
|
26694
|
+
throw error;
|
|
26695
|
+
}
|
|
26696
|
+
}
|
|
26697
|
+
function readMarkerMetadata(metaPath) {
|
|
26698
|
+
let metaStat;
|
|
26699
|
+
try {
|
|
26700
|
+
metaStat = lstatSync(metaPath);
|
|
26701
|
+
} catch (error) {
|
|
26702
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return {
|
|
26703
|
+
exists: false,
|
|
26704
|
+
meta: null
|
|
26705
|
+
};
|
|
26706
|
+
throw error;
|
|
26707
|
+
}
|
|
26708
|
+
if (metaStat.isSymbolicLink() || !metaStat.isFile() || metaStat.size > MAX_META_BYTES) return {
|
|
26709
|
+
exists: true,
|
|
26710
|
+
meta: null
|
|
26711
|
+
};
|
|
26712
|
+
try {
|
|
26713
|
+
const raw = JSON.parse(readFileSync(metaPath, "utf8"));
|
|
26714
|
+
if (typeof raw.etag !== "string" || !SKILL_ETAG_RE.test(raw.etag) || typeof raw.sha256 !== "string" || typeof raw.name !== "string") return {
|
|
26715
|
+
exists: true,
|
|
26716
|
+
meta: null
|
|
26717
|
+
};
|
|
26718
|
+
return {
|
|
26719
|
+
exists: true,
|
|
26720
|
+
meta: {
|
|
26721
|
+
name: raw.name,
|
|
26722
|
+
version: typeof raw.version === "string" ? raw.version : "1",
|
|
26723
|
+
etag: raw.etag,
|
|
26724
|
+
sha256: raw.sha256,
|
|
26725
|
+
api_base_url: typeof raw.api_base_url === "string" ? raw.api_base_url : "",
|
|
26726
|
+
org_id: typeof raw.org_id === "string" ? raw.org_id : "",
|
|
26727
|
+
auth_method: typeof raw.auth_method === "string" ? raw.auth_method : null,
|
|
26728
|
+
installed_at: typeof raw.installed_at === "string" ? raw.installed_at : ""
|
|
26729
|
+
}
|
|
26730
|
+
};
|
|
26731
|
+
} catch {
|
|
26732
|
+
return {
|
|
26733
|
+
exists: true,
|
|
26734
|
+
meta: null
|
|
26735
|
+
};
|
|
26736
|
+
}
|
|
26737
|
+
}
|
|
26738
|
+
function installSkillToTarget(target, payload, options = {}) {
|
|
26739
|
+
assertNoSymlinkAncestors(target.directory, target.boundary);
|
|
26740
|
+
assertRegularFileOrMissing(target.filePath);
|
|
26741
|
+
assertRegularFileOrMissing(target.metaPath);
|
|
26742
|
+
const hadFile = isSkillFilePresent(target);
|
|
26743
|
+
const marker = readMarkerMetadata(target.metaPath);
|
|
26744
|
+
let locallyModified = false;
|
|
26745
|
+
if (hadFile) {
|
|
26746
|
+
const stat = lstatSync(target.filePath);
|
|
26747
|
+
let existingText = null;
|
|
26748
|
+
if (stat.size <= MAX_SKILL_BYTES) {
|
|
26749
|
+
existingText = readFileSync(target.filePath, "utf8");
|
|
26750
|
+
if (hasConnectFrontmatter(existingText)) throw new Errors.CLIError(`Refusing to overwrite bundled "${CONNECT_SKILL_NAME}" skill at ${target.filePath}.`, { exit: 2 });
|
|
26751
|
+
}
|
|
26752
|
+
if (!marker.exists) {
|
|
26753
|
+
if (!options.force) throw new Errors.CLIError(`Refusing to overwrite unmanaged skill file at ${target.filePath} (missing ${SKILL_META_FILENAME}). Pass --force to overwrite it, or pass --name to install under a different skill directory.`, { exit: 2 });
|
|
26754
|
+
} else if (marker.meta) {
|
|
26755
|
+
const currentHash = existingText !== null ? sha256Text(existingText) : null;
|
|
26756
|
+
if (currentHash === null || currentHash !== marker.meta.sha256) locallyModified = true;
|
|
26757
|
+
}
|
|
26758
|
+
}
|
|
26759
|
+
const normalizedName = validateSkillName(payload.name);
|
|
26760
|
+
const markdown = applySkillFrontmatterName(payload.markdown, normalizedName);
|
|
26761
|
+
const existing = readInstalledSkillMeta(target);
|
|
26762
|
+
const sha256 = sha256Text(markdown);
|
|
26763
|
+
if (!options.force && existing && existing.etag === payload.etag && existing.sha256 === sha256) return {
|
|
26764
|
+
state: "unchanged",
|
|
26765
|
+
previousEtag: existing.etag
|
|
26766
|
+
};
|
|
26767
|
+
const meta = {
|
|
26768
|
+
name: normalizedName,
|
|
26769
|
+
version: payload.version,
|
|
26770
|
+
etag: payload.etag,
|
|
26771
|
+
sha256,
|
|
26772
|
+
api_base_url: payload.apiBaseUrl,
|
|
26773
|
+
org_id: payload.orgId,
|
|
26774
|
+
auth_method: payload.authMethod,
|
|
26775
|
+
installed_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
26776
|
+
};
|
|
26777
|
+
writeFileAtomically(target.filePath, markdown, target.boundary);
|
|
26778
|
+
writeFileAtomically(target.metaPath, `${JSON.stringify(meta, null, 2)}\n`, target.boundary);
|
|
26779
|
+
const warning = locallyModified ? `Overwrote locally modified ${target.filePath} with the live Primitive skill from the server.` : void 0;
|
|
26780
|
+
return {
|
|
26781
|
+
state: existing || hadFile ? "updated" : "installed",
|
|
26782
|
+
previousEtag: existing?.etag ?? marker.meta?.etag ?? null,
|
|
26783
|
+
...warning ? { warning } : {}
|
|
26784
|
+
};
|
|
26785
|
+
}
|
|
26786
|
+
// src/oclif/commands/skill.ts
|
|
26787
|
+
async function fetchCliSkill(options) {
|
|
26788
|
+
const authenticated = await createAuthenticatedCliApiClient({
|
|
26789
|
+
configDir: options.configDir,
|
|
26790
|
+
apiKey: options.apiKey,
|
|
26791
|
+
apiBaseUrl: options.apiBaseUrl
|
|
26792
|
+
});
|
|
26793
|
+
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 });
|
|
26794
|
+
const headers = {
|
|
26795
|
+
accept: "application/json",
|
|
26796
|
+
...options.ifNoneMatch && SKILL_ETAG_RE.test(options.ifNoneMatch) ? { "if-none-match": `"${options.ifNoneMatch}"` } : {}
|
|
26797
|
+
};
|
|
26798
|
+
const baseUrl = authenticated.auth.apiBaseUrl.replace(/\/+$/, "");
|
|
26799
|
+
let response;
|
|
26800
|
+
try {
|
|
26801
|
+
response = await authenticated.fetch(`${baseUrl}/cli/skill`, {
|
|
26802
|
+
method: "GET",
|
|
26803
|
+
headers,
|
|
26804
|
+
redirect: "manual",
|
|
26805
|
+
signal: AbortSignal.timeout(3e4)
|
|
26806
|
+
});
|
|
26807
|
+
} catch (error) {
|
|
26808
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
26809
|
+
throw new Errors.CLIError(`Could not fetch Primitive skill: ${detail}`, { exit: 1 });
|
|
26810
|
+
}
|
|
26811
|
+
if (response.status === 304) {
|
|
26812
|
+
const rawEtag = response.headers.get("etag");
|
|
26813
|
+
return {
|
|
26814
|
+
status: "not_modified",
|
|
26815
|
+
etag: rawEtag ? rawEtag.replace(/^W\//i, "").replace(/^"(.*)"$/, "$1") : options.ifNoneMatch ?? null,
|
|
26816
|
+
apiBaseUrl: baseUrl
|
|
26817
|
+
};
|
|
26818
|
+
}
|
|
26819
|
+
const rawBody = await response.text();
|
|
26820
|
+
let parsed;
|
|
26821
|
+
try {
|
|
26822
|
+
parsed = rawBody ? JSON.parse(rawBody) : null;
|
|
26823
|
+
} catch {
|
|
26824
|
+
parsed = null;
|
|
26825
|
+
}
|
|
26826
|
+
if (!response.ok) {
|
|
26827
|
+
const errObj = parsed && typeof parsed === "object" && "error" in parsed ? parsed.error : void 0;
|
|
26828
|
+
const code = errObj?.code;
|
|
26829
|
+
const message = errObj?.message || `Primitive API returned HTTP ${response.status} for GET /v1/cli/skill.`;
|
|
26830
|
+
throw new Errors.CLIError(message, {
|
|
26831
|
+
exit: 1,
|
|
26832
|
+
...code ? { code } : {}
|
|
26833
|
+
});
|
|
26834
|
+
}
|
|
26835
|
+
const data = parsed && typeof parsed === "object" && "data" in parsed ? parsed.data : void 0;
|
|
26836
|
+
if (!data || typeof data.markdown !== "string" || !data.etag) throw new Errors.CLIError("Unexpected response shape from GET /v1/cli/skill.", { exit: 1 });
|
|
26837
|
+
return {
|
|
26838
|
+
status: "ok",
|
|
26839
|
+
data,
|
|
26840
|
+
apiBaseUrl: baseUrl
|
|
26841
|
+
};
|
|
26842
|
+
}
|
|
26843
|
+
function commonInstalledEtag(etags) {
|
|
26844
|
+
if (etags.length === 0) return null;
|
|
26845
|
+
const first = etags[0];
|
|
26846
|
+
if (!first) return null;
|
|
26847
|
+
return etags.every((value) => value === first) ? first : null;
|
|
26848
|
+
}
|
|
26849
|
+
function reportSkillCheckResult(command, params) {
|
|
26850
|
+
const statuses = params.targets.map((t, index) => {
|
|
26851
|
+
const meta = params.metas[index];
|
|
26852
|
+
const state = meta && params.serverEtag && meta.etag === params.serverEtag ? "fresh" : meta || isSkillFilePresent(t) ? "stale" : "missing";
|
|
26853
|
+
return {
|
|
26854
|
+
target: t.target,
|
|
26855
|
+
path: t.filePath,
|
|
26856
|
+
state,
|
|
26857
|
+
installed_etag: meta?.etag ?? null
|
|
26858
|
+
};
|
|
26859
|
+
});
|
|
26860
|
+
const allFresh = statuses.every((s) => s.state === "fresh");
|
|
26861
|
+
const overall = allFresh ? "fresh" : statuses.every((s) => s.state === "missing") ? "missing" : "stale";
|
|
26862
|
+
if (params.json) command.log(JSON.stringify({
|
|
26863
|
+
state: overall,
|
|
26864
|
+
etag: params.serverEtag,
|
|
26865
|
+
targets: statuses,
|
|
26866
|
+
...!allFresh ? { error: {
|
|
26867
|
+
code: overall === "missing" ? "skill_missing" : "skill_stale",
|
|
26868
|
+
message: overall === "missing" ? "Installed Primitive skill is missing. Run `primitive skill install` to install." : "Installed Primitive skill is out of date. Run `primitive skill install` to update."
|
|
26869
|
+
} } : {}
|
|
26870
|
+
}));
|
|
26871
|
+
else {
|
|
26872
|
+
for (const item of statuses) command.log(`${item.state}\t${item.target}\t${item.path}`);
|
|
26873
|
+
if (!allFresh) process.stderr.write("Skill is out of date or missing. Run `primitive skill install` to update.\n");
|
|
26874
|
+
}
|
|
26875
|
+
if (!allFresh) process.exitCode = 2;
|
|
26876
|
+
}
|
|
26877
|
+
var SkillCommand = class SkillCommand extends Command {
|
|
26878
|
+
static summary = "Print or verify the live Primitive skill tailored to your credential";
|
|
26879
|
+
static description = "Fetch the authenticated, permission- and entitlement-scoped Primitive skill document from the server. Prints SKILL.md to stdout by default so agents and scripts can load it directly without MCP. Use `primitive skill install` to write it into local agent skill directories.";
|
|
26880
|
+
static examples = [
|
|
26881
|
+
"<%= config.bin %> skill",
|
|
26882
|
+
"<%= config.bin %> skill --json",
|
|
26883
|
+
"<%= config.bin %> skill --check",
|
|
26884
|
+
"<%= config.bin %> skill --out ./SKILL.md",
|
|
26885
|
+
"<%= config.bin %> skill install"
|
|
26886
|
+
];
|
|
26887
|
+
static flags = {
|
|
26888
|
+
check: Flags.boolean({ description: "Check whether the installed local skill matches the server ETag (exits 0 if fresh, 2 if stale or missing)" }),
|
|
26889
|
+
out: Flags.string({ description: "Write SKILL.md to this file path (or check freshness against this path with --check)" }),
|
|
26890
|
+
target: Flags.string({
|
|
26891
|
+
description: "Target agent runtime for --check (auto, all, claude, codex, antigravity, cursor, openclaw, agents)",
|
|
26892
|
+
multiple: true
|
|
26893
|
+
}),
|
|
26894
|
+
project: Flags.boolean({ description: "With --check, check project-local skill directories" }),
|
|
26895
|
+
name: Flags.string({
|
|
26896
|
+
description: "Skill directory name when checking installed copies",
|
|
26897
|
+
default: DEFAULT_LIVE_SKILL_NAME
|
|
26898
|
+
}),
|
|
26899
|
+
json: Flags.boolean({ description: "Output structured skill metadata and markdown as JSON" }),
|
|
26900
|
+
time: Flags.boolean({ description: "Print request timing to stderr" }),
|
|
26901
|
+
"api-key": Flags.string({
|
|
26902
|
+
description: "Override the Primitive API key for this request",
|
|
26903
|
+
env: "PRIMITIVE_API_KEY"
|
|
26904
|
+
}),
|
|
26905
|
+
"api-base-url": Flags.string({
|
|
26906
|
+
description: "Override the API base URL",
|
|
26907
|
+
env: "PRIMITIVE_API_BASE_URL",
|
|
26908
|
+
hidden: true
|
|
26909
|
+
})
|
|
26910
|
+
};
|
|
26911
|
+
async run() {
|
|
26912
|
+
const { flags } = await this.parse(SkillCommand);
|
|
26913
|
+
if (flags.out && (flags.project || flags.target && flags.target.length > 0)) throw new Errors.CLIError("--out cannot be combined with --target or --project.", { exit: 2 });
|
|
26914
|
+
if (!flags.check && (flags.project || flags.target && flags.target.length > 0)) throw new Errors.CLIError("--target and --project require --check on `primitive skill`, or use `primitive skill install`.", { exit: 2 });
|
|
26915
|
+
await runWithTiming(flags.time === true, async () => {
|
|
26916
|
+
if (flags.check) {
|
|
26917
|
+
const targets = resolveSkillTargets({
|
|
26918
|
+
targets: flags.target,
|
|
26919
|
+
project: flags.project,
|
|
26920
|
+
out: flags.out,
|
|
26921
|
+
name: flags.name
|
|
26922
|
+
});
|
|
26923
|
+
const metas = targets.map((t) => readInstalledSkillMeta(t));
|
|
26924
|
+
const sharedEtag = commonInstalledEtag(metas.map((m) => m?.etag ?? null));
|
|
26925
|
+
const result = await fetchCliSkill({
|
|
26926
|
+
configDir: this.config.configDir,
|
|
26927
|
+
apiKey: flags["api-key"],
|
|
26928
|
+
apiBaseUrl: flags["api-base-url"],
|
|
26929
|
+
ifNoneMatch: sharedEtag
|
|
26930
|
+
});
|
|
26931
|
+
const serverEtag = result.status === "not_modified" ? result.etag : result.data.etag;
|
|
26932
|
+
reportSkillCheckResult(this, {
|
|
26933
|
+
targets,
|
|
26934
|
+
metas,
|
|
26935
|
+
serverEtag,
|
|
26936
|
+
json: flags.json === true
|
|
26937
|
+
});
|
|
26938
|
+
return;
|
|
26939
|
+
}
|
|
26940
|
+
if (flags.out !== void 0) {
|
|
26941
|
+
const normalizedName = validateSkillName(flags.name);
|
|
26942
|
+
const [target] = resolveSkillTargets({
|
|
26943
|
+
out: flags.out,
|
|
26944
|
+
name: normalizedName
|
|
26945
|
+
});
|
|
26946
|
+
if (!target) throw new Errors.CLIError("Could not resolve --out target.", { exit: 2 });
|
|
26947
|
+
const result = await fetchCliSkill({
|
|
26948
|
+
configDir: this.config.configDir,
|
|
26949
|
+
apiKey: flags["api-key"],
|
|
26950
|
+
apiBaseUrl: flags["api-base-url"]
|
|
26951
|
+
});
|
|
26952
|
+
if (result.status !== "ok") throw new Errors.CLIError("Unexpected 304 response without If-None-Match.", { exit: 1 });
|
|
26953
|
+
const outcome = installSkillToTarget(target, {
|
|
26954
|
+
name: normalizedName,
|
|
26955
|
+
version: result.data.version,
|
|
26956
|
+
etag: result.data.etag,
|
|
26957
|
+
apiBaseUrl: result.apiBaseUrl,
|
|
26958
|
+
orgId: result.data.org_id,
|
|
26959
|
+
authMethod: result.data.auth_method,
|
|
26960
|
+
markdown: result.data.markdown
|
|
26961
|
+
}, { force: true });
|
|
26962
|
+
if (outcome.warning) process.stderr.write(`Warning: ${outcome.warning}\n`);
|
|
26963
|
+
if (flags.json) this.log(JSON.stringify({
|
|
26964
|
+
state: outcome.state,
|
|
26965
|
+
path: target.filePath,
|
|
26966
|
+
etag: result.data.etag,
|
|
26967
|
+
modules: result.data.modules,
|
|
26968
|
+
...outcome.warning ? { warning: outcome.warning } : {}
|
|
26969
|
+
}));
|
|
26970
|
+
else this.log(`Wrote Primitive skill (${result.data.etag}) to ${target.filePath}`);
|
|
26971
|
+
return;
|
|
26972
|
+
}
|
|
26973
|
+
const result = await fetchCliSkill({
|
|
26974
|
+
configDir: this.config.configDir,
|
|
26975
|
+
apiKey: flags["api-key"],
|
|
26976
|
+
apiBaseUrl: flags["api-base-url"]
|
|
26977
|
+
});
|
|
26978
|
+
if (result.status !== "ok") throw new Errors.CLIError("Unexpected 304 response without If-None-Match.", { exit: 1 });
|
|
26979
|
+
if (flags.json) {
|
|
26980
|
+
this.log(JSON.stringify(result.data, null, 2));
|
|
26981
|
+
return;
|
|
26982
|
+
}
|
|
26983
|
+
process.stdout.write(result.data.markdown.endsWith("\n") ? result.data.markdown : `${result.data.markdown}\n`);
|
|
26984
|
+
});
|
|
26985
|
+
}
|
|
26986
|
+
};
|
|
26987
|
+
var SkillInstallCommand = class SkillInstallCommand extends Command {
|
|
26988
|
+
static summary = "Install or update the live Primitive skill into local agent directories";
|
|
26989
|
+
static description = "Fetch your credential's tailored Primitive skill from the server and atomically write SKILL.md into detected or selected coding-agent skill directories (Claude Code, Codex, Antigravity, Cursor, OpenClaw, or universal ~/.agents/skills).";
|
|
26990
|
+
static examples = [
|
|
26991
|
+
"<%= config.bin %> skill install",
|
|
26992
|
+
"<%= config.bin %> skill install --target claude,codex",
|
|
26993
|
+
"<%= config.bin %> skill install --project",
|
|
26994
|
+
"<%= config.bin %> skill install --check",
|
|
26995
|
+
"<%= config.bin %> skill install --out ./my-agent/SKILL.md"
|
|
26996
|
+
];
|
|
26997
|
+
static flags = {
|
|
26998
|
+
target: Flags.string({
|
|
26999
|
+
description: "Target agent runtime(s): auto (default), all, claude, codex, antigravity, cursor, openclaw, agents",
|
|
27000
|
+
multiple: true
|
|
27001
|
+
}),
|
|
27002
|
+
project: Flags.boolean({ description: "Install into workspace-local skill directories instead of user home" }),
|
|
27003
|
+
out: Flags.string({ description: "Install into an explicit directory or SKILL.md path (cannot combine with --target or --project)" }),
|
|
27004
|
+
name: Flags.string({
|
|
27005
|
+
description: "Skill folder name (default: primitive)",
|
|
27006
|
+
default: DEFAULT_LIVE_SKILL_NAME
|
|
27007
|
+
}),
|
|
27008
|
+
check: Flags.boolean({ description: "Dry-run freshness check against server ETag without writing files (exits 0 fresh, 2 stale/missing)" }),
|
|
27009
|
+
force: Flags.boolean({ description: "Rewrite SKILL.md even if the installed ETag matches or an unmanaged file exists" }),
|
|
27010
|
+
json: Flags.boolean({ description: "Output installation summary as JSON" }),
|
|
27011
|
+
time: Flags.boolean({ description: "Print request timing to stderr" }),
|
|
27012
|
+
"api-key": Flags.string({
|
|
27013
|
+
description: "Override the Primitive API key for this request",
|
|
27014
|
+
env: "PRIMITIVE_API_KEY"
|
|
27015
|
+
}),
|
|
27016
|
+
"api-base-url": Flags.string({
|
|
27017
|
+
description: "Override the API base URL",
|
|
27018
|
+
env: "PRIMITIVE_API_BASE_URL",
|
|
27019
|
+
hidden: true
|
|
27020
|
+
})
|
|
27021
|
+
};
|
|
27022
|
+
async run() {
|
|
27023
|
+
const { flags } = await this.parse(SkillInstallCommand);
|
|
27024
|
+
if (flags.out && (flags.project || flags.target && flags.target.length > 0)) throw new Errors.CLIError("--out cannot be combined with --target or --project.", { exit: 2 });
|
|
27025
|
+
await runWithTiming(flags.time === true, async () => {
|
|
27026
|
+
const targets = resolveSkillTargets({
|
|
27027
|
+
targets: flags.target,
|
|
27028
|
+
project: flags.project,
|
|
27029
|
+
out: flags.out,
|
|
27030
|
+
name: flags.name
|
|
27031
|
+
});
|
|
27032
|
+
const metas = targets.map((t) => readInstalledSkillMeta(t));
|
|
27033
|
+
const sharedEtag = flags.force ? null : commonInstalledEtag(metas.map((m) => m?.etag ?? null));
|
|
27034
|
+
const result = await fetchCliSkill({
|
|
27035
|
+
configDir: this.config.configDir,
|
|
27036
|
+
apiKey: flags["api-key"],
|
|
27037
|
+
apiBaseUrl: flags["api-base-url"],
|
|
27038
|
+
ifNoneMatch: sharedEtag
|
|
27039
|
+
});
|
|
27040
|
+
if (flags.check) {
|
|
27041
|
+
const serverEtag = result.status === "not_modified" ? result.etag : result.data.etag;
|
|
27042
|
+
reportSkillCheckResult(this, {
|
|
27043
|
+
targets,
|
|
27044
|
+
metas,
|
|
27045
|
+
serverEtag,
|
|
27046
|
+
json: flags.json === true
|
|
27047
|
+
});
|
|
27048
|
+
return;
|
|
27049
|
+
}
|
|
27050
|
+
if (result.status === "not_modified") {
|
|
27051
|
+
const items = targets.map((t, idx) => ({
|
|
27052
|
+
target: t.target,
|
|
27053
|
+
path: t.filePath,
|
|
27054
|
+
state: "unchanged",
|
|
27055
|
+
previous_etag: metas[idx]?.etag ?? null
|
|
27056
|
+
}));
|
|
27057
|
+
if (flags.json) this.log(JSON.stringify({
|
|
27058
|
+
state: "unchanged",
|
|
27059
|
+
etag: result.etag,
|
|
27060
|
+
targets: items
|
|
27061
|
+
}));
|
|
27062
|
+
else for (const item of items) this.log(`unchanged\t${item.target}\t${item.path}`);
|
|
27063
|
+
return;
|
|
27064
|
+
}
|
|
27065
|
+
const normalizedName = validateSkillName(flags.name);
|
|
27066
|
+
const installed = targets.map((t) => {
|
|
27067
|
+
const outcome = installSkillToTarget(t, {
|
|
27068
|
+
name: normalizedName,
|
|
27069
|
+
version: result.data.version,
|
|
27070
|
+
etag: result.data.etag,
|
|
27071
|
+
apiBaseUrl: result.apiBaseUrl,
|
|
27072
|
+
orgId: result.data.org_id,
|
|
27073
|
+
authMethod: result.data.auth_method,
|
|
27074
|
+
markdown: result.data.markdown
|
|
27075
|
+
}, { force: flags.force });
|
|
27076
|
+
if (outcome.warning) process.stderr.write(`Warning: ${outcome.warning}\n`);
|
|
27077
|
+
return {
|
|
27078
|
+
target: t.target,
|
|
27079
|
+
path: t.filePath,
|
|
27080
|
+
state: outcome.state,
|
|
27081
|
+
previous_etag: outcome.previousEtag,
|
|
27082
|
+
...outcome.warning ? { warning: outcome.warning } : {}
|
|
27083
|
+
};
|
|
27084
|
+
});
|
|
27085
|
+
const overall = installed.every((i) => i.state === "unchanged") ? "unchanged" : installed.some((i) => i.state === "updated") ? "updated" : "installed";
|
|
27086
|
+
if (flags.json) this.log(JSON.stringify({
|
|
27087
|
+
state: overall,
|
|
27088
|
+
etag: result.data.etag,
|
|
27089
|
+
modules: result.data.modules,
|
|
27090
|
+
policy: result.data.policy,
|
|
27091
|
+
targets: installed
|
|
27092
|
+
}));
|
|
27093
|
+
else for (const item of installed) this.log(`${item.state}\t${item.target}\t${item.path}`);
|
|
27094
|
+
});
|
|
27095
|
+
}
|
|
27096
|
+
};
|
|
25524
27097
|
// src/oclif/commands/skills-install.ts
|
|
25525
27098
|
/**
|
|
25526
27099
|
* Install every skill bundled in the CLI package at `packageRoot`, or only
|
|
@@ -25855,6 +27428,77 @@ var ThreadsMutedCommand = class ThreadsMutedCommand extends Command {
|
|
|
25855
27428
|
this.log(JSON.stringify(entries, null, 2));
|
|
25856
27429
|
}
|
|
25857
27430
|
};
|
|
27431
|
+
// src/oclif/commands/unlock.ts
|
|
27432
|
+
var UnlockCommand = class UnlockCommand extends Command {
|
|
27433
|
+
static summary = "Unlock global CLI credentials (permanently or temporarily with auto-relock)";
|
|
27434
|
+
static description = "Unlocks global Primitive CLI credentials previously locked with `primitive lock`. Refuses non-interactive shells by default so AI agents cannot unlock your global admin credentials on their own. Pass `--for 15m` to unlock temporarily and auto-relock.";
|
|
27435
|
+
static examples = [
|
|
27436
|
+
"<%= config.bin %> unlock --for 15m",
|
|
27437
|
+
"<%= config.bin %> unlock --for 1h",
|
|
27438
|
+
"<%= config.bin %> unlock"
|
|
27439
|
+
];
|
|
27440
|
+
static flags = {
|
|
27441
|
+
for: Flags.string({ description: "Temporarily unlock for a bounded duration before automatically re-locking (for example: 15m, 1h, 4h)" }),
|
|
27442
|
+
"force-non-interactive": Flags.boolean({
|
|
27443
|
+
description: "Allow unlocking outside an interactive TTY (intended for human-authored scripts only; AI agents must not pass this)",
|
|
27444
|
+
hidden: true
|
|
27445
|
+
}),
|
|
27446
|
+
json: Flags.boolean({ description: "Print the unlock result as JSON" })
|
|
27447
|
+
};
|
|
27448
|
+
async run() {
|
|
27449
|
+
const { flags } = await this.parse(UnlockCommand);
|
|
27450
|
+
try {
|
|
27451
|
+
if (!process.stdin.isTTY && !flags["force-non-interactive"]) throw new Errors.CLIError([
|
|
27452
|
+
"Refusing to unlock global Primitive credentials from a non-interactive shell.",
|
|
27453
|
+
"AI agents: Do NOT unlock the user's global admin credentials. Ask the user to share a scoped Access Pass (`primitive connect <url>`) or ask the user to run `primitive unlock` directly in their own terminal.",
|
|
27454
|
+
"Humans: Run `primitive unlock --for 15m` or `primitive unlock` directly in your interactive terminal."
|
|
27455
|
+
].join("\n"), { exit: 1 });
|
|
27456
|
+
if (flags.for) {
|
|
27457
|
+
const seconds = parseUnlockDurationSeconds(flags.for);
|
|
27458
|
+
const nowMs = Date.now();
|
|
27459
|
+
const existing = readCliLockState(this.config.configDir, () => nowMs);
|
|
27460
|
+
const lockedAt = existing.status === "unlocked" ? new Date(nowMs).toISOString() : existing.lockedAt;
|
|
27461
|
+
const reason = existing.status === "unlocked" ? null : existing.reason;
|
|
27462
|
+
const unlockedUntil = new Date(nowMs + seconds * 1e3).toISOString();
|
|
27463
|
+
writeCliLockState(this.config.configDir, {
|
|
27464
|
+
version: 1,
|
|
27465
|
+
locked: true,
|
|
27466
|
+
locked_at: lockedAt,
|
|
27467
|
+
unlocked_until: unlockedUntil,
|
|
27468
|
+
...reason ? { reason } : {}
|
|
27469
|
+
});
|
|
27470
|
+
if (flags.json) {
|
|
27471
|
+
this.log(JSON.stringify({
|
|
27472
|
+
status: "temporarily_unlocked",
|
|
27473
|
+
locked: false,
|
|
27474
|
+
unlocked_until: unlockedUntil
|
|
27475
|
+
}));
|
|
27476
|
+
return;
|
|
27477
|
+
}
|
|
27478
|
+
this.log(`Unlocked global Primitive credentials until ${unlockedUntil} (will auto-relock).`);
|
|
27479
|
+
this.log("Run `primitive lock` to re-lock earlier.");
|
|
27480
|
+
return;
|
|
27481
|
+
}
|
|
27482
|
+
const removed = removeCliLockState(this.config.configDir);
|
|
27483
|
+
if (flags.json) {
|
|
27484
|
+
this.log(JSON.stringify({
|
|
27485
|
+
status: "unlocked",
|
|
27486
|
+
locked: false,
|
|
27487
|
+
was_locked: removed
|
|
27488
|
+
}));
|
|
27489
|
+
return;
|
|
27490
|
+
}
|
|
27491
|
+
if (removed) {
|
|
27492
|
+
this.log("Unlocked global Primitive credentials.");
|
|
27493
|
+
this.log("Run `primitive lock` again when you want to protect global credentials from agent sessions.");
|
|
27494
|
+
} else this.log("Global Primitive credentials were already unlocked.");
|
|
27495
|
+
} catch (error) {
|
|
27496
|
+
if (error instanceof Errors.CLIError) throw error;
|
|
27497
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
27498
|
+
throw new Errors.CLIError(message, { exit: 1 });
|
|
27499
|
+
}
|
|
27500
|
+
}
|
|
27501
|
+
};
|
|
25858
27502
|
// src/oclif/commands/version.ts
|
|
25859
27503
|
/** The facts `--version` prints, as fields. `node` is Node's version without its leading v. */
|
|
25860
27504
|
function versionInfo(config) {
|
|
@@ -27487,7 +29131,13 @@ const OVERRIDDEN_OPERATION_IDS = /* @__PURE__ */ new Set([
|
|
|
27487
29131
|
"inbox:get-inbox-status",
|
|
27488
29132
|
"search:semantic-search",
|
|
27489
29133
|
"credits:redeem-credit-code",
|
|
27490
|
-
"cli:list-cli-orgs"
|
|
29134
|
+
"cli:list-cli-orgs",
|
|
29135
|
+
"activity:create-email-activity",
|
|
29136
|
+
"activity:create-thread-activity",
|
|
29137
|
+
"activity:get-thread-timeline",
|
|
29138
|
+
"activity:list-mail-activity-actors",
|
|
29139
|
+
"activity:list-org-mail-activity",
|
|
29140
|
+
"activity:update-thread-activity"
|
|
27491
29141
|
]);
|
|
27492
29142
|
const generatedCommands = Object.fromEntries(rawCliOperationManifest.filter((operation) => !OVERRIDDEN_OPERATION_IDS.has(operationId(operation))).map((operation) => [operationId(operation), createOperationCommand(canonicalOperation(operation))]));
|
|
27493
29143
|
generatedCommands["emails:get-email"] = createEmailsGetCommand(generatedCommands["emails:get-email"]);
|
|
@@ -27627,6 +29277,8 @@ const rawCommands = {
|
|
|
27627
29277
|
"org:secrets:remove": OrgSecretsRemoveCommand,
|
|
27628
29278
|
connect: ConnectCommand,
|
|
27629
29279
|
disconnect: DisconnectCommand,
|
|
29280
|
+
lock: LockCommand,
|
|
29281
|
+
unlock: UnlockCommand,
|
|
27630
29282
|
api: ApiCommand,
|
|
27631
29283
|
"payloads:push": PayloadsPushCommand,
|
|
27632
29284
|
"payloads:pull": PayloadsPullCommand,
|
|
@@ -27674,7 +29326,14 @@ const rawCommands = {
|
|
|
27674
29326
|
"wake:authorizations:create": WakeAuthorizationsCreateCommand,
|
|
27675
29327
|
"wake:authorizations:update": WakeAuthorizationsUpdateCommand,
|
|
27676
29328
|
"wake:authorizations:delete": WakeAuthorizationsDeleteCommand,
|
|
27677
|
-
"wake:dispatches:list": WakeDispatchesListCommand
|
|
29329
|
+
"wake:dispatches:list": WakeDispatchesListCommand,
|
|
29330
|
+
skill: SkillCommand,
|
|
29331
|
+
"skill:install": SkillInstallCommand,
|
|
29332
|
+
"activity:log": ActivityLogCommand,
|
|
29333
|
+
"activity:update": ActivityUpdateCommand,
|
|
29334
|
+
"activity:timeline": ActivityTimelineCommand,
|
|
29335
|
+
"activity:list": ActivityListCommand,
|
|
29336
|
+
"activity:agents": ActivityAgentsCommand
|
|
27678
29337
|
};
|
|
27679
29338
|
for (const [oldId, target] of Object.entries(COMMAND_PAIR_RENAMES)) {
|
|
27680
29339
|
const request = generatedCommands[oldId];
|
|
@@ -27690,5 +29349,6 @@ for (const [oldId, target] of Object.entries(COMMAND_PAIR_RENAMES)) {
|
|
|
27690
29349
|
const COMMANDS = canonicalCommands(rawCommands);
|
|
27691
29350
|
for (const command of new Set(Object.values(COMMANDS))) ignoreArgumentStdin(command);
|
|
27692
29351
|
setKnownCommands(Object.keys(COMMANDS), CANONICAL_OPERATION_ALIASES);
|
|
29352
|
+
attachActivityContextFlags(COMMANDS);
|
|
27693
29353
|
guardJsonOutputCommands(COMMANDS);
|
|
27694
29354
|
export { CANONICAL_OPERATION_ALIASES, COMMANDS, COMMAND_RENAMES, lookupOperation, retiredCommandTarget };
|