primcli 1.41.0 → 1.42.0

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.
@@ -1,1222 +1,12 @@
1
1
  import { h as sendPreparedSignal, p as prepareSignalEmail } from "./repeats-CoK0tpCK-Bx7nmyRi.js";
2
- import { d as requireDefaultLoginProfile } from "./connected-agent-profile-8tpOMdq3.js";
3
- import { C as getEmail, K as listSentEmails, V as listEndpoints, a as createEndpoint, ct as searchEmails, dt as sendEmail, st as sdk_gen_exports } from "./sdk.gen-I4mhUuUW.js";
4
- import { C as resolveCliAuth, S as normalizeApiBaseUrl, T as saveSignupCredentials, _ as deleteCliCredentials, c as resolveConfigEnvironment, d as validateCliHeaderName, f as validateCliHeaderValue, i as loadCliConfig, j as PrimitiveApiClient, m as cliAccessTokenExpiresAt, p as acquireCliCredentialsLock, w as saveCliCredentials, x as loadCliCredentials, y as detectPrimitiveKeyEnvMisname } from "./cli-config-UOlrfcPz.js";
5
- import { _ as acquireListenLock, a as mailLockBusy, b as listenProcessIdentity, c as mailTime, d as readMailJson, f as removeMailFile, h as writeMailJson, i as mailId, l as privateMailDirectory, m as withMailLock, n as invalidSharedMail, o as mailObject, p as syncMailDirectory, r as mailAddress, s as mailString, t as SharedMailStateError, v as compareListenProcessIdentity, y as listenIdentity } from "./shared-mail-files-CZqI1kj6.js";
6
- import { F as readBeforeDeadline, I as scopedChatSenderTrust, N as isPlainChatReply, S as recordSentSignal } from "./auto-signals-C8nMME8J.js";
7
- import { Command, Errors, Flags } from "@oclif/core";
8
- import { opendirSync, readFileSync, watch, writeFileSync } from "node:fs";
2
+ import { Bt as getEmail, Dn as sendEmail, I as extractErrorPayload, St as createEndpoint, g as classifySendError, k as successfulSendOutcome, ln as listSentEmails, r as isWakeInteractionLabel, s as wakeInteractionLabel } from "./interaction-actions-D5o_frTT.js";
3
+ import { _ as acquireListenLock, a as mailLockBusy, b as listenProcessIdentity, c as mailTime, d as readMailJson, f as removeMailFile, h as writeMailJson, i as mailId, l as privateMailDirectory, m as withMailLock, n as invalidSharedMail, o as mailObject, p as syncMailDirectory, r as mailAddress, s as mailString, t as SharedMailStateError, v as compareListenProcessIdentity, y as listenIdentity } from "./shared-mail-files-SPPcis9g.js";
4
+ import { F as readBeforeDeadline, I as scopedChatSenderTrust, N as isPlainChatReply, S as recordSentSignal } from "./auto-signals-D3NqwgYA.js";
5
+ import { Errors } from "@oclif/core";
6
+ import { opendirSync, watch } from "node:fs";
9
7
  import { createHash, randomUUID, scryptSync } from "node:crypto";
10
8
  import { dirname, join } from "node:path";
