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,8 +1,607 @@
1
- import { c as loadConnectedAgentProfile, d as requireDefaultLoginProfile, m as createConfig, n as AgentConnectionSetupError, o as connectedAgentIdentity, p as createClient, r as agentProfileDirectory } from "./connected-agent-profile-8tpOMdq3.js";
1
+ 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-SPPcis9g.js";
2
2
  import { Errors } from "@oclif/core";
3
3
  import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { dirname, join } from "node:path";
6
+ //#region ../packages/api-core/src/api/core/bodySerializer.gen.ts
7
+ const jsonBodySerializer = { bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value) };
8
+ //#endregion
9
+ //#region ../packages/api-core/src/api/core/serverSentEvents.gen.ts
10
+ function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
11
+ let lastEventId;
12
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
13
+ const createStream = async function* () {
14
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
15
+ let attempt = 0;
16
+ const signal = options.signal ?? new AbortController().signal;
17
+ while (true) {
18
+ if (signal.aborted) break;
19
+ attempt++;
20
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
21
+ if (lastEventId !== void 0) headers.set("Last-Event-ID", lastEventId);
22
+ try {
23
+ const requestInit = {
24
+ redirect: "follow",
25
+ ...options,
26
+ body: options.serializedBody,
27
+ headers,
28
+ signal
29
+ };
30
+ let request = new Request(url, requestInit);
31
+ if (onRequest) request = await onRequest(url, requestInit);
32
+ const response = await (options.fetch ?? globalThis.fetch)(request);
33
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
34
+ if (!response.body) throw new Error("No body in SSE response");
35
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
36
+ let buffer = "";
37
+ const abortHandler = () => {
38
+ try {
39
+ reader.cancel();
40
+ } catch {}
41
+ };
42
+ signal.addEventListener("abort", abortHandler);
43
+ try {
44
+ while (true) {
45
+ const { done, value } = await reader.read();
46
+ if (done) break;
47
+ buffer += value;
48
+ buffer = buffer.replace(/\r\n?/g, "\n");
49
+ const chunks = buffer.split("\n\n");
50
+ buffer = chunks.pop() ?? "";
51
+ for (const chunk of chunks) {
52
+ const lines = chunk.split("\n");
53
+ const dataLines = [];
54
+ let eventName;
55
+ for (const line of lines) if (line.startsWith("data:")) dataLines.push(line.replace(/^data:\s*/, ""));
56
+ else if (line.startsWith("event:")) eventName = line.replace(/^event:\s*/, "");
57
+ else if (line.startsWith("id:")) lastEventId = line.replace(/^id:\s*/, "");
58
+ else if (line.startsWith("retry:")) {
59
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
60
+ if (!Number.isNaN(parsed)) retryDelay = parsed;
61
+ }
62
+ let data;
63
+ let parsedJson = false;
64
+ if (dataLines.length) {
65
+ const rawData = dataLines.join("\n");
66
+ try {
67
+ data = JSON.parse(rawData);
68
+ parsedJson = true;
69
+ } catch {
70
+ data = rawData;
71
+ }
72
+ }
73
+ if (parsedJson) {
74
+ if (responseValidator) await responseValidator(data);
75
+ if (responseTransformer) data = await responseTransformer(data);
76
+ }
77
+ onSseEvent?.({
78
+ data,
79
+ event: eventName,
80
+ id: lastEventId,
81
+ retry: retryDelay
82
+ });
83
+ if (dataLines.length) yield data;
84
+ }
85
+ }
86
+ } finally {
87
+ signal.removeEventListener("abort", abortHandler);
88
+ reader.releaseLock();
89
+ }
90
+ break;
91
+ } catch (error) {
92
+ onSseError?.(error);
93
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) break;
94
+ await sleep(Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4));
95
+ }
96
+ }
97
+ };
98
+ return { stream: createStream() };
99
+ }
100
+ //#endregion
101
+ //#region ../packages/api-core/src/api/core/pathSerializer.gen.ts
102
+ const separatorArrayExplode = (style) => {
103
+ switch (style) {
104
+ case "label": return ".";
105
+ case "matrix": return ";";
106
+ case "simple": return ",";
107
+ default: return "&";
108
+ }
109
+ };
110
+ const separatorArrayNoExplode = (style) => {
111
+ switch (style) {
112
+ case "form": return ",";
113
+ case "pipeDelimited": return "|";
114
+ case "spaceDelimited": return "%20";
115
+ default: return ",";
116
+ }
117
+ };
118
+ const separatorObjectExplode = (style) => {
119
+ switch (style) {
120
+ case "label": return ".";
121
+ case "matrix": return ";";
122
+ case "simple": return ",";
123
+ default: return "&";
124
+ }
125
+ };
126
+ const serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
127
+ if (!explode) {
128
+ const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
129
+ switch (style) {
130
+ case "label": return `.${joinedValues}`;
131
+ case "matrix": return `;${name}=${joinedValues}`;
132
+ case "simple": return joinedValues;
133
+ default: return `${name}=${joinedValues}`;
134
+ }
135
+ }
136
+ const separator = separatorArrayExplode(style);
137
+ const joinedValues = value.map((v) => {
138
+ if (style === "label" || style === "simple") return allowReserved ? v : encodeURIComponent(v);
139
+ return serializePrimitiveParam({
140
+ allowReserved,
141
+ name,
142
+ value: v
143
+ });
144
+ }).join(separator);
145
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
146
+ };
147
+ const serializePrimitiveParam = ({ allowReserved, name, value }) => {
148
+ if (value === void 0 || value === null) return "";
149
+ if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
150
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
151
+ };
152
+ const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => {
153
+ if (value instanceof Date) return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
154
+ if (style !== "deepObject" && !explode) {
155
+ let values = [];
156
+ Object.entries(value).forEach(([key, v]) => {
157
+ values = [
158
+ ...values,
159
+ key,
160
+ allowReserved ? v : encodeURIComponent(v)
161
+ ];
162
+ });
163
+ const joinedValues = values.join(",");
164
+ switch (style) {
165
+ case "form": return `${name}=${joinedValues}`;
166
+ case "label": return `.${joinedValues}`;
167
+ case "matrix": return `;${name}=${joinedValues}`;
168
+ default: return joinedValues;
169
+ }
170
+ }
171
+ const separator = separatorObjectExplode(style);
172
+ const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
173
+ allowReserved,
174
+ name: style === "deepObject" ? `${name}[${key}]` : key,
175
+ value: v
176
+ })).join(separator);
177
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
178
+ };
179
+ //#endregion
180
+ //#region ../packages/api-core/src/api/core/utils.gen.ts
181
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
182
+ const defaultPathSerializer = ({ path, url: _url }) => {
183
+ let url = _url;
184
+ const matches = _url.match(PATH_PARAM_RE);
185
+ if (matches) for (const match of matches) {
186
+ let explode = false;
187
+ let name = match.substring(1, match.length - 1);
188
+ let style = "simple";
189
+ if (name.endsWith("*")) {
190
+ explode = true;
191
+ name = name.substring(0, name.length - 1);
192
+ }
193
+ if (name.startsWith(".")) {
194
+ name = name.substring(1);
195
+ style = "label";
196
+ } else if (name.startsWith(";")) {
197
+ name = name.substring(1);
198
+ style = "matrix";
199
+ }
200
+ const value = path[name];
201
+ if (value === void 0 || value === null) continue;
202
+ if (Array.isArray(value)) {
203
+ url = url.replace(match, serializeArrayParam({
204
+ explode,
205
+ name,
206
+ style,
207
+ value
208
+ }));
209
+ continue;
210
+ }
211
+ if (typeof value === "object") {
212
+ url = url.replace(match, serializeObjectParam({
213
+ explode,
214
+ name,
215
+ style,
216
+ value,
217
+ valueOnly: true
218
+ }));
219
+ continue;
220
+ }
221
+ if (style === "matrix") {
222
+ url = url.replace(match, `;${serializePrimitiveParam({
223
+ name,
224
+ value
225
+ })}`);
226
+ continue;
227
+ }
228
+ const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
229
+ url = url.replace(match, replaceValue);
230
+ }
231
+ return url;
232
+ };
233
+ const getUrl = ({ baseUrl, path, query, querySerializer, url: _url }) => {
234
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
235
+ let url = (baseUrl ?? "") + pathUrl;
236
+ if (path) url = defaultPathSerializer({
237
+ path,
238
+ url
239
+ });
240
+ let search = query ? querySerializer(query) : "";
241
+ if (search.startsWith("?")) search = search.substring(1);
242
+ if (search) url += `?${search}`;
243
+ return url;
244
+ };
245
+ function getValidRequestBody(options) {
246
+ const hasBody = options.body !== void 0;
247
+ if (hasBody && options.bodySerializer) {
248
+ if ("serializedBody" in options) return options.serializedBody !== void 0 && options.serializedBody !== "" ? options.serializedBody : null;
249
+ return options.body !== "" ? options.body : null;
250
+ }
251
+ if (hasBody) return options.body;
252
+ }
253
+ //#endregion
254
+ //#region ../packages/api-core/src/api/core/auth.gen.ts
255
+ const getAuthToken = async (auth, callback) => {
256
+ const token = typeof callback === "function" ? await callback(auth) : callback;
257
+ if (!token) return;
258
+ if (auth.scheme === "bearer") return `Bearer ${token}`;
259
+ if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
260
+ return token;
261
+ };
262
+ //#endregion
263
+ //#region ../packages/api-core/src/api/client/utils.gen.ts
264
+ const createQuerySerializer = ({ parameters = {}, ...args } = {}) => {
265
+ const querySerializer = (queryParams) => {
266
+ const search = [];
267
+ if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
268
+ const value = queryParams[name];
269
+ if (value === void 0 || value === null) continue;
270
+ const options = parameters[name] || args;
271
+ if (Array.isArray(value)) {
272
+ const serializedArray = serializeArrayParam({
273
+ allowReserved: options.allowReserved,
274
+ explode: true,
275
+ name,
276
+ style: "form",
277
+ value,
278
+ ...options.array
279
+ });
280
+ if (serializedArray) search.push(serializedArray);
281
+ } else if (typeof value === "object") {
282
+ const serializedObject = serializeObjectParam({
283
+ allowReserved: options.allowReserved,
284
+ explode: true,
285
+ name,
286
+ style: "deepObject",
287
+ value,
288
+ ...options.object
289
+ });
290
+ if (serializedObject) search.push(serializedObject);
291
+ } else {
292
+ const serializedPrimitive = serializePrimitiveParam({
293
+ allowReserved: options.allowReserved,
294
+ name,
295
+ value
296
+ });
297
+ if (serializedPrimitive) search.push(serializedPrimitive);
298
+ }
299
+ }
300
+ return search.join("&");
301
+ };
302
+ return querySerializer;
303
+ };
304
+ /**
305
+ * Infers parseAs value from provided Content-Type header.
306
+ */
307
+ const getParseAs = (contentType) => {
308
+ if (!contentType) return "stream";
309
+ const cleanContent = contentType.split(";")[0]?.trim();
310
+ if (!cleanContent) return;
311
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) return "json";
312
+ if (cleanContent === "multipart/form-data") return "formData";
313
+ if ([
314
+ "application/",
315
+ "audio/",
316
+ "image/",
317
+ "video/"
318
+ ].some((type) => cleanContent.startsWith(type))) return "blob";
319
+ if (cleanContent.startsWith("text/")) return "text";
320
+ };
321
+ const checkForExistence = (options, name) => {
322
+ if (!name) return false;
323
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) return true;
324
+ return false;
325
+ };
326
+ async function setAuthParams(options) {
327
+ for (const auth of options.security ?? []) {
328
+ if (checkForExistence(options, auth.name)) continue;
329
+ const token = await getAuthToken(auth, options.auth);
330
+ if (!token) continue;
331
+ const name = auth.name ?? "Authorization";
332
+ switch (auth.in) {
333
+ case "query":
334
+ if (!options.query) options.query = {};
335
+ options.query[name] = token;
336
+ break;
337
+ case "cookie":
338
+ options.headers.append("Cookie", `${name}=${token}`);
339
+ break;
340
+ default:
341
+ options.headers.set(name, token);
342
+ break;
343
+ }
344
+ }
345
+ }
346
+ const buildUrl = (options) => getUrl({
347
+ baseUrl: options.baseUrl,
348
+ path: options.path,
349
+ query: options.query,
350
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
351
+ url: options.url
352
+ });
353
+ const mergeConfigs = (a, b) => {
354
+ const config = {
355
+ ...a,
356
+ ...b
357
+ };
358
+ if (config.baseUrl?.endsWith("/")) config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
359
+ config.headers = mergeHeaders(a.headers, b.headers);
360
+ return config;
361
+ };
362
+ const headersEntries = (headers) => {
363
+ const entries = [];
364
+ headers.forEach((value, key) => {
365
+ entries.push([key, value]);
366
+ });
367
+ return entries;
368
+ };
369
+ const mergeHeaders = (...headers) => {
370
+ const mergedHeaders = new Headers();
371
+ for (const header of headers) {
372
+ if (!header) continue;
373
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
374
+ for (const [key, value] of iterator) if (value === null) mergedHeaders.delete(key);
375
+ else if (Array.isArray(value)) for (const v of value) mergedHeaders.append(key, v);
376
+ else if (value !== void 0) mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
377
+ }
378
+ return mergedHeaders;
379
+ };
380
+ var Interceptors = class {
381
+ fns = [];
382
+ clear() {
383
+ this.fns = [];
384
+ }
385
+ eject(id) {
386
+ const index = this.getInterceptorIndex(id);
387
+ if (this.fns[index]) this.fns[index] = null;
388
+ }
389
+ exists(id) {
390
+ const index = this.getInterceptorIndex(id);
391
+ return Boolean(this.fns[index]);
392
+ }
393
+ getInterceptorIndex(id) {
394
+ if (typeof id === "number") return this.fns[id] ? id : -1;
395
+ return this.fns.indexOf(id);
396
+ }
397
+ update(id, fn) {
398
+ const index = this.getInterceptorIndex(id);
399
+ if (this.fns[index]) {
400
+ this.fns[index] = fn;
401
+ return id;
402
+ }
403
+ return false;
404
+ }
405
+ use(fn) {
406
+ this.fns.push(fn);
407
+ return this.fns.length - 1;
408
+ }
409
+ };
410
+ const createInterceptors = () => ({
411
+ error: new Interceptors(),
412
+ request: new Interceptors(),
413
+ response: new Interceptors()
414
+ });
415
+ const defaultQuerySerializer = createQuerySerializer({
416
+ allowReserved: false,
417
+ array: {
418
+ explode: true,
419
+ style: "form"
420
+ },
421
+ object: {
422
+ explode: true,
423
+ style: "deepObject"
424
+ }
425
+ });
426
+ const defaultHeaders = { "Content-Type": "application/json" };
427
+ const createConfig = (override = {}) => ({
428
+ ...jsonBodySerializer,
429
+ headers: defaultHeaders,
430
+ parseAs: "auto",
431
+ querySerializer: defaultQuerySerializer,
432
+ ...override
433
+ });
434
+ //#endregion
435
+ //#region ../packages/api-core/src/api/client/client.gen.ts
436
+ const createClient = (config = {}) => {
437
+ let _config = mergeConfigs(createConfig(), config);
438
+ const getConfig = () => ({ ..._config });
439
+ const setConfig = (config) => {
440
+ _config = mergeConfigs(_config, config);
441
+ return getConfig();
442
+ };
443
+ const interceptors = createInterceptors();
444
+ const beforeRequest = async (options) => {
445
+ const opts = {
446
+ ..._config,
447
+ ...options,
448
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
449
+ headers: mergeHeaders(_config.headers, options.headers),
450
+ serializedBody: void 0
451
+ };
452
+ if (opts.security) await setAuthParams(opts);
453
+ if (opts.requestValidator) await opts.requestValidator(opts);
454
+ if (opts.body !== void 0 && opts.bodySerializer) opts.serializedBody = opts.bodySerializer(opts.body);
455
+ if (opts.body === void 0 || opts.serializedBody === "") opts.headers.delete("Content-Type");
456
+ const resolvedOpts = opts;
457
+ return {
458
+ opts: resolvedOpts,
459
+ url: buildUrl(resolvedOpts)
460
+ };
461
+ };
462
+ const request = async (options) => {
463
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
464
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
465
+ let request;
466
+ let response;
467
+ try {
468
+ const { opts, url } = await beforeRequest(options);
469
+ const requestInit = {
470
+ redirect: "follow",
471
+ ...opts,
472
+ body: getValidRequestBody(opts)
473
+ };
474
+ request = new Request(url, requestInit);
475
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
476
+ const _fetch = opts.fetch;
477
+ response = await _fetch(request);
478
+ for (const fn of interceptors.response.fns) if (fn) response = await fn(response, request, opts);
479
+ const result = {
480
+ request,
481
+ response
482
+ };
483
+ if (response.ok) {
484
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
485
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
486
+ let emptyData;
487
+ switch (parseAs) {
488
+ case "arrayBuffer":
489
+ case "blob":
490
+ case "text":
491
+ emptyData = await response[parseAs]();
492
+ break;
493
+ case "formData":
494
+ emptyData = new FormData();
495
+ break;
496
+ case "stream":
497
+ emptyData = response.body;
498
+ break;
499
+ default:
500
+ emptyData = {};
501
+ break;
502
+ }
503
+ return opts.responseStyle === "data" ? emptyData : {
504
+ data: emptyData,
505
+ ...result
506
+ };
507
+ }
508
+ let data;
509
+ switch (parseAs) {
510
+ case "arrayBuffer":
511
+ case "blob":
512
+ case "formData":
513
+ case "text":
514
+ data = await response[parseAs]();
515
+ break;
516
+ case "json": {
517
+ const text = await response.text();
518
+ data = text ? JSON.parse(text) : {};
519
+ break;
520
+ }
521
+ case "stream": return opts.responseStyle === "data" ? response.body : {
522
+ data: response.body,
523
+ ...result
524
+ };
525
+ }
526
+ if (parseAs === "json") {
527
+ if (opts.responseValidator) await opts.responseValidator(data);
528
+ if (opts.responseTransformer) data = await opts.responseTransformer(data);
529
+ }
530
+ return opts.responseStyle === "data" ? data : {
531
+ data,
532
+ ...result
533
+ };
534
+ }
535
+ const textError = await response.text();
536
+ let jsonError;
537
+ try {
538
+ jsonError = JSON.parse(textError);
539
+ } catch {}
540
+ throw jsonError ?? textError;
541
+ } catch (error) {
542
+ let finalError = error;
543
+ for (const fn of interceptors.error.fns) if (fn) finalError = await fn(finalError, response, request, options);
544
+ finalError = finalError || {};
545
+ if (throwOnError) throw finalError;
546
+ return responseStyle === "data" ? void 0 : {
547
+ error: finalError,
548
+ request,
549
+ response
550
+ };
551
+ }
552
+ };
553
+ const makeMethodFn = (method) => (options) => request({
554
+ ...options,
555
+ method
556
+ });
557
+ const makeSseFn = (method) => async (options) => {
558
+ const { opts, url } = await beforeRequest(options);
559
+ return createSseClient({
560
+ ...opts,
561
+ body: opts.body,
562
+ method,
563
+ onRequest: async (url, init) => {
564
+ let request = new Request(url, init);
565
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
566
+ return request;
567
+ },
568
+ serializedBody: getValidRequestBody(opts),
569
+ url
570
+ });
571
+ };
572
+ const _buildUrl = (options) => buildUrl({
573
+ ..._config,
574
+ ...options
575
+ });
576
+ return {
577
+ buildUrl: _buildUrl,
578
+ connect: makeMethodFn("CONNECT"),
579
+ delete: makeMethodFn("DELETE"),
580
+ get: makeMethodFn("GET"),
581
+ getConfig,
582
+ head: makeMethodFn("HEAD"),
583
+ interceptors,
584
+ options: makeMethodFn("OPTIONS"),
585
+ patch: makeMethodFn("PATCH"),
586
+ post: makeMethodFn("POST"),
587
+ put: makeMethodFn("PUT"),
588
+ request,
589
+ setConfig,
590
+ sse: {
591
+ connect: makeSseFn("CONNECT"),
592
+ delete: makeSseFn("DELETE"),
593
+ get: makeSseFn("GET"),
594
+ head: makeSseFn("HEAD"),
595
+ options: makeSseFn("OPTIONS"),
596
+ patch: makeSseFn("PATCH"),
597
+ post: makeSseFn("POST"),
598
+ put: makeSseFn("PUT"),
599
+ trace: makeSseFn("TRACE")
600
+ },
601
+ trace: makeMethodFn("TRACE")
602
+ };
603
+ };
604
+ //#endregion
6
605
  //#region ../packages/api-core/src/client.ts
