@elisym/cli 0.34.0 → 0.36.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.
package/dist/index.js CHANGED
@@ -1,26 +1,28 @@
1
1
  #!/usr/bin/env -S node --no-deprecation
2
+ import { randomBytes, createHash } from 'node:crypto';
3
+ import { writeFile, readFile, realpath, stat, unlink, readdir, mkdtemp, rm, mkdir, chmod, open, rename, link } from 'node:fs/promises';
4
+ import { dirname, join, resolve, sep, basename, extname, relative } from 'node:path';
5
+ import { nip19, generateSecretKey, getPublicKey, verifyEvent } from 'nostr-tools';
6
+ import { bytesToHex, hexToBytes } from 'nostr-tools/utils';
7
+ import * as nip44 from 'nostr-tools/nip44';
8
+ import { finalizeEvent, generateSecretKey as generateSecretKey$1, getPublicKey as getPublicKey$1, verifyEvent as verifyEvent$1 } from 'nostr-tools/pure';
9
+ import Decimal2 from 'decimal.js-light';
2
10
  import { ReadableStream } from 'node:stream/web';
3
11
  import { readFileSync, existsSync, readdirSync, statSync, realpathSync, renameSync, chmodSync, mkdirSync, writeFileSync, unlinkSync, appendFileSync, rmdirSync } from 'node:fs';
4
- import { dirname, join, resolve, basename, extname, relative, sep } from 'node:path';
5
12
  import { DEFAULTS, SolanaPaymentStrategy, validateAgentName, RELAYS, ElisymIdentity, splAssetsForNetwork, formatSol, formatAssetAmount, deleteControlCharacters, signerFromSecretKeyBase58, resolveUsdcAsset, ElisymClient, KIND_EXTERNAL_IDENTITIES, POLICY_D_TAG_PREFIX, KIND_LONG_FORM_ARTICLE, jobRequestKind, DEFAULT_KIND_OFFSET, toDTag, createBlossomTransport, generateSolanaWallet, verifyAgentIdentities, getProtocolConfig, getProtocolProgramId, calculateProtocolFee, LIMITS, makeCensor, DEFAULT_REDACT_PATHS, flattenForComparison, POLICY_T_TAG, SESSION_ID_REGEX, createSlidingWindowLimiter, excerptUntrusted, isScriptBillingExhaustedError, excerptUntrustedTail, scriptOutput, isScriptExecutionError, utf8ByteLength, readAcceptedTransports, resolveDelegationAsset, MAX_PROOF_TTL_SECS, PROOF_CLOCK_SKEW_SECS, verifyDelegationAuthProof, deriveOwnerDelegationAta, getDelegation, buildDelegatedTransfer, buildSignedPull, sendConfirmToTerminal, parseDelegatedPayment, confirmPullToTerminal, isDefinitelyUnpaid, decodeJobPayload, isLlmHealthError, BoundedSet, KIND_JOB_FEEDBACK, encodeSecretKeyBase58, GITHUB_USERNAME_REGEX, X_USERNAME_REGEX, normalizeNip05Identifier, splitNip05Identifier, clipToCodeUnits, degenerateReference, PROVIDER_REFUSED_PREFIX, PROVIDER_FAILED_MESSAGE, NATIVE_SOL, GIST_ID_REGEX, TWEET_ID_REGEX } from '@elisym/sdk';
6
13
  import { ElisymYamlSchema, resolveInHome, resolveInProject, createAgentDir, writeYamlInitial, writeExampleSkillTemplate, writeSecrets, listAgents, loadAgent, writeYaml, agentPaths, ensureGitignoreHasX402Entries, readMediaCache, ensureGitignoreHasPrivateStateEntries, loadPoliciesFromDir, ensureGitignoreHasDelegationNoncesEntry, ensureGitignoreHasIrohEntry, ensureGitignoreHasSessionsEntry, readAgentPublic, isBlockingNodeSync, AgentNameSchema, lookupCachedUrl, newCacheEntry, isBlockingNode, writeMediaCache } from '@elisym/sdk/agent-store';
7
14
  import { isAddress, createSolanaRpc, address, signature } from '@solana/kit';
8
- import { generateSecretKey, getPublicKey, nip19, verifyEvent } from 'nostr-tools';
9
15
  import YAML2 from 'yaml';
10
- import { Command } from 'commander';
11
- import { hexToBytes, bytesToHex } from 'nostr-tools/utils';
16
+ import { Command, CommanderError } from 'commander';
17
+ import { homedir, tmpdir } from 'node:os';
12
18
  import { parseSkillMd, validateSkillFrontmatter, isHostScratchError, isScriptRefusalError, startsWithRefusalHint, HostScratchError, DEFAULT_X402_MAX_INPUT_BYTES, resolveInsidePathReal, DEFAULT_SCRIPT_TIMEOUT_MS, loadSkillsFromDir, OnchainCallSkill, DynamicScriptSkill as DynamicScriptSkill$1, StaticScriptSkill as StaticScriptSkill$1, StaticFileSkill as StaticFileSkill$1, ScriptSkill as ScriptSkill$1 } from '@elisym/sdk/skills';
13
- import { mkdtemp, writeFile, rm, readFile, mkdir, chmod, rename, readdir, stat } from 'node:fs/promises';
14
19
  import chalk from 'chalk';
15
- import Decimal from 'decimal.js-light';
16
20
  import { decodePaymentRequiredHeader } from '@x402/core/http';
17
- import { createHash, randomBytes } from 'node:crypto';
18
21
  import { LlmHealthMonitor, startLlmRecovery, createFreeLlmLimiterSet, FREE_LLM_GLOBAL_KEY, freeLlmCustomerKey } from '@elisym/sdk/llm-health';
19
22
  import { createIrohTransport } from '@elisym/sdk/node';
20
23
  import { lookup } from 'node:dns/promises';
21
24
  import { Socket } from 'node:net';
22
25
  import pino from 'pino';
23
- import { tmpdir } from 'node:os';
24
26
  import pLimit from 'p-limit';
25
27
  import { x402Client, wrapFetchWithPayment } from '@x402/fetch';
26
28
  import { ExactSvmScheme } from '@x402/svm';
@@ -35,6 +37,2377 @@ var __export = (target, all) => {
35
37
  for (var name in all)
36
38
  __defProp(target, name, { get: all[name], enumerable: true });
37
39
  };
