@elisym/cli 0.36.0 → 0.37.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,14 +1,14 @@
1
1
  #!/usr/bin/env -S node --no-deprecation
2
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';
3
+ import { writeFile, readFile, realpath, stat, open, unlink, readdir, mkdtemp, rm, mkdir, chmod, rename, link } from 'node:fs/promises';
4
4
  import { dirname, join, resolve, sep, basename, extname, relative } from 'node:path';
5
5
  import { nip19, generateSecretKey, getPublicKey, verifyEvent } from 'nostr-tools';
6
6
  import { bytesToHex, hexToBytes } from 'nostr-tools/utils';
7
7
  import * as nip44 from 'nostr-tools/nip44';
8
8
  import { finalizeEvent, generateSecretKey as generateSecretKey$1, getPublicKey as getPublicKey$1, verifyEvent as verifyEvent$1 } from 'nostr-tools/pure';
9
9
  import Decimal2 from 'decimal.js-light';
10
+ import { readFileSync, constants, existsSync, readdirSync, statSync, realpathSync, renameSync, chmodSync, mkdirSync, writeFileSync, unlinkSync, appendFileSync, rmdirSync } from 'node:fs';
10
11
  import { ReadableStream } from 'node:stream/web';
11
- import { readFileSync, existsSync, readdirSync, statSync, realpathSync, renameSync, chmodSync, mkdirSync, writeFileSync, unlinkSync, appendFileSync, rmdirSync } from 'node:fs';
12
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';
13
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';
14
14
  import { isAddress, createSolanaRpc, address, signature } from '@solana/kit';
@@ -81,7 +81,7 @@ var init_errors = __esm({
81
81
  });
82
82
 
