@primitivedotdev/cli 3.0.0-preview.25 → 3.0.0-preview.27

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.
@@ -149,7 +149,7 @@ var AgentPassAuthError = class extends Error {
149
149
  this.name = "AgentPassAuthError";
150
150
  }
151
151
  };
152
- function isRecord$3(value) {
152
+ function isRecord$4(value) {
153
153
  return value !== null && typeof value === "object" && !Array.isArray(value);
154
154
  }
155
155
  function stripTrailingSlashes(value) {
@@ -257,6 +257,57 @@ function agentPassRootDir(configDir) {
257
257
  function agentPassClaimCachePath(configDir, tokenHash) {
258
258
  return join(agentPassRootDir(configDir), "claims", `${tokenHash}.json`);
259
259
  }
260
+ const SAFE_SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{3,63}$/;
261
+ const EXTRA_AGENT_SESSION_VARS = [
262
+ {
263
+ runtime: "primitive",
264
+ variables: ["PRIMITIVE_SESSION_ID"]
265
+ },
266
+ {
267
+ runtime: "antigravity",
268
+ variables: ["ANTIGRAVITY_CONVERSATION_ID", "ANTIGRAVITY_SESSION_ID"]
269
+ },
270
+ {
271
+ runtime: "cursor",
272
+ variables: ["CURSOR_SESSION_ID", "CURSOR_TRACE_ID"]
273
+ },
274
+ {
275
+ runtime: "windsurf",
276
+ variables: ["WINDSURF_SESSION_ID", "CODEIUM_SESSION_ID"]
277
+ },
278
+ {
279
+ runtime: "gemini",
280
+ variables: ["GEMINI_SESSION_ID", "GEMINI_CLI_SESSION_ID"]
281
+ },
282
+ {
283
+ runtime: "opencode",
284
+ variables: ["OPENCODE_SESSION_ID"]
285
+ },
286
+ {
287
+ runtime: "agent",
288
+ variables: [
289
+ "AIDER_SESSION_ID",
290
+ "GOOSE_SESSION_ID",
291
+ "AMP_THREAD_ID"
292
+ ]
293
+ }
294
+ ];
295
+ function sanitizeSessionTokenForFilename(raw) {
296
+ const lower = raw.trim().toLowerCase();
297
+ if (SAFE_SESSION_ID_PATTERN.test(lower)) return lower;
298
+ return createHash("sha256").update(lower).digest("hex").slice(0, 32);
299
+ }
300
+ function detectExtraAgentSession(env) {
301
+ for (const entry of EXTRA_AGENT_SESSION_VARS) for (const variable of entry.variables) {
302
+ const value = env[variable]?.trim();
303
+ if (!value) continue;
304
+ return {
305
+ runtime: entry.runtime,
306
+ session: sanitizeSessionTokenForFilename(value)
307
+ };
308
+ }
309
+ return null;
310
+ }
260
311
  function resolveAgentPassSlot(params) {
261
312
  const env = params.env ?? process.env;
262
313
  const profileName = params.profile?.trim() || env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
@@ -270,6 +321,18 @@ function resolveAgentPassSlot(params) {
270
321
  }
271
322
  };
272
323
  }
324
+ const explicitPrimitiveSession = env.PRIMITIVE_SESSION_ID?.trim();
325
+ if (explicitPrimitiveSession) {
326
+ const session = sanitizeSessionTokenForFilename(explicitPrimitiveSession);
327
+ return {
328
+ path: join(agentPassRootDir(params.configDir), "sessions", `primitive-${session}.json`),
329
+ binding: {
330
+ kind: "session",
331
+ runtime: "primitive",
332
+ session
333
+ }
334
+ };
335
+ }
273
336
  const detected = detectRuntimeSession(env);
274
337
  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.`);
275
338
  if (detected.kind === "detected") return {
@@ -280,6 +343,15 @@ function resolveAgentPassSlot(params) {
280
343
  session: detected.session
281
344
  }
282
345
  };
346
+ const extra = detectExtraAgentSession(env);
347
+ if (extra) return {
348
+ path: join(agentPassRootDir(params.configDir), "sessions", `${extra.runtime}-${extra.session}.json`),
349
+ binding: {
350
+ kind: "session",
351
+ runtime: extra.runtime,
352
+ session: extra.session
353
+ }
354
+ };
283
355
  return {
284
356
  path: join(agentPassRootDir(params.configDir), "default.json"),
285
357
  binding: { kind: "default" }
@@ -335,11 +407,11 @@ function writePrivateJsonAtomic(filePath, data, privateRootDir) {
335
407
  }
336
408
  }
337
409
  function parseStoredAgentPass(raw) {
338
- 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.");
410
+ if (!isRecord$4(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.");
339
411
  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.");
340
412
  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.");
341
413
  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.");
342
- const bindingRaw = isRecord$3(raw.binding) ? raw.binding : null;
414
+ const bindingRaw = isRecord$4(raw.binding) ? raw.binding : null;
343
415
  let binding = { kind: "default" };
344
416
  if (bindingRaw?.kind === "session" && typeof bindingRaw.runtime === "string" && typeof bindingRaw.session === "string") binding = {
345
417
  kind: "session",
@@ -389,10 +461,6 @@ function readAgentPassFile(filePath) {
389
461
  }
390
462
  return parseStoredAgentPass(parsed);
391
463
  }
392
- function isAgentPassExpired(pass, now = Date.now) {
393
- if (pass.revoked_at) return true;
394
- return Date.parse(pass.expires_at) <= now();
395
- }
396
464
  function saveAgentPass(params) {
397
465
  const rootDir = agentPassRootDir(params.configDir);
398
466
  writePrivateJsonAtomic(params.slotPath, params.pass, rootDir);
@@ -403,12 +471,70 @@ function loadCachedAgentPassByToken(params) {
403
471
  const cachePath = agentPassClaimCachePath(params.configDir, hash);
404
472
  try {
405
473
  const cached = readAgentPassFile(cachePath);
406
- if (!cached || isAgentPassExpired(cached, params.now)) return null;
474
+ if (!cached || cached.revoked_at) return null;
407
475
  return cached;
408
476
  } catch {
409
477
  return null;
410
478
  }
411
479
  }
480
+ function extractWhoamiGrantDetails(grantData) {
481
+ if (!isRecord$4(grantData)) return {
482
+ permissions: [],
483
+ expiresAt: null,
484
+ accessPass: null
485
+ };
486
+ const root = isRecord$4(grantData.data) ? grantData.data : grantData;
487
+ const grantObj = isRecord$4(root.grant) ? root.grant : null;
488
+ const permissions = (Array.isArray(grantObj?.permissions) ? grantObj.permissions : Array.isArray(root.permissions) ? root.permissions : []).filter((p) => typeof p === "string");
489
+ const rawExpires = typeof grantObj?.expires_at === "string" && !Number.isNaN(Date.parse(grantObj.expires_at)) ? grantObj.expires_at : null;
490
+ const rawPass = isRecord$4(root.access_pass) ? root.access_pass : null;
491
+ return {
492
+ permissions,
493
+ expiresAt: rawExpires,
494
+ accessPass: rawPass ? {
495
+ id: typeof rawPass.id === "string" ? rawPass.id : null,
496
+ name: typeof rawPass.name === "string" && rawPass.name.trim() ? rawPass.name.trim() : null,
497
+ mode: typeof rawPass.mode === "string" && rawPass.mode.trim() ? rawPass.mode.trim() : null,
498
+ manageUrl: typeof rawPass.manage_url === "string" && rawPass.manage_url.trim() ? rawPass.manage_url.trim() : null
499
+ } : null
500
+ };
501
+ }
502
+ function syncAgentPassMetadataFromGrant(params) {
503
+ const details = extractWhoamiGrantDetails(params.grantData);
504
+ const updatedMeta = {
505
+ ...params.pass,
506
+ ...details.expiresAt ? { expires_at: details.expiresAt } : {},
507
+ ...details.accessPass?.id ? { pass_id: details.accessPass.id } : {},
508
+ ...details.accessPass?.name ? { label: details.accessPass.name } : {},
509
+ ...details.accessPass?.mode ? { mode: details.accessPass.mode } : {},
510
+ ...details.accessPass?.manageUrl ? { manage_url: details.accessPass.manageUrl } : {}
511
+ };
512
+ if (updatedMeta.expires_at !== params.pass.expires_at || updatedMeta.label !== params.pass.label || updatedMeta.mode !== params.pass.mode || updatedMeta.pass_id !== params.pass.pass_id || updatedMeta.manage_url !== params.pass.manage_url) try {
513
+ const explicitProfile = params.pass.binding.kind === "profile" ? params.pass.binding.profile : void 0;
514
+ const slot = resolveAgentPassSlot({
515
+ configDir: params.configDir,
516
+ profile: explicitProfile,
517
+ env: params.env
518
+ });
519
+ const existing = readAgentPassFile(slot.path);
520
+ if (existing && !existing.revoked_at) saveAgentPass({
521
+ configDir: params.configDir,
522
+ slotPath: slot.path,
523
+ pass: {
524
+ ...existing,
525
+ expires_at: updatedMeta.expires_at,
526
+ label: updatedMeta.label,
527
+ mode: updatedMeta.mode,
528
+ pass_id: updatedMeta.pass_id,
529
+ ...updatedMeta.manage_url ? { manage_url: updatedMeta.manage_url } : {}
530
+ }
531
+ });
532
+ } catch {}
533
+ return {
534
+ pass: updatedMeta,
535
+ permissions: details.permissions
536
+ };
537
+ }
412
538
  function loadActiveAgentPass(params) {
413
539
  const env = params.env ?? process.env;
414
540
  const explicitProfile = params.profile?.trim() || env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
@@ -433,8 +559,8 @@ function deleteAgentPass(params) {
433
559
  if (params.tokenSha256) rmSync(agentPassClaimCachePath(params.configDir, params.tokenSha256), { force: true });
434
560
  }
435
561
  function extractErrorMessage(payload, status) {
436
- if (isRecord$3(payload)) {
437
- const inner = isRecord$3(payload.error) ? payload.error : payload;
562
+ if (isRecord$4(payload)) {
563
+ const inner = isRecord$4(payload.error) ? payload.error : payload;
438
564
  const message = typeof inner.message === "string" ? inner.message : typeof payload.message === "string" ? payload.message : null;
439
565
  const code = typeof inner.code === "string" ? inner.code : null;
440
566
  if (message && code) return `${message} (${code}, HTTP ${status})`;
@@ -445,7 +571,7 @@ function extractErrorMessage(payload, status) {
445
571
  }
446
572
  function deriveSliceSummary(data, grantSummary) {
447
573
  if (typeof data.slice_summary === "string" && data.slice_summary.trim()) return data.slice_summary.trim();
448
- const mailScope = grantSummary && isRecord$3(grantSummary.mail_scope) ? grantSummary.mail_scope : null;
574
+ const mailScope = grantSummary && isRecord$4(grantSummary.mail_scope) ? grantSummary.mail_scope : null;
449
575
  if (!mailScope) return null;
450
576
  if (mailScope.kind === "snapshot") {
451
577
  const label = typeof mailScope.snapshot_label === "string" && mailScope.snapshot_label.trim() ? mailScope.snapshot_label.trim() : "Frozen snapshot";
@@ -483,9 +609,9 @@ async function claimAccessPassRemote(params) {
483
609
  }
484
610
  const payload = await response.json().catch(() => null);
485
611
  if (!response.ok) throw new AgentPassAuthError(`Could not claim Access Pass: ${extractErrorMessage(payload, response.status)}`);
486
- const data = isRecord$3(payload) && isRecord$3(payload.data) ? payload.data : payload;
487
- if (!isRecord$3(data) || typeof data.api_key !== "string" || !data.api_key) throw new AgentPassAuthError("Primitive returned an unexpected Access Pass claim response.");
488
- const grantSummary = isRecord$3(data.grant_summary) ? data.grant_summary : null;
612
+ const data = isRecord$4(payload) && isRecord$4(payload.data) ? payload.data : payload;
613
+ if (!isRecord$4(data) || typeof data.api_key !== "string" || !data.api_key) throw new AgentPassAuthError("Primitive returned an unexpected Access Pass claim response.");
614
+ const grantSummary = isRecord$4(data.grant_summary) ? data.grant_summary : null;
489
615
  const expiresAt = typeof data.expires_at === "string" && !Number.isNaN(Date.parse(data.expires_at)) ? data.expires_at : new Date(Date.now() + 144e5).toISOString();
490
616
  const resolvedApiBaseUrl = typeof data.api_base_url === "string" && data.api_base_url.trim() ? validateAccessBaseUrl(data.api_base_url.trim()) : validateAccessBaseUrl(normalizeBaseUrl(params.apiBaseUrl));
491
617
  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";
@@ -693,7 +819,7 @@ function profileAlreadyConnectedMessage(profileName, address) {
693
819
  const CHAT_STATE_FILE = "chat-state.json";
694
820
  const CHAT_STATE_VERSION = 2;
695
821
  const MAX_CONVERSATIONS = 50;
696
- function isRecord$2(value) {
822
+ function isRecord$3(value) {
697
823
  return value !== null && typeof value === "object" && !Array.isArray(value);
698
824
  }
699
825
  function nonEmptyString(value) {
@@ -722,7 +848,7 @@ function chatConversationState(params) {
722
848
  };
723
849
  }
724
850
  function parseConversation(raw) {
725
- if (!isRecord$2(raw)) return null;
851
+ if (!isRecord$3(raw)) return null;
726
852
  const localId = parseLocalId(raw.local_id);
727
853
  const recipient = nonEmptyString(raw.recipient);
728
854
  const from = nonEmptyString(raw.from);
@@ -750,7 +876,7 @@ function parseConversation(raw) {
750
876
  };
751
877
  }
752
878
  function parseLegacyActiveState(raw) {
753
- if (!isRecord$2(raw) || raw.version !== 1) return null;
879
+ if (!isRecord$3(raw) || raw.version !== 1) return null;
754
880
  const legacy = parseConversation({
755
881
  ...raw,
756
882
  local_id: 0
@@ -764,7 +890,7 @@ function parseLegacyActiveState(raw) {
764
890
  };
765
891
  }
766
892
  function parseChatState(raw) {
767
- if (!isRecord$2(raw)) return null;
893
+ if (!isRecord$3(raw)) return null;
768
894
  if (raw.version === 1) return parseLegacyActiveState(raw);
769
895
  if (raw.version !== CHAT_STATE_VERSION) return null;
770
896
  if (!Array.isArray(raw.conversations)) return null;
@@ -851,6 +977,119 @@ function saveActiveChatState(configDir, input, options = {}) {
851
977
  });
852
978
  return conversation;
853
979
  }
980
+ // src/oclif/cli-lock.ts
981
+ const CLI_LOCK_FILE = "cli-lock.json";
982
+ const MIN_UNLOCK_SECONDS = 60;
983
+ const MAX_UNLOCK_SECONDS = 86400;
984
+ var CliAuthLockedError = class extends Error {
985
+ constructor(message) {
986
+ super(message);
987
+ this.name = "CliAuthLockedError";
988
+ }
989
+ };
990
+ function cliLockFilePath(configDir) {
991
+ return join(configDir, CLI_LOCK_FILE);
992
+ }
993
+ function isRecord$2(value) {
994
+ return value !== null && typeof value === "object" && !Array.isArray(value);
995
+ }
996
+ function readCliLockState(configDir, now = Date.now) {
997
+ const path = cliLockFilePath(configDir);
998
+ let rawText;
999
+ try {
1000
+ const st = lstatSync(path);
1001
+ if (st.isSymbolicLink() || !st.isFile()) throw new CliAuthLockedError(`Refusing to read Primitive lock file at ${path}: expected a regular file.`);
1002
+ rawText = readFileSync(path, "utf8");
1003
+ } catch (error) {
1004
+ if (error instanceof CliAuthLockedError) throw error;
1005
+ if (error && typeof error === "object" && error.code === "ENOENT") return {
1006
+ status: "unlocked",
1007
+ locked: false
1008
+ };
1009
+ throw new CliAuthLockedError(`Could not read Primitive lock file at ${path}; failing closed. Run \`primitive unlock\` in your terminal to reset.`);
1010
+ }
1011
+ let parsed;
1012
+ try {
1013
+ parsed = JSON.parse(rawText);
1014
+ } catch {
1015
+ throw new CliAuthLockedError(`Primitive lock file at ${path} is malformed; failing closed. Run \`primitive unlock\` in your terminal to reset.`);
1016
+ }
1017
+ if (!isRecord$2(parsed) || parsed.locked !== true) return {
1018
+ status: "unlocked",
1019
+ locked: false
1020
+ };
1021
+ const lockedAt = typeof parsed.locked_at === "string" && parsed.locked_at.trim() ? parsed.locked_at : new Date(now()).toISOString();
1022
+ const reason = typeof parsed.reason === "string" && parsed.reason.trim() ? parsed.reason.trim() : null;
1023
+ const unlockedUntil = typeof parsed.unlocked_until === "string" && !Number.isNaN(Date.parse(parsed.unlocked_until)) ? parsed.unlocked_until : null;
1024
+ if (unlockedUntil && Date.parse(unlockedUntil) > now()) return {
1025
+ status: "temporarily_unlocked",
1026
+ locked: false,
1027
+ lockedAt,
1028
+ unlockedUntil,
1029
+ reason
1030
+ };
1031
+ return {
1032
+ status: "locked",
1033
+ locked: true,
1034
+ lockedAt,
1035
+ reason
1036
+ };
1037
+ }
1038
+ function writeCliLockState(configDir, record) {
1039
+ const path = cliLockFilePath(configDir);
1040
+ const dir = dirname(path);
1041
+ mkdirSync(dir, {
1042
+ recursive: true,
1043
+ mode: 448
1044
+ });
1045
+ try {
1046
+ if (lstatSync(path).isSymbolicLink()) throw new CliAuthLockedError(`Refusing to overwrite symlinked Primitive lock file at ${path}.`);
1047
+ } catch (error) {
1048
+ if (error instanceof CliAuthLockedError) throw error;
1049
+ if (!(error && typeof error === "object" && error.code === "ENOENT")) throw error;
1050
+ }
1051
+ const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
1052
+ try {
1053
+ writeFileSync(tempPath, `${JSON.stringify(record, null, 2)}\n`, {
1054
+ flag: "wx",
1055
+ mode: 384
1056
+ });
1057
+ if (process.platform !== "win32") chmodSync(tempPath, 384);
1058
+ renameSync(tempPath, path);
1059
+ if (process.platform !== "win32") chmodSync(path, 384);
1060
+ } catch (error) {
1061
+ rmSync(tempPath, { force: true });
1062
+ throw error;
1063
+ }
1064
+ }
1065
+ function removeCliLockState(configDir) {
1066
+ const path = cliLockFilePath(configDir);
1067
+ try {
1068
+ lstatSync(path);
1069
+ rmSync(path, { force: true });
1070
+ return true;
1071
+ } catch (error) {
1072
+ if (error && typeof error === "object" && error.code === "ENOENT") return false;
1073
+ throw error;
1074
+ }
1075
+ }
1076
+ function parseUnlockDurationSeconds(raw) {
1077
+ const trimmed = raw.trim().toLowerCase();
1078
+ const match = /^(\d+)(s|m|h|d)$/.exec(trimmed);
1079
+ if (!match?.[1] || !match[2]) throw new Error(`Invalid duration "${raw}". Use a value like 15m, 1h, or 4h (between 1m and 24h).`);
1080
+ const amount = Number.parseInt(match[1], 10);
1081
+ const unit = match[2];
1082
+ const seconds = amount * (unit === "s" ? 1 : unit === "m" ? 60 : unit === "h" ? 3600 : 86400);
1083
+ if (!Number.isFinite(seconds) || seconds < MIN_UNLOCK_SECONDS || seconds > MAX_UNLOCK_SECONDS) throw new Error(`Duration "${raw}" is out of range. Choose between 1m and 24h (for example: 15m, 1h, 4h).`);
1084
+ return seconds;
1085
+ }
1086
+ function formatLockedAuthErrorMessage(state) {
1087
+ return [
1088
+ `Global Primitive credentials are locked (\`primitive lock\` is active).${state.reason ? ` Reason: ${state.reason}.` : ""}`,
1089
+ "AI agents: Do NOT unlock global credentials. Ask the user to share a scoped Access Pass and claim it with `primitive connect <url>` (Access Passes work while locked without using global admin credentials).",
1090
+ "Humans: Run `primitive unlock --for 15m` (auto-relocks) or `primitive unlock` in your interactive terminal to use your global login or PRIMITIVE_API_KEY."
1091
+ ].join("\n");
1092
+ }
854
1093
  // src/oclif/auth.ts
