@keyban/cli 0.2.2 → 0.2.3

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.mjs CHANGED
@@ -3207,9 +3207,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
3207
3207
  helpWidth: context.helpWidth,
3208
3208
  outputHasColors: context.hasColors
3209
3209
  });
3210
- const text5 = helper.formatHelp(this, helper);
3211
- if (context.hasColors) return text5;
3212
- return this._outputConfiguration.stripColor(text5);
3210
+ const text6 = helper.formatHelp(this, helper);
3211
+ if (context.hasColors) return text6;
3212
+ return this._outputConfiguration.stripColor(text6);
3213
3213
  }
3214
3214
  /**
3215
3215
  * @typedef HelpContext
@@ -3369,7 +3369,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
3369
3369
  * @param {(string | Function)} text - string to add, or a function returning a string
3370
3370
  * @return {Command} `this` command for chaining
3371
3371
  */
3372
- addHelpText(position, text5) {
3372
+ addHelpText(position, text6) {
3373
3373
  const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3374
3374
  if (!allowedValues.includes(position)) {
3375
3375
  throw new Error(`Unexpected value for position to addHelpText.
@@ -3378,10 +3378,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
3378
3378
  const helpEvent = `${position}Help`;
3379
3379
  this.on(helpEvent, (context) => {
3380
3380
  let helpStr;
3381
- if (typeof text5 === "function") {
3382
- helpStr = text5({ error: context.error, command: context.command });
3381
+ if (typeof text6 === "function") {
3382
+ helpStr = text6({ error: context.error, command: context.command });
3383
3383
  } else {
3384
- helpStr = text5;
3384
+ helpStr = text6;
3385
3385
  }
3386
3386
  if (helpStr) {
3387
3387
  context.write(`${helpStr}
@@ -15113,9 +15113,9 @@ var require_instructions_service = __commonJS({
15113
15113
  const cached2 = this.cache.get(name);
15114
15114
  if (cached2 !== void 0)
15115
15115
  return cached2;
15116
- const text5 = await this.readSkill(name);
15117
- this.cache.set(name, text5);
15118
- return text5;
15116
+ const text6 = await this.readSkill(name);
15117
+ this.cache.set(name, text6);
15118
+ return text6;
15119
15119
  }
15120
15120
  };
15121
15121
  exports.InstructionsService = InstructionsService;
@@ -26776,7 +26776,7 @@ var require_core = __commonJS({
26776
26776
  errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
26777
26777
  if (!errors || errors.length === 0)
26778
26778
  return "No errors";
26779
- return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text5, msg) => text5 + separator + msg);
26779
+ return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text6, msg) => text6 + separator + msg);
26780
26780
  }
26781
26781
  $dataMetaSchema(metaSchema, keywordsJsonPointers) {
26782
26782
  const rules = this.RULES.all;
@@ -103235,8 +103235,8 @@ ${problems.map((e) => ` - ${e}`).join("\n")}`);
103235
103235
  extensions: import_zod28.z.array(import_zod28.z.string()).default([]),
103236
103236
  signers: import_zod28.z.record(import_zod28.z.string(), import_zod28.z.array(import_zod28.z.string())).default({})
103237
103237
  });
103238
- function responseExcerpt(text5, limit = 200) {
103239
- const compact = text5.trim().replace(/\s+/g, " ");
103238
+ function responseExcerpt(text6, limit = 200) {
103239
+ const compact = text6.trim().replace(/\s+/g, " ");
103240
103240
  if (!compact) {
103241
103241
  return "<empty response>";
103242
103242
  }
@@ -103298,19 +103298,19 @@ ${problems.map((e) => ` - ${e}`).join("\n")}`);
103298
103298
  return result;
103299
103299
  }
103300
103300
  async function parseSuccessResponse(response, schema, operation) {
103301
- const text5 = await response.text();
103301
+ const text6 = await response.text();
103302
103302
  let data;
103303
103303
  try {
103304
- data = JSON.parse(text5);
103304
+ data = JSON.parse(text6);
103305
103305
  } catch {
103306
103306
  throw new FacilitatorResponseError2(
103307
- `Facilitator ${operation} returned invalid JSON: ${responseExcerpt(text5)}`
103307
+ `Facilitator ${operation} returned invalid JSON: ${responseExcerpt(text6)}`
103308
103308
  );
103309
103309
  }
103310
103310
  const parsed = schema.safeParse(data);
103311
103311
  if (!parsed.success) {
103312
103312
  throw new FacilitatorResponseError2(
103313
- `Facilitator ${operation} returned invalid data: ${responseExcerpt(text5)}`
103313
+ `Facilitator ${operation} returned invalid data: ${responseExcerpt(text6)}`
103314
103314
  );
103315
103315
  }
103316
103316
  return parsed.data;
@@ -103360,13 +103360,13 @@ ${problems.map((e) => ` - ${e}`).join("\n")}`);
103360
103360
  signal
103361
103361
  });
103362
103362
  if (!response.ok) {
103363
- const text5 = await response.text();
103363
+ const text6 = await response.text();
103364
103364
  let data;
103365
103365
  try {
103366
- data = JSON.parse(text5);
103366
+ data = JSON.parse(text6);
103367
103367
  } catch {
103368
103368
  throw new Error(
103369
- `Facilitator verify failed (${response.status}): ${responseExcerpt(text5)}`
103369
+ `Facilitator verify failed (${response.status}): ${responseExcerpt(text6)}`
103370
103370
  );
103371
103371
  }
103372
103372
  if (typeof data === "object" && data !== null && "isValid" in data) {
@@ -103408,13 +103408,13 @@ ${problems.map((e) => ` - ${e}`).join("\n")}`);
103408
103408
  signal
103409
103409
  });
