@primitivedotdev/cli 3.0.0-preview.3 → 3.0.0-preview.30
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/README.md +110 -39
- package/bin/run.js +21 -2
- package/dist/api-command-JSxKMsEp.js +67356 -0
- package/dist/cli-command-names-A9nkSBH6.js +380 -0
- package/dist/cli-config-BEo5mbDK.js +1750 -0
- package/dist/help-inputs-NGARVZL_.js +109 -0
- package/dist/{json-output-DWrJMakZ.js → json-output-BMZrLH47.js} +25 -6
- package/dist/{listen-background-C0F9gNDD.js → listen-background-DyBYca28.js} +323 -36
- package/dist/{machine-session-BG4getHB.js → machine-session-CDLKmg8U.js} +10 -10
- package/dist/{notify-session-8Jv4jJzI.js → notify-session-BeYhiOD0.js} +71 -32
- package/dist/oclif/auto-signal-worker.js +3 -3
- package/dist/oclif/auto-signals.js +1 -1
- package/dist/oclif/command-not-found.js +133 -0
- package/dist/oclif/command-stdin.js +9 -0
- package/dist/oclif/help.js +82 -17
- package/dist/oclif/index.js +5814 -105060
- package/dist/oclif/listen-supervisor.js +1 -1
- package/dist/oclif/proxy-auto-detect.js +1 -1
- package/dist/oclif/receiver-heal.js +4 -4
- package/dist/oclif/root-signup-hint.js +16 -16
- package/dist/receiver.d.ts +1 -1
- package/dist/{repeats-Dj_o6c-X-BKHiZsYv.js → repeats-Dj_o6c-X-r9r6uQOb.js} +15081 -14000
- package/dist/retry-ids-04ZPJCZY.js +59 -0
- package/dist/{scoped-chat-_AEpylPV.js → scoped-chat-BqmFQ1yz.js} +1 -1
- package/dist/{shared-mail-watch-BAPMsFNv.js → shared-mail-watch-DdtgJOrV.js} +12 -0
- package/dist/{signal-command-CBHAR7zj.js → signal-command-CCfFQ72M.js} +19 -9
- package/dist/skills/primitive-connect/SKILL.md +5 -6
- package/dist/skills/primitive-connect/references/access-passes.md +32 -0
- package/dist/skills/primitive-connect/references/contact-requests.md +4 -4
- package/dist/skills/primitive-connect/references/contacts.md +1 -1
- package/dist/skills/primitive-connect.json +6 -5
- package/man/primitive.1 +27 -12
- package/package.json +35 -13
- package/dist/api-command-DWjtyqH9.js +0 -3675
- package/dist/cli-config-Ms_0vNjq.js +0 -949
|
@@ -0,0 +1,1750 @@
|
|
|
1
|
+
import { n as createConfig, t as createClient } from "./client.gen-6rZvmHfx.js";
|
|
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
|
+
import { Errors } from "@oclif/core";
|
|
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
|
+
// ../packages/api-core/src/client.ts
|
|
8
|
+
/**
|
|
9
|
+
* Host-aware Primitive API client and shared error type.
|
|
10
|
+
*
|
|
11
|
+
* Lives in api-core (instead of sdk-node) so the CLI can build a
|
|
12
|
+
* configured request client without taking a dependency on sdk-node.
|
|
13
|
+
* The higher-level `PrimitiveClient` (with `.send`, `.reply`,
|
|
14
|
+
* `.forward`) still lives in sdk-node because it needs the
|
|
15
|
+
* `ReceivedEmail` type from the webhook parsing surface.
|
|
16
|
+
*/
|
|
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 || reason === null) && (runId === void 0 || runId === null)) 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 && reason !== null) headers.set(PRIMITIVE_REASON_HEADER, validateActivityReason(reason));
|
|
59
|
+
if (runId !== void 0 && runId !== null) headers.set(PRIMITIVE_RUN_ID_HEADER, validateActivityRunId(runId));
|
|
60
|
+
return Object.fromEntries(headers.entries());
|
|
61
|
+
}
|
|
62
|
+
function createDefaultAuth(apiKey) {
|
|
63
|
+
return (security) => {
|
|
64
|
+
if (security.type === "http" && security.scheme === "bearer") return apiKey;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
var PrimitiveApiClient = class {
|
|
68
|
+
client;
|
|
69
|
+
constructor(options = {}) {
|
|
70
|
+
const { apiKey, auth, apiBaseUrl = DEFAULT_API_BASE_URL, reason, runId, headers, ...config } = options;
|
|
71
|
+
const resolvedAuth = auth ?? createDefaultAuth(apiKey);
|
|
72
|
+
const resolvedHeaders = mergeDefaultActivityHeaders(headers, reason, runId);
|
|
73
|
+
this.client = createClient(createConfig({
|
|
74
|
+
...config,
|
|
75
|
+
...resolvedHeaders !== void 0 ? { headers: resolvedHeaders } : {},
|
|
76
|
+
auth: resolvedAuth,
|
|
77
|
+
baseUrl: apiBaseUrl
|
|
78
|
+
}));
|
|
79
|
+
this.client.interceptors.request.use((request, reqOptions) => {
|
|
80
|
+
const activityOpts = reqOptions;
|
|
81
|
+
if (activityOpts.reason === null) request.headers.delete(PRIMITIVE_REASON_HEADER);
|
|
82
|
+
else if (typeof activityOpts.reason === "string") request.headers.set(PRIMITIVE_REASON_HEADER, validateActivityReason(activityOpts.reason));
|
|
83
|
+
if (activityOpts.runId === null) request.headers.delete(PRIMITIVE_RUN_ID_HEADER);
|
|
84
|
+
else if (typeof activityOpts.runId === "string") request.headers.set(PRIMITIVE_RUN_ID_HEADER, validateActivityRunId(activityOpts.runId));
|
|
85
|
+
return request;
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
getConfig() {
|
|
89
|
+
return this.client.getConfig();
|
|
90
|
+
}
|
|
91
|
+
setConfig(config) {
|
|
92
|
+
return this.client.setConfig(config);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
// src/oclif/runtime-session.ts
|
|
96
|
+
/**
|
|
97
|
+
* The variables each runtime sets to its exact session ID, first match wins.
|
|
98
|
+
* The loaded Codex thread is the receiving identity; the process session ID
|
|
99
|
+
* is only a fallback when no thread ID is exposed.
|
|
100
|
+
*/
|
|
101
|
+
const RUNTIME_SESSION_VARIABLES = {
|
|
102
|
+
claude: ["CLAUDE_CODE_SESSION_ID"],
|
|
103
|
+
codex: ["CODEX_THREAD_ID", "CODEX_SESSION_ID"]
|
|
104
|
+
};
|
|
105
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
106
|
+
/** Each runtime whose environment names a session UUID. Never guessed from history or cwd. */
|
|
107
|
+
function runtimeSessions(env) {
|
|
108
|
+
return Object.keys(RUNTIME_SESSION_VARIABLES).flatMap((runtime) => {
|
|
109
|
+
for (const variable of RUNTIME_SESSION_VARIABLES[runtime]) {
|
|
110
|
+
const value = env[variable]?.trim().toLowerCase();
|
|
111
|
+
if (!value) continue;
|
|
112
|
+
return UUID.test(value) ? [{
|
|
113
|
+
runtime,
|
|
114
|
+
session: value,
|
|
115
|
+
variable
|
|
116
|
+
}] : [];
|
|
117
|
+
}
|
|
118
|
+
return [];
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
/** The one session the runtime environment names, if exactly one runtime names one. */
|
|
122
|
+
function detectRuntimeSession(env = process.env) {
|
|
123
|
+
const candidates = runtimeSessions(env);
|
|
124
|
+
const [only] = candidates;
|
|
125
|
+
if (!only) return { kind: "none" };
|
|
126
|
+
return candidates.length === 1 ? {
|
|
127
|
+
kind: "detected",
|
|
128
|
+
...only
|
|
129
|
+
} : {
|
|
130
|
+
kind: "ambiguous",
|
|
131
|
+
candidates
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The runtime whose tool environment names this exact session. A session ID
|
|
136
|
+
* that matches neither runtime's variable, or both, has no detectable runtime.
|
|
137
|
+
*/
|
|
138
|
+
function detectAgentRuntime(session, env = process.env) {
|
|
139
|
+
const wanted = session.trim().toLowerCase();
|
|
140
|
+
const matches = runtimeSessions(env).filter((candidate) => candidate.session === wanted);
|
|
141
|
+
return matches.length === 1 ? matches[0]?.runtime ?? null : null;
|
|
142
|
+
}
|
|
143
|
+
/** Every variable a runtime may name its session in, for messages. */
|
|
144
|
+
function runtimeSessionVariableList() {
|
|
145
|
+
const names = Object.values(RUNTIME_SESSION_VARIABLES).flat();
|
|
146
|
+
return `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
|
|
147
|
+
}
|
|
148
|
+
// src/oclif/agent-pass.ts
|
|
149
|
+
const AGENT_PASS_PROFILE_ENV = "PRIMITIVE_AGENT_PASS_PROFILE";
|
|
150
|
+
const AGENT_PASS_DIR = "agent-passes";
|
|
151
|
+
const PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
|
|
152
|
+
const TOKEN_PATTERN = /\b(pit_v1_[A-Za-z0-9_-]{16,256})\b/;
|
|
153
|
+
const EXACT_TOKEN_PATTERN = /^pit_v1_[A-Za-z0-9_-]{16,256}$/;
|
|
154
|
+
var AgentPassAuthError = class extends Error {
|
|
155
|
+
constructor(message) {
|
|
156
|
+
super(message);
|
|
157
|
+
this.name = "AgentPassAuthError";
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
function isRecord$4(value) {
|
|
161
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
162
|
+
}
|
|
163
|
+
function stripTrailingSlashes(value) {
|
|
164
|
+
let end = value.length;
|
|
165
|
+
while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
|
|
166
|
+
return value.slice(0, end);
|
|
167
|
+
}
|
|
168
|
+
function normalizeBaseUrl(raw) {
|
|
169
|
+
const trimmed = raw?.trim();
|
|
170
|
+
if (!trimmed) return DEFAULT_API_BASE_URL;
|
|
171
|
+
return stripTrailingSlashes(trimmed);
|
|
172
|
+
}
|
|
173
|
+
function isLocalhostHostname(hostname) {
|
|
174
|
+
const lower = hostname.toLowerCase();
|
|
175
|
+
return lower === "localhost" || lower === "127.0.0.1" || lower === "[::1]" || lower === "::1";
|
|
176
|
+
}
|
|
177
|
+
function validateAccessBaseUrl(rawUrl) {
|
|
178
|
+
let parsed;
|
|
179
|
+
try {
|
|
180
|
+
parsed = new URL(rawUrl);
|
|
181
|
+
} catch {
|
|
182
|
+
throw new AgentPassAuthError("Access Pass URL is not a valid URL. Paste the full presigned access URL or pit_v1_ token.");
|
|
183
|
+
}
|
|
184
|
+
if (parsed.username || parsed.password) throw new AgentPassAuthError("Access Pass URL must not include embedded credentials.");
|
|
185
|
+
const isHttps = parsed.protocol === "https:";
|
|
186
|
+
const isLocalHttp = parsed.protocol === "http:" && isLocalhostHostname(parsed.hostname);
|
|
187
|
+
if (!isHttps && !isLocalHttp) throw new AgentPassAuthError("Access Pass URL must use https (or http only for localhost).");
|
|
188
|
+
const cleanPath = stripTrailingSlashes(parsed.pathname);
|
|
189
|
+
const lowerPath = cleanPath.toLowerCase();
|
|
190
|
+
const accessIdx = lowerPath.indexOf("/v1/access/");
|
|
191
|
+
let basePath;
|
|
192
|
+
if (accessIdx !== -1) basePath = cleanPath.slice(0, accessIdx + 3);
|
|
193
|
+
else if (lowerPath === "/v1" || lowerPath.endsWith("/v1")) basePath = cleanPath;
|
|
194
|
+
else if (cleanPath === "" || cleanPath === "/") basePath = "/v1";
|
|
195
|
+
else basePath = `${cleanPath}/v1`;
|
|
196
|
+
return `${parsed.protocol}//${parsed.host}${basePath}`;
|
|
197
|
+
}
|
|
198
|
+
function validateAgentPassProfileName(profile) {
|
|
199
|
+
const trimmed = profile.trim();
|
|
200
|
+
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).");
|
|
201
|
+
return trimmed;
|
|
202
|
+
}
|
|
203
|
+
function agentPassTokenSha256(token) {
|
|
204
|
+
return createHash("sha256").update(token).digest("hex");
|
|
205
|
+
}
|
|
206
|
+
function trimWrapperChars(value) {
|
|
207
|
+
const leading = `"'<>()\`[`;
|
|
208
|
+
const trailing = `"'<>()\`].,;`;
|
|
209
|
+
let start = 0;
|
|
210
|
+
let end = value.length;
|
|
211
|
+
while (start < end && leading.includes(value[start] ?? "")) start += 1;
|
|
212
|
+
while (end > start && trailing.includes(value[end - 1] ?? "")) end -= 1;
|
|
213
|
+
return value.slice(start, end);
|
|
214
|
+
}
|
|
215
|
+
function extractUrlWithToken(input) {
|
|
216
|
+
for (const rawPiece of input.split(/\s+/)) {
|
|
217
|
+
const piece = trimWrapperChars(rawPiece);
|
|
218
|
+
const lower = piece.toLowerCase();
|
|
219
|
+
if (!lower.startsWith("http://") && !lower.startsWith("https://")) continue;
|
|
220
|
+
let parsed;
|
|
221
|
+
try {
|
|
222
|
+
parsed = new URL(piece);
|
|
223
|
+
} catch {
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
const idx = parsed.pathname.toLowerCase().indexOf("/v1/access/");
|
|
227
|
+
if (idx === -1) continue;
|
|
228
|
+
const token = parsed.pathname.slice(idx + 11).split("/")[0] ?? "";
|
|
229
|
+
if (EXACT_TOKEN_PATTERN.test(token)) return {
|
|
230
|
+
url: piece,
|
|
231
|
+
token
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
function parseAccessPassInput(rawInput, explicitApiBaseUrl) {
|
|
237
|
+
const trimmed = rawInput.trim();
|
|
238
|
+
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.");
|
|
239
|
+
const urlMatch = extractUrlWithToken(trimmed);
|
|
240
|
+
if (urlMatch) {
|
|
241
|
+
const inferredBaseUrl = validateAccessBaseUrl(urlMatch.url);
|
|
242
|
+
const apiBaseUrl = explicitApiBaseUrl?.trim() ? validateAccessBaseUrl(normalizeBaseUrl(explicitApiBaseUrl)) : inferredBaseUrl;
|
|
243
|
+
return {
|
|
244
|
+
token: urlMatch.token,
|
|
245
|
+
apiBaseUrl
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
const tokenMatch = TOKEN_PATTERN.exec(trimmed);
|
|
249
|
+
if (tokenMatch?.[1]) {
|
|
250
|
+
const apiBaseUrl = explicitApiBaseUrl?.trim() ? validateAccessBaseUrl(normalizeBaseUrl(explicitApiBaseUrl)) : DEFAULT_API_BASE_URL;
|
|
251
|
+
return {
|
|
252
|
+
token: tokenMatch[1],
|
|
253
|
+
apiBaseUrl
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
throw new AgentPassAuthError("Could not find a valid Primitive Access Pass URL or pit_v1_ token in the input.");
|
|
257
|
+
}
|
|
258
|
+
function agentPassMetadata(pass) {
|
|
259
|
+
const { api_key: _redacted, ...meta } = pass;
|
|
260
|
+
return meta;
|
|
261
|
+
}
|
|
262
|
+
function agentPassRootDir(configDir) {
|
|
263
|
+
return join(configDir, AGENT_PASS_DIR);
|
|
264
|
+
}
|
|
265
|
+
function agentPassClaimCachePath(configDir, tokenHash) {
|
|
266
|
+
return join(agentPassRootDir(configDir), "claims", `${tokenHash}.json`);
|
|
267
|
+
}
|
|
268
|
+
const SAFE_SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{3,63}$/;
|
|
269
|
+
const EXTRA_AGENT_SESSION_VARS = [
|
|
270
|
+
{
|
|
271
|
+
runtime: "primitive",
|
|
272
|
+
variables: ["PRIMITIVE_SESSION_ID"]
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
runtime: "antigravity",
|
|
276
|
+
variables: ["ANTIGRAVITY_CONVERSATION_ID", "ANTIGRAVITY_SESSION_ID"]
|
|
277
|
+
},
|
|
278
|
+
{
|
|
279
|
+
runtime: "cursor",
|
|
280
|
+
variables: ["CURSOR_SESSION_ID", "CURSOR_TRACE_ID"]
|
|
281
|
+
},
|
|
282
|
+
{
|
|
283
|
+
runtime: "windsurf",
|
|
284
|
+
variables: ["WINDSURF_SESSION_ID", "CODEIUM_SESSION_ID"]
|
|
285
|
+
},
|
|
286
|
+
{
|
|
287
|
+
runtime: "gemini",
|
|
288
|
+
variables: ["GEMINI_SESSION_ID", "GEMINI_CLI_SESSION_ID"]
|
|
289
|
+
},
|
|
290
|
+
{
|
|
291
|
+
runtime: "opencode",
|
|
292
|
+
variables: ["OPENCODE_SESSION_ID"]
|
|
293
|
+
},
|
|
294
|
+
{
|
|
295
|
+
runtime: "agent",
|
|
296
|
+
variables: [
|
|
297
|
+
"AIDER_SESSION_ID",
|
|
298
|
+
"GOOSE_SESSION_ID",
|
|
299
|
+
"AMP_THREAD_ID"
|
|
300
|
+
]
|
|
301
|
+
}
|
|
302
|
+
];
|
|
303
|
+
function sanitizeSessionTokenForFilename(raw) {
|
|
304
|
+
const lower = raw.trim().toLowerCase();
|
|
305
|
+
if (SAFE_SESSION_ID_PATTERN.test(lower)) return lower;
|
|
306
|
+
return createHash("sha256").update(lower).digest("hex").slice(0, 32);
|
|
307
|
+
}
|
|
308
|
+
function detectExtraAgentSession(env) {
|
|
309
|
+
for (const entry of EXTRA_AGENT_SESSION_VARS) for (const variable of entry.variables) {
|
|
310
|
+
const value = env[variable]?.trim();
|
|
311
|
+
if (!value) continue;
|
|
312
|
+
return {
|
|
313
|
+
runtime: entry.runtime,
|
|
314
|
+
session: sanitizeSessionTokenForFilename(value)
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
function resolveAgentPassSlot(params) {
|
|
320
|
+
const env = params.env ?? process.env;
|
|
321
|
+
const profileName = params.profile?.trim() || env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
|
|
322
|
+
if (profileName) {
|
|
323
|
+
const safe = validateAgentPassProfileName(profileName);
|
|
324
|
+
return {
|
|
325
|
+
path: join(agentPassRootDir(params.configDir), "profiles", `${safe}.json`),
|
|
326
|
+
binding: {
|
|
327
|
+
kind: "profile",
|
|
328
|
+
profile: safe
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
const explicitPrimitiveSession = env.PRIMITIVE_SESSION_ID?.trim();
|
|
333
|
+
if (explicitPrimitiveSession) {
|
|
334
|
+
const session = sanitizeSessionTokenForFilename(explicitPrimitiveSession);
|
|
335
|
+
return {
|
|
336
|
+
path: join(agentPassRootDir(params.configDir), "sessions", `primitive-${session}.json`),
|
|
337
|
+
binding: {
|
|
338
|
+
kind: "session",
|
|
339
|
+
runtime: "primitive",
|
|
340
|
+
session
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
const detected = detectRuntimeSession(env);
|
|
345
|
+
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.`);
|
|
346
|
+
if (detected.kind === "detected") return {
|
|
347
|
+
path: join(agentPassRootDir(params.configDir), "sessions", `${detected.runtime}-${detected.session}.json`),
|
|
348
|
+
binding: {
|
|
349
|
+
kind: "session",
|
|
350
|
+
runtime: detected.runtime,
|
|
351
|
+
session: detected.session
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
const extra = detectExtraAgentSession(env);
|
|
355
|
+
if (extra) return {
|
|
356
|
+
path: join(agentPassRootDir(params.configDir), "sessions", `${extra.runtime}-${extra.session}.json`),
|
|
357
|
+
binding: {
|
|
358
|
+
kind: "session",
|
|
359
|
+
runtime: extra.runtime,
|
|
360
|
+
session: extra.session
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
return {
|
|
364
|
+
path: join(agentPassRootDir(params.configDir), "default.json"),
|
|
365
|
+
binding: { kind: "default" }
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function ensurePrivateDir(dirPath, stopAtDir) {
|
|
369
|
+
mkdirSync(dirPath, {
|
|
370
|
+
mode: 448,
|
|
371
|
+
recursive: true
|
|
372
|
+
});
|
|
373
|
+
if (process.platform === "win32") return;
|
|
374
|
+
const resolvedStop = stopAtDir ? resolve(stopAtDir) : null;
|
|
375
|
+
let current = resolve(dirPath);
|
|
376
|
+
for (;;) {
|
|
377
|
+
try {
|
|
378
|
+
if (lstatSync(current).isSymbolicLink()) throw new AgentPassAuthError(`Refusing to use symlinked Access Pass directory at ${current}.`);
|
|
379
|
+
chmodSync(current, 448);
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (error instanceof AgentPassAuthError) throw error;
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
if (!resolvedStop || current === resolvedStop) break;
|
|
385
|
+
const parent = dirname(current);
|
|
386
|
+
if (parent === current) break;
|
|
387
|
+
current = parent;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function assertPrivateRegularFile(filePath) {
|
|
391
|
+
const st = lstatSync(filePath);
|
|
392
|
+
if (st.isSymbolicLink() || !st.isFile()) throw new AgentPassAuthError(`Refusing to read Access Pass at ${filePath}: expected a regular file.`);
|
|
393
|
+
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\`.`);
|
|
394
|
+
}
|
|
395
|
+
function writePrivateJsonAtomic(filePath, data, privateRootDir) {
|
|
396
|
+
ensurePrivateDir(dirname(filePath), privateRootDir);
|
|
397
|
+
try {
|
|
398
|
+
if (lstatSync(filePath).isSymbolicLink()) throw new AgentPassAuthError(`Refusing to overwrite symlinked Access Pass file at ${filePath}.`);
|
|
399
|
+
} catch (error) {
|
|
400
|
+
if (error instanceof AgentPassAuthError) throw error;
|
|
401
|
+
if (!(error && typeof error === "object" && error.code === "ENOENT")) throw error;
|
|
402
|
+
}
|
|
403
|
+
const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
404
|
+
try {
|
|
405
|
+
writeFileSync(tempPath, `${JSON.stringify(data, null, 2)}\n`, {
|
|
406
|
+
flag: "wx",
|
|
407
|
+
mode: 384
|
|
408
|
+
});
|
|
409
|
+
if (process.platform !== "win32") chmodSync(tempPath, 384);
|
|
410
|
+
renameSync(tempPath, filePath);
|
|
411
|
+
if (process.platform !== "win32") chmodSync(filePath, 384);
|
|
412
|
+
} catch (error) {
|
|
413
|
+
rmSync(tempPath, { force: true });
|
|
414
|
+
throw error;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
function parseStoredAgentPass(raw) {
|
|
418
|
+
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.");
|
|
419
|
+
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.");
|
|
420
|
+
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.");
|
|
421
|
+
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.");
|
|
422
|
+
const bindingRaw = isRecord$4(raw.binding) ? raw.binding : null;
|
|
423
|
+
let binding = { kind: "default" };
|
|
424
|
+
if (bindingRaw?.kind === "session" && typeof bindingRaw.runtime === "string" && typeof bindingRaw.session === "string") binding = {
|
|
425
|
+
kind: "session",
|
|
426
|
+
runtime: bindingRaw.runtime,
|
|
427
|
+
session: bindingRaw.session
|
|
428
|
+
};
|
|
429
|
+
else if (bindingRaw?.kind === "profile" && typeof bindingRaw.profile === "string") binding = {
|
|
430
|
+
kind: "profile",
|
|
431
|
+
profile: bindingRaw.profile
|
|
432
|
+
};
|
|
433
|
+
return {
|
|
434
|
+
version: 1,
|
|
435
|
+
auth_method: "agent_pass",
|
|
436
|
+
api_key: raw.api_key,
|
|
437
|
+
api_base_url: validateAccessBaseUrl(normalizeBaseUrl(raw.api_base_url)),
|
|
438
|
+
pass_id: typeof raw.pass_id === "string" ? raw.pass_id : null,
|
|
439
|
+
key_id: typeof raw.key_id === "string" ? raw.key_id : null,
|
|
440
|
+
label: typeof raw.label === "string" && raw.label ? raw.label : "Agent Pass",
|
|
441
|
+
mode: typeof raw.mode === "string" && raw.mode ? raw.mode : "read_only",
|
|
442
|
+
...typeof raw.purpose === "string" ? { purpose: raw.purpose } : {},
|
|
443
|
+
...typeof raw.profile_hint === "string" ? { profile_hint: raw.profile_hint } : {},
|
|
444
|
+
...typeof raw.mcp_url === "string" ? { mcp_url: raw.mcp_url } : {},
|
|
445
|
+
...typeof raw.manage_url === "string" ? { manage_url: raw.manage_url } : {},
|
|
446
|
+
expires_at: raw.expires_at,
|
|
447
|
+
slice_summary: typeof raw.slice_summary === "string" ? raw.slice_summary : null,
|
|
448
|
+
claimed_at: typeof raw.claimed_at === "string" ? raw.claimed_at : (/* @__PURE__ */ new Date()).toISOString(),
|
|
449
|
+
revoked_at: typeof raw.revoked_at === "string" ? raw.revoked_at : null,
|
|
450
|
+
token_sha256: typeof raw.token_sha256 === "string" ? raw.token_sha256 : "",
|
|
451
|
+
binding
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
function readAgentPassFile(filePath) {
|
|
455
|
+
let rawText;
|
|
456
|
+
try {
|
|
457
|
+
assertPrivateRegularFile(filePath);
|
|
458
|
+
rawText = readFileSync(filePath, "utf8");
|
|
459
|
+
} catch (error) {
|
|
460
|
+
if (error instanceof AgentPassAuthError) throw error;
|
|
461
|
+
if (error && typeof error === "object" && error.code === "ENOENT") return null;
|
|
462
|
+
throw new AgentPassAuthError(`Could not read saved Access Pass: ${error instanceof Error ? error.message : String(error)}`);
|
|
463
|
+
}
|
|
464
|
+
let parsed;
|
|
465
|
+
try {
|
|
466
|
+
parsed = JSON.parse(rawText);
|
|
467
|
+
} catch {
|
|
468
|
+
throw new AgentPassAuthError("Saved Access Pass file is not valid JSON. Run `primitive disconnect --local-only` and reconnect.");
|
|
469
|
+
}
|
|
470
|
+
return parseStoredAgentPass(parsed);
|
|
471
|
+
}
|
|
472
|
+
function saveAgentPass(params) {
|
|
473
|
+
const rootDir = agentPassRootDir(params.configDir);
|
|
474
|
+
writePrivateJsonAtomic(params.slotPath, params.pass, rootDir);
|
|
475
|
+
if (params.pass.token_sha256) writePrivateJsonAtomic(agentPassClaimCachePath(params.configDir, params.pass.token_sha256), params.pass, rootDir);
|
|
476
|
+
}
|
|
477
|
+
function loadCachedAgentPassByToken(params) {
|
|
478
|
+
const hash = agentPassTokenSha256(params.token);
|
|
479
|
+
const cachePath = agentPassClaimCachePath(params.configDir, hash);
|
|
480
|
+
try {
|
|
481
|
+
const cached = readAgentPassFile(cachePath);
|
|
482
|
+
if (!cached || cached.revoked_at) return null;
|
|
483
|
+
return cached;
|
|
484
|
+
} catch {
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
function extractWhoamiGrantDetails(grantData) {
|
|
489
|
+
if (!isRecord$4(grantData)) return {
|
|
490
|
+
permissions: [],
|
|
491
|
+
expiresAt: null,
|
|
492
|
+
accessPass: null
|
|
493
|
+
};
|
|
494
|
+
const root = isRecord$4(grantData.data) ? grantData.data : grantData;
|
|
495
|
+
const grantObj = isRecord$4(root.grant) ? root.grant : null;
|
|
496
|
+
const permissions = (Array.isArray(grantObj?.permissions) ? grantObj.permissions : Array.isArray(root.permissions) ? root.permissions : []).filter((p) => typeof p === "string");
|
|
497
|
+
const rawExpires = typeof grantObj?.expires_at === "string" && !Number.isNaN(Date.parse(grantObj.expires_at)) ? grantObj.expires_at : null;
|
|
498
|
+
const rawPass = isRecord$4(root.access_pass) ? root.access_pass : null;
|
|
499
|
+
return {
|
|
500
|
+
permissions,
|
|
501
|
+
expiresAt: rawExpires,
|
|
502
|
+
accessPass: rawPass ? {
|
|
503
|
+
id: typeof rawPass.id === "string" ? rawPass.id : null,
|
|
504
|
+
name: typeof rawPass.name === "string" && rawPass.name.trim() ? rawPass.name.trim() : null,
|
|
505
|
+
mode: typeof rawPass.mode === "string" && rawPass.mode.trim() ? rawPass.mode.trim() : null,
|
|
506
|
+
manageUrl: typeof rawPass.manage_url === "string" && rawPass.manage_url.trim() ? rawPass.manage_url.trim() : null
|
|
507
|
+
} : null
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
function syncAgentPassMetadataFromGrant(params) {
|
|
511
|
+
const details = extractWhoamiGrantDetails(params.grantData);
|
|
512
|
+
const updatedMeta = {
|
|
513
|
+
...params.pass,
|
|
514
|
+
...details.expiresAt ? { expires_at: details.expiresAt } : {},
|
|
515
|
+
...details.accessPass?.id ? { pass_id: details.accessPass.id } : {},
|
|
516
|
+
...details.accessPass?.name ? { label: details.accessPass.name } : {},
|
|
517
|
+
...details.accessPass?.mode ? { mode: details.accessPass.mode } : {},
|
|
518
|
+
...details.accessPass?.manageUrl ? { manage_url: details.accessPass.manageUrl } : {}
|
|
519
|
+
};
|
|
520
|
+
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 {
|
|
521
|
+
const explicitProfile = params.pass.binding.kind === "profile" ? params.pass.binding.profile : void 0;
|
|
522
|
+
const slot = resolveAgentPassSlot({
|
|
523
|
+
configDir: params.configDir,
|
|
524
|
+
profile: explicitProfile,
|
|
525
|
+
env: params.env
|
|
526
|
+
});
|
|
527
|
+
const existing = readAgentPassFile(slot.path);
|
|
528
|
+
if (existing && !existing.revoked_at) saveAgentPass({
|
|
529
|
+
configDir: params.configDir,
|
|
530
|
+
slotPath: slot.path,
|
|
531
|
+
pass: {
|
|
532
|
+
...existing,
|
|
533
|
+
expires_at: updatedMeta.expires_at,
|
|
534
|
+
label: updatedMeta.label,
|
|
535
|
+
mode: updatedMeta.mode,
|
|
536
|
+
pass_id: updatedMeta.pass_id,
|
|
537
|
+
...updatedMeta.manage_url ? { manage_url: updatedMeta.manage_url } : {}
|
|
538
|
+
}
|
|
539
|
+
});
|
|
540
|
+
} catch {}
|
|
541
|
+
return {
|
|
542
|
+
pass: updatedMeta,
|
|
543
|
+
permissions: details.permissions
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
function loadActiveAgentPass(params) {
|
|
547
|
+
const env = params.env ?? process.env;
|
|
548
|
+
const explicitProfile = params.profile?.trim() || env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
|
|
549
|
+
const slot = resolveAgentPassSlot({
|
|
550
|
+
configDir: params.configDir,
|
|
551
|
+
profile: explicitProfile,
|
|
552
|
+
env
|
|
553
|
+
});
|
|
554
|
+
const pass = readAgentPassFile(slot.path);
|
|
555
|
+
if (!pass) {
|
|
556
|
+
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}.`);
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
if (pass.revoked_at) 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 been revoked. 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.`);
|
|
560
|
+
return {
|
|
561
|
+
pass,
|
|
562
|
+
path: slot.path
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
function deleteAgentPass(params) {
|
|
566
|
+
rmSync(params.slotPath, { force: true });
|
|
567
|
+
if (params.tokenSha256) rmSync(agentPassClaimCachePath(params.configDir, params.tokenSha256), { force: true });
|
|
568
|
+
}
|
|
569
|
+
function extractErrorMessage(payload, status) {
|
|
570
|
+
if (isRecord$4(payload)) {
|
|
571
|
+
const inner = isRecord$4(payload.error) ? payload.error : payload;
|
|
572
|
+
const message = typeof inner.message === "string" ? inner.message : typeof payload.message === "string" ? payload.message : null;
|
|
573
|
+
const code = typeof inner.code === "string" ? inner.code : null;
|
|
574
|
+
if (message && code) return `${message} (${code}, HTTP ${status})`;
|
|
575
|
+
if (message) return `${message} (HTTP ${status})`;
|
|
576
|
+
if (code) return `${code} (HTTP ${status})`;
|
|
577
|
+
}
|
|
578
|
+
return `Request failed with HTTP ${status}`;
|
|
579
|
+
}
|
|
580
|
+
function deriveSliceSummary(data, grantSummary) {
|
|
581
|
+
if (typeof data.slice_summary === "string" && data.slice_summary.trim()) return data.slice_summary.trim();
|
|
582
|
+
const mailScope = grantSummary && isRecord$4(grantSummary.mail_scope) ? grantSummary.mail_scope : null;
|
|
583
|
+
if (!mailScope) return null;
|
|
584
|
+
if (mailScope.kind === "snapshot") {
|
|
585
|
+
const label = typeof mailScope.snapshot_label === "string" && mailScope.snapshot_label.trim() ? mailScope.snapshot_label.trim() : "Frozen snapshot";
|
|
586
|
+
const count = typeof mailScope.snapshot_email_count === "number" ? mailScope.snapshot_email_count : null;
|
|
587
|
+
return count !== null ? `${label} (${count} ${count === 1 ? "email" : "emails"})` : label;
|
|
588
|
+
}
|
|
589
|
+
if (mailScope.kind === "org") return "Organization mailboxes";
|
|
590
|
+
const parts = [];
|
|
591
|
+
if (Array.isArray(mailScope.addresses) && mailScope.addresses.length > 0) {
|
|
592
|
+
const addrs = mailScope.addresses.filter((a) => typeof a === "string" && a.length > 0);
|
|
593
|
+
if (addrs.length > 0) parts.push(addrs.join(", "));
|
|
594
|
+
}
|
|
595
|
+
if (Array.isArray(mailScope.domains) && mailScope.domains.length > 0) {
|
|
596
|
+
const doms = mailScope.domains.filter((d) => typeof d === "string" && d.length > 0);
|
|
597
|
+
if (doms.length > 0) parts.push(`domains: ${doms.join(", ")}`);
|
|
598
|
+
}
|
|
599
|
+
if (Array.isArray(mailScope.rules) && mailScope.rules.length > 0) parts.push(`${mailScope.rules.length} rule(s)`);
|
|
600
|
+
return parts.length > 0 ? parts.join("; ") : null;
|
|
601
|
+
}
|
|
602
|
+
async function claimAccessPassRemote(params) {
|
|
603
|
+
const fetchImpl = params.fetch ?? fetch;
|
|
604
|
+
const endpoint = `${normalizeBaseUrl(params.apiBaseUrl)}/access/claim`;
|
|
605
|
+
let response;
|
|
606
|
+
try {
|
|
607
|
+
response = await fetchImpl(endpoint, {
|
|
608
|
+
method: "POST",
|
|
609
|
+
headers: {
|
|
610
|
+
"content-type": "application/json",
|
|
611
|
+
accept: "application/json"
|
|
612
|
+
},
|
|
613
|
+
body: JSON.stringify({ token: params.token })
|
|
614
|
+
});
|
|
615
|
+
} catch (error) {
|
|
616
|
+
throw new AgentPassAuthError(`Could not reach Primitive to claim the Access Pass: ${error instanceof Error ? error.message : String(error)}`);
|
|
617
|
+
}
|
|
618
|
+
const payload = await response.json().catch(() => null);
|
|
619
|
+
if (!response.ok) throw new AgentPassAuthError(`Could not claim Access Pass: ${extractErrorMessage(payload, response.status)}`);
|
|
620
|
+
const data = isRecord$4(payload) && isRecord$4(payload.data) ? payload.data : payload;
|
|
621
|
+
if (!isRecord$4(data) || typeof data.api_key !== "string" || !data.api_key) throw new AgentPassAuthError("Primitive returned an unexpected Access Pass claim response.");
|
|
622
|
+
const grantSummary = isRecord$4(data.grant_summary) ? data.grant_summary : null;
|
|
623
|
+
const expiresAt = typeof data.expires_at === "string" && !Number.isNaN(Date.parse(data.expires_at)) ? data.expires_at : new Date(Date.now() + 144e5).toISOString();
|
|
624
|
+
const resolvedApiBaseUrl = typeof data.api_base_url === "string" && data.api_base_url.trim() ? validateAccessBaseUrl(data.api_base_url.trim()) : validateAccessBaseUrl(normalizeBaseUrl(params.apiBaseUrl));
|
|
625
|
+
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";
|
|
626
|
+
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";
|
|
627
|
+
const purpose = typeof data.purpose === "string" && data.purpose.trim() ? data.purpose.trim() : grantSummary && typeof grantSummary.purpose === "string" && grantSummary.purpose.trim() ? grantSummary.purpose.trim() : null;
|
|
628
|
+
return {
|
|
629
|
+
api_key: data.api_key,
|
|
630
|
+
api_base_url: resolvedApiBaseUrl,
|
|
631
|
+
pass_id: typeof data.pass_id === "string" ? data.pass_id : typeof data.invitation_id === "string" ? data.invitation_id : null,
|
|
632
|
+
key_id: typeof data.key_id === "string" ? data.key_id : null,
|
|
633
|
+
label,
|
|
634
|
+
mode,
|
|
635
|
+
purpose,
|
|
636
|
+
profile_hint: typeof data.profile_hint === "string" && data.profile_hint.trim() ? data.profile_hint.trim() : null,
|
|
637
|
+
mcp_url: typeof data.mcp_url === "string" && data.mcp_url.trim() ? data.mcp_url.trim() : null,
|
|
638
|
+
manage_url: typeof data.manage_url === "string" && data.manage_url.trim() ? data.manage_url.trim() : null,
|
|
639
|
+
expires_at: expiresAt,
|
|
640
|
+
slice_summary: deriveSliceSummary(data, grantSummary),
|
|
641
|
+
grant_summary: grantSummary,
|
|
642
|
+
preview: data.preview ?? null,
|
|
643
|
+
guide: data.guide ?? null
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
async function revokeAccessPassRemote(params) {
|
|
647
|
+
const fetchImpl = params.fetch ?? fetch;
|
|
648
|
+
const endpoint = `${validateAccessBaseUrl(normalizeBaseUrl(params.apiBaseUrl))}/keys/me/revoke`;
|
|
649
|
+
let response;
|
|
650
|
+
try {
|
|
651
|
+
response = await fetchImpl(endpoint, {
|
|
652
|
+
method: "POST",
|
|
653
|
+
headers: {
|
|
654
|
+
authorization: `Bearer ${params.apiKey}`,
|
|
655
|
+
accept: "application/json"
|
|
656
|
+
}
|
|
657
|
+
});
|
|
658
|
+
} catch (error) {
|
|
659
|
+
throw new AgentPassAuthError(`Could not reach Primitive to revoke the Access Pass: ${error instanceof Error ? error.message : String(error)}`);
|
|
660
|
+
}
|
|
661
|
+
if (response.ok) return {
|
|
662
|
+
revoked: true,
|
|
663
|
+
alreadyRevoked: false
|
|
664
|
+
};
|
|
665
|
+
if (response.status === 401) return {
|
|
666
|
+
revoked: true,
|
|
667
|
+
alreadyRevoked: true
|
|
668
|
+
};
|
|
669
|
+
const payload = await response.json().catch(() => null);
|
|
670
|
+
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." : "";
|
|
671
|
+
throw new AgentPassAuthError(`Could not revoke Access Pass: ${extractErrorMessage(payload, response.status)}.${hint}`);
|
|
672
|
+
}
|
|
673
|
+
// src/oclif/connected-agent-profile.ts
|
|
674
|
+
const AGENT_PROFILE_ENV = "PRIMITIVE_AGENT_PROFILE";
|
|
675
|
+
/**
|
|
676
|
+
* The selected agent's email address, exported next to AGENT_PROFILE_ENV for
|
|
677
|
+
* a registered session so other tools can read it without running the CLI.
|
|
678
|
+
*/
|
|
679
|
+
const AGENT_ADDRESS_ENV = "PRIMITIVE_AGENT_ADDRESS";
|
|
680
|
+
/**
|
|
681
|
+
* One sentence telling a session whose agent is selected how to run a command
|
|
682
|
+
* as the member login instead. An empty PRIMITIVE_AGENT_PROFILE selects no
|
|
683
|
+
* profile everywhere in the CLI.
|
|
684
|
+
*/
|
|
685
|
+
const MEMBER_LOGIN_OPT_OUT = "rerun the same command with `PRIMITIVE_AGENT_PROFILE=` in front of it (or under `env -u PRIMITIVE_AGENT_PROFILE`) to run it as the member login";
|
|
686
|
+
function parsePresenceProfile(value, owner) {
|
|
687
|
+
const row = mailObject(value, [
|
|
688
|
+
"protocol",
|
|
689
|
+
"version",
|
|
690
|
+
"authentication_profile",
|
|
691
|
+
"return_address"
|
|
692
|
+
]);
|
|
693
|
+
if (row.protocol !== "primitive.presence" || row.version !== 1 || row.authentication_profile !== "primitive-issued-v1" || mailAddress(row.return_address) !== owner) throw new AgentConnectionSetupError("The presence authentication profile is not supported.");
|
|
694
|
+
return {
|
|
695
|
+
protocol: "primitive.presence",
|
|
696
|
+
version: 1,
|
|
697
|
+
authentication_profile: "primitive-issued-v1",
|
|
698
|
+
return_address: owner
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
function supportedPresenceProfile(value, owner) {
|
|
702
|
+
if (value === void 0) return void 0;
|
|
703
|
+
try {
|
|
704
|
+
return parsePresenceProfile(value, owner);
|
|
705
|
+
} catch {
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
var AgentConnectionSetupError = class extends Error {};
|
|
710
|
+
function requireDefaultLoginProfile() {
|
|
711
|
+
if (process.env["PRIMITIVE_AGENT_PROFILE"]?.trim()) throw new AgentConnectionSetupError(`This command manages the member login, so it does not run as the agent selected by PRIMITIVE_AGENT_PROFILE; ${MEMBER_LOGIN_OPT_OUT}, and the agent profile is unchanged.`);
|
|
712
|
+
}
|
|
713
|
+
function agentProfileName(value) {
|
|
714
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/.test(value)) throw new AgentConnectionSetupError("Agent profile must start with a letter or number and contain only letters, numbers, dots, underscores or hyphens (at most 63 characters).");
|
|
715
|
+
return value;
|
|
716
|
+
}
|
|
717
|
+
function connectedApiBaseUrl(value) {
|
|
718
|
+
if (value !== "https://api.primitive.dev/v1" && value !== "https://api.primitive-staging-1.com/v1") throw new AgentConnectionSetupError("Agent setup requires an official Primitive API origin.");
|
|
719
|
+
return value;
|
|
720
|
+
}
|
|
721
|
+
function agentProfilesDirectory(configDir) {
|
|
722
|
+
return join(configDir, "agent-connections");
|
|
723
|
+
}
|
|
724
|
+
function agentProfileDirectory(configDir, profileName) {
|
|
725
|
+
return join(agentProfilesDirectory(configDir), "profiles", agentProfileName(profileName));
|
|
726
|
+
}
|
|
727
|
+
function profilePath(configDir, profileName) {
|
|
728
|
+
return join(agentProfileDirectory(configDir, profileName), "connection.json");
|
|
729
|
+
}
|
|
730
|
+
function parseConnectedAgentProfile(value) {
|
|
731
|
+
try {
|
|
732
|
+
const keys = [
|
|
733
|
+
"version",
|
|
734
|
+
"auth_method",
|
|
735
|
+
"api_key",
|
|
736
|
+
"api_base_url",
|
|
737
|
+
"org_id",
|
|
738
|
+
"agent_address",
|
|
739
|
+
"owner_address",
|
|
740
|
+
"invitation_hash",
|
|
741
|
+
"created_at"
|
|
742
|
+
];
|
|
743
|
+
const has = (key) => Boolean(value && typeof value === "object" && Object.hasOwn(value, key));
|
|
744
|
+
const row = mailObject(value, [
|
|
745
|
+
...keys,
|
|
746
|
+
...has("presence_profile") ? ["presence_profile"] : [],
|
|
747
|
+
...has("owner_member_address") ? ["owner_member_address"] : []
|
|
748
|
+
]);
|
|
749
|
+
const apiKey = mailString(row.api_key, 4096);
|
|
750
|
+
const invitationHash = mailString(row.invitation_hash, 64);
|
|
751
|
+
if (row.version !== 1 || row.auth_method !== "agent_connection" || !apiKey.startsWith("pconn_") || /\s/.test(apiKey) || !/^[a-f0-9]{64}$/.test(invitationHash)) throw new Error();
|
|
752
|
+
const presence = supportedPresenceProfile(row.presence_profile, mailAddress(row.owner_address));
|
|
753
|
+
const ownerMember = has("owner_member_address") ? parseOwnerMemberAddress(row.owner_member_address, mailAddress(row.owner_address), mailAddress(row.agent_address)) : void 0;
|
|
754
|
+
return {
|
|
755
|
+
version: 1,
|
|
756
|
+
auth_method: "agent_connection",
|
|
757
|
+
api_key: apiKey,
|
|
758
|
+
api_base_url: connectedApiBaseUrl(row.api_base_url),
|
|
759
|
+
org_id: mailId(row.org_id),
|
|
760
|
+
agent_address: mailAddress(row.agent_address),
|
|
761
|
+
owner_address: mailAddress(row.owner_address),
|
|
762
|
+
...ownerMember === void 0 ? {} : { owner_member_address: ownerMember },
|
|
763
|
+
invitation_hash: invitationHash,
|
|
764
|
+
created_at: mailTime(row.created_at),
|
|
765
|
+
...presence === void 0 ? {} : { presence_profile: presence }
|
|
766
|
+
};
|
|
767
|
+
} catch {
|
|
768
|
+
throw new AgentConnectionSetupError("Saved agent profile is invalid. Preserve its private files and request a fresh setup invitation.");
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
function loadConnectedAgentProfile(configDir, profileName) {
|
|
772
|
+
agentProfileName(profileName);
|
|
773
|
+
try {
|
|
774
|
+
privateMailDirectory(agentProfilesDirectory(configDir));
|
|
775
|
+
privateMailDirectory(join(agentProfilesDirectory(configDir), "profiles"));
|
|
776
|
+
privateMailDirectory(agentProfileDirectory(configDir, profileName));
|
|
777
|
+
const value = readMailJson(profilePath(configDir, profileName));
|
|
778
|
+
return value === null ? null : parseConnectedAgentProfile(value);
|
|
779
|
+
} catch (error) {
|
|
780
|
+
if (error.code === "ENOENT") return null;
|
|
781
|
+
throw new AgentConnectionSetupError("Cannot read the private agent profile. Check its ownership and permissions without exposing its contents.");
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
function saveConnectedAgentProfile(configDir, profileName, profile) {
|
|
785
|
+
const validated = parseConnectedAgentProfile(profile);
|
|
786
|
+
privateMailDirectory(agentProfilesDirectory(configDir), true);
|
|
787
|
+
privateMailDirectory(join(agentProfilesDirectory(configDir), "profiles"), true);
|
|
788
|
+
privateMailDirectory(agentProfileDirectory(configDir, profileName), true);
|
|
789
|
+
writeMailJson(profilePath(configDir, profileName), validated);
|
|
790
|
+
}
|
|
791
|
+
function connectedAgentIdentity(profileName, profile) {
|
|
792
|
+
return {
|
|
793
|
+
profileName,
|
|
794
|
+
orgId: profile.org_id,
|
|
795
|
+
agentAddress: profile.agent_address,
|
|
796
|
+
ownerAddress: profile.owner_address,
|
|
797
|
+
ownerMemberAddress: profile.owner_member_address ?? null,
|
|
798
|
+
apiBaseUrl: profile.api_base_url
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Validates a server-reported owner personal address. It is a person's
|
|
803
|
+
* mailbox, so it can never be the control sender or the agent itself.
|
|
804
|
+
*/
|
|
805
|
+
function parseOwnerMemberAddress(value, ownerAddress, agentAddress) {
|
|
806
|
+
if (value === null) return null;
|
|
807
|
+
const address = mailAddress(value);
|
|
808
|
+
if (address === ownerAddress || address === agentAddress) throw new Error();
|
|
809
|
+
return address;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Refusal text for a profile that is already connected (or mid-setup) with a
|
|
813
|
+
* different invitation. It never tells the agent to pick another profile on
|
|
814
|
+
* its own: whether this session keeps its address or replaces it is the
|
|
815
|
+
* user's decision.
|
|
816
|
+
*/
|
|
817
|
+
function profileAlreadyConnectedMessage(profileName, address) {
|
|
818
|
+
const who = address ? `already connected as ${address}` : "already set up";
|
|
819
|
+
const it = address ?? "it";
|
|
820
|
+
return [
|
|
821
|
+
`Agent profile ${profileName} is ${who} with a different invitation. No invitation was claimed and nothing was changed.`,
|
|
822
|
+
`Do not create a separate profile on your own. Ask the user whether to keep ${it} and not connect a new address, or to disconnect it first. Do not decide for them.`,
|
|
823
|
+
`If they choose to disconnect it, run \`primitive agent disconnect --profile ${profileName}\` (or rerun this command with --replace-existing when it is bound to this session), then connect again. If they want a second address on purpose, rerun with a new --profile and --keep-existing.`
|
|
824
|
+
].join(" ");
|
|
825
|
+
}
|
|
826
|
+
// src/oclif/chat-state.ts
|
|
827
|
+
const CHAT_STATE_FILE = "chat-state.json";
|
|
828
|
+
const CHAT_STATE_VERSION = 2;
|
|
829
|
+
const MAX_CONVERSATIONS = 50;
|
|
830
|
+
function isRecord$3(value) {
|
|
831
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
832
|
+
}
|
|
833
|
+
function nonEmptyString(value) {
|
|
834
|
+
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
835
|
+
}
|
|
836
|
+
function positiveInteger(value) {
|
|
837
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null;
|
|
838
|
+
}
|
|
839
|
+
function nonNegativeInteger(value) {
|
|
840
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
|
|
841
|
+
}
|
|
842
|
+
function parseLocalId(value) {
|
|
843
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= Number.MAX_SAFE_INTEGER ? value : null;
|
|
844
|
+
}
|
|
845
|
+
function chatStatePath(configDir, profileName = process.env["PRIMITIVE_AGENT_PROFILE"]?.trim() || null) {
|
|
846
|
+
return join(profileName ? agentProfileDirectory(configDir, profileName) : configDir, CHAT_STATE_FILE);
|
|
847
|
+
}
|
|
848
|
+
function deleteChatState(configDir) {
|
|
849
|
+
rmSync(chatStatePath(configDir, null), { force: true });
|
|
850
|
+
}
|
|
851
|
+
function chatConversationState(params) {
|
|
852
|
+
return {
|
|
853
|
+
...params.input,
|
|
854
|
+
local_id: params.localId,
|
|
855
|
+
updated_at: params.input.updated_at ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
function parseConversation(raw) {
|
|
859
|
+
if (!isRecord$3(raw)) return null;
|
|
860
|
+
const localId = parseLocalId(raw.local_id);
|
|
861
|
+
const recipient = nonEmptyString(raw.recipient);
|
|
862
|
+
const from = nonEmptyString(raw.from);
|
|
863
|
+
const lastReplyEmailId = nonEmptyString(raw.last_reply_email_id);
|
|
864
|
+
const lastSentEmailId = nonEmptyString(raw.last_sent_email_id);
|
|
865
|
+
const lastReplyReceivedAt = nonEmptyString(raw.last_reply_received_at);
|
|
866
|
+
const updatedAt = nonEmptyString(raw.updated_at);
|
|
867
|
+
const timeoutSeconds = nonNegativeInteger(raw.timeout_seconds);
|
|
868
|
+
const strictPhaseSeconds = positiveInteger(raw.strict_phase_seconds);
|
|
869
|
+
if (localId === null || !recipient || !from || !lastReplyEmailId || !lastSentEmailId || !lastReplyReceivedAt || !updatedAt || timeoutSeconds === null || strictPhaseSeconds === null || typeof raw.strict_only !== "boolean") return null;
|
|
870
|
+
const threadId = raw.thread_id !== null && raw.thread_id !== void 0 ? nonEmptyString(raw.thread_id) : null;
|
|
871
|
+
if (raw.thread_id !== null && raw.thread_id !== void 0 && !threadId) return null;
|
|
872
|
+
return {
|
|
873
|
+
from,
|
|
874
|
+
last_reply_email_id: lastReplyEmailId,
|
|
875
|
+
last_reply_received_at: lastReplyReceivedAt,
|
|
876
|
+
last_sent_email_id: lastSentEmailId,
|
|
877
|
+
local_id: localId,
|
|
878
|
+
recipient,
|
|
879
|
+
strict_only: raw.strict_only,
|
|
880
|
+
strict_phase_seconds: strictPhaseSeconds,
|
|
881
|
+
thread_id: threadId,
|
|
882
|
+
timeout_seconds: timeoutSeconds,
|
|
883
|
+
updated_at: updatedAt
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
function parseLegacyActiveState(raw) {
|
|
887
|
+
if (!isRecord$3(raw) || raw.version !== 1) return null;
|
|
888
|
+
const legacy = parseConversation({
|
|
889
|
+
...raw,
|
|
890
|
+
local_id: 0
|
|
891
|
+
});
|
|
892
|
+
if (!legacy) return null;
|
|
893
|
+
return {
|
|
894
|
+
active_local_id: 0,
|
|
895
|
+
conversations: [legacy],
|
|
896
|
+
next_local_id: 1,
|
|
897
|
+
version: CHAT_STATE_VERSION
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
function parseChatState(raw) {
|
|
901
|
+
if (!isRecord$3(raw)) return null;
|
|
902
|
+
if (raw.version === 1) return parseLegacyActiveState(raw);
|
|
903
|
+
if (raw.version !== CHAT_STATE_VERSION) return null;
|
|
904
|
+
if (!Array.isArray(raw.conversations)) return null;
|
|
905
|
+
const conversations = raw.conversations.map((entry) => parseConversation(entry)).filter((entry) => entry !== null);
|
|
906
|
+
if (conversations.length !== raw.conversations.length) return null;
|
|
907
|
+
const ids = /* @__PURE__ */ new Set();
|
|
908
|
+
for (const conversation of conversations) {
|
|
909
|
+
if (ids.has(conversation.local_id)) return null;
|
|
910
|
+
ids.add(conversation.local_id);
|
|
911
|
+
}
|
|
912
|
+
const activeLocalId = raw.active_local_id === null ? null : parseLocalId(raw.active_local_id);
|
|
913
|
+
if (activeLocalId === null && raw.active_local_id !== null) return null;
|
|
914
|
+
if (activeLocalId !== null && !ids.has(activeLocalId)) return null;
|
|
915
|
+
const nextLocalId = nonNegativeInteger(raw.next_local_id) ?? 0;
|
|
916
|
+
return {
|
|
917
|
+
active_local_id: activeLocalId,
|
|
918
|
+
conversations,
|
|
919
|
+
next_local_id: Math.max(nextLocalId, ...conversations.map((conversation) => conversation.local_id + 1), 0),
|
|
920
|
+
version: CHAT_STATE_VERSION
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
function loadChatState(configDir) {
|
|
924
|
+
let contents;
|
|
925
|
+
try {
|
|
926
|
+
contents = readFileSync(chatStatePath(configDir), "utf8");
|
|
927
|
+
} catch {
|
|
928
|
+
return null;
|
|
929
|
+
}
|
|
930
|
+
try {
|
|
931
|
+
return parseChatState(JSON.parse(contents));
|
|
932
|
+
} catch {
|
|
933
|
+
return null;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
function loadActiveChatState(configDir) {
|
|
937
|
+
const state = loadChatState(configDir);
|
|
938
|
+
if (state?.active_local_id === null || state === null) return null;
|
|
939
|
+
return state.conversations.find((conversation) => conversation.local_id === state.active_local_id) ?? null;
|
|
940
|
+
}
|
|
941
|
+
function loadChatConversationByLocalId(configDir, localId) {
|
|
942
|
+
return loadChatState(configDir)?.conversations.find((conversation) => conversation.local_id === localId) ?? null;
|
|
943
|
+
}
|
|
944
|
+
function saveChatState(configDir, state) {
|
|
945
|
+
const path = chatStatePath(configDir);
|
|
946
|
+
const directory = dirname(path);
|
|
947
|
+
mkdirSync(directory, {
|
|
948
|
+
mode: 448,
|
|
949
|
+
recursive: true
|
|
950
|
+
});
|
|
951
|
+
const tempPath = join(directory, `${CHAT_STATE_FILE}.${process.pid}.${randomUUID()}.tmp`);
|
|
952
|
+
try {
|
|
953
|
+
writeFileSync(tempPath, `${JSON.stringify(state, null, 2)}\n`, { mode: 384 });
|
|
954
|
+
renameSync(tempPath, path);
|
|
955
|
+
} catch (error) {
|
|
956
|
+
rmSync(tempPath, { force: true });
|
|
957
|
+
throw error;
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
function compareConversationUpdatedAt(left, right) {
|
|
961
|
+
return right.updated_at.localeCompare(left.updated_at);
|
|
962
|
+
}
|
|
963
|
+
function saveActiveChatState(configDir, input, options = {}) {
|
|
964
|
+
const existing = loadChatState(configDir) ?? {
|
|
965
|
+
active_local_id: null,
|
|
966
|
+
conversations: [],
|
|
967
|
+
next_local_id: 0,
|
|
968
|
+
version: CHAT_STATE_VERSION
|
|
969
|
+
};
|
|
970
|
+
const existingByPreferredId = options.preferredLocalId === void 0 ? void 0 : existing.conversations.find((conversation) => conversation.local_id === options.preferredLocalId);
|
|
971
|
+
const existingByThread = input.thread_id === null ? void 0 : existing.conversations.find((conversation) => conversation.thread_id === input.thread_id);
|
|
972
|
+
const localId = existingByPreferredId?.local_id ?? existingByThread?.local_id ?? existing.next_local_id;
|
|
973
|
+
const conversation = chatConversationState({
|
|
974
|
+
input,
|
|
975
|
+
localId
|
|
976
|
+
});
|
|
977
|
+
const conversations = [conversation, ...existing.conversations.filter((item) => item.local_id !== localId)].sort(compareConversationUpdatedAt).slice(0, MAX_CONVERSATIONS);
|
|
978
|
+
const activeStillPresent = conversations.some((item) => item.local_id === localId);
|
|
979
|
+
const nextLocalId = Math.max(existing.next_local_id, localId + 1, ...conversations.map((item) => item.local_id + 1));
|
|
980
|
+
saveChatState(configDir, {
|
|
981
|
+
active_local_id: activeStillPresent ? localId : null,
|
|
982
|
+
conversations,
|
|
983
|
+
next_local_id: nextLocalId,
|
|
984
|
+
version: CHAT_STATE_VERSION
|
|
985
|
+
});
|
|
986
|
+
return conversation;
|
|
987
|
+
}
|
|
988
|
+
// src/oclif/cli-lock.ts
|
|
989
|
+
const CLI_LOCK_FILE = "cli-lock.json";
|
|
990
|
+
const MIN_UNLOCK_SECONDS = 60;
|
|
991
|
+
const MAX_UNLOCK_SECONDS = 86400;
|
|
992
|
+
var CliAuthLockedError = class extends Error {
|
|
993
|
+
constructor(message) {
|
|
994
|
+
super(message);
|
|
995
|
+
this.name = "CliAuthLockedError";
|
|
996
|
+
}
|
|
997
|
+
};
|
|
998
|
+
function cliLockFilePath(configDir) {
|
|
999
|
+
return join(configDir, CLI_LOCK_FILE);
|
|
1000
|
+
}
|
|
1001
|
+
function isRecord$2(value) {
|
|
1002
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1003
|
+
}
|
|
1004
|
+
function readCliLockState(configDir, now = Date.now) {
|
|
1005
|
+
const path = cliLockFilePath(configDir);
|
|
1006
|
+
let rawText;
|
|
1007
|
+
try {
|
|
1008
|
+
const st = lstatSync(path);
|
|
1009
|
+
if (st.isSymbolicLink() || !st.isFile()) throw new CliAuthLockedError(`Refusing to read Primitive lock file at ${path}: expected a regular file.`);
|
|
1010
|
+
rawText = readFileSync(path, "utf8");
|
|
1011
|
+
} catch (error) {
|
|
1012
|
+
if (error instanceof CliAuthLockedError) throw error;
|
|
1013
|
+
if (error && typeof error === "object" && error.code === "ENOENT") return {
|
|
1014
|
+
status: "unlocked",
|
|
1015
|
+
locked: false
|
|
1016
|
+
};
|
|
1017
|
+
throw new CliAuthLockedError(`Could not read Primitive lock file at ${path}; failing closed. Run \`primitive unlock\` in your terminal to reset.`);
|
|
1018
|
+
}
|
|
1019
|
+
let parsed;
|
|
1020
|
+
try {
|
|
1021
|
+
parsed = JSON.parse(rawText);
|
|
1022
|
+
} catch {
|
|
1023
|
+
throw new CliAuthLockedError(`Primitive lock file at ${path} is malformed; failing closed. Run \`primitive unlock\` in your terminal to reset.`);
|
|
1024
|
+
}
|
|
1025
|
+
if (!isRecord$2(parsed) || parsed.locked !== true) return {
|
|
1026
|
+
status: "unlocked",
|
|
1027
|
+
locked: false
|
|
1028
|
+
};
|
|
1029
|
+
const lockedAt = typeof parsed.locked_at === "string" && parsed.locked_at.trim() ? parsed.locked_at : new Date(now()).toISOString();
|
|
1030
|
+
const reason = typeof parsed.reason === "string" && parsed.reason.trim() ? parsed.reason.trim() : null;
|
|
1031
|
+
const unlockedUntil = typeof parsed.unlocked_until === "string" && !Number.isNaN(Date.parse(parsed.unlocked_until)) ? parsed.unlocked_until : null;
|
|
1032
|
+
if (unlockedUntil && Date.parse(unlockedUntil) > now()) return {
|
|
1033
|
+
status: "temporarily_unlocked",
|
|
1034
|
+
locked: false,
|
|
1035
|
+
lockedAt,
|
|
1036
|
+
unlockedUntil,
|
|
1037
|
+
reason
|
|
1038
|
+
};
|
|
1039
|
+
return {
|
|
1040
|
+
status: "locked",
|
|
1041
|
+
locked: true,
|
|
1042
|
+
lockedAt,
|
|
1043
|
+
reason
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
function writeCliLockState(configDir, record) {
|
|
1047
|
+
const path = cliLockFilePath(configDir);
|
|
1048
|
+
const dir = dirname(path);
|
|
1049
|
+
mkdirSync(dir, {
|
|
1050
|
+
recursive: true,
|
|
1051
|
+
mode: 448
|
|
1052
|
+
});
|
|
1053
|
+
try {
|
|
1054
|
+
if (lstatSync(path).isSymbolicLink()) throw new CliAuthLockedError(`Refusing to overwrite symlinked Primitive lock file at ${path}.`);
|
|
1055
|
+
} catch (error) {
|
|
1056
|
+
if (error instanceof CliAuthLockedError) throw error;
|
|
1057
|
+
if (!(error && typeof error === "object" && error.code === "ENOENT")) throw error;
|
|
1058
|
+
}
|
|
1059
|
+
const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
1060
|
+
try {
|
|
1061
|
+
writeFileSync(tempPath, `${JSON.stringify(record, null, 2)}\n`, {
|
|
1062
|
+
flag: "wx",
|
|
1063
|
+
mode: 384
|
|
1064
|
+
});
|
|
1065
|
+
if (process.platform !== "win32") chmodSync(tempPath, 384);
|
|
1066
|
+
renameSync(tempPath, path);
|
|
1067
|
+
if (process.platform !== "win32") chmodSync(path, 384);
|
|
1068
|
+
} catch (error) {
|
|
1069
|
+
rmSync(tempPath, { force: true });
|
|
1070
|
+
throw error;
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
function removeCliLockState(configDir) {
|
|
1074
|
+
const path = cliLockFilePath(configDir);
|
|
1075
|
+
try {
|
|
1076
|
+
lstatSync(path);
|
|
1077
|
+
rmSync(path, { force: true });
|
|
1078
|
+
return true;
|
|
1079
|
+
} catch (error) {
|
|
1080
|
+
if (error && typeof error === "object" && error.code === "ENOENT") return false;
|
|
1081
|
+
throw error;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
function parseUnlockDurationSeconds(raw) {
|
|
1085
|
+
const trimmed = raw.trim().toLowerCase();
|
|
1086
|
+
const match = /^(\d+)(s|m|h|d)$/.exec(trimmed);
|
|
1087
|
+
if (!match?.[1] || !match[2]) throw new Error(`Invalid duration "${raw}". Use a value like 15m, 1h, or 4h (between 1m and 24h).`);
|
|
1088
|
+
const amount = Number.parseInt(match[1], 10);
|
|
1089
|
+
const unit = match[2];
|
|
1090
|
+
const seconds = amount * (unit === "s" ? 1 : unit === "m" ? 60 : unit === "h" ? 3600 : 86400);
|
|
1091
|
+
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).`);
|
|
1092
|
+
return seconds;
|
|
1093
|
+
}
|
|
1094
|
+
function formatLockedAuthErrorMessage(state) {
|
|
1095
|
+
return [
|
|
1096
|
+
`Global Primitive credentials are locked (\`primitive lock\` is active).${state.reason ? ` Reason: ${state.reason}.` : ""}`,
|
|
1097
|
+
"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).",
|
|
1098
|
+
"Humans: Run `primitive unlock --for 15m` (auto-relocks) or `primitive unlock` in your interactive terminal to use your global login or PRIMITIVE_API_KEY."
|
|
1099
|
+
].join("\n");
|
|
1100
|
+
}
|
|
1101
|
+
// src/oclif/auth.ts
|
|
1102
|
+
const CREDENTIALS_FILE = "credentials.json";
|
|
1103
|
+
const CREDENTIALS_LOCK_DIR = "credentials.lock";
|
|
1104
|
+
const CREDENTIALS_LOCK_OWNER_FILE = "owner.json";
|
|
1105
|
+
const CREDENTIALS_LOCK_STALE_MS = 18e5;
|
|
1106
|
+
const MALFORMED_CREDENTIALS_HINT = "Run `primitive logout` and then `primitive signin`.";
|
|
1107
|
+
const CREDENTIALS_LOCK_CLEANUP_SIGNALS = [
|
|
1108
|
+
"SIGINT",
|
|
1109
|
+
"SIGTERM",
|
|
1110
|
+
"SIGHUP"
|
|
1111
|
+
];
|
|
1112
|
+
function isRecord$1(value) {
|
|
1113
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1114
|
+
}
|
|
1115
|
+
function requireString(value, key) {
|
|
1116
|
+
const raw = value[key];
|
|
1117
|
+
if (typeof raw !== "string" || raw.trim().length === 0) throw new Error(`Stored Primitive CLI credentials are malformed: ${key} must be a non-empty string. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
1118
|
+
return raw;
|
|
1119
|
+
}
|
|
1120
|
+
function readStoredApiBaseUrl(raw) {
|
|
1121
|
+
const value = raw.api_base_url ?? raw.api_base_url_2 ?? raw.api_base_url_1;
|
|
1122
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new Error(`Stored Primitive CLI credentials are malformed: api_base_url must be a non-empty string. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
1123
|
+
return normalizeApiBaseUrl(value);
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* Sentinel returned by parseCredentials when the on-disk credentials were
|
|
1127
|
+
* written by an API-key-based CLI. The caller treats this as "not logged in"
|
|
1128
|
+
* after clearing the local file. The backing API key is intentionally not
|
|
1129
|
+
* revoked; API keys still work when passed explicitly via --api-key/env.
|
|
1130
|
+
*/
|
|
1131
|
+
var LegacyApiKeyCredentialFormatError = class extends Error {
|
|
1132
|
+
constructor() {
|
|
1133
|
+
super("legacy_api_key_credential_format");
|
|
1134
|
+
this.name = "LegacyApiKeyCredentialFormatError";
|
|
1135
|
+
}
|
|
1136
|
+
};
|
|
1137
|
+
function parseCredentials(raw) {
|
|
1138
|
+
if (!isRecord$1(raw)) throw new Error(`Stored Primitive CLI credentials are malformed: expected a JSON object. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
1139
|
+
if (raw.auth_method === "user_grant") return parseUserGrantCredentials(raw);
|
|
1140
|
+
if (raw.auth_method !== "oauth") {
|
|
1141
|
+
if (typeof raw.api_key === "string" || typeof raw.key_id === "string" || typeof raw.base_url === "string") throw new LegacyApiKeyCredentialFormatError();
|
|
1142
|
+
throw new Error(`Stored Primitive CLI credentials are malformed: auth_method must be oauth. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
1143
|
+
}
|
|
1144
|
+
const orgName = raw.org_name;
|
|
1145
|
+
if (orgName !== null && typeof orgName !== "string") throw new Error(`Stored Primitive CLI credentials are malformed: org_name must be a string or null. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
1146
|
+
if (requireString(raw, "token_type") !== "Bearer") throw new Error(`Stored Primitive CLI credentials are malformed: token_type must be Bearer. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
1147
|
+
return {
|
|
1148
|
+
auth_method: "oauth",
|
|
1149
|
+
access_token: requireString(raw, "access_token"),
|
|
1150
|
+
refresh_token: requireString(raw, "refresh_token"),
|
|
1151
|
+
token_type: "Bearer",
|
|
1152
|
+
expires_at: requireString(raw, "expires_at"),
|
|
1153
|
+
oauth_grant_id: requireString(raw, "oauth_grant_id"),
|
|
1154
|
+
oauth_client_id: requireString(raw, "oauth_client_id"),
|
|
1155
|
+
org_id: requireString(raw, "org_id"),
|
|
1156
|
+
org_name: orgName,
|
|
1157
|
+
api_base_url: readStoredApiBaseUrl(raw),
|
|
1158
|
+
created_at: requireString(raw, "created_at")
|
|
1159
|
+
};
|
|
1160
|
+
}
|
|
1161
|
+
function malformed(detail) {
|
|
1162
|
+
return /* @__PURE__ */ new Error(`Stored Primitive CLI credentials are malformed: ${detail}. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
1163
|
+
}
|
|
1164
|
+
function requireText(value, key, options = {}) {
|
|
1165
|
+
const raw = value[key];
|
|
1166
|
+
if (typeof raw !== "string" || !options.allowEmpty && raw.trim().length === 0) throw malformed(`${key} must be a non-empty string`);
|
|
1167
|
+
return raw;
|
|
1168
|
+
}
|
|
1169
|
+
function nullableText(value, key) {
|
|
1170
|
+
const raw = value[key];
|
|
1171
|
+
if (raw === void 0 || raw === null) return null;
|
|
1172
|
+
if (typeof raw !== "string") throw malformed(`${key} must be a string or null`);
|
|
1173
|
+
return raw;
|
|
1174
|
+
}
|
|
1175
|
+
function parseOrgToken(raw) {
|
|
1176
|
+
if (!isRecord$1(raw)) throw malformed("user_grant.org_tokens entries must be objects");
|
|
1177
|
+
return {
|
|
1178
|
+
access_token: requireText(raw, "access_token"),
|
|
1179
|
+
expires_at: requireText(raw, "expires_at"),
|
|
1180
|
+
oauth_grant_id: requireText(raw, "oauth_grant_id"),
|
|
1181
|
+
org_id: requireText(raw, "org_id"),
|
|
1182
|
+
org_name: nullableText(raw, "org_name"),
|
|
1183
|
+
role: nullableText(raw, "role")
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
function parseUserGrantCredentials(raw) {
|
|
1187
|
+
const grantRaw = raw.user_grant;
|
|
1188
|
+
if (!isRecord$1(grantRaw)) throw malformed("user_grant must be an object");
|
|
1189
|
+
if (raw.token_type !== "Bearer") throw malformed("token_type must be Bearer");
|
|
1190
|
+
const tokensRaw = grantRaw.org_tokens ?? {};
|
|
1191
|
+
if (!isRecord$1(tokensRaw)) throw malformed("user_grant.org_tokens must be an object");
|
|
1192
|
+
const orgTokens = {};
|
|
1193
|
+
for (const [orgId, token] of Object.entries(tokensRaw)) orgTokens[orgId] = parseOrgToken(token);
|
|
1194
|
+
const orgId = requireText(raw, "org_id", { allowEmpty: true });
|
|
1195
|
+
return {
|
|
1196
|
+
access_token: requireText(raw, "access_token", { allowEmpty: true }),
|
|
1197
|
+
api_base_url: readStoredApiBaseUrl(raw),
|
|
1198
|
+
auth_method: "user_grant",
|
|
1199
|
+
created_at: requireText(raw, "created_at"),
|
|
1200
|
+
expires_at: requireText(raw, "expires_at"),
|
|
1201
|
+
oauth_client_id: requireText(raw, "oauth_client_id"),
|
|
1202
|
+
oauth_grant_id: requireText(raw, "oauth_grant_id", { allowEmpty: true }),
|
|
1203
|
+
org_id: orgId,
|
|
1204
|
+
org_name: nullableText(raw, "org_name"),
|
|
1205
|
+
refresh_token: requireText(raw, "refresh_token"),
|
|
1206
|
+
token_type: "Bearer",
|
|
1207
|
+
user_grant: {
|
|
1208
|
+
access_token: requireText(grantRaw, "access_token"),
|
|
1209
|
+
expires_at: requireText(grantRaw, "expires_at"),
|
|
1210
|
+
org_role: nullableText(grantRaw, "org_role"),
|
|
1211
|
+
org_tokens: orgTokens,
|
|
1212
|
+
requested_grant: nullableText(grantRaw, "requested_grant"),
|
|
1213
|
+
user_grant_id: requireText(grantRaw, "user_grant_id"),
|
|
1214
|
+
user_id: requireText(grantRaw, "user_id")
|
|
1215
|
+
}
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
function credentialsPath(configDir) {
|
|
1219
|
+
return join(configDir, CREDENTIALS_FILE);
|
|
1220
|
+
}
|
|
1221
|
+
function credentialsLockPath(configDir) {
|
|
1222
|
+
return join(configDir, CREDENTIALS_LOCK_DIR);
|
|
1223
|
+
}
|
|
1224
|
+
function normalize$1(url, fallback) {
|
|
1225
|
+
const trimmed = url?.trim();
|
|
1226
|
+
if (!trimmed) return fallback;
|
|
1227
|
+
return trimmed.replace(/\/+$/, "");
|
|
1228
|
+
}
|
|
1229
|
+
function canonicalizeKnownApiBaseUrl(url) {
|
|
1230
|
+
let parsed;
|
|
1231
|
+
try {
|
|
1232
|
+
parsed = new URL(url);
|
|
1233
|
+
} catch {
|
|
1234
|
+
return url;
|
|
1235
|
+
}
|
|
1236
|
+
if (parsed.pathname.replace(/\/+$/, "") !== "/api/v1") return url;
|
|
1237
|
+
if (parsed.hostname === "primitive.dev" || parsed.hostname === "www.primitive.dev") {
|
|
1238
|
+
parsed.hostname = "api.primitive.dev";
|
|
1239
|
+
parsed.pathname = "/v1";
|
|
1240
|
+
return parsed.toString().replace(/\/+$/, "");
|
|
1241
|
+
}
|
|
1242
|
+
if (parsed.hostname === "primitive-staging-1.com") {
|
|
1243
|
+
parsed.hostname = "api.primitive-staging-1.com";
|
|
1244
|
+
parsed.pathname = "/v1";
|
|
1245
|
+
return parsed.toString().replace(/\/+$/, "");
|
|
1246
|
+
}
|
|
1247
|
+
return url;
|
|
1248
|
+
}
|
|
1249
|
+
function normalizeApiBaseUrl(url) {
|
|
1250
|
+
return canonicalizeKnownApiBaseUrl(normalize$1(url, DEFAULT_API_BASE_URL));
|
|
1251
|
+
}
|
|
1252
|
+
function cliAccessTokenExpiresAt(expiresInSeconds, now = Date.now) {
|
|
1253
|
+
return new Date(now() + expiresInSeconds * 1e3).toISOString();
|
|
1254
|
+
}
|
|
1255
|
+
function loadCliCredentials(configDir) {
|
|
1256
|
+
const path = credentialsPath(configDir);
|
|
1257
|
+
let contents;
|
|
1258
|
+
try {
|
|
1259
|
+
contents = readFileSync(path, "utf8");
|
|
1260
|
+
} catch (error) {
|
|
1261
|
+
if (error && typeof error === "object" && error.code === "ENOENT") return null;
|
|
1262
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1263
|
+
throw new Error(`Could not read Primitive CLI credentials: ${detail}`);
|
|
1264
|
+
}
|
|
1265
|
+
try {
|
|
1266
|
+
return parseCredentials(JSON.parse(contents));
|
|
1267
|
+
} catch (error) {
|
|
1268
|
+
if (error instanceof LegacyApiKeyCredentialFormatError) {
|
|
1269
|
+
try {
|
|
1270
|
+
rmSync(path, { force: true });
|
|
1271
|
+
deleteChatState(configDir);
|
|
1272
|
+
} catch {}
|
|
1273
|
+
process.stderr.write("Removed local Primitive CLI API-key login state. API keys are still valid when passed explicitly, but saved CLI auth now uses OAuth. Run `primitive signin` to create an OAuth session. No API key was revoked.\n");
|
|
1274
|
+
return null;
|
|
1275
|
+
}
|
|
1276
|
+
if (error instanceof SyntaxError) throw new Error("Stored Primitive CLI credentials are not valid JSON. Run `primitive logout` and then `primitive signin`.");
|
|
1277
|
+
throw error;
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
function saveCliCredentials(configDir, credentials) {
|
|
1281
|
+
requireDefaultLoginProfile();
|
|
1282
|
+
mkdirSync(configDir, {
|
|
1283
|
+
mode: 448,
|
|
1284
|
+
recursive: true
|
|
1285
|
+
});
|
|
1286
|
+
const path = credentialsPath(configDir);
|
|
1287
|
+
const tempPath = join(configDir, `${CREDENTIALS_FILE}.${process.pid}.${randomUUID()}.tmp`);
|
|
1288
|
+
try {
|
|
1289
|
+
writeFileSync(tempPath, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 384 });
|
|
1290
|
+
chmodSync(tempPath, 384);
|
|
1291
|
+
renameSync(tempPath, path);
|
|
1292
|
+
chmodSync(path, 384);
|
|
1293
|
+
} catch (error) {
|
|
1294
|
+
rmSync(tempPath, { force: true });
|
|
1295
|
+
throw error;
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
function deleteCliCredentials(configDir) {
|
|
1299
|
+
requireDefaultLoginProfile();
|
|
1300
|
+
rmSync(credentialsPath(configDir), { force: true });
|
|
1301
|
+
deleteChatState(configDir);
|
|
1302
|
+
}
|
|
1303
|
+
function saveSignupCredentials(params) {
|
|
1304
|
+
requireDefaultLoginProfile();
|
|
1305
|
+
deleteChatState(params.configDir);
|
|
1306
|
+
saveCliCredentials(params.configDir, {
|
|
1307
|
+
access_token: params.signup.access_token,
|
|
1308
|
+
api_base_url: params.apiBaseUrl,
|
|
1309
|
+
auth_method: "oauth",
|
|
1310
|
+
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1311
|
+
expires_at: cliAccessTokenExpiresAt(params.signup.expires_in),
|
|
1312
|
+
oauth_client_id: params.signup.oauth_client_id,
|
|
1313
|
+
oauth_grant_id: params.signup.oauth_grant_id,
|
|
1314
|
+
org_id: params.signup.org_id,
|
|
1315
|
+
org_name: params.signup.org_name,
|
|
1316
|
+
refresh_token: params.signup.refresh_token,
|
|
1317
|
+
token_type: params.signup.token_type
|
|
1318
|
+
});
|
|
1319
|
+
}
|
|
1320
|
+
function deleteCliCredentialsLock(configDir) {
|
|
1321
|
+
rmSync(credentialsLockPath(configDir), {
|
|
1322
|
+
force: true,
|
|
1323
|
+
recursive: true
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
function errorCode(error) {
|
|
1327
|
+
return error && typeof error === "object" ? error.code : void 0;
|
|
1328
|
+
}
|
|
1329
|
+
function removeStaleCliCredentialsLock(lockPath, staleMs, now) {
|
|
1330
|
+
try {
|
|
1331
|
+
const stats = statSync(lockPath);
|
|
1332
|
+
if (now() - stats.mtimeMs < staleMs) return false;
|
|
1333
|
+
} catch (error) {
|
|
1334
|
+
if (errorCode(error) === "ENOENT") return true;
|
|
1335
|
+
throw error;
|
|
1336
|
+
}
|
|
1337
|
+
rmSync(lockPath, {
|
|
1338
|
+
force: true,
|
|
1339
|
+
recursive: true
|
|
1340
|
+
});
|
|
1341
|
+
return true;
|
|
1342
|
+
}
|
|
1343
|
+
function readCliCredentialsLockOwner(lockPath) {
|
|
1344
|
+
let raw;
|
|
1345
|
+
try {
|
|
1346
|
+
raw = readFileSync(join(lockPath, CREDENTIALS_LOCK_OWNER_FILE), "utf8");
|
|
1347
|
+
} catch (error) {
|
|
1348
|
+
if (errorCode(error) === "ENOENT") return null;
|
|
1349
|
+
throw error;
|
|
1350
|
+
}
|
|
1351
|
+
try {
|
|
1352
|
+
const pid = JSON.parse(raw)?.pid;
|
|
1353
|
+
return Number.isInteger(pid) && pid > 0 ? { pid } : null;
|
|
1354
|
+
} catch {
|
|
1355
|
+
return null;
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
function processIsRunning(pid) {
|
|
1359
|
+
try {
|
|
1360
|
+
process.kill(pid, 0);
|
|
1361
|
+
return true;
|
|
1362
|
+
} catch (error) {
|
|
1363
|
+
if (errorCode(error) === "ESRCH") return false;
|
|
1364
|
+
return true;
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
function removeRecoverableCliCredentialsLock(params) {
|
|
1368
|
+
const owner = readCliCredentialsLockOwner(params.lockPath);
|
|
1369
|
+
if (owner && params.isRunning(owner.pid)) return false;
|
|
1370
|
+
if (owner) {
|
|
1371
|
+
rmSync(params.lockPath, {
|
|
1372
|
+
force: true,
|
|
1373
|
+
recursive: true
|
|
1374
|
+
});
|
|
1375
|
+
return true;
|
|
1376
|
+
}
|
|
1377
|
+
return removeStaleCliCredentialsLock(params.lockPath, params.staleMs, params.now);
|
|
1378
|
+
}
|
|
1379
|
+
function writeCliCredentialsLockOwner(lockPath) {
|
|
1380
|
+
const ownerPath = join(lockPath, CREDENTIALS_LOCK_OWNER_FILE);
|
|
1381
|
+
writeFileSync(ownerPath, `${JSON.stringify({
|
|
1382
|
+
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1383
|
+
pid: process.pid
|
|
1384
|
+
})}\n`, { mode: 384 });
|
|
1385
|
+
chmodSync(ownerPath, 384);
|
|
1386
|
+
}
|
|
1387
|
+
function installCredentialsLockSignalCleanup(lockPath) {
|
|
1388
|
+
let active = true;
|
|
1389
|
+
const listeners = CREDENTIALS_LOCK_CLEANUP_SIGNALS.map((signal) => {
|
|
1390
|
+
const listener = () => {
|
|
1391
|
+
if (!active) return;
|
|
1392
|
+
active = false;
|
|
1393
|
+
rmSync(lockPath, {
|
|
1394
|
+
force: true,
|
|
1395
|
+
recursive: true
|
|
1396
|
+
});
|
|
1397
|
+
process.exit(signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 129);
|
|
1398
|
+
};
|
|
1399
|
+
process.once(signal, listener);
|
|
1400
|
+
return {
|
|
1401
|
+
listener,
|
|
1402
|
+
signal
|
|
1403
|
+
};
|
|
1404
|
+
});
|
|
1405
|
+
return () => {
|
|
1406
|
+
if (!active) return;
|
|
1407
|
+
active = false;
|
|
1408
|
+
for (const { listener, signal } of listeners) process.removeListener(signal, listener);
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
function credentialsLockInProgressMessage(lockPath) {
|
|
1412
|
+
return `Another Primitive CLI credential operation is already in progress. Wait for it to finish, then retry. If no Primitive auth command is still running, run \`primitive logout --force\` to clear local CLI auth state and remove ${lockPath}.`;
|
|
1413
|
+
}
|
|
1414
|
+
function acquireCliCredentialsLock(configDir, options = {}) {
|
|
1415
|
+
requireDefaultLoginProfile();
|
|
1416
|
+
mkdirSync(configDir, {
|
|
1417
|
+
mode: 448,
|
|
1418
|
+
recursive: true
|
|
1419
|
+
});
|
|
1420
|
+
const lockPath = credentialsLockPath(configDir);
|
|
1421
|
+
const installSignalHandlers = options.installSignalHandlers ?? true;
|
|
1422
|
+
const isRunning = options.isProcessRunning ?? processIsRunning;
|
|
1423
|
+
const now = options.now ?? Date.now;
|
|
1424
|
+
const staleMs = options.staleMs ?? CREDENTIALS_LOCK_STALE_MS;
|
|
1425
|
+
let acquired = false;
|
|
1426
|
+
for (let attempt = 0; attempt < 2; attempt += 1) try {
|
|
1427
|
+
mkdirSync(lockPath, { mode: 448 });
|
|
1428
|
+
acquired = true;
|
|
1429
|
+
break;
|
|
1430
|
+
} catch (error) {
|
|
1431
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
1432
|
+
if (removeRecoverableCliCredentialsLock({
|
|
1433
|
+
isRunning,
|
|
1434
|
+
lockPath,
|
|
1435
|
+
now,
|
|
1436
|
+
staleMs
|
|
1437
|
+
})) continue;
|
|
1438
|
+
throw new Error(credentialsLockInProgressMessage(lockPath));
|
|
1439
|
+
}
|
|
1440
|
+
if (!acquired) throw new Error(credentialsLockInProgressMessage(lockPath));
|
|
1441
|
+
try {
|
|
1442
|
+
writeCliCredentialsLockOwner(lockPath);
|
|
1443
|
+
} catch (error) {
|
|
1444
|
+
rmSync(lockPath, {
|
|
1445
|
+
force: true,
|
|
1446
|
+
recursive: true
|
|
1447
|
+
});
|
|
1448
|
+
throw error;
|
|
1449
|
+
}
|
|
1450
|
+
const removeSignalCleanup = installSignalHandlers ? installCredentialsLockSignalCleanup(lockPath) : () => void 0;
|
|
1451
|
+
let released = false;
|
|
1452
|
+
return () => {
|
|
1453
|
+
if (released) return;
|
|
1454
|
+
released = true;
|
|
1455
|
+
removeSignalCleanup();
|
|
1456
|
+
rmSync(lockPath, {
|
|
1457
|
+
force: true,
|
|
1458
|
+
recursive: true
|
|
1459
|
+
});
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* Detect the PRIMITIVE_KEY vs PRIMITIVE_API_KEY rename trap.
|
|
1464
|
+
*
|
|
1465
|
+
* AGX feedback: users on older docs (or coming from other tools) set
|
|
1466
|
+
* `PRIMITIVE_KEY` and then cannot figure out why the CLI reports no
|
|
1467
|
+
* API key. The CLI reads `PRIMITIVE_API_KEY` only. Returns a stderr
|
|
1468
|
+
* hint when `PRIMITIVE_KEY` is set but `PRIMITIVE_API_KEY` is not,
|
|
1469
|
+
* otherwise null. Exported as a helper so both `doctor` and the
|
|
1470
|
+
* general auth-resolution path surface the same guidance from the
|
|
1471
|
+
* first command the user runs, instead of forcing them to discover
|
|
1472
|
+
* the rename via `doctor` after the fact.
|
|
1473
|
+
*/
|
|
1474
|
+
function detectPrimitiveKeyEnvMisname(env = process.env) {
|
|
1475
|
+
const primitiveKey = env.PRIMITIVE_KEY;
|
|
1476
|
+
const primitiveApiKey = env.PRIMITIVE_API_KEY;
|
|
1477
|
+
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.";
|
|
1478
|
+
return null;
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* True when a usable OAuth login session is saved on disk. Used by `pay-email`
|
|
1482
|
+
* to decide whether it can safely ignore an env-only `PRIMITIVE_API_KEY` in
|
|
1483
|
+
* favor of the payer's logged-in account (which owns the inbound challenge
|
|
1484
|
+
* inbox). Returns false when nothing is stored or the stored credential is
|
|
1485
|
+
* unreadable/legacy, so the caller falls back to whatever key did resolve
|
|
1486
|
+
* rather than silently dropping the user's only auth.
|
|
1487
|
+
*/
|
|
1488
|
+
function hasStoredCliLogin(configDir) {
|
|
1489
|
+
try {
|
|
1490
|
+
return loadCliCredentials(configDir) !== null;
|
|
1491
|
+
} catch {
|
|
1492
|
+
return false;
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
function resolveCliAuth(params) {
|
|
1496
|
+
const apiKey = params.apiKey?.trim();
|
|
1497
|
+
const apiBaseUrl = normalizeApiBaseUrl(params.apiBaseUrl);
|
|
1498
|
+
const profileName = (params.env ?? process.env)["PRIMITIVE_AGENT_PROFILE"]?.trim() || void 0;
|
|
1499
|
+
if (profileName !== void 0) {
|
|
1500
|
+
const profile = loadConnectedAgentProfile(params.configDir, profileName);
|
|
1501
|
+
if (!profile) throw new AgentConnectionSetupError(`Agent profile ${profileName} selected by PRIMITIVE_AGENT_PROFILE is not saved on this machine, so no login is used; run \`primitive agent status --profile ${profileName}\` to see what happened to it, or ${MEMBER_LOGIN_OPT_OUT}.`);
|
|
1502
|
+
if (apiKey && apiKey !== profile.api_key || params.apiBaseUrl !== void 0 && apiBaseUrl !== profile.api_base_url) throw new AgentConnectionSetupError(`An explicit API key or API origin conflicts with agent profile ${profileName} selected by PRIMITIVE_AGENT_PROFILE; drop the override to act as that agent, or rerun the same command with \`PRIMITIVE_AGENT_PROFILE=\` in front of it to use the override.`);
|
|
1503
|
+
return {
|
|
1504
|
+
apiKey: profile.api_key,
|
|
1505
|
+
apiBaseUrl: profile.api_base_url,
|
|
1506
|
+
credentials: null,
|
|
1507
|
+
connectedAgent: connectedAgentIdentity(profileName, profile),
|
|
1508
|
+
source: "connected-profile"
|
|
1509
|
+
};
|
|
1510
|
+
}
|
|
1511
|
+
const env = params.env ?? process.env;
|
|
1512
|
+
const ambientEnvApiKey = env.PRIMITIVE_API_KEY?.trim() || void 0;
|
|
1513
|
+
const ambientEnvBaseUrl = env.PRIMITIVE_API_BASE_URL?.trim() || void 0;
|
|
1514
|
+
const hasExplicitKeyOverride = Boolean(apiKey && apiKey !== ambientEnvApiKey);
|
|
1515
|
+
const hasExplicitBaseOverride = Boolean(params.apiBaseUrl !== void 0 && params.apiBaseUrl.trim() !== ambientEnvBaseUrl);
|
|
1516
|
+
const passProfile = env["PRIMITIVE_AGENT_PASS_PROFILE"]?.trim() || void 0;
|
|
1517
|
+
if (passProfile !== void 0) {
|
|
1518
|
+
const activePass = loadActiveAgentPass({
|
|
1519
|
+
configDir: params.configDir,
|
|
1520
|
+
profile: passProfile,
|
|
1521
|
+
env
|
|
1522
|
+
});
|
|
1523
|
+
if (activePass) {
|
|
1524
|
+
const validatedOverrideBase = hasExplicitBaseOverride ? validateAccessBaseUrl(apiBaseUrl) : void 0;
|
|
1525
|
+
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}.`);
|
|
1526
|
+
return {
|
|
1527
|
+
apiKey: activePass.pass.api_key,
|
|
1528
|
+
apiBaseUrl: activePass.pass.api_base_url,
|
|
1529
|
+
credentials: null,
|
|
1530
|
+
agentPass: agentPassMetadata(activePass.pass),
|
|
1531
|
+
source: "agent-pass"
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
const activePass = loadActiveAgentPass({
|
|
1536
|
+
configDir: params.configDir,
|
|
1537
|
+
env
|
|
1538
|
+
});
|
|
1539
|
+
if (activePass) {
|
|
1540
|
+
const validatedOverrideBase = hasExplicitBaseOverride ? validateAccessBaseUrl(apiBaseUrl) : void 0;
|
|
1541
|
+
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.`);
|
|
1542
|
+
return {
|
|
1543
|
+
apiKey: activePass.pass.api_key,
|
|
1544
|
+
apiBaseUrl: activePass.pass.api_base_url,
|
|
1545
|
+
credentials: null,
|
|
1546
|
+
agentPass: agentPassMetadata(activePass.pass),
|
|
1547
|
+
source: "agent-pass"
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
const lockState = readCliLockState(params.configDir);
|
|
1551
|
+
if (lockState.status === "locked") throw new CliAuthLockedError(formatLockedAuthErrorMessage(lockState));
|
|
1552
|
+
if (apiKey) return {
|
|
1553
|
+
apiKey,
|
|
1554
|
+
apiBaseUrl,
|
|
1555
|
+
credentials: null,
|
|
1556
|
+
source: "flag-or-env"
|
|
1557
|
+
};
|
|
1558
|
+
const credentials = loadCliCredentials(params.configDir);
|
|
1559
|
+
if (credentials) return {
|
|
1560
|
+
apiKey: credentials.access_token,
|
|
1561
|
+
apiBaseUrl: credentials.api_base_url,
|
|
1562
|
+
credentials,
|
|
1563
|
+
source: "stored"
|
|
1564
|
+
};
|
|
1565
|
+
return {
|
|
1566
|
+
apiKey: void 0,
|
|
1567
|
+
apiBaseUrl,
|
|
1568
|
+
credentials: null,
|
|
1569
|
+
source: "none"
|
|
1570
|
+
};
|
|
1571
|
+
}
|
|
1572
|
+
// src/oclif/cli-config.ts
|
|
1573
|
+
const CONFIG_FILE = "config.json";
|
|
1574
|
+
const CONFIG_VERSION = 1;
|
|
1575
|
+
const DEFAULT_ENVIRONMENT = "default";
|
|
1576
|
+
function cliConfigPath(configDir) {
|
|
1577
|
+
return join(configDir, CONFIG_FILE);
|
|
1578
|
+
}
|
|
1579
|
+
function cliConfigError(message) {
|
|
1580
|
+
return new Errors.CLIError(`${message} Run \`primitive config reset\` to clear the local CLI config.`, { exit: 1 });
|
|
1581
|
+
}
|
|
1582
|
+
function isRecord(value) {
|
|
1583
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1584
|
+
}
|
|
1585
|
+
function normalizeCliEnvironmentName(name) {
|
|
1586
|
+
const trimmed = name?.trim();
|
|
1587
|
+
if (!trimmed) throw new Errors.CLIError("Environment name must be a non-empty string.", { exit: 1 });
|
|
1588
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/.test(trimmed)) throw new Errors.CLIError("Environment name must start with a letter or number and may only contain letters, numbers, '.', '_', or '-'.", { exit: 1 });
|
|
1589
|
+
return trimmed;
|
|
1590
|
+
}
|
|
1591
|
+
function validateCliHeaderName(name) {
|
|
1592
|
+
const trimmed = name.trim();
|
|
1593
|
+
if (!trimmed) throw new Errors.CLIError("Header name must be a non-empty string.", { exit: 1 });
|
|
1594
|
+
if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(trimmed)) throw new Errors.CLIError(`Invalid header name: ${name}`, { exit: 1 });
|
|
1595
|
+
if (trimmed.toLowerCase() === "authorization") throw new Errors.CLIError("The Authorization header is managed by PRIMITIVE_API_KEY or saved OAuth CLI credentials.", { exit: 1 });
|
|
1596
|
+
return trimmed;
|
|
1597
|
+
}
|
|
1598
|
+
function validateCliHeaderValue(value, name) {
|
|
1599
|
+
if (value.length === 0) throw new Errors.CLIError(`Header ${name} value must not be empty.`, { exit: 1 });
|
|
1600
|
+
if (/[\r\n\0]/.test(value)) throw new Errors.CLIError(`Header ${name} value must not contain CR, LF, or NUL characters.`, { exit: 1 });
|
|
1601
|
+
return value;
|
|
1602
|
+
}
|
|
1603
|
+
function parseHeaderAssignment(assignment) {
|
|
1604
|
+
const separator = assignment.indexOf("=");
|
|
1605
|
+
if (separator <= 0) throw new Errors.CLIError("Header values must use name=value syntax, for example `x-custom=secret`.", { exit: 1 });
|
|
1606
|
+
const name = validateCliHeaderName(assignment.slice(0, separator));
|
|
1607
|
+
return [name, validateCliHeaderValue(assignment.slice(separator + 1), name)];
|
|
1608
|
+
}
|
|
1609
|
+
function parseHeaders(raw, context) {
|
|
1610
|
+
if (raw === void 0) return {};
|
|
1611
|
+
if (!isRecord(raw)) throw cliConfigError(`${context} headers must be a JSON object.`);
|
|
1612
|
+
const headers = {};
|
|
1613
|
+
for (const [rawName, rawValue] of Object.entries(raw)) {
|
|
1614
|
+
const name = validateCliHeaderName(rawName);
|
|
1615
|
+
if (typeof rawValue !== "string") throw cliConfigError(`${context} header ${name} must be a string.`);
|
|
1616
|
+
headers[name] = validateCliHeaderValue(rawValue, name);
|
|
1617
|
+
}
|
|
1618
|
+
return headers;
|
|
1619
|
+
}
|
|
1620
|
+
function parseEnvironmentConfig(raw, context) {
|
|
1621
|
+
if (!isRecord(raw)) throw cliConfigError(`${context} must be a JSON object.`);
|
|
1622
|
+
const env = {};
|
|
1623
|
+
const rawApiBaseUrl = raw.api_base_url ?? raw.api_base_url_2 ?? raw.api_base_url_1;
|
|
1624
|
+
if (rawApiBaseUrl !== void 0) {
|
|
1625
|
+
if (typeof rawApiBaseUrl !== "string") throw cliConfigError(`${context}.api_base_url must be a string.`);
|
|
1626
|
+
env.api_base_url = normalizeApiBaseUrl(rawApiBaseUrl);
|
|
1627
|
+
}
|
|
1628
|
+
const headers = parseHeaders(raw.headers, context);
|
|
1629
|
+
if (Object.keys(headers).length > 0) env.headers = headers;
|
|
1630
|
+
return env;
|
|
1631
|
+
}
|
|
1632
|
+
function parseStoredCliConfig(raw) {
|
|
1633
|
+
if (!isRecord(raw)) throw cliConfigError("Primitive CLI config must be a JSON object.");
|
|
1634
|
+
if (raw.version !== CONFIG_VERSION) throw cliConfigError(`Primitive CLI config version must be ${CONFIG_VERSION}.`);
|
|
1635
|
+
const currentRaw = raw.current_environment;
|
|
1636
|
+
const current_environment = currentRaw === null || currentRaw === void 0 ? null : typeof currentRaw === "string" ? normalizeCliEnvironmentName(currentRaw) : (() => {
|
|
1637
|
+
throw cliConfigError("Primitive CLI config current_environment must be a string or null.");
|
|
1638
|
+
})();
|
|
1639
|
+
if (!isRecord(raw.environments)) throw cliConfigError("Primitive CLI config environments must be an object.");
|
|
1640
|
+
const environments = {};
|
|
1641
|
+
for (const [rawName, rawEnv] of Object.entries(raw.environments)) {
|
|
1642
|
+
const name = normalizeCliEnvironmentName(rawName);
|
|
1643
|
+
environments[name] = parseEnvironmentConfig(rawEnv, `Primitive CLI config environment ${name}`);
|
|
1644
|
+
}
|
|
1645
|
+
if (current_environment && !environments[current_environment]) throw cliConfigError(`Primitive CLI config current environment ${current_environment} does not exist.`);
|
|
1646
|
+
return {
|
|
1647
|
+
version: CONFIG_VERSION,
|
|
1648
|
+
current_environment,
|
|
1649
|
+
environments
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
function emptyCliConfig() {
|
|
1653
|
+
return {
|
|
1654
|
+
version: CONFIG_VERSION,
|
|
1655
|
+
current_environment: null,
|
|
1656
|
+
environments: {}
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
function loadCliConfig(configDir) {
|
|
1660
|
+
const path = cliConfigPath(configDir);
|
|
1661
|
+
let contents;
|
|
1662
|
+
try {
|
|
1663
|
+
contents = readFileSync(path, "utf8");
|
|
1664
|
+
} catch (error) {
|
|
1665
|
+
if (error && typeof error === "object" && error.code === "ENOENT") return null;
|
|
1666
|
+
throw cliConfigError(`Could not read Primitive CLI config: ${error instanceof Error ? error.message : String(error)}.`);
|
|
1667
|
+
}
|
|
1668
|
+
try {
|
|
1669
|
+
return parseStoredCliConfig(JSON.parse(contents));
|
|
1670
|
+
} catch (error) {
|
|
1671
|
+
if (error instanceof SyntaxError) throw cliConfigError("Primitive CLI config is not valid JSON.");
|
|
1672
|
+
throw error;
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
function saveCliConfig(configDir, config) {
|
|
1676
|
+
mkdirSync(configDir, {
|
|
1677
|
+
mode: 448,
|
|
1678
|
+
recursive: true
|
|
1679
|
+
});
|
|
1680
|
+
const path = cliConfigPath(configDir);
|
|
1681
|
+
const tempPath = join(configDir, `${CONFIG_FILE}.${process.pid}.${randomUUID()}.tmp`);
|
|
1682
|
+
try {
|
|
1683
|
+
writeFileSync(tempPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 384 });
|
|
1684
|
+
renameSync(tempPath, path);
|
|
1685
|
+
} catch (error) {
|
|
1686
|
+
rmSync(tempPath, { force: true });
|
|
1687
|
+
throw error;
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
function deleteCliConfig(configDir) {
|
|
1691
|
+
rmSync(cliConfigPath(configDir), { force: true });
|
|
1692
|
+
}
|
|
1693
|
+
function resolveConfigEnvironment(config) {
|
|
1694
|
+
if (!config) return null;
|
|
1695
|
+
const current = config.current_environment;
|
|
1696
|
+
if (current) {
|
|
1697
|
+
const environment = config.environments[current];
|
|
1698
|
+
return environment ? {
|
|
1699
|
+
name: current,
|
|
1700
|
+
config: environment
|
|
1701
|
+
} : null;
|
|
1702
|
+
}
|
|
1703
|
+
const defaultEnvironment = config.environments[DEFAULT_ENVIRONMENT];
|
|
1704
|
+
return defaultEnvironment ? {
|
|
1705
|
+
name: DEFAULT_ENVIRONMENT,
|
|
1706
|
+
config: defaultEnvironment
|
|
1707
|
+
} : null;
|
|
1708
|
+
}
|
|
1709
|
+
function upsertCliEnvironment(params) {
|
|
1710
|
+
const name = normalizeCliEnvironmentName(params.environmentName ?? resolveConfigEnvironment(params.config)?.name ?? "default");
|
|
1711
|
+
const existing = params.config.environments[name] ?? {};
|
|
1712
|
+
const nextHeaders = { ...existing.headers ?? {} };
|
|
1713
|
+
for (const assignment of params.headers ?? []) {
|
|
1714
|
+
const [headerName, value] = parseHeaderAssignment(assignment);
|
|
1715
|
+
nextHeaders[headerName] = value;
|
|
1716
|
+
}
|
|
1717
|
+
for (const rawName of params.unsetHeaders ?? []) delete nextHeaders[validateCliHeaderName(rawName)];
|
|
1718
|
+
const nextEnvironment = {
|
|
1719
|
+
...existing,
|
|
1720
|
+
...params.apiBaseUrl !== void 0 ? { api_base_url: normalizeApiBaseUrl(params.apiBaseUrl) } : {},
|
|
1721
|
+
...Object.keys(nextHeaders).length > 0 ? { headers: nextHeaders } : {}
|
|
1722
|
+
};
|
|
1723
|
+
if (Object.keys(nextHeaders).length === 0) delete nextEnvironment.headers;
|
|
1724
|
+
return {
|
|
1725
|
+
...params.config,
|
|
1726
|
+
current_environment: params.use === false ? params.config.current_environment : name,
|
|
1727
|
+
environments: {
|
|
1728
|
+
...params.config.environments,
|
|
1729
|
+
[name]: nextEnvironment
|
|
1730
|
+
}
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
function removeCliEnvironment(config, environmentName) {
|
|
1734
|
+
const name = normalizeCliEnvironmentName(environmentName);
|
|
1735
|
+
const environments = { ...config.environments };
|
|
1736
|
+
delete environments[name];
|
|
1737
|
+
return {
|
|
1738
|
+
...config,
|
|
1739
|
+
current_environment: config.current_environment === name ? null : config.current_environment,
|
|
1740
|
+
environments
|
|
1741
|
+
};
|
|
1742
|
+
}
|
|
1743
|
+
function redactCliEnvironment(environment) {
|
|
1744
|
+
const headers = environment.headers && Object.keys(environment.headers).length > 0 ? Object.fromEntries(Object.keys(environment.headers).map((name) => [name, "***"])) : void 0;
|
|
1745
|
+
return {
|
|
1746
|
+
...environment,
|
|
1747
|
+
...headers ? { headers } : {}
|
|
1748
|
+
};
|
|
1749
|
+
}
|
|
1750
|
+
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 };
|