855
1094
  const CREDENTIALS_FILE = "credentials.json";
856
1095
  const CREDENTIALS_LOCK_DIR = "credentials.lock";
@@ -1230,6 +1469,21 @@ function detectPrimitiveKeyEnvMisname(env = process.env) {
1230
1469
  if ((primitiveKey?.length ?? 0) > 0 && (primitiveApiKey?.length ?? 0) === 0) return "PRIMITIVE_KEY is set but the CLI reads PRIMITIVE_API_KEY. Rename your env var, or re-run with PRIMITIVE_API_KEY=$PRIMITIVE_KEY.";
1231
1470
  return null;
1232
1471
  }
1472
+ /**
1473
+ * True when a usable OAuth login session is saved on disk. Used by `pay-email`
1474
+ * to decide whether it can safely ignore an env-only `PRIMITIVE_API_KEY` in
1475
+ * favor of the payer's logged-in account (which owns the inbound challenge
1476
+ * inbox). Returns false when nothing is stored or the stored credential is
1477
+ * unreadable/legacy, so the caller falls back to whatever key did resolve
1478
+ * rather than silently dropping the user's only auth.
1479
+ */
1480
+ function hasStoredCliLogin(configDir) {
1481
+ try {
1482
+ return loadCliCredentials(configDir) !== null;
1483
+ } catch {
1484
+ return false;
1485
+ }
1486
+ }
1233
1487
  function resolveCliAuth(params) {
1234
1488
  const apiKey = params.apiKey?.trim();
1235
1489
  const apiBaseUrl = normalizeApiBaseUrl(params.apiBaseUrl);
@@ -1247,6 +1501,10 @@ function resolveCliAuth(params) {
1247
1501
  };
1248
1502
  }