11
9
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
12
- //#region src/oclif/api-client.ts
13
- const API_HEADERS_ENV = "PRIMITIVE_API_HEADERS";
14
- const OAUTH_REFRESH_SKEW_MS = 60 * 1e3;
15
- const SAVED_CLI_OAUTH_SESSION_EXPIRED_MESSAGE = "Saved Primitive CLI OAuth session expired or was revoked. Run `primitive signin` to authenticate again.";
16
- function mergeHeaders$1(...headers) {
17
- const merged = {};
18
- for (const headerSet of headers) {
19
- if (!headerSet) continue;
20
- for (const [name, value] of Object.entries(headerSet)) merged[name] = value;
21
- }
22
- return Object.keys(merged).length > 0 ? merged : void 0;
23
- }
24
- function parseHeadersJson(raw) {
25
- let parsed;
26
- try {
27
- parsed = JSON.parse(raw);
28
- } catch (error) {
29
- const detail = error instanceof Error ? error.message : String(error);
30
- throw new Errors.CLIError(`${API_HEADERS_ENV} must be valid JSON object syntax: ${detail}`, { exit: 1 });
31
- }
32
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Errors.CLIError(`${API_HEADERS_ENV} must be a JSON object.`, { exit: 1 });
33
- const headers = {};
34
- for (const [rawName, rawValue] of Object.entries(parsed)) {
35
- const name = validateCliHeaderName(rawName);
36
- if (typeof rawValue !== "string") throw new Errors.CLIError(`${API_HEADERS_ENV}.${name} must be a string.`, { exit: 1 });
37
- headers[name] = validateCliHeaderValue(rawValue, name);
38
- }
39
- return headers;
40
- }
41
- function cliApiHeadersFromEnv(env = process.env) {
42
- const rawGenericHeaders = env[API_HEADERS_ENV]?.trim();
43
- return rawGenericHeaders ? parseHeadersJson(rawGenericHeaders) : void 0;
44
- }
45
- function resolveCliApiRequestConfig(params) {
46
- if ((params.env ?? process.env)["PRIMITIVE_AGENT_PROFILE"]?.trim()) {
47
- const auth = resolveCliAuth(params);
48
- return {
49
- apiBaseUrl: auth.apiBaseUrl,
50
- resolvedApiBaseUrl: auth.apiBaseUrl,
51
- baseUrlOverridden: params.apiBaseUrl !== void 0,
52
- environmentName: null
53
- };
54
- }
55
- const currentEnvironment = resolveConfigEnvironment(loadCliConfig(params.configDir));
56
- const configuredApiBaseUrl = currentEnvironment?.config.api_base_url;
57
- if (currentEnvironment !== null && currentEnvironment.name !== "default" && params.apiBaseUrl === void 0 && configuredApiBaseUrl === void 0) throw new Errors.CLIError(`The active Primitive CLI environment \`${currentEnvironment.name}\` does not specify an api_base_url. Set one with \`primitive config set --environment ${currentEnvironment.name} --api-base-url https://...\`, or switch to a different environment with \`primitive config use <name>\`. Refusing to fall back to the production default for a non-default environment.`, { exit: 1 });
58
- const apiBaseUrl = params.apiBaseUrl !== void 0 ? normalizeApiBaseUrl(params.apiBaseUrl) : configuredApiBaseUrl;
59
- return {
60
- apiBaseUrl,
61
- baseUrlOverridden: apiBaseUrl !== void 0,
62
- environmentName: currentEnvironment?.name ?? null,
63
- headers: mergeHeaders$1(currentEnvironment?.config.headers, cliApiHeadersFromEnv(params.env)),
64
- resolvedApiBaseUrl: normalizeApiBaseUrl(apiBaseUrl)
65
- };
66
- }
67
- function createCliApiClient(params) {
68
- const requestConfig = resolveCliApiRequestConfig(params);
69
- return {
70
- apiClient: new PrimitiveApiClient({
71
- apiKey: params.apiKey,
72
- apiBaseUrl: requestConfig.resolvedApiBaseUrl,
73
- headers: requestConfig.headers
74
- }),
75
- requestConfig
76
- };
77
- }
78
- function oauthTokenEndpoint(apiBaseUrl) {
79
- const url = new URL(apiBaseUrl);
80
- url.pathname = "/oauth/token";
81
- url.search = "";
82
- url.hash = "";
83
- return url.toString();
84
- }
85
- function shouldRefresh(credentials, now) {
86
- const expiresAt = Date.parse(credentials.expires_at);
87
- if (!Number.isFinite(expiresAt)) return true;
88
- return expiresAt <= now() + OAUTH_REFRESH_SKEW_MS;
89
- }
90
- function isOAuthRefreshSuccess(value) {
91
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
92
- const row = value;
93
- return typeof row.access_token === "string" && typeof row.refresh_token === "string" && row.token_type === "Bearer" && typeof row.expires_in === "number" && Number.isFinite(row.expires_in) && row.expires_in > 0;
94
- }
95
- function oauthErrorCode(value) {
96
- if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
97
- const raw = value.error;
98
- return typeof raw === "string" ? raw : null;
99
- }
100
- function oauthErrorDescription(value) {
101
- if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
102
- const raw = value.error_description;
103
- return typeof raw === "string" && raw.trim() ? raw : null;
104
- }
105
- async function refreshStoredCliCredentials(params) {
106
- const now = params.now ?? Date.now;
107
- if (!shouldRefresh(params.credentials, now)) return params.credentials;
108
- let releaseLock;
109
- try {
110
- if (!params.credentialsLockHeld) try {
111
- releaseLock = acquireCliCredentialsLock(params.configDir);
112
- } catch (error) {
113
- const detail = error instanceof Error ? error.message : String(error);
114
- throw new Errors.CLIError(detail, { exit: 1 });
115
- }
116
- const current = loadCliCredentials(params.configDir);
117
- if (!current) throw new Errors.CLIError("Saved Primitive CLI OAuth session is no longer available. Run `primitive signin` to authenticate again.", { exit: 1 });
118
- if (!shouldRefresh(current, now)) return current;
119
- const fetchImpl = params.fetch ?? fetch;
120
- const body = new URLSearchParams({
121
- client_id: current.oauth_client_id,
122
- grant_type: "refresh_token",
123
- refresh_token: current.refresh_token
124
- });
125
- let response;
126
- try {
127
- response = await fetchImpl(oauthTokenEndpoint(params.apiBaseUrl), {
128
- body,
129
- headers: {
130
- ...params.headers ?? {},
131
- "content-type": "application/x-www-form-urlencoded"
132
- },
133
- method: "POST"
134
- });
135
- } catch (error) {
136
- const detail = error instanceof Error ? error.message : String(error);
137
- throw new Errors.CLIError(`Could not refresh saved Primitive CLI OAuth credentials: ${detail}`, { exit: 1 });
138
- }
139
- const payload = await response.json().catch(() => null);
140
- if (!response.ok) {
141
- const code = oauthErrorCode(payload);
142
- const description = oauthErrorDescription(payload);
143
- if (code === "invalid_grant") {
144
- deleteCliCredentials(params.configDir);
145
- throw new Errors.CLIError(SAVED_CLI_OAUTH_SESSION_EXPIRED_MESSAGE, { exit: 1 });
146
- }
147
- throw new Errors.CLIError(`Could not refresh saved Primitive CLI OAuth credentials${description ? `: ${description}` : "."}`, { exit: 1 });
148
- }
149
- if (!isOAuthRefreshSuccess(payload)) throw new Errors.CLIError("Primitive OAuth token endpoint returned an unexpected refresh response.", { exit: 1 });
150
- const next = {
151
- ...current,
152
- access_token: payload.access_token,
153
- expires_at: cliAccessTokenExpiresAt(payload.expires_in, now),
154
- refresh_token: payload.refresh_token,
155
- token_type: payload.token_type
156
- };
157
- saveCliCredentials(params.configDir, next);
158
- return next;
159
- } finally {
160
- releaseLock?.();
161
- }
162
- }
163
- async function createAuthenticatedCliApiClient(params) {
164
- const requestConfig = resolveCliApiRequestConfig(params);
165
- let auth = resolveCliAuth({
166
- apiKey: params.apiKey,
167
- apiBaseUrl: requestConfig.apiBaseUrl,
168
- configDir: params.configDir,
169
- env: params.env
170
- });
171
- if (auth.apiKey === void 0) {
172
- const hint = detectPrimitiveKeyEnvMisname(params.env ?? process.env);
173
- if (hint) process.stderr.write(`${hint}\n`);
174
- }
175
- if (auth.source === "stored" && auth.credentials) {
176
- const refreshed = await refreshStoredCliCredentials({
177
- apiBaseUrl: auth.apiBaseUrl,
178
- configDir: params.configDir,
179
- credentials: auth.credentials,
180
- credentialsLockHeld: params.credentialsLockHeld,
181
- fetch: params.fetch,
182
- headers: requestConfig.headers,
183
- now: params.now
184
- });
185
- auth = {
186
- ...auth,
187
- apiKey: refreshed.access_token,
188
- credentials: refreshed
189
- };
190
- }
191
- return {
192
- apiClient: new PrimitiveApiClient({
193
- apiKey: auth.apiKey,
194
- apiBaseUrl: auth.apiBaseUrl,
195
- headers: auth.connectedAgent ? void 0 : requestConfig.headers
196
- }),
197
- auth,
198
- baseUrlOverridden: requestConfig.baseUrlOverridden,
199
- requestConfig
200
- };
201
- }
202
- //#endregion
203
- //#region src/oclif/attachment-wait.ts
204
- /** Generated download commands that wait for attachment content by default. */
205
- const ATTACHMENT_WAIT_OPERATIONS = new Set([
206
- "downloadAttachments",
207
- "downloadEmailAttachmentPart",
208
- "downloadSentAttachmentPart"
209
- ]);
210
- /** Longest a download command waits for attachment content, in total. */
211
- const ATTACHMENT_WAIT_MAX_MS = 6e4;
212
- const INITIAL_DELAY_MS = 1e3;
213
- const MAX_DELAY_MS = 8e3;
214
- const ATTACHMENT_WAIT_FLAG_DESCRIPTION = `Wait and retry while the attachment content is not ready yet (attachment_not_ready), for up to ${ATTACHMENT_WAIT_MAX_MS / 1e3}s. Pass --no-wait to return the error immediately.`;
215
- /** Seconds from a Retry-After header, or undefined when absent or not a number of seconds. */
216
- function retryAfterMs(response) {
217
- const header = response?.headers?.get("retry-after");
218
- if (!header || !/^\d+$/.test(header.trim())) return void 0;
219
- return Number(header.trim()) * 1e3;
220
- }
221
- /**
222
- * Delay before the next attempt: the server's Retry-After when it gives one,
223
- * otherwise exponential backoff from 1s, capped at 8s either way, and never
224
- * past the remaining budget.
225
- */
226
- function nextAttachmentWaitDelay(attempt, remainingMs, serverHintMs) {
227
- const backoff = INITIAL_DELAY_MS * 2 ** Math.min(attempt, 10);
228
- return Math.max(0, Math.min(Math.min(serverHintMs ?? backoff, MAX_DELAY_MS), remainingMs));
229
- }
230
- const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
231
- /**
232
- * Run `call` and, while it fails with attachment_not_ready, wait and run it
233
- * again until it succeeds, fails differently, or the budget is spent. The last
234
- * result is returned either way, so the caller reports it exactly as before.
235
- */
236
- async function withAttachmentWait(call, options) {
237
- const now = options.now ?? Date.now;
238
- const sleep = options.sleep ?? defaultSleep;
239
- const maxWaitMs = options.maxWaitMs ?? 6e4;
240
- const started = now();
241
- let result = await call();
242
- for (let attempt = 0; options.wait; attempt++) {
243
- if (!result.error || options.errorCode(result.error) !== "attachment_not_ready") break;
244
- const remaining = maxWaitMs - (now() - started);
245
- if (remaining <= 0) break;
246
- if (attempt === 0) options.onFirstWait?.();
247
- await sleep(nextAttachmentWaitDelay(attempt, remaining, retryAfterMs(result.response)));
248
- result = await call();
249
- }
250
- return result;
251
- }
252
- //#endregion
253
- //#region src/oclif/automated-filter.ts
254
- /**
255
- * The server-side `automated` verdict on inbound email: `automated`
256
- * (boolean) and `automated_reasons` (why, in rule order), decided by
257
- * the API when the email arrives, and the `automated=true|false` filter
258
- * on GET /emails and GET /emails/search.
259
- *
260
- * A server that predates it either rejects the `automated` filter (GET
261
- * /emails validates its query strictly) or ignores it and returns rows
262
- * without the fields (GET /emails/search). Both must fail loudly: a CLI
263
- * that read a missing verdict as "not automated" would hand an agent
264
- * every bounce and newsletter as mail from a person, and one that fell
265
- * back to deciding it locally would re-read all unanswered automated
266
- * mail on every call.
267
- */
268
- const AUTOMATED_FILTER_UNSUPPORTED_CODE = "automated_filter_unsupported";
269
- const AUTOMATED_VALUES = ["true", "false"];
270
- const AUTOMATED_FLAG_DESCRIPTION = "Only emails whose server-decided `automated` verdict is this value: `false` = sent by a person, `true` = bounces and delivery reports, auto-replies, list and newsletter mail, and mail from the address it was sent to. Fails if the server does not support the automated filter yet.";
271
- var AutomatedFilterUnsupportedError = class extends Error {
272
- code = AUTOMATED_FILTER_UNSUPPORTED_CODE;
273
- constructor(detail) {
274
- super(`The server does not support the \`automated\` filter yet: ${detail} Nothing was treated as sent by a person. Upgrade to a server that returns \`automated\` and \`automated_reasons\`, or pass --include-automated.`);
275
- this.name = "AutomatedFilterUnsupportedError";
276
- }
277
- };
278
- /** Like AutomatedFilterUnsupportedError, for a probe that failed. */
279
- var AutomatedFilterUnverifiedError = class extends AutomatedFilterUnsupportedError {
280
- constructor(detail) {
281
- super(detail);
282
- this.message = `Could not verify that the server supports the \`automated\` filter: ${detail} Nothing was treated as matching. Retry the command.`;
283
- this.name = "AutomatedFilterUnverifiedError";
284
- this.code = "automated_filter_unverified";
285
- }
286
- };
287
- function hasAutomatedVerdict(row) {
288
- if (row === null || typeof row !== "object") return false;
289
- const candidate = row;
290
- return typeof candidate.automated === "boolean" && Array.isArray(candidate.automated_reasons) && candidate.automated_reasons.every((reason) => typeof reason === "string");
291
- }
292
- /**
293
- * Throw unless every row carries the verdict, and, for each `expected`
294
- * value given, unless every row has that value: a server that accepted
295
- * the filter but did not apply it must not pass for one that did.
296
- */
297
- function assertAutomatedVerdict(rows, surface, expected) {
298
- const missing = rows.filter((row) => !hasAutomatedVerdict(row)).length;
299
- if (missing > 0) throw new AutomatedFilterUnsupportedError(`${surface} returned ${missing} of ${rows.length} email${rows.length === 1 ? "" : "s"} without the \`automated\` and \`automated_reasons\` fields.`);
300
- const verdicts = expected === void 0 ? [] : typeof expected === "boolean" ? [expected] : expected;
301
- for (const verdict of verdicts) {
302
- const wrong = rows.filter((row) => row.automated !== verdict).length;
303
- if (wrong > 0) throw new AutomatedFilterUnsupportedError(`${surface} ignored \`automated=${verdict}\` and returned ${wrong} email${wrong === 1 ? "" : "s"} with \`automated=${!verdict}\`.`);
304
- }
305
- }
306
- /**
307
- * The verdicts the `automated:` terms in a search DSL query require.
308
- * The DSL joins its terms with AND, so every `automated:true|false`
309
- * term must hold for every returned row. Quoted text is skipped, so a
310
- * phrase that merely contains "automated:false" does not count.
311
- */
312
- function automatedVerdictsFromQuery(q) {
313
- if (typeof q !== "string") return [];
314
- const verdicts = [];
315
- const tokens = q.match(/(?:[^\s"]|"(?:[^"\\]|\\.)*"?)+/g) ?? [];
316
- for (const token of tokens) {
317
- const match = /^automated:"?(true|false)"?$/i.exec(token);
318
- if (match) verdicts.push(match[1].toLowerCase() === "true");
319
- }
320
- return verdicts;
321
- }
322
- /**
323
- * Every verdict a list or search call asked for: the `automated`
324
- * parameter plus any `automated:` terms in the search query.
325
- */
326
- function expectedAutomatedVerdicts(automated, q) {
327
- return [...automated === void 0 ? [] : [automated], ...automatedVerdictsFromQuery(q)];
328
- }
329
- /** True when a search DSL query uses the `automated:` term. */
330
- function queryUsesAutomated(q) {
331
- return typeof q === "string" && /(^|[\s(])-?automated:/i.test(q);
332
- }
333
- function errorBody$1(payload) {
334
- if (payload === null || typeof payload !== "object") return {};
335
- const inner = payload.error;
336
- return inner !== null && typeof inner === "object" ? inner : payload;
337
- }
338
- /**
339
- * True when an API error is an older server rejecting the `automated`
340
- * query parameter or the `automated:` search term as unknown.
341
- */
342
- function isAutomatedRejectedError(payload) {
343
- const body = errorBody$1(payload);
344
- if (body.code !== "validation_error") return false;
345
- const message = typeof body.message === "string" ? body.message : JSON.stringify(payload);
346
- return /automated/i.test(message) && /unrecogni[sz]ed|unknown/i.test(message);
347
- }
348
- function automatedRejectedError(surface) {
349
- return new AutomatedFilterUnsupportedError(`${surface} rejected the \`automated\` filter as unknown.`);
350
- }
351
- const AUTOMATED_SURFACES = {
352
- listEmails: "GET /emails",
353
- searchEmails: "GET /emails/search"
354
- };
355
- /**
356
- * For the generated `emails list` / `emails search` commands: the
357
- * surface name when this call filtered on `automated` (the parameter or
358
- * an `automated:` search term), else null.
359
- */
360
- function automatedSurfaceForOperation(sdkName, query) {
361
- const surface = AUTOMATED_SURFACES[sdkName];
362
- if (!surface || !query) return null;
363
- const q = typeof query.q === "string" ? query.q : void 0;
364
- return query.automated !== void 0 || queryUsesAutomated(q) ? surface : null;
365
- }
366
- const searchSupportProbes$1 = /* @__PURE__ */ new WeakMap();
367
- /**
368
- * GET /emails/search ignores unknown parameters, so an empty page for
369
- * `automated=...` does not show that the server applied the filter.
370
- * Read one unfiltered row: if it lacks the verdict the server does not
371
- * support it. No rows at all means the mailbox is empty, so the empty
372
- * answer stands. One probe per API client per process.
373
- */
374
- function ensureSearchReportsAutomated(apiClient) {
375
- const key = apiClient;
376
- let probe = searchSupportProbes$1.get(key);
377
- if (!probe) {
378
- probe = (async () => {
379
- const result = await searchEmails({
380
- client: apiClient.client,
381
- query: {
382
- limit: 1,
383
- include_facets: "false",
384
- snippet: "false"
385
- },
386
- responseStyle: "fields"
387
- });
388
- if (result.error) throw new AutomatedFilterUnverifiedError("the empty result could not be checked: reading one unfiltered row from GET /emails/search failed.");
389
- const rows = result.data?.data;
390
- assertAutomatedVerdict(rows ?? [], "GET /emails/search");
391
- })();
392
- searchSupportProbes$1.set(key, probe);
393
- probe.catch(() => {
394
- if (searchSupportProbes$1.get(key) === probe) searchSupportProbes$1.delete(key);
395
- });
396
- }
397
- return probe;
398
- }
399
- //#endregion
400
- //#region src/oclif/endpoints-test-redirect.ts
401
- async function detectFunctionEndpoint(endpointId, listEndpoints) {
402
- let response;
403
- try {
404
- response = await listEndpoints();
405
- } catch {
406
- return null;
407
- }
408
- if (response.error) return null;
409
- const rows = response.data?.data;
410
- if (!Array.isArray(rows)) return null;
411
- for (const row of rows) {
412
- if (!row || typeof row !== "object") continue;
413
- if (row.id !== endpointId) continue;
414
- if (row.kind !== "function") return null;
415
- const functionId = row.function_id;
416
- if (typeof functionId !== "string" || functionId.length === 0) return null;
417
- return {
418
- endpointId,
419
- functionId
420
- };
421
- }
422
- return null;
423
- }
424
- function formatFunctionEndpointRedirect(match) {
425
- return [
426
- "This is a function endpoint. Function endpoints are tested differently. Run:",
427
- "",
428
- ` primitive functions test --id ${match.functionId}`,
429
- "",
430
- `(pass the function id, not the endpoint id. endpoint_id=${match.endpointId} function_id=${match.functionId})`
431
- ].join("\n");
432
- }
433
- async function maybeWriteFunctionEndpointRedirect(inputs) {
434
- if (inputs.sdkName !== "testEndpoint") return null;
435
- if (inputs.errorCode !== "not_found") return null;
436
- if (!inputs.endpointId) return null;
437
- const match = await detectFunctionEndpoint(inputs.endpointId, inputs.listEndpoints);
438
- if (!match) return null;
439
- inputs.writeStderr(`${formatFunctionEndpointRedirect(match)}\n`);
440
- return match;
441
- }
442
- //#endregion
443
- //#region src/oclif/idempotent-replay-banner.ts
444
- /**
445
- * If `data` carries `idempotent_replay: true`, write a stderr notice
446
- * that the message already went out and nothing new was sent.
447
- * Otherwise no-op.
448
- *
449
- * The notice deliberately gives no advice on how to force a fresh
450
- * copy. Whoever sees a replay has already sent this message; telling
451
- * them to vary the content is an instruction to double-send.
452
- */
453
- function writeIdempotentReplayBannerIfReplay(data, options) {
454
- if (!isReplay(data)) return;
455
- options.write(`${formatAlreadySentNotice(data)}\n`);
456
- }
457
- function isReplay(data) {
458
- if (data === null || typeof data !== "object") return false;
459
- return data.idempotent_replay === true;
460
- }
461
- function formatAlreadySentNotice(sent) {
462
- const details = [];
463
- if (typeof sent.id === "string" && sent.id) details.push(`sent id ${sent.id}`);
464
- const status = typeof sent.status === "string" && sent.status ? sent.status : null;
465
- const deliveryStatus = typeof sent.delivery_status === "string" && sent.delivery_status ? sent.delivery_status : null;
466
- if (status) details.push(`status ${status}`);
467
- if (deliveryStatus && deliveryStatus !== status) details.push(`delivery status ${deliveryStatus}`);
468
- return `Already sent: this exact message went out earlier${details.length > 0 ? ` (${details.join(", ")})` : ""}. Nothing new was sent.`;
469
- }
470
- //#endregion
471
- //#region src/oclif/reply-state.ts
472
- const AWAITING_VALUES = ["you", "them"];
473
- const AWAITING_FLAG_DESCRIPTION = "Only emails whose reply state is this value: `you` = waiting on your reply (the thread's latest message is inbound), `them` = you replied last. Queued and scheduled replies count as replied. Delivered mail only: rejected mail is never returned. Fails if the server does not report reply state yet.";
474
- const REPLY_STATE_UNSUPPORTED_CODE = "reply_state_unsupported";
475
- /** True when a search DSL query uses the `awaiting:` term. */
476
- function queryUsesAwaiting(q) {
477
- return typeof q === "string" && /(^|[\s(])-?awaiting:/i.test(q);
478
- }
479
- var ReplyStateUnsupportedError = class extends Error {
480
- code = REPLY_STATE_UNSUPPORTED_CODE;
481
- constructor(detail) {
482
- super(`The server does not support reply state yet: ${detail} Nothing was treated as awaiting your reply. Upgrade to a server that returns \`awaiting\` and \`reply_count\`, or run without reply-state options.`);
483
- this.name = "ReplyStateUnsupportedError";
484
- }
485
- };
486
- /**
487
- * The server's reply-state support could not be established (a probe
488
- * failed). Reported like ReplyStateUnsupportedError so callers never
489
- * read an unverified empty answer as "nothing matched".
490
- */
491
- var ReplyStateUnverifiedError = class extends ReplyStateUnsupportedError {
492
- constructor(detail) {
493
- super(detail);
494
- this.message = `Could not verify that the server supports reply state: ${detail} Nothing was treated as matching. Retry the command.`;
495
- this.name = "ReplyStateUnverifiedError";
496
- this.code = "reply_state_unverified";
497
- }
498
- };
499
- function hasReplyState(row) {
500
- if (row === null || typeof row !== "object") return false;
501
- const candidate = row;
502
- return (candidate.awaiting === "you" || candidate.awaiting === "them") && typeof candidate.reply_count === "number" && (candidate.last_replied_at === null || typeof candidate.last_replied_at === "string");
503
- }
504
- /**
505
- * Throw unless every row carries reply state. An empty page proves
506
- * nothing either way; callers that asked for reply state follow an
507
- * empty search page with ensureSearchReportsReplyState(). `surface` names the
508
- * response for the error, e.g. "GET /emails".
509
- */
510
- function assertReplyState(rows, surface) {
511
- const missing = rows.filter((row) => !hasReplyState(row)).length;
512
- if (missing > 0) throw new ReplyStateUnsupportedError(`${surface} returned ${missing} of ${rows.length} email${rows.length === 1 ? "" : "s"} without the \`awaiting\` and \`reply_count\` fields.`);
513
- }
514
- const AWAITING_REJECTED_UNSUPPORTED_CODE = "awaiting_rejected_unsupported";
515
- /**
516
- * The `awaiting` filter matches delivered mail only: a rejected email
517
- * (for example refused over the storage limit) was never delivered, so it
518
- * awaits no one. A server that returns one through the filter predates
519
- * that, and an agent would be handed mail nobody can answer.
520
- */
521
- var AwaitingIncludesRejectedError = class extends ReplyStateUnsupportedError {
522
- constructor(detail) {
523
- super(detail);
524
- this.message = `The server's \`awaiting\` filter does not exclude undelivered mail yet: ${detail} Upgrade to a server whose \`awaiting\` filter matches delivered mail only.`;
525
- this.name = "AwaitingIncludesRejectedError";
526
- this.code = AWAITING_REJECTED_UNSUPPORTED_CODE;
527
- }
528
- };
529
- /**
530
- * For rows returned BY an `awaiting` filter (not the unfiltered probe):
531
- * every row carries reply state, and none has status `rejected`.
532
- */
533
- function assertAwaitingFilterRows(rows, surface) {
534
- assertReplyState(rows, surface);
535
- const rejected = rows.filter((row) => row !== null && typeof row === "object" && row.status === "rejected").length;
536
- if (rejected > 0) throw new AwaitingIncludesRejectedError(`${surface} returned ${rejected} email${rejected === 1 ? "" : "s"} with status \`rejected\`.`);
537
- }
538
- function errorBody(payload) {
539
- if (payload === null || typeof payload !== "object") return {};
540
- const inner = payload.error;
541
- return inner !== null && typeof inner === "object" ? inner : payload;
542
- }
543
- /**
544
- * True when an API error is an older server rejecting the `awaiting`
545
- * query parameter or the `awaiting:` search term as unknown. A current
546
- * server accepts both, and the CLI only ever sends valid values.
547
- */
548
- function isAwaitingRejectedError(payload) {
549
- const body = errorBody(payload);
550
- if (body.code !== "validation_error") return false;
551
- const message = typeof body.message === "string" ? body.message : JSON.stringify(payload);
552
- return /awaiting/i.test(message) && /unrecogni[sz]ed|unknown/i.test(message);
553
- }
554
- function awaitingRejectedError(surface) {
555
- return new ReplyStateUnsupportedError(`${surface} rejected the \`awaiting\` filter as unknown.`);
556
- }
557
- /** Short column value for tables: "you", "them", or "-" when absent. */
558
- function formatAwaitingCell(row) {
559
- if (!hasReplyState(row)) return "-";
560
- return row.awaiting;
561
- }
562
- /** Reply count for tables, or "-" when the server did not report it. */
563
- function formatRepliesCell(row) {
564
- if (!hasReplyState(row)) return "-";
565
- return String(row.reply_count);
566
- }
567
- const REPLY_STATE_SURFACES = {
568
- listEmails: "GET /emails",
569
- searchEmails: "GET /emails/search"
570
- };
571
- /**
572
- * For the generated `emails list` / `emails search` commands: the
573
- * surface name when this call asked for reply state (an `awaiting`
574
- * parameter or an `awaiting:` search term), else null.
575
- */
576
- function replyStateSurfaceForOperation(sdkName, query) {
577
- const surface = REPLY_STATE_SURFACES[sdkName];
578
- if (!surface || !query) return null;
579
- const q = typeof query.q === "string" ? query.q : void 0;
580
- return query.awaiting !== void 0 || queryUsesAwaiting(q) ? surface : null;
581
- }
582
- const searchSupportProbes = /* @__PURE__ */ new WeakMap();
583
- /**
584
- * GET /emails/search ignores unknown parameters, so an empty page for
585
- * `awaiting=...` does not show that the server applied the filter.
586
- * Read one unfiltered row: if it lacks reply state the server does not
587
- * support it and this throws ReplyStateUnsupportedError. No rows at all
588
- * means the mailbox is empty, so the empty answer stands.
589
- */
590
- function ensureSearchReportsReplyState(apiClient) {
591
- const key = apiClient;
592
- let probe = searchSupportProbes.get(key);
593
- if (!probe) {
594
- probe = (async () => {
595
- const result = await searchEmails({
596
- client: apiClient.client,
597
- query: {
598
- limit: 1,
599
- include_facets: "false",
600
- snippet: "false"
601
- },
602
- responseStyle: "fields"
603
- });
604
- if (result.error) throw new ReplyStateUnverifiedError("the empty result could not be checked: reading one unfiltered row from GET /emails/search failed.");
605
- const rows = result.data?.data;
606
- assertReplyState(rows ?? [], "GET /emails/search");
607
- })();
608
- searchSupportProbes.set(key, probe);
609
- probe.catch(() => {
610
- if (searchSupportProbes.get(key) === probe) searchSupportProbes.delete(key);
611
- });
612
- }
613
- return probe;
614
- }
615
- //#endregion
616
- //#region src/oclif/api-command.ts
617
- const API_ERROR_CODES = {
618
- accessDenied: "access_denied",
619
- authorizationPending: "authorization_pending",
620
- expiredToken: "expired_token",
621
- invalidDeviceCode: "invalid_device_code",
622
- notFound: "not_found",
623
- slowDown: "slow_down",
624
- unauthorized: "unauthorized"
625
- };
626
- function flagName(parameterName) {
627
- return parameterName.replace(/_/g, "-");
628
- }
629
- function flagDescription(parameter) {
630
- return parameter.description ?? parameter.name;
631
- }
632
- const numberFlag = Flags.custom({ async parse(input, _context, options) {
633
- const trimmed = input.trim();
634
- if (trimmed === "") throw new Errors.CLIError(`Expected a number but received: ${input}`);
635
- const value = Number(trimmed);
636
- if (!Number.isFinite(value)) throw new Errors.CLIError(`Expected a number but received: ${input}`);
637
- if (options.min !== void 0 && value < options.min) throw new Errors.CLIError(`Expected a number greater than or equal to ${options.min} but received: ${input}`);
638
- if (options.max !== void 0 && value > options.max) throw new Errors.CLIError(`Expected a number less than or equal to ${options.max} but received: ${input}`);
639
- return value;
640
- } });
641
- function numericFlagOptions(parameter) {
642
- return {
643
- ...typeof parameter.default === "number" ? { default: parameter.default } : {},
644
- ...typeof parameter.maximum === "number" ? { max: parameter.maximum } : {},
645
- ...typeof parameter.minimum === "number" ? { min: parameter.minimum } : {}
646
- };
647
- }
648
- function extractBodyFields(schema) {
649
- if (!schema || typeof schema !== "object") return [];
650
- const properties = schema.properties;
651
- if (!properties || typeof properties !== "object") return [];
652
- const requiredArr = Array.isArray(schema.required) ? schema.required.filter((k) => typeof k === "string") : [];
653
- const required = new Set(requiredArr);
654
- const fields = [];
655
- for (const [name, raw] of Object.entries(properties)) {
656
- const propSchema = raw && typeof raw === "object" ? raw : {};
657
- const t = propSchema.type;
658
- let displayType = "any";
659
- let kind = "complex";
660
- if (typeof t === "string") {
661
- displayType = t;
662
- if (t === "string") kind = "string";
663
- else if (t === "integer") kind = "integer";
664
- else if (t === "number") kind = "number";
665
- else if (t === "boolean") kind = "boolean";
666
- else if (t === "array") {
667
- const items = propSchema.items;
668
- if (items && typeof items === "object") {
669
- const itemType = items.type;
670
- if (typeof itemType === "string") displayType = `array<${itemType}>`;
671
- }
672
- kind = "complex";
673
- } else kind = "complex";
674
- } else if (Array.isArray(t)) {
675
- const nonNull = t.filter((s) => s !== "null");
676
- if (nonNull.length === 1) {
677
- const single = nonNull[0];
678
- displayType = `${single}?`;
679
- if (single === "string") kind = "string";
680
- else if (single === "integer") kind = "integer";
681
- else if (single === "number") kind = "number";
682
- else if (single === "boolean") kind = "boolean";
683
- else kind = "complex";
684
- } else {
685
- displayType = nonNull.join("|");
686
- kind = "complex";
687
- }
688
- }
689
- const description = typeof propSchema.description === "string" ? propSchema.description.split(/\n\s*\n/)[0].replace(/\s*\n\s*/g, " ").trim() : "";
690
- const enumRaw = propSchema.enum;
691
- const enumValues = kind === "string" && Array.isArray(enumRaw) ? enumRaw.filter((e) => typeof e === "string") : void 0;
692
- fields.push({
693
- name,
694
- description,
695
- required: required.has(name),
696
- displayType,
697
- kind,
698
- ...enumValues && enumValues.length > 0 ? { enumValues } : {},
699
- ...typeof propSchema.maximum === "number" ? { maximum: propSchema.maximum } : {},
700
- ...typeof propSchema.minimum === "number" ? { minimum: propSchema.minimum } : {}
701
- });
702
- }
703
- return fields.sort((a, b) => {
704
- if (a.required !== b.required) return a.required ? -1 : 1;
705
- return a.name.localeCompare(b.name);
706
- });
707
- }
708
- /**
709
- * Render a "Body fields" summary for the per-command help.
710
- *
711
- * Most scalar fields are exposed as individual `--flag` flags,
712
- * which oclif auto-renders in the FLAGS section above. To avoid
713
- * duplicating that, the summary here only documents fields that
714
- * MUST go through `--raw-body` (complex types: arrays, objects,
715
- * mixed-non-nullable). When an operation has only scalars, the
716
- * summary is omitted entirely and oclif's FLAGS section is the
717
- * full story.
718
- *
719
- * For operations with mixed scalar and complex fields, we also
720
- * include a short header pointing the agent at the flag form so
721
- * the natural reading is "use the flags above; --raw-body for
722
- * the leftovers below."
723
- */
724
- function renderRequestSchemaSummary(schema) {
725
- const fields = extractBodyFields(schema);
726
- if (fields.length === 0) return null;
727
- const complex = fields.filter((f) => f.kind === "complex");
728
- if (complex.length === 0) return null;
729
- const nameWidth = Math.min(24, Math.max(...complex.map((f) => f.name.length)));
730
- const descMax = 78;
731
- const lines = ["Body fields requiring --raw-body JSON (these are not exposed as flags):"];
732
- for (const f of complex) {
733
- const marker = f.required ? " *" : " ";
734
- const padName = f.name.padEnd(nameWidth);
735
- const trimmedDesc = f.description.length > descMax ? `${f.description.slice(0, descMax - 3)}...` : f.description;
736
- const desc = trimmedDesc ? ` ${trimmedDesc}` : "";
737
- lines.push(`${marker} ${padName} ${f.displayType}${desc}`);
738
- }
739
- lines.push("(* = required. Scalar body fields are exposed as individual --flag-name flags; see FLAGS above.)");
740
- return lines.join("\n");
741
- }
742
- function flagForParameter(parameter) {
743
- const common = {
744
- description: flagDescription(parameter),
745
- required: parameter.required
746
- };
747
- if (parameter.type === "boolean") return Flags.boolean(common);
748
- if (parameter.type === "integer") return Flags.integer({
749
- ...common,
750
- ...numericFlagOptions(parameter)
751
- });
752
- if (parameter.type === "number") return numberFlag({
753
- ...common,
754
- ...numericFlagOptions(parameter)
755
- });
756
- if (parameter.enum && parameter.enum.length > 0) return Flags.string({
757
- ...common,
758
- options: parameter.enum
759
- });
760
- return Flags.string(common);
761
- }
762
- function coerceParameterValue(parameter, value) {
763
- if (value === void 0) return;
764
- if (parameter.type === "number") {
765
- if (typeof value === "number") return value;
766
- const parsed = Number(value);
767
- if (Number.isNaN(parsed)) throw new Errors.CLIError(`Invalid number for --${parameter.name}: ${value}`);
768
- return parsed;
769
- }
770
- if (typeof value === "boolean" || typeof value === "number" || typeof value === "string") return value;
771
- throw new Errors.CLIError(`Unsupported flag value for --${parameter.name}`);
772
- }
773
- function cliError(message) {
774
- return new Errors.CLIError(message, { exit: 1 });
775
- }
776
- function parseJson(source, flagLabel) {
777
- try {
778
- return JSON.parse(source);
779
- } catch (error) {
780
- throw cliError(`${flagLabel} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
781
- }
782
- }
783
- function readJsonBody(flags) {
784
- const bodyFile = flags["body-file"];
785
- const rawBody = flags["raw-body"];
786
- if (bodyFile && rawBody) throw cliError("Use either --raw-body or --body-file, not both");
787
- if (typeof bodyFile === "string") {
788
- let contents;
789
- try {
790
- contents = readFileSync(bodyFile, "utf8");
791
- } catch (error) {
792
- throw cliError(`Could not read --body-file ${bodyFile}: ${error instanceof Error ? error.message : String(error)}`);
793
- }
794
- return parseJson(contents, `--body-file ${bodyFile}`);
795
- }
796
- if (typeof rawBody === "string") return parseJson(rawBody, "--raw-body");
797
- }
798
- function readTextFileFlag(path, flagLabel) {
799
- try {
800
- return readFileSync(path, "utf8");
801
- } catch (error) {
802
- throw cliError(`Could not read ${flagLabel} ${path}: ${error instanceof Error ? error.message : String(error)}`);
803
- }
804
- }
805
- function extractErrorPayload(raw) {
806
- if (raw && typeof raw === "object" && !(raw instanceof Error) && "error" in raw) {
807
- const inner = raw.error;
808
- if (inner !== null && inner !== void 0) return inner;
809
- }
810
- return raw;
811
- }
812
- function extractCauseDetails(cause) {
813
- const details = {};
814
- let code;
815
- if (!cause || typeof cause !== "object") return { details };
816
- for (const [key, value] of Object.entries(cause)) if (typeof value === "string" || typeof value === "number") {
817
- details[key] = value;
818
- if (key === "code" && typeof value === "string") code = value;
819
- }
820
- return {
821
- code,
822
- details
823
- };
824
- }
825
- function formatErrorPayload(payload) {
826
- if (payload instanceof Error) {
827
- const { code, details } = extractCauseDetails(payload.cause);
828
- const body = {
829
- code: code ?? "client_error",
830
- message: payload.message || payload.name || String(payload)
831
- };
832
- if (Object.keys(details).length > 0) body.cause = details;
833
- return JSON.stringify(body, null, 2);
834
- }
835
- return JSON.stringify(payload, null, 2);
836
- }
837
- function extractErrorCode(payload) {
838
- if (payload instanceof Error) {
839
- const { code } = extractCauseDetails(payload.cause);
840
- return code;
841
- }
842
- if (payload && typeof payload === "object") {
843
- const inner = payload.error;
844
- if (inner && typeof inner === "object" && typeof inner.code === "string") return inner.code;
845
- const direct = payload.code;
846
- if (typeof direct === "string") return direct;
847
- }
848
- }
849
- const ERROR_CODE_HINTS = { [API_ERROR_CODES.unauthorized]: "Hint: run `primitive signin`, pass --api-key explicitly, or set PRIMITIVE_API_KEY in your environment. `primitive whoami` is the fastest way to verify auth is live." };
850
- const NETWORK_ERROR_HINTS = {
851
- ENETUNREACH: "Hint: the network is unreachable. If you're behind a proxy and set HTTP(S)_PROXY, re-run with NODE_USE_ENV_PROXY=1 (Node 22+ ignores those env vars by default). `primitive doctor` reports the local environment in one shot.",
852
- ECONNREFUSED: "Hint: the server refused the connection. Check that your firewall allows egress to *.primitive.dev, that your PRIMITIVE_API_BASE_URL_* overrides (if any) point at a reachable host, and re-run with NODE_USE_ENV_PROXY=1 if you're behind a proxy. `primitive doctor` reports the local environment in one shot.",
853
- ETIMEDOUT: "Hint: the connection timed out. Check egress rules and proxy configuration; if you're behind a proxy, re-run with NODE_USE_ENV_PROXY=1 and HTTPS_PROXY set. `primitive doctor` reports the local environment in one shot.",
854
- EAI_AGAIN: "Hint: DNS lookup failed. Check /etc/resolv.conf inside containers, and try `curl -v https://api.primitive.dev/v1/account` to confirm the host resolves. `primitive doctor` reports the local environment in one shot."
855
- };
856
- function writeErrorWithHints(payload) {
857
- process.stderr.write(`${formatErrorPayload(payload)}\n`);
858
- const code = extractErrorCode(payload);
859
- if (!code) return;
860
- if (code in ERROR_CODE_HINTS) {
861
- const hint = ERROR_CODE_HINTS[code];
862
- process.stderr.write(`${hint}\n`);
863
- return;
864
- }
865
- if (code in NETWORK_ERROR_HINTS) process.stderr.write(`${NETWORK_ERROR_HINTS[code]}\n`);
866
- }
867
- /**
868
- * Surface a user-facing hint when a request comes back unauthorized.
869
- *
870
- * Deliberately does NOT mutate the saved credentials.json. Auto-
871
- * deleting on any 401 made transient rejections look like permanent
872
- * credential failures and forced unnecessary re-login cycles; we
873
- * surface a hint and let the user decide whether to re-authenticate.
874
- *
875
- * The one legitimate auto-delete case lives in `primitive login`'s
876
- * `checkExistingLogin`: the user has explicitly asked to log in,
877
- * existing credentials are probed, and if they fail we clean up
878
- * before minting a new key. That path calls `deleteCliCredentials`
879
- * directly rather than going through this function.
880
- */
881
- function surfaceUnauthorizedHint(params) {
882
- if (extractErrorCode(params.payload) !== API_ERROR_CODES.unauthorized || params.auth.source !== "stored") return;
883
- if (params.baseUrlOverridden && params.auth.credentials !== null && params.auth.apiBaseUrl !== params.auth.credentials.api_base_url) {
884
- process.stderr.write("Saved Primitive CLI credentials were rejected by the overridden API base URL. The saved credential is preserved; unset PRIMITIVE_API_BASE_URL, run `primitive config reset` to clear configured URL overrides, or run `primitive logout` to remove the stored credential.\n");
885
- return;
886
- }
887
- process.stderr.write("Your saved Primitive CLI OAuth session was rejected. If the command was working a moment ago, please retry; brief retries often clear transient rejections. If it keeps failing, run `primitive logout && primitive signin` to mint a fresh session.\n");
888
- }
889
- function formatElapsed(ms) {
890
- const seconds = ms / 1e3;
891
- if (seconds < 60) return `${seconds.toFixed(2)}s`;
892
- const minutes = Math.floor(seconds / 60);
893
- return `${minutes}m ${(seconds - minutes * 60).toFixed(2)}s`;
894
- }
895
- async function runWithTiming(enabled, fn) {
896
- if (!enabled) return fn();
897
- const start = Date.now();
898
- try {
899
- return await fn();
900
- } finally {
901
- process.stderr.write(`[time: ${formatElapsed(Date.now() - start)}]\n`);
902
- }
903
- }
904
- const TIME_FLAG_DESCRIPTION = "Print the wall-clock duration of this command to stderr after it completes (e.g. `[time: 1.34s]`). Useful for measuring `--wait` send latency, comparing CLI overhead, or capturing timing in scripts.";
905
- const API_BASE_URL_FLAG_DESCRIPTION = "Override the API base URL. Internal testing only; not documented to customers.";
906
- const RESERVED_FLAG_NAMES = new Set([
907
- "api-key",
908
- "api-base-url",
909
- "raw-body",
910
- "body-file",
911
- "envelope",
912
- "output"
913
- ]);
914
- function bodyFieldFlag(field, aliases) {
915
- const common = {
916
- description: field.description || field.name,
917
- ...aliases && aliases.length > 0 ? { aliases } : {}
918
- };
919
- if (field.kind === "boolean") return Flags.boolean({
920
- ...common,
921
- allowNo: true
922
- });
923
- if (field.kind === "integer") return Flags.integer({
924
- ...common,
925
- ...numericFlagOptions(field)
926
- });
927
- if (field.kind === "number") return numberFlag({
928
- ...common,
929
- ...numericFlagOptions(field)
930
- });
931
- if (field.enumValues) return Flags.string({
932
- ...common,
933
- options: field.enumValues
934
- });
935
- return Flags.string(common);
936
- }
937
- function buildFlags(operation) {
938
- const flags = {
939
- "api-key": Flags.string({
940
- description: "Primitive API key override (defaults to PRIMITIVE_API_KEY or saved OAuth login credentials)",
941
- env: "PRIMITIVE_API_KEY"
942
- }),
943
- "api-base-url": Flags.string({
944
- description: "Override the API base URL. Internal testing only; not documented to customers.",
945
- env: "PRIMITIVE_API_BASE_URL",
946
- hidden: true
947
- }),
948
- time: Flags.boolean({ description: TIME_FLAG_DESCRIPTION })
949
- };
950
- if (!operation.binaryResponse) {
951
- flags.json = Flags.boolean({ description: "Print exactly one JSON document on stdout, on success and on failure, and nothing on stderr. Stdout keeps its usual shape: the data payload, or with --envelope the full response envelope (data plus meta, including meta.cursor, and empty-result hints in summary). The next-cursor line is not printed; use --envelope to page. A failure prints the error with exit_code. Without --json, the cursor and notices go to stderr." });
952
- flags.envelope = Flags.boolean({ description: "Print the full response envelope, including pagination metadata such as meta.cursor. Defaults to printing only the data payload for backward compatibility." });
953
- }
954
- for (const parameter of [...operation.pathParams, ...operation.queryParams]) flags[flagName(parameter.name)] = flagForParameter(parameter);
955
- const bodyFieldFlagToProperty = /* @__PURE__ */ new Map();
956
- if (operation.hasJsonBody) {
957
- flags["raw-body"] = Flags.string({ description: "Full request body as raw JSON. Escape hatch for nested or complex fields (e.g. arrays); prefer per-field flags (e.g. --to, --from, --body-text) when available." });
958
- flags["body-file"] = Flags.string({ description: "Path to a JSON file used as the request body. Same role as --raw-body for callers passing a saved payload." });
959
- const bodyFields = extractBodyFields(operation.requestSchema);
960
- const aliasesForOperation = OPERATION_FLAG_ALIASES[operation.sdkName];
961
- for (const field of bodyFields) {
962
- if (field.kind === "complex") continue;
963
- const name = flagName(field.name);
964
- if (RESERVED_FLAG_NAMES.has(name)) continue;
965
- if (flags[name] !== void 0) continue;
966
- flags[name] = bodyFieldFlag(field, aliasesForOperation?.[field.name]);
967
- bodyFieldFlagToProperty.set(name, field.name);
968
- }
969
- }
970
- if (operation.binaryResponse) flags.output = Flags.string({ description: "Write binary response bytes to a file" });
971
- if (ATTACHMENT_WAIT_OPERATIONS.has(operation.sdkName)) flags.wait = Flags.boolean({
972
- allowNo: true,
973
- default: true,
974
- description: ATTACHMENT_WAIT_FLAG_DESCRIPTION
975
- });
976
- return {
977
- flags,
978
- bodyFieldFlagToProperty
979
- };
980
- }
981
- function collectBodyFieldFlags(parsedFlags, bodyFieldFlagToProperty) {
982
- const result = {};
983
- for (const [flag, property] of bodyFieldFlagToProperty) {
984
- const value = parsedFlags[flag];
985
- if (value === void 0) continue;
986
- result[property] = value;
987
- }
988
- return result;
989
- }
990
- function collectValues(parameters, flags) {
991
- const values = {};
992
- for (const parameter of parameters) {
993
- const value = coerceParameterValue(parameter, flags[flagName(parameter.name)]);
994
- if (value !== void 0) values[parameter.name] = value;
995
- }
996
- return values;
997
- }
998
- function operationOutputPayload(envelope, includeEnvelope) {
999
- return includeEnvelope ? envelope ?? null : envelope?.data ?? null;
1000
- }
1001
- /**
1002
- * The `--json` document for a generated command: the full response
1003
- * envelope, so pagination metadata travels with the data, plus any
1004
- * notes the command would otherwise print on stderr.
1005
- */
1006
- function operationJsonDocument(envelope, summary = []) {
1007
- const document = envelope !== null && typeof envelope === "object" ? { ...envelope } : { data: null };
1008
- if (summary.length > 0) document.summary = summary.join("\n");
1009
- return document;
1010
- }
1011
- function isIncompleteDomainVerification(operation, envelope) {
1012
- if (operation.sdkName !== "verifyDomain") return false;
1013
- const data = envelope?.data;
1014
- if (!data || typeof data !== "object") return false;
1015
- return data.verified === false;
1016
- }
1017
- function writeIncompleteDomainVerificationHint() {
1018
- process.stderr.write("Domain verification is incomplete. Add or fix the DNS records shown above, or run `primitive domains zone-file --id <domain-id>` to download the complete zone file, then retry `primitive domains verify --id <domain-id>`.\n");
1019
- }
1020
- const OPERATION_HINTS = {
1021
- addDomain: "Tip: after this returns a domain id, run `primitive domains zone-file --id <domain-id> --output <domain>.zone` when the user wants an importable DNS zone file.",
1022
- verifyDomain: "Tip: if DNS is still missing, run `primitive domains zone-file --id <domain-id> --output <domain>.zone` to give the user an importable DNS zone file.",
1023
- downloadDomainZoneFile: "Tip: prefer `primitive domains zone-file --id <domain-id> --output <domain>.zone` for CLI-friendly file output.",
1024
- getInboxStatus: "Tip: prefer `primitive inbox status` for a compact readiness summary and next-step commands.",
1025
- getSendPermissions: "Tip: this command answers where you may send mail to. To find usable sender domains for --from, run `primitive domains list` or `primitive inbox status` and use an address at an active verified domain.",
1026
- sendEmail: "Tip: prefer `primitive send --to <address> --body <text> --attachment <file>` for file attachments. This raw command exists for callers passing JSON.",
1027
- createFunction: "Tip: prefer `primitive functions deploy --name <name> --file <bundle>` for file-input ergonomics. This raw command exists for callers passing JSON.",
1028
- updateFunction: "Tip: prefer `primitive functions redeploy --id <id> --file <bundle>` for file-input ergonomics. This raw command exists for callers passing JSON.",
1029
- createFunctionSecret: "Tip: prefer `primitive functions set-secret --id <id> --key <KEY> --value <value> [--redeploy]` for secret writes that also push the binding live. This raw command exists for callers passing JSON.",
1030
- setFunctionSecret: "Tip: prefer `primitive functions set-secret --id <id> --key <KEY> --value <value> [--redeploy]` for secret writes that also push the binding live. This raw command exists for callers passing JSON.",
1031
- setMemory: "Tip: prefer `primitive memories set <key> <json-value> [--function <function-id>]` for JSON value parsing and scope flags. This raw command exists for callers passing full request JSON.",
1032
- getMemory: "Tip: prefer `primitive memories get <key> [--function <function-id>]` for the common read path.",
1033
- deleteMemory: "Tip: prefer `primitive memories delete <key> [--function <function-id>]` for the common delete path.",
1034
- searchMemories: "Tip: prefer `primitive memories search [prefix] [--metadata-only] [--function <function-id>]` for the common search path.",
1035
- startAgentSignup: "Tip: pass --terms-accepted, and optionally --signup-code <code> if you have one. Capture the signup_token from the response and feed it to `primitive agent verify-agent-signup --signup-token <token> --verification-code <6-digit-code>` (the verify flag accepts --code as an alias). The high-level `primitive signup <email>` command walks an interactive user through both steps with friendlier prompts.",
1036
- verifyAgentSignup: "Tip: pass --verification-code <code> (or --code; both work). The response carries OAuth tokens but not your assigned inbox domain; run `primitive domains list` (or `primitive whoami`) after success to see the managed *.primitive.email address that routes to this account."
1037
- };
1038
- const OPERATION_FLAG_ALIASES = { verifyAgentSignup: { verification_code: ["code"] } };
1039
- const OPERATION_SUCCESS_HOOKS = { verifyAgentSignup: ({ envelope, configDir, apiBaseUrl, writeStderr }) => {
1040
- const data = envelope?.data;
1041
- if (!data?.access_token || !data?.refresh_token) return;
1042
- saveSignupCredentials({
1043
- apiBaseUrl,
1044
- configDir,
1045
- signup: data
1046
- });
1047
- writeStderr("Credentials saved to the CLI config; `primitive whoami` will work on the next call.\n");
1048
- } };
1049
- function createOperationCommand(operation) {
1050
- const { flags, bodyFieldFlagToProperty } = buildFlags(operation);
1051
- const baseDescription = operation.description !== null && operation.description !== void 0 ? canonicalizeCliReferences(operation.description) : `${operation.method} ${operation.path}`;
1052
- const schemaSummary = operation.hasJsonBody ? renderRequestSchemaSummary(operation.requestSchema) : null;
1053
- const hint = OPERATION_HINTS[operation.sdkName];
1054
- const descriptionWithSchema = schemaSummary ? `${baseDescription}\n\n${schemaSummary}` : baseDescription;
1055
- const fullDescription = hint ? `${descriptionWithSchema}\n\n${hint}` : descriptionWithSchema;
1056
- class OperationCommand extends Command {
1057
- static description = fullDescription;
1058
- static flags = flags;
1059
- static summary = operation.summary ?? `${operation.method} ${operation.path}`;
1060
- async run() {
1061
- const { flags } = await this.parse(OperationCommand);
1062
- const parsedFlags = flags;
1063
- if ([
1064
- "startAgentSignup",
1065
- "verifyAgentSignup",
1066
- "resendAgentSignupVerification"
1067
- ].includes(operation.operationId)) requireDefaultLoginProfile();
1068
- await runWithTiming(parsedFlags.time === true, async () => {
1069
- const { apiClient, auth, baseUrlOverridden } = await createAuthenticatedCliApiClient({
1070
- apiKey: typeof parsedFlags["api-key"] === "string" ? parsedFlags["api-key"] : void 0,
1071
- apiBaseUrl: typeof parsedFlags["api-base-url"] === "string" ? parsedFlags["api-base-url"] : void 0,
1072
- configDir: this.config.configDir
1073
- });
1074
- let body;
1075
- if (operation.hasJsonBody) {
1076
- const explicit = readJsonBody(parsedFlags);
1077
- const overrides = collectBodyFieldFlags(parsedFlags, bodyFieldFlagToProperty);
1078
- if (Object.keys(overrides).length > 0) if (explicit === void 0) body = overrides;
1079
- else if (explicit !== null && typeof explicit === "object" && !Array.isArray(explicit)) body = {
1080
- ...explicit,
1081
- ...overrides
1082
- };
1083
- else {
1084
- const explicitKind = explicit === null ? "null" : Array.isArray(explicit) ? "array" : typeof explicit;
1085
- const overrideFlags = Object.keys(overrides).map((p) => `--${flagName(p)}`).join(", ");
1086
- throw new Errors.CLIError(`--raw-body must be a JSON object when also passing per-field flags (got ${explicitKind}); supplied per-field flags: ${overrideFlags}. Either drop --raw-body and rely on the per-field flags, or move every field into the JSON --raw-body and drop the flags.`);
1087
- }
1088
- else body = explicit;
1089
- }
1090
- if (operation.bodyRequired && body === void 0) throw new Errors.CLIError(`Operation ${operation.operationId} requires a body. Pass each field as a --flag (see --help) or supply JSON via --raw-body / --body-file.`);
1091
- const operationFn = sdk_gen_exports[operation.sdkName];
1092
- const query = collectValues(operation.queryParams, parsedFlags);
1093
- const replyStateSurface = replyStateSurfaceForOperation(operation.sdkName, query);
1094
- const automatedSurface = automatedSurfaceForOperation(operation.sdkName, query);
1095
- const callOperation = () => operationFn({
1096
- body,
1097
- client: apiClient.client,
1098
- parseAs: operation.binaryResponse ? "blob" : "auto",
1099
- path: collectValues(operation.pathParams, parsedFlags),
1100
- query,
1101
- responseStyle: "fields"
1102
- });
1103
- const result = ATTACHMENT_WAIT_OPERATIONS.has(operation.sdkName) ? await withAttachmentWait(callOperation, {
1104
- wait: parsedFlags.wait !== false,
1105
- errorCode: (error) => extractErrorCode(extractErrorPayload(error)),
1106
- onFirstWait: () => {
1107
- process.stderr.write(`Attachment content is not ready yet; waiting up to ${ATTACHMENT_WAIT_MAX_MS / 1e3}s. Pass --no-wait to return immediately.\n`);
1108
- }
1109
- }) : await callOperation();
1110
- if (result.error) {
1111
- const errorPayload = extractErrorPayload(result.error);
1112
- writeErrorWithHints(errorPayload);
1113
- if (replyStateSurface && isAwaitingRejectedError(errorPayload)) process.stderr.write(`${awaitingRejectedError(replyStateSurface).message}\n`);
1114
- if (automatedSurface && isAutomatedRejectedError(errorPayload)) process.stderr.write(`${automatedRejectedError(automatedSurface).message}\n`);
1115
- surfaceUnauthorizedHint({
1116
- auth,
1117
- baseUrlOverridden,
1118
- configDir: this.config.configDir,
1119
- payload: errorPayload
1120
- });
1121
- const listClient = apiClient.client;
1122
- const listEndpointsFn = () => listEndpoints({
1123
- client: listClient,
1124
- responseStyle: "fields"
1125
- });
1126
- await maybeWriteFunctionEndpointRedirect({
1127
- sdkName: operation.sdkName,
1128
- errorCode: extractErrorCode(errorPayload),
1129
- endpointId: typeof parsedFlags.id === "string" ? parsedFlags.id : void 0,
1130
- listEndpoints: listEndpointsFn,
1131
- writeStderr: (chunk) => {
1132
- process.stderr.write(chunk);
1133
- }
1134
- });
1135
- process.exitCode = 1;
1136
- return;
1137
- }
1138
- if (operation.binaryResponse) {
1139
- const blob = result.data;
1140
- const bytes = Buffer.from(await blob.arrayBuffer());
1141
- const output = parsedFlags.output;
1142
- if (typeof output === "string") {
1143
- writeFileSync(output, bytes);
1144
- return;
1145
- }
1146
- process.stdout.write(bytes);
1147
- return;
1148
- }
1149
- const envelope = result.data;
1150
- if (replyStateSurface) try {
1151
- const rows = Array.isArray(envelope?.data) ? envelope.data : [];
1152
- assertAwaitingFilterRows(rows, replyStateSurface);
1153
- if (rows.length === 0 && operation.sdkName === "searchEmails") await ensureSearchReportsReplyState(apiClient);
1154
- } catch (error) {
1155
- if (!(error instanceof ReplyStateUnsupportedError)) throw error;
1156
- process.stderr.write(`${error.message}\n`);
1157
- process.exitCode = 1;
1158
- return;
1159
- }
1160
- if (automatedSurface) try {
1161
- const rows = Array.isArray(envelope?.data) ? envelope.data : [];
1162
- assertAutomatedVerdict(rows, automatedSurface, expectedAutomatedVerdicts(query?.automated === "true" ? true : query?.automated === "false" ? false : void 0, typeof query?.q === "string" ? query.q : void 0));
1163
- if (rows.length === 0 && operation.sdkName === "searchEmails") await ensureSearchReportsAutomated(apiClient);
1164
- } catch (error) {
1165
- if (!(error instanceof AutomatedFilterUnsupportedError)) throw error;
1166
- process.stderr.write(`${error.message}\n`);
1167
- process.exitCode = 1;
1168
- return;
1169
- }
1170
- const jsonOutput = parsedFlags.json === true;
1171
- const withEnvelope = parsedFlags.envelope === true;
1172
- const cursor = envelope?.meta?.cursor;
1173
- if (cursor && !jsonOutput) process.stderr.write(`next cursor: ${cursor}\n`);
1174
- const summary = [];
1175
- if (Array.isArray(envelope?.data) && envelope.data.length === 0) {
1176
- const hint = EMPTY_RESULT_HINTS[operation.sdkName];
1177
- if (hint && jsonOutput) {
1178
- if (withEnvelope) summary.push(hint);
1179
- } else if (hint) process.stderr.write(`${hint}\n`);
1180
- }
1181
- writeIdempotentReplayBannerIfReplay(envelope?.data, { write: (chunk) => {
1182
- process.stderr.write(chunk);
1183
- } });
1184
- const successHook = OPERATION_SUCCESS_HOOKS[operation.sdkName];
1185
- if (successHook) try {
1186
- successHook({
1187
- envelope,
1188
- configDir: this.config.configDir,
1189
- apiBaseUrl: auth.apiBaseUrl,
1190
- writeStderr: (chunk) => {
1191
- process.stderr.write(chunk);
1192
- }
1193
- });
1194
- } catch (hookError) {
1195
- const detail = hookError instanceof Error ? hookError.message : String(hookError);
1196
- process.stderr.write(`Warning: ${operation.sdkName} succeeded but its post-success hook threw (${detail}). The response below is still valid; act on it manually.\n`);
1197
- }
1198
- this.log(JSON.stringify(jsonOutput && withEnvelope ? operationJsonDocument(envelope, summary) : operationOutputPayload(envelope, withEnvelope), null, 2));
1199
- if (isIncompleteDomainVerification(operation, envelope)) {
1200
- writeIncompleteDomainVerificationHint();
1201
- process.exitCode = 1;
1202
- }
1203
- });
1204
- }
1205
- }
1206
- return OperationCommand;
1207
- }
1208
- const EMPTY_RESULT_HINTS = {
1209
- listDeliveries: "(no results) No webhook deliveries logged yet. If you have an endpoint configured but expected to see test fires here: test deliveries from `primitive endpoints test` are NOT logged in this list, they're synchronous and visible only in the test-endpoint command's response. Real deliveries are logged when an inbound `email.received` event fans out to your endpoints. If you have no endpoints, run `primitive endpoints list` to check.",
1210
- listEndpoints: "(no results) No webhook endpoints configured. Add one with `primitive endpoints create --url <your-url>`.",
1211
- listEmails: "(no results) No inbound emails received yet on this account. Send one to a verified domain to populate this list. For a compact view, prefer `primitive emails latest`.",
1212
- listDomains: "(no results) No domains on this account. Add one with `primitive domains add --domain <yourdomain.example>`.",
1213
- listFilters: "(no results) No filter rules configured.",
1214
- listFunctions: "(no results) No Functions configured yet. Start with `primitive functions templates`, then `primitive functions init --template <template>` and `primitive functions deploy --name <name> --file <bundle>`."
1215
- };
1216
- function canonicalizeCliReferences(description) {
1217
- return description.replaceAll("`primitive emails:latest`", "`primitive emails latest`").replaceAll("`primitive describe emails:get-email | jq '.responseSchema.properties'`", "`primitive describe emails:get | jq '.responseSchema.properties'`");
1218
- }
1219
- //#endregion
1220
10
  //#region ../sdk-node/dist/payloads-CXgCzM4Y.js
1221
11
  /**
1222
12
  * Load a Node builtin at call time. Exported for direct testing of the
@@ -2655,20 +1445,23 @@ function formatWakeContext(context) {
2655
1445
  const sender = displayAddress(context.sender);
2656
1446
  const thread = context.threadId && UUID.test(context.threadId) ? context.threadId.toLowerCase() : "none";
2657
1447
  const newer = context.newer !== void 0 && Number.isSafeInteger(context.newer) && context.newer >= 0 ? ` newer=${Math.min(context.newer, 9999)}` : "";
2658
- return `from=${sender} relationship=${context.relationship} thread=${thread} in_thread=${context.inThread ? "yes" : "no"} attachments=${context.attachments ? "yes" : "no"}${newer}`;
1448
+ const interaction = isWakeInteractionLabel(context.interaction) ? ` interaction=${context.interaction}` : "";
1449
+ return `from=${sender} relationship=${context.relationship} thread=${thread} in_thread=${context.inThread ? "yes" : "no"} attachments=${context.attachments ? "yes" : "no"}${newer}${interaction}`;
2659
1450
  }
2660
1451
  /** Build a wake context, reading the thread once. Never throws for API failures. */
2661
1452
  async function describeWake(input) {
2662
1453
  const { detail } = input;
2663
1454
  const threadId = typeof detail.thread_id === "string" && UUID.test(detail.thread_id) ? detail.thread_id.toLowerCase() : null;
2664
1455
  const thread = threadId ? await readThreadContext(input.client, threadId, detail.id, input.signal) : null;
1456
+ const interaction = wakeInteractionLabel(detail);
2665
1457
  return {
2666
1458
  sender: detail.from_email.trim().toLowerCase(),
2667
1459
  relationship: serverRelationship(detail) ?? input.relationship,
2668
1460
  threadId,
2669
1461
  inThread: input.localInThread || sentInThread(thread, input.self) === true,
2670
1462
  attachments: hasAttachments(detail),
2671
- ...thread?.newerInboundCount === void 0 ? {} : { newer: thread.newerInboundCount }
1463
+ ...thread?.newerInboundCount === void 0 ? {} : { newer: thread.newerInboundCount },
1464
+ ...interaction ? { interaction } : {}
2672
1465
  };
2673
1466
  }
2674
1467
  //#endregion
@@ -3920,357 +2713,6 @@ async function reconcileChatSend(params) {
3920
2713
  return sent;
3921
2714
  }
3922
2715
  //#endregion
3923
- //#region src/oclif/send-outcome.ts
3924
- const SEND_OUTCOME_EXIT_CODES = {
3925
- replied: 0,
3926
- sent: 0,
3927
- already_sent: 0,
3928
- not_sent: 1,
3929
- sent_awaiting_reply: 3,
3930
- uncertain: 4
3931
- };
3932
- const DEFINITIVE_SEND_REJECTION_STATUSES = [
3933
- 400,
3934
- 401,
3935
- 402,
3936
- 403,
3937
- 404,
3938
- 413,
3939
- 422,
3940
- 429
3941
- ];
3942
- const SEND_OUTCOME_HELP = `Outcomes and exit codes, shared by chat, chat reply, send and reply (JSON output carries the name as "outcome"):
3943
- - exit 0 replied: chat only. The message was sent and a reply arrived.
3944
- - exit 0 sent: accepted for delivery. A queued status counts as sent.
3945
- - exit 0 already_sent: an identical earlier send exists (or was deleted: HTTP 410 sent_email_deleted). Nothing new went out. Do not resend.
3946
- - exit 1 not_sent: the API rejected the request (HTTP 400, 401, 402, 403, 404, 413, 422 or 429), the command failed before sending, or the send record has status agent_failed, gate_denied or canceled. Nothing went out.
3947
- - exit 2: invalid flags or arguments. Nothing went out.
3948
- - exit 3 sent_awaiting_reply: chat only. Sent, but no reply before the timeout. Wait; do not resend.
3949
- - exit 4 uncertain: transport error, conflict, server error, or a send record with status unknown. It may or may not have gone out. Reconcile with primitive sent get --idempotency-key <key> (the key is in the --json envelope) before retrying.`;
3950
- function sendOutcomeExitCode(outcome) {
3951
- return SEND_OUTCOME_EXIT_CODES[outcome];
3952
- }
3953
- function sendFailureOutcome(httpStatus) {
3954
- return httpStatus !== void 0 && DEFINITIVE_SEND_REJECTION_STATUSES.includes(httpStatus) ? "not_sent" : "uncertain";
3955
- }
3956
- const SENT_EMAIL_DELETED_CODE = "sent_email_deleted";
3957
- function errorPayloadCode(payload) {
3958
- if (payload === null || typeof payload !== "object") return void 0;
3959
- const code = payload.code;
3960
- return typeof code === "string" ? code : void 0;
3961
- }
3962
- function isDeletedEarlierSend(httpStatus, errorPayload) {
3963
- return httpStatus === 410 && errorPayloadCode(errorPayload) === SENT_EMAIL_DELETED_CODE;
3964
- }
3965
- /** Classify an API error from a send request. */
3966
- function classifySendError(httpStatus, errorPayload) {
3967
- return isDeletedEarlierSend(httpStatus, errorPayload) ? "already_sent" : sendFailureOutcome(httpStatus);
3968
- }
3969
- function formatDeletedEarlierSendNotice() {
3970
- return "Already sent: an earlier send matching this request went out and its record was later deleted, so the API refused this one (HTTP 410 sent_email_deleted). Nothing new was sent. Do not resend or change the idempotency key to get around this.";
3971
- }
3972
- /** Read the HTTP status from a `responseStyle: "fields"` API result. */
3973
- function apiResultHttpStatus(result) {
3974
- if (result === null || typeof result !== "object") return void 0;
3975
- if (!("response" in result)) return void 0;
3976
- const response = result.response;
3977
- return typeof response?.status === "number" ? response.status : void 0;
3978
- }
3979
- const SEND_STATUSES_THAT_DID_NOT_GO_OUT = new Set([
3980
- "agent_failed",
3981
- "canceled",
3982
- "gate_denied"
3983
- ]);
3984
- const SEND_STATUSES_WITH_UNKNOWN_OUTCOME = new Set(["unknown"]);
3985
- /**
3986
- * Classify a send record the API returned with a 2xx. A 2xx alone does
3987
- * not mean a message went out: the record's status can show the
3988
- * attempt was rejected or that its result is indeterminate. The same
3989
- * holds for an idempotent replay, which returns the earlier attempt's
3990
- * record as it stands.
3991
- */
3992
- function successfulSendOutcome(sent) {
3993
- if (SEND_STATUSES_THAT_DID_NOT_GO_OUT.has(sent.status)) return "not_sent";
3994
- if (SEND_STATUSES_WITH_UNKNOWN_OUTCOME.has(sent.status)) return "uncertain";
3995
- return sent.idempotent_replay === true ? "already_sent" : "sent";
3996
- }
3997
- /**
3998
- * Summary for a 2xx send record whose status shows it did not go out
3999
- * (`not_sent`) or that its result is indeterminate (`uncertain`).
4000
- */
4001
- function formatSendRecordFailureSummary(noun, outcome, sent) {
4002
- const record = sent.idempotent_replay === true ? `the earlier identical attempt (sent id ${sent.id}) has status ${sent.status}` : `the send record (id ${sent.id}) has status ${sent.status}`;
4003
- if (outcome === "not_sent") return `${noun} not sent: ${record}. Nothing went out; fix the problem before retrying.`;
4004
- return `${noun} send outcome uncertain: ${record}. It may or may not have gone out. Do not resend blindly; check sent history first.`;
4005
- }
4006
- function describeSentStatus(status) {
4007
- if (status === "queued") return "queued for delivery";
4008
- if (status === "delivered") return "delivered";
4009
- return `status ${status}`;
4010
- }
4011
- function formatSentSummary(noun, sent) {
4012
- return `${noun} sent (${describeSentStatus(sent.status)}, id ${sent.id}). Do not resend.`;
4013
- }
4014
- function formatSendFailureSummary(noun, outcome, httpStatus) {
4015
- if (outcome === "not_sent") return `${noun} not sent: ${httpStatus === void 0 ? "the request failed before sending" : `the API rejected the request (HTTP ${httpStatus})`}. Nothing went out; fix the problem before retrying.`;
4016
- return `${noun} send outcome uncertain (${httpStatus === void 0 ? "no response from the API" : `HTTP ${httpStatus}`}): it may or may not have gone out. Do not resend blindly; check sent history first.`;
4017
- }
4018
- function priorRepliesThatWentOut(replies, options = {}) {
4019
- return (replies ?? []).filter((reply) => !SEND_STATUSES_THAT_DID_NOT_GO_OUT.has(reply.status) && reply.id !== options.excludeSentId);
4020
- }
4021
- function formatPriorRepliesWarning(prior) {
4022
- const latest = prior.at(-1);
4023
- if (!latest) return null;
4024
- return `This email already has ${prior.length === 1 ? "1 outgoing email" : `${prior.length} outgoing emails`}, most recently at ${latest.created_at} (sent id ${latest.id}). These may include activity updates and do not prove a completed answer. Sending this reply.`;
4025
- }
4026
- function formatPriorRepliesCheckSkipped(emailId, reason) {
4027
- return `Could not check whether you already replied to email ${emailId} (${reason}). Prior-reply check skipped; sending the reply anyway.`;
4028
- }
4029
- /**
4030
- * Look up the inbound email and report replies to it that already
4031
- * went out. Never throws: the check is advisory and must not block a
4032
- * send, so every failure comes back as `skipped` with a reason the
4033
- * caller surfaces.
4034
- */
4035
- async function checkPriorReplies(params) {
4036
- try {
4037
- const result = await getEmail({
4038
- client: params.client,
4039
- path: { id: params.emailId },
4040
- responseStyle: "fields"
4041
- });
4042
- if (result.error) {
4043
- const status = apiResultHttpStatus(result);
4044
- return {
4045
- status: "skipped",
4046
- reason: status === void 0 ? "the email lookup failed" : `the email lookup returned HTTP ${status}`
4047
- };
4048
- }
4049
- const envelope = result.data;
4050
- const detail = envelope?.data ?? envelope;
4051
- if (!detail || !Array.isArray(detail.replies)) return {
4052
- status: "skipped",
4053
- reason: "the email lookup returned no reply history"
4054
- };
4055
- return {
4056
- status: "checked",
4057
- prior: priorRepliesThatWentOut(detail.replies),
4058
- detail
4059
- };
4060
- } catch (error) {
4061
- return {
4062
- status: "skipped",
4063
- reason: `the email lookup failed: ${error instanceof Error ? error.message : String(error)}`
4064
- };
4065
- }
4066
- }
4067
- function shellQuote(value) {
4068
- if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(value)) return value;
4069
- return `'${value.replaceAll("'", "'\\''")}'`;
4070
- }
4071
- function commandFromArgv(argv) {
4072
- return argv.map(shellQuote).join(" ");
4073
- }
4074
- function buildFollowUpCommand(kind, description, argv, options = {}) {
4075
- const requiresMessage = options.requiresMessage ?? false;
4076
- return {
4077
- argv,
4078
- description,
4079
- command: commandFromArgv(argv),
4080
- kind,
4081
- placeholders: requiresMessage ? [{
4082
- description: "Replace with the message body before running.",
4083
- token: "<message>"
4084
- }] : [],
4085
- requires_message: requiresMessage
4086
- };
4087
- }
4088
- const SENT_HISTORY_CLOCK_SKEW_MS = 300 * 1e3;
4089
- function sentHistoryWindowStart(attemptStartedAtIso) {
4090
- const started = Date.parse(attemptStartedAtIso);
4091
- if (!Number.isFinite(started)) return attemptStartedAtIso;
4092
- return new Date(started - SENT_HISTORY_CLOCK_SKEW_MS).toISOString();
4093
- }
4094
- /** Header rule for Idempotency-Key: 1 to 255 printable ASCII characters. */
4095
- const IDEMPOTENCY_KEY_PATTERN = /^[\x21-\x7E]{1,255}$/;
4096
- const IDEMPOTENCY_KEY_FLAG_DESCRIPTION = "Idempotency key for this send (1 to 255 printable ASCII characters). Retrying with the same key returns the original send instead of sending twice. Defaults to a key derived from the request content and the current five-minute window, so an identical retry within that window is deduplicated and a deliberate repeat later still sends. To retry an uncertain send after that, pass the key it reported. Look a send up later with `primitive sent get --idempotency-key <key>`.";
4097
- function assertValidIdempotencyKey(key) {
4098
- if (!IDEMPOTENCY_KEY_PATTERN.test(key)) throw new Errors.CLIError("--idempotency-key must be 1 to 255 printable ASCII characters with no spaces.", { exit: 2 });
4099
- return key;
4100
- }
4101
- const NON_CONTENT_SEND_FIELDS = new Set(["wait", "wait_timeout_ms"]);
4102
- function canonicalJson(value) {
4103
- if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item ?? null)).join(",")}]`;
4104
- if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
4105
- return JSON.stringify(value ?? null);
4106
- }
4107
- /**
4108
- * How long a derived key stays the same. It matches the window the API
4109
- * uses for the key it derives itself when a request carries none, so an
4110
- * identical send repeated inside this window is deduplicated and a
4111
- * deliberate repeat later (a digest, a heartbeat, the same short reply
4112
- * on another day) still goes out, exactly as without a key. An explicit
4113
- * --idempotency-key never expires.
4114
- */
4115
- const DERIVED_IDEMPOTENCY_WINDOW_MS = 300 * 1e3;
4116
- /**
4117
- * The idempotency key a send uses when the caller passes none. It is a
4118
- * hash of what is sent (and, for a reply, of the email replied to) and
4119
- * of the current five-minute window, so dedup matches what the API did
4120
- * before the CLI sent a key, while the CLI knows the key before the
4121
- * request starts. That lets an uncertain outcome still report the key to
4122
- * reconcile with, and to retry under with --idempotency-key.
4123
- */
4124
- function deriveSendIdempotencyKey(kind, request, now = Date.now()) {
4125
- const content = Object.fromEntries(Object.entries(request).filter(([key]) => !NON_CONTENT_SEND_FIELDS.has(key)));
4126
- return `primitive-${kind}-${createHash("sha256").update(canonicalJson(content)).update(`:t${Math.floor(now / DERIVED_IDEMPOTENCY_WINDOW_MS)}`).digest("hex")}`;
4127
- }
4128
- /**
4129
- * Identity fields every send, reply and chat `--json` envelope carries,
4130
- * whatever the outcome. `sent_email_id` is null until a send record is
4131
- * known; `idempotency_key` is known before the request starts, so an
4132
- * uncertain outcome can be reconciled with
4133
- * `primitive sent get --idempotency-key <key>`.
4134
- */
4135
- function sendIdentityFields(params) {
4136
- return {
4137
- sent_email_id: params.sent?.id ?? null,
4138
- idempotency_key: params.idempotencyKey ?? params.sent?.client_idempotency_key ?? null
4139
- };
4140
- }
4141
- /**
4142
- * Commands that inspect an existing send. None of them send again:
4143
- * a caller that follows them after a failure cannot double-send.
4144
- */
4145
- function buildSendCommandFollowUps(params) {
4146
- const commands = [];
4147
- if (params.sentId === null && params.outcome === "uncertain" && params.idempotencyKey) commands.push(buildFollowUpCommand("find_sent_email_by_idempotency_key", "Look up this attempt by its idempotency key before retrying", [
4148
- "primitive",
4149
- "sent",
4150
- "get",
4151
- "--idempotency-key",
4152
- params.idempotencyKey
4153
- ]));
4154
- if (params.sentId !== null) commands.push(buildFollowUpCommand("inspect_sent_email", "Inspect the send and its delivery status", [
4155
- "primitive",
4156
- "sent",
4157
- "get",
4158
- "--id",
4159
- params.sentId
4160
- ]));
4161
- if (params.outcome === "uncertain") commands.push(buildFollowUpCommand("list_recent_sent_emails", "Check sent history for this attempt before retrying", [
4162
- "primitive",
4163
- "sent",
4164
- "list",
4165
- "--date-from",
4166
- sentHistoryWindowStart(params.attemptStartedAtIso)
4167
- ]));
4168
- return commands;
4169
- }
4170
- /**
4171
- * Classify a `send` / `reply` API result, write the stderr summary,
4172
- * and print stdout. Without `--json` stdout stays exactly what these
4173
- * commands always printed (the SendMailResult, or `null`), so
4174
- * existing `| jq` pipelines keep working; the outcome is on stderr
4175
- * and in the exit code. With `--json` stdout is always an envelope,
4176
- * whatever the outcome, and the summary is only its outcome_message.
4177
- */
4178
- function reportSendCommandResult(params) {
4179
- const httpStatus = apiResultHttpStatus(params.result);
4180
- let outcome;
4181
- let outcomeMessage;
4182
- let sent = null;
4183
- let errorPayload = null;
4184
- if (params.result.error) {
4185
- errorPayload = extractErrorPayload(params.result.error);
4186
- params.onApiError(errorPayload);
4187
- const failure = classifySendError(httpStatus, errorPayload);
4188
- outcome = failure;
4189
- outcomeMessage = failure === "already_sent" ? formatDeletedEarlierSendNotice() : formatSendFailureSummary(params.noun, failure, httpStatus);
4190
- if (!params.json) params.writeStderr(`${outcomeMessage}\n`);
4191
- } else {
4192
- sent = params.result.data?.data ?? null;
4193
- if (sent === null) {
4194
- outcome = "uncertain";
4195
- outcomeMessage = `${params.noun} send outcome uncertain: the API accepted the request but returned no send record. Do not resend blindly; check sent history first.`;
4196
- errorPayload = { message: "The API returned no send record." };
4197
- } else {
4198
- outcome = successfulSendOutcome(sent);
4199
- outcomeMessage = outcome === "not_sent" || outcome === "uncertain" ? formatSendRecordFailureSummary(params.noun, outcome, sent) : outcome === "already_sent" ? formatAlreadySentNotice(sent) : formatSentSummary(params.noun, sent);
4200
- }
4201
- if (!params.json) params.writeStderr(`${outcomeMessage}\n`);
4202
- }
4203
- if (params.json) {
4204
- const envelope = {
4205
- outcome,
4206
- exit_code: sendOutcomeExitCode(outcome),
4207
- outcome_message: outcomeMessage,
4208
- ...sendIdentityFields({
4209
- idempotencyKey: params.idempotencyKey,
4210
- sent
4211
- }),
4212
- sent,
4213
- http_status: httpStatus ?? null,
4214
- error: serializeErrorPayload(errorPayload),
4215
- follow_up_commands: buildSendCommandFollowUps({
4216
- attemptStartedAtIso: params.attemptStartedAtIso,
4217
- idempotencyKey: params.idempotencyKey,
4218
- outcome,
4219
- sentId: sent?.id ?? null
4220
- }),
4221
- ...params.extraEnvelopeFields
4222
- };
4223
- params.log(JSON.stringify(envelope, null, 2));
4224
- } else if (!params.result.error) params.log(JSON.stringify(sent, null, 2));
4225
- return outcome;
4226
- }
4227
- /** JSON-safe form of an API error payload; `Error` objects stringify to `{}`. */
4228
- function serializeErrorPayload(payload) {
4229
- if (!(payload instanceof Error)) return payload ?? null;
4230
- const serialized = {
4231
- name: payload.name,
4232
- message: payload.message
4233
- };
4234
- const cause = payload.cause;
4235
- if (cause && typeof cause.code === "string") serialized.code = cause.code;
4236
- return serialized;
4237
- }
4238
- /**
4239
- * Envelope for a `send` / `reply` that threw instead of returning an
4240
- * API result. Printed in --json mode so stdout carries an envelope for
4241
- * every outcome. Before the request starts (bad input, missing auth,
4242
- * unreadable attachment) nothing went out; after it starts the
4243
- * outcome is unknown.
4244
- */
4245
- function buildThrownSendFailureEnvelope(params) {
4246
- const message = params.error instanceof Error ? params.error.message : String(params.error);
4247
- const outcome = params.requestStarted ? "uncertain" : "not_sent";
4248
- return {
4249
- outcome,
4250
- exit_code: params.requestStarted ? sendOutcomeExitCode("uncertain") : thrownErrorExitCode(params.error),
4251
- outcome_message: formatSendFailureSummary(params.noun, outcome, void 0),
4252
- ...sendIdentityFields({
4253
- idempotencyKey: params.idempotencyKey,
4254
- sent: null
4255
- }),
4256
- sent: null,
4257
- http_status: null,
4258
- error: { message },
4259
- follow_up_commands: params.requestStarted && params.attemptStartedAtIso ? buildSendCommandFollowUps({
4260
- attemptStartedAtIso: params.attemptStartedAtIso,
4261
- idempotencyKey: params.idempotencyKey,
4262
- outcome,
4263
- sentId: null
4264
- }) : [],
4265
- ...params.extraEnvelopeFields
4266
- };
4267
- }
4268
- /** Exit code oclif will use for a thrown error (2 for usage errors). */
4269
- function thrownErrorExitCode(error) {
4270
- const exit = error?.oclif?.exit;
4271
- return typeof exit === "number" ? exit : 1;
4272
- }
4273
- //#endregion
4274
2716
  //#region src/oclif/signal-command.ts
4275
2717
  const sendStatuses = new Set([
4276
2718
  "queued",
@@ -4511,4 +2953,4 @@ async function sendSignal(context, options) {
4511
2953
  }
4512
2954
  }
4513
2955
  //#endregion
4514
- export { extractErrorCode as $, reserveSharedMailSubscription as A, queryUsesAutomated as At, sentInThread as B, thrownErrorExitCode as C, AutomatedFilterUnsupportedError as Ct, ensureSharedMailSubscription as D, expectedAutomatedVerdicts as Dt, sharedMailScope as E, ensureSearchReportsAutomated as Et, describeWake as F, resolveCliApiRequestConfig as Ft, EventConnection as G, serverRelationship as H, displayAddress as I, pushFile as J, EventReceiverError as K, formatWakeContext as L, readConversationFollow as M, createAuthenticatedCliApiClient as Mt, otherParticipants as N, createCliApiClient as Nt, createSharedMailWaiter as O, hasAutomatedVerdict as Ot, bareAddress as P, refreshStoredCliCredentials as Pt, createOperationCommand as Q, latestOwnOutbound as R, successfulSendOutcome as S, AUTOMATED_VALUES as St, openSharedMailReceiver as T, automatedRejectedError as Tt, wakeRelationship as U, serverMuted as V, readSharedMailOwner as W, API_ERROR_CODES as X, API_BASE_URL_FLAG_DESCRIPTION as Y, TIME_FLAG_DESCRIPTION as Z, reportSendCommandResult as _, queryUsesAwaiting as _t, assertValidIdempotencyKey as a, writeErrorWithHints as at, sentHistoryWindowStart as b, AUTOMATED_FILTER_UNSUPPORTED_CODE as bt, checkPriorReplies as c, REPLY_STATE_UNSUPPORTED_CODE as ct, formatDeletedEarlierSendNotice as d, awaitingRejectedError as dt, extractErrorPayload as et, formatPriorRepliesCheckSkipped as f, ensureSearchReportsReplyState as ft, priorRepliesThatWentOut as g, isAwaitingRejectedError as gt, formatSendRecordFailureSummary as h, hasReplyState as ht, apiResultHttpStatus as i, surfaceUnauthorizedHint as it, followEmailConversation as j, SAVED_CLI_OAUTH_SESSION_EXPIRED_MESSAGE as jt, openSharedMailStore as k, isAutomatedRejectedError as kt, classifySendError as l, ReplyStateUnsupportedError as lt, formatSendFailureSummary as m, formatRepliesCell as mt, IDEMPOTENCY_KEY_FLAG_DESCRIPTION as n, readTextFileFlag as nt, buildFollowUpCommand as o, AWAITING_FLAG_DESCRIPTION as ot, formatPriorRepliesWarning as p, formatAwaitingCell as pt, pullFile as q, SEND_OUTCOME_HELP as r, runWithTiming as rt, buildThrownSendFailureEnvelope as s, AWAITING_VALUES as st, sendSignal as t, formatErrorPayload as tt, deriveSendIdempotencyKey as u, assertAwaitingFilterRows as ut, sendIdentityFields as v, formatAlreadySentNotice as vt, reconcileChatSend as w, assertAutomatedVerdict as wt, serializeErrorPayload as x, AUTOMATED_FLAG_DESCRIPTION as xt, sendOutcomeExitCode as y, writeIdempotentReplayBannerIfReplay as yt, readThreadContext as z };
2956
+ export { EventConnection as C, pushFile as E, readSharedMailOwner as S, pullFile as T, readThreadContext as _, ensureSharedMailSubscription as a, serverRelationship as b, reserveSharedMailSubscription as c, otherParticipants as d, bareAddress as f, latestOwnOutbound as g, formatWakeContext as h, sharedMailScope as i, followEmailConversation as l, displayAddress as m, reconcileChatSend as n, createSharedMailWaiter as o, describeWake as p, openSharedMailReceiver as r, openSharedMailStore as s, sendSignal as t, readConversationFollow as u, sentInThread as v, EventReceiverError as w, wakeRelationship as x, serverMuted as y };