40
+
41
+ // src/commands/askr/errors.ts
42
+ function outcomeOfExit(failure) {
43
+ const error = { code: failure.code };
44
+ if (failure.hint !== void 0) {
45
+ error.hint = failure.hint;
46
+ }
47
+ if (failure.serverMessage !== void 0) {
48
+ error.message = failure.serverMessage;
49
+ }
50
+ return { exitCode: failure.exitCode, output: { ok: false, error, ...failure.fields } };
51
+ }
52
+ var EXIT, AskrExit;
53
+ var init_errors = __esm({
54
+ "src/commands/askr/errors.ts"() {
55
+ EXIT = {
56
+ OK: 0,
57
+ BAD_INPUT: 1,
58
+ KEY: 2,
59
+ REFUSED: 3,
60
+ NOT_DONE: 4,
61
+ LIMIT: 5,
62
+ EXISTING_STORE: 6
63
+ };
64
+ AskrExit = class extends Error {
65
+ exitCode;
66
+ code;
67
+ hint;
68
+ serverMessage;
69
+ fields;
70
+ constructor(exitCode, code, options = {}) {
71
+ super(code);
72
+ this.name = "AskrExit";
73
+ this.exitCode = exitCode;
74
+ this.code = code;
75
+ this.hint = options.hint;
76
+ this.serverMessage = options.message;
77
+ this.fields = options.fields ?? {};
78
+ }
79
+ };
80
+ }
81
+ });
82
+
83
+ // src/commands/askr/constants.ts
84
+ var ASKR_COMMAND, DEADLINE_MS, ADMIN_URL, CONTACT_URL, PRICING_URL, FIND_STORE_ID_URL, UPGRADE, WIDGET_SCRIPT_URL, WIDGET_ELEMENT, API_OVERRIDE_ENV, RELAY_OVERRIDE_ENV, UNSAFE_OVERRIDE_ENV, LOCAL_HOSTS, NOT_AUTHORIZED_MESSAGE, SYNC_BUSY_MESSAGE, STORE_POLL_MS, SYNC_POLL_MS, PROBE_RETRY_MS, MIN_REAL_CALL_MS, PREVIEW_TIMEOUT_MS, NOT_AUTHORIZED_RETRY_MS, MAX_CATALOG_BODY_BYTES, MAX_AHEAD_SECS, ABSENT_WARNING_BPS, ABSENT_WARNING_COUNT, SAMPLE_SIZE, MAX_ISSUES, PROFILE_RE, DEFAULT_PROFILE, POLICY_SLUG_RE;
85
+ var init_constants = __esm({
86
+ "src/commands/askr/constants.ts"() {
87
+ ASKR_COMMAND = "npx -y @elisym/cli@latest askr";
88
+ DEADLINE_MS = 85e3;
89
+ ADMIN_URL = "https://app.askr.elisym.network/admin/";
90
+ CONTACT_URL = "https://askr.elisym.network/contact";
91
+ PRICING_URL = "https://askr.elisym.network/#pricing";
92
+ FIND_STORE_ID_URL = "https://docs.elisym.network/askr/overview#find-your-store-id";
93
+ UPGRADE = {
94
+ howTo: "Message us with your Store ID",
95
+ contact: CONTACT_URL,
96
+ pricing: PRICING_URL,
97
+ findStoreId: FIND_STORE_ID_URL
98
+ };
99
+ WIDGET_SCRIPT_URL = "https://app.askr.elisym.network/widget.js";
100
+ WIDGET_ELEMENT = "askr-chat";
101
+ API_OVERRIDE_ENV = "ELISYM_ASKR_API";
102
+ RELAY_OVERRIDE_ENV = "ELISYM_ASKR_RELAY";
103
+ UNSAFE_OVERRIDE_ENV = "ELISYM_ASKR_UNSAFE_TEST";
104
+ LOCAL_HOSTS = ["localhost", "127.0.0.1"];
105
+ NOT_AUTHORIZED_MESSAGE = "This key is not authorized as a catalog key by the store owner";
106
+ SYNC_BUSY_MESSAGE = "Another catalog sync of this store is running";
107
+ STORE_POLL_MS = 2e3;
108
+ SYNC_POLL_MS = 3e3;
109
+ PROBE_RETRY_MS = 1e4;
110
+ MIN_REAL_CALL_MS = 2e4;
111
+ PREVIEW_TIMEOUT_MS = 7e4;
112
+ NOT_AUTHORIZED_RETRY_MS = 2e3;
113
+ MAX_CATALOG_BODY_BYTES = 8 * 1024 * 1024;
114
+ MAX_AHEAD_SECS = 10 * 60;
115
+ ABSENT_WARNING_BPS = 2e3;
116
+ ABSENT_WARNING_COUNT = 10;
117
+ SAMPLE_SIZE = 20;
118
+ MAX_ISSUES = 20;
119
+ PROFILE_RE = /^[a-z0-9-]{1,32}$/;
120
+ DEFAULT_PROFILE = "default";
121
+ POLICY_SLUG_RE = /^[a-z0-9-]{1,64}$/;
122
+ }
123
+ });
124
+ function profileOf(value) {
125
+ const profile = value ?? DEFAULT_PROFILE;
126
+ if (!PROFILE_RE.test(profile)) {
127
+ throw new AskrExit(EXIT.BAD_INPUT, "bad_flag", {
128
+ hint: "--profile takes 1 to 32 lowercase letters, digits or hyphens"
129
+ });
130
+ }
131
+ return profile;
132
+ }
133
+ function keyDirOf(home) {
134
+ return join(home, ".elisym", ".askr");
135
+ }
136
+ function keyFileOf(home, profile) {
137
+ return join(keyDirOf(home), `${profile}.json`);
138
+ }
139
+ function ownerKeyOf(secretKey, path) {
140
+ const owner = getPublicKey(secretKey);
141
+ return { secretKey, owner, storeId: nip19.npubEncode(owner), path };
142
+ }
143
+ function sleep(ms) {
144
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
145
+ }
146
+ function errorCode(error) {
147
+ if (typeof error === "object" && error !== null && "code" in error) {
148
+ const code = error.code;
149
+ return typeof code === "string" ? code : void 0;
150
+ }
151
+ return void 0;
152
+ }
153
+ function unreadable(path) {
154
+ return new AskrExit(EXIT.KEY, "key_file_unreadable", {
155
+ hint: "the owner key file of this profile cannot be read; restore it from your backup or sign in to the admin",
156
+ fields: { ownerKeyFile: path }
157
+ });
158
+ }
159
+ function withoutBom(text) {
160
+ return text.startsWith("\uFEFF") ? text.slice(1) : text;
161
+ }
162
+ function parseKeyFile(text, path) {
163
+ const parsed = JSON.parse(withoutBom(text));
164
+ if (typeof parsed !== "object" || parsed === null || !("secretKey" in parsed)) {
165
+ throw unreadable(path);
166
+ }
167
+ const secretHex = parsed.secretKey;
168
+ if (typeof secretHex !== "string" || !HEX_KEY_RE.test(secretHex)) {
169
+ throw unreadable(path);
170
+ }
171
+ return ownerKeyOf(hexToBytes(secretHex), path);
172
+ }
173
+ async function readOwnerKey(home, profile) {
174
+ const path = keyFileOf(home, profile);
175
+ const started = Date.now();
176
+ for (; ; ) {
177
+ let text;
178
+ try {
179
+ text = await readFile(path, "utf-8");
180
+ } catch (error) {
181
+ if (errorCode(error) === "ENOENT") {
182
+ return void 0;
183
+ }
184
+ throw unreadable(path);
185
+ }
186
+ try {
187
+ return parseKeyFile(text, path);
188
+ } catch (error) {
189
+ if (error instanceof AskrExit) {
190
+ throw error;
191
+ }
192
+ if (Date.now() - started >= PARTIAL_READ_RETRY_MS) {
193
+ throw unreadable(path);
194
+ }
195
+ await sleep(PARTIAL_READ_STEP_MS);
196
+ }
197
+ }
198
+ }
199
+ async function ensureKeyDir(home) {
200
+ const dir = keyDirOf(home);
201
+ await mkdir(dir, { recursive: true, mode: DIR_MODE });
202
+ const current = await stat(dir);
203
+ if ((current.mode & 511) !== DIR_MODE) {
204
+ await chmod(dir, DIR_MODE);
205
+ }
206
+ }
207
+ function keyFileText(secretKey, now) {
208
+ const owner = getPublicKey(secretKey);
209
+ return `${JSON.stringify(
210
+ {
211
+ version: KEY_FILE_VERSION,
212
+ storeId: nip19.npubEncode(owner),
213
+ owner,
214
+ secretKey: bytesToHex(secretKey),
215
+ createdAt: now
216
+ },
217
+ null,
218
+ 2
219
+ )}
220
+ `;
221
+ }
222
+ async function writeExclusive(path, text) {
223
+ let handle;
224
+ try {
225
+ handle = await open(path, "wx", FILE_MODE);
226
+ } catch (error) {
227
+ if (errorCode(error) === "EEXIST") {
228
+ return false;
229
+ }
230
+ throw error;
231
+ }
232
+ try {
233
+ await handle.writeFile(text, "utf-8");
234
+ await handle.sync();
235
+ } finally {
236
+ await handle.close();
237
+ }
238
+ return true;
239
+ }
240
+ async function saveOwnerKey(home, profile, secretKey, now, ops = DEFAULT_OPS) {
241
+ await ensureKeyDir(home);
242
+ const path = keyFileOf(home, profile);
243
+ const text = keyFileText(secretKey, now);
244
+ const temp = `${path}.tmp.${randomBytes(8).toString("hex")}`;
245
+ await writeFile(temp, text, { encoding: "utf-8", mode: FILE_MODE, flag: "wx" });
246
+ let linked = false;
247
+ try {
248
+ await ops.link(temp, path);
249
+ linked = true;
250
+ } catch (error) {
251
+ const code = errorCode(error);
252
+ if (code === "EPERM" || code === "ENOTSUP") {
253
+ linked = await writeExclusive(path, text);
254
+ } else if (code !== "EEXIST") {
255
+ throw unreadable(path);
256
+ }
257
+ } finally {
258
+ await unlink(temp).catch(() => void 0);
259
+ }
260
+ if (linked) {
261
+ return ownerKeyOf(secretKey, path);
262
+ }
263
+ const existing = await readOwnerKey(home, profile);
264
+ if (existing === void 0) {
265
+ throw unreadable(path);
266
+ }
267
+ return existing;
268
+ }
269
+ function importRefused(hint) {
270
+ return new AskrExit(EXIT.KEY, "key_file_unreadable", { hint: `--owner-key-file: ${hint}` });
271
+ }
272
+ function validKey(secretKey) {
273
+ try {
274
+ getPublicKey(secretKey);
275
+ return secretKey;
276
+ } catch {
277
+ throw importRefused("the key in the file is not a valid secret key");
278
+ }
279
+ }
280
+ function jsonObjectOf(text) {
281
+ let parsed;
282
+ try {
283
+ parsed = JSON.parse(text);
284
+ } catch {
285
+ return void 0;
286
+ }
287
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? { ...parsed } : void 0;
288
+ }
289
+ function keyOfJson(parsed) {
290
+ const secretHex = parsed.secretKey;
291
+ if (typeof secretHex !== "string" || !HEX_KEY_RE.test(secretHex.toLowerCase())) {
292
+ throw importRefused("a JSON key file needs a secretKey of 64 hex characters");
293
+ }
294
+ const secretKey = validKey(hexToBytes(secretHex.toLowerCase()));
295
+ const owner = getPublicKey(secretKey);
296
+ if (parsed.owner !== void 0 && parsed.owner !== owner) {
297
+ throw importRefused("its secretKey does not match its owner");
298
+ }
299
+ if (parsed.storeId !== void 0 && parsed.storeId !== nip19.npubEncode(owner)) {
300
+ throw importRefused("its secretKey does not match its storeId");
301
+ }
302
+ return secretKey;
303
+ }
304
+ function decodedNsec(nsec) {
305
+ try {
306
+ const decoded = nip19.decode(nsec);
307
+ if (decoded.type === "nsec") {
308
+ return decoded.data;
309
+ }
310
+ } catch {
311
+ }
312
+ throw importRefused("the nsec1... key in the file is not valid");
313
+ }
314
+ function keyOfText(text) {
315
+ const candidates = /* @__PURE__ */ new Map();
316
+ for (const nsec of text.match(NSEC_RE) ?? []) {
317
+ const secretKey2 = decodedNsec(nsec);
318
+ candidates.set(bytesToHex(secretKey2), secretKey2);
319
+ }
320
+ for (const hex of text.match(HEX_TOKEN_RE) ?? []) {
321
+ const secretKey2 = hexToBytes(hex.toLowerCase());
322
+ candidates.set(bytesToHex(secretKey2), secretKey2);
323
+ }
324
+ const publicKeys = new Set(
325
+ [...candidates.values()].flatMap((secretKey2) => {
326
+ try {
327
+ return [getPublicKey(secretKey2)];
328
+ } catch {
329
+ return [];
330
+ }
331
+ })
332
+ );
333
+ if (candidates.size > 1) {
334
+ for (const hex of publicKeys) {
335
+ candidates.delete(hex);
336
+ }
337
+ }
338
+ if (candidates.size > 1) {
339
+ throw importRefused("the file holds more than one key: give a file with only the secret key");
340
+ }
341
+ const [secretKey] = candidates.values();
342
+ if (secretKey === void 0) {
343
+ throw importRefused("no nsec1... or 64-character hex secret key found in the file");
344
+ }
345
+ const storeId = nip19.npubEncode(getPublicKey(validKey(secretKey)));
346
+ if ((text.match(NPUB_RE) ?? []).some((npub) => npub !== storeId)) {
347
+ throw importRefused("the Store ID in the file is not the one of its secret key");
348
+ }
349
+ return secretKey;
350
+ }
351
+ async function readImportedKey(path) {
352
+ let text;
353
+ try {
354
+ const info = await stat(path);
355
+ if (!info.isFile() || info.size > MAX_IMPORT_BYTES) {
356
+ throw new Error("not a key file");
357
+ }
358
+ text = withoutBom(await readFile(path, "utf-8"));
359
+ } catch {
360
+ throw importRefused("the file cannot be read, or is not a key file");
361
+ }
362
+ const parsed = jsonObjectOf(text);
363
+ return parsed === void 0 ? keyOfText(text) : keyOfJson(parsed);
364
+ }
365
+ function sameKey(left, right) {
366
+ return bytesToHex(left) === bytesToHex(right);
367
+ }
368
+ var DIR_MODE, FILE_MODE, KEY_FILE_VERSION, HEX_KEY_RE, PARTIAL_READ_RETRY_MS, PARTIAL_READ_STEP_MS, DEFAULT_OPS, NSEC_RE, NPUB_RE, HEX_TOKEN_RE, MAX_IMPORT_BYTES;
369
+ var init_owner_key = __esm({
370
+ "src/commands/askr/owner-key.ts"() {
371
+ init_constants();
372
+ init_errors();
373
+ DIR_MODE = 448;
374
+ FILE_MODE = 384;
375
+ KEY_FILE_VERSION = 1;
376
+ HEX_KEY_RE = /^[0-9a-f]{64}$/;
377
+ PARTIAL_READ_RETRY_MS = 2e3;
378
+ PARTIAL_READ_STEP_MS = 100;
379
+ DEFAULT_OPS = { link };
380
+ NSEC_RE = /nsec1[02-9ac-hj-np-z]{58}/g;
381
+ NPUB_RE = /npub1[02-9ac-hj-np-z]{58}/g;
382
+ HEX_TOKEN_RE = /\b[0-9a-fA-F]{64}\b/g;
383
+ MAX_IMPORT_BYTES = 64 * 1024;
384
+ }
385
+ });
386
+ function notFound(path, flag) {
387
+ return new AskrExit(EXIT.BAD_INPUT, "file_not_found", {
388
+ hint: `${flag}: no readable file at this path`,
389
+ fields: { file: path }
390
+ });
391
+ }
392
+ function secretFile(flag) {
393
+ return new AskrExit(EXIT.KEY, "secret_in_file", {
394
+ hint: `${flag}: this file is or holds an Askr owner key, which is never sent anywhere: name another file`
395
+ });
396
+ }
397
+ async function localKeys(home) {
398
+ let names;
399
+ try {
400
+ names = await readdir(keyDirOf(home));
401
+ } catch {
402
+ return [];
403
+ }
404
+ const keys = await Promise.all(
405
+ names.filter((name) => name.endsWith(KEY_FILE_SUFFIX)).map((name) => name.slice(0, -KEY_FILE_SUFFIX.length)).filter((profile) => PROFILE_RE.test(profile)).map((profile) => readOwnerKey(home, profile).catch(() => void 0))
406
+ );
407
+ return keys.flatMap((key) => key === void 0 ? [] : [key.secretKey]);
408
+ }
409
+ async function realKeyDir(home) {
410
+ try {
411
+ return await realpath(keyDirOf(home));
412
+ } catch {
413
+ return resolve(keyDirOf(home));
414
+ }
415
+ }
416
+ async function readFlagFile(path, flag, home, extraKeys = []) {
417
+ let real;
418
+ try {
419
+ real = await realpath(path);
420
+ if (!(await stat(real)).isFile()) {
421
+ throw new Error("not a file");
422
+ }
423
+ } catch {
424
+ throw notFound(path, flag);
425
+ }
426
+ const keyDir = await realKeyDir(home);
427
+ if (real === keyDir || real.startsWith(`${keyDir}${sep}`)) {
428
+ throw secretFile(flag);
429
+ }
430
+ let text;
431
+ try {
432
+ text = await readFile(real, "utf-8");
433
+ } catch {
434
+ throw notFound(path, flag);
435
+ }
436
+ const lower = text.toLowerCase();
437
+ for (const secretKey of [...await localKeys(home), ...extraKeys]) {
438
+ if (lower.includes(bytesToHex(secretKey)) || lower.includes(nip19.nsecEncode(secretKey))) {
439
+ throw secretFile(flag);
440
+ }
441
+ }
442
+ return text;
443
+ }
444
+ async function fileSize(path, flag) {
445
+ try {
446
+ const info = await stat(path);
447
+ if (info.isFile()) {
448
+ return info.size;
449
+ }
450
+ } catch {
451
+ }
452
+ throw new AskrExit(EXIT.BAD_INPUT, "file_not_found", {
453
+ hint: `${flag}: no readable file at this path`,
454
+ fields: { file: path }
455
+ });
456
+ }
457
+ function invalidFlag(flag, hint) {
458
+ return new AskrExit(EXIT.BAD_INPUT, "invalid_flag", { hint: `${flag}: ${hint}` });
459
+ }
460
+ var KEY_FILE_SUFFIX;
461
+ var init_files = __esm({
462
+ "src/commands/askr/files.ts"() {
463
+ init_constants();
464
+ init_errors();
465
+ init_owner_key();
466
+ KEY_FILE_SUFFIX = ".json";
467
+ }
468
+ });
469
+
470
+ // src/commands/askr/store.ts
471
+ async function useOwnerKey(session) {
472
+ const key = await readOwnerKey(session.deps.home, session.profile);
473
+ if (key === void 0) {
474
+ throw new AskrExit(EXIT.KEY, "no_key", {
475
+ hint: `this computer has no Askr owner key for the profile "${session.profile}": ${INIT_FIRST_HINT}`
476
+ });
477
+ }
478
+ session.signAs(key.secretKey);
479
+ return key;
480
+ }
481
+ function tierOf(view) {
482
+ return view.tier === null ? null : { name: view.tier.name, maxProducts: view.tier.maxProducts, branding: view.tier.branding };
483
+ }
484
+ function awaitingPlanOf(view) {
485
+ return view.status === "pending" && view.tier === null;
486
+ }
487
+ function planHintOf(view) {
488
+ return awaitingPlanOf(view) ? CHOOSE_PLAN_HINT : CONTACT_HINT;
489
+ }
490
+ function inactiveExit(view, exitCode = EXIT.LIMIT) {
491
+ return new AskrExit(exitCode, "inactive", {
492
+ hint: `the store is ${view.status}, not active: ${planHintOf(view)}`,
493
+ fields: { status: view.status, awaitingPlan: awaitingPlanOf(view), upgrade: UPGRADE }
494
+ });
495
+ }
496
+ function movedExit(fields) {
497
+ return new AskrExit(EXIT.REFUSED, "moved_store", {
498
+ hint: MOVED_HINT,
499
+ ...fields === void 0 ? {} : { fields }
500
+ });
501
+ }
502
+ function serverMessage(result) {
503
+ if (result.ok) {
504
+ return void 0;
505
+ }
506
+ const message = result.detail.message;
507
+ return typeof message === "string" ? message : void 0;
508
+ }
509
+ function refusalExit(session, result) {
510
+ if (result.ok) {
511
+ return new AskrExit(EXIT.REFUSED, "unexpected");
512
+ }
513
+ const message = serverMessage(result);
514
+ const fields = { status: result.status };
515
+ if (result.status === 401) {
516
+ const reason = typeof result.detail.reason === "string" ? result.detail.reason : "unknown";
517
+ return new AskrExit(EXIT.REFUSED, reason === "stale" ? "stale" : "unauthorized", {
518
+ hint: UNAUTHORIZED_HINTS[reason] ?? "the server did not accept the signed request",
519
+ fields: { ...fields, reason }
520
+ });
521
+ }
522
+ if (result.status === 409 && result.code === "moved") {
523
+ return movedExit();
524
+ }
525
+ if (result.status === 404 && result.code === "no_store") {
526
+ return new AskrExit(EXIT.BAD_INPUT, "no_store", { hint: INIT_FIRST_HINT });
527
+ }
528
+ if (result.status === 429) {
529
+ return session.notDone("rate_limited", {
530
+ hint: "the server asked to slow down: run the resume command in about a minute",
531
+ fields: { retryAfterSeconds: 60 }
532
+ });
533
+ }
534
+ if (result.status >= 500 || result.status === 0) {
535
+ return session.notDone(result.code === "unexpected" ? "unavailable" : result.code, {
536
+ hint: "the Askr server is not available just now: run the resume command in about a minute",
537
+ ...message === void 0 ? {} : { message }
538
+ });
539
+ }
540
+ return new AskrExit(EXIT.REFUSED, result.code, {
541
+ ...message === void 0 ? {} : { message },
542
+ fields
543
+ });
544
+ }
545
+ async function readView(session) {
546
+ const result = await session.call("GET", "/v1/admin/store");
547
+ if (!result.ok) {
548
+ throw refusalExit(session, result);
549
+ }
550
+ return result.body;
551
+ }
552
+ async function waitPublished(session, first, onStopped) {
553
+ let view = first;
554
+ for (; ; ) {
555
+ if (view.events.failing.some((event) => event.stopped)) {
556
+ throw onStopped(view);
557
+ }
558
+ if (view.events.pending === 0) {
559
+ return { view, published: true };
560
+ }
561
+ if (session.remaining() <= STORE_POLL_MS) {
562
+ return { view, published: false };
563
+ }
564
+ await session.sleep(STORE_POLL_MS);
565
+ view = await readView(session);
566
+ }
567
+ }
568
+ function stoppedKinds(view) {
569
+ return view.events.failing.filter((event) => event.stopped).map((event) => event.kind);
570
+ }
571
+ var CHOOSE_PLAN_HINT, CONTACT_HINT, INIT_FIRST_HINT, CLOCK_HINT, UNAUTHORIZED_HINTS, MOVED_HINT;
572
+ var init_store = __esm({
573
+ "src/commands/askr/store.ts"() {
574
+ init_constants();
575
+ init_errors();
576
+ init_owner_key();
577
+ CHOOSE_PLAN_HINT = "choose a plan: askr plan free (only if the human chose Free), or message us with your Store ID for a paid plan";
578
+ CONTACT_HINT = `message us with your Store ID: ${CONTACT_URL}`;
579
+ INIT_FIRST_HINT = "run askr init first";
580
+ CLOCK_HINT = "check this computer's clock: it is off by more than a minute";
581
+ UNAUTHORIZED_HINTS = {
582
+ stale: CLOCK_HINT,
583
+ url: "the server is reached at another address than it signs for"
584
+ };
585
+ MOVED_HINT = "this key's store moved: finish the move in the admin, it shows the old settings to check and sign";
586
+ }
587
+ });
588
+ function isEventShaped(value) {
589
+ if (typeof value !== "object" || value === null) {
590
+ return false;
591
+ }
592
+ const event = value;
593
+ return typeof event.id === "string" && typeof event.pubkey === "string" && typeof event.created_at === "number" && typeof event.kind === "number" && typeof event.content === "string" && typeof event.sig === "string" && Array.isArray(event.tags) && event.tags.every(
594
+ (tag) => Array.isArray(tag) && tag.every((part) => typeof part === "string")
595
+ );
596
+ }
597
+ function verifies(event) {
598
+ try {
599
+ return verifyEvent$1(event);
600
+ } catch {
601
+ return false;
602
+ }
603
+ }
604
+ function genuine(events, author, now) {
605
+ return events.flatMap((value) => {
606
+ if (!isEventShaped(value)) {
607
+ return [];
608
+ }
609
+ const event = {
610
+ id: value.id,
611
+ pubkey: value.pubkey,
612
+ created_at: value.created_at,
613
+ kind: value.kind,
614
+ tags: value.tags.map((tag) => [...tag]),
615
+ content: value.content,
616
+ sig: value.sig
617
+ };
618
+ return event.pubkey === author && event.created_at <= now + MAX_AHEAD_SECS && verifies(event) ? [event] : [];
619
+ });
620
+ }
621
+ function dOf(event) {
622
+ return event.tags.find((tag) => tag[0] === "d")?.[1];
623
+ }
624
+ function isNewer(candidate, current) {
625
+ return candidate.created_at > current.created_at || candidate.created_at === current.created_at && candidate.id < current.id;
626
+ }
627
+ function newestPerD(events, kind) {
628
+ const newest = /* @__PURE__ */ new Map();
629
+ for (const event of events) {
630
+ const d = dOf(event);
631
+ if (event.kind !== kind || d === void 0) {
632
+ continue;
633
+ }
634
+ const current = newest.get(d);
635
+ if (current === void 0 || isNewer(event, current)) {
636
+ newest.set(d, event);
637
+ }
638
+ }
639
+ return newest;
640
+ }
641
+ function deletedAfter(event, deletions) {
642
+ const address7 = `${event.kind}:${event.pubkey}:${dOf(event) ?? ""}`;
643
+ return deletions.some(
644
+ (deletion) => deletion.created_at >= event.created_at && deletion.tags.some((tag) => tag[0] === "a" && tag[1] === address7)
645
+ );
646
+ }
647
+ async function readSigned(session, owner, secretKey) {
648
+ const { askr } = session;
649
+ const now = session.nowSecs();
650
+ const relayEvents = await session.relayQuery({
651
+ kinds: [askr.KIND_CONFIG, askr.KIND_CATALOG_AUTH, KIND_DELETION],
652
+ authors: [owner]
653
+ });
654
+ const stored = await session.call("GET", "/v1/admin/store/events");
655
+ if (!stored.ok) {
656
+ throw refusalExit(session, stored);
657
+ }
658
+ const storedEvents = Array.isArray(stored.body.events) ? stored.body.events : [];
659
+ const seen = /* @__PURE__ */ new Set();
660
+ const events = genuine([...relayEvents, ...storedEvents], owner, now).filter((event) => {
661
+ if (seen.has(event.id)) {
662
+ return false;
663
+ }
664
+ seen.add(event.id);
665
+ return true;
666
+ });
667
+ const configs = events.filter((event) => event.kind === askr.KIND_CONFIG && dOf(event) === askr.CONFIG_D_TAG).sort((left, right) => isNewer(left, right) ? -1 : 1);
668
+ let config;
669
+ for (const event of configs) {
670
+ config = askr.parseConfig(event);
671
+ if (config !== void 0) {
672
+ break;
673
+ }
674
+ }
675
+ const privatePart = config === void 0 ? void 0 : await askr.decryptPrivateConfigWith(
676
+ config,
677
+ async (ciphertext, peer) => nip44.v2.decrypt(ciphertext, nip44.v2.utils.getConversationKey(secretKey, peer))
678
+ );
679
+ const authNewestAt = /* @__PURE__ */ new Map();
680
+ for (const [key, event] of newestPerD(events, askr.KIND_CATALOG_AUTH)) {
681
+ authNewestAt.set(key, event.created_at);
682
+ }
683
+ return {
684
+ config,
685
+ privatePart,
686
+ authorized: askr.readCatalogAuthority(events, owner, now),
687
+ authNewestAt
688
+ };
689
+ }
690
+ async function readListings(session, key) {
691
+ const events = genuine(
692
+ await session.relayQuery({ kinds: [KIND_PRODUCT, KIND_DELETION], authors: [key] }),
693
+ key,
694
+ Number.POSITIVE_INFINITY
695
+ );
696
+ const deletions = events.filter((event) => event.kind === KIND_DELETION);
697
+ const live = [...newestPerD(events, KIND_PRODUCT)].filter(
698
+ ([, event]) => !deletedAfter(event, deletions)
699
+ );
700
+ return {
701
+ listed: live.map(([d]) => d),
702
+ visible: live.filter(
703
+ ([, event]) => !event.tags.some((tag) => tag[0] === "visibility" && tag[1] === "hidden")
704
+ ).length
705
+ };
706
+ }
707
+ async function readPolicySlugs(session, key) {
708
+ const { askr } = session;
709
+ const events = genuine(
710
+ await session.relayQuery({ kinds: [askr.KIND_POLICY, KIND_DELETION], authors: [key] }),
711
+ key,
712
+ session.nowSecs()
713
+ );
714
+ const deletions = events.filter((event) => event.kind === KIND_DELETION);
715
+ return [...newestPerD(events, askr.KIND_POLICY)].filter(([, event]) => !deletedAfter(event, deletions)).map(([slug]) => slug).sort();
716
+ }
717
+ var KIND_DELETION, KIND_PRODUCT;
718
+ var init_read = __esm({
719
+ "src/commands/askr/read.ts"() {
720
+ init_constants();
721
+ init_store();
722
+ KIND_DELETION = 5;
723
+ KIND_PRODUCT = 30402;
724
+ }
725
+ });
726
+ function configInputOf(values, assistant, createdAt) {
727
+ return {
728
+ assistant,
729
+ origins: values.origins,
730
+ linkOrigins: values.linkOrigins,
731
+ name: values.name,
732
+ language: values.language,
733
+ currency: values.currency,
734
+ source: values.source,
735
+ catalogKey: values.catalogKey,
736
+ ...values.policyKey === values.catalogKey ? {} : { policyKey: values.policyKey },
737
+ ...values.displayName === void 0 ? {} : { displayName: values.displayName },
738
+ ...values.greeting === void 0 ? {} : { greeting: values.greeting },
739
+ ...values.contact === void 0 ? {} : { contact: values.contact },
740
+ private: values.private,
741
+ createdAt
742
+ };
743
+ }
744
+ function signSettings(input) {
745
+ const events = [];
746
+ if (input.config !== void 0) {
747
+ events.push(
748
+ finalizeEvent(input.askr.buildConfigEvent(input.config, input.secretKey), input.secretKey)
749
+ );
750
+ }
751
+ if (input.authorize !== void 0) {
752
+ events.push(
753
+ finalizeEvent(
754
+ input.askr.buildCatalogAuth({
755
+ key: input.authorize.key,
756
+ mode: "hosted",
757
+ createdAt: input.authorize.createdAt
758
+ }),
759
+ input.secretKey
760
+ )
761
+ );
762
+ }
763
+ return events;
764
+ }
765
+ var init_signing = __esm({
766
+ "src/commands/askr/signing.ts"() {
767
+ }
768
+ });
769
+
770
+ // src/commands/askr/init.ts
771
+ var init_exports = {};
772
+ __export(init_exports, {
773
+ runInit: () => runInit
774
+ });
775
+ function withHttps(value) {
776
+ return !SCHEME_RE.test(value) && BARE_HOST_RE.test(value) ? `https://${value}` : value;
777
+ }
778
+ function originOf(value) {
779
+ let url;
780
+ try {
781
+ url = new URL(withHttps(value.trim()));
782
+ } catch {
783
+ throw invalidFlag("--origin", `"${value}" is not a web address`);
784
+ }
785
+ if (url.protocol !== "https:") {
786
+ throw invalidFlag("--origin", `"${value}" must start with https://`);
787
+ }
788
+ return url.origin;
789
+ }
790
+ function httpsUrlOf(value, flag) {
791
+ try {
792
+ if (value.length <= MAX_URL_CHARS && new URL(value).protocol === "https:") {
793
+ return value;
794
+ }
795
+ } catch {
796
+ }
797
+ throw invalidFlag(flag, "an https address");
798
+ }
799
+ function optionalText(value) {
800
+ return value === void 0 ? void 0 : value.trim();
801
+ }
802
+ async function checkFlags(session, options) {
803
+ const { LIMITS: LIMITS3, CONNECTOR_PLATFORMS } = session.askr;
804
+ const flags = {};
805
+ const imported = options.ownerKeyFile === void 0 ? [] : [await readImportedKey(options.ownerKeyFile)];
806
+ if (options.name !== void 0) {
807
+ const name = options.name.trim();
808
+ if (name === "" || name.length > LIMITS3.TITLE_CHARS) {
809
+ throw invalidFlag("--name", `1 to ${LIMITS3.TITLE_CHARS} characters`);
810
+ }
811
+ flags.name = name;
812
+ }
813
+ if (options.origin !== void 0 && options.origin.length > 0) {
814
+ const origins = [...new Set(options.origin.map((value) => originOf(value)))];
815
+ if (origins.length > LIMITS3.MAX_ORIGINS) {
816
+ throw invalidFlag("--origin", `at most ${LIMITS3.MAX_ORIGINS} origins`);
817
+ }
818
+ flags.origins = origins;
819
+ }
820
+ if (options.language !== void 0) {
821
+ if (!LANGUAGE_RE.test(options.language) || options.language.length > LIMITS3.LOCALE_CHARS) {
822
+ throw invalidFlag("--language", "a BCP 47 tag such as en or de-CH");
823
+ }
824
+ flags.language = options.language;
825
+ }
826
+ if (options.currency !== void 0) {
827
+ const currency = options.currency.trim().toUpperCase();
828
+ if (!CURRENCY_RE.test(currency)) {
829
+ throw invalidFlag("--currency", "an ISO 4217 code such as USD or EUR");
830
+ }
831
+ flags.currency = currency;
832
+ }
833
+ if (options.source !== void 0) {
834
+ if (options.source !== "admin" && options.source !== "connector") {
835
+ throw invalidFlag("--source", "admin or connector");
836
+ }
837
+ flags.source = options.source;
838
+ }
839
+ if (options.platform !== void 0) {
840
+ const platform = CONNECTOR_PLATFORMS.find((known) => known === options.platform);
841
+ if (platform === void 0) {
842
+ throw invalidFlag("--platform", CONNECTOR_PLATFORMS.join(", "));
843
+ }
844
+ flags.platform = platform;
845
+ }
846
+ if (options.shopUrl !== void 0) {
847
+ const shopUrl = session.askr.normalizeShopUrl(withHttps(options.shopUrl.trim()));
848
+ if (shopUrl === void 0) {
849
+ throw invalidFlag("--shop-url", "the https address of the shop, like https://shop.example");
850
+ }
851
+ flags.shopUrl = shopUrl;
852
+ }
853
+ if (options.feedUrl !== void 0) {
854
+ flags.feedUrl = httpsUrlOf(options.feedUrl.trim(), "--feed-url");
855
+ }
856
+ const displayName = optionalText(options.displayName);
857
+ if (displayName !== void 0) {
858
+ if (displayName.length > LIMITS3.TITLE_CHARS) {
859
+ throw invalidFlag("--display-name", `at most ${LIMITS3.TITLE_CHARS} characters`);
860
+ }
861
+ flags.displayName = displayName;
862
+ }
863
+ const greeting = optionalText(options.greeting);
864
+ if (greeting !== void 0) {
865
+ if (greeting.length > LIMITS3.GREETING_CHARS) {
866
+ throw invalidFlag("--greeting", `at most ${LIMITS3.GREETING_CHARS} characters`);
867
+ }
868
+ flags.greeting = greeting;
869
+ }
870
+ const contact = optionalText(options.contact);
871
+ if (contact !== void 0) {
872
+ flags.contact = contact === "" ? "" : httpsUrlOf(contact, "--contact");
873
+ }
874
+ if (options.voiceFile !== void 0) {
875
+ flags.voice = await readFlagFile(
876
+ options.voiceFile,
877
+ "--voice-file",
878
+ session.deps.home,
879
+ imported
880
+ );
881
+ if (flags.voice.length > LIMITS3.CONFIG_VOICE_CHARS) {
882
+ throw invalidFlag("--voice-file", `at most ${LIMITS3.CONFIG_VOICE_CHARS} characters`);
883
+ }
884
+ }
885
+ if (options.instructionsFile !== void 0) {
886
+ flags.instructions = await readFlagFile(
887
+ options.instructionsFile,
888
+ "--instructions-file",
889
+ session.deps.home,
890
+ imported
891
+ );
892
+ if (flags.instructions.length > LIMITS3.CONFIG_INSTRUCTIONS_CHARS) {
893
+ throw invalidFlag(
894
+ "--instructions-file",
895
+ `at most ${LIMITS3.CONFIG_INSTRUCTIONS_CHARS} characters`
896
+ );
897
+ }
898
+ }
899
+ return flags;
900
+ }
901
+ function missingNameOrOrigins() {
902
+ return new AskrExit(EXIT.BAD_INPUT, "missing_flag", {
903
+ hint: "a new store needs --name and at least one --origin"
904
+ });
905
+ }
906
+ function otherKey(path) {
907
+ return new AskrExit(EXIT.KEY, "profile_has_other_key", {
908
+ hint: "this profile already holds another owner key: use --profile <name> for the imported store",
909
+ fields: { ownerKeyFile: path }
910
+ });
911
+ }
912
+ async function requireStoreOf(session, secretKey) {
913
+ session.signAs(secretKey);
914
+ const read = await session.call("GET", "/v1/admin/store");
915
+ if (read.ok) {
916
+ return;
917
+ }
918
+ if (read.status === 409 && read.code === "moved") {
919
+ throw new AskrExit(EXIT.REFUSED, "moved_store", {
920
+ hint: "this key's store moved to another owner key and now lives there: import that key's file instead, or sign in to the admin with it"
921
+ });
922
+ }
923
+ if (read.status === 404 && read.code === "no_store") {
924
+ throw new AskrExit(EXIT.KEY, "no_store_for_key", {
925
+ hint: "no store has this key: the file must hold the store's secret key (nsec), not its Store ID or public key"
926
+ });
927
+ }
928
+ throw refusalExit(session, read);
929
+ }
930
+ async function ownerKeyFor(session, options) {
931
+ const imported = options.ownerKeyFile === void 0 ? void 0 : await readImportedKey(options.ownerKeyFile);
932
+ const existing = await readOwnerKey(session.deps.home, session.profile);
933
+ if (existing !== void 0) {
934
+ if (imported !== void 0 && !sameKey(imported, existing.secretKey)) {
935
+ throw otherKey(existing.path);
936
+ }
937
+ return existing;
938
+ }
939
+ if (imported !== void 0) {
940
+ await requireStoreOf(session, imported);
941
+ }
942
+ const candidate = imported ?? generateSecretKey$1();
943
+ const saved = await saveOwnerKey(
944
+ session.deps.home,
945
+ session.profile,
946
+ candidate,
947
+ session.nowSecs(),
948
+ session.deps.keyFileOps
949
+ );
950
+ if (imported !== void 0 && !sameKey(imported, saved.secretKey)) {
951
+ throw otherKey(saved.path);
952
+ }
953
+ return saved;
954
+ }
955
+ async function openStore(session) {
956
+ const read = await session.call("GET", "/v1/admin/store");
957
+ if (read.ok) {
958
+ return { view: read.body, created: false };
959
+ }
960
+ if (read.status !== 404 || read.code !== "no_store") {
961
+ throw refusalExit(session, read);
962
+ }
963
+ const made = await session.call("POST", "/v1/admin/store");
964
+ if (made.ok) {
965
+ return { view: made.body, created: true };
966
+ }
967
+ if (made.status === 429) {
968
+ throw new AskrExit(EXIT.REFUSED, "rate_limited", {
969
+ hint: "too many new stores from this network; try again in an hour"
970
+ });
971
+ }
972
+ throw refusalExit(session, made);
973
+ }
974
+ function comparable(values, assistant) {
975
+ return JSON.stringify({
976
+ assistant,
977
+ origins: values.origins,
978
+ linkOrigins: values.linkOrigins,
979
+ name: values.name,
980
+ displayName: values.displayName,
981
+ greeting: values.greeting,
982
+ language: values.language,
983
+ currency: values.currency,
984
+ source: {
985
+ kind: values.source.kind,
986
+ platform: values.source.platform,
987
+ shopUrl: values.source.shopUrl
988
+ },
989
+ catalogKey: values.catalogKey,
990
+ policyKey: values.policyKey,
991
+ contact: values.contact,
992
+ private: {
993
+ voice: values.private.voice,
994
+ instructions: values.private.instructions,
995
+ notes: values.private.notes
996
+ }
997
+ });
998
+ }
999
+ function valuesOfConfig(config, privatePart) {
1000
+ return {
1001
+ name: config.name,
1002
+ origins: config.origins,
1003
+ linkOrigins: config.linkOrigins,
1004
+ language: config.language,
1005
+ currency: config.currency,
1006
+ source: config.source,
1007
+ catalogKey: config.catalogKey,
1008
+ policyKey: config.policyKey,
1009
+ ...config.displayName === void 0 ? {} : { displayName: config.displayName },
1010
+ ...config.greeting === void 0 ? {} : { greeting: config.greeting },
1011
+ ...config.contact === void 0 ? {} : { contact: config.contact },
1012
+ private: privatePart
1013
+ };
1014
+ }
1015
+ function sameOrigins(left, right) {
1016
+ return left.length === right.length && left.every((origin) => right.includes(origin));
1017
+ }
1018
+ function optionalField(flag, previous) {
1019
+ const value = flag ?? previous;
1020
+ return value === void 0 || value === "" ? void 0 : value;
1021
+ }
1022
+ function merge(session, flags, view, previous) {
1023
+ const serverKey = view.catalogKey;
1024
+ const config = previous?.config;
1025
+ const name = flags.name ?? config?.name;
1026
+ const origins = flags.origins ?? config?.origins;
1027
+ if (name === void 0 || origins === void 0) {
1028
+ throw missingNameOrOrigins();
1029
+ }
1030
+ const kind = flags.source ?? (config?.source.kind === "connector" ? "connector" : "admin");
1031
+ const source = { kind };
1032
+ let feedUrl;
1033
+ if (kind === "connector") {
1034
+ const platform = flags.platform ?? (config?.source.kind === "connector" ? config.source.platform : void 0);
1035
+ if (platform === void 0) {
1036
+ throw new AskrExit(EXIT.BAD_INPUT, "missing_flag", {
1037
+ hint: "--source connector needs --platform shopify, woocommerce or google"
1038
+ });
1039
+ }
1040
+ source.platform = platform;
1041
+ if (platform === "google") {
1042
+ feedUrl = flags.feedUrl ?? (view.connector?.platform === "google" ? view.connector.url : void 0);
1043
+ if (feedUrl === void 0) {
1044
+ throw new AskrExit(EXIT.BAD_INPUT, "missing_flag", {
1045
+ hint: "--platform google needs --feed-url with the https address of the product feed"
1046
+ });
1047
+ }
1048
+ } else {
1049
+ const shopUrl = flags.shopUrl ?? config?.source.shopUrl;
1050
+ if (shopUrl === void 0) {
1051
+ throw new AskrExit(EXIT.BAD_INPUT, "missing_flag", {
1052
+ hint: `--platform ${platform} needs --shop-url with the https address of the shop`
1053
+ });
1054
+ }
1055
+ const shopOrigin = new URL(shopUrl).origin;
1056
+ if (!origins.includes(shopOrigin)) {
1057
+ throw invalidFlag(
1058
+ "--shop-url",
1059
+ `add ${shopOrigin} as an --origin, so the chat can add to its cart`
1060
+ );
1061
+ }
1062
+ source.shopUrl = shopUrl;
1063
+ }
1064
+ }
1065
+ const values = {
1066
+ name,
1067
+ origins,
1068
+ linkOrigins: config?.linkOrigins ?? [],
1069
+ language: flags.language ?? config?.language ?? DEFAULT_LANGUAGE,
1070
+ currency: flags.currency ?? config?.currency ?? DEFAULT_CURRENCY,
1071
+ source,
1072
+ catalogKey: serverKey,
1073
+ policyKey: config !== void 0 && config.source.kind === kind && config.catalogKey === serverKey ? config.policyKey : serverKey,
1074
+ private: {
1075
+ voice: flags.voice ?? previous?.privatePart.voice ?? "",
1076
+ instructions: flags.instructions ?? previous?.privatePart.instructions ?? "",
1077
+ notes: previous?.privatePart.notes ?? ""
1078
+ }
1079
+ };
1080
+ const displayName = optionalField(flags.displayName, config?.displayName);
1081
+ const greeting = optionalField(flags.greeting, config?.greeting);
1082
+ const contact = optionalField(flags.contact, config?.contact);
1083
+ if (displayName !== void 0) {
1084
+ values.displayName = displayName;
1085
+ }
1086
+ if (greeting !== void 0) {
1087
+ values.greeting = greeting;
1088
+ }
1089
+ if (contact !== void 0) {
1090
+ values.contact = contact;
1091
+ }
1092
+ const checked = session.askr.StoreConfigInputSchema.safeParse(
1093
+ configInputOf(values, view.nextAssistant ?? view.assistant, session.nowSecs())
1094
+ );
1095
+ if (!checked.success) {
1096
+ const [issue] = checked.error.issues;
1097
+ throw new AskrExit(EXIT.BAD_INPUT, "invalid_settings", {
1098
+ hint: `${String(issue?.path[0] ?? "settings")}: ${issue?.message ?? "not valid"}`
1099
+ });
1100
+ }
1101
+ return feedUrl === void 0 ? { values } : { values, feedUrl };
1102
+ }
1103
+ function eventsRefusal(session, result) {
1104
+ if (result.code === "bad_event") {
1105
+ const reason = typeof result.detail.reason === "string" ? result.detail.reason : "unknown";
1106
+ if (reason === "config_assistant") {
1107
+ return session.notDone("bad_event", {
1108
+ hint: "the assistant key rotated meanwhile: run the resume command, it signs for the new one",
1109
+ fields: { reason }
1110
+ });
1111
+ }
1112
+ if (reason === "stale_config") {
1113
+ return session.notDone("bad_event", {
1114
+ hint: "the server holds newer settings (saved in the admin meanwhile?): run the resume command, it merges onto them",
1115
+ fields: { reason }
1116
+ });
1117
+ }
1118
+ return new AskrExit(EXIT.REFUSED, "bad_event", {
1119
+ hint: reason === "future" ? "check this computer's clock: a signed event is dated in the future" : "the server refused a signed event",
1120
+ fields: { reason }
1121
+ });
1122
+ }
1123
+ if (result.code === "too_many_events") {
1124
+ return new AskrExit(EXIT.REFUSED, "too_many_events", {
1125
+ hint: "too many signed changes are waiting: wait until they are published, then run again"
1126
+ });
1127
+ }
1128
+ return refusalExit(session, result);
1129
+ }
1130
+ async function reconcileConnector(session, merged, before) {
1131
+ const { source } = merged.values;
1132
+ if (source.kind !== "connector" || source.platform === void 0) {
1133
+ if (before !== null) {
1134
+ const removed = await session.call("DELETE", "/v1/admin/connector");
1135
+ if (!removed.ok) {
1136
+ throw refusalExit(session, removed);
1137
+ }
1138
+ }
1139
+ return null;
1140
+ }
1141
+ const url = source.platform === "google" ? merged.feedUrl : source.shopUrl;
1142
+ if (url === void 0) {
1143
+ return before;
1144
+ }
1145
+ const result = await session.call(
1146
+ "PUT",
1147
+ "/v1/admin/connector",
1148
+ {
1149
+ platform: source.platform,
1150
+ url,
1151
+ ...before?.currency === void 0 ? {} : { currency: before.currency },
1152
+ importPolicies: source.platform === "shopify" ? before?.importPolicies ?? true : false
1153
+ }
1154
+ );
1155
+ if (!result.ok) {
1156
+ throw refusalExit(session, result);
1157
+ }
1158
+ return result.body.connector;
1159
+ }
1160
+ async function runInit(session, options) {
1161
+ const flags = await checkFlags(session, options);
1162
+ const newStore = options.ownerKeyFile === void 0 && await readOwnerKey(session.deps.home, session.profile) === void 0;
1163
+ if (newStore && (flags.name === void 0 || flags.origins === void 0)) {
1164
+ throw missingNameOrOrigins();
1165
+ }
1166
+ const key = await ownerKeyFor(session, options);
1167
+ session.signAs(key.secretKey);
1168
+ const opened = await openStore(session);
1169
+ let view = opened.view;
1170
+ const signed = await readSigned(session, key.owner, key.secretKey);
1171
+ if (view.movedFrom !== null && signed.config === void 0) {
1172
+ throw movedExit();
1173
+ }
1174
+ if (signed.config?.source.kind === "catalog") {
1175
+ throw new AskrExit(EXIT.REFUSED, "catalog_source", {
1176
+ hint: "this store takes its products from its own catalog key: manage it in the admin"
1177
+ });
1178
+ }
1179
+ if (signed.config !== void 0 && options.update !== true) {
1180
+ const nameChanged = flags.name !== void 0 && flags.name !== signed.config.name;
1181
+ const originsChanged = flags.origins !== void 0 && !sameOrigins(flags.origins, signed.config.origins);
1182
+ if (nameChanged || originsChanged) {
1183
+ throw new AskrExit(EXIT.EXISTING_STORE, "existing_store", {
1184
+ hint: "update it with --update, or use --profile <name> for a separate store",
1185
+ fields: {
1186
+ existingStore: key.storeId,
1187
+ name: signed.config.name,
1188
+ origins: signed.config.origins
1189
+ }
1190
+ });
1191
+ }
1192
+ }
1193
+ if (signed.config !== void 0 && signed.privatePart === void 0) {
1194
+ throw new AskrExit(EXIT.REFUSED, "config_unreadable", {
1195
+ hint: "the store's assistant settings cannot be read back: open the admin"
1196
+ });
1197
+ }
1198
+ const previous = signed.config !== void 0 && signed.privatePart !== void 0 ? { config: signed.config, privatePart: signed.privatePart } : void 0;
1199
+ const merged = merge(session, flags, view, previous);
1200
+ const assistant = view.nextAssistant ?? view.assistant;
1201
+ const now = session.nowSecs();
1202
+ const stopped = stoppedKinds(view);
1203
+ const configChanged = previous === void 0 || stopped.includes(session.askr.KIND_CONFIG) || comparable(merged.values, assistant) !== comparable(valuesOfConfig(previous.config, previous.privatePart), previous.config.assistant);
1204
+ const authMissing = !signed.authorized.has(view.catalogKey) || stopped.includes(session.askr.KIND_CATALOG_AUTH);
1205
+ const events = signSettings({
1206
+ askr: session.askr,
1207
+ secretKey: key.secretKey,
1208
+ ...configChanged ? {
1209
+ config: configInputOf(
1210
+ merged.values,
1211
+ assistant,
1212
+ Math.max(now, (previous?.config.createdAt ?? 0) + 1)
1213
+ )
1214
+ } : {},
1215
+ ...authMissing ? {
1216
+ authorize: {
1217
+ key: view.catalogKey,
1218
+ createdAt: Math.max(now, (signed.authNewestAt.get(view.catalogKey) ?? 0) + 1)
1219
+ }
1220
+ } : {}
1221
+ });
1222
+ if (events.length > 0) {
1223
+ const posted = await session.call("POST", "/v1/admin/store/events", { events });
1224
+ if (!posted.ok) {
1225
+ throw eventsRefusal(session, posted);
1226
+ }
1227
+ }
1228
+ const connector = await reconcileConnector(session, merged, view.connector);
1229
+ let published = false;
1230
+ if (view.status === "active") {
1231
+ view = await readView(session);
1232
+ const waited = await waitPublished(
1233
+ session,
1234
+ view,
1235
+ (stoppedView) => new AskrExit(EXIT.REFUSED, "publish_stopped", {
1236
+ hint: STOPPED_HINT,
1237
+ fields: { kinds: stoppedKinds(stoppedView) }
1238
+ })
1239
+ );
1240
+ if (!waited.published) {
1241
+ throw session.notDone("publication_pending", {
1242
+ hint: "the settings are stored but not published yet: run the resume command in about a minute",
1243
+ fields: { published: false }
1244
+ });
1245
+ }
1246
+ view = waited.view;
1247
+ published = true;
1248
+ }
1249
+ const awaitingPlan = awaitingPlanOf(view);
1250
+ const output = {
1251
+ ok: true,
1252
+ profile: session.profile,
1253
+ storeId: key.storeId,
1254
+ status: view.status,
1255
+ tier: tierOf(view),
1256
+ awaitingPlan,
1257
+ created: opened.created,
1258
+ config: configChanged ? "signed" : "unchanged",
1259
+ authorization: authMissing ? "signed" : "present",
1260
+ connector: connector === null ? null : { platform: connector.platform, enabled: connector.enabled },
1261
+ published,
1262
+ ownerKeyFile: key.path,
1263
+ adminUrl: session.adminUrl
1264
+ };
1265
+ if (awaitingPlan) {
1266
+ output.next = NEXT_PLAN;
1267
+ output.upgrade = UPGRADE;
1268
+ } else if (view.status !== "active") {
1269
+ output.hint = CONTACT_HINT;
1270
+ }
1271
+ return { exitCode: EXIT.OK, output };
1272
+ }
1273
+ var DEFAULT_LANGUAGE, DEFAULT_CURRENCY, LANGUAGE_RE, CURRENCY_RE, SCHEME_RE, BARE_HOST_RE, MAX_URL_CHARS, NEXT_PLAN, STOPPED_HINT;
1274
+ var init_init = __esm({
1275
+ "src/commands/askr/init.ts"() {
1276
+ init_constants();
1277
+ init_errors();
1278
+ init_files();
1279
+ init_owner_key();
1280
+ init_read();
1281
+ init_signing();
1282
+ init_store();
1283
+ DEFAULT_LANGUAGE = "en";
1284
+ DEFAULT_CURRENCY = "USD";
1285
+ LANGUAGE_RE = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
1286
+ CURRENCY_RE = /^[A-Z]{3}$/;
1287
+ SCHEME_RE = /^[a-z][a-z0-9+.-]*:\/\//iu;
1288
+ BARE_HOST_RE = /^[^\s/:]+\.[^\s/:]+(?::\d+)?(?:\/.*)?$/u;
1289
+ MAX_URL_CHARS = 2048;
1290
+ NEXT_PLAN = `choose a plan: Free via askr plan free, only if the human chose Free; a paid plan: message us at ${CONTACT_URL} with your Store ID and the name of the plan the human chose`;
1291
+ STOPPED_HINT = "report this to us with your Store ID";
1292
+ }
1293
+ });
1294
+
1295
+ // src/commands/askr/plan.ts
1296
+ var plan_exports = {};
1297
+ __export(plan_exports, {
1298
+ runPlan: () => runPlan
1299
+ });
1300
+ async function runPlan(session, plan) {
1301
+ if (plan !== FREE) {
1302
+ throw new AskrExit(EXIT.BAD_INPUT, "paid_plan", {
1303
+ hint: "paid plans: message us with your Store ID",
1304
+ fields: { upgrade: UPGRADE }
1305
+ });
1306
+ }
1307
+ const key = await useOwnerKey(session);
1308
+ const result = await session.call(
1309
+ "POST",
1310
+ "/v1/admin/store/plan",
1311
+ { plan: FREE }
1312
+ );
1313
+ if (!result.ok) {
1314
+ switch (result.code) {
1315
+ case "capacity_reached":
1316
+ throw new AskrExit(EXIT.LIMIT, "capacity_reached", {
1317
+ hint: "Free is full right now: message us with your Store ID, or try again tomorrow",
1318
+ fields: { upgrade: UPGRADE, resume: session.resumeSame() }
1319
+ });
1320
+ case "free_unavailable":
1321
+ throw new AskrExit(EXIT.LIMIT, "free_unavailable", {
1322
+ hint: "Free cannot be started right now: message us with your Store ID",
1323
+ fields: { upgrade: UPGRADE }
1324
+ });
1325
+ case "no_settings":
1326
+ case "no_store":
1327
+ throw new AskrExit(EXIT.BAD_INPUT, result.code, { hint: INIT_FIRST_HINT });
1328
+ case "not_pending":
1329
+ throw new AskrExit(EXIT.REFUSED, "not_pending", {
1330
+ hint: `the store is suspended: ${CONTACT_HINT}`
1331
+ });
1332
+ case "operator_managed":
1333
+ throw new AskrExit(EXIT.REFUSED, "operator_managed", {
1334
+ hint: `we manage this store's plan: ${CONTACT_HINT}`
1335
+ });
1336
+ case "read_failed":
1337
+ throw session.notDone("read_failed", {
1338
+ hint: "the store changed meanwhile: run the resume command in about a minute"
1339
+ });
1340
+ default:
1341
+ throw refusalExit(session, result);
1342
+ }
1343
+ }
1344
+ const activation = result.body.activation;
1345
+ const waited = await waitPublished(
1346
+ session,
1347
+ await readView(session),
1348
+ (view) => new AskrExit(EXIT.REFUSED, "publish_stopped", {
1349
+ hint: "run the same askr init line once (it stores the event again); if it stays stopped, report this to us with your Store ID",
1350
+ fields: { kinds: stoppedKinds(view) }
1351
+ })
1352
+ );
1353
+ if (!waited.published) {
1354
+ throw session.notDone("publication_pending", {
1355
+ hint: "the store is active; its settings are being published: run the resume command in about a minute",
1356
+ fields: { activation, published: false }
1357
+ });
1358
+ }
1359
+ return {
1360
+ exitCode: EXIT.OK,
1361
+ output: {
1362
+ ok: true,
1363
+ storeId: key.storeId,
1364
+ status: waited.view.status,
1365
+ tier: tierOf(waited.view),
1366
+ activation,
1367
+ published: true
1368
+ }
1369
+ };
1370
+ }
1371
+ var FREE;
1372
+ var init_plan = __esm({
1373
+ "src/commands/askr/plan.ts"() {
1374
+ init_constants();
1375
+ init_errors();
1376
+ init_store();
1377
+ FREE = "free";
1378
+ }
1379
+ });
1380
+
1381
+ // src/commands/askr/products.ts
1382
+ var products_exports = {};
1383
+ __export(products_exports, {
1384
+ runProducts: () => runProducts
1385
+ });
1386
+ function invalidFile(hint, fields = {}) {
1387
+ return new AskrExit(EXIT.BAD_INPUT, "invalid_file", { hint, fields });
1388
+ }
1389
+ function itemsOfJson(parsed) {
1390
+ if (Array.isArray(parsed)) {
1391
+ return parsed;
1392
+ }
1393
+ if (typeof parsed === "object" && parsed !== null && "items" in parsed) {
1394
+ const items = parsed.items;
1395
+ return Array.isArray(items) ? items : void 0;
1396
+ }
1397
+ return void 0;
1398
+ }
1399
+ async function readProductsFile(session, path) {
1400
+ const { askr } = session;
1401
+ const lower = path.toLowerCase();
1402
+ const isCsv = lower.endsWith(".csv");
1403
+ if (!isCsv && !lower.endsWith(".json")) {
1404
+ await fileSize(path, "--file");
1405
+ throw invalidFile("--file: a .json or .csv file");
1406
+ }
1407
+ const size = await fileSize(path, "--file");
1408
+ if (isCsv) {
1409
+ const tooLarge = askr.csvSizeProblem(size);
1410
+ if (tooLarge !== void 0) {
1411
+ throw invalidFile(tooLarge);
1412
+ }
1413
+ } else if (size > MAX_CATALOG_BODY_BYTES) {
1414
+ throw invalidFile(
1415
+ "the file is larger than 8 MB: split it and publish it in parts without --replace"
1416
+ );
1417
+ }
1418
+ const text = await readFlagFile(path, "--file", session.deps.home);
1419
+ if (isCsv) {
1420
+ const parsed2 = askr.parseCsv(text);
1421
+ if (parsed2.unclosedQuoteLine !== void 0) {
1422
+ throw invalidFile(`a quoted field opened on line ${parsed2.unclosedQuoteLine} never closes`);
1423
+ }
1424
+ if (parsed2.rows.length < 2) {
1425
+ throw invalidFile("the CSV needs a header row and at least one product row");
1426
+ }
1427
+ return { format: "csv", text };
1428
+ }
1429
+ let parsed;
1430
+ try {
1431
+ parsed = JSON.parse(text);
1432
+ } catch {
1433
+ throw invalidFile("the file is not valid JSON");
1434
+ }
1435
+ const values = itemsOfJson(parsed);
1436
+ if (values === void 0) {
1437
+ throw invalidFile('the JSON must be an array of products or { "items": [...] }');
1438
+ }
1439
+ const items = [];
1440
+ const issues = [];
1441
+ values.forEach((value, index) => {
1442
+ const checked = askr.CatalogItemInputSchema.safeParse(value);
1443
+ if (checked.success) {
1444
+ items.push(checked.data);
1445
+ return;
1446
+ }
1447
+ for (const issue of checked.error.issues) {
1448
+ issues.push({ index, path: issue.path.join("."), message: issue.message });
1449
+ }
1450
+ });
1451
+ if (issues.length > 0) {
1452
+ throw invalidFile("fix these products and run again", { issues: issues.slice(0, MAX_ISSUES) });
1453
+ }
1454
+ const repeated = repeatedIds(items);
1455
+ if (repeated.length > 0) {
1456
+ throw invalidFile("each product needs its own d: these ids are used more than once", {
1457
+ repeated: repeated.slice(0, MAX_ISSUES)
1458
+ });
1459
+ }
1460
+ return { format: "json", items };
1461
+ }
1462
+ function repeatedIds(items) {
1463
+ const seen = /* @__PURE__ */ new Set();
1464
+ const repeated = /* @__PURE__ */ new Set();
1465
+ for (const item of items) {
1466
+ if (seen.has(item.d)) {
1467
+ repeated.add(item.d);
1468
+ }
1469
+ seen.add(item.d);
1470
+ }
1471
+ return [...repeated];
1472
+ }
1473
+ function itemsOfCsv(session, text, currency) {
1474
+ const imported = session.askr.productsFromCsv(text, currency);
1475
+ if (imported.fileErrors.length > 0) {
1476
+ throw invalidFile("the CSV cannot be read: fix the problems listed and run again", {
1477
+ fileErrors: imported.fileErrors
1478
+ });
1479
+ }
1480
+ if (imported.errors.length > 0) {
1481
+ throw new AskrExit(EXIT.BAD_INPUT, "invalid_rows", {
1482
+ hint: "fix these CSV lines and run again",
1483
+ fields: { errors: imported.errors.slice(0, MAX_ISSUES) }
1484
+ });
1485
+ }
1486
+ return imported.items;
1487
+ }
1488
+ function sourceGate(config) {
1489
+ if (config.source.kind === "admin") {
1490
+ return;
1491
+ }
1492
+ throw new AskrExit(EXIT.REFUSED, "wrong_source", {
1493
+ hint: config.source.kind === "connector" ? "products come from your connector" : "manage this store in the admin"
1494
+ });
1495
+ }
1496
+ function urlWarnings(items, config) {
1497
+ const allowed = /* @__PURE__ */ new Set([...config.origins, ...config.linkOrigins]);
1498
+ return items.flatMap((item) => {
1499
+ if (item.url === void 0) {
1500
+ return [];
1501
+ }
1502
+ let origin;
1503
+ try {
1504
+ origin = new URL(item.url).origin;
1505
+ } catch {
1506
+ origin = void 0;
1507
+ }
1508
+ return origin !== void 0 && allowed.has(origin) ? [] : [{ d: item.d, url: item.url }];
1509
+ });
1510
+ }
1511
+ function isNotAuthorized(result) {
1512
+ return result.code === "sync_refused" && result.detail.message === NOT_AUTHORIZED_MESSAGE;
1513
+ }
1514
+ async function runProducts(session, options) {
1515
+ const file = await readProductsFile(session, options.file);
1516
+ const key = await useOwnerKey(session);
1517
+ const view = await readView(session);
1518
+ const localDryRun = options.dryRun === true && view.status === "pending";
1519
+ if (view.status !== "active" && !localDryRun) {
1520
+ throw inactiveExit(view);
1521
+ }
1522
+ const { config } = await readSigned(session, key.owner, key.secretKey);
1523
+ if (config === void 0) {
1524
+ throw new AskrExit(EXIT.BAD_INPUT, "no_settings", { hint: "run askr init first" });
1525
+ }
1526
+ sourceGate(config);
1527
+ const items = file.format === "csv" ? itemsOfCsv(session, file.text, config.currency) : file.items;
1528
+ const mode = options.replace === true ? "replace" : "upsert";
1529
+ const bodyOf = (dryRun) => ({ mode, items, dryRun });
1530
+ if (Buffer.byteLength(JSON.stringify(bodyOf(false)), "utf8") > MAX_CATALOG_BODY_BYTES) {
1531
+ throw new AskrExit(EXIT.BAD_INPUT, "body_too_large", {
1532
+ hint: "split the file and publish it in parts without --replace"
1533
+ });
1534
+ }
1535
+ const flow = new CatalogFlow(session, view, bodyOf, options.dryRun === true);
1536
+ const summary = {
1537
+ ok: true,
1538
+ storeId: key.storeId,
1539
+ mode,
1540
+ dryRun: options.dryRun === true,
1541
+ inFile: items.length,
1542
+ visibleInFile: items.filter((item) => item.visibility !== "hidden").length
1543
+ };
1544
+ const extra = {};
1545
+ const linkWarnings = urlWarnings(items, config);
1546
+ if (linkWarnings.length > 0) {
1547
+ extra.urlWarnings = linkWarnings.slice(0, SAMPLE_SIZE);
1548
+ }
1549
+ if (localDryRun) {
1550
+ const local = await localDiff(session, view.catalogKey, items, mode);
1551
+ return { exitCode: EXIT.OK, output: { ...summary, ...local, ...extra } };
1552
+ }
1553
+ for (; ; ) {
1554
+ const diff = await flow.dryRun();
1555
+ if (mode === "upsert" && extra.warning === void 0) {
1556
+ const warning = await absentWarning(session, view.catalogKey, items);
1557
+ if (warning !== void 0) {
1558
+ extra.warning = warning;
1559
+ }
1560
+ }
1561
+ const counts = countsOf(diff);
1562
+ if (options.dryRun === true) {
1563
+ return { exitCode: EXIT.OK, output: { ...summary, ...counts, ...extra } };
1564
+ }
1565
+ if (mode === "replace" && diff.hidden.length > 0 && options.allowHide !== true) {
1566
+ throw new AskrExit(EXIT.BAD_INPUT, "would_hide", {
1567
+ hint: "this would hide listed products missing from the file: confirm with the human, then add --allow-hide",
1568
+ fields: { ...counts, wouldHide: diff.hidden }
1569
+ });
1570
+ }
1571
+ if (diff.created.length + diff.updated.length + diff.hidden.length === 0) {
1572
+ return { exitCode: EXIT.OK, output: { ...summary, ...counts, sync: "done", ...extra } };
1573
+ }
1574
+ if (session.remaining() < MIN_REAL_CALL_MS) {
1575
+ throw session.notDone("deadline", {
1576
+ hint: "too little time left to publish in this run: run the resume command"
1577
+ });
1578
+ }
1579
+ const started = await flow.publish();
1580
+ if (started === void 0) {
1581
+ continue;
1582
+ }
1583
+ const sync = await flow.waitSync();
1584
+ return {
1585
+ exitCode: EXIT.OK,
1586
+ output: {
1587
+ ...summary,
1588
+ ...countsOf(started),
1589
+ sync,
1590
+ ...sync === "running" ? { next: "askr status" } : {},
1591
+ ...extra
1592
+ }
1593
+ };
1594
+ }
1595
+ }
1596
+ async function localDiff(session, catalogKey, items, mode) {
1597
+ const { listed } = await readListings(session, catalogKey);
1598
+ const inFile = new Set(items.map((item) => item.d));
1599
+ const listedIds = new Set(listed);
1600
+ const created = items.filter((item) => !listedIds.has(item.d)).map((item) => item.d);
1601
+ const hidden = mode === "replace" ? listed.filter((d) => !inFile.has(d)) : [];
1602
+ return {
1603
+ checked: "local",
1604
+ published: false,
1605
+ created: created.length,
1606
+ alreadyListed: items.length - created.length,
1607
+ hidden: hidden.length,
1608
+ sample: { created: created.slice(0, SAMPLE_SIZE), hidden: hidden.slice(0, SAMPLE_SIZE) },
1609
+ note: "the store is pending: the file is valid and nothing was published; once the plan is active, run this line again without --dry-run (the server then also checks the plan's product limit)"
1610
+ };
1611
+ }
1612
+ function countsOf(diff) {
1613
+ return {
1614
+ created: diff.created.length,
1615
+ updated: diff.updated.length,
1616
+ hidden: diff.hidden.length,
1617
+ unchanged: diff.unchanged.length,
1618
+ sample: {
1619
+ created: diff.created.slice(0, SAMPLE_SIZE),
1620
+ hidden: diff.hidden.slice(0, SAMPLE_SIZE)
1621
+ }
1622
+ };
1623
+ }
1624
+ async function absentWarning(session, catalogKey, items) {
1625
+ const { listed } = await readListings(session, catalogKey);
1626
+ if (listed.length === 0) {
1627
+ return void 0;
1628
+ }
1629
+ const inFile = new Set(items.map((item) => item.d));
1630
+ const absent = listed.filter((d) => !inFile.has(d)).length;
1631
+ const overShare = absent * BPS_WHOLE > ABSENT_WARNING_BPS * listed.length;
1632
+ if (!overShare && absent <= ABSENT_WARNING_COUNT) {
1633
+ return void 0;
1634
+ }
1635
+ return `${absent} listed products are not in this file; if the file is your whole catalog, run with --replace (dry run first)`;
1636
+ }
1637
+ var BPS_WHOLE, CatalogFlow;
1638
+ var init_products = __esm({
1639
+ "src/commands/askr/products.ts"() {
1640
+ init_constants();
1641
+ init_errors();
1642
+ init_files();
1643
+ init_read();
1644
+ init_store();
1645
+ BPS_WHOLE = 1e4;
1646
+ CatalogFlow = class {
1647
+ constructor(session, view, bodyOf, dryRunOnly) {
1648
+ this.session = session;
1649
+ this.view = view;
1650
+ this.bodyOf = bodyOf;
1651
+ this.dryRunOnly = dryRunOnly;
1652
+ }
1653
+ notAuthorizedWait = NOT_AUTHORIZED_RETRY_MS;
1654
+ call(dryRun) {
1655
+ return this.session.call("POST", "/v1/admin/catalog", this.bodyOf(dryRun));
1656
+ }
1657
+ /** Wait while the catalog's server K has no authorization on the relay yet. */
1658
+ async waitAuthorized() {
1659
+ if (this.session.remaining() <= this.notAuthorizedWait) {
1660
+ throw this.session.notDone("not_authorized_yet", {
1661
+ hint: "the store's catalog key is not on the relay yet: run the resume command in about a minute"
1662
+ });
1663
+ }
1664
+ await this.session.sleep(this.notAuthorizedWait);
1665
+ this.notAuthorizedWait *= 2;
1666
+ }
1667
+ /** Wait until no sync of this store runs, at least one poll (a dry run's guard never shows). */
1668
+ async waitIdle() {
1669
+ for (; ; ) {
1670
+ if (this.session.remaining() <= SYNC_POLL_MS) {
1671
+ throw this.session.notDone("sync_running", {
1672
+ hint: "another catalog sync of this store is running: run the resume command in about a minute"
1673
+ });
1674
+ }
1675
+ await this.session.sleep(SYNC_POLL_MS);
1676
+ const view = await readView(this.session);
1677
+ if (view.catalogSync?.state !== "running") {
1678
+ return;
1679
+ }
1680
+ }
1681
+ }
1682
+ refusal(result) {
1683
+ switch (result.code) {
1684
+ case "too_many_products":
1685
+ return new AskrExit(EXIT.LIMIT, "too_many_products", {
1686
+ hint: "more products than the store's plan allows",
1687
+ fields: { max: result.detail.max, upgrade: UPGRADE }
1688
+ });
1689
+ case "invalid_items":
1690
+ return new AskrExit(EXIT.BAD_INPUT, "invalid_items", {
1691
+ fields: {
1692
+ issues: Array.isArray(result.detail.issues) ? result.detail.issues.slice(0, MAX_ISSUES) : []
1693
+ }
1694
+ });
1695
+ case "inactive":
1696
+ return inactiveExit(this.view);
1697
+ case "bad_request":
1698
+ return new AskrExit(EXIT.BAD_INPUT, "bad_request", {
1699
+ ...typeof result.detail.message === "string" ? { message: result.detail.message } : {}
1700
+ });
1701
+ case "sync_refused":
1702
+ return this.session.notDone("sync_refused", {
1703
+ hint: "the server could not check the catalog against the relay: run the resume command in about a minute",
1704
+ ...typeof result.detail.message === "string" ? { message: result.detail.message } : {}
1705
+ });
1706
+ default:
1707
+ return refusalExit(this.session, result);
1708
+ }
1709
+ }
1710
+ async dryRun() {
1711
+ for (; ; ) {
1712
+ const result = await this.call(true);
1713
+ if (result.ok) {
1714
+ return result.body.diff;
1715
+ }
1716
+ if (result.code === "sync_running") {
1717
+ if (this.dryRunOnly) {
1718
+ throw this.session.notDone("sync_running", {
1719
+ hint: "another catalog sync of this store is running: run the resume command in about a minute"
1720
+ });
1721
+ }
1722
+ await this.waitIdle();
1723
+ continue;
1724
+ }
1725
+ if (isNotAuthorized(result)) {
1726
+ await this.waitAuthorized();
1727
+ continue;
1728
+ }
1729
+ throw this.refusal(result);
1730
+ }
1731
+ }
1732
+ /** The real call: its diff once accepted, or undefined to start over with a dry run. */
1733
+ async publish() {
1734
+ const result = await this.call(false);
1735
+ if (result.ok) {
1736
+ return result.body.diff;
1737
+ }
1738
+ if (result.code === "sync_running") {
1739
+ await this.waitIdle();
1740
+ return void 0;
1741
+ }
1742
+ if (isNotAuthorized(result)) {
1743
+ await this.waitAuthorized();
1744
+ return void 0;
1745
+ }
1746
+ throw this.refusal(result);
1747
+ }
1748
+ /** Follow the accepted sync: `done`, `running` at the deadline, or exit 4 when it failed. */
1749
+ async waitSync() {
1750
+ for (; ; ) {
1751
+ const view = await readView(this.session);
1752
+ const sync = view.catalogSync;
1753
+ if (sync?.state === "done") {
1754
+ return "done";
1755
+ }
1756
+ if (sync?.state === "failed") {
1757
+ throw this.session.notDone("sync_failed", {
1758
+ hint: "the catalog sync failed: run the resume command once; it sends only what is still different",
1759
+ message: sync.error
1760
+ });
1761
+ }
1762
+ if (this.session.remaining() <= SYNC_POLL_MS) {
1763
+ return "running";
1764
+ }
1765
+ await this.session.sleep(SYNC_POLL_MS);
1766
+ }
1767
+ }
1768
+ };
1769
+ }
1770
+ });
1771
+
1772
+ // src/commands/askr/policy.ts
1773
+ var policy_exports = {};
1774
+ __export(policy_exports, {
1775
+ runPolicy: () => runPolicy
1776
+ });
1777
+ async function runPolicy(session, options) {
1778
+ const { LIMITS: LIMITS3 } = session.askr;
1779
+ if (!POLICY_SLUG_RE.test(options.slug)) {
1780
+ throw invalidFlag("--slug", "up to 64 lowercase letters, digits or hyphens, like returns");
1781
+ }
1782
+ const title = options.title.trim();
1783
+ if (title === "" || title.length > LIMITS3.TITLE_CHARS) {
1784
+ throw invalidFlag("--title", `1 to ${LIMITS3.TITLE_CHARS} characters`);
1785
+ }
1786
+ const body = await readFlagFile(options.file, "--file", session.deps.home);
1787
+ if (body.trim() === "" || body.length > LIMITS3.POLICY_CONTENT_CHARS) {
1788
+ throw invalidFlag("--file", `1 to ${LIMITS3.POLICY_CONTENT_CHARS} characters of Markdown`);
1789
+ }
1790
+ const key = await useOwnerKey(session);
1791
+ const view = await readView(session);
1792
+ if (view.status !== "active") {
1793
+ throw inactiveExit(view);
1794
+ }
1795
+ const { config } = await readSigned(session, key.owner, key.secretKey);
1796
+ if (config === void 0) {
1797
+ throw new AskrExit(EXIT.BAD_INPUT, "no_settings", { hint: "run askr init first" });
1798
+ }
1799
+ if (config.policyKey !== view.catalogKey) {
1800
+ throw new AskrExit(EXIT.REFUSED, "wrong_source", {
1801
+ hint: "this store's policies are signed by another key: manage them where that key is"
1802
+ });
1803
+ }
1804
+ let wait = NOT_AUTHORIZED_RETRY_MS;
1805
+ for (; ; ) {
1806
+ const result = await session.call(
1807
+ "PUT",
1808
+ `/v1/admin/policies/${encodeURIComponent(options.slug)}`,
1809
+ { title, body }
1810
+ );
1811
+ if (result.ok) {
1812
+ return {
1813
+ exitCode: EXIT.OK,
1814
+ output: { ok: true, storeId: key.storeId, slug: options.slug, id: result.body.id }
1815
+ };
1816
+ }
1817
+ const message = typeof result.detail.message === "string" ? result.detail.message : void 0;
1818
+ if (result.code === "publish_refused" && message === NOT_AUTHORIZED_MESSAGE) {
1819
+ if (session.remaining() <= wait) {
1820
+ throw session.notDone("not_authorized_yet", {
1821
+ hint: "the store's catalog key is not on the relay yet: run the resume command in about a minute"
1822
+ });
1823
+ }
1824
+ await session.sleep(wait);
1825
+ wait *= 2;
1826
+ continue;
1827
+ }
1828
+ switch (result.code) {
1829
+ case "publish_refused":
1830
+ throw session.notDone("publish_refused", {
1831
+ hint: "the relay did not take the policy: run the resume command in about a minute",
1832
+ ...message === void 0 ? {} : { message }
1833
+ });
1834
+ case "policy_imported":
1835
+ throw new AskrExit(EXIT.REFUSED, "policy_imported", {
1836
+ hint: "your Shopify connector imports this policy: change it in Shopify"
1837
+ });
1838
+ case "too_many_policies":
1839
+ throw new AskrExit(EXIT.REFUSED, "too_many_policies", {
1840
+ hint: "a store has at most 50 policies: remove one in the admin"
1841
+ });
1842
+ case "inactive":
1843
+ throw inactiveExit(view);
1844
+ case "bad_request":
1845
+ throw new AskrExit(EXIT.BAD_INPUT, "bad_request");
1846
+ default:
1847
+ throw refusalExit(session, result);
1848
+ }
1849
+ }
1850
+ }
1851
+ var init_policy = __esm({
1852
+ "src/commands/askr/policy.ts"() {
1853
+ init_constants();
1854
+ init_errors();
1855
+ init_files();
1856
+ init_read();
1857
+ init_store();
1858
+ }
1859
+ });
1860
+
1861
+ // src/commands/askr/connector-run.ts
1862
+ function isRecord2(value) {
1863
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1864
+ }
1865
+ function lengthOf(value) {
1866
+ return Array.isArray(value) ? value.length : 0;
1867
+ }
1868
+ function summaryOfRun(result) {
1869
+ if (!isRecord2(result) || typeof result.status !== "string") {
1870
+ return null;
1871
+ }
1872
+ const summary = { status: result.status };
1873
+ if (result.status === "ok" && isRecord2(result.diff)) {
1874
+ summary.counts = {
1875
+ created: lengthOf(result.diff.created),
1876
+ updated: lengthOf(result.diff.updated),
1877
+ hidden: lengthOf(result.diff.hidden),
1878
+ unchanged: lengthOf(result.diff.unchanged)
1879
+ };
1880
+ }
1881
+ if (result.status === "error" && result.reason === "too_many_products") {
1882
+ summary.reason = "too_many_products";
1883
+ if (typeof result.count === "number") {
1884
+ summary.count = result.count;
1885
+ }
1886
+ if (typeof result.max === "number") {
1887
+ summary.max = result.max;
1888
+ }
1889
+ } else if (result.status === "error" && result.message === SYNC_BUSY_MESSAGE) {
1890
+ summary.reason = "sync_busy";
1891
+ }
1892
+ if (typeof result.httpStatus === "number") {
1893
+ summary.httpStatus = result.httpStatus;
1894
+ }
1895
+ return summary;
1896
+ }
1897
+ var init_connector_run = __esm({
1898
+ "src/commands/askr/connector-run.ts"() {
1899
+ init_constants();
1900
+ }
1901
+ });
1902
+
1903
+ // src/commands/askr/connector.ts
1904
+ var connector_exports = {};
1905
+ __export(connector_exports, {
1906
+ runConnector: () => runConnector
1907
+ });
1908
+ function resultExit(summary, detail) {
1909
+ if (summary.status === "ok") {
1910
+ return void 0;
1911
+ }
1912
+ if (summary.status === "verification_failed") {
1913
+ return new AskrExit(EXIT.BAD_INPUT, "verification_failed", {
1914
+ hint: META_HINT,
1915
+ fields: detail
1916
+ });
1917
+ }
1918
+ if (summary.reason === "too_many_products") {
1919
+ return new AskrExit(EXIT.LIMIT, "too_many_products", {
1920
+ hint: "the shop has more products than the store's plan allows",
1921
+ fields: { count: summary.count, max: summary.max, upgrade: UPGRADE }
1922
+ });
1923
+ }
1924
+ if (summary.status === "source_closed") {
1925
+ return new AskrExit(EXIT.REFUSED, "source_closed", {
1926
+ hint: BOT_CHECK_HINT,
1927
+ fields: { httpStatus: summary.httpStatus ?? null }
1928
+ });
1929
+ }
1930
+ return new AskrExit(EXIT.REFUSED, summary.status === "error" ? "error" : summary.status, {
1931
+ hint: "the connector could not read the shop: check the shop address, or open the Connector tab in the admin",
1932
+ fields: detail
1933
+ });
1934
+ }
1935
+ function failuresOf(result) {
1936
+ if (typeof result !== "object" || result === null) {
1937
+ return {};
1938
+ }
1939
+ const detail = {};
1940
+ if ("failures" in result && Array.isArray(result.failures)) {
1941
+ detail.failures = result.failures;
1942
+ }
1943
+ if ("message" in result && typeof result.message === "string") {
1944
+ detail.message = result.message;
1945
+ }
1946
+ return detail;
1947
+ }
1948
+ function busyExit(session, connector) {
1949
+ if (!connector.enabled) {
1950
+ return session.notDone("sync_running", {
1951
+ hint: "an earlier preview is still running: run the resume command in 150 seconds",
1952
+ fields: { retryAfterSeconds: 150 }
1953
+ });
1954
+ }
1955
+ if (summaryOfRun(connector.lastStatus)?.reason === "sync_busy") {
1956
+ return session.notDone("sync_running", {
1957
+ hint: "the last run found another sync running: run the resume command in 150 seconds",
1958
+ fields: { retryAfterSeconds: 150 }
1959
+ });
1960
+ }
1961
+ return session.notDone("sync_running", {
1962
+ hint: "a sync of the connector is running: follow it with askr status",
1963
+ resume: session.resumeWith("status")
1964
+ });
1965
+ }
1966
+ function noConnectorExit() {
1967
+ return new AskrExit(EXIT.BAD_INPUT, "no_connector", {
1968
+ hint: "set the connector up first: askr init --source connector --platform ..."
1969
+ });
1970
+ }
1971
+ function actionRefusal(session, view, result) {
1972
+ if (!result.ok && result.code === "inactive") {
1973
+ return inactiveExit(view);
1974
+ }
1975
+ if (!result.ok && result.code === "no_connector") {
1976
+ return noConnectorExit();
1977
+ }
1978
+ return refusalExit(session, result);
1979
+ }
1980
+ async function runConnector(session) {
1981
+ const key = await useOwnerKey(session);
1982
+ const view = await readView(session);
1983
+ if (view.status !== "active" || view.tier === null) {
1984
+ throw inactiveExit(view);
1985
+ }
1986
+ const connector = view.connector;
1987
+ if (connector === null) {
1988
+ throw noConnectorExit();
1989
+ }
1990
+ const lastRunAtBefore = connector.lastRunAt;
1991
+ const preview = await session.call(
1992
+ "POST",
1993
+ "/v1/admin/connector/preview",
1994
+ void 0,
1995
+ {
1996
+ timeoutMs: PREVIEW_TIMEOUT_MS,
1997
+ onTimeout: () => session.notDone("preview_timeout", {
1998
+ hint: SLOW_SHOP_HINT,
1999
+ resume: session.resumeWith("connector"),
2000
+ fields: { retryAfterSeconds: 90 }
2001
+ })
2002
+ }
2003
+ );
2004
+ if (!preview.ok) {
2005
+ if (preview.code === "sync_running") {
2006
+ throw busyExit(session, connector);
2007
+ }
2008
+ throw actionRefusal(session, view, preview);
2009
+ }
2010
+ const previewed = summaryOfRun(preview.body.result);
2011
+ if (previewed === null) {
2012
+ throw new AskrExit(EXIT.REFUSED, "unexpected");
2013
+ }
2014
+ const previewExit = resultExit(previewed, failuresOf(preview.body.result));
2015
+ if (previewExit !== void 0) {
2016
+ throw previewExit;
2017
+ }
2018
+ const skipped = typeof preview.body.result === "object" && preview.body.result !== null && "skipped" in preview.body.result && Array.isArray(preview.body.result.skipped) ? preview.body.result.skipped.length : 0;
2019
+ const enabled = await session.call("POST", "/v1/admin/connector/enable");
2020
+ if (!enabled.ok) {
2021
+ throw actionRefusal(session, view, enabled);
2022
+ }
2023
+ for (; ; ) {
2024
+ if (session.remaining() <= SYNC_POLL_MS) {
2025
+ throw session.notDone("first_sync_pending", {
2026
+ hint: "the first sync has not run yet: check that connector.lastRunAt is newer than lastRunAtBefore",
2027
+ resume: session.resumeWith("status"),
2028
+ fields: { enabled: true, lastRunAtBefore }
2029
+ });
2030
+ }
2031
+ await session.sleep(SYNC_POLL_MS);
2032
+ const current = (await readView(session)).connector;
2033
+ const lastRunAt = current?.lastRunAt ?? null;
2034
+ if (current === null || lastRunAt === null || lastRunAtBefore !== null && lastRunAt <= lastRunAtBefore) {
2035
+ continue;
2036
+ }
2037
+ const run = summaryOfRun(current.lastStatus);
2038
+ if (run?.reason === "sync_busy") {
2039
+ throw session.notDone("sync_busy", {
2040
+ hint: "the first run found another sync running and did nothing: run the resume command in a minute",
2041
+ resume: session.resumeWith("connector"),
2042
+ fields: { retryAfterSeconds: 60 }
2043
+ });
2044
+ }
2045
+ const runExit = run === null ? void 0 : resultExit(run, failuresOf(current.lastStatus));
2046
+ if (runExit !== void 0) {
2047
+ throw runExit;
2048
+ }
2049
+ return {
2050
+ exitCode: EXIT.OK,
2051
+ output: {
2052
+ ok: true,
2053
+ storeId: key.storeId,
2054
+ preview: {
2055
+ status: previewed.status,
2056
+ created: previewed.counts?.created ?? 0,
2057
+ updated: previewed.counts?.updated ?? 0,
2058
+ hidden: previewed.counts?.hidden ?? 0,
2059
+ skipped
2060
+ },
2061
+ enabled: true,
2062
+ lastRun: {
2063
+ at: lastRunAt,
2064
+ status: run?.status ?? null,
2065
+ ...run?.counts ?? {}
2066
+ }
2067
+ }
2068
+ };
2069
+ }
2070
+ }
2071
+ var META_HINT, BOT_CHECK_HINT, SLOW_SHOP_HINT;
2072
+ var init_connector = __esm({
2073
+ "src/commands/askr/connector.ts"() {
2074
+ init_connector_run();
2075
+ init_constants();
2076
+ init_errors();
2077
+ init_store();
2078
+ META_HINT = 'add <meta name="askr-verification" content="<Store ID>"> to the head of your home page (askr embed prints it), deploy, then run askr connector again';
2079
+ BOT_CHECK_HINT = "the shop refused to be read: it may block automated readers (a bot check, a password or maintenance page); make the products public or allow the reader, then run askr connector again";
2080
+ SLOW_SHOP_HINT = "the shop is slow to read; run the resume command in 90 seconds. A shop that is always this slow: use the admin's Connector tab, whose preview waits the full 2 minutes";
2081
+ }
2082
+ });
2083
+
2084
+ // src/commands/askr/status.ts
2085
+ var status_exports = {};
2086
+ __export(status_exports, {
2087
+ BUDGET_HINT: () => BUDGET_HINT,
2088
+ runStatus: () => runStatus
2089
+ });
2090
+ function money(value) {
2091
+ try {
2092
+ return new Decimal2(value).toString();
2093
+ } catch {
2094
+ return "0";
2095
+ }
2096
+ }
2097
+ function connectorOf(view) {
2098
+ const connector = view.connector;
2099
+ if (connector === null) {
2100
+ return null;
2101
+ }
2102
+ const run = summaryOfRun(connector.lastStatus);
2103
+ return {
2104
+ platform: connector.platform,
2105
+ url: connector.url,
2106
+ enabled: connector.enabled,
2107
+ lastRunAt: connector.lastRunAt,
2108
+ lastStatus: run?.status ?? null,
2109
+ ...run?.reason === void 0 ? {} : { lastReason: run.reason },
2110
+ ...run?.reason === "too_many_products" ? { count: run.count, max: run.max } : {},
2111
+ ...run?.counts === void 0 ? {} : { lastCounts: run.counts }
2112
+ };
2113
+ }
2114
+ async function probeOnce(session, view, origin) {
2115
+ const visitor = getPublicKey$1(generateSecretKey$1());
2116
+ const result = await session.call(
2117
+ "POST",
2118
+ "/v1/session",
2119
+ { store: view.owner, visitor },
2120
+ { unsigned: true, headers: { origin } }
2121
+ );
2122
+ if (result.ok) {
2123
+ return "ok";
2124
+ }
2125
+ if (result.status === 429) {
2126
+ return "rate_limited";
2127
+ }
2128
+ if (result.status === 410) {
2129
+ return "moved";
2130
+ }
2131
+ if (result.status === 403) {
2132
+ return "forbidden";
2133
+ }
2134
+ if (result.code === "not_ready") {
2135
+ return "not_ready";
2136
+ }
2137
+ const reason = result.detail.reason;
2138
+ if (reason === "inactive") {
2139
+ return view.status === "active" ? "not_ready" : "inactive";
2140
+ }
2141
+ return reason === "budget" ? "budget" : "error";
2142
+ }
2143
+ async function probe(session, view, origin) {
2144
+ for (; ; ) {
2145
+ const result = await probeOnce(session, view, origin);
2146
+ const retried = result === "not_ready" || result === "forbidden";
2147
+ if (!retried || session.remaining() <= PROBE_RETRY_MS) {
2148
+ return { origin, result };
2149
+ }
2150
+ await session.sleep(PROBE_RETRY_MS);
2151
+ }
2152
+ }
2153
+ function probeExit(session, view, probed, status) {
2154
+ const fields = { ...status, probe: probed };
2155
+ switch (probed.result) {
2156
+ case "ok":
2157
+ return void 0;
2158
+ case "not_ready":
2159
+ return session.notDone("not_ready", {
2160
+ hint: "the chat is not served yet: run the resume command in about a minute",
2161
+ fields
2162
+ });
2163
+ case "rate_limited":
2164
+ return session.notDone("rate_limited", {
2165
+ hint: "the gateway asked to slow down: run the resume command in a minute",
2166
+ fields: { ...fields, retryAfterSeconds: 60 }
2167
+ });
2168
+ case "forbidden":
2169
+ return new AskrExit(EXIT.REFUSED, "forbidden", {
2170
+ hint: "the probed origin is not in the store's origins: run askr init --update with the right --origin",
2171
+ fields
2172
+ });
2173
+ case "inactive":
2174
+ return new AskrExit(EXIT.REFUSED, "inactive", { hint: planHintOf(view), fields });
2175
+ case "budget":
2176
+ return new AskrExit(EXIT.LIMIT, "budget", {
2177
+ hint: BUDGET_HINT,
2178
+ fields
2179
+ });
2180
+ case "moved":
2181
+ return movedExit(fields);
2182
+ default:
2183
+ return new AskrExit(EXIT.REFUSED, "probe_failed", { fields });
2184
+ }
2185
+ }
2186
+ function skippedProbe(view) {
2187
+ return view.status === "pending" ? {
2188
+ result: "skipped",
2189
+ reason: "the store is pending: the chat is not served until its plan is active"
2190
+ } : { result: "skipped", reason: "the store lists no origin" };
2191
+ }
2192
+ async function runStatus(session, options) {
2193
+ const key = await readOwnerKey(session.deps.home, session.profile);
2194
+ if (key === void 0) {
2195
+ return { exitCode: EXIT.OK, output: { ok: true, profile: session.profile, store: null } };
2196
+ }
2197
+ session.signAs(key.secretKey);
2198
+ const read = await session.call("GET", "/v1/admin/store");
2199
+ if (!read.ok && read.status === 404 && read.code === "no_store") {
2200
+ return {
2201
+ exitCode: EXIT.OK,
2202
+ output: {
2203
+ ok: true,
2204
+ profile: session.profile,
2205
+ store: null,
2206
+ ownerKeyFile: key.path,
2207
+ hint: "a key exists but no store yet: askr init creates it with this key"
2208
+ }
2209
+ };
2210
+ }
2211
+ if (!read.ok) {
2212
+ throw refusalExit(session, read);
2213
+ }
2214
+ const view = read.body;
2215
+ const { config } = await readSigned(session, key.owner, key.secretKey);
2216
+ const catalogKey = config?.catalogKey ?? view.catalogKey;
2217
+ const policyKey = config?.policyKey ?? view.catalogKey;
2218
+ const listings = await readListings(session, catalogKey);
2219
+ const policies = await readPolicySlugs(session, policyKey);
2220
+ const awaitingPlan = awaitingPlanOf(view);
2221
+ const output = {
2222
+ ok: true,
2223
+ profile: session.profile,
2224
+ storeId: key.storeId,
2225
+ status: view.status,
2226
+ tier: tierOf(view),
2227
+ awaitingPlan,
2228
+ name: config?.name ?? null,
2229
+ origins: config?.origins ?? [],
2230
+ language: config?.language ?? null,
2231
+ currency: config?.currency ?? null,
2232
+ source: config === void 0 ? null : config.source,
2233
+ products: { listed: listings.listed.length, visible: listings.visible },
2234
+ policies,
2235
+ catalogSync: view.catalogSync === null ? null : { state: view.catalogSync.state },
2236
+ connector: connectorOf(view),
2237
+ events: {
2238
+ pending: view.events.pending,
2239
+ failing: view.events.failing.length
2240
+ },
2241
+ usage: {
2242
+ conversations: view.usage.conversations,
2243
+ todaySpentUsd: money(view.usage.today.spent),
2244
+ monthSpentUsd: money(view.usage.month.spent)
2245
+ },
2246
+ ownerKeyFile: key.path,
2247
+ adminUrl: session.adminUrl,
2248
+ upgrade: UPGRADE
2249
+ };
2250
+ if (view.status !== "active") {
2251
+ output.hint = planHintOf(view);
2252
+ }
2253
+ if (options.probe !== true) {
2254
+ return { exitCode: EXIT.OK, output };
2255
+ }
2256
+ const origin = config?.origins[0];
2257
+ if (view.status === "pending" || origin === void 0) {
2258
+ output.probe = skippedProbe(view);
2259
+ return { exitCode: EXIT.OK, output };
2260
+ }
2261
+ const probed = await probe(session, view, origin);
2262
+ output.probe = probed;
2263
+ const status = Object.fromEntries(Object.entries(output).filter(([name]) => name !== "ok"));
2264
+ const failed = probeExit(session, view, probed, status);
2265
+ if (failed !== void 0) {
2266
+ throw failed;
2267
+ }
2268
+ return { exitCode: EXIT.OK, output };
2269
+ }
2270
+ var BUDGET_HINT;
2271
+ var init_status = __esm({
2272
+ "src/commands/askr/status.ts"() {
2273
+ init_connector_run();
2274
+ init_constants();
2275
+ init_errors();
2276
+ init_owner_key();
2277
+ init_read();
2278
+ init_store();
2279
+ BUDGET_HINT = "the store reached its plan's monthly limit, so the chat does not answer until the plan is upgraded or the next month starts: to upgrade, message us with your Store ID (upgrade.contact)";
2280
+ }
2281
+ });
2282
+
2283
+ // src/commands/askr/embed.ts
2284
+ var embed_exports = {};
2285
+ __export(embed_exports, {
2286
+ elementSnippet: () => elementSnippet,
2287
+ runEmbed: () => runEmbed,
2288
+ scriptSnippet: () => scriptSnippet,
2289
+ verificationMeta: () => verificationMeta
2290
+ });
2291
+ function scriptSnippet(npub) {
2292
+ return `<script src="${WIDGET_SCRIPT_URL}" data-store="${npub}" async></script>`;
2293
+ }
2294
+ function elementSnippet(npub) {
2295
+ return `<${WIDGET_ELEMENT} store="${npub}"></${WIDGET_ELEMENT}>
2296
+ <script src="${WIDGET_SCRIPT_URL}" async></script>`;
2297
+ }
2298
+ function verificationMeta(npub) {
2299
+ return `<meta name="askr-verification" content="${npub}">`;
2300
+ }
2301
+ function cspSources(askr) {
2302
+ const relayOrigins = askr.ASKR_RELAYS.map((relay) => new URL(relay).origin);
2303
+ return [
2304
+ { directive: "script-src", sources: [askr.ASKR_API_BASE] },
2305
+ { directive: "connect-src", sources: [askr.ASKR_API_BASE, ...relayOrigins] },
2306
+ { directive: "img-src", sources: ["https:"] }
2307
+ ];
2308
+ }
2309
+ async function runEmbed(session) {
2310
+ const key = await useOwnerKey(session);
2311
+ await readView(session);
2312
+ const { config } = await readSigned(session, key.owner, key.secretKey);
2313
+ if (config === void 0) {
2314
+ throw new AskrExit(EXIT.BAD_INPUT, "no_settings", { hint: "run askr init first" });
2315
+ }
2316
+ return {
2317
+ exitCode: EXIT.OK,
2318
+ output: {
2319
+ ok: true,
2320
+ storeId: key.storeId,
2321
+ snippet: scriptSnippet(key.storeId),
2322
+ element: elementSnippet(key.storeId),
2323
+ verificationMeta: verificationMeta(key.storeId),
2324
+ csp: cspSources(session.askr),
2325
+ platformHints: PLATFORM_HINTS,
2326
+ ...config.source.kind === "admin" ? { addToCart: ADD_TO_CART } : {}
2327
+ }
2328
+ };
2329
+ }
2330
+ var ADD_TO_CART, PLATFORM_HINTS;
2331
+ var init_embed = __esm({
2332
+ "src/commands/askr/embed.ts"() {
2333
+ init_constants();
2334
+ init_errors();
2335
+ init_read();
2336
+ init_store();
2337
+ ADD_TO_CART = `<script>
2338
+ window.Askr = window.Askr || {};
2339
+ window.Askr.onAddToCart = function (detail) {
2340
+ // detail.d: the product ID; detail.sku: its SKU, if it has one;
2341
+ // detail.variant: the variant ID, when the shopper's pick determines one;
2342
+ // detail.options: { "Size": "M", ... }, whenever a choice is made.
2343
+ // Put the product in your cart here.
2344
+ };
2345
+ </script>`;
2346
+ PLATFORM_HINTS = [
2347
+ {
2348
+ platform: "Shopify",
2349
+ where: "Online Store, Themes, then Edit code in the theme menu: open theme.liquid and paste it before </body>."
2350
+ },
2351
+ {
2352
+ platform: "WordPress and WooCommerce",
2353
+ where: "a plugin that adds code to every page (such as WPCode), set to the footer."
2354
+ },
2355
+ {
2356
+ platform: "Wix",
2357
+ where: "Settings, Custom Code, on all pages (a paid plan with a connected domain). Not the Embed HTML element: it runs on another address, where the chat does not answer."
2358
+ },
2359
+ {
2360
+ platform: "Squarespace",
2361
+ where: "Settings, Code Injection, in the footer (a Core plan or higher). A code block on a page shows the chat on that page only."
2362
+ },
2363
+ {
2364
+ platform: "Other site builders",
2365
+ where: "the site-wide custom code setting, never a block on one page."
2366
+ }
2367
+ ];
2368
+ }
2369
+ });
2370
+
2371
+ // src/commands/askr/export-key.ts
2372
+ var export_key_exports = {};
2373
+ __export(export_key_exports, {
2374
+ keyFileText: () => keyFileText2,
2375
+ runExportKey: () => runExportKey
2376
+ });
2377
+ function keyFileText2(nsec, npub, apiBase) {
2378
+ return [
2379
+ "Askr secret key",
2380
+ "",
2381
+ `Secret key: ${nsec}`,
2382
+ `Store ID: ${npub}`,
2383
+ "",
2384
+ `To sign in, open the Askr admin at ${apiBase}/admin/ and paste the secret key.`,
2385
+ "",
2386
+ "Keep this file private. Whoever has this file controls your store: its settings, products and policies. Nobody can recover the key for you if you lose it.",
2387
+ ""
2388
+ ].join("\n");
2389
+ }
2390
+ async function runExportKey(session, out) {
2391
+ const key = await useOwnerKey(session);
2392
+ const text = keyFileText2(nip19.nsecEncode(key.secretKey), key.storeId, session.apiBase);
2393
+ try {
2394
+ await writeFile(out, text, { encoding: "utf-8", mode: FILE_MODE2, flag: "wx" });
2395
+ } catch (error) {
2396
+ const exists = typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
2397
+ throw new AskrExit(EXIT.BAD_INPUT, exists ? "file_exists" : "file_not_writable", {
2398
+ hint: exists ? "--out: a file is already there; name a new one" : "--out: cannot write there"
2399
+ });
2400
+ }
2401
+ return { exitCode: EXIT.OK, output: { ok: true, path: out } };
2402
+ }
2403
+ var FILE_MODE2;
2404
+ var init_export_key = __esm({
2405
+ "src/commands/askr/export-key.ts"() {
2406
+ init_errors();
2407
+ init_store();
2408
+ FILE_MODE2 = 384;
2409
+ }
2410
+ });
38
2411
  function resolveLlmTimeoutMs() {
39
2412
  const raw = process.env.ELISYM_LLM_TIMEOUT_MS;
40
2413
  if (raw === void 0) {
@@ -53,9 +2426,9 @@ function sleepWithSignal(ms, signal) {
53
2426
  return Promise.reject(createAbortError());
54
2427
  }
55
2428
  if (!signal) {
56
- return new Promise((resolve4) => setTimeout(resolve4, ms));
2429
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
57
2430
  }
58
- return new Promise((resolve4, reject) => {
2431
+ return new Promise((resolve5, reject) => {
59
2432
  const cleanup = () => {
60
2433
  clearTimeout(timer);
61
2434
  signal.removeEventListener("abort", onAbort);
@@ -66,7 +2439,7 @@ function sleepWithSignal(ms, signal) {
66
2439
  };
67
2440
  const timer = setTimeout(() => {
68
2441
  cleanup();
69
- resolve4();
2442
+ resolve5();
70
2443
  }, ms);
71
2444
  signal.addEventListener("abort", onAbort, { once: true });
72
2445
  });
@@ -1062,8 +3435,8 @@ var init_llm = __esm({
1062
3435
  });
1063
3436
 
1064
3437
  // src/commands/init.ts
1065
- var init_exports = {};
1066
- __export(init_exports, {
3438
+ var init_exports2 = {};
3439
+ __export(init_exports2, {
1067
3440
  cmdInit: () => cmdInit,
1068
3441
  fetchModels: () => fetchModels3,
1069
3442
  parseNetworkOption: () => parseNetworkOption
@@ -1492,7 +3865,7 @@ async function promptYaml(inquirer, networkFlag) {
1492
3865
  });
1493
3866
  return { yaml, apiKey: envKey ? void 0 : apiKey };
1494
3867
  }
1495
- var init_init = __esm({
3868
+ var init_init2 = __esm({
1496
3869
  "src/commands/init.ts"() {
1497
3870
  init_llm();
1498
3871
  }
@@ -1605,6 +3978,415 @@ async function cmdAskrKey(agentName, options) {
1605
3978
  console.warn(" ! No passphrase set: the catalog key is stored unencrypted on disk.");
1606
3979
  }
1607
3980
  }
3981
+
3982
+ // src/commands/askr/register.ts
3983
+ var PROFILE_FLAG = "--profile <name>";
3984
+ var PROFILE_HELP = "a separate store on this computer: its own owner key file (default: default)";
3985
+ function collect(value, previous) {
3986
+ return [...previous, value];
3987
+ }
3988
+ function registerAskr(program2, run, args, jsonErrors) {
3989
+ const askr = program2.command("askr").description(
3990
+ "Set up and update an Askr store from a terminal or an AI coding agent: JSON output, no prompts"
3991
+ );
3992
+ if (jsonErrors) {
3993
+ askr.exitOverride().configureOutput({ writeErr: () => {
3994
+ } });
3995
+ }
3996
+ const context = (options) => ({
3997
+ ...options.profile === void 0 ? {} : { profile: options.profile },
3998
+ args
3999
+ });
4000
+ askr.command("init").description("Create the store (or update it) and sign its settings; never chooses a plan").option("--name <text>", "store name (required for a new store)").option("--origin <https-origin>", "a site the chat runs on; repeat for each", collect, []).option("--language <bcp47>", "catalog language (default en for a new store)").option("--currency <iso4217>", "store currency (default USD for a new store)").option("--source <source>", "where products come from: admin (files) or connector").option("--platform <platform>", "connector platform: shopify, woocommerce or google").option("--shop-url <url>", "Shopify or WooCommerce: the https address of the shop").option("--feed-url <url>", "google: the https address of the product feed").option("--display-name <text>", "the assistant's name in the chat").option("--greeting <text>", "the first message the chat shows").option("--contact <https-url>", "a contact link the assistant may give").option("--voice-file <path>", "a text file with the assistant's voice").option(
4001
+ "--instructions-file <path>",
4002
+ "a text file with what the assistant always or never says"
4003
+ ).option("--owner-key-file <path>", "adopt a store made in the admin: its secret key file").option("--update", "allow changing the name or origins of the existing store").option(PROFILE_FLAG, PROFILE_HELP).action(
4004
+ (options) => run({ command: "init", options }, context(options))
4005
+ );
4006
+ askr.command("plan <plan>").description(
4007
+ "Choose a plan: only free is self-serve; run it only on the human's explicit choice"
4008
+ ).option(PROFILE_FLAG, PROFILE_HELP).action(
4009
+ (plan, options) => run({ command: "plan", plan }, context(options))
4010
+ );
4011
+ askr.command("products").description("Publish products from a JSON or CSV file (source admin)").requiredOption("--file <path>", "products.json or products.csv").option(
4012
+ "--replace",
4013
+ "the file is the whole catalog: listed products missing from it are hidden"
4014
+ ).option("--allow-hide", "with --replace: allow hiding products (after the human confirmed)").option("--dry-run", "print what would change, publish nothing").option(PROFILE_FLAG, PROFILE_HELP).action(
4015
+ (options) => run({ command: "products", options }, context(options))
4016
+ );
4017
+ askr.command("policy").description("Publish one policy page (returns, shipping, warranty, faq, ...)").requiredOption("--slug <slug>", "lowercase letters, digits and hyphens, like returns").requiredOption("--title <text>", "the policy title").requiredOption("--file <path>", "a Markdown file with the policy text").option(PROFILE_FLAG, PROFILE_HELP).action(
4018
+ (options) => run({ command: "policy", options }, context(options))
4019
+ );
4020
+ askr.command("connector").description("Preview the shop connector, enable it, and wait for its first sync").option(PROFILE_FLAG, PROFILE_HELP).action((options) => run({ command: "connector" }, context(options)));
4021
+ askr.command("status").description("Show the store: plan, products, policies, connector, usage").option("--probe", "also check that the chat is served on the first site").option(PROFILE_FLAG, PROFILE_HELP).action(
4022
+ (options) => run({ command: "status", options }, context(options))
4023
+ );
4024
+ askr.command("embed").description("Print the widget snippet, the verification meta tag and the CSP sources").option(PROFILE_FLAG, PROFILE_HELP).action((options) => run({ command: "embed" }, context(options)));
4025
+ askr.command("export-key").description(
4026
+ "Write the owner key as a key file for your password manager (run it yourself, never by an agent)"
4027
+ ).requiredOption("--out <path>", "a new file to write (never overwritten)").option(PROFILE_FLAG, PROFILE_HELP).action(
4028
+ (options) => run({ command: "export-key", out: options.out }, context(options))
4029
+ );
4030
+ return askr;
4031
+ }
4032
+
4033
+ // src/commands/askr/runner.ts
4034
+ init_errors();
4035
+ init_owner_key();
4036
+
4037
+ // src/commands/askr/session.ts
4038
+ init_constants();
4039
+ init_errors();
4040
+ function defaultDeps(askr) {
4041
+ return {
4042
+ fetch: (input, init) => globalThis.fetch(input, init),
4043
+ connectRelay: (url) => askr.connectSyncClient(url),
4044
+ now: () => Date.now(),
4045
+ home: process.env.HOME ?? homedir(),
4046
+ env: process.env,
4047
+ notice: (line) => process.stderr.write(`${line}
4048
+ `)
4049
+ };
4050
+ }
4051
+ var SHELL_SAFE_RE = /^[A-Za-z0-9_@%+=:,./-]+$/;
4052
+ function shellQuote(value) {
4053
+ return SHELL_SAFE_RE.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
4054
+ }
4055
+ function isRecord(value) {
4056
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4057
+ }
4058
+ function recordOf(text) {
4059
+ if (text === void 0) {
4060
+ return {};
4061
+ }
4062
+ try {
4063
+ const parsed = JSON.parse(text);
4064
+ return isRecord(parsed) ? parsed : {};
4065
+ } catch {
4066
+ return {};
4067
+ }
4068
+ }
4069
+ function withoutTrailingSlash(value) {
4070
+ return value.replace(/\/+$/u, "");
4071
+ }
4072
+ function overridden(deps, name, fallback) {
4073
+ const value = deps.env[name]?.trim();
4074
+ if (value === void 0 || value === "") {
4075
+ return fallback;
4076
+ }
4077
+ let url;
4078
+ try {
4079
+ url = new URL(value);
4080
+ } catch {
4081
+ throw new AskrExit(EXIT.BAD_INPUT, "bad_override", { hint: `${name} is not a URL` });
4082
+ }
4083
+ if (!LOCAL_HOSTS.includes(url.hostname) && deps.env[UNSAFE_OVERRIDE_ENV] !== "1") {
4084
+ throw new AskrExit(EXIT.BAD_INPUT, "bad_override", {
4085
+ hint: `${name} is for local tests only: it must name localhost or 127.0.0.1`
4086
+ });
4087
+ }
4088
+ const base = withoutTrailingSlash(value);
4089
+ deps.notice(`askr: ${name} override in use: ${base}`);
4090
+ return base;
4091
+ }
4092
+ var EXPIRED = Symbol("expired");
4093
+ var Session = class {
4094
+ askr;
4095
+ deps;
4096
+ profile;
4097
+ apiBase;
4098
+ relayUrl;
4099
+ adminUrl;
4100
+ args;
4101
+ deadline;
4102
+ relay;
4103
+ signer;
4104
+ constructor(input) {
4105
+ this.askr = input.askr;
4106
+ this.deps = input.deps;
4107
+ this.profile = input.profile;
4108
+ this.args = input.args;
4109
+ this.deadline = input.deps.now() + DEADLINE_MS;
4110
+ this.apiBase = overridden(input.deps, API_OVERRIDE_ENV, input.askr.ASKR_API_BASE);
4111
+ this.relayUrl = overridden(input.deps, RELAY_OVERRIDE_ENV, input.askr.ASKR_RELAYS[0] ?? "");
4112
+ this.adminUrl = this.apiBase === input.askr.ASKR_API_BASE ? ADMIN_URL : `${this.apiBase}/admin/`;
4113
+ }
4114
+ /** The owner key every admin call is signed with. */
4115
+ signAs(secretKey) {
4116
+ this.signer = secretKey;
4117
+ }
4118
+ remaining() {
4119
+ return Math.max(0, this.deadline - this.deps.now());
4120
+ }
4121
+ nowSecs() {
4122
+ return Math.floor(this.deps.now() / 1e3);
4123
+ }
4124
+ /** `--profile <name>`, when not the default. */
4125
+ profileArgs() {
4126
+ return this.profile === DEFAULT_PROFILE ? [] : ["--profile", this.profile];
4127
+ }
4128
+ /** The exact line that ran: re-running it finishes the job. */
4129
+ resumeSame() {
4130
+ return [ASKR_COMMAND, ...this.args.map((arg) => shellQuote(arg))].join(" ");
4131
+ }
4132
+ /** Another command of the same profile. */
4133
+ resumeWith(command) {
4134
+ return [ASKR_COMMAND, command, ...this.profileArgs()].join(" ");
4135
+ }
4136
+ /** Exit 4 with the line to resume with. */
4137
+ notDone(code, options = {}) {
4138
+ return new AskrExit(EXIT.NOT_DONE, code, {
4139
+ ...options,
4140
+ fields: { ...options.fields, resume: options.resume ?? this.resumeSame() }
4141
+ });
4142
+ }
4143
+ deadlineReached() {
4144
+ return this.notDone("deadline", {
4145
+ hint: "not done within this command's time: run the resume command in about a minute"
4146
+ });
4147
+ }
4148
+ /** Wait `ms`, or what is left of the deadline when less. */
4149
+ async sleep(ms) {
4150
+ const wait = Math.min(ms, this.remaining());
4151
+ await new Promise((resolve5) => setTimeout(resolve5, wait));
4152
+ }
4153
+ /** `work`, or EXPIRED when `ms` pass first; a late rejection of `work` is swallowed. */
4154
+ async within(work, ms) {
4155
+ work.catch(() => void 0);
4156
+ let timer;
4157
+ const expiry = new Promise((resolve5) => {
4158
+ timer = setTimeout(() => resolve5(EXPIRED), ms);
4159
+ });
4160
+ try {
4161
+ return await Promise.race([work, expiry]);
4162
+ } finally {
4163
+ clearTimeout(timer);
4164
+ }
4165
+ }
4166
+ async authorization(url, method, body) {
4167
+ const secretKey = this.signer;
4168
+ if (secretKey === void 0) {
4169
+ throw new Error("no owner key to sign with");
4170
+ }
4171
+ return this.askr.nip98Header({
4172
+ signEvent: async (template) => finalizeEvent(template, secretKey),
4173
+ url,
4174
+ method,
4175
+ body,
4176
+ now: this.nowSecs()
4177
+ });
4178
+ }
4179
+ /** One API call within the deadline, NIP-98 signed by O over the exact body. */
4180
+ async call(method, path, payload, options = {}) {
4181
+ const url = `${this.apiBase}${path}`;
4182
+ const body = payload === void 0 ? "" : JSON.stringify(payload);
4183
+ const headers = { ...options.headers };
4184
+ if (options.unsigned !== true) {
4185
+ headers.authorization = await this.authorization(url, method, body);
4186
+ }
4187
+ if (body !== "") {
4188
+ headers["content-type"] = "application/json";
4189
+ }
4190
+ const limit = Math.min(this.remaining(), options.timeoutMs ?? Number.POSITIVE_INFINITY);
4191
+ const ownBound = limit < this.remaining() ? options.onTimeout : void 0;
4192
+ const timedOut = () => ownBound === void 0 ? this.deadlineReached() : ownBound();
4193
+ if (limit <= 0) {
4194
+ throw timedOut();
4195
+ }
4196
+ const controller = new AbortController();
4197
+ const request = this.deps.fetch(url, {
4198
+ method,
4199
+ headers,
4200
+ ...body === "" ? {} : { body },
4201
+ signal: controller.signal
4202
+ });
4203
+ let response;
4204
+ try {
4205
+ response = await this.within(request, limit);
4206
+ } catch {
4207
+ throw this.notDone("network", {
4208
+ hint: "the Askr server could not be reached: check the connection and run the resume command"
4209
+ });
4210
+ }
4211
+ if (response === EXPIRED) {
4212
+ controller.abort();
4213
+ throw timedOut();
4214
+ }
4215
+ const text = await this.within(response.text(), this.remaining()).catch(() => void 0);
4216
+ if (text === EXPIRED) {
4217
+ throw this.deadlineReached();
4218
+ }
4219
+ if (response.ok && text !== void 0) {
4220
+ try {
4221
+ const body2 = JSON.parse(text);
4222
+ return { ok: true, status: response.status, body: body2 };
4223
+ } catch {
4224
+ return { ok: false, status: response.status, code: "unexpected", detail: {} };
4225
+ }
4226
+ }
4227
+ const detail = recordOf(text);
4228
+ const code = typeof detail.error === "string" ? detail.error : "unexpected";
4229
+ return { ok: false, status: response.status, code, detail };
4230
+ }
4231
+ async connection() {
4232
+ if (this.relay !== void 0) {
4233
+ return this.relay;
4234
+ }
4235
+ const connecting = this.deps.connectRelay(this.relayUrl);
4236
+ let relay;
4237
+ try {
4238
+ relay = await this.within(connecting, this.remaining());
4239
+ } catch {
4240
+ throw this.notDone("relay_unavailable", {
4241
+ hint: "the Askr relay could not be reached: run the resume command in about a minute"
4242
+ });
4243
+ }
4244
+ if (relay === EXPIRED) {
4245
+ connecting.then((late) => late.close()).catch(() => void 0);
4246
+ throw this.deadlineReached();
4247
+ }
4248
+ this.relay = relay;
4249
+ return relay;
4250
+ }
4251
+ /**
4252
+ * A whole relay read, raced against the deadline: a read takes no signal, so
4253
+ * on expiry the connection is closed, which ends the pending read.
4254
+ */
4255
+ async relayQuery(filter) {
4256
+ const relay = await this.connection();
4257
+ let events;
4258
+ try {
4259
+ events = await this.within(relay.query([this.relayUrl], filter), this.remaining());
4260
+ } catch {
4261
+ this.close();
4262
+ throw this.notDone("relay_unavailable", {
4263
+ hint: "the Askr relay did not answer the whole read: run the resume command in about a minute"
4264
+ });
4265
+ }
4266
+ if (events === EXPIRED) {
4267
+ this.close();
4268
+ throw this.deadlineReached();
4269
+ }
4270
+ return events;
4271
+ }
4272
+ close() {
4273
+ this.relay?.close();
4274
+ this.relay = void 0;
4275
+ }
4276
+ };
4277
+
4278
+ // src/commands/askr/runner.ts
4279
+ var loadAskr = () => import('@elisym/askr');
4280
+ var PROCESS_IO = {
4281
+ write: (line, flushed) => {
4282
+ process.stdout.write(line, () => flushed());
4283
+ },
4284
+ exit: (code) => process.exit(code)
4285
+ };
4286
+ var DEFAULT_HOOKS = {
4287
+ loadAskr,
4288
+ deps: defaultDeps,
4289
+ io: PROCESS_IO,
4290
+ hasWebSocket: () => "WebSocket" in globalThis
4291
+ };
4292
+ function emit(outcome, io) {
4293
+ io.write(`${JSON.stringify(outcome.output)}
4294
+ `, () => io.exit(outcome.exitCode));
4295
+ }
4296
+ function outcomeOf(error) {
4297
+ if (error instanceof AskrExit) {
4298
+ return outcomeOfExit(error);
4299
+ }
4300
+ return outcomeOfExit(
4301
+ new AskrExit(EXIT.BAD_INPUT, "unexpected", {
4302
+ hint: "an unexpected error: run the command again, or report it",
4303
+ fields: { name: error instanceof Error ? error.name : typeof error }
4304
+ })
4305
+ );
4306
+ }
4307
+ async function dispatch(session, invocation) {
4308
+ switch (invocation.command) {
4309
+ case "init": {
4310
+ const { runInit: runInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
4311
+ return runInit2(session, invocation.options);
4312
+ }
4313
+ case "plan": {
4314
+ const { runPlan: runPlan2 } = await Promise.resolve().then(() => (init_plan(), plan_exports));
4315
+ return runPlan2(session, invocation.plan);
4316
+ }
4317
+ case "products": {
4318
+ const { runProducts: runProducts2 } = await Promise.resolve().then(() => (init_products(), products_exports));
4319
+ return runProducts2(session, invocation.options);
4320
+ }
4321
+ case "policy": {
4322
+ const { runPolicy: runPolicy2 } = await Promise.resolve().then(() => (init_policy(), policy_exports));
4323
+ return runPolicy2(session, invocation.options);
4324
+ }
4325
+ case "connector": {
4326
+ const { runConnector: runConnector2 } = await Promise.resolve().then(() => (init_connector(), connector_exports));
4327
+ return runConnector2(session);
4328
+ }
4329
+ case "status": {
4330
+ const { runStatus: runStatus2 } = await Promise.resolve().then(() => (init_status(), status_exports));
4331
+ return runStatus2(session, invocation.options);
4332
+ }
4333
+ case "embed": {
4334
+ const { runEmbed: runEmbed2 } = await Promise.resolve().then(() => (init_embed(), embed_exports));
4335
+ return runEmbed2(session);
4336
+ }
4337
+ case "export-key": {
4338
+ const { runExportKey: runExportKey2 } = await Promise.resolve().then(() => (init_export_key(), export_key_exports));
4339
+ return runExportKey2(session, invocation.out);
4340
+ }
4341
+ }
4342
+ }
4343
+ async function runAskrCommand(invocation, context, hooks = DEFAULT_HOOKS) {
4344
+ let session;
4345
+ let outcome;
4346
+ try {
4347
+ let askr;
4348
+ try {
4349
+ askr = await hooks.loadAskr();
4350
+ } catch {
4351
+ throw new AskrExit(EXIT.BAD_INPUT, "askr_unavailable", {
4352
+ hint: "the @elisym/askr package cannot be loaded: reinstall the CLI (npx -y @elisym/cli@latest)"
4353
+ });
4354
+ }
4355
+ if (!hooks.hasWebSocket()) {
4356
+ throw new AskrExit(EXIT.BAD_INPUT, "node_version", {
4357
+ hint: "Askr commands need Node 22 or newer"
4358
+ });
4359
+ }
4360
+ session = new Session({
4361
+ askr,
4362
+ deps: hooks.deps(askr),
4363
+ profile: profileOf(context.profile),
4364
+ args: context.args
4365
+ });
4366
+ outcome = await dispatch(session, invocation);
4367
+ } catch (error) {
4368
+ outcome = outcomeOf(error);
4369
+ } finally {
4370
+ session?.close();
4371
+ }
4372
+ emit(outcome, hooks.io);
4373
+ return outcome;
4374
+ }
4375
+ var ZERO_EXIT_CODES = /* @__PURE__ */ new Set(["commander.helpDisplayed", "commander.version"]);
4376
+ function emitParseError(error, io = PROCESS_IO) {
4377
+ if (error instanceof CommanderError && (error.exitCode === 0 || ZERO_EXIT_CODES.has(error.code))) {
4378
+ io.exit(EXIT.OK);
4379
+ return;
4380
+ }
4381
+ const exitCode = EXIT.BAD_INPUT;
4382
+ const outcome = error instanceof CommanderError ? outcomeOfExit(
4383
+ new AskrExit(exitCode, "bad_flag", {
4384
+ hint: error.code === "commander.help" ? "name a command: init, plan, products, policy, connector, status, embed, export-key" : "run askr <command> --help for its flags",
4385
+ ...error.code === "commander.help" ? {} : { message: error.message }
4386
+ })
4387
+ ) : outcomeOf(error);
4388
+ emit(outcome, io);
4389
+ }
1608
4390
  var MAX_CONCURRENT_JOBS = 10;
1609
4391
  var RECOVERY_MAX_RETRIES = 5;
1610
4392
  var RECOVERY_INTERVAL_SECS = 60;
@@ -2068,7 +4850,7 @@ function computeBridgePriceSubunits(quote, marginBps, feeBps) {
2068
4850
  throw new Error(`feeBps ${feeBps} >= ${BPS_DENOMINATOR} - refusing zero/negative denominator`);
2069
4851
  }
2070
4852
  return BigInt(
2071
- new Decimal(quote.toString()).mul(BPS_DENOMINATOR + marginBps).div(BPS_DENOMINATOR - feeBps).toDecimalPlaces(0, Decimal.ROUND_CEIL).toString()
4853
+ new Decimal2(quote.toString()).mul(BPS_DENOMINATOR + marginBps).div(BPS_DENOMINATOR - feeBps).toDecimalPlaces(0, Decimal2.ROUND_CEIL).toString()
2072
4854
  );
2073
4855
  }
2074
4856
  function buildSkillMd(input) {
@@ -2151,8 +4933,8 @@ function scanExistingSkills(skillsDir, candidateDTag, url) {
2151
4933
  }
2152
4934
  return scan;
2153
4935
  }
2154
- function describeUnacceptableAccepts(probe, agentNetwork) {
2155
- const networks = [...new Set(probe.accepts.map((requirement) => String(requirement.network)))];
4936
+ function describeUnacceptableAccepts(probe2, agentNetwork) {
4937
+ const networks = [...new Set(probe2.accepts.map((requirement) => String(requirement.network)))];
2156
4938
  if (networks.length > 0 && networks.every((network) => network.startsWith("eip155:"))) {
2157
4939
  return `the service accepts only EVM networks (${networks.join(", ")}) - not supported yet`;
2158
4940
  }
@@ -2244,9 +5026,9 @@ async function cmdX402Add(url, agentName, options) {
2244
5026
  const usdcAsset = resolveUsdcAsset(agentNetwork);
2245
5027
  console.log(`
2246
5028
  Probing ${url} (${method}, unpaid)...`);
2247
- let probe;
5029
+ let probe2;
2248
5030
  try {
2249
- probe = await probePaymentRequired(url, method);
5031
+ probe2 = await probePaymentRequired(url, method);
2250
5032
  } catch (error) {
2251
5033
  if (error instanceof X402ProbeError) {
2252
5034
  fail(error.message);
@@ -2258,9 +5040,9 @@ async function cmdX402Add(url, agentName, options) {
2258
5040
  maxUpstreamSubunits: BigInt(Number.MAX_SAFE_INTEGER),
2259
5041
  network: agentNetwork
2260
5042
  };
2261
- const requirement = selectAcceptableRequirement(probe.accepts, anyCeiling);
5043
+ const requirement = selectAcceptableRequirement(probe2.accepts, anyCeiling);
2262
5044
  if (requirement === void 0) {
2263
- fail(describeUnacceptableAccepts(probe, agentNetwork));
5045
+ fail(describeUnacceptableAccepts(probe2, agentNetwork));
2264
5046
  }
2265
5047
  const quote = requirementAmount(requirement);
2266
5048
  if (quote === null || quote <= 0n) {
@@ -2375,11 +5157,11 @@ async function cmdX402Add(url, agentName, options) {
2375
5157
  );
2376
5158
  }
2377
5159
  const priceSubunits = computeBridgePriceSubunits(quote, marginBps, feeBps);
2378
- const priceDisplay = new Decimal(priceSubunits.toString()).div(new Decimal(10).pow(usdcAsset.decimals)).toString();
5160
+ const priceDisplay = new Decimal2(priceSubunits.toString()).div(new Decimal2(10).pow(usdcAsset.decimals)).toString();
2379
5161
  const protocolFee = calculateProtocolFee(Number(priceSubunits), feeBps);
2380
5162
  const netMargin = priceSubunits - BigInt(protocolFee) - quote;
2381
5163
  const fallbackName = slugFromUrl(parsedUrl);
2382
- const rawName = options.name ?? probe.resource?.serviceName ?? fallbackName;
5164
+ const rawName = options.name ?? probe2.resource?.serviceName ?? fallbackName;
2383
5165
  const skillName = sanitizeUpstreamText(rawName, LIMITS.MAX_AGENT_NAME_LENGTH);
2384
5166
  if (!/[a-zA-Z0-9]/.test(skillName)) {
2385
5167
  fail(
@@ -2388,7 +5170,7 @@ async function cmdX402Add(url, agentName, options) {
2388
5170
  }
2389
5171
  const candidateDTag = toDTag(skillName);
2390
5172
  const description = sanitizeUpstreamText(
2391
- probe.resource?.description ?? `x402 bridge to ${parsedUrl.hostname}`,
5173
+ probe2.resource?.description ?? `x402 bridge to ${parsedUrl.hostname}`,
2392
5174
  LIMITS.MAX_DESCRIPTION_LENGTH
2393
5175
  );
2394
5176
  const capabilities = [candidateDTag];
@@ -2435,8 +5217,8 @@ async function cmdX402Add(url, agentName, options) {
2435
5217
  fail("--query-param only applies to GET upstreams (POST maps the input to the request body)");
2436
5218
  }
2437
5219
  const noInput = method === "GET" && queryParam === void 0;
2438
- const feePercent = new Decimal(feeBps).div(100).toString();
2439
- const marginPercent = new Decimal(marginBps).div(100).toString();
5220
+ const feePercent = new Decimal2(feeBps).div(100).toString();
5221
+ const marginPercent = new Decimal2(marginBps).div(100).toString();
2440
5222
  console.log("");
2441
5223
  console.log(` ${chalk.bold(skillName)}`);
2442
5224
  console.log(` ${description}`);
@@ -3174,7 +5956,7 @@ async function cmdIdentityStatus(agentName, deps = {}) {
3174
5956
  }
3175
5957
 
3176
5958
  // src/index.ts
3177
- init_init();
5959
+ init_init2();
3178
5960
 
3179
5961
  // src/commands/profile.ts
3180
5962
  init_llm();
@@ -3364,7 +6146,7 @@ async function cmdProfile(name) {
3364
6146
  ]);
3365
6147
  const probeKey = apiKey || pickPlainKey(loaded.secrets, llmProvider);
3366
6148
  console.log(" Fetching available models...");
3367
- const { fetchModels: fetchModels4 } = await Promise.resolve().then(() => (init_init(), init_exports));
6149
+ const { fetchModels: fetchModels4 } = await Promise.resolve().then(() => (init_init2(), init_exports2));
3368
6150
  const models = await fetchModels4(llmProvider, probeKey);
3369
6151
  const { model } = await inquirer.prompt([
3370
6152
  {
@@ -3457,7 +6239,7 @@ function parseRelayUrl(url) {
3457
6239
  }
3458
6240
  }
3459
6241
  async function tcpProbe(host, port, timeoutMs) {
3460
- return new Promise((resolve4) => {
6242
+ return new Promise((resolve5) => {
3461
6243
  const started = Date.now();
3462
6244
  const socket = new Socket();
3463
6245
  let settled = false;
@@ -3467,7 +6249,7 @@ async function tcpProbe(host, port, timeoutMs) {
3467
6249
  }
3468
6250
  settled = true;
3469
6251
  socket.destroy();
3470
- resolve4(result);
6252
+ resolve5(result);
3471
6253
  };
3472
6254
  const timer = setTimeout(() => finish({ error: "timeout" }), timeoutMs);
3473
6255
  socket.once("connect", () => {
@@ -3504,19 +6286,19 @@ async function probeRelays(relays, logger, timeoutMs = TCP_PROBE_TIMEOUT_MS) {
3504
6286
  results.push({ url, host, port, ips: [], error: `dns: ${message}` });
3505
6287
  continue;
3506
6288
  }
3507
- const probe = await tcpProbe(host, port, timeoutMs);
3508
- if ("openMs" in probe) {
6289
+ const probe2 = await tcpProbe(host, port, timeoutMs);
6290
+ if ("openMs" in probe2) {
3509
6291
  logger.debug(
3510
- { event: "net_diag_tcp_open", url, host, port, ips, tcpOpenMs: probe.openMs },
6292
+ { event: "net_diag_tcp_open", url, host, port, ips, tcpOpenMs: probe2.openMs },
3511
6293
  "TCP open"
3512
6294
  );
3513
- results.push({ url, host, port, ips, tcpOpenMs: probe.openMs });
6295
+ results.push({ url, host, port, ips, tcpOpenMs: probe2.openMs });
3514
6296
  } else {
3515
6297
  logger.debug(
3516
- { event: "net_diag_tcp_failed", url, host, port, ips, error: probe.error },
6298
+ { event: "net_diag_tcp_failed", url, host, port, ips, error: probe2.error },
3517
6299
  "TCP probe failed"
3518
6300
  );
3519
- results.push({ url, host, port, ips, error: `tcp: ${probe.error}` });
6301
+ results.push({ url, host, port, ips, error: `tcp: ${probe2.error}` });
3520
6302
  }
3521
6303
  }
3522
6304
  return results;
@@ -4238,8 +7020,8 @@ function recoveryDeferDelayMs(attempts, recoveryIntervalSecs, jitter) {
4238
7020
  return ticks * intervalMs + jitterMs;
4239
7021
  }
4240
7022
  function waitMs(ms) {
4241
- return new Promise((resolve4) => {
4242
- setTimeout(resolve4, ms);
7023
+ return new Promise((resolve5) => {
7024
+ setTimeout(resolve5, ms);
4243
7025
  });
4244
7026
  }
4245
7027
  function needsPaymentScan(entry, delegated) {
@@ -4481,14 +7263,14 @@ var PaymentRecovery = class {
4481
7263
  return Promise.resolve(false);
4482
7264
  }
4483
7265
  if (this.endpointProbe === void 0) {
4484
- const probe = this.probeEndpointSoundness(rpc, log);
4485
- this.endpointProbe = probe;
7266
+ const probe2 = this.probeEndpointSoundness(rpc, log);
7267
+ this.endpointProbe = probe2;
4486
7268
  const release = () => {
4487
- if (this.endpointProbe === probe) {
7269
+ if (this.endpointProbe === probe2) {
4488
7270
  this.endpointProbe = void 0;
4489
7271
  }
4490
7272
  };
4491
- void probe.then(release, release);
7273
+ void probe2.then(release, release);
4492
7274
  }
4493
7275
  return this.endpointProbe;
4494
7276
  }
@@ -4925,8 +7707,8 @@ var SESSION_SUMMARY_PREFIX = "[Conversation summary]";
4925
7707
  var SESSION_CONTEXT_UNAVAILABLE = "[earlier context unavailable]";
4926
7708
  var TRUNCATION_MARKER = "\n[truncated]";
4927
7709
  var CUSTOMER_PUBKEY_REGEX = /^[0-9a-f]{64}$/;
4928
- var DIR_MODE = 448;
4929
- var FILE_MODE = 384;
7710
+ var DIR_MODE2 = 448;
7711
+ var FILE_MODE3 = 384;
4930
7712
  var SessionStore = class {
4931
7713
  root;
4932
7714
  log;
@@ -5015,8 +7797,8 @@ var SessionStore = class {
5015
7797
  }
5016
7798
  installLock(key) {
5017
7799
  let release;
5018
- const promise = new Promise((resolve4) => {
5019
- release = resolve4;
7800
+ const promise = new Promise((resolve5) => {
7801
+ release = resolve5;
5020
7802
  });
5021
7803
  const entry = { promise, release };
5022
7804
  this.locks.set(key, entry);
@@ -5095,8 +7877,8 @@ var SessionStore = class {
5095
7877
  };
5096
7878
  let exists = existsSync(path);
5097
7879
  if (exists) {
5098
- const stat2 = statSync(path);
5099
- if (Date.now() - stat2.mtimeMs > this.ttlMs) {
7880
+ const stat4 = statSync(path);
7881
+ if (Date.now() - stat4.mtimeMs > this.ttlMs) {
5100
7882
  this.deleteSessionFile(customerId, sessionId);
5101
7883
  exists = false;
5102
7884
  this.log(`[sessions] ${sessionId.slice(0, 8)} expired; starting fresh`);
@@ -5195,13 +7977,13 @@ var SessionStore = class {
5195
7977
  }
5196
7978
  try {
5197
7979
  try {
5198
- appendFileSync(path, payload, { mode: FILE_MODE });
7980
+ appendFileSync(path, payload, { mode: FILE_MODE3 });
5199
7981
  } catch (error) {
5200
7982
  if (error.code !== "ENOENT") {
5201
7983
  throw error;
5202
7984
  }
5203
- mkdirSync(join(this.root, customerId), { recursive: true, mode: DIR_MODE });
5204
- appendFileSync(path, payload, { mode: FILE_MODE });
7985
+ mkdirSync(join(this.root, customerId), { recursive: true, mode: DIR_MODE2 });
7986
+ appendFileSync(path, payload, { mode: FILE_MODE3 });
5205
7987
  }
5206
7988
  } catch (error) {
5207
7989
  const reason = error instanceof Error ? error.message : String(error);
@@ -5314,7 +8096,7 @@ var SessionStore = class {
5314
8096
  const payload = lines.map((line) => JSON.stringify(line)).join("\n") + (lines.length > 0 ? "\n" : "");
5315
8097
  const tempPath = `${path}.tmp.${randomBytes(6).toString("hex")}`;
5316
8098
  try {
5317
- writeFileSync(tempPath, payload, { mode: FILE_MODE });
8099
+ writeFileSync(tempPath, payload, { mode: FILE_MODE3 });
5318
8100
  renameSync(tempPath, path);
5319
8101
  } catch (error) {
5320
8102
  try {
@@ -5392,9 +8174,9 @@ var SessionStore = class {
5392
8174
  const path = this.sessionPath(customerId, sessionId);
5393
8175
  const oldSize = existsSync(path) ? statSync(path).size : 0;
5394
8176
  const tempPath = `${path}.tmp.${randomBytes(6).toString("hex")}`;
5395
- mkdirSync(join(this.root, customerId), { recursive: true, mode: DIR_MODE });
8177
+ mkdirSync(join(this.root, customerId), { recursive: true, mode: DIR_MODE2 });
5396
8178
  try {
5397
- writeFileSync(tempPath, payload, { mode: FILE_MODE });
8179
+ writeFileSync(tempPath, payload, { mode: FILE_MODE3 });
5398
8180
  renameSync(tempPath, path);
5399
8181
  } catch (error) {
5400
8182
  try {
@@ -5515,8 +8297,8 @@ var SessionStore = class {
5515
8297
  continue;
5516
8298
  }
5517
8299
  try {
5518
- const stat2 = statSync(join(this.root, customerId, name));
5519
- out.push({ customerId, sessionId, size: stat2.size, mtimeMs: stat2.mtimeMs });
8300
+ const stat4 = statSync(join(this.root, customerId, name));
8301
+ out.push({ customerId, sessionId, size: stat4.size, mtimeMs: stat4.mtimeMs });
5520
8302
  } catch {
5521
8303
  }
5522
8304
  }
@@ -6247,12 +9029,12 @@ var AgentRuntime = class {
6247
9029
  if (!this.scratchFailed) {
6248
9030
  return true;
6249
9031
  }
6250
- const probe = await mkdtemp(join(tmpdir(), "elisym-probe-")).catch(() => null);
6251
- if (probe === null) {
9032
+ const probe2 = await mkdtemp(join(tmpdir(), "elisym-probe-")).catch(() => null);
9033
+ if (probe2 === null) {
6252
9034
  return false;
6253
9035
  }
6254
- const wrote = await writeFile(join(probe, "probe"), "x").then(() => true).catch(() => false);
6255
- await rm(probe, { recursive: true, force: true }).catch(() => {
9036
+ const wrote = await writeFile(join(probe2, "probe"), "x").then(() => true).catch(() => false);
9037
+ await rm(probe2, { recursive: true, force: true }).catch(() => {
6256
9038
  });
6257
9039
  if (!wrote) {
6258
9040
  return false;
@@ -6505,8 +9287,8 @@ var AgentRuntime = class {
6505
9287
  });
6506
9288
  });
6507
9289
  log("Agent runtime started. Listening for jobs...");
6508
- await new Promise((resolve4) => {
6509
- this.abortController.signal.addEventListener("abort", () => resolve4(), { once: true });
9290
+ await new Promise((resolve5) => {
9291
+ this.abortController.signal.addEventListener("abort", () => resolve5(), { once: true });
6510
9292
  let shuttingDown = false;
6511
9293
  const onSignal = () => {
6512
9294
  if (shuttingDown) {
@@ -7656,7 +10438,7 @@ var AgentRuntime = class {
7656
10438
  let paymentRefusal;
7657
10439
  let result;
7658
10440
  try {
7659
- result = await new Promise((resolve4, reject) => {
10441
+ result = await new Promise((resolve5, reject) => {
7660
10442
  let settled = false;
7661
10443
  let pending = 2;
7662
10444
  let lastResult = { verified: false };
@@ -7666,7 +10448,7 @@ var AgentRuntime = class {
7666
10448
  }
7667
10449
  settled = true;
7668
10450
  clearTimeout(deadline);
7669
- resolve4(verified);
10451
+ resolve5(verified);
7670
10452
  };
7671
10453
  const lose = (verified, reason) => {
7672
10454
  if (settled) {
@@ -7678,7 +10460,7 @@ var AgentRuntime = class {
7678
10460
  if (pending === 0) {
7679
10461
  settled = true;
7680
10462
  clearTimeout(deadline);
7681
- resolve4(lastResult);
10463
+ resolve5(lastResult);
7682
10464
  }
7683
10465
  };
7684
10466
  const accept = (verified, pathLabel, askedSignature) => {
@@ -7750,7 +10532,7 @@ var AgentRuntime = class {
7750
10532
  }
7751
10533
  settled = true;
7752
10534
  log(`[${job.jobId.slice(0, 8)}] verify deadline (${deadlineMs}ms) hit`);
7753
- resolve4(lastResult);
10535
+ resolve5(lastResult);
7754
10536
  }, deadlineMs);
7755
10537
  if (signal?.aborted) {
7756
10538
  settled = true;
@@ -8848,7 +11630,7 @@ var NostrTransport = class {
8848
11630
  * expiry window - without it this path waits forever on the relay.
8849
11631
  */
8850
11632
  waitForPaymentSignature(jobId, customerPubkey, signal, timeoutMs) {
8851
- return new Promise((resolve4) => {
11633
+ return new Promise((resolve5) => {
8852
11634
  let settled = false;
8853
11635
  const filter = {
8854
11636
  kinds: [KIND_JOB_FEEDBACK],
@@ -8867,7 +11649,7 @@ var NostrTransport = class {
8867
11649
  }
8868
11650
  signal.removeEventListener("abort", onAbort);
8869
11651
  sub.close();
8870
- resolve4(sig);
11652
+ resolve5(sig);
8871
11653
  };
8872
11654
  const sub = this.client.pool.subscribe(filter, (event) => {
8873
11655
  if (settled) {
@@ -9555,18 +12337,18 @@ function maskCustomerInput(text, forms) {
9555
12337
  return masked;
9556
12338
  }
9557
12339
  function abortableDelay(ms, signal) {
9558
- return new Promise((resolve4) => {
12340
+ return new Promise((resolve5) => {
9559
12341
  if (signal?.aborted) {
9560
- resolve4(false);
12342
+ resolve5(false);
9561
12343
  return;
9562
12344
  }
9563
12345
  const onAbort = () => {
9564
12346
  clearTimeout(timer);
9565
- resolve4(false);
12347
+ resolve5(false);
9566
12348
  };
9567
12349
  const timer = setTimeout(() => {
9568
12350
  signal?.removeEventListener("abort", onAbort);
9569
- resolve4(true);
12351
+ resolve5(true);
9570
12352
  }, ms);
9571
12353
  signal?.addEventListener("abort", onAbort, { once: true });
9572
12354
  });
@@ -9653,9 +12435,9 @@ var X402Driver = class {
9653
12435
  maxUpstreamSubunits: job.params.maxUpstreamSubunits,
9654
12436
  network: this.options.network
9655
12437
  };
9656
- let probe;
12438
+ let probe2;
9657
12439
  try {
9658
- probe = await probePaymentRequiredCached(
12440
+ probe2 = await probePaymentRequiredCached(
9659
12441
  job.params.url,
9660
12442
  job.params.method,
9661
12443
  X402_PROBE_TTL_MS
@@ -9667,7 +12449,7 @@ var X402Driver = class {
9667
12449
  const message = error instanceof Error ? error.message : String(error);
9668
12450
  throw new X402PreflightError(`upstream unreachable: ${quoteUpstream(message)}`);
9669
12451
  }
9670
- const quote = maxAcceptableQuote(probe.accepts, rule);
12452
+ const quote = maxAcceptableQuote(probe2.accepts, rule);
9671
12453
  if (quote === null) {
9672
12454
  throw new X402PreflightError(
9673
12455
  "no acceptable upstream payment requirement: network/asset/scheme mismatch or the live quote exceeds x402_max_upstream (if the upstream repriced, re-run `npx @elisym/cli x402 add` to regenerate the skill)"
@@ -10883,7 +13665,7 @@ async function resolveStartAgentName(nameArg, cwd) {
10883
13665
  { type: "list", name: "selected", message: "Select agent to start", choices }
10884
13666
  ]);
10885
13667
  if (selected === "__new__") {
10886
- const { cmdInit: cmdInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
13668
+ const { cmdInit: cmdInit2 } = await Promise.resolve().then(() => (init_init2(), init_exports2));
10887
13669
  await cmdInit2();
10888
13670
  return void 0;
10889
13671
  }
@@ -11067,6 +13849,15 @@ program.command("askr-key <name>").description(
11067
13849
  await cmdAskrKey(name, options);
11068
13850
  })
11069
13851
  );
13852
+ var isAskrLine = process.argv[2] === "askr";
13853
+ registerAskr(
13854
+ program,
13855
+ async (invocation, context) => {
13856
+ await runAskrCommand(invocation, context);
13857
+ },
13858
+ process.argv.slice(3),
13859
+ isAskrLine
13860
+ );
11070
13861
  var identity = program.command("identity").description("Link, verify, and unlink external identities (GitHub, X, website)");
11071
13862
  identity.command("link <platform> [agent]").description(
11072
13863
  "Link a github|x|website identity: prints the NIP-39 proof template, verifies the proof live, writes elisym.yaml, and publishes the claim (kind 10011 / kind-0 nip05)"
@@ -11105,6 +13896,17 @@ x402.command("add <url> [agent]").description("Generate a bridge skill from a li
11105
13896
  await cmdX402Add(url, agent, options);
11106
13897
  })
11107
13898
  );
11108
- program.parse();
13899
+ async function main() {
13900
+ if (!isAskrLine) {
13901
+ program.parse();
13902
+ return;
13903
+ }
13904
+ try {
13905
+ await program.parseAsync();
13906
+ } catch (error) {
13907
+ emitParseError(error);
13908
+ }
13909
+ }
13910
+ void main();
11109
13911
  //# sourceMappingURL=index.js.map
11110
13912
  //# sourceMappingURL=index.js.map