1249
1503
  const env = params.env ?? process.env;
1504
+ const ambientEnvApiKey = env.PRIMITIVE_API_KEY?.trim() || void 0;
1505
+ const ambientEnvBaseUrl = env.PRIMITIVE_API_BASE_URL?.trim() || void 0;
1506
+ const hasExplicitKeyOverride = Boolean(apiKey && apiKey !== ambientEnvApiKey);
1507
+ const hasExplicitBaseOverride = Boolean(params.apiBaseUrl !== void 0 && params.apiBaseUrl.trim() !== ambientEnvBaseUrl);
1250
1508
  const passProfile = env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
1251
1509
  if (passProfile !== void 0) {
1252
1510
  const activePass = loadActiveAgentPass({
@@ -1255,8 +1513,8 @@ function resolveCliAuth(params) {
1255
1513
  env
1256
1514
  });
1257
1515
  if (activePass) {
1258
- const validatedOverrideBase = params.apiBaseUrl !== void 0 ? validateAccessBaseUrl(apiBaseUrl) : void 0;
1259
- 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}.`);
1516
+ const validatedOverrideBase = hasExplicitBaseOverride ? validateAccessBaseUrl(apiBaseUrl) : void 0;
1517
+ if (hasExplicitKeyOverride && 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}.`);
1260
1518
  return {
1261
1519
  apiKey: activePass.pass.api_key,
1262
1520
  apiBaseUrl: activePass.pass.api_base_url,
@@ -1271,8 +1529,8 @@ function resolveCliAuth(params) {
1271
1529
  env
1272
1530
  });
1273
1531
  if (activePass) {
1274
- const validatedOverrideBase = params.apiBaseUrl !== void 0 ? validateAccessBaseUrl(apiBaseUrl) : void 0;
1275
- 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.`);
1532
+ const validatedOverrideBase = hasExplicitBaseOverride ? validateAccessBaseUrl(apiBaseUrl) : void 0;
1533
+ if (hasExplicitKeyOverride && 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 omit --api-key to use the pass.`);
1276
1534
  return {
1277
1535
  apiKey: activePass.pass.api_key,
1278
1536
  apiBaseUrl: activePass.pass.api_base_url,
@@ -1281,6 +1539,8 @@ function resolveCliAuth(params) {
1281
1539
  source: "agent-pass"
1282
1540
  };
1283
1541
  }
1542
+ const lockState = readCliLockState(params.configDir);
1543
+ if (lockState.status === "locked") throw new CliAuthLockedError(formatLockedAuthErrorMessage(lockState));
1284
1544
  if (apiKey) return {
1285
1545
  apiKey,
1286
1546
  apiBaseUrl,
@@ -1479,4 +1739,4 @@ function redactCliEnvironment(environment) {
1479
1739
  ...headers ? { headers } : {}
1480
1740
  };
1481
1741
  }
1482
- 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 };
1742
+ export { agentPassMetadata as $, removeCliLockState as A, agentProfileDirectory as B, normalizeApiBaseUrl as C, CliAuthLockedError as D, saveSignupCredentials as E, loadChatConversationByLocalId as F, loadConnectedAgentProfile as G, agentProfilesDirectory as H, saveActiveChatState as I, profileAlreadyConnectedMessage as J, parseConnectedAgentProfile as K, AGENT_ADDRESS_ENV as L, chatStatePath as M, deleteChatState as N, parseUnlockDurationSeconds as O, loadActiveChatState as P, AgentPassAuthError as Q, AGENT_PROFILE_ENV as R, loadCliCredentials as S, saveCliCredentials as T, connectedAgentIdentity as U, agentProfileName as V, connectedApiBaseUrl as W, saveConnectedAgentProfile as X, requireDefaultLoginProfile as Y, AGENT_PASS_PROFILE_ENV as Z, credentialsPath as _, normalizeCliEnvironmentName as a, parseAccessPassInput as at, detectPrimitiveKeyEnvMisname as b, removeCliEnvironment as c, revokeAccessPassRemote as ct, upsertCliEnvironment as d, detectAgentRuntime as dt, agentPassTokenSha256 as et, validateCliHeaderName as f, detectRuntimeSession as ft, credentialsLockPath as g, cliAccessTokenExpiresAt as h, loadCliConfig as i, loadCachedAgentPassByToken as it, writeCliLockState as j, readCliLockState as k, resolveConfigEnvironment as l, saveAgentPass as lt, acquireCliCredentialsLock as m, PrimitiveApiClient as mt, deleteCliConfig as n, deleteAgentPass as nt, parseHeaderAssignment as o, readAgentPassFile as ot, validateCliHeaderValue as p, runtimeSessionVariableList as pt, parseOwnerMemberAddress as q, emptyCliConfig as r, loadActiveAgentPass as rt, redactCliEnvironment as s, resolveAgentPassSlot as st, DEFAULT_ENVIRONMENT as t, claimAccessPassRemote as tt, saveCliConfig as u, syncAgentPassMetadataFromGrant as ut, deleteCliCredentials as v, resolveCliAuth as w, hasStoredCliLogin as x, deleteCliCredentialsLock as y, AgentConnectionSetupError as z };
@@ -1,8 +1,8 @@
1
- import { B as parseConnectedAgentProfile, F as agentProfileName, H as profileAlreadyConnectedMessage, I as agentProfilesDirectory, L as connectedAgentIdentity, M as AGENT_PROFILE_ENV, N as AgentConnectionSetupError, P as agentProfileDirectory, R as connectedApiBaseUrl, V as parseOwnerMemberAddress, W as saveConnectedAgentProfile, at as detectAgentRuntime, ct as PrimitiveApiClient, x as loadCliCredentials, z as loadConnectedAgentProfile } from "./cli-config-D2MU7PiU.js";
1
+ import { B as agentProfileDirectory, G as loadConnectedAgentProfile, H as agentProfilesDirectory, J as profileAlreadyConnectedMessage, K as parseConnectedAgentProfile, R as AGENT_PROFILE_ENV, S as loadCliCredentials, U as connectedAgentIdentity, V as agentProfileName, W as connectedApiBaseUrl, X as saveConnectedAgentProfile, dt as detectAgentRuntime, mt as PrimitiveApiClient, q as parseOwnerMemberAddress, z as AgentConnectionSetupError } from "./cli-config-CwZJQIcn.js";
2
2
  import { An as putAgentContact, Ft as getContact, Gn as sendEmail, Hn as searchEmails, Mn as putContact, Pt as getAgentContactPolicy, St as deleteContact, an as listAgentContacts, fr as __exportAll, in as listAgentConnections, jn as putAgentContactPolicy, sn as listContacts, tn as inviteAgentConnection, un as listDomains, wn as listSentEmails, xt as deleteAgentContact, zt as getEmail } from "./repeats-Dj_o6c-X-CK1wU9lP.js";