83
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;
84
+ var ASKR_COMMAND, DEADLINE_MS, ADMIN_URL, CONTACT_URL, PRICING_URL, FIND_STORE_ID_URL, UPGRADE, WIDGET_SCRIPT_URL, WIDGET_ELEMENT, STORE_FILES_BASE, ASKR_SITE_URL, 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
85
  var init_constants = __esm({
86
86
  "src/commands/askr/constants.ts"() {
87
87
  ASKR_COMMAND = "npx -y @elisym/cli@latest askr";
@@ -98,6 +98,8 @@ var init_constants = __esm({
98
98
  };
99
99
  WIDGET_SCRIPT_URL = "https://app.askr.elisym.network/widget.js";
100
100
  WIDGET_ELEMENT = "askr-chat";
101
+ STORE_FILES_BASE = "https://app.askr.elisym.network/s";
102
+ ASKR_SITE_URL = "https://askr.elisym.network";
101
103
  API_OVERRIDE_ENV = "ELISYM_ASKR_API";
102
104
  RELAY_OVERRIDE_ENV = "ELISYM_ASKR_RELAY";
103
105
  UNSAFE_OVERRIDE_ENV = "ELISYM_ASKR_UNSAFE_TEST";
@@ -2279,6 +2281,113 @@ var init_status = __esm({
2279
2281
  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
2282
  }
2281
2283
  });
2284
+ function storeLlmsTxtUrl(npub) {
2285
+ return `${STORE_FILES_BASE}/${npub}/llms.txt`;
2286
+ }
2287
+ function storeCatalogJsonUrl(npub) {
2288
+ return `${STORE_FILES_BASE}/${npub}/catalog.json`;
2289
+ }
2290
+ function headingName(name) {
2291
+ const line = name.replace(/\s+/gu, " ").replace(/^[#\s]+/u, "").trim();
2292
+ return line === "" ? "This store" : line;
2293
+ }
2294
+ function siteLlmsTxtSection(npub) {
2295
+ return [
2296
+ LLMS_SECTION_HEADING,
2297
+ "",
2298
+ `- [Products and policies for AI agents](${storeLlmsTxtUrl(npub)}): every product with its price and page, and the store's policies, read-only`,
2299
+ `- [Catalog as JSON](${storeCatalogJsonUrl(npub)}): the same, machine-readable`,
2300
+ `- [Askr](${ASKR_SITE_URL}): the shopping assistant this store uses. Purchases happen on this site's product pages.`,
2301
+ ""
2302
+ ].join("\n");
2303
+ }
2304
+ function siteLlmsTxt(npub, storeName) {
2305
+ const name = headingName(storeName);
2306
+ return [
2307
+ `# ${name}`,
2308
+ "",
2309
+ `> ${name} has a shopping assistant, Askr: the chat on every page of this site answers questions about products, prices and policies.`,
2310
+ "",
2311
+ siteLlmsTxtSection(npub)
2312
+ ].join("\n");
2313
+ }
2314
+ function notWritable(hint) {
2315
+ return new AskrExit(EXIT.BAD_INPUT, "file_not_writable", { hint: `--llms-txt: ${hint}` });
2316
+ }
2317
+ function codeOf(error) {
2318
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : void 0;
2319
+ }
2320
+ async function create(path, text) {
2321
+ try {
2322
+ await writeFile(path, text, { encoding: "utf-8", flag: "wx" });
2323
+ return "created";
2324
+ } catch (error) {
2325
+ throw notWritable(
2326
+ codeOf(error) === "EEXIST" ? "something else is at that path" : "cannot write there"
2327
+ );
2328
+ }
2329
+ }
2330
+ async function appendTo(handle, npub) {
2331
+ const info = await handle.stat();
2332
+ if (!info.isFile()) {
2333
+ throw notWritable("not a regular file");
2334
+ }
2335
+ if (info.size > MAX_EXISTING_LLMS_BYTES) {
2336
+ throw notWritable("the file there is over 1 MiB: not an llms.txt");
2337
+ }
2338
+ const existing = await handle.readFile({ encoding: "utf-8" });
2339
+ if (existing.includes("\0")) {
2340
+ throw notWritable("the file there is not text");
2341
+ }
2342
+ if (existing.includes(storeLlmsTxtUrl(npub))) {
2343
+ return "unchanged";
2344
+ }
2345
+ let separator = "\n\n";
2346
+ if (existing === "" || existing.endsWith("\n\n") || existing.endsWith("\r\n\r\n")) {
2347
+ separator = "";
2348
+ } else if (existing.endsWith("\r\n")) {
2349
+ separator = "\r\n";
2350
+ } else if (existing.endsWith("\n")) {
2351
+ separator = "\n";
2352
+ }
2353
+ await handle.appendFile(`${separator}${siteLlmsTxtSection(npub)}`, { encoding: "utf-8" });
2354
+ return "appended";
2355
+ }
2356
+ async function writeSiteLlmsTxt(path, npub, storeName) {
2357
+ if (basename(path) !== LLMS_FILE_NAME) {
2358
+ throw notWritable("name a file called llms.txt (at your site root)");
2359
+ }
2360
+ let handle;
2361
+ try {
2362
+ handle = await open(path, constants.O_RDWR | constants.O_APPEND | NO_FOLLOW);
2363
+ } catch (error) {
2364
+ const code = codeOf(error);
2365
+ if (code === "ENOENT") {
2366
+ return create(path, siteLlmsTxt(npub, storeName));
2367
+ }
2368
+ throw notWritable(
2369
+ code === "ELOOP" ? "a link, not a regular file" : "cannot open the file there"
2370
+ );
2371
+ }
2372
+ try {
2373
+ return await appendTo(handle, npub);
2374
+ } catch (error) {
2375
+ throw error instanceof AskrExit ? error : notWritable("cannot write there");
2376
+ } finally {
2377
+ await handle.close();
2378
+ }
2379
+ }
2380
+ var LLMS_SECTION_HEADING, LLMS_FILE_NAME, MAX_EXISTING_LLMS_BYTES, NO_FOLLOW;
2381
+ var init_llms_txt = __esm({
2382
+ "src/commands/askr/llms-txt.ts"() {
2383
+ init_constants();
2384
+ init_errors();
2385
+ LLMS_SECTION_HEADING = "## Shopping assistant";
2386
+ LLMS_FILE_NAME = "llms.txt";
2387
+ MAX_EXISTING_LLMS_BYTES = 1024 * 1024;
2388
+ NO_FOLLOW = constants.O_NOFOLLOW ?? 0;
2389
+ }
2390
+ });
2282
2391
 
2283
2392
  // src/commands/askr/embed.ts
2284
2393
  var embed_exports = {};
@@ -2306,13 +2415,14 @@ function cspSources(askr) {
2306
2415
  { directive: "img-src", sources: ["https:"] }
2307
2416
  ];
2308
2417
  }
2309
- async function runEmbed(session) {
2418
+ async function runEmbed(session, options = {}) {
2310
2419
  const key = await useOwnerKey(session);
2311
2420
  await readView(session);
2312
2421
  const { config } = await readSigned(session, key.owner, key.secretKey);
2313
2422
  if (config === void 0) {
2314
2423
  throw new AskrExit(EXIT.BAD_INPUT, "no_settings", { hint: "run askr init first" });
2315
2424
  }
2425
+ const written = options.llmsTxt === void 0 ? void 0 : await writeSiteLlmsTxt(options.llmsTxt, key.storeId, config.name);
2316
2426
  return {
2317
2427
  exitCode: EXIT.OK,
2318
2428
  output: {
@@ -2323,7 +2433,10 @@ async function runEmbed(session) {
2323
2433
  verificationMeta: verificationMeta(key.storeId),
2324
2434
  csp: cspSources(session.askr),
2325
2435
  platformHints: PLATFORM_HINTS,
2326
- ...config.source.kind === "admin" ? { addToCart: ADD_TO_CART } : {}
2436
+ ...config.source.kind === "admin" ? { addToCart: ADD_TO_CART } : {},
2437
+ llmsTxt: siteLlmsTxt(key.storeId, config.name),
2438
+ llmsTxtUrl: storeLlmsTxtUrl(key.storeId),
2439
+ ...written === void 0 ? {} : { llmsTxtFile: { path: options.llmsTxt, result: written } }
2327
2440
  }
2328
2441
  };
2329
2442
  }
@@ -2332,6 +2445,7 @@ var init_embed = __esm({
2332
2445
  "src/commands/askr/embed.ts"() {
2333
2446
  init_constants();
2334
2447
  init_errors();
2448
+ init_llms_txt();
2335
2449
  init_read();
2336
2450
  init_store();
2337
2451
  ADD_TO_CART = `<script>
@@ -4021,7 +4135,20 @@ function registerAskr(program2, run, args, jsonErrors) {
4021
4135
  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
4136
  (options) => run({ command: "status", options }, context(options))
4023
4137
  );
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)));
4138
+ askr.command("embed").description(
4139
+ "Print the widget snippet, the verification meta tag, the CSP sources and the site's llms.txt"
4140
+ ).option(
4141
+ "--llms-txt <path>",
4142
+ "write the site's llms.txt there (appends the Askr part to an existing one)"
4143
+ ).option(PROFILE_FLAG, PROFILE_HELP).action(
4144
+ (options) => run(
4145
+ {
4146
+ command: "embed",
4147
+ options: options.llmsTxt === void 0 ? {} : { llmsTxt: options.llmsTxt }
4148
+ },
4149
+ context(options)
4150
+ )
4151
+ );
4025
4152
  askr.command("export-key").description(
4026
4153
  "Write the owner key as a key file for your password manager (run it yourself, never by an agent)"
4027
4154
  ).requiredOption("--out <path>", "a new file to write (never overwritten)").option(PROFILE_FLAG, PROFILE_HELP).action(
@@ -4332,7 +4459,7 @@ async function dispatch(session, invocation) {
4332
4459
  }
4333
4460
  case "embed": {
4334
4461
  const { runEmbed: runEmbed2 } = await Promise.resolve().then(() => (init_embed(), embed_exports));
4335
- return runEmbed2(session);
4462
+ return runEmbed2(session, invocation.options);
4336
4463
  }
4337
4464
  case "export-key": {
4338
4465
  const { runExportKey: runExportKey2 } = await Promise.resolve().then(() => (init_export_key(), export_key_exports));