primcli 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.
@@ -49,7 +49,13 @@ const COMMAND_RENAMES = {
49
49
  "account:leave-organization": "roles-and-members:leave",
50
50
  "account:show": "account:get",
51
51
  "account:update-account": "account:update",
52
- "activity:list-activity-objects": "activity:list",
52
+ "activity:create-email-activity": "activity:log",
53
+ "activity:create-thread-activity": "activity:log",
54
+ "activity:get-thread-timeline": "activity:timeline",
55
+ "activity:list-activity-objects": "activity:objects",
56
+ "activity:list-mail-activity-actors": "activity:agents",
57
+ "activity:list-org-mail-activity": "activity:list",
58
+ "activity:update-thread-activity": "activity:update",
53
59
  "address-notes:delete-address-note": "address-notes:delete",
54
60
  "address-notes:get-address-note": "address-notes:get",
55
61
  "address-notes:get-public-address-note": "address-notes:get-public",
@@ -15,6 +15,50 @@ import { dirname, join, resolve } from "node:path";
15
15
  * `ReceivedEmail` type from the webhook parsing surface.
16
16
  */
17
17
  const DEFAULT_API_BASE_URL = "https://api.primitive.dev/v1";
18
+ const PRIMITIVE_REASON_HEADER = "X-Primitive-Reason";
19
+ const PRIMITIVE_RUN_ID_HEADER = "X-Primitive-Run-Id";
20
+ const MAX_ACTIVITY_REASON_LENGTH = 500;
21
+ const ACTIVITY_RUN_ID_REGEX = /^[A-Za-z0-9._:/-]{1,128}$/;
22
+ function trimAsciiSpaceTab(value) {
23
+ let start = 0;
24
+ let end = value.length;
25
+ while (start < end && (value[start] === " " || value[start] === " ")) start += 1;
26
+ while (end > start && (value[end - 1] === " " || value[end - 1] === " ")) end -= 1;
27
+ return value.slice(start, end);
28
+ }
29
+ /** Validate and normalize an X-Primitive-Reason header value. */
30
+ function validateActivityReason(raw) {
31
+ if (/[\r\n\0]/.test(raw)) throw new TypeError("reason must not contain newline or null control characters");
32
+ const normalized = trimAsciiSpaceTab(raw.replace(/[ \t]+/g, " "));
33
+ if (!normalized) throw new TypeError("reason must not be empty");
34
+ for (let i = 0; i < normalized.length; i += 1) {
35
+ const code = normalized.charCodeAt(i);
36
+ if (code < 32 || code > 126) throw new TypeError("reason must contain only printable ASCII characters");
37
+ }
38
+ if (normalized.length > MAX_ACTIVITY_REASON_LENGTH) throw new TypeError(`reason must be at most ${MAX_ACTIVITY_REASON_LENGTH} characters`);
39
+ return normalized;
40
+ }
41
+ /** Validate and normalize an X-Primitive-Run-Id header value. */
42
+ function validateActivityRunId(raw) {
43
+ const trimmed = trimAsciiSpaceTab(raw);
44
+ if (!trimmed || !ACTIVITY_RUN_ID_REGEX.test(trimmed)) throw new TypeError("runId must be 1 to 128 characters matching [A-Za-z0-9._:/-]");
45
+ return trimmed;
46
+ }
47
+ function mergeDefaultActivityHeaders(existing, reason, runId) {
48
+ if (reason === void 0 && runId === void 0) return existing;
49
+ const headers = new Headers();
50
+ if (existing instanceof Headers) existing.forEach((value, key) => {
51
+ headers.set(key, value);
52
+ });
53
+ else if (Array.isArray(existing)) {
54
+ for (const [key, value] of existing) if (value !== void 0 && value !== null) headers.set(key, String(value));
55
+ } else if (existing && typeof existing === "object") {
56
+ for (const [key, value] of Object.entries(existing)) if (value !== void 0 && value !== null) headers.set(key, String(value));
57
+ }
58
+ if (reason !== void 0) headers.set(PRIMITIVE_REASON_HEADER, validateActivityReason(reason));
59
+ if (runId !== void 0) headers.set(PRIMITIVE_RUN_ID_HEADER, validateActivityRunId(runId));
60
+ return Object.fromEntries(headers.entries());
61
+ }
18
62
  function createDefaultAuth(apiKey) {
19
63
  return (security) => {
20
64
  if (security.type === "http" && security.scheme === "bearer") return apiKey;
@@ -23,10 +67,12 @@ function createDefaultAuth(apiKey) {
23
67
  var PrimitiveApiClient = class {
24
68
  client;
25
69
  constructor(options = {}) {
26
- const { apiKey, auth, apiBaseUrl = DEFAULT_API_BASE_URL, ...config } = options;
70
+ const { apiKey, auth, apiBaseUrl = DEFAULT_API_BASE_URL, reason, runId, headers, ...config } = options;
27
71
  const resolvedAuth = auth ?? createDefaultAuth(apiKey);
72
+ const resolvedHeaders = mergeDefaultActivityHeaders(headers, reason, runId);
28
73
  this.client = createClient(createConfig({
29
74
  ...config,
75
+ ...resolvedHeaders !== void 0 ? { headers: resolvedHeaders } : {},
30
76
  auth: resolvedAuth,
31
77
  baseUrl: apiBaseUrl
32
78
  }));
@@ -103,7 +149,7 @@ var AgentPassAuthError = class extends Error {
103
149
  this.name = "AgentPassAuthError";
104
150
  }
105
151
  };
106
- function isRecord$3(value) {
152
+ function isRecord$4(value) {
107
153
  return value !== null && typeof value === "object" && !Array.isArray(value);
108
154
  }
109
155
  function stripTrailingSlashes(value) {
@@ -211,6 +257,57 @@ function agentPassRootDir(configDir) {
211
257
  function agentPassClaimCachePath(configDir, tokenHash) {
212
258
  return join(agentPassRootDir(configDir), "claims", `${tokenHash}.json`);
213
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
+ }
214
311
  function resolveAgentPassSlot(params) {
215
312
  const env = params.env ?? process.env;
216
313
  const profileName = params.profile?.trim() || env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
@@ -224,6 +321,18 @@ function resolveAgentPassSlot(params) {
224
321
  }
225
322
  };
226
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
+ }
227
336
  const detected = detectRuntimeSession(env);
228
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.`);
229
338
  if (detected.kind === "detected") return {
@@ -234,6 +343,15 @@ function resolveAgentPassSlot(params) {
234
343
  session: detected.session
235
344
  }
236
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
+ };
237
355
  return {
238
356
  path: join(agentPassRootDir(params.configDir), "default.json"),
239
357
  binding: { kind: "default" }
@@ -289,11 +407,11 @@ function writePrivateJsonAtomic(filePath, data, privateRootDir) {
289
407
  }
290
408
  }
291
409
  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.");
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.");
293
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.");
294
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.");
295
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.");
296
- const bindingRaw = isRecord$3(raw.binding) ? raw.binding : null;
414
+ const bindingRaw = isRecord$4(raw.binding) ? raw.binding : null;
297
415
  let binding = { kind: "default" };
298
416
  if (bindingRaw?.kind === "session" && typeof bindingRaw.runtime === "string" && typeof bindingRaw.session === "string") binding = {
299
417
  kind: "session",
@@ -343,10 +461,6 @@ function readAgentPassFile(filePath) {
343
461
  }
344
462
  return parseStoredAgentPass(parsed);
345
463
  }
346
- function isAgentPassExpired(pass, now = Date.now) {
347
- if (pass.revoked_at) return true;
348
- return Date.parse(pass.expires_at) <= now();
349
- }
350
464
  function saveAgentPass(params) {
351
465
  const rootDir = agentPassRootDir(params.configDir);
352
466
  writePrivateJsonAtomic(params.slotPath, params.pass, rootDir);
@@ -357,12 +471,70 @@ function loadCachedAgentPassByToken(params) {
357
471
  const cachePath = agentPassClaimCachePath(params.configDir, hash);
358
472
  try {
359
473
  const cached = readAgentPassFile(cachePath);
360
- if (!cached || isAgentPassExpired(cached, params.now)) return null;
474
+ if (!cached || cached.revoked_at) return null;
361
475
  return cached;
362
476
  } catch {
363
477
  return null;
364
478
  }
365
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
+ }
366
538
  function loadActiveAgentPass(params) {
367
539
  const env = params.env ?? process.env;
368
540
  const explicitProfile = params.profile?.trim() || env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
@@ -387,8 +559,8 @@ function deleteAgentPass(params) {
387
559
  if (params.tokenSha256) rmSync(agentPassClaimCachePath(params.configDir, params.tokenSha256), { force: true });
388
560
  }
389
561
  function extractErrorMessage(payload, status) {
390
- if (isRecord$3(payload)) {
391
- const inner = isRecord$3(payload.error) ? payload.error : payload;
562
+ if (isRecord$4(payload)) {
563
+ const inner = isRecord$4(payload.error) ? payload.error : payload;
392
564
  const message = typeof inner.message === "string" ? inner.message : typeof payload.message === "string" ? payload.message : null;
393
565
  const code = typeof inner.code === "string" ? inner.code : null;
394
566
  if (message && code) return `${message} (${code}, HTTP ${status})`;
@@ -399,7 +571,7 @@ function extractErrorMessage(payload, status) {
399
571
  }
400
572
  function deriveSliceSummary(data, grantSummary) {
401
573
  if (typeof data.slice_summary === "string" && data.slice_summary.trim()) return data.slice_summary.trim();
402
- 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;
403
575
  if (!mailScope) return null;
404
576
  if (mailScope.kind === "snapshot") {
405
577
  const label = typeof mailScope.snapshot_label === "string" && mailScope.snapshot_label.trim() ? mailScope.snapshot_label.trim() : "Frozen snapshot";
@@ -437,9 +609,9 @@ async function claimAccessPassRemote(params) {
437
609
  }
438
610
  const payload = await response.json().catch(() => null);
439
611
  if (!response.ok) throw new AgentPassAuthError(`Could not claim Access Pass: ${extractErrorMessage(payload, response.status)}`);
440
- const data = isRecord$3(payload) && isRecord$3(payload.data) ? payload.data : payload;
441
- if (!isRecord$3(data) || typeof data.api_key !== "string" || !data.api_key) throw new AgentPassAuthError("Primitive returned an unexpected Access Pass claim response.");
442
- 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;
443
615
  const expiresAt = typeof data.expires_at === "string" && !Number.isNaN(Date.parse(data.expires_at)) ? data.expires_at : new Date(Date.now() + 144e5).toISOString();
444
616
  const resolvedApiBaseUrl = typeof data.api_base_url === "string" && data.api_base_url.trim() ? validateAccessBaseUrl(data.api_base_url.trim()) : validateAccessBaseUrl(normalizeBaseUrl(params.apiBaseUrl));
445
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";
@@ -647,7 +819,7 @@ function profileAlreadyConnectedMessage(profileName, address) {
647
819
  const CHAT_STATE_FILE = "chat-state.json";
648
820
  const CHAT_STATE_VERSION = 2;
649
821
  const MAX_CONVERSATIONS = 50;
650
- function isRecord$2(value) {
822
+ function isRecord$3(value) {
651
823
  return value !== null && typeof value === "object" && !Array.isArray(value);
652
824
  }
653
825
  function nonEmptyString(value) {
@@ -676,7 +848,7 @@ function chatConversationState(params) {
676
848
  };
677
849
  }
678
850
  function parseConversation(raw) {
679
- if (!isRecord$2(raw)) return null;
851
+ if (!isRecord$3(raw)) return null;
680
852
  const localId = parseLocalId(raw.local_id);
681
853
  const recipient = nonEmptyString(raw.recipient);
682
854
  const from = nonEmptyString(raw.from);
@@ -704,7 +876,7 @@ function parseConversation(raw) {
704
876
  };
705
877
  }
706
878
  function parseLegacyActiveState(raw) {
707
- if (!isRecord$2(raw) || raw.version !== 1) return null;
879
+ if (!isRecord$3(raw) || raw.version !== 1) return null;
708
880
  const legacy = parseConversation({
709
881
  ...raw,
710
882
  local_id: 0
@@ -718,7 +890,7 @@ function parseLegacyActiveState(raw) {
718
890
  };
719
891
  }
720
892
  function parseChatState(raw) {
721
- if (!isRecord$2(raw)) return null;
893
+ if (!isRecord$3(raw)) return null;
722
894
  if (raw.version === 1) return parseLegacyActiveState(raw);
723
895
  if (raw.version !== CHAT_STATE_VERSION) return null;
724
896
  if (!Array.isArray(raw.conversations)) return null;
@@ -805,6 +977,119 @@ function saveActiveChatState(configDir, input, options = {}) {
805
977
  });
806
978
  return conversation;
807
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
+ }
808
1093
  // src/oclif/auth.ts
809
1094
  const CREDENTIALS_FILE = "credentials.json";
810
1095
  const CREDENTIALS_LOCK_DIR = "credentials.lock";
@@ -1184,6 +1469,21 @@ function detectPrimitiveKeyEnvMisname(env = process.env) {
1184
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.";
1185
1470
  return null;
1186
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
+ }
1187
1487
  function resolveCliAuth(params) {
1188
1488
  const apiKey = params.apiKey?.trim();
1189
1489
  const apiBaseUrl = normalizeApiBaseUrl(params.apiBaseUrl);
@@ -1201,6 +1501,10 @@ function resolveCliAuth(params) {
1201
1501
  };
1202
1502
  }
1203
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);
1204
1508
  const passProfile = env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
1205
1509
  if (passProfile !== void 0) {
1206
1510
  const activePass = loadActiveAgentPass({
@@ -1209,8 +1513,8 @@ function resolveCliAuth(params) {
1209
1513
  env
1210
1514
  });
1211
1515
  if (activePass) {
1212
- const validatedOverrideBase = params.apiBaseUrl !== void 0 ? validateAccessBaseUrl(apiBaseUrl) : void 0;
1213
- 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}.`);
1214
1518
  return {
1215
1519
  apiKey: activePass.pass.api_key,
1216
1520
  apiBaseUrl: activePass.pass.api_base_url,
@@ -1225,8 +1529,8 @@ function resolveCliAuth(params) {
1225
1529
  env
1226
1530
  });
1227
1531
  if (activePass) {
1228
- const validatedOverrideBase = params.apiBaseUrl !== void 0 ? validateAccessBaseUrl(apiBaseUrl) : void 0;
1229
- 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.`);
1230
1534
  return {
1231
1535
  apiKey: activePass.pass.api_key,
1232
1536
  apiBaseUrl: activePass.pass.api_base_url,
@@ -1235,6 +1539,8 @@ function resolveCliAuth(params) {
1235
1539
  source: "agent-pass"
1236
1540
  };
1237
1541
  }
1542
+ const lockState = readCliLockState(params.configDir);
1543
+ if (lockState.status === "locked") throw new CliAuthLockedError(formatLockedAuthErrorMessage(lockState));
1238
1544
  if (apiKey) return {
1239
1545
  apiKey,
1240
1546
  apiBaseUrl,
@@ -1433,4 +1739,4 @@ function redactCliEnvironment(environment) {
1433
1739
  ...headers ? { headers } : {}
1434
1740
  };
1435
1741
  }
1436
- 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,12 +1,12 @@
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-DiuUnquY.js";
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-x61TNLz-.js";
3
- import { bn as refreshStoredCliCredentials, jt as defaultConnectionName, kt as cliInvocation, xn as refuseOrgSelectionForProfile } from "./api-command-p-qsR7e6.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
+ 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 { 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 { C as readBundledConnectSkill, a as NotificationRetryError, b as installSkill, d as SESSION_UUID, f as connectNativeSession, m as NativeSessionDisconnectedError, p as defaultSessionSocket, t as notificationScope } from "./notify-session-DR1570cm.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";
9
- import { o as scopedChatSenderTrust } from "./scoped-chat-Bss3OjFI.js";
9
+ import { o as scopedChatSenderTrust } from "./scoped-chat-DN0qj4AY.js";
10
10
  import { accessSync, chmodSync, closeSync, constants, copyFileSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
11
11
  import { createHash, randomUUID } from "node:crypto";
12
12
  import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
@@ -1,5 +1,5 @@
1
- import { _ as isTrustedSender, c as classifySignalContent, g as isEmailReceivedEvent, kt as downloadEmailAttachmentPart, v as parseWebhookEvent } from "./repeats-Dj_o6c-X-x61TNLz-.js";
2
- import { R as skillFirstLine, et as wakeInteractionSentence, z as wakeReadCommand } from "./api-command-p-qsR7e6.js";
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 { 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";
@@ -1483,4 +1483,4 @@ async function openSessionNotifications(options) {
1483
1483
  }
1484
1484
  var ContactNoticeSuppressed = class extends Error {};
1485
1485
  var ContactNoticeDeferred = class extends Error {};
1486
- export { readBundledConnectSkill as C, installedVersion as S, NotificationOutcomeUnknownError as _, NotificationRetryError as a, installSkill as b, readConversationStatusContent as c, SESSION_UUID as d, connectNativeSession as f, NativeSessionNotLoadedError as g, NativeSessionError as h, notificationReceiptPage as i, createListenHandler as l, NativeSessionDisconnectedError as m, notificationSenders as n, isRoutineNotificationContent as o, defaultSessionSocket as p, openSessionNotifications as r, notificationPartReader as s, notificationScope as t, readableDelivery as u, bundledSkillNames as v, readBundledSkill as w, installedConnectSkillFile as x, connectSkillTarget as y };
1486
+ export { installedVersion as C, installedConnectSkillFile as S, readBundledSkill as T, NotificationOutcomeUnknownError as _, NotificationRetryError as a, connectSkillTarget as b, readConversationStatusContent as c, SESSION_UUID as d, connectNativeSession as f, NativeSessionNotLoadedError as g, NativeSessionError as h, notificationReceiptPage as i, createListenHandler as l, NativeSessionDisconnectedError as m, notificationSenders as n, isRoutineNotificationContent as o, defaultSessionSocket as p, openSessionNotifications as r, notificationPartReader as s, notificationScope as t, readableDelivery as u, CONNECT_SKILL_NAME as v, readBundledConnectSkill as w, installSkill as x, bundledSkillNames as y };
@@ -1,8 +1,8 @@
1
- import { Qt as getSentEmail } from "../repeats-Dj_o6c-X-x61TNLz-.js";
2
- import { P as readThreadContext, vn as createAuthenticatedCliApiClient } from "../api-command-p-qsR7e6.js";
1
+ import { Qt as getSentEmail } from "../repeats-Dj_o6c-X-CK1wU9lP.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-7tV4fkDC.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 isPlainChatReply, o as scopedChatSenderTrust } from "../scoped-chat-Bss3OjFI.js";
1
+ import { n as isPlainChatReply, o as scopedChatSenderTrust } from "../scoped-chat-DN0qj4AY.js";
2
2
  import { d as readMailJson, h as writeMailJson, i as mailId, l as privateMailDirectory, r as mailAddress } from "../shared-mail-files-BAQSGxxz.js";
3
3
  import { existsSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
@@ -1,4 +1,4 @@
1
- import { n as COMMAND_RENAMES } from "../cli-command-names-DteMqL-H.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. */