3
- import { Sn as refuseOrgSelectionForProfile, jt as defaultConnectionName, kt as cliInvocation, xn as refreshStoredCliCredentials } from "./api-command-DhY2wrh5.js";
3
+ import { At as cliInvocation, Cn as refuseOrgSelectionForProfile, Mt as defaultConnectionName, Sn as refreshStoredCliCredentials } from "./api-command-B-nuABGm.js";
4
4
  import { _ as acquireListenLock, b as listenLockHeld, c as mailTime, d as readMailJson, f as removeMailFile, g as ListenStateError, h as writeMailJson, i as mailId, l as privateMailDirectory, o as mailObject, p as syncMailDirectory, r as mailAddress, s as mailString } from "./shared-mail-files-BAQSGxxz.js";
5
- import { a as NotificationRetryError, d as SESSION_UUID, f as connectNativeSession, m as NativeSessionDisconnectedError, p as defaultSessionSocket, t as notificationScope, w as readBundledConnectSkill, x as installSkill } from "./notify-session-DrgOcIT6.js";
5
+ import { a as NotificationRetryError, d as SESSION_UUID, f as connectNativeSession, m as NativeSessionDisconnectedError, p as defaultSessionSocket, t as notificationScope, w as readBundledConnectSkill, x as installSkill } from "./notify-session-CM4_ZYe9.js";
6
6
  import { a as backgroundListenStatus, d as stopBackgroundListen } from "./listen-background-DyBYca28.js";