103410
103410
  if (!response.ok) {
103411
- const text5 = await response.text();
103411
+ const text6 = await response.text();
103412
103412
  let data;
103413
103413
  try {
103414
- data = JSON.parse(text5);
103414
+ data = JSON.parse(text6);
103415
103415
  } catch {
103416
103416
  throw new Error(
103417
- `Facilitator settle failed (${response.status}): ${responseExcerpt(text5)}`
103417
+ `Facilitator settle failed (${response.status}): ${responseExcerpt(text6)}`
103418
103418
  );
103419
103419
  }
103420
103420
  if (typeof data === "object" && data !== null && "success" in data) {
@@ -115803,8 +115803,8 @@ var require_lt = __commonJS({
115803
115803
  Object.defineProperty(exports, "__esModule", { value: true });
115804
115804
  exports.default = default_1;
115805
115805
  var util2 = __importStar(require_util3());
115806
- var capitalizeFirstCharacter = (text5) => {
115807
- return text5.charAt(0).toUpperCase() + text5.slice(1);
115806
+ var capitalizeFirstCharacter = (text6) => {
115807
+ return text6.charAt(0).toUpperCase() + text6.slice(1);
115808
115808
  };
115809
115809
  function getUnitTypeFromNumber(number4) {
115810
115810
  const abs = Math.abs(number4);
@@ -131256,6 +131256,77 @@ function resolveURL(value) {
131256
131256
  return ENV_URLS[value] ?? value;
131257
131257
  }
131258
131258
 
131259
+ // src/lib/admin-names.ts
131260
+ var PAGE_SIZE = 100;
131261
+ var KINDS = {
131262
+ signer: {
131263
+ list: "list_wallet_signers",
131264
+ nameField: "name",
131265
+ idFields: ["signerId"],
131266
+ page: () => ({}),
131267
+ scope: (args) => {
131268
+ const walletId = args.path?.walletId ?? args.path?.agentWalletId;
131269
+ return walletId === void 0 ? void 0 : { walletId };
131270
+ }
131271
+ },
131272
+ wallet: {
131273
+ list: "list_wallets",
131274
+ nameField: "label",
131275
+ idFields: ["walletId", "agentWalletId"],
131276
+ page: (index2) => ({ currentPage: index2 + 1, pageSize: PAGE_SIZE })
131277
+ },
131278
+ application: {
131279
+ list: "list_applications",
131280
+ nameField: "name",
131281
+ idFields: ["appId", "applicationId", "application"],
131282
+ page: (index2) => ({ currentPage: index2 + 1, pageSize: PAGE_SIZE })
131283
+ },
131284
+ mission: {
131285
+ list: "list_missions",
131286
+ nameField: "key",
131287
+ idFields: ["missionId"],
131288
+ page: (index2) => ({ limit: PAGE_SIZE, offset: index2 * PAGE_SIZE })
131289
+ }
131290
+ };
131291
+ function kindOf(toolName, field) {
131292
+ for (const [kind, { idFields }] of Object.entries(KINDS)) {
131293
+ if (idFields.includes(field)) return kind;
131294
+ if (field === "id" && toolName.endsWith(`_${kind}`)) return kind;
131295
+ }
131296
+ return void 0;
131297
+ }
131298
+ function nameFieldOf(kind) {
131299
+ return KINDS[kind].nameField;
131300
+ }
131301
+ function isScoped(kind) {
131302
+ return KINDS[kind].scope !== void 0;
131303
+ }
131304
+ function text(result) {
131305
+ return result.content.map((part) => part.type === "text" ? part.text : "").join("");
131306
+ }
131307
+ async function resolveName(kind, name, list, args = {}) {
131308
+ const { list: tool, nameField, page, scope } = KINDS[kind];
131309
+ const path = scope?.(args);
131310
+ if (scope && !path) throw new Error(`A ${kind} is found by name within its wallet: pass the wallet too.`);
131311
+ const ids = [];
131312
+ let seen = 0;
131313
+ for (let index2 = 0; ; index2++) {
131314
+ const result = await list(tool, { ...path && { path }, query: page(index2) });
131315
+ if (result.isError) throw new Error(text(result));
131316
+ const { data = [], total = 0 } = JSON.parse(text(result)) ?? {};
131317
+ seen += data.length;
131318
+ ids.push(
131319
+ ...data.filter((item) => item[nameField] === name && item.id !== void 0).map((item) => String(item.id))
131320
+ );
131321
+ if (data.length === 0 || seen >= total) break;
131322
+ }
131323
+ if (ids.length === 0) throw new Error(`No ${kind} with the ${nameField} "${name}".`);
131324
+ if (ids.length > 1) {
131325
+ throw new Error(`${ids.length} ${kind}s have the ${nameField} "${name}": ${ids.join(", ")}. Pass the id.`);
131326
+ }
131327
+ return ids[0];
131328
+ }
131329
+
131259
131330
  // src/lib/kebab.ts
131260
131331
  function kebab(name) {
131261
131332
  return name.replace(/_/g, "-").replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
@@ -131300,8 +131371,14 @@ function optionFor(flag, schema, required2) {
131300
131371
  if (schema.enum?.every((v) => typeof v === "string")) option.choices(schema.enum);
131301
131372
  return option;
131302
131373
  }
131303
- function addFieldOptions(command, tool) {
131374
+ function nameFlagOf(flag, nameField) {
131375
+ const name = kebab(nameField);
131376
+ if (flag === "id" || flag.endsWith("-id")) return `${flag.slice(0, -"id".length)}${name}`;
131377
+ return `${flag}-${name}`;
131378
+ }
131379
+ function addFieldOptions(command, tool, names) {
131304
131380
  const targets = /* @__PURE__ */ new Map();
131381
+ const nameTargets = /* @__PURE__ */ new Map();
131305
131382
  const groups = tool.inputSchema.properties ?? {};
131306
131383
  for (const group of GROUPS) {
131307
131384
  const groupSchema = groups[group];
@@ -131314,7 +131391,29 @@ function addFieldOptions(command, tool) {
131314
131391
  targets.set(camel(flag), { group, field });
131315
131392
  }
131316
131393
  }
131317
- return targets;
131394
+ for (const [key, { group, field }] of targets) {
131395
+ const kind = names?.kindOf(tool.name, field);
131396
+ if (!names || !kind) continue;
131397
+ const idFlag = kebab(key);
131398
+ const nameField = names.nameField(kind);
131399
+ const flag = [nameFlagOf(idFlag, nameField), `${kind}-${kebab(nameField)}`].find(
131400
+ (candidate) => !targets.has(camel(candidate)) && !nameTargets.has(candidate)
131401
+ );
131402
+ if (!flag) continue;
131403
+ nameTargets.set(flag, { group, field, kind, idFlag });
131404
+ command.addOption(new Option(`--${flag} <${kebab(nameField)}>`, `the ${kind} of that ${nameField}, instead of --${idFlag}`));
131405
+ }
131406
+ return { targets, nameTargets };
131407
+ }
131408
+ async function resolveNames(options, nameTargets, args, names, command) {
131409
+ if (!names) return;
131410
+ const ordered = [...nameTargets].sort(([, a], [, b]) => Number(names.isScoped(a.kind)) - Number(names.isScoped(b.kind)));
131411
+ for (const [flag, { group, field, kind, idFlag }] of ordered) {
131412
+ const name = options[camel(flag)];
131413
+ if (typeof name !== "string") continue;
131414
+ if (args[group]?.[field] !== void 0) throw new Error(`pass --${flag} or --${idFlag}, not both`);
131415
+ args[group] = { ...args[group], [field]: await names.resolve(kind, name, command, args) };
131416
+ }
131318
131417
  }
131319
131418
  function mergeArgs(options, targets) {
131320
131419
  const args = options.input ? JSON.parse(String(options.input)) : {};
@@ -131328,16 +131427,18 @@ function mergeArgs(options, targets) {
131328
131427
  function resultText(result) {
131329
131428
  return result.content.map((part) => part.type === "text" ? part.text : JSON.stringify(part)).join("\n");
131330
131429
  }
131331
- function jsonToolCommand(tool, call2) {
131430
+ function jsonToolCommand(tool, call2, names) {
131332
131431
  const command = new Command(kebab(tool.name)).summary(tool.title ?? tool.name).description(tool.description ?? "");
131333
- const targets = addFieldOptions(command, tool);
131432
+ const { targets, nameTargets } = addFieldOptions(command, tool, names);
131334
131433
  command.addOption(new Option("--input <json>", "the whole tool input as JSON, merged under the options"));
131335
131434
  return command.action(async (options, self2) => {
131336
131435
  try {
131337
- const result = await call2(mergeArgs(options, targets), self2);
131338
- const text5 = resultText(result);
131339
- if (result.isError) throw new Error(text5);
131340
- process.stdout.write(`${text5}
131436
+ const args = mergeArgs(options, targets);
131437
+ await resolveNames(options, nameTargets, args, names, self2);
131438
+ const result = await call2(args, self2);
131439
+ const text6 = resultText(result);
131440
+ if (result.isError) throw new Error(text6);
131441
+ process.stdout.write(`${text6}
131341
131442
  `);
131342
131443
  } catch (error2) {
131343
131444
  process.stderr.write(`Error: ${error2 instanceof Error ? error2.message : String(error2)}
@@ -131347,6 +131448,92 @@ function jsonToolCommand(tool, call2) {
131347
131448
  });
131348
131449
  }
131349
131450
 
131451
+ // src/lib/wallet-file.ts
131452
+ import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
131453
+ import { homedir as homedir2 } from "node:os";
131454
+ import { dirname, join as join2 } from "node:path";
131455
+ function walletFilePath(env = process.env) {
131456
+ if (env.KEYBAN_WALLET_PATH) return env.KEYBAN_WALLET_PATH;
131457
+ const configHome = env.XDG_CONFIG_HOME || join2(homedir2(), ".config");
131458
+ return join2(configHome, "keyban", "wallet.json");
131459
+ }
131460
+ function moveOldDefaultWalletFile(env) {
131461
+ if (env.KEYBAN_WALLET_PATH) return;
131462
+ const file = walletFilePath(env);
131463
+ const old = join2(dirname(file), "wallets", "default.json");
131464
+ if (existsSync(file) || !existsSync(old)) return;
131465
+ renameSync(old, file);
131466
+ process.stderr.write(`Moved the keyban wallet ${old} to ${file}
131467
+ `);
131468
+ }
131469
+ function loadWalletFile(env = process.env) {
131470
+ moveOldDefaultWalletFile(env);
131471
+ const file = walletFilePath(env);
131472
+ if (!existsSync(file)) {
131473
+ if (env.KEYBAN_WALLET_PATH) throw new Error(`No keyban wallet at ${file}.`);
131474
+ return;
131475
+ }
131476
+ let parsed;
131477
+ try {
131478
+ parsed = JSON.parse(readFileSync2(file, "utf8"));
131479
+ } catch (err) {
131480
+ throw new Error(`The keyban wallet ${file} is not valid JSON.`, { cause: err });
131481
+ }
131482
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
131483
+ throw new Error(`The keyban wallet ${file} must be a JSON object of variables.`);
131484
+ }
131485
+ for (const [name, value] of Object.entries(parsed)) {
131486
+ if (typeof value !== "string") {
131487
+ throw new Error(`The keyban wallet ${file}: ${name} must be a string.`);
131488
+ }
131489
+ if (!env[name]) env[name] = value;
131490
+ }
131491
+ }
131492
+ function importWalletFile(source, env = process.env, force = false) {
131493
+ return importSigners(JSON.parse(readFileSync2(source, "utf8")), source, env, force);
131494
+ }
131495
+ function refuseExistingWalletFile(env = process.env, force = false) {
131496
+ moveOldDefaultWalletFile(env);
131497
+ const file = walletFilePath(env);
131498
+ if (force || !existsSync(file)) return;
131499
+ throw new Error(
131500
+ `The keyban wallet ${file} already exists: overwriting it loses its client share. Set KEYBAN_WALLET_PATH to another file, or pass --force.`
131501
+ );
131502
+ }
131503
+ function importSigners(signers, source, env = process.env, force = false) {
131504
+ refuseExistingWalletFile(env, force);
131505
+ const parsed = signers;
131506
+ if (!parsed || typeof parsed !== "object") {
131507
+ throw new Error(`${source} holds no signer: expected a JSON object.`);
131508
+ }
131509
+ const signer = parsed.data ? parsed.data[0] : parsed;
131510
+ const block = signer?.mcpConfig?.mcpServers?.["agent-wallet"]?.env;
131511
+ if (!block || typeof block !== "object") {
131512
+ throw new Error(`${source} holds no signer with an MCP configuration (is the signer ready?).`);
131513
+ }
131514
+ const file = walletFilePath(env);
131515
+ mkdirSync2(dirname(file), { recursive: true });
131516
+ writeFileSync2(file, `${JSON.stringify(block, null, 2)}
131517
+ `, { mode: 384 });
131518
+ return file;
131519
+ }
131520
+ function readClientShare(env = process.env) {
131521
+ const file = walletFilePath(env);
131522
+ if (!existsSync(file)) return void 0;
131523
+ const blob = JSON.parse(readFileSync2(file, "utf8")).KEYBAN_DKG_BLOB;
131524
+ return blob ? Buffer.from(blob, "base64").toString("utf8") : void 0;
131525
+ }
131526
+ function keepClientShare(dkgBlob, env = process.env) {
131527
+ const file = walletFilePath(env);
131528
+ if (!existsSync(file)) throw new Error(`No keyban wallet at ${file}: run keyban wallet import first.`);
131529
+ const variables = JSON.parse(readFileSync2(file, "utf8"));
131530
+ if (variables.KEYBAN_DKG_BLOB) throw new Error(`The keyban wallet ${file} already holds a client share.`);
131531
+ variables.KEYBAN_DKG_BLOB = Buffer.from(dkgBlob, "utf8").toString("base64");
131532
+ writeFileSync2(file, `${JSON.stringify(variables, null, 2)}
131533
+ `, { mode: 384 });
131534
+ return file;
131535
+ }
131536
+
131350
131537
  // src/subcommands.ts
131351
131538
  init_zod();
131352
131539
 
@@ -131506,73 +131693,6 @@ function registerUiPages(server, tools, pages) {
131506
131693
  }
131507
131694
  }
131508
131695
 
131509
- // src/lib/wallet-file.ts
131510
- import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
131511
- import { homedir as homedir2 } from "node:os";
131512
- import { dirname, join as join2 } from "node:path";
131513
- function walletFilePath(env = process.env) {
131514
- if (env.KEYBAN_WALLET_PATH) return env.KEYBAN_WALLET_PATH;
131515
- const configHome = env.XDG_CONFIG_HOME || join2(homedir2(), ".config");
131516
- return join2(configHome, "keyban", "wallet.json");
131517
- }
131518
- function loadWalletFile(env = process.env) {
131519
- const file = walletFilePath(env);
131520
- if (!existsSync(file)) {
131521
- if (env.KEYBAN_WALLET_PATH) throw new Error(`No keyban wallet at ${file}.`);
131522
- return;
131523
- }
131524
- let parsed;
131525
- try {
131526
- parsed = JSON.parse(readFileSync2(file, "utf8"));
131527
- } catch (err) {
131528
- throw new Error(`The keyban wallet ${file} is not valid JSON.`, { cause: err });
131529
- }
131530
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
131531
- throw new Error(`The keyban wallet ${file} must be a JSON object of variables.`);
131532
- }
131533
- for (const [name, value] of Object.entries(parsed)) {
131534
- if (typeof value !== "string") {
131535
- throw new Error(`The keyban wallet ${file}: ${name} must be a string.`);
131536
- }
131537
- if (!env[name]) env[name] = value;
131538
- }
131539
- }
131540
- function importWalletFile(source, env = process.env) {
131541
- return importSigners(JSON.parse(readFileSync2(source, "utf8")), source, env);
131542
- }
131543
- function importSigners(signers, source, env = process.env) {
131544
- const parsed = signers;
131545
- if (!parsed || typeof parsed !== "object") {
131546
- throw new Error(`${source} holds no signer: expected a JSON object.`);
131547
- }
131548
- const signer = parsed.data ? parsed.data[0] : parsed;
131549
- const block = signer?.mcpConfig?.mcpServers?.["agent-wallet"]?.env;
131550
- if (!block || typeof block !== "object") {
131551
- throw new Error(`${source} holds no signer with an MCP configuration (is the signer ready?).`);
131552
- }
131553
- const file = walletFilePath(env);
131554
- mkdirSync2(dirname(file), { recursive: true });
131555
- writeFileSync2(file, `${JSON.stringify(block, null, 2)}
131556
- `, { mode: 384 });
131557
- return file;
131558
- }
131559
- function readClientShare(env = process.env) {
131560
- const file = walletFilePath(env);
131561
- if (!existsSync(file)) return void 0;
131562
- const blob = JSON.parse(readFileSync2(file, "utf8")).KEYBAN_DKG_BLOB;
131563
- return blob ? Buffer.from(blob, "base64").toString("utf8") : void 0;
131564
- }
131565
- function keepClientShare(dkgBlob, env = process.env) {
131566
- const file = walletFilePath(env);
131567
- if (!existsSync(file)) throw new Error(`No keyban wallet at ${file}: run keyban wallet import first.`);
131568
- const variables = JSON.parse(readFileSync2(file, "utf8"));
131569
- if (variables.KEYBAN_DKG_BLOB) throw new Error(`The keyban wallet ${file} already holds a client share.`);
131570
- variables.KEYBAN_DKG_BLOB = Buffer.from(dkgBlob, "utf8").toString("base64");
131571
- writeFileSync2(file, `${JSON.stringify(variables, null, 2)}
131572
- `, { mode: 384 });
131573
- return file;
131574
- }
131575
-
131576
131696
  // src/subcommands.ts
131577
131697
  function unwrap(schema) {
131578
131698
  let base2 = schema;
@@ -131621,19 +131741,19 @@ function commandFor(tool) {
131621
131741
  }
131622
131742
  return command.action(async (options) => {
131623
131743
  let out = process.stdout;
131624
- let text5;
131744
+ let text6;
131625
131745
  let code = 0;
131626
131746
  try {
131627
- text5 = toolText(await tool.handler(tool.inputSchema.parse(options)));
131747
+ text6 = toolText(await tool.handler(tool.inputSchema.parse(options)));
131628
131748
  } catch (error2) {
131629
131749
  const message = error2 instanceof Error ? error2.message : String(error2);
131630
131750
  const cause = error2 instanceof Error && error2.cause ? `
131631
131751
  Caused by: ${error2.cause}` : "";
131632
131752
  out = process.stderr;
131633
- text5 = `Error: ${message}${cause}`;
131753
+ text6 = `Error: ${message}${cause}`;
131634
131754
  code = 1;
131635
131755
  }
131636
- await new Promise((resolve) => out.write(text5.endsWith("\n") ? text5 : `${text5}
131756
+ await new Promise((resolve) => out.write(text6.endsWith("\n") ? text6 : `${text6}
131637
131757
  `, () => resolve()));
131638
131758
  process.exit(code);
131639
131759
  });
@@ -131643,7 +131763,8 @@ function missionCommands(missions) {
131643
131763
  }
131644
131764
  var SIGNER_READY_TIMEOUT_MS = 6e4;
131645
131765
  var SIGNER_READY_POLL_MS = 2e3;
131646
- async function importWalletSigner(apiOption, walletId, env) {
131766
+ async function importWalletSigner(apiOption, walletId, env, force = false) {
131767
+ refuseExistingWalletFile(env, force);
131647
131768
  const api = resolveURL(apiOption);
131648
131769
  const origin = new URL(api).origin;
131649
131770
  const document = await loadOpenApi(origin);
@@ -131652,10 +131773,10 @@ async function importWalletSigner(apiOption, walletId, env) {
131652
131773
  const result = await callAdminTool(document, origin, await adminAccessToken(api), "list_wallet_signers", {
131653
131774
  path: { walletId }
131654
131775
  });
131655
- const text5 = result.content.map((part) => part.type === "text" ? part.text : "").join("");
131656
- if (result.isError) throw new Error(text5);
131776
+ const text6 = result.content.map((part) => part.type === "text" ? part.text : "").join("");
131777
+ if (result.isError) throw new Error(text6);
131657
131778
  try {
131658
- return importSigners(JSON.parse(text5), `wallet ${walletId}`, env);
131779
+ return importSigners(JSON.parse(text6), `wallet ${walletId}`, env, force);
131659
131780
  } catch (error2) {
131660
131781
  if (Date.now() > deadline || !/is the signer ready/.test(String(error2))) throw error2;
131661
131782
  await new Promise((resolve) => setTimeout(resolve, SIGNER_READY_POLL_MS));
@@ -131668,16 +131789,16 @@ function walletCommand(wallet, missions) {
131668
131789
  );
131669
131790
  for (const tool of wallet.tools.filter(isModelVisible)) command.addCommand(commandFor(tool));
131670
131791
  for (const mission of missions ? missionCommands(missions) : []) command.addCommand(mission);
131671
- command.command("import").argument("[signer.json]", "a signer, as `keyban admin get-wallet-signer` prints it").option("--wallet-id <id>", "read the signer of this wallet through the `keyban admin login` session instead").option("--api <env|url>", "the Keyban API of that session", process.env.KEYBAN_BASE_URL ?? "prod").description("Keep the wallet configuration a signer carries in the wallet file (KEYBAN_WALLET_PATH, else XDG keyban/wallet.json)").action(async (source, options) => {
131792
+ command.command("import").argument("[signer.json]", "a signer, as `keyban admin get-wallet-signer` prints it").option("--wallet-id <id>", "read the signer of this wallet through the `keyban admin login` session instead").option("--api <env|url>", "the Keyban API of that session", process.env.KEYBAN_BASE_URL ?? "prod").option("--force", "overwrite the wallet file there, losing its client share").description("Keep the wallet configuration a signer carries in the wallet file (KEYBAN_WALLET_PATH, else XDG keyban/wallet.json)").action(async (source, options) => {
131672
131793
  try {
131673
131794
  const env = process.env;
131674
131795
  if (options.walletId) {
131675
- process.stdout.write(`Wrote ${await importWalletSigner(options.api, options.walletId, env)}
131796
+ process.stdout.write(`Wrote ${await importWalletSigner(options.api, options.walletId, env, options.force)}
131676
131797
  `);
131677
131798
  return;
131678
131799
  }
131679
131800
  if (!source) throw new Error("Give a signer.json, or --wallet-id.");
131680
- process.stdout.write(`Wrote ${importWalletFile(source, env)}
131801
+ process.stdout.write(`Wrote ${importWalletFile(source, env, options.force)}
131681
131802
  `);
131682
131803
  } catch (error2) {
131683
131804
  process.stderr.write(`Error: ${error2 instanceof Error ? error2.message : String(error2)}
@@ -131745,24 +131866,43 @@ function newWalletCommand(tool, document) {
131745
131866
  },
131746
131867
  async (args, self2) => {
131747
131868
  const api = apiOf(self2);
131869
+ const { share, force } = self2.opts();
131870
+ const env = process.env;
131871
+ refuseExistingWalletFile(env, force);
131748
131872
  const created = await callAdminTool(document, new URL(api).origin, await adminAccessToken(api), tool.name, args);
131749
131873
  if (created.isError) return created;
131750
- const text5 = created.content.map((part) => part.type === "text" ? part.text : "").join("");
131751
- const createdWallet = JSON.parse(text5);
131752
- const { share } = self2.opts();
131753
- const env = process.env;
131754
- const file = await importWalletSigner(api, createdWallet.id, env);
131874
+ const text6 = created.content.map((part) => part.type === "text" ? part.text : "").join("");
131875
+ const createdWallet = JSON.parse(text6);
131876
+ const file = await importWalletSigner(api, createdWallet.id, env, force);
131755
131877
  if (share) runDkg(env, file);
131756
131878
  return { content: [{ type: "text", text: JSON.stringify({ ...createdWallet, file }, null, 2) }] };
131757
- }
131879
+ },
131880
+ adminNames(document)
131758
131881
  );
131759
- return command.option("--share", "also run the DKG, keeping the client share in the wallet file");
131882
+ return command.option("--share", "also run the DKG, keeping the client share in the wallet file").option("--force", "overwrite the wallet file there, losing its client share");
131883
+ }
131884
+ function adminNames(document) {
131885
+ return {
131886
+ kindOf,
131887
+ nameField: nameFieldOf,
131888
+ isScoped,
131889
+ resolve: async (kind, name, self2, args) => {
131890
+ const api = apiOf(self2);
131891
+ const origin = new URL(api).origin;
131892
+ const token = await adminAccessToken(api);
131893
+ return resolveName(kind, name, (list, listArgs) => callAdminTool(document, origin, token, list, listArgs), args);
131894
+ }
131895
+ };
131760
131896
  }
131761
131897
  function commandFor2(tool, document) {
131762
- return jsonToolCommand(tool, async (args, self2) => {
131763
- const api = apiOf(self2);
131764
- return callAdminTool(document, new URL(api).origin, await adminAccessToken(api), tool.name, args);
131765
- });
131898
+ return jsonToolCommand(
131899
+ tool,
131900
+ async (args, self2) => {
131901
+ const api = apiOf(self2);
131902
+ return callAdminTool(document, new URL(api).origin, await adminAccessToken(api), tool.name, args);
131903
+ },
131904
+ adminNames(document)
131905
+ );
131766
131906
  }
131767
131907
  async function adminCommand(argv = process.argv) {
131768
131908
  const command = new Command("admin").description("Administer Keyban as yourself: log in, then one subcommand per admin MCP tool").option("--api <env|url>", `Keyban API: ${Object.keys(ENV_URLS).join(", ")}, or a URL`, defaultApi());
@@ -131842,8 +131982,8 @@ function candidates(program2, words) {
131842
131982
  const pool = typed.startsWith("-") || subcommands.length === 0 ? options : subcommands;
131843
131983
  return pool.filter((name) => name.startsWith(typed));
131844
131984
  }
131845
- function print(text5) {
131846
- return new Promise(() => process.stdout.write(text5, () => process.exit(0)));
131985
+ function print(text6) {
131986
+ return new Promise(() => process.stdout.write(text6, () => process.exit(0)));
131847
131987
  }
131848
131988
  function addCompletion(program2) {
131849
131989
  program2.command("completion").description("Print the shell completion script: source <(keyban completion bash)").argument("<shell>", `one of ${Object.keys(SCRIPTS).join(", ")}`).action(async (shell) => {
@@ -142858,8 +142998,8 @@ async function fetchRpcUrl(session) {
142858
142998
  const url2 = `${session.baseURL}/v1/metadata?network=${encodeURIComponent(session.network)}`;
142859
142999
  const res = await fetch(url2, { headers: buildApiKeyHeaders(session) });
142860
143000
  if (!res.ok) {
142861
- const text5 = await res.text();
142862
- throw new Error(`metadata request failed (${res.status}): ${text5}`);
143001
+ const text6 = await res.text();
143002
+ throw new Error(`metadata request failed (${res.status}): ${text6}`);
142863
143003
  }
142864
143004
  const json2 = await res.json();
142865
143005
  const rpcUrl = json2?.network?.rpcUrl;
@@ -143115,8 +143255,8 @@ async function* sseJsonPayloads(body) {
143115
143255
 
143116
143256
  // src/lib/policy-intents.ts
143117
143257
  var PENDING_APPROVAL = "pending_human_approval";
143118
- var text = (v) => typeof v === "string" ? v : void 0;
143119
- var nullableText = (v) => v === null ? null : text(v);
143258
+ var text2 = (v) => typeof v === "string" ? v : void 0;
143259
+ var nullableText = (v) => v === null ? null : text2(v);
143120
143260
  function asIntentState(v) {
143121
143261
  if (typeof v !== "object" || v === null) return null;
143122
143262
  const o = v;
@@ -143124,13 +143264,13 @@ function asIntentState(v) {
143124
143264
  return {
143125
143265
  intentId: o.intentId,
143126
143266
  state: o.state,
143127
- kind: text(o.kind),
143128
- recipient: text(o.recipient),
143267
+ kind: text2(o.kind),
143268
+ recipient: text2(o.recipient),
143129
143269
  resource: nullableText(o.resource),
143130
143270
  payTo: nullableText(o.payTo),
143131
- asset: text(o.asset),
143132
- amountNative: text(o.amountNative),
143133
- amountRef: text(o.amountRef),
143271
+ asset: text2(o.asset),
143272
+ amountNative: text2(o.amountNative),
143273
+ amountRef: text2(o.amountRef),
143134
143274
  expiresAt: nullableText(o.expiresAt)
143135
143275
  };
143136
143276
  }
@@ -144860,7 +145000,7 @@ function cardlessSession(session) {
144860
145000
  }
144861
145001
  async function answerInMission(pay, tool, inMissionTool, missionRunId) {
144862
145002
  const pattern = new RegExp(`\\b${tool}\\b`, "g");
144863
- const retell = (text5) => text5.replace(pattern, `${inMissionTool} (missionRunId=${missionRunId})`);
145003
+ const retell = (text6) => text6.replace(pattern, `${inMissionTool} (missionRunId=${missionRunId})`);
144864
145004
  try {
144865
145005
  const answer = await pay();
144866
145006
  return typeof answer === "string" ? retell(answer) : { ...answer, text: retell(answer.text) };
@@ -144996,9 +145136,9 @@ var BROADCAST_FAILURE_MARKERS = [
144996
145136
  "facilitator verify failed (429",
144997
145137
  "facilitator settle failed (429"
144998
145138
  ];
144999
- function isBroadcastFailure(text5) {
145000
- if (!text5) return false;
145001
- const haystack = text5.toLowerCase();
145139
+ function isBroadcastFailure(text6) {
145140
+ if (!text6) return false;
145141
+ const haystack = text6.toLowerCase();
145002
145142
  return BROADCAST_FAILURE_MARKERS.some((marker) => haystack.includes(marker));
145003
145143
  }
145004
145144
  var BROADCAST_FAILURE_HINT = "The payment never reached a block: either the facilitator itself did not answer (a gateway error), or it could not broadcast the transaction from the single account it relays every tenant through. Either way this is infrastructure trouble rather than a problem with this payment \u2014 the authorization was not spent and nothing was charged. Retrying re-sends the same authorization, which cannot double-charge.";
@@ -145188,7 +145328,7 @@ ${diag.join("\n")}` : message
145188
145328
  }
145189
145329
  const txHash = sent.txHash;
145190
145330
  const explorer = explorerTxUrl(chain.id, txHash);
145191
- const text5 = [
145331
+ const text6 = [
145192
145332
  "USDC transfer successful.",
145193
145333
  `Transaction hash: ${txHash}`,
145194
145334
  ...explorer ? [`Explorer: ${explorer}`] : []
@@ -145196,9 +145336,9 @@ ${diag.join("\n")}` : message
145196
145336
  if (input.missionRunId) {
145197
145337
  if (sent.intentId) recordRunPayment(session, input.missionRunId, { intentId: sent.intentId, txHash });
145198
145338
  else logger.warn(`transfer_usdc: transfer in mission run ${input.missionRunId} has no intent id, not recorded for the run card`);
145199
- return text5;
145339
+ return text6;
145200
145340
  }
145201
- if (!session.rendersApps) return text5;
145341
+ if (!session.rendersApps) return text6;
145202
145342
  const receipt = await paymentCard(session, {
145203
145343
  intentId: null,
145204
145344
  state: "consumed",
@@ -145210,7 +145350,7 @@ ${diag.join("\n")}` : message
145210
145350
  expiresAt: null,
145211
145351
  explorerUrl: explorer ?? null
145212
145352
  });
145213
- return { text: text5, structuredContent: receipt };
145353
+ return { text: text6, structuredContent: receipt };
145214
145354
  };
145215
145355
  }
145216
145356
  function createTransferUsdcTool(session) {
@@ -145760,7 +145900,7 @@ function probeHeaders(headers, body) {
145760
145900
 
145761
145901
  // src/lib/seller-error.ts
145762
145902
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
145763
- var text2 = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
145903
+ var text3 = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
145764
145904
  function sellerError(body) {
145765
145905
  let parsed;
145766
145906
  try {
@@ -145770,11 +145910,11 @@ function sellerError(body) {
145770
145910
  }
145771
145911
  if (!isRecord(parsed)) return void 0;
145772
145912
  const validation = parsed.validation_error;
145773
- const fromValidation = isRecord(validation) ? text2(validation.error) ?? text2(validation.message) : text2(validation);
145913
+ const fromValidation = isRecord(validation) ? text3(validation.error) ?? text3(validation.message) : text3(validation);
145774
145914
  if (fromValidation) return fromValidation;
145775
145915
  if (Array.isArray(parsed.accepts)) return void 0;
145776
145916
  const error2 = parsed.error;
145777
- return (isRecord(error2) ? text2(error2.message) : text2(error2)) ?? text2(parsed.message) ?? text2(parsed.detail);
145917
+ return (isRecord(error2) ? text3(error2.message) : text3(error2)) ?? text3(parsed.message) ?? text3(parsed.detail);
145778
145918
  }
145779
145919
  function chargeState(settle, body) {
145780
145920
  let parsed;
@@ -146210,7 +146350,7 @@ ${paidByKeybanLine({
146210
146350
  } else if (signedBy === "server") {
146211
146351
  paymentInfo += "\nCovered by the Keyban welcome offer: nothing was taken from the wallet.";
146212
146352
  }
146213
- const text5 = `${response.status} ${response.statusText}${paymentInfo}
146353
+ const text6 = `${response.status} ${response.statusText}${paymentInfo}
146214
146354
 
146215
146355
  ${responseBody}`;
146216
146356
  if (missionRunId) {
@@ -146220,9 +146360,9 @@ ${responseBody}`;
146220
146360
  } else {
146221
146361
  logger.warn(`x402_pay: payment in mission run ${missionRunId} has no intent id, not recorded for the run card`);
146222
146362
  }
146223
- return text5;
146363
+ return text6;
146224
146364
  }
146225
- if (prepaid || !session.rendersApps) return text5;
146365
+ if (prepaid || !session.rendersApps) return text6;
146226
146366
  const receipt = await paymentCard(session, {
146227
146367
  intentId: intentId ?? null,
146228
146368
  state: "consumed",
@@ -146234,7 +146374,7 @@ ${responseBody}`;
146234
146374
  expiresAt: null,
146235
146375
  explorerUrl: ((hash3) => hash3 ? explorerTxUrl(chainId, hash3) ?? null : null)(settledTxHash(settle))
146236
146376
  });
146237
- return { text: text5, structuredContent: receipt };
146377
+ return { text: text6, structuredContent: receipt };
146238
146378
  };
146239
146379
  return (input) => withFundingFallback(pay, input, session.funding);
146240
146380
  }
@@ -146812,8 +146952,8 @@ function fieldLines(section, location) {
146812
146952
  const type = typeof rawType === "string" ? rawType : "any";
146813
146953
  const flags = [type, requiredSet.has(name) ? "required" : null, location ?? null].filter((flag) => flag !== null).join(", ");
146814
146954
  const description = at(spec, ["description"]);
146815
- const text5 = typeof description === "string" ? `: ${description.slice(0, MAX_DESCRIPTION)}` : "";
146816
- return ` - ${name} (${flags})${text5}`;
146955
+ const text6 = typeof description === "string" ? `: ${description.slice(0, MAX_DESCRIPTION)}` : "";
146956
+ return ` - ${name} (${flags})${text6}`;
146817
146957
  });
146818
146958
  }
146819
146959
  function examplePathLines(examples) {
@@ -147279,8 +147419,8 @@ var discoverX402ServicesSchema = external_exports.object({
147279
147419
  limit: external_exports.number().int().positive().max(50).optional().default(10).describe("Max number of services to return (default 10, max 50).")
147280
147420
  });
147281
147421
  var MAX_HINT_CHARS = 300;
147282
- function truncate(text5) {
147283
- return text5.length <= MAX_HINT_CHARS ? text5 : `${text5.slice(0, MAX_HINT_CHARS)}\u2026 (truncated, ${text5.length} chars)`;
147422
+ function truncate(text6) {
147423
+ return text6.length <= MAX_HINT_CHARS ? text6 : `${text6.slice(0, MAX_HINT_CHARS)}\u2026 (truncated, ${text6.length} chars)`;
147284
147424
  }
147285
147425
  var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
147286
147426
  function exampleEntries(params) {
@@ -147660,13 +147800,13 @@ async function fetchMissionRun(session, runId) {
147660
147800
 
147661
147801
  // src/lib/mission-card.ts
147662
147802
  var record3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : null;
147663
- var text3 = (v) => typeof v === "string" ? v : null;
147803
+ var text4 = (v) => typeof v === "string" ? v : null;
147664
147804
  var count = (v) => typeof v === "number" && Number.isInteger(v) ? v : null;
147665
147805
  var amount = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : null;
147666
147806
  function frequencyOf(v) {
147667
147807
  const frequency = record3(v);
147668
147808
  const times = count(frequency?.count);
147669
- const period = text3(frequency?.period);
147809
+ const period = text4(frequency?.period);
147670
147810
  return times !== null && period !== null ? { count: times, period } : null;
147671
147811
  }
147672
147812
  var records = (v) => Array.isArray(v) ? v.flatMap((item) => {
@@ -147676,8 +147816,8 @@ var records = (v) => Array.isArray(v) ? v.flatMap((item) => {
147676
147816
  function sourcesOf(v) {
147677
147817
  if (!Array.isArray(v)) return null;
147678
147818
  return records(v).flatMap((source) => {
147679
- const endpoint = text3(source.endpoint);
147680
- return endpoint === null ? [] : [{ endpoint, label: text3(source.label), callsPerUnit: count(source.callsPerUnit), callPriceRef: amount(source.callPriceRef) }];
147819
+ const endpoint = text4(source.endpoint);
147820
+ return endpoint === null ? [] : [{ endpoint, label: text4(source.label), callsPerUnit: count(source.callsPerUnit), callPriceRef: amount(source.callPriceRef) }];
147681
147821
  });
147682
147822
  }
147683
147823
  function usageOf(v, txUrls) {
@@ -147690,9 +147830,9 @@ function usageOf(v, txUrls) {
147690
147830
  ...source,
147691
147831
  calls: count(usage.calls) ?? 0,
147692
147832
  paidRef: amount(usage.paidRef) ?? "0",
147693
- paidCents: text3(usage.paidCents),
147833
+ paidCents: text4(usage.paidCents),
147694
147834
  paidNative: amount(usage.paidNative),
147695
- asset: text3(usage.asset),
147835
+ asset: text4(usage.asset),
147696
147836
  txUrls: intentIds.flatMap(txUrls)
147697
147837
  }];
147698
147838
  });
@@ -147718,8 +147858,8 @@ var NOTHING_SPENT = {
147718
147858
  };
147719
147859
  function economics(source) {
147720
147860
  return {
147721
- currency: text3(source.currency) ?? "",
147722
- unitLabel: text3(source.unitLabel),
147861
+ currency: text4(source.currency) ?? "",
147862
+ unitLabel: text4(source.unitLabel),
147723
147863
  unitPriceRef: amount(source.unitPriceRef),
147724
147864
  unitCount: count(source.unitCount),
147725
147865
  overrides: Array.isArray(source.overrides) ? source.overrides.length : 0,
@@ -147729,9 +147869,9 @@ function economics(source) {
147729
147869
  };
147730
147870
  }
147731
147871
  function cardOfRun(run, approvalUrl) {
147732
- const runId = text3(run.id);
147733
- const missionId = text3(run.missionId);
147734
- const status = text3(run.status);
147872
+ const runId = text4(run.id);
147873
+ const missionId = text4(run.missionId);
147874
+ const status = text4(run.status);
147735
147875
  const envelopeRef = amount(run.envelopeRef);
147736
147876
  if (!runId || !missionId || !status || envelopeRef === null) return null;
147737
147877
  const usage = usageOf(run.sourceUsage, () => []);
@@ -147740,7 +147880,7 @@ function cardOfRun(run, approvalUrl) {
147740
147880
  return {
147741
147881
  kind: run.kind === "trial" ? "trial" : "run",
147742
147882
  missionId,
147743
- missionTitle: text3(run.missionTitle) ?? "",
147883
+ missionTitle: text4(run.missionTitle) ?? "",
147744
147884
  versionNumber: count(run.versionNumber) ?? 0,
147745
147885
  runId,
147746
147886
  status,
@@ -147750,13 +147890,13 @@ function cardOfRun(run, approvalUrl) {
147750
147890
  mode: null,
147751
147891
  frequency: null,
147752
147892
  digest: null,
147753
- expiresAt: text3(run.expiresAt),
147893
+ expiresAt: text4(run.expiresAt),
147754
147894
  approvalUrl,
147755
147895
  sourceUsage: usage,
147756
147896
  spentRef: amount(run.spentRef),
147757
- spentCents: text3(run.spentCents),
147897
+ spentCents: text4(run.spentCents),
147758
147898
  spentNative: amount(run.spentNative),
147759
- spentAsset: text3(run.spentAsset),
147899
+ spentAsset: text4(run.spentAsset),
147760
147900
  payments,
147761
147901
  unitsDone: count(run.unitsDoneCount),
147762
147902
  ...NOTHING_TO_SHOW,
@@ -147790,9 +147930,9 @@ function cardOfCompletion(run, context) {
147790
147930
  kind: "completion",
147791
147931
  sourceUsage: usage,
147792
147932
  spentRef: amount(run.spentRef),
147793
- spentCents: text3(run.spentCents),
147933
+ spentCents: text4(run.spentCents),
147794
147934
  spentNative: amount(run.spentNative),
147795
- spentAsset: text3(run.spentAsset),
147935
+ spentAsset: text4(run.spentAsset),
147796
147936
  payments: made,
147797
147937
  otherPayments: otherCalls === 0 ? null : { calls: otherCalls, txUrls: others.flatMap((payment) => urlOf(payment.intentId)) },
147798
147938
  runKind: trial ? "trial" : "run",
@@ -147802,23 +147942,23 @@ function cardOfCompletion(run, context) {
147802
147942
  }
147803
147943
  function cardOfDraft(mission, approvalUrl) {
147804
147944
  const draft = record3(mission.draft);
147805
- const missionId = text3(mission.id);
147945
+ const missionId = text4(mission.id);
147806
147946
  const versionNumber = count(draft?.number);
147807
147947
  const envelopeRef = amount(draft?.envelopeRef);
147808
147948
  if (!draft || !missionId || versionNumber === null || envelopeRef === null) return null;
147809
147949
  return {
147810
147950
  kind: "publication",
147811
147951
  missionId,
147812
- missionTitle: text3(draft.title) ?? "",
147952
+ missionTitle: text4(draft.title) ?? "",
147813
147953
  versionNumber,
147814
147954
  runId: null,
147815
147955
  status: "pending_publication",
147816
147956
  envelopeRef,
147817
147957
  ...economics(draft),
147818
- sharing: text3(draft.sharing),
147819
- mode: text3(draft.mode),
147958
+ sharing: text4(draft.sharing),
147959
+ mode: text4(draft.mode),
147820
147960
  frequency: frequencyOf(draft.frequency),
147821
- digest: text3(draft.digest),
147961
+ digest: text4(draft.digest),
147822
147962
  expiresAt: null,
147823
147963
  approvalUrl,
147824
147964
  sourceUsage: null,
@@ -147831,7 +147971,7 @@ function publicationState(mission, versionNumber, digest) {
147831
147971
  if (count(record3(mission.published)?.number) === versionNumber) return "published";
147832
147972
  const draft = record3(mission.draft);
147833
147973
  if (!draft) return "discarded";
147834
- return text3(draft.digest) === digest ? "pending_publication" : "draft_changed";
147974
+ return text4(draft.digest) === digest ? "pending_publication" : "draft_changed";
147835
147975
  }
147836
147976
 
147837
147977
  // src/lib/mission-publishability.ts
@@ -147914,13 +148054,13 @@ function createPublishMissionTool(session) {
147914
148054
  const link = missionPageLink(session.baseURL, session.appId, missionId);
147915
148055
  const card = cardOfDraft(mission, link);
147916
148056
  if (!card) throw new Error(`MISSION_NO_DRAFT: mission ${input.mission} has no draft to publish.`);
147917
- const text5 = [
148057
+ const text6 = [
147918
148058
  `The draft v${card.versionNumber} of "${card.missionTitle}" can be published. Ask the user to publish it in the Keyban dashboard${link ? `: ${link}` : "."}`,
147919
148059
  PUBLISHER_NOTE,
147920
148060
  elsewhere ? OTHER_WALLET_NOTE : "",
147921
148061
  card.sharing === "organization" ? ORGANIZATION_NOTE : ""
147922
148062
  ].filter(Boolean).join(" ");
147923
- return { text: text5, structuredContent: { card } };
148063
+ return { text: text6, structuredContent: { card } };
147924
148064
  }
147925
148065
  };
147926
148066
  }
@@ -147933,8 +148073,8 @@ function sourcesOf2(v) {
147933
148073
  if (!Array.isArray(v)) return [];
147934
148074
  return v.flatMap((item) => {
147935
148075
  const source = record3(item);
147936
- const endpoint = text3(source?.endpoint);
147937
- return source && endpoint !== null ? [{ endpoint, label: text3(source.label), callsPerUnit: count(source.callsPerUnit), callPriceRef: amount(source.callPriceRef) }] : [];
148076
+ const endpoint = text4(source?.endpoint);
148077
+ return source && endpoint !== null ? [{ endpoint, label: text4(source.label), callsPerUnit: count(source.callsPerUnit), callPriceRef: amount(source.callPriceRef) }] : [];
147938
148078
  });
147939
148079
  }
147940
148080
  var planOf = (source) => ({
@@ -147975,9 +148115,9 @@ function statsOf(mission) {
147975
148115
  if (!stats || number4 === null) return [];
147976
148116
  return [{
147977
148117
  number: number4,
147978
- status: text3(stats.status) ?? "",
148118
+ status: text4(stats.status) ?? "",
147979
148119
  basis: basis === "regular" || basis === "trial" ? basis : null,
147980
- price: text3(stats.observedUnitPriceCents)
148120
+ price: text4(stats.observedUnitPriceCents)
147981
148121
  }];
147982
148122
  });
147983
148123
  }
@@ -148134,7 +148274,7 @@ function walletTools(session) {
148134
148274
 
148135
148275
  // src/lib/x402-cache.ts
148136
148276
  import { createHash as createHash2 } from "node:crypto";
148137
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, writeFileSync as writeFileSync3 } from "node:fs";
148277
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "node:fs";
148138
148278
  import { homedir as homedir3 } from "node:os";
148139
148279
  import { dirname as dirname4, join as join5 } from "node:path";
148140
148280
  function read(file) {
@@ -148162,7 +148302,7 @@ function write(file, data) {
148162
148302
  mkdirSync3(dirname4(file), { recursive: true, mode: 448 });
148163
148303
  const tmp = `${file}.${process.pid}.tmp`;
148164
148304
  writeFileSync3(tmp, JSON.stringify(data), { mode: 384 });
148165
- renameSync(tmp, file);
148305
+ renameSync2(tmp, file);
148166
148306
  }
148167
148307
  var PersistedMap = class extends Map {
148168
148308
  constructor(file, field) {
@@ -148316,14 +148456,14 @@ async function waitForMissionRun(session, runId, timeoutMs) {
148316
148456
 
148317
148457
  // src/lib/mission-run-decision.ts
148318
148458
  var WAIT_TOOL = "wait_for_mission_run";
148319
- var text4 = (v) => typeof v === "string" ? v : "";
148459
+ var text5 = (v) => typeof v === "string" ? v : "";
148320
148460
  var subjectOf = (run) => run.kind === "trial" ? "The trial" : "The run";
148321
148461
  var validatedAt = (session, runId) => {
148322
148462
  const link = missionRunLink(session.baseURL, session.appId, runId);
148323
148463
  return link ? ` The user validates it at ${link}.` : "";
148324
148464
  };
148325
148465
  function awaitingDecision(session, run) {
148326
- const runId = text4(run.id);
148466
+ const runId = text5(run.id);
148327
148467
  return `${subjectOf(run)} waits for a wallet operator's approval: its card shows the user the Validate in Keyban button.${validatedAt(session, runId)} Call ${WAIT_TOOL} with runId ${runId} now, and again while it is still waiting. Do not start the work before it says active.`;
148328
148468
  }
148329
148469
  function stillWaiting3(session, runId) {
@@ -148331,18 +148471,18 @@ function stillWaiting3(session, runId) {
148331
148471
  }
148332
148472
  function decisionText(run) {
148333
148473
  const subject = subjectOf(run);
148334
- const status = text4(run.status);
148474
+ const status = text5(run.status);
148335
148475
  if (status === "active") {
148336
- return `${subject} is active: execute the mission now, do not ask the user again (the validation is the go-ahead). Pay with x402_pay_in_mission or transfer_usdc_in_mission and missionRunId ${text4(run.id)}; deliver the result to the user, then call complete_mission_run last.`;
148476
+ return `${subject} is active: execute the mission now, do not ask the user again (the validation is the go-ahead). Pay with x402_pay_in_mission or transfer_usdc_in_mission and missionRunId ${text5(run.id)}; deliver the result to the user, then call complete_mission_run last.`;
148337
148477
  }
148338
148478
  if (status === "completed") return `${subject} is already finished: there is nothing more to do on it. Do not start the work again.`;
148339
148479
  if (status === MISSION_RUN_PENDING) {
148340
- return `${subject} is still waiting for the operator: call ${WAIT_TOOL} again with runId ${text4(run.id)}. Do not start the work yet.`;
148480
+ return `${subject} is still waiting for the operator: call ${WAIT_TOOL} again with runId ${text5(run.id)}. Do not start the work yet.`;
148341
148481
  }
148342
148482
  return `${subject} is ${status}: it was not approved to go on. Stop here, do not start the work, and tell the user.`;
148343
148483
  }
148344
148484
  async function settleRun(session, run, timeoutMs) {
148345
- const runId = text4(run.id);
148485
+ const runId = text5(run.id);
148346
148486
  if (run.status !== MISSION_RUN_PENDING || !runId) return { run, text: null };
148347
148487
  const waited = await waitForMissionRun(session, runId, timeoutMs);
148348
148488
  if (!waited.decided) return { run, text: stillWaiting3(session, runId) };
@@ -148373,8 +148513,8 @@ var waitForMissionRunTool = {
148373
148513
  async function callWaitForMissionRun(session, args) {
148374
148514
  const input = waitForMissionRunSchema.parse(args);
148375
148515
  requireCredentials(session);
148376
- const { run, text: text5 } = await settleRun(session, await fetchMissionRun(session, input.runId), input.timeoutMs);
148377
- return { content: [{ type: "text", text: text5 ?? decisionText(run) }], structuredContent: run };
148516
+ const { run, text: text6 } = await settleRun(session, await fetchMissionRun(session, input.runId), input.timeoutMs);
148517
+ return { content: [{ type: "text", text: text6 ?? decisionText(run) }], structuredContent: run };
148378
148518
  }
148379
148519
 
148380
148520
  // src/lib/wallet-scope.ts
@@ -148449,7 +148589,7 @@ ${WALLET_NOTE}`.trimStart();
148449
148589
  var RUN_TOOLS = /* @__PURE__ */ new Set(["start_mission_run", "request_mission_trial"]);
148450
148590
  var COMPLETE_TOOL = "complete_mission_run";
148451
148591
  var MISSION_CARD_TOOLS = /* @__PURE__ */ new Set([...RUN_TOOLS, COMPLETE_TOOL]);
148452
- var failure = (text5) => ({ content: [{ type: "text", text: text5 }], isError: true });
148592
+ var failure = (text6) => ({ content: [{ type: "text", text: text6 }], isError: true });
148453
148593
  function buildServer(operations, session) {
148454
148594
  const server = (0, import_mcp_openapi2.createMcpServer)({ name: "keyban-missions", version: "0" }, { capabilities: { tools: {} } });
148455
148595
  const registry2 = new import_mcp_openapi2.ToolRegistry(
@@ -149920,7 +150060,7 @@ async function readRequestBody(request, maxBytes = DEFAULT_MAX_REQUEST_BODY_SIZE
149920
150060
  const reader2 = request.body.getReader();
149921
150061
  const decoder2 = new TextDecoder();
149922
150062
  let received = 0;
149923
- let text5 = "";
150063
+ let text6 = "";
149924
150064
  try {
149925
150065
  for (; ; ) {
149926
150066
  const { done, value } = await reader2.read();
@@ -149931,12 +150071,12 @@ async function readRequestBody(request, maxBytes = DEFAULT_MAX_REQUEST_BODY_SIZE
149931
150071
  if (received > maxBytes) {
149932
150072
  return { tooLarge: true };
149933
150073
  }
149934
- text5 += decoder2.decode(value, { stream: true });
150074
+ text6 += decoder2.decode(value, { stream: true });
149935
150075
  }
149936
150076
  } finally {
149937
150077
  reader2.releaseLock();
149938
150078
  }
149939
- return { tooLarge: false, text: text5 + decoder2.decode() };
150079
+ return { tooLarge: false, text: text6 + decoder2.decode() };
149940
150080
  }
149941
150081
 
149942
150082
  // node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_supports-color@7.2.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.js
@@ -150944,7 +151084,7 @@ async function serveMcp(wallet, version5, { http: http2 }, missions) {
150944
151084
  }
150945
151085
 
150946
151086
  // src/index.ts
150947
- var VERSION = true ? "0.2.2" : "0.0.0";
151087
+ var VERSION = true ? "0.2.3" : "0.0.0";
150948
151088
  if (process.argv[2] !== "mcp" && !process.env.MCP_LOG_LEVEL) logger.setMinLevel("error");
150949
151089
  function typedArgv(argv) {
150950
151090
  if (argv[2] !== "__complete") return argv;