7
606
  /**
8
607
  * Host-aware Primitive API client and shared error type.
@@ -38,6 +637,134 @@ var PrimitiveApiClient = class {
38
637
  }
39
638
  };
40
639
  //#endregion
640
+ //#region src/oclif/connected-agent-profile.ts
641
+ const AGENT_PROFILE_ENV = "PRIMITIVE_AGENT_PROFILE";
642
+ function parsePresenceProfile(value, owner) {
643
+ const row = mailObject(value, [
644
+ "protocol",
645
+ "version",
646
+ "authentication_profile",
647
+ "return_address"
648
+ ]);
649
+ 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.");
650
+ return {
651
+ protocol: "primitive.presence",
652
+ version: 1,
653
+ authentication_profile: "primitive-issued-v1",
654
+ return_address: owner
655
+ };
656
+ }
657
+ function supportedPresenceProfile(value, owner) {
658
+ if (value === void 0) return void 0;
659
+ try {
660
+ return parsePresenceProfile(value, owner);
661
+ } catch {
662
+ return;
663
+ }
664
+ }
665
+ var AgentConnectionSetupError = class extends Error {};
666
+ function requireDefaultLoginProfile() {
667
+ if (process.env["PRIMITIVE_AGENT_PROFILE"]?.trim()) throw new AgentConnectionSetupError("This command manages the default OAuth login. Unset PRIMITIVE_AGENT_PROFILE before using it; the connected-agent profile is unchanged.");
668
+ }
669
+ function agentProfileName(value) {
670
+ 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).");
671
+ return value;
672
+ }
673
+ function connectedApiBaseUrl(value) {
674
+ 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.");
675
+ return value;
676
+ }
677
+ function agentProfilesDirectory(configDir) {
678
+ return join(configDir, "agent-connections");
679
+ }
680
+ function agentProfileDirectory(configDir, profileName) {
681
+ return join(agentProfilesDirectory(configDir), "profiles", agentProfileName(profileName));
682
+ }
683
+ function profilePath(configDir, profileName) {
684
+ return join(agentProfileDirectory(configDir, profileName), "connection.json");
685
+ }
686
+ function parseConnectedAgentProfile(value) {
687
+ try {
688
+ const keys = [
689
+ "version",
690
+ "auth_method",
691
+ "api_key",
692
+ "api_base_url",
693
+ "org_id",
694
+ "agent_address",
695
+ "owner_address",
696
+ "invitation_hash",
697
+ "created_at"
698
+ ];
699
+ const has = (key) => Boolean(value && typeof value === "object" && Object.hasOwn(value, key));
700
+ const row = mailObject(value, [
701
+ ...keys,
702
+ ...has("presence_profile") ? ["presence_profile"] : [],
703
+ ...has("owner_member_address") ? ["owner_member_address"] : []
704
+ ]);
705
+ const apiKey = mailString(row.api_key, 4096);
706
+ const invitationHash = mailString(row.invitation_hash, 64);
707
+ if (row.version !== 1 || row.auth_method !== "agent_connection" || !apiKey.startsWith("pconn_") || /\s/.test(apiKey) || !/^[a-f0-9]{64}$/.test(invitationHash)) throw new Error();
708
+ const presence = supportedPresenceProfile(row.presence_profile, mailAddress(row.owner_address));
709
+ const ownerMember = has("owner_member_address") ? parseOwnerMemberAddress(row.owner_member_address, mailAddress(row.owner_address), mailAddress(row.agent_address)) : void 0;
710
+ return {
711
+ version: 1,
712
+ auth_method: "agent_connection",
713
+ api_key: apiKey,
714
+ api_base_url: connectedApiBaseUrl(row.api_base_url),
715
+ org_id: mailId(row.org_id),
716
+ agent_address: mailAddress(row.agent_address),
717
+ owner_address: mailAddress(row.owner_address),
718
+ ...ownerMember === void 0 ? {} : { owner_member_address: ownerMember },
719
+ invitation_hash: invitationHash,
720
+ created_at: mailTime(row.created_at),
721
+ ...presence === void 0 ? {} : { presence_profile: presence }
722
+ };
723
+ } catch {
724
+ throw new AgentConnectionSetupError("Saved agent profile is invalid. Preserve its private files and request a fresh setup invitation.");
725
+ }
726
+ }
727
+ function loadConnectedAgentProfile(configDir, profileName) {
728
+ agentProfileName(profileName);
729
+ try {
730
+ privateMailDirectory(agentProfilesDirectory(configDir));
731
+ privateMailDirectory(join(agentProfilesDirectory(configDir), "profiles"));
732
+ privateMailDirectory(agentProfileDirectory(configDir, profileName));
733
+ const value = readMailJson(profilePath(configDir, profileName));
734
+ return value === null ? null : parseConnectedAgentProfile(value);
735
+ } catch (error) {
736
+ if (error.code === "ENOENT") return null;
737
+ throw new AgentConnectionSetupError("Cannot read the private agent profile. Check its ownership and permissions without exposing its contents.");
738
+ }
739
+ }
740
+ function saveConnectedAgentProfile(configDir, profileName, profile) {
741
+ const validated = parseConnectedAgentProfile(profile);
742
+ privateMailDirectory(agentProfilesDirectory(configDir), true);
743
+ privateMailDirectory(join(agentProfilesDirectory(configDir), "profiles"), true);
744
+ privateMailDirectory(agentProfileDirectory(configDir, profileName), true);
745
+ writeMailJson(profilePath(configDir, profileName), validated);
746
+ }
747
+ function connectedAgentIdentity(profileName, profile) {
748
+ return {
749
+ profileName,
750
+ orgId: profile.org_id,
751
+ agentAddress: profile.agent_address,
752
+ ownerAddress: profile.owner_address,
753
+ ownerMemberAddress: profile.owner_member_address ?? null,
754
+ apiBaseUrl: profile.api_base_url
755
+ };
756
+ }
757
+ /**
758
+ * Validates a server-reported owner personal address. It is a person's
759
+ * mailbox, so it can never be the control sender or the agent itself.
760
+ */
761
+ function parseOwnerMemberAddress(value, ownerAddress, agentAddress) {
762
+ if (value === null) return null;
763
+ const address = mailAddress(value);
764
+ if (address === ownerAddress || address === agentAddress) throw new Error();
765
+ return address;
766
+ }
767
+ //#endregion
41
768
  //#region src/oclif/chat-state.ts
