@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
|
@@ -1,949 +0,0 @@
|
|
|
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, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
-
import { randomUUID } from "node:crypto";
|
|
6
|
-
import { dirname, join } 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
|
-
function createDefaultAuth(apiKey) {
|
|
19
|
-
return (security) => {
|
|
20
|
-
if (security.type === "http" && security.scheme === "bearer") return apiKey;
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
var PrimitiveApiClient = class {
|
|
24
|
-
client;
|
|
25
|
-
constructor(options = {}) {
|
|
26
|
-
const { apiKey, auth, apiBaseUrl = DEFAULT_API_BASE_URL, ...config } = options;
|
|
27
|
-
const resolvedAuth = auth ?? createDefaultAuth(apiKey);
|
|
28
|
-
this.client = createClient(createConfig({
|
|
29
|
-
...config,
|
|
30
|
-
auth: resolvedAuth,
|
|
31
|
-
baseUrl: apiBaseUrl
|
|
32
|
-
}));
|
|
33
|
-
}
|
|
34
|
-
getConfig() {
|
|
35
|
-
return this.client.getConfig();
|
|
36
|
-
}
|
|
37
|
-
setConfig(config) {
|
|
38
|
-
return this.client.setConfig(config);
|
|
39
|
-
}
|
|
40
|
-
};
|
|
41
|
-
// src/oclif/connected-agent-profile.ts
|
|
42
|
-
const AGENT_PROFILE_ENV = "PRIMITIVE_AGENT_PROFILE";
|
|
43
|
-
/**
|
|
44
|
-
* The selected agent's email address, exported next to AGENT_PROFILE_ENV for
|
|
45
|
-
* a registered session so other tools can read it without running the CLI.
|
|
46
|
-
*/
|
|
47
|
-
const AGENT_ADDRESS_ENV = "PRIMITIVE_AGENT_ADDRESS";
|
|
48
|
-
/**
|
|
49
|
-
* One sentence telling a session whose agent is selected how to run a command
|
|
50
|
-
* as the member login instead. An empty PRIMITIVE_AGENT_PROFILE selects no
|
|
51
|
-
* profile everywhere in the CLI.
|
|
52
|
-
*/
|
|
53
|
-
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";
|
|
54
|
-
function parsePresenceProfile(value, owner) {
|
|
55
|
-
const row = mailObject(value, [
|
|
56
|
-
"protocol",
|
|
57
|
-
"version",
|
|
58
|
-
"authentication_profile",
|
|
59
|
-
"return_address"
|
|
60
|
-
]);
|
|
61
|
-
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.");
|
|
62
|
-
return {
|
|
63
|
-
protocol: "primitive.presence",
|
|
64
|
-
version: 1,
|
|
65
|
-
authentication_profile: "primitive-issued-v1",
|
|
66
|
-
return_address: owner
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
function supportedPresenceProfile(value, owner) {
|
|
70
|
-
if (value === void 0) return void 0;
|
|
71
|
-
try {
|
|
72
|
-
return parsePresenceProfile(value, owner);
|
|
73
|
-
} catch {
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
var AgentConnectionSetupError = class extends Error {};
|
|
78
|
-
function requireDefaultLoginProfile() {
|
|
79
|
-
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.`);
|
|
80
|
-
}
|
|
81
|
-
function agentProfileName(value) {
|
|
82
|
-
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).");
|
|
83
|
-
return value;
|
|
84
|
-
}
|
|
85
|
-
function connectedApiBaseUrl(value) {
|
|
86
|
-
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.");
|
|
87
|
-
return value;
|
|
88
|
-
}
|
|
89
|
-
function agentProfilesDirectory(configDir) {
|
|
90
|
-
return join(configDir, "agent-connections");
|
|
91
|
-
}
|
|
92
|
-
function agentProfileDirectory(configDir, profileName) {
|
|
93
|
-
return join(agentProfilesDirectory(configDir), "profiles", agentProfileName(profileName));
|
|
94
|
-
}
|
|
95
|
-
function profilePath(configDir, profileName) {
|
|
96
|
-
return join(agentProfileDirectory(configDir, profileName), "connection.json");
|
|
97
|
-
}
|
|
98
|
-
function parseConnectedAgentProfile(value) {
|
|
99
|
-
try {
|
|
100
|
-
const keys = [
|
|
101
|
-
"version",
|
|
102
|
-
"auth_method",
|
|
103
|
-
"api_key",
|
|
104
|
-
"api_base_url",
|
|
105
|
-
"org_id",
|
|
106
|
-
"agent_address",
|
|
107
|
-
"owner_address",
|
|
108
|
-
"invitation_hash",
|
|
109
|
-
"created_at"
|
|
110
|
-
];
|
|
111
|
-
const has = (key) => Boolean(value && typeof value === "object" && Object.hasOwn(value, key));
|
|
112
|
-
const row = mailObject(value, [
|
|
113
|
-
...keys,
|
|
114
|
-
...has("presence_profile") ? ["presence_profile"] : [],
|
|
115
|
-
...has("owner_member_address") ? ["owner_member_address"] : []
|
|
116
|
-
]);
|
|
117
|
-
const apiKey = mailString(row.api_key, 4096);
|
|
118
|
-
const invitationHash = mailString(row.invitation_hash, 64);
|
|
119
|
-
if (row.version !== 1 || row.auth_method !== "agent_connection" || !apiKey.startsWith("pconn_") || /\s/.test(apiKey) || !/^[a-f0-9]{64}$/.test(invitationHash)) throw new Error();
|
|
120
|
-
const presence = supportedPresenceProfile(row.presence_profile, mailAddress(row.owner_address));
|
|
121
|
-
const ownerMember = has("owner_member_address") ? parseOwnerMemberAddress(row.owner_member_address, mailAddress(row.owner_address), mailAddress(row.agent_address)) : void 0;
|
|
122
|
-
return {
|
|
123
|
-
version: 1,
|
|
124
|
-
auth_method: "agent_connection",
|
|
125
|
-
api_key: apiKey,
|
|
126
|
-
api_base_url: connectedApiBaseUrl(row.api_base_url),
|
|
127
|
-
org_id: mailId(row.org_id),
|
|
128
|
-
agent_address: mailAddress(row.agent_address),
|
|
129
|
-
owner_address: mailAddress(row.owner_address),
|
|
130
|
-
...ownerMember === void 0 ? {} : { owner_member_address: ownerMember },
|
|
131
|
-
invitation_hash: invitationHash,
|
|
132
|
-
created_at: mailTime(row.created_at),
|
|
133
|
-
...presence === void 0 ? {} : { presence_profile: presence }
|
|
134
|
-
};
|
|
135
|
-
} catch {
|
|
136
|
-
throw new AgentConnectionSetupError("Saved agent profile is invalid. Preserve its private files and request a fresh setup invitation.");
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
function loadConnectedAgentProfile(configDir, profileName) {
|
|
140
|
-
agentProfileName(profileName);
|
|
141
|
-
try {
|
|
142
|
-
privateMailDirectory(agentProfilesDirectory(configDir));
|
|
143
|
-
privateMailDirectory(join(agentProfilesDirectory(configDir), "profiles"));
|
|
144
|
-
privateMailDirectory(agentProfileDirectory(configDir, profileName));
|
|
145
|
-
const value = readMailJson(profilePath(configDir, profileName));
|
|
146
|
-
return value === null ? null : parseConnectedAgentProfile(value);
|
|
147
|
-
} catch (error) {
|
|
148
|
-
if (error.code === "ENOENT") return null;
|
|
149
|
-
throw new AgentConnectionSetupError("Cannot read the private agent profile. Check its ownership and permissions without exposing its contents.");
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
function saveConnectedAgentProfile(configDir, profileName, profile) {
|
|
153
|
-
const validated = parseConnectedAgentProfile(profile);
|
|
154
|
-
privateMailDirectory(agentProfilesDirectory(configDir), true);
|
|
155
|
-
privateMailDirectory(join(agentProfilesDirectory(configDir), "profiles"), true);
|
|
156
|
-
privateMailDirectory(agentProfileDirectory(configDir, profileName), true);
|
|
157
|
-
writeMailJson(profilePath(configDir, profileName), validated);
|
|
158
|
-
}
|
|
159
|
-
function connectedAgentIdentity(profileName, profile) {
|
|
160
|
-
return {
|
|
161
|
-
profileName,
|
|
162
|
-
orgId: profile.org_id,
|
|
163
|
-
agentAddress: profile.agent_address,
|
|
164
|
-
ownerAddress: profile.owner_address,
|
|
165
|
-
ownerMemberAddress: profile.owner_member_address ?? null,
|
|
166
|
-
apiBaseUrl: profile.api_base_url
|
|
167
|
-
};
|
|
168
|
-
}
|
|
169
|
-
/**
|
|
170
|
-
* Validates a server-reported owner personal address. It is a person's
|
|
171
|
-
* mailbox, so it can never be the control sender or the agent itself.
|
|
172
|
-
*/
|
|
173
|
-
function parseOwnerMemberAddress(value, ownerAddress, agentAddress) {
|
|
174
|
-
if (value === null) return null;
|
|
175
|
-
const address = mailAddress(value);
|
|
176
|
-
if (address === ownerAddress || address === agentAddress) throw new Error();
|
|
177
|
-
return address;
|
|
178
|
-
}
|
|
179
|
-
/**
|
|
180
|
-
* Refusal text for a profile that is already connected (or mid-setup) with a
|
|
181
|
-
* different invitation. It never tells the agent to pick another profile on
|
|
182
|
-
* its own: whether this session keeps its address or replaces it is the
|
|
183
|
-
* user's decision.
|
|
184
|
-
*/
|
|
185
|
-
function profileAlreadyConnectedMessage(profileName, address) {
|
|
186
|
-
const who = address ? `already connected as ${address}` : "already set up";
|
|
187
|
-
const it = address ?? "it";
|
|
188
|
-
return [
|
|
189
|
-
`Agent profile ${profileName} is ${who} with a different invitation. No invitation was claimed and nothing was changed.`,
|
|
190
|
-
`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.`,
|
|
191
|
-
`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.`
|
|
192
|
-
].join(" ");
|
|
193
|
-
}
|
|
194
|
-
// src/oclif/chat-state.ts
|
|
195
|
-
const CHAT_STATE_FILE = "chat-state.json";
|
|
196
|
-
const CHAT_STATE_VERSION = 2;
|
|
197
|
-
const MAX_CONVERSATIONS = 50;
|
|
198
|
-
function isRecord$2(value) {
|
|
199
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
200
|
-
}
|
|
201
|
-
function nonEmptyString(value) {
|
|
202
|
-
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
203
|
-
}
|
|
204
|
-
function positiveInteger(value) {
|
|
205
|
-
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null;
|
|
206
|
-
}
|
|
207
|
-
function nonNegativeInteger(value) {
|
|
208
|
-
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
|
|
209
|
-
}
|
|
210
|
-
function parseLocalId(value) {
|
|
211
|
-
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= Number.MAX_SAFE_INTEGER ? value : null;
|
|
212
|
-
}
|
|
213
|
-
function chatStatePath(configDir, profileName = process.env["PRIMITIVE_AGENT_PROFILE"]?.trim() || null) {
|
|
214
|
-
return join(profileName ? agentProfileDirectory(configDir, profileName) : configDir, CHAT_STATE_FILE);
|
|
215
|
-
}
|
|
216
|
-
function deleteChatState(configDir) {
|
|
217
|
-
rmSync(chatStatePath(configDir, null), { force: true });
|
|
218
|
-
}
|
|
219
|
-
function chatConversationState(params) {
|
|
220
|
-
return {
|
|
221
|
-
...params.input,
|
|
222
|
-
local_id: params.localId,
|
|
223
|
-
updated_at: params.input.updated_at ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
function parseConversation(raw) {
|
|
227
|
-
if (!isRecord$2(raw)) return null;
|
|
228
|
-
const localId = parseLocalId(raw.local_id);
|
|
229
|
-
const recipient = nonEmptyString(raw.recipient);
|
|
230
|
-
const from = nonEmptyString(raw.from);
|
|
231
|
-
const lastReplyEmailId = nonEmptyString(raw.last_reply_email_id);
|
|
232
|
-
const lastSentEmailId = nonEmptyString(raw.last_sent_email_id);
|
|
233
|
-
const lastReplyReceivedAt = nonEmptyString(raw.last_reply_received_at);
|
|
234
|
-
const updatedAt = nonEmptyString(raw.updated_at);
|
|
235
|
-
const timeoutSeconds = nonNegativeInteger(raw.timeout_seconds);
|
|
236
|
-
const strictPhaseSeconds = positiveInteger(raw.strict_phase_seconds);
|
|
237
|
-
if (localId === null || !recipient || !from || !lastReplyEmailId || !lastSentEmailId || !lastReplyReceivedAt || !updatedAt || timeoutSeconds === null || strictPhaseSeconds === null || typeof raw.strict_only !== "boolean") return null;
|
|
238
|
-
const threadId = raw.thread_id !== null && raw.thread_id !== void 0 ? nonEmptyString(raw.thread_id) : null;
|
|
239
|
-
if (raw.thread_id !== null && raw.thread_id !== void 0 && !threadId) return null;
|
|
240
|
-
return {
|
|
241
|
-
from,
|
|
242
|
-
last_reply_email_id: lastReplyEmailId,
|
|
243
|
-
last_reply_received_at: lastReplyReceivedAt,
|
|
244
|
-
last_sent_email_id: lastSentEmailId,
|
|
245
|
-
local_id: localId,
|
|
246
|
-
recipient,
|
|
247
|
-
strict_only: raw.strict_only,
|
|
248
|
-
strict_phase_seconds: strictPhaseSeconds,
|
|
249
|
-
thread_id: threadId,
|
|
250
|
-
timeout_seconds: timeoutSeconds,
|
|
251
|
-
updated_at: updatedAt
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
function parseLegacyActiveState(raw) {
|
|
255
|
-
if (!isRecord$2(raw) || raw.version !== 1) return null;
|
|
256
|
-
const legacy = parseConversation({
|
|
257
|
-
...raw,
|
|
258
|
-
local_id: 0
|
|
259
|
-
});
|
|
260
|
-
if (!legacy) return null;
|
|
261
|
-
return {
|
|
262
|
-
active_local_id: 0,
|
|
263
|
-
conversations: [legacy],
|
|
264
|
-
next_local_id: 1,
|
|
265
|
-
version: CHAT_STATE_VERSION
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
function parseChatState(raw) {
|
|
269
|
-
if (!isRecord$2(raw)) return null;
|
|
270
|
-
if (raw.version === 1) return parseLegacyActiveState(raw);
|
|
271
|
-
if (raw.version !== CHAT_STATE_VERSION) return null;
|
|
272
|
-
if (!Array.isArray(raw.conversations)) return null;
|
|
273
|
-
const conversations = raw.conversations.map((entry) => parseConversation(entry)).filter((entry) => entry !== null);
|
|
274
|
-
if (conversations.length !== raw.conversations.length) return null;
|
|
275
|
-
const ids = /* @__PURE__ */ new Set();
|
|
276
|
-
for (const conversation of conversations) {
|
|
277
|
-
if (ids.has(conversation.local_id)) return null;
|
|
278
|
-
ids.add(conversation.local_id);
|
|
279
|
-
}
|
|
280
|
-
const activeLocalId = raw.active_local_id === null ? null : parseLocalId(raw.active_local_id);
|
|
281
|
-
if (activeLocalId === null && raw.active_local_id !== null) return null;
|
|
282
|
-
if (activeLocalId !== null && !ids.has(activeLocalId)) return null;
|
|
283
|
-
const nextLocalId = nonNegativeInteger(raw.next_local_id) ?? 0;
|
|
284
|
-
return {
|
|
285
|
-
active_local_id: activeLocalId,
|
|
286
|
-
conversations,
|
|
287
|
-
next_local_id: Math.max(nextLocalId, ...conversations.map((conversation) => conversation.local_id + 1), 0),
|
|
288
|
-
version: CHAT_STATE_VERSION
|
|
289
|
-
};
|
|
290
|
-
}
|
|
291
|
-
function loadChatState(configDir) {
|
|
292
|
-
let contents;
|
|
293
|
-
try {
|
|
294
|
-
contents = readFileSync(chatStatePath(configDir), "utf8");
|
|
295
|
-
} catch {
|
|
296
|
-
return null;
|
|
297
|
-
}
|
|
298
|
-
try {
|
|
299
|
-
return parseChatState(JSON.parse(contents));
|
|
300
|
-
} catch {
|
|
301
|
-
return null;
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
function loadActiveChatState(configDir) {
|
|
305
|
-
const state = loadChatState(configDir);
|
|
306
|
-
if (state?.active_local_id === null || state === null) return null;
|
|
307
|
-
return state.conversations.find((conversation) => conversation.local_id === state.active_local_id) ?? null;
|
|
308
|
-
}
|
|
309
|
-
function loadChatConversationByLocalId(configDir, localId) {
|
|
310
|
-
return loadChatState(configDir)?.conversations.find((conversation) => conversation.local_id === localId) ?? null;
|
|
311
|
-
}
|
|
312
|
-
function saveChatState(configDir, state) {
|
|
313
|
-
const path = chatStatePath(configDir);
|
|
314
|
-
const directory = dirname(path);
|
|
315
|
-
mkdirSync(directory, {
|
|
316
|
-
mode: 448,
|
|
317
|
-
recursive: true
|
|
318
|
-
});
|
|
319
|
-
const tempPath = join(directory, `${CHAT_STATE_FILE}.${process.pid}.${randomUUID()}.tmp`);
|
|
320
|
-
try {
|
|
321
|
-
writeFileSync(tempPath, `${JSON.stringify(state, null, 2)}\n`, { mode: 384 });
|
|
322
|
-
renameSync(tempPath, path);
|
|
323
|
-
} catch (error) {
|
|
324
|
-
rmSync(tempPath, { force: true });
|
|
325
|
-
throw error;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
function compareConversationUpdatedAt(left, right) {
|
|
329
|
-
return right.updated_at.localeCompare(left.updated_at);
|
|
330
|
-
}
|
|
331
|
-
function saveActiveChatState(configDir, input, options = {}) {
|
|
332
|
-
const existing = loadChatState(configDir) ?? {
|
|
333
|
-
active_local_id: null,
|
|
334
|
-
conversations: [],
|
|
335
|
-
next_local_id: 0,
|
|
336
|
-
version: CHAT_STATE_VERSION
|
|
337
|
-
};
|
|
338
|
-
const existingByPreferredId = options.preferredLocalId === void 0 ? void 0 : existing.conversations.find((conversation) => conversation.local_id === options.preferredLocalId);
|
|
339
|
-
const existingByThread = input.thread_id === null ? void 0 : existing.conversations.find((conversation) => conversation.thread_id === input.thread_id);
|
|
340
|
-
const localId = existingByPreferredId?.local_id ?? existingByThread?.local_id ?? existing.next_local_id;
|
|
341
|
-
const conversation = chatConversationState({
|
|
342
|
-
input,
|
|
343
|
-
localId
|
|
344
|
-
});
|
|
345
|
-
const conversations = [conversation, ...existing.conversations.filter((item) => item.local_id !== localId)].sort(compareConversationUpdatedAt).slice(0, MAX_CONVERSATIONS);
|
|
346
|
-
const activeStillPresent = conversations.some((item) => item.local_id === localId);
|
|
347
|
-
const nextLocalId = Math.max(existing.next_local_id, localId + 1, ...conversations.map((item) => item.local_id + 1));
|
|
348
|
-
saveChatState(configDir, {
|
|
349
|
-
active_local_id: activeStillPresent ? localId : null,
|
|
350
|
-
conversations,
|
|
351
|
-
next_local_id: nextLocalId,
|
|
352
|
-
version: CHAT_STATE_VERSION
|
|
353
|
-
});
|
|
354
|
-
return conversation;
|
|
355
|
-
}
|
|
356
|
-
// src/oclif/auth.ts
|
|
357
|
-
const CREDENTIALS_FILE = "credentials.json";
|
|
358
|
-
const CREDENTIALS_LOCK_DIR = "credentials.lock";
|
|
359
|
-
const CREDENTIALS_LOCK_OWNER_FILE = "owner.json";
|
|
360
|
-
const CREDENTIALS_LOCK_STALE_MS = 18e5;
|
|
361
|
-
const MALFORMED_CREDENTIALS_HINT = "Run `primitive logout` and then `primitive signin`.";
|
|
362
|
-
const CREDENTIALS_LOCK_CLEANUP_SIGNALS = [
|
|
363
|
-
"SIGINT",
|
|
364
|
-
"SIGTERM",
|
|
365
|
-
"SIGHUP"
|
|
366
|
-
];
|
|
367
|
-
function isRecord$1(value) {
|
|
368
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
369
|
-
}
|
|
370
|
-
function requireString(value, key) {
|
|
371
|
-
const raw = value[key];
|
|
372
|
-
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}`);
|
|
373
|
-
return raw;
|
|
374
|
-
}
|
|
375
|
-
function readStoredApiBaseUrl(raw) {
|
|
376
|
-
const value = raw.api_base_url ?? raw.api_base_url_2 ?? raw.api_base_url_1;
|
|
377
|
-
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}`);
|
|
378
|
-
return normalizeApiBaseUrl(value);
|
|
379
|
-
}
|
|
380
|
-
/**
|
|
381
|
-
* Sentinel returned by parseCredentials when the on-disk credentials were
|
|
382
|
-
* written by an API-key-based CLI. The caller treats this as "not logged in"
|
|
383
|
-
* after clearing the local file. The backing API key is intentionally not
|
|
384
|
-
* revoked; API keys still work when passed explicitly via --api-key/env.
|
|
385
|
-
*/
|
|
386
|
-
var LegacyApiKeyCredentialFormatError = class extends Error {
|
|
387
|
-
constructor() {
|
|
388
|
-
super("legacy_api_key_credential_format");
|
|
389
|
-
this.name = "LegacyApiKeyCredentialFormatError";
|
|
390
|
-
}
|
|
391
|
-
};
|
|
392
|
-
function parseCredentials(raw) {
|
|
393
|
-
if (!isRecord$1(raw)) throw new Error(`Stored Primitive CLI credentials are malformed: expected a JSON object. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
394
|
-
if (raw.auth_method === "user_grant") return parseUserGrantCredentials(raw);
|
|
395
|
-
if (raw.auth_method !== "oauth") {
|
|
396
|
-
if (typeof raw.api_key === "string" || typeof raw.key_id === "string" || typeof raw.base_url === "string") throw new LegacyApiKeyCredentialFormatError();
|
|
397
|
-
throw new Error(`Stored Primitive CLI credentials are malformed: auth_method must be oauth. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
398
|
-
}
|
|
399
|
-
const orgName = raw.org_name;
|
|
400
|
-
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}`);
|
|
401
|
-
if (requireString(raw, "token_type") !== "Bearer") throw new Error(`Stored Primitive CLI credentials are malformed: token_type must be Bearer. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
402
|
-
return {
|
|
403
|
-
auth_method: "oauth",
|
|
404
|
-
access_token: requireString(raw, "access_token"),
|
|
405
|
-
refresh_token: requireString(raw, "refresh_token"),
|
|
406
|
-
token_type: "Bearer",
|
|
407
|
-
expires_at: requireString(raw, "expires_at"),
|
|
408
|
-
oauth_grant_id: requireString(raw, "oauth_grant_id"),
|
|
409
|
-
oauth_client_id: requireString(raw, "oauth_client_id"),
|
|
410
|
-
org_id: requireString(raw, "org_id"),
|
|
411
|
-
org_name: orgName,
|
|
412
|
-
api_base_url: readStoredApiBaseUrl(raw),
|
|
413
|
-
created_at: requireString(raw, "created_at")
|
|
414
|
-
};
|
|
415
|
-
}
|
|
416
|
-
function malformed(detail) {
|
|
417
|
-
return /* @__PURE__ */ new Error(`Stored Primitive CLI credentials are malformed: ${detail}. ${MALFORMED_CREDENTIALS_HINT}`);
|
|
418
|
-
}
|
|
419
|
-
function requireText(value, key, options = {}) {
|
|
420
|
-
const raw = value[key];
|
|
421
|
-
if (typeof raw !== "string" || !options.allowEmpty && raw.trim().length === 0) throw malformed(`${key} must be a non-empty string`);
|
|
422
|
-
return raw;
|
|
423
|
-
}
|
|
424
|
-
function nullableText(value, key) {
|
|
425
|
-
const raw = value[key];
|
|
426
|
-
if (raw === void 0 || raw === null) return null;
|
|
427
|
-
if (typeof raw !== "string") throw malformed(`${key} must be a string or null`);
|
|
428
|
-
return raw;
|
|
429
|
-
}
|
|
430
|
-
function parseOrgToken(raw) {
|
|
431
|
-
if (!isRecord$1(raw)) throw malformed("user_grant.org_tokens entries must be objects");
|
|
432
|
-
return {
|
|
433
|
-
access_token: requireText(raw, "access_token"),
|
|
434
|
-
expires_at: requireText(raw, "expires_at"),
|
|
435
|
-
oauth_grant_id: requireText(raw, "oauth_grant_id"),
|
|
436
|
-
org_id: requireText(raw, "org_id"),
|
|
437
|
-
org_name: nullableText(raw, "org_name"),
|
|
438
|
-
role: nullableText(raw, "role")
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
function parseUserGrantCredentials(raw) {
|
|
442
|
-
const grantRaw = raw.user_grant;
|
|
443
|
-
if (!isRecord$1(grantRaw)) throw malformed("user_grant must be an object");
|
|
444
|
-
if (raw.token_type !== "Bearer") throw malformed("token_type must be Bearer");
|
|
445
|
-
const tokensRaw = grantRaw.org_tokens ?? {};
|
|
446
|
-
if (!isRecord$1(tokensRaw)) throw malformed("user_grant.org_tokens must be an object");
|
|
447
|
-
const orgTokens = {};
|
|
448
|
-
for (const [orgId, token] of Object.entries(tokensRaw)) orgTokens[orgId] = parseOrgToken(token);
|
|
449
|
-
const orgId = requireText(raw, "org_id", { allowEmpty: true });
|
|
450
|
-
return {
|
|
451
|
-
access_token: requireText(raw, "access_token", { allowEmpty: true }),
|
|
452
|
-
api_base_url: readStoredApiBaseUrl(raw),
|
|
453
|
-
auth_method: "user_grant",
|
|
454
|
-
created_at: requireText(raw, "created_at"),
|
|
455
|
-
expires_at: requireText(raw, "expires_at"),
|
|
456
|
-
oauth_client_id: requireText(raw, "oauth_client_id"),
|
|
457
|
-
oauth_grant_id: requireText(raw, "oauth_grant_id", { allowEmpty: true }),
|
|
458
|
-
org_id: orgId,
|
|
459
|
-
org_name: nullableText(raw, "org_name"),
|
|
460
|
-
refresh_token: requireText(raw, "refresh_token"),
|
|
461
|
-
token_type: "Bearer",
|
|
462
|
-
user_grant: {
|
|
463
|
-
access_token: requireText(grantRaw, "access_token"),
|
|
464
|
-
expires_at: requireText(grantRaw, "expires_at"),
|
|
465
|
-
org_role: nullableText(grantRaw, "org_role"),
|
|
466
|
-
org_tokens: orgTokens,
|
|
467
|
-
requested_grant: nullableText(grantRaw, "requested_grant"),
|
|
468
|
-
user_grant_id: requireText(grantRaw, "user_grant_id"),
|
|
469
|
-
user_id: requireText(grantRaw, "user_id")
|
|
470
|
-
}
|
|
471
|
-
};
|
|
472
|
-
}
|
|
473
|
-
function credentialsPath(configDir) {
|
|
474
|
-
return join(configDir, CREDENTIALS_FILE);
|
|
475
|
-
}
|
|
476
|
-
function credentialsLockPath(configDir) {
|
|
477
|
-
return join(configDir, CREDENTIALS_LOCK_DIR);
|
|
478
|
-
}
|
|
479
|
-
function normalize$1(url, fallback) {
|
|
480
|
-
const trimmed = url?.trim();
|
|
481
|
-
if (!trimmed) return fallback;
|
|
482
|
-
return trimmed.replace(/\/+$/, "");
|
|
483
|
-
}
|
|
484
|
-
function canonicalizeKnownApiBaseUrl(url) {
|
|
485
|
-
let parsed;
|
|
486
|
-
try {
|
|
487
|
-
parsed = new URL(url);
|
|
488
|
-
} catch {
|
|
489
|
-
return url;
|
|
490
|
-
}
|
|
491
|
-
if (parsed.pathname.replace(/\/+$/, "") !== "/api/v1") return url;
|
|
492
|
-
if (parsed.hostname === "primitive.dev" || parsed.hostname === "www.primitive.dev") {
|
|
493
|
-
parsed.hostname = "api.primitive.dev";
|
|
494
|
-
parsed.pathname = "/v1";
|
|
495
|
-
return parsed.toString().replace(/\/+$/, "");
|
|
496
|
-
}
|
|
497
|
-
if (parsed.hostname === "primitive-staging-1.com") {
|
|
498
|
-
parsed.hostname = "api.primitive-staging-1.com";
|
|
499
|
-
parsed.pathname = "/v1";
|
|
500
|
-
return parsed.toString().replace(/\/+$/, "");
|
|
501
|
-
}
|
|
502
|
-
return url;
|
|
503
|
-
}
|
|
504
|
-
function normalizeApiBaseUrl(url) {
|
|
505
|
-
return canonicalizeKnownApiBaseUrl(normalize$1(url, DEFAULT_API_BASE_URL));
|
|
506
|
-
}
|
|
507
|
-
function cliAccessTokenExpiresAt(expiresInSeconds, now = Date.now) {
|
|
508
|
-
return new Date(now() + expiresInSeconds * 1e3).toISOString();
|
|
509
|
-
}
|
|
510
|
-
function loadCliCredentials(configDir) {
|
|
511
|
-
const path = credentialsPath(configDir);
|
|
512
|
-
let contents;
|
|
513
|
-
try {
|
|
514
|
-
contents = readFileSync(path, "utf8");
|
|
515
|
-
} catch (error) {
|
|
516
|
-
if (error && typeof error === "object" && error.code === "ENOENT") return null;
|
|
517
|
-
const detail = error instanceof Error ? error.message : String(error);
|
|
518
|
-
throw new Error(`Could not read Primitive CLI credentials: ${detail}`);
|
|
519
|
-
}
|
|
520
|
-
try {
|
|
521
|
-
return parseCredentials(JSON.parse(contents));
|
|
522
|
-
} catch (error) {
|
|
523
|
-
if (error instanceof LegacyApiKeyCredentialFormatError) {
|
|
524
|
-
try {
|
|
525
|
-
rmSync(path, { force: true });
|
|
526
|
-
deleteChatState(configDir);
|
|
527
|
-
} catch {}
|
|
528
|
-
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");
|
|
529
|
-
return null;
|
|
530
|
-
}
|
|
531
|
-
if (error instanceof SyntaxError) throw new Error("Stored Primitive CLI credentials are not valid JSON. Run `primitive logout` and then `primitive signin`.");
|
|
532
|
-
throw error;
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
function saveCliCredentials(configDir, credentials) {
|
|
536
|
-
requireDefaultLoginProfile();
|
|
537
|
-
mkdirSync(configDir, {
|
|
538
|
-
mode: 448,
|
|
539
|
-
recursive: true
|
|
540
|
-
});
|
|
541
|
-
const path = credentialsPath(configDir);
|
|
542
|
-
const tempPath = join(configDir, `${CREDENTIALS_FILE}.${process.pid}.${randomUUID()}.tmp`);
|
|
543
|
-
try {
|
|
544
|
-
writeFileSync(tempPath, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 384 });
|
|
545
|
-
chmodSync(tempPath, 384);
|
|
546
|
-
renameSync(tempPath, path);
|
|
547
|
-
chmodSync(path, 384);
|
|
548
|
-
} catch (error) {
|
|
549
|
-
rmSync(tempPath, { force: true });
|
|
550
|
-
throw error;
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
function deleteCliCredentials(configDir) {
|
|
554
|
-
requireDefaultLoginProfile();
|
|
555
|
-
rmSync(credentialsPath(configDir), { force: true });
|
|
556
|
-
deleteChatState(configDir);
|
|
557
|
-
}
|
|
558
|
-
function saveSignupCredentials(params) {
|
|
559
|
-
requireDefaultLoginProfile();
|
|
560
|
-
deleteChatState(params.configDir);
|
|
561
|
-
saveCliCredentials(params.configDir, {
|
|
562
|
-
access_token: params.signup.access_token,
|
|
563
|
-
api_base_url: params.apiBaseUrl,
|
|
564
|
-
auth_method: "oauth",
|
|
565
|
-
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
566
|
-
expires_at: cliAccessTokenExpiresAt(params.signup.expires_in),
|
|
567
|
-
oauth_client_id: params.signup.oauth_client_id,
|
|
568
|
-
oauth_grant_id: params.signup.oauth_grant_id,
|
|
569
|
-
org_id: params.signup.org_id,
|
|
570
|
-
org_name: params.signup.org_name,
|
|
571
|
-
refresh_token: params.signup.refresh_token,
|
|
572
|
-
token_type: params.signup.token_type
|
|
573
|
-
});
|
|
574
|
-
}
|
|
575
|
-
function deleteCliCredentialsLock(configDir) {
|
|
576
|
-
rmSync(credentialsLockPath(configDir), {
|
|
577
|
-
force: true,
|
|
578
|
-
recursive: true
|
|
579
|
-
});
|
|
580
|
-
}
|
|
581
|
-
function errorCode(error) {
|
|
582
|
-
return error && typeof error === "object" ? error.code : void 0;
|
|
583
|
-
}
|
|
584
|
-
function removeStaleCliCredentialsLock(lockPath, staleMs, now) {
|
|
585
|
-
try {
|
|
586
|
-
const stats = statSync(lockPath);
|
|
587
|
-
if (now() - stats.mtimeMs < staleMs) return false;
|
|
588
|
-
} catch (error) {
|
|
589
|
-
if (errorCode(error) === "ENOENT") return true;
|
|
590
|
-
throw error;
|
|
591
|
-
}
|
|
592
|
-
rmSync(lockPath, {
|
|
593
|
-
force: true,
|
|
594
|
-
recursive: true
|
|
595
|
-
});
|
|
596
|
-
return true;
|
|
597
|
-
}
|
|
598
|
-
function readCliCredentialsLockOwner(lockPath) {
|
|
599
|
-
let raw;
|
|
600
|
-
try {
|
|
601
|
-
raw = readFileSync(join(lockPath, CREDENTIALS_LOCK_OWNER_FILE), "utf8");
|
|
602
|
-
} catch (error) {
|
|
603
|
-
if (errorCode(error) === "ENOENT") return null;
|
|
604
|
-
throw error;
|
|
605
|
-
}
|
|
606
|
-
try {
|
|
607
|
-
const pid = JSON.parse(raw)?.pid;
|
|
608
|
-
return Number.isInteger(pid) && pid > 0 ? { pid } : null;
|
|
609
|
-
} catch {
|
|
610
|
-
return null;
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
function processIsRunning(pid) {
|
|
614
|
-
try {
|
|
615
|
-
process.kill(pid, 0);
|
|
616
|
-
return true;
|
|
617
|
-
} catch (error) {
|
|
618
|
-
if (errorCode(error) === "ESRCH") return false;
|
|
619
|
-
return true;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
function removeRecoverableCliCredentialsLock(params) {
|
|
623
|
-
const owner = readCliCredentialsLockOwner(params.lockPath);
|
|
624
|
-
if (owner && params.isRunning(owner.pid)) return false;
|
|
625
|
-
if (owner) {
|
|
626
|
-
rmSync(params.lockPath, {
|
|
627
|
-
force: true,
|
|
628
|
-
recursive: true
|
|
629
|
-
});
|
|
630
|
-
return true;
|
|
631
|
-
}
|
|
632
|
-
return removeStaleCliCredentialsLock(params.lockPath, params.staleMs, params.now);
|
|
633
|
-
}
|
|
634
|
-
function writeCliCredentialsLockOwner(lockPath) {
|
|
635
|
-
const ownerPath = join(lockPath, CREDENTIALS_LOCK_OWNER_FILE);
|
|
636
|
-
writeFileSync(ownerPath, `${JSON.stringify({
|
|
637
|
-
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
638
|
-
pid: process.pid
|
|
639
|
-
})}\n`, { mode: 384 });
|
|
640
|
-
chmodSync(ownerPath, 384);
|
|
641
|
-
}
|
|
642
|
-
function installCredentialsLockSignalCleanup(lockPath) {
|
|
643
|
-
let active = true;
|
|
644
|
-
const listeners = CREDENTIALS_LOCK_CLEANUP_SIGNALS.map((signal) => {
|
|
645
|
-
const listener = () => {
|
|
646
|
-
if (!active) return;
|
|
647
|
-
active = false;
|
|
648
|
-
rmSync(lockPath, {
|
|
649
|
-
force: true,
|
|
650
|
-
recursive: true
|
|
651
|
-
});
|
|
652
|
-
process.exit(signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 129);
|
|
653
|
-
};
|
|
654
|
-
process.once(signal, listener);
|
|
655
|
-
return {
|
|
656
|
-
listener,
|
|
657
|
-
signal
|
|
658
|
-
};
|
|
659
|
-
});
|
|
660
|
-
return () => {
|
|
661
|
-
if (!active) return;
|
|
662
|
-
active = false;
|
|
663
|
-
for (const { listener, signal } of listeners) process.removeListener(signal, listener);
|
|
664
|
-
};
|
|
665
|
-
}
|
|
666
|
-
function credentialsLockInProgressMessage(lockPath) {
|
|
667
|
-
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}.`;
|
|
668
|
-
}
|
|
669
|
-
function acquireCliCredentialsLock(configDir, options = {}) {
|
|
670
|
-
requireDefaultLoginProfile();
|
|
671
|
-
mkdirSync(configDir, {
|
|
672
|
-
mode: 448,
|
|
673
|
-
recursive: true
|
|
674
|
-
});
|
|
675
|
-
const lockPath = credentialsLockPath(configDir);
|
|
676
|
-
const installSignalHandlers = options.installSignalHandlers ?? true;
|
|
677
|
-
const isRunning = options.isProcessRunning ?? processIsRunning;
|
|
678
|
-
const now = options.now ?? Date.now;
|
|
679
|
-
const staleMs = options.staleMs ?? CREDENTIALS_LOCK_STALE_MS;
|
|
680
|
-
let acquired = false;
|
|
681
|
-
for (let attempt = 0; attempt < 2; attempt += 1) try {
|
|
682
|
-
mkdirSync(lockPath, { mode: 448 });
|
|
683
|
-
acquired = true;
|
|
684
|
-
break;
|
|
685
|
-
} catch (error) {
|
|
686
|
-
if (errorCode(error) !== "EEXIST") throw error;
|
|
687
|
-
if (removeRecoverableCliCredentialsLock({
|
|
688
|
-
isRunning,
|
|
689
|
-
lockPath,
|
|
690
|
-
now,
|
|
691
|
-
staleMs
|
|
692
|
-
})) continue;
|
|
693
|
-
throw new Error(credentialsLockInProgressMessage(lockPath));
|
|
694
|
-
}
|
|
695
|
-
if (!acquired) throw new Error(credentialsLockInProgressMessage(lockPath));
|
|
696
|
-
try {
|
|
697
|
-
writeCliCredentialsLockOwner(lockPath);
|
|
698
|
-
} catch (error) {
|
|
699
|
-
rmSync(lockPath, {
|
|
700
|
-
force: true,
|
|
701
|
-
recursive: true
|
|
702
|
-
});
|
|
703
|
-
throw error;
|
|
704
|
-
}
|
|
705
|
-
const removeSignalCleanup = installSignalHandlers ? installCredentialsLockSignalCleanup(lockPath) : () => void 0;
|
|
706
|
-
let released = false;
|
|
707
|
-
return () => {
|
|
708
|
-
if (released) return;
|
|
709
|
-
released = true;
|
|
710
|
-
removeSignalCleanup();
|
|
711
|
-
rmSync(lockPath, {
|
|
712
|
-
force: true,
|
|
713
|
-
recursive: true
|
|
714
|
-
});
|
|
715
|
-
};
|
|
716
|
-
}
|
|
717
|
-
/**
|
|
718
|
-
* Detect the PRIMITIVE_KEY vs PRIMITIVE_API_KEY rename trap.
|
|
719
|
-
*
|
|
720
|
-
* AGX feedback: users on older docs (or coming from other tools) set
|
|
721
|
-
* `PRIMITIVE_KEY` and then cannot figure out why the CLI reports no
|
|
722
|
-
* API key. The CLI reads `PRIMITIVE_API_KEY` only. Returns a stderr
|
|
723
|
-
* hint when `PRIMITIVE_KEY` is set but `PRIMITIVE_API_KEY` is not,
|
|
724
|
-
* otherwise null. Exported as a helper so both `doctor` and the
|
|
725
|
-
* general auth-resolution path surface the same guidance from the
|
|
726
|
-
* first command the user runs, instead of forcing them to discover
|
|
727
|
-
* the rename via `doctor` after the fact.
|
|
728
|
-
*/
|
|
729
|
-
function detectPrimitiveKeyEnvMisname(env = process.env) {
|
|
730
|
-
const primitiveKey = env.PRIMITIVE_KEY;
|
|
731
|
-
const primitiveApiKey = env.PRIMITIVE_API_KEY;
|
|
732
|
-
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.";
|
|
733
|
-
return null;
|
|
734
|
-
}
|
|
735
|
-
function resolveCliAuth(params) {
|
|
736
|
-
const apiKey = params.apiKey?.trim();
|
|
737
|
-
const apiBaseUrl = normalizeApiBaseUrl(params.apiBaseUrl);
|
|
738
|
-
const profileName = (params.env ?? process.env)["PRIMITIVE_AGENT_PROFILE"]?.trim() || void 0;
|
|
739
|
-
if (profileName !== void 0) {
|
|
740
|
-
const profile = loadConnectedAgentProfile(params.configDir, profileName);
|
|
741
|
-
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}.`);
|
|
742
|
-
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.`);
|
|
743
|
-
return {
|
|
744
|
-
apiKey: profile.api_key,
|
|
745
|
-
apiBaseUrl: profile.api_base_url,
|
|
746
|
-
credentials: null,
|
|
747
|
-
connectedAgent: connectedAgentIdentity(profileName, profile),
|
|
748
|
-
source: "connected-profile"
|
|
749
|
-
};
|
|
750
|
-
}
|
|
751
|
-
if (apiKey) return {
|
|
752
|
-
apiKey,
|
|
753
|
-
apiBaseUrl,
|
|
754
|
-
credentials: null,
|
|
755
|
-
source: "flag-or-env"
|
|
756
|
-
};
|
|
757
|
-
const credentials = loadCliCredentials(params.configDir);
|
|
758
|
-
if (credentials) return {
|
|
759
|
-
apiKey: credentials.access_token,
|
|
760
|
-
apiBaseUrl: credentials.api_base_url,
|
|
761
|
-
credentials,
|
|
762
|
-
source: "stored"
|
|
763
|
-
};
|
|
764
|
-
return {
|
|
765
|
-
apiKey: void 0,
|
|
766
|
-
apiBaseUrl,
|
|
767
|
-
credentials: null,
|
|
768
|
-
source: "none"
|
|
769
|
-
};
|
|
770
|
-
}
|
|
771
|
-
// src/oclif/cli-config.ts
|
|
772
|
-
const CONFIG_FILE = "config.json";
|
|
773
|
-
const CONFIG_VERSION = 1;
|
|
774
|
-
const DEFAULT_ENVIRONMENT = "default";
|
|
775
|
-
function cliConfigPath(configDir) {
|
|
776
|
-
return join(configDir, CONFIG_FILE);
|
|
777
|
-
}
|
|
778
|
-
function cliConfigError(message) {
|
|
779
|
-
return new Errors.CLIError(`${message} Run \`primitive config reset\` to clear the local CLI config.`, { exit: 1 });
|
|
780
|
-
}
|
|
781
|
-
function isRecord(value) {
|
|
782
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
783
|
-
}
|
|
784
|
-
function normalizeCliEnvironmentName(name) {
|
|
785
|
-
const trimmed = name?.trim();
|
|
786
|
-
if (!trimmed) throw new Errors.CLIError("Environment name must be a non-empty string.", { exit: 1 });
|
|
787
|
-
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 });
|
|
788
|
-
return trimmed;
|
|
789
|
-
}
|
|
790
|
-
function validateCliHeaderName(name) {
|
|
791
|
-
const trimmed = name.trim();
|
|
792
|
-
if (!trimmed) throw new Errors.CLIError("Header name must be a non-empty string.", { exit: 1 });
|
|
793
|
-
if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(trimmed)) throw new Errors.CLIError(`Invalid header name: ${name}`, { exit: 1 });
|
|
794
|
-
if (trimmed.toLowerCase() === "authorization") throw new Errors.CLIError("The Authorization header is managed by PRIMITIVE_API_KEY or saved OAuth CLI credentials.", { exit: 1 });
|
|
795
|
-
return trimmed;
|
|
796
|
-
}
|
|
797
|
-
function validateCliHeaderValue(value, name) {
|
|
798
|
-
if (value.length === 0) throw new Errors.CLIError(`Header ${name} value must not be empty.`, { exit: 1 });
|
|
799
|
-
if (/[\r\n\0]/.test(value)) throw new Errors.CLIError(`Header ${name} value must not contain CR, LF, or NUL characters.`, { exit: 1 });
|
|
800
|
-
return value;
|
|
801
|
-
}
|
|
802
|
-
function parseHeaderAssignment(assignment) {
|
|
803
|
-
const separator = assignment.indexOf("=");
|
|
804
|
-
if (separator <= 0) throw new Errors.CLIError("Header values must use name=value syntax, for example `x-custom=secret`.", { exit: 1 });
|
|
805
|
-
const name = validateCliHeaderName(assignment.slice(0, separator));
|
|
806
|
-
return [name, validateCliHeaderValue(assignment.slice(separator + 1), name)];
|
|
807
|
-
}
|
|
808
|
-
function parseHeaders(raw, context) {
|
|
809
|
-
if (raw === void 0) return {};
|
|
810
|
-
if (!isRecord(raw)) throw cliConfigError(`${context} headers must be a JSON object.`);
|
|
811
|
-
const headers = {};
|
|
812
|
-
for (const [rawName, rawValue] of Object.entries(raw)) {
|
|
813
|
-
const name = validateCliHeaderName(rawName);
|
|
814
|
-
if (typeof rawValue !== "string") throw cliConfigError(`${context} header ${name} must be a string.`);
|
|
815
|
-
headers[name] = validateCliHeaderValue(rawValue, name);
|
|
816
|
-
}
|
|
817
|
-
return headers;
|
|
818
|
-
}
|
|
819
|
-
function parseEnvironmentConfig(raw, context) {
|
|
820
|
-
if (!isRecord(raw)) throw cliConfigError(`${context} must be a JSON object.`);
|
|
821
|
-
const env = {};
|
|
822
|
-
const rawApiBaseUrl = raw.api_base_url ?? raw.api_base_url_2 ?? raw.api_base_url_1;
|
|
823
|
-
if (rawApiBaseUrl !== void 0) {
|
|
824
|
-
if (typeof rawApiBaseUrl !== "string") throw cliConfigError(`${context}.api_base_url must be a string.`);
|
|
825
|
-
env.api_base_url = normalizeApiBaseUrl(rawApiBaseUrl);
|
|
826
|
-
}
|
|
827
|
-
const headers = parseHeaders(raw.headers, context);
|
|
828
|
-
if (Object.keys(headers).length > 0) env.headers = headers;
|
|
829
|
-
return env;
|
|
830
|
-
}
|
|
831
|
-
function parseStoredCliConfig(raw) {
|
|
832
|
-
if (!isRecord(raw)) throw cliConfigError("Primitive CLI config must be a JSON object.");
|
|
833
|
-
if (raw.version !== CONFIG_VERSION) throw cliConfigError(`Primitive CLI config version must be ${CONFIG_VERSION}.`);
|
|
834
|
-
const currentRaw = raw.current_environment;
|
|
835
|
-
const current_environment = currentRaw === null || currentRaw === void 0 ? null : typeof currentRaw === "string" ? normalizeCliEnvironmentName(currentRaw) : (() => {
|
|
836
|
-
throw cliConfigError("Primitive CLI config current_environment must be a string or null.");
|
|
837
|
-
})();
|
|
838
|
-
if (!isRecord(raw.environments)) throw cliConfigError("Primitive CLI config environments must be an object.");
|
|
839
|
-
const environments = {};
|
|
840
|
-
for (const [rawName, rawEnv] of Object.entries(raw.environments)) {
|
|
841
|
-
const name = normalizeCliEnvironmentName(rawName);
|
|
842
|
-
environments[name] = parseEnvironmentConfig(rawEnv, `Primitive CLI config environment ${name}`);
|
|
843
|
-
}
|
|
844
|
-
if (current_environment && !environments[current_environment]) throw cliConfigError(`Primitive CLI config current environment ${current_environment} does not exist.`);
|
|
845
|
-
return {
|
|
846
|
-
version: CONFIG_VERSION,
|
|
847
|
-
current_environment,
|
|
848
|
-
environments
|
|
849
|
-
};
|
|
850
|
-
}
|
|
851
|
-
function emptyCliConfig() {
|
|
852
|
-
return {
|
|
853
|
-
version: CONFIG_VERSION,
|
|
854
|
-
current_environment: null,
|
|
855
|
-
environments: {}
|
|
856
|
-
};
|
|
857
|
-
}
|
|
858
|
-
function loadCliConfig(configDir) {
|
|
859
|
-
const path = cliConfigPath(configDir);
|
|
860
|
-
let contents;
|
|
861
|
-
try {
|
|
862
|
-
contents = readFileSync(path, "utf8");
|
|
863
|
-
} catch (error) {
|
|
864
|
-
if (error && typeof error === "object" && error.code === "ENOENT") return null;
|
|
865
|
-
throw cliConfigError(`Could not read Primitive CLI config: ${error instanceof Error ? error.message : String(error)}.`);
|
|
866
|
-
}
|
|
867
|
-
try {
|
|
868
|
-
return parseStoredCliConfig(JSON.parse(contents));
|
|
869
|
-
} catch (error) {
|
|
870
|
-
if (error instanceof SyntaxError) throw cliConfigError("Primitive CLI config is not valid JSON.");
|
|
871
|
-
throw error;
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
function saveCliConfig(configDir, config) {
|
|
875
|
-
mkdirSync(configDir, {
|
|
876
|
-
mode: 448,
|
|
877
|
-
recursive: true
|
|
878
|
-
});
|
|
879
|
-
const path = cliConfigPath(configDir);
|
|
880
|
-
const tempPath = join(configDir, `${CONFIG_FILE}.${process.pid}.${randomUUID()}.tmp`);
|
|
881
|
-
try {
|
|
882
|
-
writeFileSync(tempPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 384 });
|
|
883
|
-
renameSync(tempPath, path);
|
|
884
|
-
} catch (error) {
|
|
885
|
-
rmSync(tempPath, { force: true });
|
|
886
|
-
throw error;
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
function deleteCliConfig(configDir) {
|
|
890
|
-
rmSync(cliConfigPath(configDir), { force: true });
|
|
891
|
-
}
|
|
892
|
-
function resolveConfigEnvironment(config) {
|
|
893
|
-
if (!config) return null;
|
|
894
|
-
const current = config.current_environment;
|
|
895
|
-
if (current) {
|
|
896
|
-
const environment = config.environments[current];
|
|
897
|
-
return environment ? {
|
|
898
|
-
name: current,
|
|
899
|
-
config: environment
|
|
900
|
-
} : null;
|
|
901
|
-
}
|
|
902
|
-
const defaultEnvironment = config.environments[DEFAULT_ENVIRONMENT];
|
|
903
|
-
return defaultEnvironment ? {
|
|
904
|
-
name: DEFAULT_ENVIRONMENT,
|
|
905
|
-
config: defaultEnvironment
|
|
906
|
-
} : null;
|
|
907
|
-
}
|
|
908
|
-
function upsertCliEnvironment(params) {
|
|
909
|
-
const name = normalizeCliEnvironmentName(params.environmentName ?? resolveConfigEnvironment(params.config)?.name ?? "default");
|
|
910
|
-
const existing = params.config.environments[name] ?? {};
|
|
911
|
-
const nextHeaders = { ...existing.headers ?? {} };
|
|
912
|
-
for (const assignment of params.headers ?? []) {
|
|
913
|
-
const [headerName, value] = parseHeaderAssignment(assignment);
|
|
914
|
-
nextHeaders[headerName] = value;
|
|
915
|
-
}
|
|
916
|
-
for (const rawName of params.unsetHeaders ?? []) delete nextHeaders[validateCliHeaderName(rawName)];
|
|
917
|
-
const nextEnvironment = {
|
|
918
|
-
...existing,
|
|
919
|
-
...params.apiBaseUrl !== void 0 ? { api_base_url: normalizeApiBaseUrl(params.apiBaseUrl) } : {},
|
|
920
|
-
...Object.keys(nextHeaders).length > 0 ? { headers: nextHeaders } : {}
|
|
921
|
-
};
|
|
922
|
-
if (Object.keys(nextHeaders).length === 0) delete nextEnvironment.headers;
|
|
923
|
-
return {
|
|
924
|
-
...params.config,
|
|
925
|
-
current_environment: params.use === false ? params.config.current_environment : name,
|
|
926
|
-
environments: {
|
|
927
|
-
...params.config.environments,
|
|
928
|
-
[name]: nextEnvironment
|
|
929
|
-
}
|
|
930
|
-
};
|
|
931
|
-
}
|
|
932
|
-
function removeCliEnvironment(config, environmentName) {
|
|
933
|
-
const name = normalizeCliEnvironmentName(environmentName);
|
|
934
|
-
const environments = { ...config.environments };
|
|
935
|
-
delete environments[name];
|
|
936
|
-
return {
|
|
937
|
-
...config,
|
|
938
|
-
current_environment: config.current_environment === name ? null : config.current_environment,
|
|
939
|
-
environments
|
|
940
|
-
};
|
|
941
|
-
}
|
|
942
|
-
function redactCliEnvironment(environment) {
|
|
943
|
-
const headers = environment.headers && Object.keys(environment.headers).length > 0 ? Object.fromEntries(Object.keys(environment.headers).map((name) => [name, "***"])) : void 0;
|
|
944
|
-
return {
|
|
945
|
-
...environment,
|
|
946
|
-
...headers ? { headers } : {}
|
|
947
|
-
};
|
|
948
|
-
}
|
|
949
|
-
export { AGENT_ADDRESS_ENV as A, parseOwnerMemberAddress as B, saveCliCredentials as C, loadActiveChatState as D, deleteChatState as E, agentProfilesDirectory as F, requireDefaultLoginProfile as H, connectedAgentIdentity as I, connectedApiBaseUrl as L, AgentConnectionSetupError as M, agentProfileDirectory as N, loadChatConversationByLocalId as O, agentProfileName as P, loadConnectedAgentProfile as R, resolveCliAuth as S, chatStatePath as T, saveConnectedAgentProfile as U, profileAlreadyConnectedMessage as V, PrimitiveApiClient as W, deleteCliCredentials as _, normalizeCliEnvironmentName as a, loadCliCredentials as b, resolveConfigEnvironment as c, validateCliHeaderName as d, validateCliHeaderValue as f, credentialsPath as g, credentialsLockPath as h, loadCliConfig as i, AGENT_PROFILE_ENV as j, saveActiveChatState as k, saveCliConfig as l, cliAccessTokenExpiresAt as m, deleteCliConfig as n, redactCliEnvironment as o, acquireCliCredentialsLock as p, emptyCliConfig as r, removeCliEnvironment as s, DEFAULT_ENVIRONMENT as t, upsertCliEnvironment as u, deleteCliCredentialsLock as v, saveSignupCredentials as w, normalizeApiBaseUrl as x, detectPrimitiveKeyEnvMisname as y, parseConnectedAgentProfile as z };
|