7
7
  import { t as readSharedMailOwner } from "./shared-mail-watch-DdtgJOrV.js";
8
8
  import { withoutOrgSelection } from "./oclif/global-org-flag.js";
@@ -1,5 +1,5 @@
1
1
  import { _ as isTrustedSender, c as classifySignalContent, g as isEmailReceivedEvent, kt as downloadEmailAttachmentPart, v as parseWebhookEvent } from "./repeats-Dj_o6c-X-CK1wU9lP.js";
2
- import { R as skillFirstLine, et as wakeInteractionSentence, z as wakeReadCommand } from "./api-command-DhY2wrh5.js";
2
+ import { B as wakeReadCommand, tt as wakeInteractionSentence, z as skillFirstLine } from "./api-command-B-nuABGm.js";
3
3
  import { _ as acquireListenLock, g as ListenStateError, y as listenIdentity } from "./shared-mail-files-BAQSGxxz.js";
4
4
  import { closeSync, copyFileSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, opendirSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { createHash, randomUUID, scryptSync } from "node:crypto";
@@ -1,8 +1,8 @@
1
1
  import { Qt as getSentEmail } from "../repeats-Dj_o6c-X-CK1wU9lP.js";
2
- import { P as readThreadContext, vn as createAuthenticatedCliApiClient } from "../api-command-DhY2wrh5.js";
2
+ import { F as readThreadContext, yn as createAuthenticatedCliApiClient } from "../api-command-B-nuABGm.js";
3
3
  import { AUTO_SIGNAL_KIND_ENV, AUTO_WORKING_RENEW_MS, autoSignalsDisabled, clearWorkingSending, markWorkingSending, readAutoClaim, readWorkingLease, recordRenewer, stopWorkingLease, writeWorkingLease } from "./auto-signals.js";
4
4
  import { _ as acquireListenLock } from "../shared-mail-files-BAQSGxxz.js";
5
- import { t as sendSignal } from "../signal-command-BmxZqCot.js";
5
+ import { t as sendSignal } from "../signal-command-D4ZIidPX.js";
6
6
  import { join } from "node:path";
7
7
  import { homedir } from "node:os";
8
8
  // src/oclif/auto-signal-worker.ts
@@ -1,4 +1,4 @@
1
- import { n as COMMAND_RENAMES } from "../cli-command-names-DiNDwwDX.js";
1
+ import { n as COMMAND_RENAMES } from "../cli-command-names-no0f7d7s.js";
2
2
  import { i as jsonOutputRequested } from "../json-output-BMZrLH47.js";
3
3
  // src/oclif/command-not-found.ts
4
4
  /** At most this many commands are suggested for one word. */