42
769
  const CHAT_STATE_FILE = "chat-state.json";
43
770
  const CHAT_STATE_VERSION = 2;
@@ -753,4 +1480,4 @@ function redactCliEnvironment(environment) {
753
1480
  };
754
1481
  }
755
1482
  //#endregion
756
- export { saveActiveChatState as A, resolveCliAuth as C, deleteChatState as D, chatStatePath as E, loadActiveChatState as O, normalizeApiBaseUrl as S, saveSignupCredentials as T, deleteCliCredentials as _, normalizeCliEnvironmentName as a, hasStoredCliLogin as b, resolveConfigEnvironment as c, validateCliHeaderName as d, validateCliHeaderValue as f, credentialsPath as g, credentialsLockPath as h, loadCliConfig as i, PrimitiveApiClient as j, loadChatConversationByLocalId 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, saveCliCredentials as w, loadCliCredentials as x, detectPrimitiveKeyEnvMisname as y };
1483
+ export { saveActiveChatState as A, parseOwnerMemberAddress as B, resolveCliAuth as C, deleteChatState as D, chatStatePath as E, agentProfilesDirectory as F, createConfig as G, saveConnectedAgentProfile as H, connectedAgentIdentity as I, connectedApiBaseUrl as L, AgentConnectionSetupError as M, agentProfileDirectory as N, loadActiveChatState as O, agentProfileName as P, loadConnectedAgentProfile as R, normalizeApiBaseUrl as S, saveSignupCredentials as T, PrimitiveApiClient as U, requireDefaultLoginProfile as V, createClient as W, deleteCliCredentials as _, normalizeCliEnvironmentName as a, hasStoredCliLogin 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, loadChatConversationByLocalId 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, saveCliCredentials as w, loadCliCredentials as x, detectPrimitiveKeyEnvMisname as y, parseConnectedAgentProfile as z };