primcli 3.0.0-preview.22 → 3.0.0-preview.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{api-command-Dm1BKxOr.js → api-command-CP8ir5Pv.js} +18 -58
- package/dist/{cli-config-Ms_0vNjq.js → cli-config-DUQEYQ42.js} +489 -4
- package/dist/{machine-session-DPLiLNot.js → machine-session-CE31cwx2.js} +3 -3
- package/dist/{notify-session-DHQbjXOq.js → notify-session-Dx54UpkT.js} +1 -1
- package/dist/oclif/auto-signal-worker.js +2 -2
- package/dist/oclif/index.js +493 -25
- package/dist/oclif/receiver-heal.js +2 -3
- package/dist/oclif/root-signup-hint.js +1 -1
- package/dist/{signal-command-vIo4maG0.js → signal-command-CA55RTJh.js} +1 -1
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { $t as getThread, Bt as getEndpoint, C as parseRetryAfter, H as assertAwaitingFilterRows, J as isAwaitingRejectedError, U as awaitingRejectedError, V as ReplyStateUnsupportedError, Vn as sdk_gen_exports, W as ensureSearchReportsReplyState, X as replyStateSurfaceForOperation, Yt as getOwnGrant, at as expectedAutomatedVerdicts, et as AutomatedFilterUnsupportedError, it as ensureSearchReportsAutomated, nt as automatedRejectedError, pn as listEndpoints, rt as automatedSurfaceForOperation, st as isAutomatedRejectedError, tt as assertAutomatedVerdict, un as listDomains, zt as getEmail } from "./repeats-Dj_o6c-X-x61TNLz-.js";
|
|
2
2
|
import { a as canonicalCommandId, i as canonicalCliText, r as canonicalBodyFlagName } from "./cli-command-names-DteMqL-H.js";
|
|
3
|
-
import { C as
|
|
3
|
+
import { C as resolveCliAuth, I as agentProfilesDirectory, M as AGENT_PROFILE_ENV, P as agentProfileDirectory, Q as loadActiveAgentPass, S as normalizeApiBaseUrl, T as saveSignupCredentials, U as requireDefaultLoginProfile, b as detectPrimitiveKeyEnvMisname, ct as PrimitiveApiClient, f as validateCliHeaderName, h as cliAccessTokenExpiresAt, i as loadCliConfig, l as resolveConfigEnvironment, m as acquireCliCredentialsLock, ot as detectRuntimeSession, p as validateCliHeaderValue, v as deleteCliCredentials, w as saveCliCredentials, x as loadCliCredentials, z as loadConnectedAgentProfile } from "./cli-config-DUQEYQ42.js";
|
|
4
4
|
import "./oclif/global-org-flag.js";
|
|
5
5
|
import { a as assertRequiredBodyFields, i as operationHelpInputs } from "./help-inputs-NGARVZL_.js";
|
|
6
6
|
import { o as thrownErrorBody } from "./json-output-BMZrLH47.js";
|
|
@@ -55439,7 +55439,20 @@ function cliApiHeadersFromEnv(env = process.env) {
|
|
|
55439
55439
|
return rawGenericHeaders ? parseHeadersJson(rawGenericHeaders) : void 0;
|
|
55440
55440
|
}
|
|
55441
55441
|
function resolveCliApiRequestConfig(params) {
|
|
55442
|
-
|
|
55442
|
+
const env = params.env ?? process.env;
|
|
55443
|
+
if (env["PRIMITIVE_AGENT_PROFILE"]?.trim() || env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim()) {
|
|
55444
|
+
const auth = resolveCliAuth(params);
|
|
55445
|
+
return {
|
|
55446
|
+
apiBaseUrl: auth.apiBaseUrl,
|
|
55447
|
+
resolvedApiBaseUrl: auth.apiBaseUrl,
|
|
55448
|
+
baseUrlOverridden: params.apiBaseUrl !== void 0,
|
|
55449
|
+
environmentName: null
|
|
55450
|
+
};
|
|
55451
|
+
}
|
|
55452
|
+
if (loadActiveAgentPass({
|
|
55453
|
+
configDir: params.configDir,
|
|
55454
|
+
env
|
|
55455
|
+
})) {
|
|
55443
55456
|
const auth = resolveCliAuth(params);
|
|
55444
55457
|
return {
|
|
55445
55458
|
apiBaseUrl: auth.apiBaseUrl,
|
|
@@ -55660,7 +55673,7 @@ async function createAuthenticatedCliApiClient(params) {
|
|
|
55660
55673
|
})
|
|
55661
55674
|
} : { apiKey: auth.apiKey },
|
|
55662
55675
|
apiBaseUrl: auth.apiBaseUrl,
|
|
55663
|
-
headers: auth.connectedAgent ? void 0 : requestConfig.headers
|
|
55676
|
+
headers: auth.connectedAgent || auth.agentPass ? void 0 : requestConfig.headers
|
|
55664
55677
|
}),
|
|
55665
55678
|
auth,
|
|
55666
55679
|
baseUrlOverridden: requestConfig.baseUrlOverridden,
|
|
@@ -58332,59 +58345,6 @@ function metaNoteLines(meta) {
|
|
|
58332
58345
|
function metaExplainsEmptyList(meta) {
|
|
58333
58346
|
return meta !== null && typeof meta === "object" && meta.recipient_outside_access === true;
|
|
58334
58347
|
}
|
|
58335
|
-
// src/oclif/runtime-session.ts
|
|
58336
|
-
/**
|
|
58337
|
-
* The variables each runtime sets to its exact session ID, first match wins.
|
|
58338
|
-
* The loaded Codex thread is the receiving identity; the process session ID
|
|
58339
|
-
* is only a fallback when no thread ID is exposed.
|
|
58340
|
-
*/
|
|
58341
|
-
const RUNTIME_SESSION_VARIABLES = {
|
|
58342
|
-
claude: ["CLAUDE_CODE_SESSION_ID"],
|
|
58343
|
-
codex: ["CODEX_THREAD_ID", "CODEX_SESSION_ID"]
|
|
58344
|
-
};
|
|
58345
|
-
const UUID$3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
58346
|
-
/** Each runtime whose environment names a session UUID. Never guessed from history or cwd. */
|
|
58347
|
-
function runtimeSessions(env) {
|
|
58348
|
-
return Object.keys(RUNTIME_SESSION_VARIABLES).flatMap((runtime) => {
|
|
58349
|
-
for (const variable of RUNTIME_SESSION_VARIABLES[runtime]) {
|
|
58350
|
-
const value = env[variable]?.trim().toLowerCase();
|
|
58351
|
-
if (!value) continue;
|
|
58352
|
-
return UUID$3.test(value) ? [{
|
|
58353
|
-
runtime,
|
|
58354
|
-
session: value,
|
|
58355
|
-
variable
|
|
58356
|
-
}] : [];
|
|
58357
|
-
}
|
|
58358
|
-
return [];
|
|
58359
|
-
});
|
|
58360
|
-
}
|
|
58361
|
-
/** The one session the runtime environment names, if exactly one runtime names one. */
|
|
58362
|
-
function detectRuntimeSession(env = process.env) {
|
|
58363
|
-
const candidates = runtimeSessions(env);
|
|
58364
|
-
const [only] = candidates;
|
|
58365
|
-
if (!only) return { kind: "none" };
|
|
58366
|
-
return candidates.length === 1 ? {
|
|
58367
|
-
kind: "detected",
|
|
58368
|
-
...only
|
|
58369
|
-
} : {
|
|
58370
|
-
kind: "ambiguous",
|
|
58371
|
-
candidates
|
|
58372
|
-
};
|
|
58373
|
-
}
|
|
58374
|
-
/**
|
|
58375
|
-
* The runtime whose tool environment names this exact session. A session ID
|
|
58376
|
-
* that matches neither runtime's variable, or both, has no detectable runtime.
|
|
58377
|
-
*/
|
|
58378
|
-
function detectAgentRuntime(session, env = process.env) {
|
|
58379
|
-
const wanted = session.trim().toLowerCase();
|
|
58380
|
-
const matches = runtimeSessions(env).filter((candidate) => candidate.session === wanted);
|
|
58381
|
-
return matches.length === 1 ? matches[0]?.runtime ?? null : null;
|
|
58382
|
-
}
|
|
58383
|
-
/** Every variable a runtime may name its session in, for messages. */
|
|
58384
|
-
function runtimeSessionVariableList() {
|
|
58385
|
-
const names = Object.values(RUNTIME_SESSION_VARIABLES).flat();
|
|
58386
|
-
return `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
|
|
58387
|
-
}
|
|
58388
58348
|
// src/oclif/mail-session.ts
|
|
58389
58349
|
/** Runtime-provided identity only. Never guess a session from history or cwd. */
|
|
58390
58350
|
function currentMailSessionKey(env = process.env) {
|
|
@@ -59841,7 +59801,7 @@ function savedConnectedProfiles(configDir, exclude) {
|
|
|
59841
59801
|
*/
|
|
59842
59802
|
async function otherProfiles(configDir, session, current) {
|
|
59843
59803
|
if (session) try {
|
|
59844
|
-
const { connectedProfilesForSession } = await import("./machine-session-
|
|
59804
|
+
const { connectedProfilesForSession } = await import("./machine-session-CE31cwx2.js").then((n) => n.s);
|
|
59845
59805
|
return {
|
|
59846
59806
|
inSession: true,
|
|
59847
59807
|
profiles: connectedProfilesForSession(configDir, session, current)
|
|
@@ -61461,4 +61421,4 @@ function emptyDeliveriesHint(sdkName, query) {
|
|
|
61461
61421
|
function canonicalizeCliReferences(description) {
|
|
61462
61422
|
return canonicalCliText(description).replaceAll("`primitive emails:latest`", "`primitive emails latest`").replaceAll("`primitive describe emails:get-email | jq '.responseSchema.properties'`", "`primitive describe emails:get | jq '.responseSchema.properties'`");
|
|
61463
61423
|
}
|
|
61464
|
-
export { replyInteractionWarning as $,
|
|
61424
|
+
export { replyInteractionWarning as $, resolveDomainNames as $t, describeWake as A, revokeUserLogin as An, connectNextSteps as At, wakeRecipientField as B, countFromMeta as Bt, withApproval as C, selectedOrgFromEnv as Cn, sendWaitClampNotice as Ct, openBrowser as D, displayedRoleKey as Dn, thrownErrorExitCode as Dt, listenForCopyHotkey as E, credentialsFromUserLogin as En, successfulSendOutcome as Et, sentInThread as F, sanitizeForTerminal as Fn, currentMailSessionKey as Ft, pendingMailPath as G, focusProfile as Gt, claimPendingMail as H, focusFlagValues as Ht, serverMuted as I, shownLine as In, formatAlreadySentNotice as It, removePendingMail as J, manyDomainsSupported as Jt, readPendingMail as K, joinNames as Kt, serverRelationship as L, setKnownCommands as Ln, FOCUS_ENV as Lt, formatMailWakeLine as M, roleKeyText as Mn, generatedAgentName as Mt, latestOwnOutbound as N, switchCurrentOrg as Nn, identitySuggestions as Nt, explainPendingMailNotFound as O, fetchCliOrgs as On, DEFAULT_ENROLL_NAME as Ot, readThreadContext as P, routeWarningLines as Pn, loadSkillLine as Pt, replyExpectation as Q, readDomainsOrRefusal as Qt, skillFirstLine as R, operationManifest as Rn, FOCUS_SERVER_SUPPORT as Rt, terminalApprovalIo as S, resolveCliApiRequestConfig as Sn, sendOutcomeExitCode as St, formatBrowserLoginInstructions as T, RESTRICTED_ROLE_NOTE as Tn, serializeErrorPayload as Tt, clearConsumedPendingMail as U, focusFlags as Ut, wakeRelationship as V, focusEmptyHint as Vt, clearReadPendingMail as W, focusForCorpus as Wt, interactionNextActions as X, oneDomainAtATimeError as Xt, interactionHumanLine as Y, normalizeDomainNames as Yt, readEmailInteraction as Z, queryScopesItself as Zt, BROWSER_FLAG_DESCRIPTION as _, SAVED_CLI_OAUTH_SESSION_EXPIRED_MESSAGE as _n, formatSendRecordFailureSummary as _t, createOperationCommand as a, withFlagSuggestion as an, assertValidIdempotencyKey as at, approveThenRerunHint as b, refreshStoredCliCredentials as bn, sendErrorMessage as bt, formatErrorPayload as c, readCallerMailFor as cn, checkPriorReplies as ct, networkErrorHint as d, fetchBoundedPages as dn, excludeSignalReplies as dt, resolveFocus as en, wakeInteractionSentence as et, readTextFileFlag as f, withBooleanFlagValues as fn, followUpCommandPrefix as ft, writeErrorWithHints as g, ConnectedAgentKeyRequiredError as gn, formatSendFailureSummary as gt, surfaceUnauthorizedHint as h, withAttachmentWait as hn, formatPriorRepliesWarning as ht, TIME_FLAG_DESCRIPTION as i, writeFocusLine as in, apiResultHttpStatus as it, displayAddress as j, roleKeyLabel as jn, defaultConnectionName as jt, bareAddress as k, isBuiltInRoleKey as kn, cliInvocation as kt, hasControlCharacter as l, formatFact as ln, classifySendError as lt, runWithTiming as m, ATTACHMENT_WAIT_MAX_MS as mn, formatPriorRepliesCheckSkipped as mt, API_ERROR_CODES as n, withFocusMeta as nn, MAX_SEND_WAIT_TIMEOUT_MS as nt, extractErrorCode as o, emptyEmailListHint as on, buildFollowUpCommand as ot, refusesCredential as p, ATTACHMENT_WAIT_FLAG_DESCRIPTION as pn, formatDeletedEarlierSendNotice as pt, recordPendingMail as q, loadSavedFocus as qt, PAGED_LIMIT_MAX as r, withoutFocus as rn, SEND_OUTCOME_HELP as rt, extractErrorPayload as s, mailReach as sn, buildThrownSendFailureEnvelope as st, API_BASE_URL_FLAG_DESCRIPTION as t, saveFocus as tn, IDEMPOTENCY_KEY_FLAG_DESCRIPTION as tt, isGrantRefusal as u, isEmailId as un, deriveSendIdempotencyKey as ut, STEP_UP_HEADER as v, createAuthenticatedCliApiClient as vn, priorRepliesThatWentOut as vt, canOfferCopyHotkey as w, CliOrgRefusedError as wn, sentHistoryWindowStart as wt, promptLine as x, refuseOrgSelectionForProfile as xn, sendIdentityFields as xt, STEP_UP_TOKEN_FLAG_DESCRIPTION as y, createCliApiClient as yn, reportSendCommandResult as yt, wakeReadCommand as z, NO_FOCUS as zt };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { n as createConfig, t as createClient } from "./client.gen-6rZvmHfx.js";
|
|
2
2
|
import { c as mailTime, d as readMailJson, h as writeMailJson, i as mailId, l as privateMailDirectory, o as mailObject, r as mailAddress, s as mailString } from "./shared-mail-files-BAQSGxxz.js";
|
|
3
3
|
import { Errors } from "@oclif/core";
|
|
4
|
-
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
-
import { randomUUID } from "node:crypto";
|
|
6
|
-
import { dirname, join } from "node:path";
|
|
4
|
+
import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { dirname, join, resolve } from "node:path";
|
|
7
7
|
// ../packages/api-core/src/client.ts
|
|
8
8
|
/**
|
|
9
9
|
* Host-aware Primitive API client and shared error type.
|
|
@@ -38,6 +38,456 @@ var PrimitiveApiClient = class {
|
|
|
38
38
|
return this.client.setConfig(config);
|
|
39
39
|
}
|
|
40
40
|
};
|
|
41
|
+
// src/oclif/runtime-session.ts
|
|
42
|
+
/**
|
|
43
|
+
* The variables each runtime sets to its exact session ID, first match wins.
|
|
44
|
+
* The loaded Codex thread is the receiving identity; the process session ID
|
|
45
|
+
* is only a fallback when no thread ID is exposed.
|
|
46
|
+
*/
|
|
47
|
+
const RUNTIME_SESSION_VARIABLES = {
|
|
48
|
+
claude: ["CLAUDE_CODE_SESSION_ID"],
|
|
49
|
+
codex: ["CODEX_THREAD_ID", "CODEX_SESSION_ID"]
|
|
50
|
+
};
|
|
51
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
52
|
+
/** Each runtime whose environment names a session UUID. Never guessed from history or cwd. */
|
|
53
|
+
function runtimeSessions(env) {
|
|
54
|
+
return Object.keys(RUNTIME_SESSION_VARIABLES).flatMap((runtime) => {
|
|
55
|
+
for (const variable of RUNTIME_SESSION_VARIABLES[runtime]) {
|
|
56
|
+
const value = env[variable]?.trim().toLowerCase();
|
|
57
|
+
if (!value) continue;
|
|
58
|
+
return UUID.test(value) ? [{
|
|
59
|
+
runtime,
|
|
60
|
+
session: value,
|
|
61
|
+
variable
|
|
62
|
+
}] : [];
|
|
63
|
+
}
|
|
64
|
+
return [];
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/** The one session the runtime environment names, if exactly one runtime names one. */
|
|
68
|
+
function detectRuntimeSession(env = process.env) {
|
|
69
|
+
const candidates = runtimeSessions(env);
|
|
70
|
+
const [only] = candidates;
|
|
71
|
+
if (!only) return { kind: "none" };
|
|
72
|
+
return candidates.length === 1 ? {
|
|
73
|
+
kind: "detected",
|
|
74
|
+
...only
|
|
75
|
+
} : {
|
|
76
|
+
kind: "ambiguous",
|
|
77
|
+
candidates
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The runtime whose tool environment names this exact session. A session ID
|
|
82
|
+
* that matches neither runtime's variable, or both, has no detectable runtime.
|
|
83
|
+
*/
|
|
84
|
+
function detectAgentRuntime(session, env = process.env) {
|
|
85
|
+
const wanted = session.trim().toLowerCase();
|
|
86
|
+
const matches = runtimeSessions(env).filter((candidate) => candidate.session === wanted);
|
|
87
|
+
return matches.length === 1 ? matches[0]?.runtime ?? null : null;
|
|
88
|
+
}
|
|
89
|
+
/** Every variable a runtime may name its session in, for messages. */
|
|
90
|
+
function runtimeSessionVariableList() {
|
|
91
|
+
const names = Object.values(RUNTIME_SESSION_VARIABLES).flat();
|
|
92
|
+
return `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
|
|
93
|
+
}
|
|
94
|
+
// src/oclif/agent-pass.ts
|
|
95
|
+
const AGENT_PASS_PROFILE_ENV = "PRIMITIVE_AGENT_PASS_PROFILE";
|
|
96
|
+
const AGENT_PASS_DIR = "agent-passes";
|
|
97
|
+
const PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
|
|
98
|
+
const TOKEN_PATTERN = /\b(pit_v1_[A-Za-z0-9_-]{16,256})\b/;
|
|
99
|
+
const EXACT_TOKEN_PATTERN = /^pit_v1_[A-Za-z0-9_-]{16,256}$/;
|
|
100
|
+
var AgentPassAuthError = class extends Error {
|
|
101
|
+
constructor(message) {
|
|
102
|
+
super(message);
|
|
103
|
+
this.name = "AgentPassAuthError";
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
function isRecord$3(value) {
|
|
107
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
108
|
+
}
|
|
109
|
+
function stripTrailingSlashes(value) {
|
|
110
|
+
let end = value.length;
|
|
111
|
+
while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
|
|
112
|
+
return value.slice(0, end);
|
|
113
|
+
}
|
|
114
|
+
function normalizeBaseUrl(raw) {
|
|
115
|
+
const trimmed = raw?.trim();
|
|
116
|
+
if (!trimmed) return DEFAULT_API_BASE_URL;
|
|
117
|
+
return stripTrailingSlashes(trimmed);
|
|
118
|
+
}
|
|
119
|
+
function isLocalhostHostname(hostname) {
|
|
120
|
+
const lower = hostname.toLowerCase();
|
|
121
|
+
return lower === "localhost" || lower === "127.0.0.1" || lower === "[::1]" || lower === "::1";
|
|
122
|
+
}
|
|
123
|
+
function validateAccessBaseUrl(rawUrl) {
|
|
124
|
+
let parsed;
|
|
125
|
+
try {
|
|
126
|
+
parsed = new URL(rawUrl);
|
|
127
|
+
} catch {
|
|
128
|
+
throw new AgentPassAuthError("Access Pass URL is not a valid URL. Paste the full presigned access URL or pit_v1_ token.");
|
|
129
|
+
}
|
|
130
|
+
if (parsed.username || parsed.password) throw new AgentPassAuthError("Access Pass URL must not include embedded credentials.");
|
|
131
|
+
const isHttps = parsed.protocol === "https:";
|
|
132
|
+
const isLocalHttp = parsed.protocol === "http:" && isLocalhostHostname(parsed.hostname);
|
|
133
|
+
if (!isHttps && !isLocalHttp) throw new AgentPassAuthError("Access Pass URL must use https (or http only for localhost).");
|
|
134
|
+
const cleanPath = stripTrailingSlashes(parsed.pathname);
|
|
135
|
+
const lowerPath = cleanPath.toLowerCase();
|
|
136
|
+
const accessIdx = lowerPath.indexOf("/v1/access/");
|
|
137
|
+
let basePath;
|
|
138
|
+
if (accessIdx !== -1) basePath = cleanPath.slice(0, accessIdx + 3);
|
|
139
|
+
else if (lowerPath === "/v1" || lowerPath.endsWith("/v1")) basePath = cleanPath;
|
|
140
|
+
else if (cleanPath === "" || cleanPath === "/") basePath = "/v1";
|
|
141
|
+
else basePath = `${cleanPath}/v1`;
|
|
142
|
+
return `${parsed.protocol}//${parsed.host}${basePath}`;
|
|
143
|
+
}
|
|
144
|
+
function validateAgentPassProfileName(profile) {
|
|
145
|
+
const trimmed = profile.trim();
|
|
146
|
+
if (!PROFILE_NAME_PATTERN.test(trimmed)) throw new AgentPassAuthError("Profile name must start with a letter or number and contain only letters, numbers, dots, underscores, or hyphens (at most 63 characters).");
|
|
147
|
+
return trimmed;
|
|
148
|
+
}
|
|
149
|
+
function agentPassTokenSha256(token) {
|
|
150
|
+
return createHash("sha256").update(token).digest("hex");
|
|
151
|
+
}
|
|
152
|
+
function trimWrapperChars(value) {
|
|
153
|
+
const leading = `"'<>()\`[`;
|
|
154
|
+
const trailing = `"'<>()\`].,;`;
|
|
155
|
+
let start = 0;
|
|
156
|
+
let end = value.length;
|
|
157
|
+
while (start < end && leading.includes(value[start] ?? "")) start += 1;
|
|
158
|
+
while (end > start && trailing.includes(value[end - 1] ?? "")) end -= 1;
|
|
159
|
+
return value.slice(start, end);
|
|
160
|
+
}
|
|
161
|
+
function extractUrlWithToken(input) {
|
|
162
|
+
for (const rawPiece of input.split(/\s+/)) {
|
|
163
|
+
const piece = trimWrapperChars(rawPiece);
|
|
164
|
+
const lower = piece.toLowerCase();
|
|
165
|
+
if (!lower.startsWith("http://") && !lower.startsWith("https://")) continue;
|
|
166
|
+
let parsed;
|
|
167
|
+
try {
|
|
168
|
+
parsed = new URL(piece);
|
|
169
|
+
} catch {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const idx = parsed.pathname.toLowerCase().indexOf("/v1/access/");
|
|
173
|
+
if (idx === -1) continue;
|
|
174
|
+
const token = parsed.pathname.slice(idx + 11).split("/")[0] ?? "";
|
|
175
|
+
if (EXACT_TOKEN_PATTERN.test(token)) return {
|
|
176
|
+
url: piece,
|
|
177
|
+
token
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
function parseAccessPassInput(rawInput, explicitApiBaseUrl) {
|
|
183
|
+
const trimmed = rawInput.trim();
|
|
184
|
+
if (!trimmed) throw new AgentPassAuthError("No Access Pass URL or pit_v1_ token was provided. Pass it as an argument or pipe it on stdin.");
|
|
185
|
+
const urlMatch = extractUrlWithToken(trimmed);
|
|
186
|
+
if (urlMatch) {
|
|
187
|
+
const inferredBaseUrl = validateAccessBaseUrl(urlMatch.url);
|
|
188
|
+
const apiBaseUrl = explicitApiBaseUrl?.trim() ? validateAccessBaseUrl(normalizeBaseUrl(explicitApiBaseUrl)) : inferredBaseUrl;
|
|
189
|
+
return {
|
|
190
|
+
token: urlMatch.token,
|
|
191
|
+
apiBaseUrl
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
const tokenMatch = TOKEN_PATTERN.exec(trimmed);
|
|
195
|
+
if (tokenMatch?.[1]) {
|
|
196
|
+
const apiBaseUrl = explicitApiBaseUrl?.trim() ? validateAccessBaseUrl(normalizeBaseUrl(explicitApiBaseUrl)) : DEFAULT_API_BASE_URL;
|
|
197
|
+
return {
|
|
198
|
+
token: tokenMatch[1],
|
|
199
|
+
apiBaseUrl
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
throw new AgentPassAuthError("Could not find a valid Primitive Access Pass URL or pit_v1_ token in the input.");
|
|
203
|
+
}
|
|
204
|
+
function agentPassMetadata(pass) {
|
|
205
|
+
const { api_key: _redacted, ...meta } = pass;
|
|
206
|
+
return meta;
|
|
207
|
+
}
|
|
208
|
+
function agentPassRootDir(configDir) {
|
|
209
|
+
return join(configDir, AGENT_PASS_DIR);
|
|
210
|
+
}
|
|
211
|
+
function agentPassClaimCachePath(configDir, tokenHash) {
|
|
212
|
+
return join(agentPassRootDir(configDir), "claims", `${tokenHash}.json`);
|
|
213
|
+
}
|
|
214
|
+
function resolveAgentPassSlot(params) {
|
|
215
|
+
const env = params.env ?? process.env;
|
|
216
|
+
const profileName = params.profile?.trim() || env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
|
|
217
|
+
if (profileName) {
|
|
218
|
+
const safe = validateAgentPassProfileName(profileName);
|
|
219
|
+
return {
|
|
220
|
+
path: join(agentPassRootDir(params.configDir), "profiles", `${safe}.json`),
|
|
221
|
+
binding: {
|
|
222
|
+
kind: "profile",
|
|
223
|
+
profile: safe
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
const detected = detectRuntimeSession(env);
|
|
228
|
+
if (detected.kind === "ambiguous") throw new AgentPassAuthError(`Multiple coding agent sessions were detected in this environment (${detected.candidates.map((c) => `${c.variable}=${c.session}`).join(", ")}). Pass --profile <name> or set ${AGENT_PASS_PROFILE_ENV} to bind an Access Pass explicitly.`);
|
|
229
|
+
if (detected.kind === "detected") return {
|
|
230
|
+
path: join(agentPassRootDir(params.configDir), "sessions", `${detected.runtime}-${detected.session}.json`),
|
|
231
|
+
binding: {
|
|
232
|
+
kind: "session",
|
|
233
|
+
runtime: detected.runtime,
|
|
234
|
+
session: detected.session
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
return {
|
|
238
|
+
path: join(agentPassRootDir(params.configDir), "default.json"),
|
|
239
|
+
binding: { kind: "default" }
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
function ensurePrivateDir(dirPath, stopAtDir) {
|
|
243
|
+
mkdirSync(dirPath, {
|
|
244
|
+
mode: 448,
|
|
245
|
+
recursive: true
|
|
246
|
+
});
|
|
247
|
+
if (process.platform === "win32") return;
|
|
248
|
+
const resolvedStop = stopAtDir ? resolve(stopAtDir) : null;
|
|
249
|
+
let current = resolve(dirPath);
|
|
250
|
+
for (;;) {
|
|
251
|
+
try {
|
|
252
|
+
if (lstatSync(current).isSymbolicLink()) throw new AgentPassAuthError(`Refusing to use symlinked Access Pass directory at ${current}.`);
|
|
253
|
+
chmodSync(current, 448);
|
|
254
|
+
} catch (error) {
|
|
255
|
+
if (error instanceof AgentPassAuthError) throw error;
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
if (!resolvedStop || current === resolvedStop) break;
|
|
259
|
+
const parent = dirname(current);
|
|
260
|
+
if (parent === current) break;
|
|
261
|
+
current = parent;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
function assertPrivateRegularFile(filePath) {
|
|
265
|
+
const st = lstatSync(filePath);
|
|
266
|
+
if (st.isSymbolicLink() || !st.isFile()) throw new AgentPassAuthError(`Refusing to read Access Pass at ${filePath}: expected a regular file.`);
|
|
267
|
+
if (process.platform !== "win32" && (st.mode & 63) !== 0) throw new AgentPassAuthError(`Refusing to read Access Pass at ${filePath}: file permissions are too open. Run \`chmod 600 "${filePath}"\` or \`primitive disconnect --local-only\`.`);
|
|
268
|
+
}
|
|
269
|
+
function writePrivateJsonAtomic(filePath, data, privateRootDir) {
|
|
270
|
+
ensurePrivateDir(dirname(filePath), privateRootDir);
|
|
271
|
+
try {
|
|
272
|
+
if (lstatSync(filePath).isSymbolicLink()) throw new AgentPassAuthError(`Refusing to overwrite symlinked Access Pass file at ${filePath}.`);
|
|
273
|
+
} catch (error) {
|
|
274
|
+
if (error instanceof AgentPassAuthError) throw error;
|
|
275
|
+
if (!(error && typeof error === "object" && error.code === "ENOENT")) throw error;
|
|
276
|
+
}
|
|
277
|
+
const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
278
|
+
try {
|
|
279
|
+
writeFileSync(tempPath, `${JSON.stringify(data, null, 2)}\n`, {
|
|
280
|
+
flag: "wx",
|
|
281
|
+
mode: 384
|
|
282
|
+
});
|
|
283
|
+
if (process.platform !== "win32") chmodSync(tempPath, 384);
|
|
284
|
+
renameSync(tempPath, filePath);
|
|
285
|
+
if (process.platform !== "win32") chmodSync(filePath, 384);
|
|
286
|
+
} catch (error) {
|
|
287
|
+
rmSync(tempPath, { force: true });
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function parseStoredAgentPass(raw) {
|
|
292
|
+
if (!isRecord$3(raw) || raw.version !== 1 || raw.auth_method !== "agent_pass") throw new AgentPassAuthError("Saved Access Pass file is malformed. Run `primitive disconnect --local-only` and reconnect with a fresh pass.");
|
|
293
|
+
if (typeof raw.api_key !== "string" || raw.api_key.trim().length === 0) throw new AgentPassAuthError("Saved Access Pass file is missing its credential. Run `primitive disconnect --local-only` and reconnect.");
|
|
294
|
+
if (typeof raw.api_base_url !== "string" || raw.api_base_url.trim().length === 0) throw new AgentPassAuthError("Saved Access Pass file is missing api_base_url. Run `primitive disconnect --local-only` and reconnect.");
|
|
295
|
+
if (typeof raw.expires_at !== "string" || Number.isNaN(Date.parse(raw.expires_at))) throw new AgentPassAuthError("Saved Access Pass file has an invalid expires_at timestamp. Run `primitive disconnect --local-only` and reconnect.");
|
|
296
|
+
const bindingRaw = isRecord$3(raw.binding) ? raw.binding : null;
|
|
297
|
+
let binding = { kind: "default" };
|
|
298
|
+
if (bindingRaw?.kind === "session" && typeof bindingRaw.runtime === "string" && typeof bindingRaw.session === "string") binding = {
|
|
299
|
+
kind: "session",
|
|
300
|
+
runtime: bindingRaw.runtime,
|
|
301
|
+
session: bindingRaw.session
|
|
302
|
+
};
|
|
303
|
+
else if (bindingRaw?.kind === "profile" && typeof bindingRaw.profile === "string") binding = {
|
|
304
|
+
kind: "profile",
|
|
305
|
+
profile: bindingRaw.profile
|
|
306
|
+
};
|
|
307
|
+
return {
|
|
308
|
+
version: 1,
|
|
309
|
+
auth_method: "agent_pass",
|
|
310
|
+
api_key: raw.api_key,
|
|
311
|
+
api_base_url: validateAccessBaseUrl(normalizeBaseUrl(raw.api_base_url)),
|
|
312
|
+
pass_id: typeof raw.pass_id === "string" ? raw.pass_id : null,
|
|
313
|
+
key_id: typeof raw.key_id === "string" ? raw.key_id : null,
|
|
314
|
+
label: typeof raw.label === "string" && raw.label ? raw.label : "Agent Pass",
|
|
315
|
+
mode: typeof raw.mode === "string" && raw.mode ? raw.mode : "read_only",
|
|
316
|
+
...typeof raw.purpose === "string" ? { purpose: raw.purpose } : {},
|
|
317
|
+
...typeof raw.profile_hint === "string" ? { profile_hint: raw.profile_hint } : {},
|
|
318
|
+
...typeof raw.mcp_url === "string" ? { mcp_url: raw.mcp_url } : {},
|
|
319
|
+
expires_at: raw.expires_at,
|
|
320
|
+
slice_summary: typeof raw.slice_summary === "string" ? raw.slice_summary : null,
|
|
321
|
+
claimed_at: typeof raw.claimed_at === "string" ? raw.claimed_at : (/* @__PURE__ */ new Date()).toISOString(),
|
|
322
|
+
revoked_at: typeof raw.revoked_at === "string" ? raw.revoked_at : null,
|
|
323
|
+
token_sha256: typeof raw.token_sha256 === "string" ? raw.token_sha256 : "",
|
|
324
|
+
binding
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
function readAgentPassFile(filePath) {
|
|
328
|
+
let rawText;
|
|
329
|
+
try {
|
|
330
|
+
assertPrivateRegularFile(filePath);
|
|
331
|
+
rawText = readFileSync(filePath, "utf8");
|
|
332
|
+
} catch (error) {
|
|
333
|
+
if (error instanceof AgentPassAuthError) throw error;
|
|
334
|
+
if (error && typeof error === "object" && error.code === "ENOENT") return null;
|
|
335
|
+
throw new AgentPassAuthError(`Could not read saved Access Pass: ${error instanceof Error ? error.message : String(error)}`);
|
|
336
|
+
}
|
|
337
|
+
let parsed;
|
|
338
|
+
try {
|
|
339
|
+
parsed = JSON.parse(rawText);
|
|
340
|
+
} catch {
|
|
341
|
+
throw new AgentPassAuthError("Saved Access Pass file is not valid JSON. Run `primitive disconnect --local-only` and reconnect.");
|
|
342
|
+
}
|
|
343
|
+
return parseStoredAgentPass(parsed);
|
|
344
|
+
}
|
|
345
|
+
function isAgentPassExpired(pass, now = Date.now) {
|
|
346
|
+
if (pass.revoked_at) return true;
|
|
347
|
+
return Date.parse(pass.expires_at) <= now();
|
|
348
|
+
}
|
|
349
|
+
function saveAgentPass(params) {
|
|
350
|
+
const rootDir = agentPassRootDir(params.configDir);
|
|
351
|
+
writePrivateJsonAtomic(params.slotPath, params.pass, rootDir);
|
|
352
|
+
if (params.pass.token_sha256) writePrivateJsonAtomic(agentPassClaimCachePath(params.configDir, params.pass.token_sha256), params.pass, rootDir);
|
|
353
|
+
}
|
|
354
|
+
function loadCachedAgentPassByToken(params) {
|
|
355
|
+
const hash = agentPassTokenSha256(params.token);
|
|
356
|
+
const cachePath = agentPassClaimCachePath(params.configDir, hash);
|
|
357
|
+
try {
|
|
358
|
+
const cached = readAgentPassFile(cachePath);
|
|
359
|
+
if (!cached || isAgentPassExpired(cached, params.now)) return null;
|
|
360
|
+
return cached;
|
|
361
|
+
} catch {
|
|
362
|
+
return null;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
function loadActiveAgentPass(params) {
|
|
366
|
+
const env = params.env ?? process.env;
|
|
367
|
+
const explicitProfile = params.profile?.trim() || env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
|
|
368
|
+
const slot = resolveAgentPassSlot({
|
|
369
|
+
configDir: params.configDir,
|
|
370
|
+
profile: explicitProfile,
|
|
371
|
+
env
|
|
372
|
+
});
|
|
373
|
+
const pass = readAgentPassFile(slot.path);
|
|
374
|
+
if (!pass) {
|
|
375
|
+
if (explicitProfile) throw new AgentPassAuthError(`Access Pass profile "${explicitProfile}" selected by ${AGENT_PASS_PROFILE_ENV} is not saved on this machine. Run \`primitive connect --profile ${explicitProfile} <url>\` or unset ${AGENT_PASS_PROFILE_ENV}.`);
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
if (isAgentPassExpired(pass, params.now)) throw new AgentPassAuthError(`The Primitive Access Pass bound to ${slot.binding.kind === "session" ? "this session" : slot.binding.kind === "profile" ? `profile "${slot.binding.profile}"` : "this machine"} (${pass.label}) has ${pass.revoked_at ? "been revoked" : `expired at ${pass.expires_at}`}. Refusing to fall back to any other login. Request a fresh Access Pass and run \`primitive connect <url>\`, or run \`primitive disconnect --local-only\` to clear the binding.`);
|
|
379
|
+
return {
|
|
380
|
+
pass,
|
|
381
|
+
path: slot.path
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
function deleteAgentPass(params) {
|
|
385
|
+
rmSync(params.slotPath, { force: true });
|
|
386
|
+
if (params.tokenSha256) rmSync(agentPassClaimCachePath(params.configDir, params.tokenSha256), { force: true });
|
|
387
|
+
}
|
|
388
|
+
function extractErrorMessage(payload, status) {
|
|
389
|
+
if (isRecord$3(payload)) {
|
|
390
|
+
const inner = isRecord$3(payload.error) ? payload.error : payload;
|
|
391
|
+
const message = typeof inner.message === "string" ? inner.message : typeof payload.message === "string" ? payload.message : null;
|
|
392
|
+
const code = typeof inner.code === "string" ? inner.code : null;
|
|
393
|
+
if (message && code) return `${message} (${code}, HTTP ${status})`;
|
|
394
|
+
if (message) return `${message} (HTTP ${status})`;
|
|
395
|
+
if (code) return `${code} (HTTP ${status})`;
|
|
396
|
+
}
|
|
397
|
+
return `Request failed with HTTP ${status}`;
|
|
398
|
+
}
|
|
399
|
+
function deriveSliceSummary(data, grantSummary) {
|
|
400
|
+
if (typeof data.slice_summary === "string" && data.slice_summary.trim()) return data.slice_summary.trim();
|
|
401
|
+
const mailScope = grantSummary && isRecord$3(grantSummary.mail_scope) ? grantSummary.mail_scope : null;
|
|
402
|
+
if (!mailScope) return null;
|
|
403
|
+
if (mailScope.kind === "snapshot") {
|
|
404
|
+
const label = typeof mailScope.snapshot_label === "string" && mailScope.snapshot_label.trim() ? mailScope.snapshot_label.trim() : "Frozen snapshot";
|
|
405
|
+
const count = typeof mailScope.snapshot_email_count === "number" ? mailScope.snapshot_email_count : null;
|
|
406
|
+
return count !== null ? `${label} (${count} ${count === 1 ? "email" : "emails"})` : label;
|
|
407
|
+
}
|
|
408
|
+
if (mailScope.kind === "org") return "Organization mailboxes";
|
|
409
|
+
const parts = [];
|
|
410
|
+
if (Array.isArray(mailScope.addresses) && mailScope.addresses.length > 0) {
|
|
411
|
+
const addrs = mailScope.addresses.filter((a) => typeof a === "string" && a.length > 0);
|
|
412
|
+
if (addrs.length > 0) parts.push(addrs.join(", "));
|
|
413
|
+
}
|
|
414
|
+
if (Array.isArray(mailScope.domains) && mailScope.domains.length > 0) {
|
|
415
|
+
const doms = mailScope.domains.filter((d) => typeof d === "string" && d.length > 0);
|
|
416
|
+
if (doms.length > 0) parts.push(`domains: ${doms.join(", ")}`);
|
|
417
|
+
}
|
|
418
|
+
if (Array.isArray(mailScope.rules) && mailScope.rules.length > 0) parts.push(`${mailScope.rules.length} rule(s)`);
|
|
419
|
+
return parts.length > 0 ? parts.join("; ") : null;
|
|
420
|
+
}
|
|
421
|
+
async function claimAccessPassRemote(params) {
|
|
422
|
+
const fetchImpl = params.fetch ?? fetch;
|
|
423
|
+
const endpoint = `${normalizeBaseUrl(params.apiBaseUrl)}/access/claim`;
|
|
424
|
+
let response;
|
|
425
|
+
try {
|
|
426
|
+
response = await fetchImpl(endpoint, {
|
|
427
|
+
method: "POST",
|
|
428
|
+
headers: {
|
|
429
|
+
"content-type": "application/json",
|
|
430
|
+
accept: "application/json"
|
|
431
|
+
},
|
|
432
|
+
body: JSON.stringify({ token: params.token })
|
|
433
|
+
});
|
|
434
|
+
} catch (error) {
|
|
435
|
+
throw new AgentPassAuthError(`Could not reach Primitive to claim the Access Pass: ${error instanceof Error ? error.message : String(error)}`);
|
|
436
|
+
}
|
|
437
|
+
const payload = await response.json().catch(() => null);
|
|
438
|
+
if (!response.ok) throw new AgentPassAuthError(`Could not claim Access Pass: ${extractErrorMessage(payload, response.status)}`);
|
|
439
|
+
const data = isRecord$3(payload) && isRecord$3(payload.data) ? payload.data : payload;
|
|
440
|
+
if (!isRecord$3(data) || typeof data.api_key !== "string" || !data.api_key) throw new AgentPassAuthError("Primitive returned an unexpected Access Pass claim response.");
|
|
441
|
+
const grantSummary = isRecord$3(data.grant_summary) ? data.grant_summary : null;
|
|
442
|
+
const expiresAt = typeof data.expires_at === "string" && !Number.isNaN(Date.parse(data.expires_at)) ? data.expires_at : new Date(Date.now() + 144e5).toISOString();
|
|
443
|
+
const resolvedApiBaseUrl = typeof data.api_base_url === "string" && data.api_base_url.trim() ? validateAccessBaseUrl(data.api_base_url.trim()) : validateAccessBaseUrl(normalizeBaseUrl(params.apiBaseUrl));
|
|
444
|
+
const label = grantSummary && typeof grantSummary.label === "string" && grantSummary.label.trim() ? grantSummary.label.trim() : typeof data.label === "string" && data.label.trim() ? data.label.trim() : typeof data.name === "string" && data.name.trim() ? data.name.trim() : "Agent Pass";
|
|
445
|
+
const mode = grantSummary && typeof grantSummary.mode === "string" && grantSummary.mode.trim() ? grantSummary.mode.trim() : typeof data.mode === "string" && data.mode.trim() ? data.mode.trim() : "read_only";
|
|
446
|
+
const purpose = typeof data.purpose === "string" && data.purpose.trim() ? data.purpose.trim() : grantSummary && typeof grantSummary.purpose === "string" && grantSummary.purpose.trim() ? grantSummary.purpose.trim() : null;
|
|
447
|
+
return {
|
|
448
|
+
api_key: data.api_key,
|
|
449
|
+
api_base_url: resolvedApiBaseUrl,
|
|
450
|
+
pass_id: typeof data.pass_id === "string" ? data.pass_id : typeof data.invitation_id === "string" ? data.invitation_id : null,
|
|
451
|
+
key_id: typeof data.key_id === "string" ? data.key_id : null,
|
|
452
|
+
label,
|
|
453
|
+
mode,
|
|
454
|
+
purpose,
|
|
455
|
+
profile_hint: typeof data.profile_hint === "string" && data.profile_hint.trim() ? data.profile_hint.trim() : null,
|
|
456
|
+
mcp_url: typeof data.mcp_url === "string" && data.mcp_url.trim() ? data.mcp_url.trim() : null,
|
|
457
|
+
expires_at: expiresAt,
|
|
458
|
+
slice_summary: deriveSliceSummary(data, grantSummary),
|
|
459
|
+
grant_summary: grantSummary,
|
|
460
|
+
preview: data.preview ?? null,
|
|
461
|
+
guide: data.guide ?? null
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
async function revokeAccessPassRemote(params) {
|
|
465
|
+
const fetchImpl = params.fetch ?? fetch;
|
|
466
|
+
const endpoint = `${validateAccessBaseUrl(normalizeBaseUrl(params.apiBaseUrl))}/keys/me/revoke`;
|
|
467
|
+
let response;
|
|
468
|
+
try {
|
|
469
|
+
response = await fetchImpl(endpoint, {
|
|
470
|
+
method: "POST",
|
|
471
|
+
headers: {
|
|
472
|
+
authorization: `Bearer ${params.apiKey}`,
|
|
473
|
+
accept: "application/json"
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
} catch (error) {
|
|
477
|
+
throw new AgentPassAuthError(`Could not reach Primitive to revoke the Access Pass: ${error instanceof Error ? error.message : String(error)}`);
|
|
478
|
+
}
|
|
479
|
+
if (response.ok) return {
|
|
480
|
+
revoked: true,
|
|
481
|
+
alreadyRevoked: false
|
|
482
|
+
};
|
|
483
|
+
if (response.status === 401) return {
|
|
484
|
+
revoked: true,
|
|
485
|
+
alreadyRevoked: true
|
|
486
|
+
};
|
|
487
|
+
const payload = await response.json().catch(() => null);
|
|
488
|
+
const hint = response.status === 403 || response.status === 404 ? " Local credentials were kept so you can retry; revoke the pass in the Primitive dashboard or pass --local-only to remove only the local file." : "";
|
|
489
|
+
throw new AgentPassAuthError(`Could not revoke Access Pass: ${extractErrorMessage(payload, response.status)}.${hint}`);
|
|
490
|
+
}
|
|
41
491
|
// src/oclif/connected-agent-profile.ts
|
|
42
492
|
const AGENT_PROFILE_ENV = "PRIMITIVE_AGENT_PROFILE";
|
|
43
493
|
/**
|
|
@@ -748,6 +1198,41 @@ function resolveCliAuth(params) {
|
|
|
748
1198
|
source: "connected-profile"
|
|
749
1199
|
};
|
|
750
1200
|
}
|
|
1201
|
+
const env = params.env ?? process.env;
|
|
1202
|
+
const passProfile = env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
|
|
1203
|
+
if (passProfile !== void 0) {
|
|
1204
|
+
const activePass = loadActiveAgentPass({
|
|
1205
|
+
configDir: params.configDir,
|
|
1206
|
+
profile: passProfile,
|
|
1207
|
+
env
|
|
1208
|
+
});
|
|
1209
|
+
if (activePass) {
|
|
1210
|
+
const validatedOverrideBase = params.apiBaseUrl !== void 0 ? validateAccessBaseUrl(apiBaseUrl) : void 0;
|
|
1211
|
+
if (apiKey && apiKey !== activePass.pass.api_key || validatedOverrideBase !== void 0 && validatedOverrideBase !== activePass.pass.api_base_url) throw new AgentPassAuthError(`An explicit API key or API origin conflicts with Access Pass profile ${passProfile} selected by ${AGENT_PASS_PROFILE_ENV}; drop the override or unset ${AGENT_PASS_PROFILE_ENV}.`);
|
|
1212
|
+
return {
|
|
1213
|
+
apiKey: activePass.pass.api_key,
|
|
1214
|
+
apiBaseUrl: activePass.pass.api_base_url,
|
|
1215
|
+
credentials: null,
|
|
1216
|
+
agentPass: agentPassMetadata(activePass.pass),
|
|
1217
|
+
source: "agent-pass"
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
const activePass = loadActiveAgentPass({
|
|
1222
|
+
configDir: params.configDir,
|
|
1223
|
+
env
|
|
1224
|
+
});
|
|
1225
|
+
if (activePass) {
|
|
1226
|
+
const validatedOverrideBase = params.apiBaseUrl !== void 0 ? validateAccessBaseUrl(apiBaseUrl) : void 0;
|
|
1227
|
+
if (apiKey && apiKey !== activePass.pass.api_key || validatedOverrideBase !== void 0 && validatedOverrideBase !== activePass.pass.api_base_url) throw new AgentPassAuthError(`An explicit API key or API origin conflicts with the active Access Pass (${activePass.pass.label}) bound to this session; run \`primitive disconnect\` or unset PRIMITIVE_API_KEY to use a different credential.`);
|
|
1228
|
+
return {
|
|
1229
|
+
apiKey: activePass.pass.api_key,
|
|
1230
|
+
apiBaseUrl: activePass.pass.api_base_url,
|
|
1231
|
+
credentials: null,
|
|
1232
|
+
agentPass: agentPassMetadata(activePass.pass),
|
|
1233
|
+
source: "agent-pass"
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
751
1236
|
if (apiKey) return {
|
|
752
1237
|
apiKey,
|
|
753
1238
|
apiBaseUrl,
|
|
@@ -946,4 +1431,4 @@ function redactCliEnvironment(environment) {
|
|
|
946
1431
|
...headers ? { headers } : {}
|
|
947
1432
|
};
|
|
948
1433
|
}
|
|
949
|
-
export {
|
|
1434
|
+
export { loadCachedAgentPassByToken as $, saveActiveChatState as A, parseConnectedAgentProfile as B, resolveCliAuth as C, deleteChatState as D, chatStatePath as E, agentProfileName as F, AGENT_PASS_PROFILE_ENV as G, profileAlreadyConnectedMessage as H, agentProfilesDirectory as I, agentPassTokenSha256 as J, AgentPassAuthError as K, connectedAgentIdentity as L, AGENT_PROFILE_ENV as M, AgentConnectionSetupError as N, loadActiveChatState as O, agentProfileDirectory as P, loadActiveAgentPass as Q, connectedApiBaseUrl as R, normalizeApiBaseUrl as S, saveSignupCredentials as T, requireDefaultLoginProfile as U, parseOwnerMemberAddress as V, saveConnectedAgentProfile as W, deleteAgentPass as X, claimAccessPassRemote as Y, isAgentPassExpired as Z, credentialsPath as _, normalizeCliEnvironmentName as a, detectAgentRuntime as at, detectPrimitiveKeyEnvMisname as b, removeCliEnvironment as c, PrimitiveApiClient as ct, upsertCliEnvironment as d, parseAccessPassInput as et, validateCliHeaderName as f, credentialsLockPath as g, cliAccessTokenExpiresAt as h, loadCliConfig as i, saveAgentPass as it, AGENT_ADDRESS_ENV as j, loadChatConversationByLocalId as k, resolveConfigEnvironment as l, acquireCliCredentialsLock as m, deleteCliConfig as n, resolveAgentPassSlot as nt, parseHeaderAssignment as o, detectRuntimeSession as ot, validateCliHeaderValue as p, agentPassMetadata as q, emptyCliConfig as r, revokeAccessPassRemote as rt, redactCliEnvironment as s, runtimeSessionVariableList as st, DEFAULT_ENVIRONMENT as t, readAgentPassFile as tt, saveCliConfig as u, deleteCliCredentials as v, saveCliCredentials as w, loadCliCredentials as x, deleteCliCredentialsLock as y, loadConnectedAgentProfile as z };
|