kenso 0.1.138 → 0.1.140

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/kenso.js CHANGED
@@ -282,18 +282,18 @@ function readConfig(env = process.env) {
282
282
  }
283
283
  return config;
284
284
  }
285
- function ensurePrivateDir(dir2) {
286
- mkdirSync(dir2, { recursive: true, mode: 448 });
285
+ function ensurePrivateDir(dir3) {
286
+ mkdirSync(dir3, { recursive: true, mode: 448 });
287
287
  try {
288
- chmodSync(dir2, 448);
288
+ chmodSync(dir3, 448);
289
289
  } catch {
290
290
  }
291
291
  }
292
292
  function writeConfig(config, env) {
293
- const dir2 = configDir(env);
294
- ensurePrivateDir(dir2);
295
- const file = join(dir2, CONFIG_FILE);
296
- const temp = join(dir2, `.${CONFIG_FILE}.${process.pid}.${Date.now()}.tmp`);
293
+ const dir3 = configDir(env);
294
+ ensurePrivateDir(dir3);
295
+ const file = join(dir3, CONFIG_FILE);
296
+ const temp = join(dir3, `.${CONFIG_FILE}.${process.pid}.${Date.now()}.tmp`);
297
297
  try {
298
298
  writeFileSync(temp, `${JSON.stringify(config, null, 2)}
299
299
  `, { mode: 384 });
@@ -321,13 +321,13 @@ function removeProfile(name, env = process.env) {
321
321
  writeConfig(config, env);
322
322
  }
323
323
  function cacheDir(env = process.env) {
324
- const dir2 = join(configDir(env), "cache");
325
- ensurePrivateDir(dir2);
326
- return dir2;
324
+ const dir3 = join(configDir(env), "cache");
325
+ ensurePrivateDir(dir3);
326
+ return dir3;
327
327
  }
328
328
  function clearCache(env = process.env) {
329
- const dir2 = join(configDir(env), "cache");
330
- if (existsSync(dir2)) rmSync(dir2, { recursive: true, force: true });
329
+ const dir3 = join(configDir(env), "cache");
330
+ if (existsSync(dir3)) rmSync(dir3, { recursive: true, force: true });
331
331
  }
332
332
  function nonEmpty(value) {
333
333
  const trimmed = value?.trim();
@@ -2485,23 +2485,23 @@ var VERSION;
2485
2485
  var init_version = __esm({
2486
2486
  "src/core/version.ts"() {
2487
2487
  "use strict";
2488
- VERSION = true ? "0.1.138" : "0.0.0-dev";
2488
+ VERSION = true ? "0.1.140" : "0.0.0-dev";
2489
2489
  }
2490
2490
  });
2491
2491
 
2492
2492
  // src/core/context.ts
2493
- function createContext(flags, env = process.env, overrides) {
2493
+ function createContext(flags, env = process.env, overrides2) {
2494
2494
  const agent = detectAgent(env);
2495
- const signal = overrides?.signal ?? new AbortController().signal;
2496
- const auth = overrides?.noConfig ? authWithoutConfig({ workspace: flags.workspace }, env) : resolveAuth({ profile: flags.profile, workspace: flags.workspace }, env);
2495
+ const signal = overrides2?.signal ?? new AbortController().signal;
2496
+ const auth = overrides2?.noConfig ? authWithoutConfig({ workspace: flags.workspace }, env) : resolveAuth({ profile: flags.profile, workspace: flags.workspace }, env);
2497
2497
  const output = new Output({
2498
2498
  format: flags.output,
2499
2499
  fields: flags.fields?.split(","),
2500
2500
  query: flags.query,
2501
- stdout: overrides?.stdout,
2502
- stderr: overrides?.stderr,
2503
- stdoutIsTTY: overrides?.stdoutIsTTY,
2504
- stderrIsTTY: overrides?.stderrIsTTY,
2501
+ stdout: overrides2?.stdout,
2502
+ stderr: overrides2?.stderr,
2503
+ stdoutIsTTY: overrides2?.stdoutIsTTY,
2504
+ stderrIsTTY: overrides2?.stderrIsTTY,
2505
2505
  progress: flags.progress
2506
2506
  });
2507
2507
  const client = new KensoClient({
@@ -2510,8 +2510,8 @@ function createContext(flags, env = process.env, overrides) {
2510
2510
  workspaceId: auth.workspaceId,
2511
2511
  agent,
2512
2512
  version: VERSION,
2513
- fetchImpl: overrides?.fetchImpl,
2514
- sleep: overrides?.sleep,
2513
+ fetchImpl: overrides2?.fetchImpl,
2514
+ sleep: overrides2?.sleep,
2515
2515
  signal,
2516
2516
  onRetry: ({ status, waitMs }) => {
2517
2517
  const seconds = Math.max(1, Math.round(waitMs / 1e3));
@@ -2532,7 +2532,7 @@ function createContext(flags, env = process.env, overrides) {
2532
2532
  agent,
2533
2533
  version: VERSION,
2534
2534
  signal,
2535
- stdin: overrides?.stdin
2535
+ stdin: overrides2?.stdin
2536
2536
  };
2537
2537
  }
2538
2538
  var init_context = __esm({
@@ -2574,14 +2574,14 @@ async function loadWorkspaceFeatures(ctx, opts = {}) {
2574
2574
  if (!key) return { features: [] };
2575
2575
  const now = Date.now();
2576
2576
  let file;
2577
- let cache = {};
2577
+ let cache2 = {};
2578
2578
  try {
2579
2579
  file = join2(cacheDir(ctx.env), CACHE_FILE);
2580
- cache = readCache(file);
2580
+ cache2 = readCache(file);
2581
2581
  } catch {
2582
2582
  file = void 0;
2583
2583
  }
2584
- const hit = cache[key];
2584
+ const hit = cache2[key];
2585
2585
  if (isFresh(hit, now)) return { features: hit.features.filter((f) => typeof f === "string") };
2586
2586
  const timeoutMs2 = opts.timeoutMs ?? FETCH_TIMEOUT_MS;
2587
2587
  const timeout = AbortSignal.timeout(timeoutMs2);
@@ -2598,7 +2598,7 @@ async function loadWorkspaceFeatures(ctx, opts = {}) {
2598
2598
  if (file) {
2599
2599
  try {
2600
2600
  const kept = {};
2601
- for (const [k, entry] of Object.entries(cache)) if (isFresh(entry, now)) kept[k] = entry;
2601
+ for (const [k, entry] of Object.entries(cache2)) if (isFresh(entry, now)) kept[k] = entry;
2602
2602
  kept[key] = { features, fetchedAt: new Date(now).toISOString() };
2603
2603
  const temp = `${file}.${process.pid}.tmp`;
2604
2604
  writeFileSync2(temp, `${JSON.stringify(kept)}
@@ -2639,6 +2639,7 @@ __export(manifest_exports, {
2639
2639
  findOperationById: () => findOperationById,
2640
2640
  listOperations: () => listOperations,
2641
2641
  loadManifest: () => loadManifest,
2642
+ routeEffect: () => routeEffect,
2642
2643
  useManifestDirForTest: () => useManifestDirForTest,
2643
2644
  useManifestForTest: () => useManifestForTest
2644
2645
  });
@@ -2676,6 +2677,25 @@ function listOperations() {
2676
2677
  if (override) return override.operations;
2677
2678
  return loadIndex()?.operations ?? loadManifest().operations;
2678
2679
  }
2680
+ function routeEffect(method, path) {
2681
+ const fold2 = (segment) => {
2682
+ try {
2683
+ return decodeURIComponent(segment).toLowerCase();
2684
+ } catch {
2685
+ return segment.toLowerCase();
2686
+ }
2687
+ };
2688
+ const segments = path.split(/[?#]/, 1)[0].replace(/\/+$/, "").split("/").map(fold2);
2689
+ let best;
2690
+ for (const op of listOperations()) {
2691
+ const template2 = op.path.split("/");
2692
+ if (op.method !== method || template2.length !== segments.length) continue;
2693
+ const literals = template2.filter((part) => !part.startsWith("{")).length;
2694
+ const fits = template2.every((part, i) => part.startsWith("{") ? segments[i] !== "" : part.toLowerCase() === segments[i]);
2695
+ if (fits && (!best || literals > best.literals)) best = { effect: op.effect ?? "write", literals };
2696
+ }
2697
+ return best?.effect;
2698
+ }
2679
2699
  function indexes() {
2680
2700
  if (!byCommand || !byId) {
2681
2701
  const operations = listOperations();
@@ -4031,15 +4051,15 @@ import { createHash } from "node:crypto";
4031
4051
  import { readFileSync as readFileSync5 } from "node:fs";
4032
4052
  import { readFile as readFile3 } from "node:fs/promises";
4033
4053
  import { join as join4 } from "node:path";
4034
- function filesOf(dir2) {
4054
+ function filesOf(dir3) {
4035
4055
  return {
4036
- runJson: join4(dir2, "run.json"),
4037
- stateJson: join4(dir2, "state.json"),
4038
- resultsCsv: join4(dir2, "results.csv"),
4039
- resultsNdjson: join4(dir2, "results.ndjson"),
4040
- invalidCsv: join4(dir2, "invalid.csv"),
4041
- planJson: join4(dir2, "plan.json"),
4042
- summaryJson: join4(dir2, "summary.json")
4056
+ runJson: join4(dir3, "run.json"),
4057
+ stateJson: join4(dir3, "state.json"),
4058
+ resultsCsv: join4(dir3, "results.csv"),
4059
+ resultsNdjson: join4(dir3, "results.ndjson"),
4060
+ invalidCsv: join4(dir3, "invalid.csv"),
4061
+ planJson: join4(dir3, "plan.json"),
4062
+ summaryJson: join4(dir3, "summary.json")
4043
4063
  };
4044
4064
  }
4045
4065
  function hashItems(items) {
@@ -4215,24 +4235,24 @@ function rootRefusal(stats) {
4215
4235
  if ((stats.mode & 18) !== 0 && !sticky) return `other users can write it (mode ${modeText(stats)})`;
4216
4236
  return void 0;
4217
4237
  }
4218
- function notPrivateError(dir2, reason) {
4219
- return usageError(`kenso will not keep runs in ${dir2}: ${reason}.`, {
4238
+ function notPrivateError(dir3, reason) {
4239
+ return usageError(`kenso will not keep runs in ${dir3}: ${reason}.`, {
4220
4240
  hint: "Use a folder only you own and can write (chmod 700 it), or leave KENSO_RUNS_DIR and --out unset to use ~/.kenso/runs."
4221
4241
  });
4222
4242
  }
4223
- function ensureDir(dir2, mode) {
4224
- mkdirSync2(dir2, { recursive: true, mode: mode & 511 });
4243
+ function ensureDir(dir3, mode) {
4244
+ mkdirSync2(dir3, { recursive: true, mode: mode & 511 });
4225
4245
  const uid = currentUid();
4226
4246
  try {
4227
- chmodSync2(dir2, mode);
4247
+ chmodSync2(dir3, mode);
4228
4248
  } catch (err) {
4229
4249
  if (uid === void 0) return;
4230
- throw notPrivateError(dir2, `kenso cannot set its mode (${err.code ?? String(err)})`);
4250
+ throw notPrivateError(dir3, `kenso cannot set its mode (${err.code ?? String(err)})`);
4231
4251
  }
4232
4252
  if (uid === void 0) return;
4233
- const stats = statSync(dir2);
4234
- if (stats.uid !== uid) throw notPrivateError(dir2, `another user (uid ${stats.uid}) owns it`);
4235
- if ((stats.mode & 18 & ~mode) !== 0) throw notPrivateError(dir2, `its mode stayed ${modeText(stats)} after kenso set it`);
4253
+ const stats = statSync(dir3);
4254
+ if (stats.uid !== uid) throw notPrivateError(dir3, `another user (uid ${stats.uid}) owns it`);
4255
+ if ((stats.mode & 18 & ~mode) !== 0) throw notPrivateError(dir3, `its mode stayed ${modeText(stats)} after kenso set it`);
4236
4256
  }
4237
4257
  async function checkRoot(root2) {
4238
4258
  let stats;
@@ -4249,8 +4269,8 @@ async function checkRoot(root2) {
4249
4269
  if (refusal2) throw notPrivateError(root2, refusal2);
4250
4270
  return true;
4251
4271
  }
4252
- function ensurePrivateDir2(dir2) {
4253
- ensureDir(dir2, 448);
4272
+ function ensurePrivateDir2(dir3) {
4273
+ ensureDir(dir3, 448);
4254
4274
  }
4255
4275
  async function writeFileAtomic(path, content) {
4256
4276
  const temp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
@@ -4267,8 +4287,8 @@ async function writeJsonAtomic(path, value) {
4267
4287
  `);
4268
4288
  }
4269
4289
  async function writeRunRecord(record3) {
4270
- const { dir: dir2, ...rest } = record3;
4271
- await writeJsonAtomic(join5(dir2, "run.json"), rest);
4290
+ const { dir: dir3, ...rest } = record3;
4291
+ await writeJsonAtomic(join5(dir3, "run.json"), rest);
4272
4292
  }
4273
4293
  function notYoursError(path, reason) {
4274
4294
  return new KensoError({
@@ -4297,18 +4317,18 @@ function chunkList(value) {
4297
4317
  if (!Array.isArray(value)) return void 0;
4298
4318
  return value.filter((n) => Number.isInteger(n) && n >= 0);
4299
4319
  }
4300
- async function readRun(dir2) {
4320
+ async function readRun(dir3) {
4301
4321
  let dirStats;
4302
4322
  try {
4303
- dirStats = await stat(dir2);
4323
+ dirStats = await stat(dir3);
4304
4324
  } catch {
4305
4325
  return null;
4306
4326
  }
4307
4327
  const refusal2 = notOurs(dirStats);
4308
- if (refusal2) throw notYoursError(dir2, refusal2);
4328
+ if (refusal2) throw notYoursError(dir3, refusal2);
4309
4329
  let raw;
4310
4330
  try {
4311
- raw = asRecord3(await readOwnJson(join5(dir2, "run.json")));
4331
+ raw = asRecord3(await readOwnJson(join5(dir3, "run.json")));
4312
4332
  } catch (err) {
4313
4333
  if (err instanceof KensoError) throw err;
4314
4334
  return null;
@@ -4320,7 +4340,7 @@ async function readRun(dir2) {
4320
4340
  if (typeof status !== "string" || !STATUSES.includes(status)) return null;
4321
4341
  let chunksDone = chunkList(raw.chunksDone) ?? [];
4322
4342
  try {
4323
- const state = asRecord3(await readOwnJson(join5(dir2, "state.json")));
4343
+ const state = asRecord3(await readOwnJson(join5(dir3, "state.json")));
4324
4344
  chunksDone = chunkList(state?.chunksDone) ?? chunksDone;
4325
4345
  } catch {
4326
4346
  }
@@ -4333,12 +4353,12 @@ async function readRun(dir2) {
4333
4353
  status,
4334
4354
  chunkCount: typeof raw.chunkCount === "number" ? raw.chunkCount : 0,
4335
4355
  chunksDone: [...new Set(chunksDone)].sort((a, b) => a - b),
4336
- dir: dir2
4356
+ dir: dir3
4337
4357
  };
4338
4358
  return record3;
4339
4359
  }
4340
- async function readRunDir(dir2) {
4341
- return readRun(dir2).catch(() => null);
4360
+ async function readRunDir(dir3) {
4361
+ return readRun(dir3).catch(() => null);
4342
4362
  }
4343
4363
  async function listRuns(env = process.env) {
4344
4364
  const root2 = runsRoot(env);
@@ -4352,13 +4372,13 @@ async function listRuns(env = process.env) {
4352
4372
  const runs = [];
4353
4373
  for (const name of names) {
4354
4374
  if (!RUN_ID_PATTERN.test(name)) continue;
4355
- let dir2;
4375
+ let dir3;
4356
4376
  try {
4357
- dir2 = await realpath(join5(root2, name));
4377
+ dir3 = await realpath(join5(root2, name));
4358
4378
  } catch {
4359
4379
  continue;
4360
4380
  }
4361
- const run = await readRunDir(dir2);
4381
+ const run = await readRunDir(dir3);
4362
4382
  if (run && run.runId === name) runs.push(run);
4363
4383
  }
4364
4384
  return runs.sort((a, b) => a.createdAt === b.createdAt ? b.runId.localeCompare(a.runId) : b.createdAt.localeCompare(a.createdAt));
@@ -4368,14 +4388,14 @@ async function loadRun(runId, env = process.env) {
4368
4388
  if (!RUN_ID_PATTERN.test(id)) {
4369
4389
  throw usageError(`"${runId}" is not a run id: run ids look like r_ab3dxk2q.`, { field: "runId", next: "kenso runs list" });
4370
4390
  }
4371
- let dir2;
4391
+ let dir3;
4372
4392
  try {
4373
- if (await checkRoot(runsRoot(env))) dir2 = await realpath(join5(runsRoot(env), id));
4393
+ if (await checkRoot(runsRoot(env))) dir3 = await realpath(join5(runsRoot(env), id));
4374
4394
  } catch (err) {
4375
4395
  if (err instanceof KensoError) throw err;
4376
- dir2 = void 0;
4396
+ dir3 = void 0;
4377
4397
  }
4378
- const run = dir2 ? await readRun(dir2) : null;
4398
+ const run = dir3 ? await readRun(dir3) : null;
4379
4399
  if (!run || run.runId !== id) {
4380
4400
  throw new KensoError({
4381
4401
  code: "run_not_found",
@@ -4424,30 +4444,30 @@ import { join as join6, resolve as resolve3 } from "node:path";
4424
4444
  async function prepareRunDir(outDir, runId, identical, ctx) {
4425
4445
  const root2 = runsRoot(ctx.env);
4426
4446
  if (outDir === void 0) {
4427
- const dir3 = join6(root2, runId);
4447
+ const dir4 = join6(root2, runId);
4428
4448
  ensurePrivateDir2(root2);
4429
- ensurePrivateDir2(dir3);
4430
- return dir3;
4449
+ ensurePrivateDir2(dir4);
4450
+ return dir4;
4431
4451
  }
4432
- const dir2 = resolve3(outDir);
4433
- const existing = existsSync3(join6(dir2, "run.json")) ? await readRunDir(dir2) : null;
4452
+ const dir3 = resolve3(outDir);
4453
+ const existing = existsSync3(join6(dir3, "run.json")) ? await readRunDir(dir3) : null;
4434
4454
  if (existing && !identical.some((run) => run.runId === existing.runId)) {
4435
- throw usageError(`${dir2} already holds run ${existing.runId} (${existing.command}).`, {
4455
+ throw usageError(`${dir3} already holds run ${existing.runId} (${existing.command}).`, {
4436
4456
  field: "out",
4437
4457
  hint: "Pick an empty --out directory, or leave --out off to keep the run under the runs directory."
4438
4458
  });
4439
4459
  }
4440
- ensurePrivateDir2(dir2);
4460
+ ensurePrivateDir2(dir3);
4441
4461
  for (const name of ["results.csv", "invalid.csv", "plan.json", "summary.json", "state.json"]) {
4442
- await unlink2(join6(dir2, name)).catch(() => void 0);
4462
+ await unlink2(join6(dir3, name)).catch(() => void 0);
4443
4463
  }
4444
4464
  try {
4445
4465
  ensurePrivateDir2(root2);
4446
- await symlink(dir2, join6(root2, runId), "junction");
4466
+ await symlink(dir3, join6(root2, runId), "junction");
4447
4467
  } catch (err) {
4448
- ctx.output.warn(`Could not link ${dir2} into ${root2} (${errorText(err)}): kenso runs will not list this run.`);
4468
+ ctx.output.warn(`Could not link ${dir3} into ${root2} (${errorText(err)}): kenso runs will not list this run.`);
4449
4469
  }
4450
- return dir2;
4470
+ return dir3;
4451
4471
  }
4452
4472
  async function allSucceeded(run, totalRows) {
4453
4473
  const previous = await readResults(filesOf(run.dir).resultsNdjson);
@@ -4484,14 +4504,14 @@ async function alreadyDone(run, totalRows, started, ctx) {
4484
4504
  }
4485
4505
  async function dryRun(spec, ctx, plan) {
4486
4506
  let runId;
4487
- let dir2;
4507
+ let dir3;
4488
4508
  const target2 = plan.finished ?? plan.resumable;
4489
4509
  if (target2) {
4490
4510
  runId = target2.runId;
4491
- dir2 = target2.dir;
4511
+ dir3 = target2.dir;
4492
4512
  } else {
4493
4513
  runId = newRunId();
4494
- dir2 = await prepareRunDir(spec.outDir, runId, plan.identical, ctx);
4514
+ dir3 = await prepareRunDir(spec.outDir, runId, plan.identical, ctx);
4495
4515
  const now = (/* @__PURE__ */ new Date()).toISOString();
4496
4516
  await writeRunRecord({
4497
4517
  runId,
@@ -4504,7 +4524,7 @@ async function dryRun(spec, ctx, plan) {
4504
4524
  status: "planned",
4505
4525
  chunkCount: plan.chunkCount,
4506
4526
  chunksDone: [],
4507
- dir: dir2,
4527
+ dir: dir3,
4508
4528
  rows: plan.totalRows,
4509
4529
  chunkSize: spec.chunkSize,
4510
4530
  itemsSha256: plan.itemsSha256,
@@ -4512,7 +4532,7 @@ async function dryRun(spec, ctx, plan) {
4512
4532
  updatedAt: now
4513
4533
  });
4514
4534
  }
4515
- const files = filesOf(dir2);
4535
+ const files = filesOf(dir3);
4516
4536
  const planBody = {
4517
4537
  dryRun: true,
4518
4538
  command: spec.command,
@@ -4539,7 +4559,7 @@ async function dryRun(spec, ctx, plan) {
4539
4559
  ctx.output.summary(summary);
4540
4560
  return {
4541
4561
  runId,
4542
- dir: dir2,
4562
+ dir: dir3,
4543
4563
  resultsCsv: files.resultsCsv,
4544
4564
  resultsNdjson: files.resultsNdjson,
4545
4565
  invalidCsv: plan.invalid.length > 0 ? files.invalidCsv : void 0,
@@ -4618,7 +4638,7 @@ async function runBatch(spec, ctx) {
4618
4638
  };
4619
4639
  } else {
4620
4640
  const runId = newRunId();
4621
- const dir2 = await prepareRunDir(spec.outDir, runId, identical, ctx);
4641
+ const dir3 = await prepareRunDir(spec.outDir, runId, identical, ctx);
4622
4642
  record3 = {
4623
4643
  runId,
4624
4644
  command: spec.command,
@@ -4630,7 +4650,7 @@ async function runBatch(spec, ctx) {
4630
4650
  status: "running",
4631
4651
  chunkCount,
4632
4652
  chunksDone: [],
4633
- dir: dir2,
4653
+ dir: dir3,
4634
4654
  rows: totalRows,
4635
4655
  chunkSize: spec.chunkSize,
4636
4656
  itemsSha256,
@@ -7615,9 +7635,9 @@ async function resolveGenerated(resource, action) {
7615
7635
  const { operationToCommand: operationToCommand2 } = await Promise.resolve().then(() => (init_execute(), execute_exports));
7616
7636
  return operationToCommand2(op);
7617
7637
  }
7618
- async function featuresFromEnv(env, flags = {}, overrides = {}) {
7638
+ async function featuresFromEnv(env, flags = {}, overrides2 = {}) {
7619
7639
  try {
7620
- const ctx = createContext(flags, env, { ...overrides, stdout: DISCARD, stderr: DISCARD });
7640
+ const ctx = createContext(flags, env, { ...overrides2, stdout: DISCARD, stderr: DISCARD });
7621
7641
  return await loadWorkspaceFeatures(ctx, { timeoutMs: HELP_FEATURES_TIMEOUT_MS });
7622
7642
  } catch {
7623
7643
  return { features: [] };
@@ -7637,6 +7657,7 @@ async function listGenerated(opts = {}) {
7637
7657
  resource: op.resource,
7638
7658
  action: op.action,
7639
7659
  summary: op.summary ?? `${op.method} ${op.path}`,
7660
+ effect: op.effect ?? "write",
7640
7661
  beta: !gateSatisfied(op.featureGates, features),
7641
7662
  ...op.featureGates ? { featureGates: op.featureGates } : {}
7642
7663
  }));
@@ -7655,6 +7676,187 @@ var init_generated_hook = __esm({
7655
7676
  }
7656
7677
  });
7657
7678
 
7679
+ // src/manifest/data.ts
7680
+ import { readFileSync as readFileSync6 } from "node:fs";
7681
+ function readDataFile(name) {
7682
+ if (overrides.has(name)) return overrides.get(name);
7683
+ if (!cache.has(name)) {
7684
+ let value;
7685
+ try {
7686
+ value = JSON.parse(readFileSync6(new URL(name, dir2), "utf8"));
7687
+ } catch {
7688
+ value = void 0;
7689
+ }
7690
+ cache.set(name, value);
7691
+ }
7692
+ return cache.get(name);
7693
+ }
7694
+ var dir2, cache, overrides;
7695
+ var init_data = __esm({
7696
+ "src/manifest/data.ts"() {
7697
+ "use strict";
7698
+ dir2 = new URL("./", import.meta.url);
7699
+ cache = /* @__PURE__ */ new Map();
7700
+ overrides = /* @__PURE__ */ new Map();
7701
+ }
7702
+ });
7703
+
7704
+ // src/core/rate-card.ts
7705
+ import { readFileSync as readFileSync7, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
7706
+ import { join as join8 } from "node:path";
7707
+ import { Writable as Writable2 } from "node:stream";
7708
+ function cleanItems(value) {
7709
+ if (!Array.isArray(value)) return [];
7710
+ const out = [];
7711
+ for (const raw of value) {
7712
+ if (raw === null || typeof raw !== "object" || typeof raw.action !== "string") continue;
7713
+ const item = {};
7714
+ for (const key of ITEM_KEYS) {
7715
+ const field = raw[key];
7716
+ if (typeof field === "string" || typeof field === "number") item[key] = field;
7717
+ }
7718
+ out.push(item);
7719
+ }
7720
+ return out;
7721
+ }
7722
+ function bundledCards() {
7723
+ const data = readDataFile(DATA_FILE);
7724
+ const cards = [];
7725
+ for (const card of Array.isArray(data?.cards) ? data.cards : []) {
7726
+ if (typeof card.version === "number") cards.push({ version: card.version, source: "bundled", items: cleanItems(card.items) });
7727
+ }
7728
+ return cards;
7729
+ }
7730
+ function readCache2(file) {
7731
+ try {
7732
+ const parsed2 = JSON.parse(readFileSync7(file, "utf8"));
7733
+ return parsed2 !== null && typeof parsed2 === "object" && !Array.isArray(parsed2) ? parsed2 : {};
7734
+ } catch {
7735
+ return {};
7736
+ }
7737
+ }
7738
+ function isFresh2(entry, now) {
7739
+ if (!entry || typeof entry.version !== "number" || !Array.isArray(entry.items)) return false;
7740
+ const at = Date.parse(entry.fetchedAt);
7741
+ return Number.isFinite(at) && now - at >= 0 && now - at < TTL_MS2;
7742
+ }
7743
+ function writeCache(file, cache2, key, entry, now) {
7744
+ try {
7745
+ const kept = {};
7746
+ for (const [k, old] of Object.entries(cache2)) if (isFresh2(old, now)) kept[k] = old;
7747
+ kept[key] = entry;
7748
+ const temp = `${file}.${process.pid}.tmp`;
7749
+ writeFileSync3(temp, `${JSON.stringify(kept)}
7750
+ `, { mode: 384 });
7751
+ renameSync3(temp, file);
7752
+ } catch {
7753
+ }
7754
+ }
7755
+ async function loadRateCards(ctx, opts = {}) {
7756
+ const key = featureCacheKey(ctx.auth);
7757
+ if (!key) return bundledCards();
7758
+ const now = Date.now();
7759
+ let file;
7760
+ let cache2 = {};
7761
+ try {
7762
+ file = join8(cacheDir(ctx.env), CACHE_FILE2);
7763
+ cache2 = readCache2(file);
7764
+ } catch {
7765
+ file = void 0;
7766
+ }
7767
+ const entry = cache2[key];
7768
+ const hit = isFresh2(entry, now) ? entry : void 0;
7769
+ const offline = () => hit ? [{ version: hit.version, source: "cache", items: cleanItems(hit.items) }] : bundledCards();
7770
+ if (opts.live === false || opts.live === void 0 && hit) return offline();
7771
+ try {
7772
+ const signal = AbortSignal.any([ctx.signal, AbortSignal.timeout(opts.timeoutMs ?? FETCH_TIMEOUT_MS2)]);
7773
+ const res = await ctx.client.request({ method: "GET", path: "/v1/credits/rate-card", signal });
7774
+ const card = unwrap(res.body);
7775
+ if (!card || typeof card.version !== "number") return offline();
7776
+ const items = cleanItems(card.items);
7777
+ if (file) writeCache(file, cache2, key, { version: card.version, items, fetchedAt: new Date(now).toISOString() }, now);
7778
+ return [{ version: card.version, source: "live", items }];
7779
+ } catch {
7780
+ return offline();
7781
+ }
7782
+ }
7783
+ async function rateCardsForHelp(env, flags = {}, overrides2 = {}) {
7784
+ try {
7785
+ const ctx = createContext(flags, env, { ...overrides2, stdout: DISCARD2, stderr: DISCARD2 });
7786
+ return await loadRateCards(ctx, { timeoutMs: HELP_RATE_CARD_TIMEOUT_MS });
7787
+ } catch {
7788
+ return bundledCards();
7789
+ }
7790
+ }
7791
+ function credits(millicredits) {
7792
+ return String(Number((millicredits / 1e3).toFixed(3)));
7793
+ }
7794
+ function unitPrice(item, line) {
7795
+ if ((item.millicreditsPerUnit ?? 0) === 0) {
7796
+ const note = (item.note ?? "").replace(/^not charged in credits\.?\s*/i, "").replace(/\.$/, "");
7797
+ return `not charged in credits${note ? ` (${note})` : ""}`;
7798
+ }
7799
+ const amount = credits(item.millicreditsPerUnit ?? 0);
7800
+ const billing = item.billing ?? line.billing;
7801
+ const period = billing === "monthly" ? " per month" : billing === "yearly" ? " per year" : "";
7802
+ return `${amount} ${amount === "1" ? "credit" : "credits"} per ${item.unit ?? line.unit ?? "unit"}${period}`;
7803
+ }
7804
+ function priceLine(line, cards) {
7805
+ if (line.pricing === "varies") return `${line.action}: price depends on the work; --dry-run prints the estimate where the command has one`;
7806
+ const priced = [];
7807
+ for (const card of cards) {
7808
+ const item = card.items.find((candidate) => candidate.action === line.action && (candidate.pricing ?? "fixed") === "fixed");
7809
+ if (item) priced.push({ card, item });
7810
+ }
7811
+ if (priced.length === 0) return `${line.action}: charged, not on the rate card (${RATE_CARD_COMMAND})`;
7812
+ const named = cards.length > 1;
7813
+ return `${line.action}: ${priced.map(({ card, item }) => `${unitPrice(item, line)}${named ? ` (rate card v${card.version})` : ""}`).join(", ")}`;
7814
+ }
7815
+ var CACHE_FILE2, DATA_FILE, TTL_MS2, FETCH_TIMEOUT_MS2, ITEM_KEYS, HELP_RATE_CARD_TIMEOUT_MS, RATE_CARD_COMMAND, DISCARD2;
7816
+ var init_rate_card = __esm({
7817
+ "src/core/rate-card.ts"() {
7818
+ "use strict";
7819
+ init_data();
7820
+ init_config();
7821
+ init_context();
7822
+ init_features();
7823
+ init_http();
7824
+ CACHE_FILE2 = "rate-card.json";
7825
+ DATA_FILE = "pricing.json";
7826
+ TTL_MS2 = 24 * 60 * 60 * 1e3;
7827
+ FETCH_TIMEOUT_MS2 = 5e3;
7828
+ ITEM_KEYS = ["action", "unit", "unitSize", "millicreditsPerUnit", "billing", "pricing", "note"];
7829
+ HELP_RATE_CARD_TIMEOUT_MS = 1500;
7830
+ RATE_CARD_COMMAND = "kenso credit-rate-card get";
7831
+ DISCARD2 = new Writable2({
7832
+ write(_chunk, _encoding, callback) {
7833
+ callback();
7834
+ }
7835
+ });
7836
+ }
7837
+ });
7838
+
7839
+ // src/commands/help-effect.ts
7840
+ function effectAndCost(spec, rateCards) {
7841
+ const lines = [`Effect: ${spec.effect ?? "write"}.`];
7842
+ if (spec.cost && spec.cost.length > 0) {
7843
+ const cards = rateCards ?? bundledCards();
7844
+ lines.push(`Cost: ${spec.cost.map((line) => priceLine(line, cards)).join("; ")}.`);
7845
+ } else if (spec.doc?.cost) {
7846
+ lines.push(`Cost: ${spec.doc.cost}`);
7847
+ }
7848
+ return lines;
7849
+ }
7850
+ function effectMark(effect) {
7851
+ return (effect ?? "write") === "read" ? "" : ` (${effect ?? "write"})`;
7852
+ }
7853
+ var init_help_effect = __esm({
7854
+ "src/commands/help-effect.ts"() {
7855
+ "use strict";
7856
+ init_rate_card();
7857
+ }
7858
+ });
7859
+
7658
7860
  // src/commands/people/columns.ts
7659
7861
  function normalizeHeader(header) {
7660
7862
  return header.toLowerCase().replace(/[^a-z0-9]/g, "");
@@ -8558,7 +8760,7 @@ var init_merge = __esm({
8558
8760
 
8559
8761
  // src/commands/work/common.ts
8560
8762
  import { randomUUID } from "node:crypto";
8561
- import { join as join8 } from "node:path";
8763
+ import { join as join9 } from "node:path";
8562
8764
  import { setTimeout as delay4 } from "node:timers/promises";
8563
8765
  function unavailable(err) {
8564
8766
  return err instanceof KensoError && (err.code === "network_error" || err.httpStatus === 502 || err.httpStatus === 503 || err.httpStatus === 504);
@@ -8632,8 +8834,8 @@ function leaseMinutes(flags) {
8632
8834
  function shellQuote5(value) {
8633
8835
  return /^[A-Za-z0-9_\-.,:/@=+%]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
8634
8836
  }
8635
- function submitCommand(dir2) {
8636
- return `kenso work submit ${shellQuote5(join8(dir2, "/"))}*.answers.json`;
8837
+ function submitCommand(dir3) {
8838
+ return `kenso work submit ${shellQuote5(join9(dir3, "/"))}*.answers.json`;
8637
8839
  }
8638
8840
  function explainNotFound(err) {
8639
8841
  if (!(err instanceof KensoError) || err.httpStatus !== 404 || err.hint !== void 0) return err;
@@ -8761,6 +8963,7 @@ var init_duplicates = __esm({
8761
8963
  action: "duplicates",
8762
8964
  summary: "List the account pairs that look like duplicates. --scan looks for new pairs first",
8763
8965
  effect: "write",
8966
+ effectFor: ({ flags }) => flags.scan === true ? "write" : "read",
8764
8967
  description: "Reads GET /v1/account-duplicates: each pair with both accounts (account and otherAccount: name, domain, stage, owner, last touch), why they were paired (reasons: domain, linkedin, name) and isCertain (same domain and same name, the pairs Ken merges itself where that is on; heldReason says why Ken left one). --status picks open (the default), dismissed or merged. --scan sends POST /v1/account-duplicates/scan first, which compares every account of the workspace and needs a plan with accounts. Merge a pair with `kenso accounts merge <accountId> --into <id>`, or answer that it is not a duplicate with `kenso account-duplicates dismiss --duplicate-id <duplicateId>`.",
8765
8968
  flags: {
8766
8969
  status: { type: "string", description: "open (default), dismissed or merged" },
@@ -9045,10 +9248,10 @@ var init_embedded = __esm({
9045
9248
  });
9046
9249
 
9047
9250
  // src/commands/docs/content.ts
9048
- import { readFileSync as readFileSync6 } from "node:fs";
9251
+ import { readFileSync as readFileSync8 } from "node:fs";
9049
9252
  function readOptional(url) {
9050
9253
  try {
9051
- return readFileSync6(url, "utf8");
9254
+ return readFileSync8(url, "utf8");
9052
9255
  } catch {
9053
9256
  return void 0;
9054
9257
  }
@@ -9059,7 +9262,7 @@ async function topicText(topic) {
9059
9262
  }
9060
9263
  async function skillText() {
9061
9264
  if (!fromSource) return (await Promise.resolve().then(() => (init_embedded(), embedded_exports))).SKILL;
9062
- return readFileSync6(new URL("skill/kenso-cli/SKILL.md", root), "utf8");
9265
+ return readFileSync8(new URL("skill/kenso-cli/SKILL.md", root), "utf8");
9063
9266
  }
9064
9267
  var TOPICS, fromSource, root;
9065
9268
  var init_content = __esm({
@@ -9268,28 +9471,28 @@ var init_client = __esm({
9268
9471
 
9269
9472
  // src/commands/skill/clients.ts
9270
9473
  import { homedir as homedir2 } from "node:os";
9271
- import { join as join9 } from "node:path";
9474
+ import { join as join10 } from "node:path";
9272
9475
  function home(env) {
9273
9476
  return env.HOME?.trim() || env.USERPROFILE?.trim() || homedir2();
9274
9477
  }
9275
9478
  function claudeDir(env) {
9276
- return env.CLAUDE_CONFIG_DIR?.trim() || join9(home(env), ".claude");
9479
+ return env.CLAUDE_CONFIG_DIR?.trim() || join10(home(env), ".claude");
9277
9480
  }
9278
9481
  function xdgConfigDir(env) {
9279
- return env.XDG_CONFIG_HOME?.trim() || join9(home(env), ".config");
9482
+ return env.XDG_CONFIG_HOME?.trim() || join10(home(env), ".config");
9280
9483
  }
9281
9484
  function skillsFolder(client, env) {
9282
9485
  switch (client) {
9283
9486
  case "claude-code":
9284
- return join9(claudeDir(env), "skills");
9487
+ return join10(claudeDir(env), "skills");
9285
9488
  case "codex":
9286
- return join9(home(env), ".agents", "skills");
9489
+ return join10(home(env), ".agents", "skills");
9287
9490
  case "cursor":
9288
- return join9(home(env), ".cursor", "skills");
9491
+ return join10(home(env), ".cursor", "skills");
9289
9492
  case "gemini":
9290
- return join9(home(env), ".gemini", "skills");
9493
+ return join10(home(env), ".gemini", "skills");
9291
9494
  case "opencode":
9292
- return join9(xdgConfigDir(env), "opencode", "skills");
9495
+ return join10(xdgConfigDir(env), "opencode", "skills");
9293
9496
  }
9294
9497
  }
9295
9498
  var CLIENTS, CLIENT_CHOICES, CLIENT_NAMES, AGENT_CLIENTS;
@@ -9319,15 +9522,15 @@ __export(install_exports, {
9319
9522
  readExisting: () => readExisting,
9320
9523
  write: () => write
9321
9524
  });
9322
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync7, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
9323
- import { basename as basename2, dirname, join as join10, resolve as resolve6 } from "node:path";
9525
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync9, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
9526
+ import { basename as basename2, dirname, join as join11, resolve as resolve6 } from "node:path";
9324
9527
  function quote(value) {
9325
9528
  return /^[A-Za-z0-9_\-.,:/@=+%~]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
9326
9529
  }
9327
9530
  function readExisting(path) {
9328
9531
  if (!existsSync4(path)) return void 0;
9329
9532
  try {
9330
- return readFileSync7(path, "utf8");
9533
+ return readFileSync9(path, "utf8");
9331
9534
  } catch (err) {
9332
9535
  const code = err.code;
9333
9536
  throw new KensoError({ code: "file_unreadable", message: `Cannot read ${path}${code ? ` (${code})` : ""}.`, exitCode: ExitCode.Usage });
@@ -9337,17 +9540,17 @@ function write(path, text4) {
9337
9540
  try {
9338
9541
  mkdirSync3(dirname(path), { recursive: true });
9339
9542
  const temp = `${path}.${process.pid}.tmp`;
9340
- writeFileSync3(temp, text4);
9341
- renameSync3(temp, path);
9543
+ writeFileSync4(temp, text4);
9544
+ renameSync4(temp, path);
9342
9545
  } catch (err) {
9343
9546
  const code = err.code;
9344
9547
  throw new KensoError({ code: "file_unwritable", message: `Cannot write ${path}${code ? ` (${code})` : ""}.`, exitCode: ExitCode.Error });
9345
9548
  }
9346
9549
  }
9347
- function folders(ctx, client, dir2) {
9348
- if (dir2 !== void 0) return [{ client, folder: resolve6(dir2) }];
9550
+ function folders(ctx, client, dir3) {
9551
+ if (dir3 !== void 0) return [{ client, folder: resolve6(dir3) }];
9349
9552
  const clients = client === "all" ? CLIENTS : [client];
9350
- return clients.map((c) => ({ client: c, folder: join10(skillsFolder(c, ctx.env), SKILL_NAME) }));
9553
+ return clients.map((c) => ({ client: c, folder: join11(skillsFolder(c, ctx.env), SKILL_NAME) }));
9351
9554
  }
9352
9555
  function installCommand(opts) {
9353
9556
  const parts2 = ["kenso skill install"];
@@ -9382,21 +9585,21 @@ var init_install = __esm({
9382
9585
  dryRun: true,
9383
9586
  async run(ctx, { flags }) {
9384
9587
  const clientFlag = typeof flags.client === "string" ? flags.client.trim() : void 0;
9385
- const dir2 = typeof flags.dir === "string" && flags.dir.trim() !== "" ? flags.dir : void 0;
9588
+ const dir3 = typeof flags.dir === "string" && flags.dir.trim() !== "" ? flags.dir : void 0;
9386
9589
  if (clientFlag !== void 0 && !CLIENT_CHOICES.includes(clientFlag)) {
9387
9590
  throw usageError(`--client must be one of ${CLIENT_CHOICES.join(", ")} (got "${clientFlag}").`, { field: "client", next: "kenso skill install --help" });
9388
9591
  }
9389
9592
  const client = clientFlag ?? (ctx.agent ? AGENT_CLIENTS2[ctx.agent.name] : void 0) ?? "all";
9390
9593
  const text4 = await skillText();
9391
- const targets = folders(ctx, client, dir2).map(({ client: c, folder }) => {
9392
- const path = join10(folder, "SKILL.md");
9594
+ const targets = folders(ctx, client, dir3).map(({ client: c, folder }) => {
9595
+ const path = join11(folder, "SKILL.md");
9393
9596
  const existing = readExisting(path);
9394
9597
  const status = existing === void 0 ? "created" : existing === text4 ? "unchanged" : "replaced";
9395
9598
  return { client: c, path, status };
9396
9599
  });
9397
9600
  const conflicts = targets.filter((t) => t.status === "replaced");
9398
9601
  const needsForce = conflicts.length > 0 || flags.force === true;
9399
- const next = installCommand({ client: dir2 === void 0 ? client : clientFlag, dir: dir2, force: needsForce });
9602
+ const next = installCommand({ client: dir3 === void 0 ? client : clientFlag, dir: dir3, force: needsForce });
9400
9603
  if (ctx.flags.dryRun) {
9401
9604
  ctx.output.object({ dryRun: true, installed: targets, next });
9402
9605
  return ExitCode.Ok;
@@ -9414,8 +9617,8 @@ var init_install = __esm({
9414
9617
  for (const target2 of targets) {
9415
9618
  if (target2.status !== "unchanged") write(target2.path, text4);
9416
9619
  }
9417
- if (dir2 !== void 0 && basename2(resolve6(dir2)) !== SKILL_NAME) {
9418
- ctx.output.warn(`Agents expect the skill's folder to be named ${SKILL_NAME}, like the skill: ${resolve6(dir2)} is not.`);
9620
+ if (dir3 !== void 0 && basename2(resolve6(dir3)) !== SKILL_NAME) {
9621
+ ctx.output.warn(`Agents expect the skill's folder to be named ${SKILL_NAME}, like the skill: ${resolve6(dir3)} is not.`);
9419
9622
  }
9420
9623
  ctx.output.object({ installed: targets });
9421
9624
  return ExitCode.Ok;
@@ -9427,8 +9630,8 @@ var init_install = __esm({
9427
9630
 
9428
9631
  // src/commands/agent/mcp-config.ts
9429
9632
  import { spawnSync } from "node:child_process";
9430
- import { existsSync as existsSync5, readFileSync as readFileSync8 } from "node:fs";
9431
- import { delimiter, join as join11 } from "node:path";
9633
+ import { existsSync as existsSync5, readFileSync as readFileSync10 } from "node:fs";
9634
+ import { delimiter, join as join12 } from "node:path";
9432
9635
  function parse2(text4) {
9433
9636
  try {
9434
9637
  const doc = JSON.parse(text4);
@@ -9485,9 +9688,9 @@ function tomlServers(text4) {
9485
9688
  return entries2;
9486
9689
  }
9487
9690
  function opencodeFile(env) {
9488
- const dir2 = join11(xdgConfigDir(env), "opencode");
9489
- const existing = ["opencode.jsonc", "opencode.json", "config.json"].map((f) => join11(dir2, f)).find((f) => existsSync5(f));
9490
- return existing ?? join11(dir2, "opencode.json");
9691
+ const dir3 = join12(xdgConfigDir(env), "opencode");
9692
+ const existing = ["opencode.jsonc", "opencode.json", "config.json"].map((f) => join12(dir3, f)).find((f) => existsSync5(f));
9693
+ return existing ?? join12(dir3, "opencode.json");
9491
9694
  }
9492
9695
  function canonical(url) {
9493
9696
  try {
@@ -9499,7 +9702,7 @@ function canonical(url) {
9499
9702
  }
9500
9703
  function onPath(bin, env) {
9501
9704
  const names = process.platform === "win32" ? [`${bin}.cmd`, `${bin}.exe`, bin] : [bin];
9502
- return (env.PATH ?? env.Path ?? "").split(delimiter).some((dir2) => dir2 !== "" && names.some((n) => existsSync5(join11(dir2, n))));
9705
+ return (env.PATH ?? env.Path ?? "").split(delimiter).some((dir3) => dir3 !== "" && names.some((n) => existsSync5(join12(dir3, n))));
9503
9706
  }
9504
9707
  function isPresent(client, env) {
9505
9708
  const t = TARGETS[client];
@@ -9507,7 +9710,7 @@ function isPresent(client, env) {
9507
9710
  }
9508
9711
  function readText2(path) {
9509
9712
  try {
9510
- return readFileSync8(path, "utf8");
9713
+ return readFileSync10(path, "utf8");
9511
9714
  } catch {
9512
9715
  return void 0;
9513
9716
  }
@@ -9576,7 +9779,7 @@ var init_mcp_config = __esm({
9576
9779
  "claude-code": {
9577
9780
  bins: ["claude"],
9578
9781
  folder: claudeDir,
9579
- file: (env) => env.CLAUDE_CONFIG_DIR?.trim() ? join11(env.CLAUDE_CONFIG_DIR.trim(), ".claude.json") : join11(home(env), ".claude.json"),
9782
+ file: (env) => env.CLAUDE_CONFIG_DIR?.trim() ? join12(env.CLAUDE_CONFIG_DIR.trim(), ".claude.json") : join12(home(env), ".claude.json"),
9580
9783
  // User scope only: that is where setup adds it, and it reaches every project.
9581
9784
  entries: (text4) => mcpServersOf(text4),
9582
9785
  command: (url) => ["claude", "mcp", "add", "--scope", "user", "--transport", "http", SERVER_NAME, url],
@@ -9584,16 +9787,16 @@ var init_mcp_config = __esm({
9584
9787
  },
9585
9788
  codex: {
9586
9789
  bins: ["codex"],
9587
- folder: (env) => env.CODEX_HOME?.trim() || join11(home(env), ".codex"),
9588
- file: (env) => join11(env.CODEX_HOME?.trim() || join11(home(env), ".codex"), "config.toml"),
9790
+ folder: (env) => env.CODEX_HOME?.trim() || join12(home(env), ".codex"),
9791
+ file: (env) => join12(env.CODEX_HOME?.trim() || join12(home(env), ".codex"), "config.toml"),
9589
9792
  entries: tomlServers,
9590
9793
  command: (url) => ["codex", "mcp", "add", SERVER_NAME, "--url", url],
9591
9794
  signIn: "Run codex mcp login kenso."
9592
9795
  },
9593
9796
  cursor: {
9594
9797
  bins: ["cursor", "cursor-agent"],
9595
- folder: (env) => join11(home(env), ".cursor"),
9596
- file: (env) => join11(home(env), ".cursor", "mcp.json"),
9798
+ folder: (env) => join12(home(env), ".cursor"),
9799
+ file: (env) => join12(home(env), ".cursor", "mcp.json"),
9597
9800
  entries: (text4) => mcpServersOf(text4),
9598
9801
  merge: (doc, url) => {
9599
9802
  const all = isDoc(doc.mcpServers) ? doc.mcpServers : doc.mcpServers = {};
@@ -9603,8 +9806,8 @@ var init_mcp_config = __esm({
9603
9806
  },
9604
9807
  gemini: {
9605
9808
  bins: ["gemini"],
9606
- folder: (env) => join11(home(env), ".gemini"),
9607
- file: (env) => join11(home(env), ".gemini", "settings.json"),
9809
+ folder: (env) => join12(home(env), ".gemini"),
9810
+ file: (env) => join12(home(env), ".gemini", "settings.json"),
9608
9811
  // httpUrl is Gemini CLI's Streamable HTTP key; url is SSE.
9609
9812
  entries: (text4) => mcpServersOf(text4, ["httpUrl", "url"]),
9610
9813
  command: (url) => ["gemini", "mcp", "add", "--scope", "user", "--transport", "http", SERVER_NAME, url],
@@ -9612,7 +9815,7 @@ var init_mcp_config = __esm({
9612
9815
  },
9613
9816
  opencode: {
9614
9817
  bins: ["opencode"],
9615
- folder: (env) => join11(xdgConfigDir(env), "opencode"),
9818
+ folder: (env) => join12(xdgConfigDir(env), "opencode"),
9616
9819
  file: opencodeFile,
9617
9820
  // OpenCode 1.x lists servers under mcp; newer configs nest them under mcp.servers.
9618
9821
  entries: (text4) => {
@@ -9636,7 +9839,7 @@ var setup_exports = {};
9636
9839
  __export(setup_exports, {
9637
9840
  default: () => setup_default
9638
9841
  });
9639
- import { join as join12 } from "node:path";
9842
+ import { join as join13 } from "node:path";
9640
9843
  function quote2(value) {
9641
9844
  return /^[A-Za-z0-9_\-.,:/@=+%~]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
9642
9845
  }
@@ -9697,7 +9900,7 @@ var init_setup = __esm({
9697
9900
  const clients = pickClients(ctx, clientFlag, status);
9698
9901
  const text4 = await skillText();
9699
9902
  const rows = clients.map((client) => {
9700
- const path = join12(skillsFolder(client, ctx.env), SKILL_NAME, "SKILL.md");
9903
+ const path = join13(skillsFolder(client, ctx.env), SKILL_NAME, "SKILL.md");
9701
9904
  const existing = readExisting(path);
9702
9905
  const skill = existing === void 0 ? "missing" : existing === text4 ? "installed" : "different";
9703
9906
  return { client, present: isPresent(client, ctx.env), skill: { path, status: skill }, mcp: mcpState(client, ctx.env, url) };
@@ -9805,6 +10008,7 @@ var init_api3 = __esm({
9805
10008
  init_exit_codes();
9806
10009
  init_input();
9807
10010
  init_transfer();
10011
+ init_manifest();
9808
10012
  METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
9809
10013
  DEFAULT_FILE_FIELD = "file";
9810
10014
  command8 = {
@@ -9813,6 +10017,14 @@ var init_api3 = __esm({
9813
10017
  summary: "Call any API route, only when no command fits",
9814
10018
  brief: "only when no command fits",
9815
10019
  effect: "destructive",
10020
+ // The effect of the route the call reaches (a GET that charges is a spend); a route the manifest does not know
10021
+ // goes by its method.
10022
+ effectFor({ positionals }) {
10023
+ const method = (positionals[0] ?? "").toUpperCase();
10024
+ const raw = positionals[1] ?? "";
10025
+ const path = URL.canParse(raw, "http://kenso.invalid") ? new URL(raw, "http://kenso.invalid").pathname : raw;
10026
+ return routeEffect(method, path) ?? (method === "GET" ? "read" : method === "DELETE" ? "destructive" : "write");
10027
+ },
9816
10028
  description: "The raw escape hatch: sends Authorization, Ken-Version: 1.1 and X-Ken-Workspace-Id, prints the full JSON body. It reaches the legacy routes that have no command. The path may carry a query string. --all (GET only) follows pagination.nextCursor and prints the data[] items as a list. --file sends a multipart upload. An answer that is not JSON (a CSV, an image, a ZIP) prints as it came; --out saves it byte for byte, and a binary one is never printed to a terminal. POST, PUT and PATCH send at once; DELETE needs --yes (on a terminal it asks). --dry-run prints the request (method, path, body) and sends nothing.",
9817
10029
  flags: {
9818
10030
  data: { type: "string", description: "Request body: inline JSON, @file or - for stdin. With --file, its keys are form fields" },
@@ -9998,8 +10210,8 @@ async function wait(ms, ctx, deps) {
9998
10210
  }
9999
10211
  if (ctx.signal.aborted) throw interrupted4();
10000
10212
  }
10001
- async function browserLogin(ctx, opts, overrides) {
10002
- const deps = { ...defaultDeps, ...overrides };
10213
+ async function browserLogin(ctx, opts, overrides2) {
10214
+ const deps = { ...defaultDeps, ...overrides2 };
10003
10215
  let started;
10004
10216
  try {
10005
10217
  const res = await ctx.client.request({
@@ -11360,8 +11572,8 @@ function announce(ctx, kind, flags, link, answer, waiting, limitMs, deps) {
11360
11572
  }
11361
11573
  if (link && !ctx.agent && flags["no-browser"] !== true && hasDisplay(ctx.env, deps.platform)) openBrowser(link, deps);
11362
11574
  }
11363
- async function runConnect(ctx, kind, flags, overrides) {
11364
- const deps = { ...defaultDeps2, ...overrides };
11575
+ async function runConnect(ctx, kind, flags, overrides2) {
11576
+ const deps = { ...defaultDeps2, ...overrides2 };
11365
11577
  const limitMs = timeoutMs(flags);
11366
11578
  kind.manual?.check(flags);
11367
11579
  const start = kind.start?.(flags);
@@ -11457,7 +11669,7 @@ var init_run = __esm({
11457
11669
  "no-wait": { type: "boolean", description: "Print the link as JSON and end, without waiting for the connection" },
11458
11670
  "no-browser": { type: "boolean", description: "Print the link only; never open a browser" }
11459
11671
  };
11460
- KIND_EFFECTS = { linkedin: "spend", whatsapp: "spend", video: "read", github: "read" };
11672
+ KIND_EFFECTS = { linkedin: "spend", whatsapp: "spend", facebook: "spend", video: "read", github: "read" };
11461
11673
  }
11462
11674
  });
11463
11675
 
@@ -11499,10 +11711,10 @@ async function ask(ctx, path, body2, read2) {
11499
11711
  }
11500
11712
  async function creditEstimate(ctx, body2) {
11501
11713
  return ask(ctx, "/v1/credits/estimates", body2, (data) => {
11502
- const credits = (key) => typeof data[key] === "number" ? data[key] / 1e3 : null;
11714
+ const credits2 = (key) => typeof data[key] === "number" ? data[key] / 1e3 : null;
11503
11715
  return {
11504
- needed: credits("totalMillicredits"),
11505
- available: credits("availableMillicredits"),
11716
+ needed: credits2("totalMillicredits"),
11717
+ available: credits2("availableMillicredits"),
11506
11718
  sufficient: typeof data.sufficient === "boolean" ? data.sufficient : null
11507
11719
  };
11508
11720
  });
@@ -11687,14 +11899,14 @@ function overrideTarget(column, value, mode) {
11687
11899
  }
11688
11900
  return { field };
11689
11901
  }
11690
- function overrideFor(header, overrides) {
11691
- if (Object.hasOwn(overrides, header)) return { found: true, value: overrides[header] ?? null };
11902
+ function overrideFor(header, overrides2) {
11903
+ if (Object.hasOwn(overrides2, header)) return { found: true, value: overrides2[header] ?? null };
11692
11904
  const wanted = header.trim().toLowerCase();
11693
- for (const [key, value] of Object.entries(overrides)) if (key.trim().toLowerCase() === wanted) return { found: true, value };
11905
+ for (const [key, value] of Object.entries(overrides2)) if (key.trim().toLowerCase() === wanted) return { found: true, value };
11694
11906
  return { found: false, value: null };
11695
11907
  }
11696
- function buildMapping(headers, overrides, mode) {
11697
- const unknown2 = Object.keys(overrides).filter((key) => !headers.some((h) => h === key || h.trim().toLowerCase() === key.trim().toLowerCase()));
11908
+ function buildMapping(headers, overrides2, mode) {
11909
+ const unknown2 = Object.keys(overrides2).filter((key) => !headers.some((h) => h === key || h.trim().toLowerCase() === key.trim().toLowerCase()));
11698
11910
  if (unknown2.length > 0) {
11699
11911
  throw usageError(`--map names column${unknown2.length === 1 ? "" : "s"} ${unknown2.map((k) => `"${k}"`).join(", ")} that the file does not have.`, {
11700
11912
  field: "map",
@@ -11707,7 +11919,7 @@ function buildMapping(headers, overrides, mode) {
11707
11919
  result.dropped[header] = reason;
11708
11920
  };
11709
11921
  for (const header of headers) {
11710
- const override2 = overrideFor(header, overrides);
11922
+ const override2 = overrideFor(header, overrides2);
11711
11923
  let target2;
11712
11924
  if (override2.found) {
11713
11925
  if (override2.value === null) {
@@ -12195,20 +12407,20 @@ var init_import2 = __esm({
12195
12407
  }
12196
12408
  const campaignId = idFlag(flags, "campaign", COMMAND2);
12197
12409
  const file = requireFlag(flags, "file", COMMAND2, "Pass a CSV or JSONL file, or - for stdin. kenso contacts import --template shows the columns.");
12198
- const overrides = await readOverrides(ctx, flags, file);
12410
+ const overrides2 = await readOverrides(ctx, flags, file);
12199
12411
  const dryRun2 = isDryRun(ctx);
12200
12412
  const applyCommand = sameCommand2(COMMAND2, flags, ctx, ["--yes"]);
12201
12413
  if (flags["server-import"] === true) {
12202
12414
  let mapping2;
12203
- if (overrides) {
12415
+ if (overrides2) {
12204
12416
  const head = await readInput(file, { stdin: ctx.stdin });
12205
- mapping2 = buildMapping(head.headers, overrides, "import");
12417
+ mapping2 = buildMapping(head.headers, overrides2, "import");
12206
12418
  warnDropped(ctx, { ...mapping2, dropped: notUploaded(mapping2) });
12207
12419
  }
12208
12420
  return serverImport(ctx, { campaignId, file, mapping: mapping2, timeout: stringFlag2(flags, "timeout"), dryRun: dryRun2, applyCommand });
12209
12421
  }
12210
12422
  const input = await readInput(file, { stdin: ctx.stdin });
12211
- const mapping = buildMapping(flattenCustomVariables(input.headers, input.rows), overrides ?? {}, "import");
12423
+ const mapping = buildMapping(flattenCustomVariables(input.headers, input.rows), overrides2 ?? {}, "import");
12212
12424
  warnDropped(ctx, mapping);
12213
12425
  const { linkedInOnly } = await readCampaign(ctx, campaignId);
12214
12426
  if (input.rows.length > 0 && !mapping.fields.has("email") && !(linkedInOnly !== false && mapping.fields.has("linkedInUrl"))) {
@@ -12404,9 +12616,9 @@ var init_update = __esm({
12404
12616
  const campaignId = match === "email" ? idFlag(flags, "campaign", `${COMMAND3} --match email`) : void 0;
12405
12617
  const map = stringFlag2(flags, "map");
12406
12618
  if (map === "-" && file === "-") throw usageError("--map and --file cannot both read stdin.", { field: "map" });
12407
- const overrides = map === void 0 ? {} : parseMapOverrides(await readDataArg(map, ctx.stdin));
12619
+ const overrides2 = map === void 0 ? {} : parseMapOverrides(await readDataArg(map, ctx.stdin));
12408
12620
  const input = await readInput(file, { stdin: ctx.stdin });
12409
- const mapping = buildMapping(flattenCustomVariables(input.headers, input.rows), overrides, "update");
12621
+ const mapping = buildMapping(flattenCustomVariables(input.headers, input.rows), overrides2, "update");
12410
12622
  warnDropped(ctx, mapping);
12411
12623
  const key = match === "id" ? "id" : "email";
12412
12624
  if (input.rows.length > 0 && !mapping.fields.has(key)) {
@@ -12453,25 +12665,25 @@ var init_update = __esm({
12453
12665
  // src/commands/contacts/bulk-store.ts
12454
12666
  import { existsSync as existsSync6 } from "node:fs";
12455
12667
  import { appendFile as appendFile2, readFile as readFile7, writeFile as writeFile3 } from "node:fs/promises";
12456
- import { join as join13 } from "node:path";
12668
+ import { join as join14 } from "node:path";
12457
12669
  function whereDir(env) {
12458
- return join13(runsRoot(env), WHERE_DIR);
12670
+ return join14(runsRoot(env), WHERE_DIR);
12459
12671
  }
12460
12672
  async function unfinishedWhereIds(ctx, command70, args) {
12461
- const dir2 = whereDir(ctx.env);
12673
+ const dir3 = whereDir(ctx.env);
12462
12674
  const identity = argsIdentity(args);
12463
12675
  const workspaceId = ctx.client.workspaceId ?? ctx.auth.workspaceId;
12464
12676
  for (const run of await listRuns(ctx.env)) {
12465
12677
  if (run.command !== command70 || run.status === "done" || run.status === "planned") continue;
12466
12678
  if ((run.workspaceId || void 0) !== (workspaceId || void 0) || argsIdentity(run.args) !== identity) continue;
12467
- if (run.inputPath?.startsWith(`${dir2}/`) && existsSync6(run.inputPath)) return run.inputPath;
12679
+ if (run.inputPath?.startsWith(`${dir3}/`) && existsSync6(run.inputPath)) return run.inputPath;
12468
12680
  }
12469
12681
  return void 0;
12470
12682
  }
12471
12683
  async function saveWhereIds(ctx, kind, ids2) {
12472
- const dir2 = whereDir(ctx.env);
12473
- ensurePrivateDir2(dir2);
12474
- const path = join13(dir2, `${kind}-${Date.now()}-${newRunId().slice(2)}.txt`);
12684
+ const dir3 = whereDir(ctx.env);
12685
+ ensurePrivateDir2(dir3);
12686
+ const path = join14(dir3, `${kind}-${Date.now()}-${newRunId().slice(2)}.txt`);
12475
12687
  await writeFile3(path, ids2.map((id) => `${id}
12476
12688
  `).join(""), { mode: 384 });
12477
12689
  return path;
@@ -12480,7 +12692,7 @@ function chunkAttempts(env) {
12480
12692
  let earlier;
12481
12693
  return async (runId, chunkIndex) => {
12482
12694
  earlier ??= (async () => {
12483
- const path2 = join13(runsRoot(env), runId, ATTEMPTS_FILE);
12695
+ const path2 = join14(runsRoot(env), runId, ATTEMPTS_FILE);
12484
12696
  const text4 = await readFile7(path2, "utf8").catch(() => "");
12485
12697
  const indexes3 = new Set(
12486
12698
  text4.split("\n").filter((line) => line.trim() !== "").map(Number)
@@ -13122,10 +13334,10 @@ var describe_exports = {};
13122
13334
  __export(describe_exports, {
13123
13335
  default: () => describe_default
13124
13336
  });
13125
- import { Writable as Writable2 } from "node:stream";
13337
+ import { Writable as Writable3 } from "node:stream";
13126
13338
  function printJson(ctx, value) {
13127
13339
  const chunks = [];
13128
- const collect = new Writable2({
13340
+ const collect = new Writable3({
13129
13341
  write(chunk, _encoding, callback) {
13130
13342
  chunks.push(chunk.toString());
13131
13343
  callback();
@@ -13180,12 +13392,18 @@ function flagsOf(entry) {
13180
13392
  ...flag.multiple ? { multiple: true } : {}
13181
13393
  }));
13182
13394
  }
13395
+ function effectOf(entry) {
13396
+ return (entry.op ? entry.op.effect : entry.spec?.effect) ?? "write";
13397
+ }
13398
+ function creditLines(entry) {
13399
+ return entry.op?.credits ?? entry.spec?.cost ?? [];
13400
+ }
13183
13401
  function summaryOf(entry, withFlags) {
13184
- const out = { command: entry.command, summary: entry.summary, beta: entry.gates !== void 0, handWritten: entry.spec !== void 0 };
13402
+ const out = { command: entry.command, summary: entry.summary, effect: effectOf(entry), beta: entry.gates !== void 0, handWritten: entry.spec !== void 0 };
13185
13403
  if (withFlags) out.flags = flagsOf(entry);
13186
13404
  return out;
13187
13405
  }
13188
- function detailOf(entry) {
13406
+ function detailOf(entry, cards) {
13189
13407
  const spec = entry.spec;
13190
13408
  const ids2 = entry.op ? [entry.op.id] : spec?.operationIds ?? [];
13191
13409
  const op = entry.op ?? (ids2.length === 1 ? findOperationById(ids2[0]) : void 0);
@@ -13193,6 +13411,7 @@ function detailOf(entry) {
13193
13411
  const out = {
13194
13412
  command: entry.command,
13195
13413
  summary: entry.summary,
13414
+ effect: effectOf(entry),
13196
13415
  description: entry.op ? entry.op.description ?? null : spec?.description ?? null,
13197
13416
  method: op?.method ?? null,
13198
13417
  path: op?.path ?? null,
@@ -13214,6 +13433,10 @@ function detailOf(entry) {
13214
13433
  };
13215
13434
  if (entry.gates) out.featureGates = entry.gates;
13216
13435
  if (entry.op?.download) out.download = entry.op.download;
13436
+ if (cards) {
13437
+ const lines = creditLines(entry);
13438
+ out.cost = lines.length > 0 ? { lines: lines.map((line) => ({ ...line, price: priceLine(line, cards) })), rateCard: { source: cards[0]?.source ?? "bundled", versions: cards.map((card) => card.version) } } : effectOf(entry) === "spend" ? { lines: [], rateCard: null } : null;
13439
+ }
13217
13440
  return out;
13218
13441
  }
13219
13442
  function unknown(words) {
@@ -13233,6 +13456,7 @@ var init_describe = __esm({
13233
13456
  init_exit_codes();
13234
13457
  init_features();
13235
13458
  init_output();
13459
+ init_rate_card();
13236
13460
  init_version();
13237
13461
  init_execute();
13238
13462
  init_manifest();
@@ -13244,7 +13468,7 @@ var init_describe = __esm({
13244
13468
  summary: "The command map as JSON: commands, flags, body schemas",
13245
13469
  brief: "",
13246
13470
  effect: "read",
13247
- description: "Always JSON. No arguments: every command with its summary. A resource: its commands with their flags. A resource and an action: one command in full (method, path, flags, body schema, examples). Beta commands your workspace has not enabled are left out unless --all-commands; calling one still works.",
13471
+ description: "Always JSON. No arguments: every command with its summary. A resource: its commands with their flags. A resource and an action: one command in full (method, path, flags, body schema, examples). Beta commands your workspace has not enabled are left out unless --all-commands; calling one still works. Every command has an effect (read, write, spend, send or destructive), and one command in full has its cost in credits on your rate card.",
13248
13472
  flags: {
13249
13473
  // Used by scripts/build-reference.ts to write docs/reference.md in one call.
13250
13474
  full: { type: "boolean", description: "Every listed command in full (method, path, flags, body schema, examples), for the docs build" }
@@ -13254,6 +13478,7 @@ var init_describe = __esm({
13254
13478
  { name: "action", description: "One command in full" }
13255
13479
  ],
13256
13480
  examples: ["kenso describe", "kenso describe contacts", "kenso describe contacts bulk-update", "kenso describe --all-commands"],
13481
+ operationIds: ["me.get", "credit-rate-card.get"],
13257
13482
  async run(ctx, { flags, positionals }) {
13258
13483
  const [resourceArg, action] = positionals;
13259
13484
  const resource = resourceArg === void 0 ? void 0 : resourceAliases[resourceArg] ?? resourceArg;
@@ -13262,7 +13487,8 @@ var init_describe = __esm({
13262
13487
  if (resource !== void 0 && action !== void 0) {
13263
13488
  const entry = all.find((e) => e.resource === resource && e.action === action);
13264
13489
  if (!entry) throw unknown([resourceArg, action]);
13265
- printJson(ctx, detailOf(entry));
13490
+ const cards = creditLines(entry).length > 0 ? await loadRateCards(ctx, { timeoutMs: HELP_RATE_CARD_TIMEOUT_MS }) : [];
13491
+ printJson(ctx, detailOf(entry, cards));
13266
13492
  return ExitCode.Ok;
13267
13493
  }
13268
13494
  const scoped = resource === void 0 ? all : all.filter((e) => e.resource === resource);
@@ -14284,6 +14510,8 @@ var init_call = __esm({
14284
14510
  summary: "Call a hosted Kenso MCP tool, such as list_skills",
14285
14511
  brief: "list_skills runs directly",
14286
14512
  effect: "destructive",
14513
+ // The two skill tools only read; any other tool can do whatever the API can.
14514
+ effectFor: ({ positionals }) => positionals[0] === "list_skills" || positionals[0] === "load_skill" ? "read" : "destructive",
14287
14515
  description: "Calls one Kenso MCP tool with the same API key and prints its result: structuredContent when the tool returns it, else its text parsed as JSON, else the text. Covers MCP-only tools, such as the skills: list_skills and load_skill take no kenso mcp tools first. A tool error exits 1 with the tool's message. A facade tool takes its operation with --operation. --dry-run prints the tools/call request (tool and arguments) and sends nothing.",
14288
14516
  flags: {
14289
14517
  operation: { type: "string", description: "The facade operation, for example list" },
@@ -15169,6 +15397,7 @@ var init_stage_rules = __esm({
15169
15397
  action: "stage-rules",
15170
15398
  summary: "List or set the fields a deal should have in each stage",
15171
15399
  effect: "write",
15400
+ effectFor: ({ positionals }) => positionals.length === 0 ? "read" : "write",
15172
15401
  description: "Without a stage, reads GET /v1/opportunity-stages (the default pipeline's stages; --pipeline <id> reads that pipeline's from GET /v1/pipelines/{pipelineId}) and prints each stage's key, label, category, isArchived, requiredFields and isDefault, plus requirableFields: every field a stage can require (amount, closeDate, ownerMemberId, primaryPersonId, nextStep, lostReasonKey, wonReasonKey, and custom.<key> for each custom deal field). With a stage and --require, --default or --none, sends PUT /v1/opportunity-stages/{stageKey}/required-fields and prints that stage's rule. --require is the stage's whole list, in order, at most 10. --default puts it back on the default: a lost stage asks for lostReasonKey, any other stage nothing. A missing field never stops a move: the deal moves, the move prints a warning, and the deal is flagged Missing until the field is filled. Setting a rule needs the workspace_settings permission. A stage key is unique across pipelines, so it sets a stage of any pipeline; with --pipeline it first checks the stage is that pipeline's. --dry-run prints the PUT and changes nothing.",
15173
15402
  flags: {
15174
15403
  require: { type: "string", description: "Comma-separated field ids the stage requires, in order (amount,closeDate,custom.tier)" },
@@ -15474,8 +15703,8 @@ var show_exports2 = {};
15474
15703
  __export(show_exports2, {
15475
15704
  default: () => show_default2
15476
15705
  });
15477
- import { existsSync as existsSync7, readFileSync as readFileSync9 } from "node:fs";
15478
- import { join as join14 } from "node:path";
15706
+ import { existsSync as existsSync7, readFileSync as readFileSync11 } from "node:fs";
15707
+ import { join as join15 } from "node:path";
15479
15708
  var FILES, command44, show_default2;
15480
15709
  var init_show2 = __esm({
15481
15710
  "src/commands/runs/show.ts"() {
@@ -15501,16 +15730,16 @@ var init_show2 = __esm({
15501
15730
  examples: ["kenso runs show r_ab3dxk2q"],
15502
15731
  async run(ctx, { positionals }) {
15503
15732
  const run = await loadRun(positionals[0] ?? "", ctx.env);
15504
- const { dir: dir2, ...record3 } = run;
15505
- const files = { dir: dir2 };
15733
+ const { dir: dir3, ...record3 } = run;
15734
+ const files = { dir: dir3 };
15506
15735
  for (const [key, name] of FILES) {
15507
- const path = join14(dir2, name);
15736
+ const path = join15(dir3, name);
15508
15737
  if (existsSync7(path)) files[key] = path;
15509
15738
  }
15510
15739
  let summary;
15511
15740
  if (files.summary) {
15512
15741
  try {
15513
- summary = JSON.parse(readFileSync9(files.summary, "utf8"));
15742
+ summary = JSON.parse(readFileSync11(files.summary, "utf8"));
15514
15743
  } catch {
15515
15744
  summary = void 0;
15516
15745
  }
@@ -16049,7 +16278,7 @@ var init_common3 = __esm({
16049
16278
  // src/commands/studio/folder.ts
16050
16279
  import { createHash as createHash6 } from "node:crypto";
16051
16280
  import { lstat, readdir as readdir2, readFile as readFile10, stat as stat3, writeFile as writeFile4 } from "node:fs/promises";
16052
- import { extname as extname6, isAbsolute, join as join15, relative, resolve as resolve11, sep } from "node:path";
16281
+ import { extname as extname6, isAbsolute, join as join16, relative, resolve as resolve11, sep } from "node:path";
16053
16282
  function textOf2(bytes) {
16054
16283
  if (bytes.length >= TEXT_MAX_BYTES || bytes.includes(0)) return void 0;
16055
16284
  try {
@@ -16058,10 +16287,10 @@ function textOf2(bytes) {
16058
16287
  return void 0;
16059
16288
  }
16060
16289
  }
16061
- async function existingDir(dir2) {
16062
- const abs = resolve11(dir2);
16290
+ async function existingDir(dir3) {
16291
+ const abs = resolve11(dir3);
16063
16292
  const info = await stat3(abs).catch(() => void 0);
16064
- if (!info?.isDirectory()) throw usageError(`${dir2} is not a directory.`, { field: "dir" });
16293
+ if (!info?.isDirectory()) throw usageError(`${dir3} is not a directory.`, { field: "dir" });
16065
16294
  return abs;
16066
16295
  }
16067
16296
  function inBundleLayout(bundlePath) {
@@ -16072,14 +16301,14 @@ function inBundleLayout(bundlePath) {
16072
16301
  const name = segments[1];
16073
16302
  return segments[0] === "samples" && segments.length === 2 && SAMPLE_NAME.test(name) && !TOOL_CONFIG_NAMES.has(name.toLowerCase());
16074
16303
  }
16075
- async function readFolder(dir2, skipped = []) {
16076
- const root2 = await existingDir(dir2);
16304
+ async function readFolder(dir3, skipped = []) {
16305
+ const root2 = await existingDir(dir3);
16077
16306
  const files = [];
16078
16307
  const walk = async (folder) => {
16079
16308
  const entries2 = await readdir2(folder, { withFileTypes: true });
16080
16309
  for (const entry of entries2) {
16081
16310
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
16082
- const abs = join15(folder, entry.name);
16311
+ const abs = join16(folder, entry.name);
16083
16312
  const path = relative(root2, abs).split(sep).join("/");
16084
16313
  if (entry.isDirectory()) {
16085
16314
  if (path === "assets" || path.startsWith("assets/") || path === "samples") await walk(abs);
@@ -16111,7 +16340,7 @@ async function existingFileNoLinks(root2, target2, bundlePath) {
16111
16340
  const parts2 = relative(root2, target2).split(sep);
16112
16341
  let at = root2;
16113
16342
  for (const [i, part] of parts2.entries()) {
16114
- at = join15(at, part);
16343
+ at = join16(at, part);
16115
16344
  const info = await lstat(at).catch(() => void 0);
16116
16345
  if (!info) return false;
16117
16346
  if (info.isSymbolicLink()) throw unsafePath(bundlePath, `${at} is a symbolic link`);
@@ -16124,7 +16353,7 @@ async function existingFileNoLinks(root2, target2, bundlePath) {
16124
16353
  }
16125
16354
  async function readPullState(root2) {
16126
16355
  try {
16127
- const files = JSON.parse(await readFile10(join15(root2, PULL_STATE), "utf8"))?.files;
16356
+ const files = JSON.parse(await readFile10(join16(root2, PULL_STATE), "utf8"))?.files;
16128
16357
  if (typeof files !== "object" || files === null) return {};
16129
16358
  return Object.fromEntries(Object.entries(files).filter((entry) => typeof entry[1] === "string"));
16130
16359
  } catch {
@@ -16132,7 +16361,7 @@ async function readPullState(root2) {
16132
16361
  }
16133
16362
  }
16134
16363
  async function recordPullState(root2, entries2) {
16135
- const path = join15(root2, PULL_STATE);
16364
+ const path = join16(root2, PULL_STATE);
16136
16365
  await existingFileNoLinks(root2, path, PULL_STATE);
16137
16366
  const files = { ...await readPullState(root2), ...Object.fromEntries(entries2) };
16138
16367
  await writeFile4(path, `${JSON.stringify({ files }, null, 2)}
@@ -16342,7 +16571,7 @@ __export(pull_exports, {
16342
16571
  default: () => pull_default
16343
16572
  });
16344
16573
  import { mkdir, readFile as readFile11, writeFile as writeFile5 } from "node:fs/promises";
16345
- import { dirname as dirname2, join as join16, resolve as resolve12 } from "node:path";
16574
+ import { dirname as dirname2, join as join17, resolve as resolve12 } from "node:path";
16346
16575
  var command51, pull_default;
16347
16576
  var init_pull = __esm({
16348
16577
  "src/commands/studio/pull.ts"() {
@@ -16377,7 +16606,7 @@ var init_pull = __esm({
16377
16606
  if (version !== void 0 && !/^(draft|latest|\d+)$/.test(version)) {
16378
16607
  throw usageError(`--template-version must be draft, latest or a version id (got "${version}").`, { field: "template-version" });
16379
16608
  }
16380
- const dir2 = resolve12(String(flags.dir));
16609
+ const dir3 = resolve12(String(flags.dir));
16381
16610
  const res = await ctx.client.request({
16382
16611
  method: "GET",
16383
16612
  path: `/v1/asset-templates/${templateId}/pull`,
@@ -16388,17 +16617,17 @@ var init_pull = __esm({
16388
16617
  if (pulled.skipped?.length) {
16389
16618
  ctx.output.warn(`Kenso left out ${pulled.skipped.length} stored file${pulled.skipped.length === 1 ? "" : "s"} outside the bundle layout: ${pulled.skipped.join(", ")}.`);
16390
16619
  }
16391
- const files = Object.entries(pulled.files ?? {}).map(([path, file]) => ({ path, file, target: safeJoin(dir2, path) }));
16620
+ const files = Object.entries(pulled.files ?? {}).map(([path, file]) => ({ path, file, target: safeJoin(dir3, path) }));
16392
16621
  const missing2 = files.find(({ file }) => typeof file.text !== "string" && !file.downloadUrl);
16393
16622
  if (missing2) {
16394
16623
  throw new KensoError({ code: "pull_incomplete", message: `${missing2.path} came back with neither text nor a download link.`, exitCode: ExitCode.Server });
16395
16624
  }
16396
- const statePath2 = join16(dir2, PULL_STATE);
16397
- await existingFileNoLinks(dir2, statePath2, PULL_STATE);
16398
- const state = await readPullState(dir2);
16625
+ const statePath2 = join17(dir3, PULL_STATE);
16626
+ await existingFileNoLinks(dir3, statePath2, PULL_STATE);
16627
+ const state = await readPullState(dir3);
16399
16628
  const conflicts = [];
16400
16629
  for (const { path, file, target: target2 } of files) {
16401
- if (!await existingFileNoLinks(dir2, target2, path)) continue;
16630
+ if (!await existingFileNoLinks(dir3, target2, path)) continue;
16402
16631
  const current = sha2562(await readFile11(target2));
16403
16632
  const next = typeof file.text === "string" ? sha2562(Buffer.from(file.text, "utf8")) : file.sha256?.toLowerCase();
16404
16633
  if (current !== next && current !== state[path]) conflicts.push(path);
@@ -16408,7 +16637,7 @@ var init_pull = __esm({
16408
16637
  dryRun: true,
16409
16638
  templateId,
16410
16639
  versionId: pulled.versionId,
16411
- dir: dir2,
16640
+ dir: dir3,
16412
16641
  files: files.map(({ path }) => path),
16413
16642
  ...conflicts.length > 0 ? { conflicts } : {}
16414
16643
  });
@@ -16417,22 +16646,22 @@ var init_pull = __esm({
16417
16646
  if (conflicts.length > 0 && flags.force !== true) {
16418
16647
  throw new KensoError({
16419
16648
  code: "local_changes",
16420
- message: `Pulling would replace ${conflicts.length} file${conflicts.length === 1 ? "" : "s"} in ${dir2} that no earlier pull wrote or push sent, or that changed since: ${conflicts.join(", ")}.`,
16649
+ message: `Pulling would replace ${conflicts.length} file${conflicts.length === 1 ? "" : "s"} in ${dir3} that no earlier pull wrote or push sent, or that changed since: ${conflicts.join(", ")}.`,
16421
16650
  exitCode: ExitCode.Conflict,
16422
16651
  field: "force",
16423
16652
  hint: "They are files you added or changed since the last pull or push. Move them away or compare them with the template first, or add --force to replace them with the template's version. Nothing was written.",
16424
16653
  next: commandLine2(ctx, "studio pull", { flags: { ...flags, force: true }, positionals })
16425
16654
  });
16426
16655
  }
16427
- await mkdir(dir2, { recursive: true });
16656
+ await mkdir(dir3, { recursive: true });
16428
16657
  const written = await mapLimit(files, PARALLEL_TRANSFERS, async ({ path, file, target: target2 }) => {
16429
16658
  const content = typeof file.text === "string" ? Buffer.from(file.text, "utf8") : await download2(file.downloadUrl, path, file.sha256, ctx.signal);
16430
16659
  await mkdir(dirname2(target2), { recursive: true });
16431
16660
  await writeFile5(target2, content);
16432
16661
  return [path, sha2562(content)];
16433
16662
  });
16434
- await recordPullState(dir2, written);
16435
- ctx.output.object({ templateId, versionId: pulled.versionId, files: files.length, dir: dir2, ...conflicts.length > 0 ? { replaced: conflicts } : {} });
16663
+ await recordPullState(dir3, written);
16664
+ ctx.output.object({ templateId, versionId: pulled.versionId, files: files.length, dir: dir3, ...conflicts.length > 0 ? { replaced: conflicts } : {} });
16436
16665
  return ExitCode.Ok;
16437
16666
  }
16438
16667
  };
@@ -16441,24 +16670,24 @@ var init_pull = __esm({
16441
16670
  });
16442
16671
 
16443
16672
  // src/commands/studio/read.ts
16444
- async function readLocalTemplate(ctx, templateId, dir2) {
16673
+ async function readLocalTemplate(ctx, templateId, dir3) {
16445
16674
  const skipped = [];
16446
- const files = await readFolder(dir2, skipped);
16675
+ const files = await readFolder(dir3, skipped);
16447
16676
  if (skipped.length > 0) {
16448
16677
  const shown = skipped.length > SHOWN ? `${skipped.slice(0, SHOWN).join(", ")} and ${skipped.length - SHOWN} more` : skipped.join(", ");
16449
16678
  ctx.output.warn(`Skipped what is not part of a Studio bundle: ${shown}. A bundle holds only ${LAYOUT}.`);
16450
16679
  }
16451
16680
  if (files.length === 0) {
16452
- throw usageError(`${dir2} has no template files (only ${LAYOUT} are read; dotfiles and node_modules are skipped).`, {
16681
+ throw usageError(`${dir3} has no template files (only ${LAYOUT} are read; dotfiles and node_modules are skipped).`, {
16453
16682
  field: "dir",
16454
- next: `kenso studio pull ${templateId} --dir ${dir2}`
16683
+ next: `kenso studio pull ${templateId} --dir ${dir3}`
16455
16684
  });
16456
16685
  }
16457
16686
  refuseOversize(files);
16458
16687
  return files;
16459
16688
  }
16460
- async function readTemplateFolder(ctx, templateId, dir2) {
16461
- return bundleFiles(ctx, templateId, await readLocalTemplate(ctx, templateId, dir2));
16689
+ async function readTemplateFolder(ctx, templateId, dir3) {
16690
+ return bundleFiles(ctx, templateId, await readLocalTemplate(ctx, templateId, dir3));
16462
16691
  }
16463
16692
  var SHOWN;
16464
16693
  var init_read = __esm({
@@ -16647,8 +16876,8 @@ import { createHash as createHash8 } from "node:crypto";
16647
16876
  function list(paths) {
16648
16877
  return paths.length > SHOWN2 ? `${paths.slice(0, SHOWN2).join(", ")} and ${paths.length - SHOWN2} more` : paths.join(", ");
16649
16878
  }
16650
- async function warnIfFolderDiffers(ctx, templateId, dir2, versionId, push) {
16651
- const local = await readFolder(dir2);
16879
+ async function warnIfFolderDiffers(ctx, templateId, dir3, versionId, push) {
16880
+ const local = await readFolder(dir3);
16652
16881
  const res = await ctx.client.request({
16653
16882
  method: "GET",
16654
16883
  path: `/v1/asset-templates/${templateId}/pull`,
@@ -16722,10 +16951,10 @@ var init_preview = __esm({
16722
16951
  const ids2 = accountIds(stringFlag(flags["account-ids"]));
16723
16952
  const interact = flags.interact !== void 0 ? await readDataArg(String(flags.interact), ctx.stdin) : void 0;
16724
16953
  if (interact !== void 0 && !Array.isArray(interact)) throw usageError("--interact must be a JSON array of steps.", { field: "interact" });
16725
- const dir2 = stringFlag(flags.dir);
16726
- if (dir2 !== void 0) {
16727
- const push = commandLine2(ctx, "studio push", { flags: { dir: dir2 }, positionals: [String(templateId)] });
16728
- await warnIfFolderDiffers(ctx, templateId, dir2, versionId, push);
16954
+ const dir3 = stringFlag(flags.dir);
16955
+ if (dir3 !== void 0) {
16956
+ const push = commandLine2(ctx, "studio push", { flags: { dir: dir3 }, positionals: [String(templateId)] });
16957
+ await warnIfFolderDiffers(ctx, templateId, dir3, versionId, push);
16729
16958
  }
16730
16959
  const mode = stringFlag(flags.mode);
16731
16960
  const sample = stringFlag(flags.sample);
@@ -16854,7 +17083,7 @@ __export(fill_exports, {
16854
17083
  });
16855
17084
  import { createHash as createHash9 } from "node:crypto";
16856
17085
  import { readFile as readFile12 } from "node:fs/promises";
16857
- import { join as join17, resolve as resolve14 } from "node:path";
17086
+ import { join as join18, resolve as resolve14 } from "node:path";
16858
17087
  async function readTarget(ctx, flags) {
16859
17088
  const accounts = stringFlag(flags.accounts);
16860
17089
  const campaign = stringFlag(flags.campaign);
@@ -16905,7 +17134,7 @@ async function refuseRefill(ctx, args, target2) {
16905
17134
  code: "already_filled",
16906
17135
  exitCode: ExitCode.Conflict,
16907
17136
  message: unfinished ? `Run ${earlier.runId} is already filling these ${ids2} (${earlier.status}).` : `Run ${earlier.runId} already filled these ${ids2}.`,
16908
- hint: unfinished ? "Continue that run instead: a new fill would create every fill run again." : succeeded ? "Every page was filled. Filling again rebuilds and charges every page that is not building or live; to do that anyway, use kenso asset-runs create." : `Filling again rebuilds and charges every page that is not building or live. To retry only the failed ones, put the ${target2.key} values of the failed rows in ${join17(earlier.dir, "results.csv")} in a file and fill that file.`,
17137
+ hint: unfinished ? "Continue that run instead: a new fill would create every fill run again." : succeeded ? "Every page was filled. Filling again rebuilds and charges every page that is not building or live; to do that anyway, use kenso asset-runs create." : `Filling again rebuilds and charges every page that is not building or live. To retry only the failed ones, put the ${target2.key} values of the failed rows in ${join18(earlier.dir, "results.csv")} in a file and fill that file.`,
16909
17138
  next: unfinished ? `kenso runs resume ${earlier.runId}` : `kenso runs show ${earlier.runId}`
16910
17139
  });
16911
17140
  }
@@ -17447,25 +17676,25 @@ var init_views = __esm({
17447
17676
 
17448
17677
  // src/commands/webhooks/local.ts
17449
17678
  import { createHmac, randomBytes as randomBytes2 } from "node:crypto";
17450
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync10, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "node:fs";
17451
- import { join as join18 } from "node:path";
17679
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync12, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "node:fs";
17680
+ import { join as join19 } from "node:path";
17452
17681
  function webhooksDir(env) {
17453
- const dir2 = join18(configDir(env), "webhooks");
17454
- mkdirSync4(dir2, { recursive: true, mode: 448 });
17455
- return dir2;
17682
+ const dir3 = join19(configDir(env), "webhooks");
17683
+ mkdirSync4(dir3, { recursive: true, mode: 448 });
17684
+ return dir3;
17456
17685
  }
17457
17686
  function signingSecretPath(env) {
17458
- return join18(webhooksDir(env), "signing-secret");
17687
+ return join19(webhooksDir(env), "signing-secret");
17459
17688
  }
17460
17689
  function signingSecret(env) {
17461
17690
  const file = signingSecretPath(env);
17462
17691
  try {
17463
- const saved = readFileSync10(file, "utf8").trim();
17692
+ const saved = readFileSync12(file, "utf8").trim();
17464
17693
  if (/^whsec_[A-Za-z0-9+/]{32,}={0,2}$/.test(saved)) return saved;
17465
17694
  } catch {
17466
17695
  }
17467
17696
  const secret = `whsec_${randomBytes2(24).toString("base64")}`;
17468
- writeFileSync4(file, `${secret}
17697
+ writeFileSync5(file, `${secret}
17469
17698
  `, { mode: 384 });
17470
17699
  return secret;
17471
17700
  }
@@ -17506,15 +17735,15 @@ async function forward(url, event, secret, signal) {
17506
17735
  }
17507
17736
  }
17508
17737
  function statePath(env, workspaceId) {
17509
- return join18(webhooksDir(env), `listener-${(workspaceId ?? "default").replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
17738
+ return join19(webhooksDir(env), `listener-${(workspaceId ?? "default").replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
17510
17739
  }
17511
17740
  function writeListenerState(env, workspaceId, state) {
17512
- writeFileSync4(statePath(env, workspaceId), `${JSON.stringify(state)}
17741
+ writeFileSync5(statePath(env, workspaceId), `${JSON.stringify(state)}
17513
17742
  `, { mode: 384 });
17514
17743
  }
17515
17744
  function readListenerState(env, workspaceId) {
17516
17745
  try {
17517
- const state = JSON.parse(readFileSync10(statePath(env, workspaceId), "utf8"));
17746
+ const state = JSON.parse(readFileSync12(statePath(env, workspaceId), "utf8"));
17518
17747
  return typeof state.url === "string" && typeof state.token === "string" ? state : void 0;
17519
17748
  } catch {
17520
17749
  return void 0;
@@ -17849,8 +18078,8 @@ var init_status3 = __esm({
17849
18078
  });
17850
18079
 
17851
18080
  // src/work/files.ts
17852
- import { closeSync as closeSync2, constants, fchmodSync, fstatSync, lstatSync, openSync as openSync2, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "node:fs";
17853
- import { join as join19 } from "node:path";
18081
+ import { closeSync as closeSync2, constants, fchmodSync, fstatSync, lstatSync, openSync as openSync2, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "node:fs";
18082
+ import { join as join20 } from "node:path";
17854
18083
  function agentName(value) {
17855
18084
  if (typeof value !== "string") return void 0;
17856
18085
  const name = value.trim().slice(0, MAX_AGENT_NAME);
@@ -17866,13 +18095,13 @@ function workFileName(claimId) {
17866
18095
  if (!isPlainFileName(claimId)) throw new Error("claimId is not a plain file name");
17867
18096
  return `${claimId}.work.json`;
17868
18097
  }
17869
- function writeWorkFile(dir2, work, mode = 384) {
18098
+ function writeWorkFile(dir3, work, mode = 384) {
17870
18099
  const name = workFileName(work.claimId);
17871
18100
  if (!isPlainFileName(work.answersFile)) throw new Error("answersFile is not a plain file name");
17872
- const path = join19(dir2, name);
18101
+ const path = join20(dir3, name);
17873
18102
  const fd = openSync2(path, "wx", mode);
17874
18103
  try {
17875
- writeFileSync5(fd, JSON.stringify(work, null, 2) + "\n", "utf8");
18104
+ writeFileSync6(fd, JSON.stringify(work, null, 2) + "\n", "utf8");
17876
18105
  fchmodSync(fd, mode);
17877
18106
  } finally {
17878
18107
  closeSync2(fd);
@@ -17887,7 +18116,7 @@ function readRegularFile(path, what) {
17887
18116
  const stat4 = fstatSync(fd);
17888
18117
  if (!stat4.isFile()) return notPlain;
17889
18118
  if (stat4.size > MAX_ANSWERS_FILE_BYTES) return { ok: false, error: `the ${what} is too large` };
17890
- return readFileSync11(fd, "utf8");
18119
+ return readFileSync13(fd, "utf8");
17891
18120
  } finally {
17892
18121
  closeSync2(fd);
17893
18122
  }
@@ -17974,7 +18203,7 @@ var init_files = __esm({
17974
18203
 
17975
18204
  // src/work/agent-user.ts
17976
18205
  import { execFile, spawnSync as spawnSync2 } from "node:child_process";
17977
- import { readFileSync as readFileSync12 } from "node:fs";
18206
+ import { readFileSync as readFileSync14 } from "node:fs";
17978
18207
  import { isAbsolute as isAbsolute2 } from "node:path";
17979
18208
  function sudoArgs(user, command70, args, keep = [], set2 = {}) {
17980
18209
  const assignments = Object.entries(set2).map(([name, value]) => `${name}=${value}`);
@@ -18031,7 +18260,7 @@ function ids(status, field) {
18031
18260
  }
18032
18261
  function sudoGids(groupFile) {
18033
18262
  const gids = /* @__PURE__ */ new Set([0]);
18034
- for (const line of readFileSync12(groupFile, "utf8").split("\n")) {
18263
+ for (const line of readFileSync14(groupFile, "utf8").split("\n")) {
18035
18264
  const [group, , gid] = line.split(":");
18036
18265
  if (group !== void 0 && SUDO_GROUPS.has(group) && /^\d+$/.test(gid ?? "")) gids.add(Number(gid));
18037
18266
  }
@@ -18093,7 +18322,7 @@ var init_agent_user = __esm({
18093
18322
  // src/commands/work/folder.ts
18094
18323
  import { existsSync as existsSync9 } from "node:fs";
18095
18324
  import { appendFile as appendFile3, symlink as symlink2, unlink as unlink3 } from "node:fs/promises";
18096
- import { dirname as dirname3, join as join20, resolve as resolve15 } from "node:path";
18325
+ import { dirname as dirname3, join as join21, resolve as resolve15 } from "node:path";
18097
18326
  var WorkRunFolder;
18098
18327
  var init_folder2 = __esm({
18099
18328
  "src/commands/work/folder.ts"() {
@@ -18133,32 +18362,32 @@ var init_folder2 = __esm({
18133
18362
  async make() {
18134
18363
  const root2 = runsRoot(this.ctx.env);
18135
18364
  const makeDir = (path) => this.shared ? ensureDir(path, SHARED_DIR_MODE) : ensurePrivateDir2(path);
18136
- let dir2;
18365
+ let dir3;
18137
18366
  if (this.outDir === void 0) {
18138
- dir2 = join20(root2, this.runId);
18367
+ dir3 = join21(root2, this.runId);
18139
18368
  if (!this.shared) ensurePrivateDir2(root2);
18140
- makeDir(dir2);
18369
+ makeDir(dir3);
18141
18370
  } else {
18142
- dir2 = resolve15(this.outDir);
18143
- const existing = existsSync9(join20(dir2, "run.json")) ? await readRunDir(dir2) : null;
18371
+ dir3 = resolve15(this.outDir);
18372
+ const existing = existsSync9(join21(dir3, "run.json")) ? await readRunDir(dir3) : null;
18144
18373
  if (existing && !existing.command.startsWith("work ")) {
18145
- throw usageError(`${dir2} already holds run ${existing.runId} (${existing.command}).`, {
18374
+ throw usageError(`${dir3} already holds run ${existing.runId} (${existing.command}).`, {
18146
18375
  field: "out",
18147
18376
  hint: "Pick another --out directory, or leave --out off to keep the work under the runs directory."
18148
18377
  });
18149
18378
  }
18150
- makeDir(dir2);
18151
- for (const name of ["results.ndjson", "summary.json"]) await unlink3(join20(dir2, name)).catch(() => void 0);
18379
+ makeDir(dir3);
18380
+ for (const name of ["results.ndjson", "summary.json"]) await unlink3(join21(dir3, name)).catch(() => void 0);
18152
18381
  try {
18153
18382
  if (!this.shared) ensurePrivateDir2(root2);
18154
- await symlink2(dir2, join20(root2, this.runId), "junction");
18383
+ await symlink2(dir3, join21(root2, this.runId), "junction");
18155
18384
  } catch (err) {
18156
- this.ctx.output.warn(`Could not link ${dir2} into ${root2} (${err.message}): kenso runs will not list this run.`);
18385
+ this.ctx.output.warn(`Could not link ${dir3} into ${root2} (${err.message}): kenso runs will not list this run.`);
18157
18386
  }
18158
18387
  }
18159
- this.dir = dir2;
18388
+ this.dir = dir3;
18160
18389
  if (this.shared) {
18161
- this.tmpDir = join20(dir2, "tmp");
18390
+ this.tmpDir = join21(dir3, "tmp");
18162
18391
  ensureDir(this.tmpDir, JOB_DIR_MODE);
18163
18392
  }
18164
18393
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -18171,28 +18400,28 @@ var init_folder2 = __esm({
18171
18400
  status: "running",
18172
18401
  chunkCount: 0,
18173
18402
  chunksDone: [],
18174
- dir: dir2,
18403
+ dir: dir3,
18175
18404
  rows: 0,
18176
18405
  cwd: process.cwd(),
18177
18406
  pid: process.pid,
18178
18407
  updatedAt: now
18179
18408
  };
18180
18409
  await writeRunRecord(this.record);
18181
- return dir2;
18410
+ return dir3;
18182
18411
  }
18183
18412
  /**
18184
18413
  * A job's folder, jobs/<claimId> (a plain file name): private, or with --agent-user one the agent user's group
18185
18414
  * writes (3770) under a jobs folder it can only pass through (2750).
18186
18415
  */
18187
18416
  async jobDir(claimId) {
18188
- const dir2 = join20(await this.ensure(), "jobs", claimId);
18417
+ const dir3 = join21(await this.ensure(), "jobs", claimId);
18189
18418
  if (this.shared) {
18190
- ensureDir(dirname3(dir2), SHARED_DIR_MODE);
18191
- ensureDir(dir2, JOB_DIR_MODE);
18419
+ ensureDir(dirname3(dir3), SHARED_DIR_MODE);
18420
+ ensureDir(dir3, JOB_DIR_MODE);
18192
18421
  } else {
18193
- ensurePrivateDir2(dir2);
18422
+ ensurePrivateDir2(dir3);
18194
18423
  }
18195
- return dir2;
18424
+ return dir3;
18196
18425
  }
18197
18426
  /**
18198
18427
  * One line of results.ndjson, each string redacted: a failed job's detail is the agent's own stderr, which can hold
@@ -18201,13 +18430,13 @@ var init_folder2 = __esm({
18201
18430
  async append(line) {
18202
18431
  if (!this.dir) return;
18203
18432
  const json = JSON.stringify(line, (_key, value) => typeof value === "string" ? redact(value) : value);
18204
- await appendFile3(join20(this.dir, "results.ndjson"), `${json}
18433
+ await appendFile3(join21(this.dir, "results.ndjson"), `${json}
18205
18434
  `, { mode: 384 });
18206
18435
  }
18207
18436
  /** summary.json, and run.json with the final status, the claims (chunkCount) and the items (rows). */
18208
18437
  async finish(status, claims, items, summary) {
18209
18438
  if (!this.dir || !this.record) return;
18210
- await writeJsonAtomic(join20(this.dir, "summary.json"), summary);
18439
+ await writeJsonAtomic(join21(this.dir, "summary.json"), summary);
18211
18440
  this.record = { ...this.record, status, chunkCount: claims, rows: items, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
18212
18441
  await writeRunRecord(this.record);
18213
18442
  }
@@ -18315,7 +18544,7 @@ var init_pull2 = __esm({
18315
18544
  // src/commands/work/answers.ts
18316
18545
  import { randomUUID as randomUUID3 } from "node:crypto";
18317
18546
  import { existsSync as existsSync10 } from "node:fs";
18318
- import { basename as basename5, dirname as dirname4, join as join21 } from "node:path";
18547
+ import { basename as basename5, dirname as dirname4, join as join22 } from "node:path";
18319
18548
  function zeroTotals() {
18320
18549
  return { accepted: 0, rejected: 0, expired: 0, duplicate: 0, dropped: 0 };
18321
18550
  }
@@ -18387,7 +18616,7 @@ function droppedResult(d) {
18387
18616
  return { itemId: d.itemId ?? null, status: "dropped", reason: d.reason, message: `Answer ${d.index + 1} of the file was not sent: ${d.reason.replace(/_/g, " ")}.` };
18388
18617
  }
18389
18618
  async function writeResults(answersPath, claimId, results, totals) {
18390
- const path = join21(dirname4(answersPath), `${claimId}.results.json`);
18619
+ const path = join22(dirname4(answersPath), `${claimId}.results.json`);
18391
18620
  await writeJsonAtomic(path, { version: 1, claimId, submittedAt: (/* @__PURE__ */ new Date()).toISOString(), ...totals, results });
18392
18621
  return path;
18393
18622
  }
@@ -18416,7 +18645,7 @@ function workFileNextTo(answersPath) {
18416
18645
  hint: "Write the answers to <claimId>.answers.json next to its <claimId>.work.json, as the work file's rules say."
18417
18646
  });
18418
18647
  }
18419
- const workPath = join21(dirname4(answersPath), `${claimId}.work.json`);
18648
+ const workPath = join22(dirname4(answersPath), `${claimId}.work.json`);
18420
18649
  if (!existsSync10(workPath)) {
18421
18650
  throw usageError(`${workPath} is missing: kenso work submit reads it next to the answers file.`, { field: "answers-file" });
18422
18651
  }
@@ -18550,7 +18779,7 @@ var init_release = __esm({
18550
18779
  import { spawn as nodeSpawn3 } from "node:child_process";
18551
18780
  import { rmSync as rmSync3, statSync as statSync3 } from "node:fs";
18552
18781
  import { access, constants as constants2 } from "node:fs/promises";
18553
- import { delimiter as delimiter2, join as join22 } from "node:path";
18782
+ import { delimiter as delimiter2, join as join23 } from "node:path";
18554
18783
  import { setTimeout as delay12 } from "node:timers/promises";
18555
18784
  function childEnv(parent, adapter, extra) {
18556
18785
  const scrub = new Set(adapter.scrubEnv.map((name) => name.toUpperCase()));
@@ -18575,7 +18804,7 @@ async function isExecutableFile(path) {
18575
18804
  function pathDirs(env) {
18576
18805
  const key = Object.keys(env).find((name) => name.toUpperCase() === "PATH");
18577
18806
  const value = key ? env[key] : void 0;
18578
- return (value ?? "").split(delimiter2).filter((dir2) => dir2 !== "");
18807
+ return (value ?? "").split(delimiter2).filter((dir3) => dir3 !== "");
18579
18808
  }
18580
18809
  async function resolveBinary(adapter, env, override2) {
18581
18810
  const names = override2 !== void 0 && override2 !== "" ? [override2] : adapter.binaries;
@@ -18585,9 +18814,9 @@ async function resolveBinary(adapter, env, override2) {
18585
18814
  if (await isExecutableFile(name)) return name;
18586
18815
  continue;
18587
18816
  }
18588
- for (const dir2 of pathDirs(env)) {
18817
+ for (const dir3 of pathDirs(env)) {
18589
18818
  for (const ext of extensions) {
18590
- const candidate = join22(dir2, name + ext);
18819
+ const candidate = join23(dir3, name + ext);
18591
18820
  if (await isExecutableFile(candidate)) return candidate;
18592
18821
  }
18593
18822
  }
@@ -18753,11 +18982,11 @@ async function runAgentJob(adapter, job, deps) {
18753
18982
  }
18754
18983
  let work;
18755
18984
  try {
18756
- work = readWorkFile(join22(job.cwd, job.workFile));
18985
+ work = readWorkFile(join23(job.cwd, job.workFile));
18757
18986
  } catch (err) {
18758
18987
  return result("fatal", null, `the work file could not be read: ${err.message}`);
18759
18988
  }
18760
- const answersPath = join22(job.cwd, job.answersFile);
18989
+ const answersPath = join23(job.cwd, job.answersFile);
18761
18990
  try {
18762
18991
  rmSync3(answersPath, { force: true });
18763
18992
  } catch (err) {
@@ -19167,7 +19396,7 @@ ${out.stderr}`;
19167
19396
  });
19168
19397
 
19169
19398
  // src/work/adapters/opencode.ts
19170
- import { basename as basename6, join as join23 } from "node:path";
19399
+ import { basename as basename6, join as join24 } from "node:path";
19171
19400
  var opencode;
19172
19401
  var init_opencode = __esm({
19173
19402
  "src/work/adapters/opencode.ts"() {
@@ -19211,7 +19440,7 @@ ${out.stderr}`);
19211
19440
  if (job.model) args.push("--model", job.model);
19212
19441
  args.push(job.instruction);
19213
19442
  const env = { OPENCODE_CONFIG_CONTENT: JSON.stringify(config) };
19214
- if (job.tmpDir !== void 0) env.OPENCODE_DB = join23(job.tmpDir, `opencode-${basename6(job.cwd)}.db`);
19443
+ if (job.tmpDir !== void 0) env.OPENCODE_DB = join24(job.tmpDir, `opencode-${basename6(job.cwd)}.db`);
19215
19444
  return { args, env };
19216
19445
  },
19217
19446
  classify: classifyByExit
@@ -19416,7 +19645,7 @@ var init_scan = __esm({
19416
19645
 
19417
19646
  // src/work/credentials.ts
19418
19647
  import { createHash as createHash10 } from "node:crypto";
19419
- import { join as join24 } from "node:path";
19648
+ import { join as join25 } from "node:path";
19420
19649
  function unreadable(why) {
19421
19650
  return new KensoError({
19422
19651
  code: "credentials_unreadable",
@@ -19504,7 +19733,7 @@ var init_credentials = __esm({
19504
19733
  }
19505
19734
  }
19506
19735
  async read(rel) {
19507
- const r = await sudoExec(this.user, CAT, [join24(this.user.home, rel)], { maxBuffer: MAX_CREDENTIAL_BYTES });
19736
+ const r = await sudoExec(this.user, CAT, [join25(this.user.home, rel)], { maxBuffer: MAX_CREDENTIAL_BYTES });
19508
19737
  if (r.exitCode !== 0) return /No such file or directory/.test(r.stderr) ? "missing" : "unreadable";
19509
19738
  const digest = createHash10("sha256").update(r.stdout).digest("hex");
19510
19739
  if (this.seen.get(rel) !== digest) {
@@ -19518,18 +19747,18 @@ var init_credentials = __esm({
19518
19747
  });
19519
19748
 
19520
19749
  // src/work/guide.ts
19521
- import { closeSync as closeSync3, fchmodSync as fchmodSync2, openSync as openSync3, writeFileSync as writeFileSync6 } from "node:fs";
19522
- import { join as join25 } from "node:path";
19750
+ import { closeSync as closeSync3, fchmodSync as fchmodSync2, openSync as openSync3, writeFileSync as writeFileSync7 } from "node:fs";
19751
+ import { join as join26 } from "node:path";
19523
19752
  function agentGuide(opts) {
19524
19753
  const browser = opts.browser ?? findOperation("browser-runs", "create") !== void 0;
19525
19754
  const parts2 = opts.kensoKey ? [JOB, KENSO, ...browser ? [BROWSER] : [], NEVER] : [JOB, NO_KENSO, NEVER];
19526
19755
  return parts2.join("\n");
19527
19756
  }
19528
- function writeAgentGuide(dir2, text4, mode = WORK_FILE_MODE) {
19757
+ function writeAgentGuide(dir3, text4, mode = WORK_FILE_MODE) {
19529
19758
  for (const name of GUIDE_FILES) {
19530
- const fd = openSync3(join25(dir2, name), "wx", mode);
19759
+ const fd = openSync3(join26(dir3, name), "wx", mode);
19531
19760
  try {
19532
- writeFileSync6(fd, text4, "utf8");
19761
+ writeFileSync7(fd, text4, "utf8");
19533
19762
  fchmodSync2(fd, mode);
19534
19763
  } finally {
19535
19764
  closeSync3(fd);
@@ -20158,11 +20387,11 @@ var init_run3 = __esm({
20158
20387
  }
20159
20388
  try {
20160
20389
  workFileName(claim.id);
20161
- const dir2 = await folder.jobDir(claim.id);
20390
+ const dir3 = await folder.jobDir(claim.id);
20162
20391
  const work = workFileOf(claim);
20163
- writeWorkFile(dir2, work, runAs ? WORK_FILE_MODE : void 0);
20164
- if (tools) writeAgentGuide(dir2, tools.guide);
20165
- return { claim, work, dir: dir2 };
20392
+ writeWorkFile(dir3, work, runAs ? WORK_FILE_MODE : void 0);
20393
+ if (tools) writeAgentGuide(dir3, tools.guide);
20394
+ return { claim, work, dir: dir3 };
20166
20395
  } catch (err) {
20167
20396
  await releaseOnce(claim.id);
20168
20397
  error = err instanceof KensoError ? err : new KensoError({ code: "work_file_failed", message: `Could not write the work file: ${err.message}`, exitCode: ExitCode.Error });
@@ -20380,15 +20609,15 @@ __export(keys_exports, {
20380
20609
  function usage(message, field) {
20381
20610
  return new KensoError({ code: "usage_error", message, exitCode: ExitCode.Usage, field });
20382
20611
  }
20383
- function rewrap(err, overrides) {
20612
+ function rewrap(err, overrides2) {
20384
20613
  return new KensoError({
20385
20614
  code: err.code,
20386
- message: overrides.message ?? err.message,
20615
+ message: overrides2.message ?? err.message,
20387
20616
  exitCode: err.exitCode,
20388
20617
  httpStatus: err.httpStatus,
20389
20618
  field: err.field,
20390
20619
  hint: err.hint,
20391
- next: overrides.next ?? err.next,
20620
+ next: overrides2.next ?? err.next,
20392
20621
  requestId: err.requestId,
20393
20622
  details: err.details
20394
20623
  });
@@ -20911,8 +21140,10 @@ async function renderResourceHelp(resource, opts) {
20911
21140
  });
20912
21141
  }
20913
21142
  const rows = [
20914
- ...specs.map((s) => [usageLine2(s).slice(`kenso ${resource} `.length).replace(/ ?\[flags\]$/, ""), `${s.summary}${s.beta ? " (beta)" : ""}`]),
20915
- ...generated.map((g) => [g.action, `${g.summary}${g.beta ? " (beta)" : ""}`])
21143
+ ...specs.map(
21144
+ (s) => [usageLine2(s).slice(`kenso ${resource} `.length).replace(/ ?\[flags\]$/, ""), `${s.summary}${s.beta ? " (beta)" : ""}${effectMark(s.effect)}`]
21145
+ ),
21146
+ ...generated.map((g) => [g.action, `${g.summary}${g.beta ? " (beta)" : ""}${effectMark(g.effect)}`])
20916
21147
  ].sort(([a], [b]) => a.localeCompare(b));
20917
21148
  const lines = [`Usage: kenso ${resource} <action> [flags]`, "", "Actions:", columns(rows)];
20918
21149
  const hiddenActions = [
@@ -20927,7 +21158,7 @@ async function renderResourceHelp(resource, opts) {
20927
21158
  return withAgentBlock(lines.join("\n"), opts.agent);
20928
21159
  }
20929
21160
  function renderCommandHelp(spec, opts) {
20930
- const lines = [`Usage: ${usageLine2(spec)}`, "", `${spec.summary}${spec.beta ? " (beta)" : ""}`];
21161
+ const lines = [`Usage: ${usageLine2(spec)}`, "", `${spec.summary}${spec.beta ? " (beta)" : ""}`, ...effectAndCost(spec, opts.rateCards)];
20931
21162
  if (spec.description) lines.push("", spec.description);
20932
21163
  if (spec.positionals && spec.positionals.length > 0) {
20933
21164
  lines.push("", "Arguments:", columns(spec.positionals.map((p) => [`<${p.name}>${p.variadic ? "..." : ""}`, `${p.description}${p.required ? "" : " (optional)"}`])));
@@ -20948,33 +21179,40 @@ function renderCommandHelp(spec, opts) {
20948
21179
  if (spec.examples.length > 0) lines.push("", "Examples:", ...spec.examples.map((e) => ` ${e}`));
20949
21180
  return withAgentBlock(lines.join("\n"), opts.agent);
20950
21181
  }
20951
- var GLOBAL_FLAG_HELP, GLOBAL_FLAGS_LINE, GLOBAL_FLAGS_LINE_NO_DRY_RUN, COMMON_RESOURCES, EXIT_CODES, FOR_AGENTS;
21182
+ var FORMATS_PIPED, FORMATS_WORDS, GLOBAL_FLAG_HELP, GLOBAL_FLAGS_TAIL, GLOBAL_FLAGS_LINE, GLOBAL_FLAGS_LINE_NO_DRY_RUN, COMMON_RESOURCES, EXIT_CODES, FOR_AGENTS;
20952
21183
  var init_help = __esm({
20953
21184
  "src/commands/help.ts"() {
20954
21185
  "use strict";
20955
21186
  init_errors();
20956
21187
  init_exit_codes();
20957
21188
  init_features();
21189
+ init_output();
20958
21190
  init_version();
20959
21191
  init_generated_hook();
21192
+ init_help_effect();
20960
21193
  init_registry();
21194
+ FORMATS_PIPED = OUTPUT_FORMATS.join("|");
21195
+ FORMATS_WORDS = `${OUTPUT_FORMATS.slice(0, -1).join(", ")} or ${OUTPUT_FORMATS[OUTPUT_FORMATS.length - 1]}`;
20961
21196
  GLOBAL_FLAG_HELP = [
20962
21197
  ["--profile <name>", "Use a saved profile (or KENSO_PROFILE)"],
20963
21198
  ["--workspace <id>", "Workspace for this command (or KENSO_WORKSPACE_ID)"],
20964
- ["-o, --output <format>", "json, ndjson, table or ids (default: table on a terminal, JSON when piped)"],
21199
+ ["-o, --output <format>", `${FORMATS_WORDS} (default: table on a terminal, JSON when piped)`],
20965
21200
  ["--json", "Same as -o json"],
20966
21201
  ["--fields <a,b.c>", "Keep only these fields"],
20967
21202
  ["--query <JMESPath>", "Filter or reshape the output in-process"],
20968
21203
  ["-v, --verbose", "Print each request to stderr (keys redacted)"],
20969
21204
  ["-y, --yes", "Apply a write; a delete, archive or remove needs it"],
20970
21205
  ["--dry-run", "Show what a write would do and change nothing"],
21206
+ ["--read-only", "Refuse every command that is not a read (or KENSO_READ_ONLY=1)"],
20971
21207
  ["--progress", "Print progress to stderr even when it is not a terminal"],
20972
21208
  ["--all-commands", "Show beta commands in help"],
20973
21209
  ["-h, --help", "Show help"],
20974
21210
  ["--version", "Print the CLI version (only on its own: kenso --version)"]
20975
21211
  ];
20976
- GLOBAL_FLAGS_LINE = "Global flags: --dry-run, -y/--yes, --profile <name>, --workspace <id>, -o json|ndjson|table|ids, --json, --fields, --query, -v.";
20977
- GLOBAL_FLAGS_LINE_NO_DRY_RUN = "Global flags: -y/--yes, --profile <name>, --workspace <id>, -o json|ndjson|table|ids, --json, --fields, --query, -v.\nNo --dry-run: this command runs for real, so --dry-run is refused.";
21212
+ GLOBAL_FLAGS_TAIL = `--read-only, --profile <name>, --workspace <id>, -o ${FORMATS_PIPED}, --json, --fields, --query, -v.`;
21213
+ GLOBAL_FLAGS_LINE = `Global flags: --dry-run, -y/--yes, ${GLOBAL_FLAGS_TAIL}`;
21214
+ GLOBAL_FLAGS_LINE_NO_DRY_RUN = `Global flags: -y/--yes, ${GLOBAL_FLAGS_TAIL}
21215
+ No --dry-run: this command runs for real, so --dry-run is refused.`;
20978
21216
  COMMON_RESOURCES = [
20979
21217
  "accounts",
20980
21218
  "analytics",
@@ -21071,9 +21309,39 @@ function applyAliases(argv, spec) {
21071
21309
  }
21072
21310
  return out;
21073
21311
  }
21312
+ function normalizeBooleans(argv, names, strict) {
21313
+ const out = [];
21314
+ for (let i = 0; i < argv.length; i++) {
21315
+ const arg = argv[i];
21316
+ if (arg === "--") {
21317
+ out.push(...argv.slice(i));
21318
+ break;
21319
+ }
21320
+ const match = /^--([^=]+)=([\s\S]*)$/.exec(arg);
21321
+ if (!match || !names.has(match[1])) {
21322
+ out.push(arg);
21323
+ continue;
21324
+ }
21325
+ const [, name, value] = match;
21326
+ if (value === "true") out.push(`--${name}`);
21327
+ else if (value === "false") out.push(`--no-${name}`);
21328
+ else if (strict) {
21329
+ throw new KensoError({
21330
+ code: "invalid_flag_value",
21331
+ message: `--${name} takes true or false (got "${value}"). Use --${name}, --no-${name}, --${name}=true or --${name}=false.`,
21332
+ exitCode: ExitCode.Usage,
21333
+ field: name,
21334
+ next: `${strict.command} --help`
21335
+ });
21336
+ } else out.push(arg);
21337
+ }
21338
+ return out;
21339
+ }
21074
21340
  var init_flag_names = __esm({
21075
21341
  "src/core/flag-names.ts"() {
21076
21342
  "use strict";
21343
+ init_errors();
21344
+ init_exit_codes();
21077
21345
  }
21078
21346
  });
21079
21347
 
@@ -21096,23 +21364,67 @@ var init_invoked = __esm({
21096
21364
  });
21097
21365
 
21098
21366
  // src/core/pre-run.ts
21099
- async function beforeRun(_ctx, _spec, _args) {
21367
+ function readOnlySource(ctx) {
21368
+ const value = (ctx.env.KENSO_READ_ONLY ?? "").trim().toLowerCase();
21369
+ if (value !== "" && value !== "0" && value !== "false") return "env";
21370
+ return ctx.flags.readOnly === true ? "flag" : void 0;
21371
+ }
21372
+ function effectOf2(spec, args) {
21373
+ return spec.effectFor?.(args) ?? spec.effect ?? "write";
21374
+ }
21375
+ function shellQuote6(value) {
21376
+ return /^[A-Za-z0-9_\-.,:/@=+%]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
21377
+ }
21378
+ function readOnlyError(spec, effect, source, argv) {
21379
+ const name = spec.action ? `kenso ${spec.resource} ${spec.action}` : `kenso ${spec.resource}`;
21380
+ const message = `${name} is a ${effect} command, and this session is read-only.`;
21381
+ if (source === "env") {
21382
+ return new KensoError({ code: "read_only", message, exitCode: ExitCode.Usage, hint: "KENSO_READ_ONLY is set: unset it to run this command." });
21383
+ }
21384
+ if (spec.flags["body-read-only"]) {
21385
+ const hint = "Read-only is on through --read-only, the global flag. This command's own read-only option is --body-read-only.";
21386
+ return new KensoError({ code: "read_only", message, exitCode: ExitCode.Usage, hint });
21387
+ }
21388
+ const end = argv?.indexOf("--") ?? -1;
21389
+ const head = (end === -1 ? argv : argv?.slice(0, end)) ?? [];
21390
+ if (spec.dryRun !== true || !argv || head.some((token) => /^-[A-Za-z]{2,}$/.test(token) && token.includes("y"))) {
21391
+ return new KensoError({ code: "read_only", message, exitCode: ExitCode.Usage, hint: "Read-only is on through --read-only: run the command again without --read-only to make the change." });
21392
+ }
21393
+ const kept = head.filter((token) => token !== "--yes" && token !== "-y" && !token.startsWith("--yes="));
21394
+ const withDryRun = [...kept, "--dry-run", ...end === -1 ? [] : argv.slice(end)];
21395
+ return new KensoError({
21396
+ code: "read_only",
21397
+ message,
21398
+ exitCode: ExitCode.Usage,
21399
+ hint: "Read-only is on through --read-only: next prints the plan. Run the command again without --read-only to make the change.",
21400
+ next: ["kenso", ...withDryRun.map(shellQuote6)].join(" ")
21401
+ });
21402
+ }
21403
+ async function beforeRun(ctx, spec, args, argv) {
21404
+ const source = readOnlySource(ctx);
21405
+ if (!source) return;
21406
+ const effect = effectOf2(spec, args);
21407
+ if (effect === "read") return;
21408
+ if (ctx.flags.dryRun === true && spec.dryRun === true) return;
21409
+ throw readOnlyError(spec, effect, source, argv);
21100
21410
  }
21101
21411
  var init_pre_run = __esm({
21102
21412
  "src/core/pre-run.ts"() {
21103
21413
  "use strict";
21414
+ init_errors();
21415
+ init_exit_codes();
21104
21416
  }
21105
21417
  });
21106
21418
 
21107
21419
  // src/core/update-notice.ts
21108
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync13, realpathSync as realpathSync2, renameSync as renameSync4, writeFileSync as writeFileSync7 } from "node:fs";
21109
- import { dirname as dirname5, join as join26, sep as sep3 } from "node:path";
21420
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync15, realpathSync as realpathSync2, renameSync as renameSync5, writeFileSync as writeFileSync8 } from "node:fs";
21421
+ import { dirname as dirname5, join as join27, sep as sep3 } from "node:path";
21110
21422
  function installKind(script = process.argv[1], execPath = process.execPath, platform = process.platform) {
21111
21423
  try {
21112
21424
  if (!script) return "npm";
21113
21425
  const bundle = realpathSync2(script);
21114
21426
  const lib = dirname5(dirname5(dirname5(bundle)));
21115
- if (execPath !== join26(lib, platform === "win32" ? "node.exe" : "node")) return "npm";
21427
+ if (execPath !== join27(lib, platform === "win32" ? "node.exe" : "node")) return "npm";
21116
21428
  return bundle.includes(`${sep3}Cellar${sep3}kenso${sep3}`) ? "homebrew" : "standalone";
21117
21429
  } catch {
21118
21430
  return "npm";
@@ -21125,7 +21437,7 @@ function updateCommand(install, platform) {
21125
21437
  }
21126
21438
  function readCheck(file) {
21127
21439
  try {
21128
- const parsed2 = JSON.parse(readFileSync13(file, "utf8"));
21440
+ const parsed2 = JSON.parse(readFileSync15(file, "utf8"));
21129
21441
  if (typeof parsed2?.checkedAt !== "string") return void 0;
21130
21442
  return { checkedAt: parsed2.checkedAt, ...typeof parsed2.latest === "string" ? { latest: parsed2.latest } : {} };
21131
21443
  } catch {
@@ -21136,9 +21448,9 @@ function writeCheck(file, check) {
21136
21448
  try {
21137
21449
  mkdirSync5(dirname5(file), { recursive: true, mode: 448 });
21138
21450
  const temp = `${file}.${process.pid}.tmp`;
21139
- writeFileSync7(temp, `${JSON.stringify(check)}
21451
+ writeFileSync8(temp, `${JSON.stringify(check)}
21140
21452
  `, { mode: 384 });
21141
- renameSync4(temp, file);
21453
+ renameSync5(temp, file);
21142
21454
  } catch {
21143
21455
  }
21144
21456
  }
@@ -21172,7 +21484,7 @@ function startUpdateNotice(argv, opts = {}) {
21172
21484
  const stderr = opts.stderr ?? process.stderr;
21173
21485
  const wanted = (opts.stderrIsTTY ?? process.stderr.isTTY === true) && detectAgent(env) === null && env.CI === void 0 && !env.KENSO_NO_UPDATE_NOTIFIER && RELEASE.test(version) && !argv.some((word) => QUIET_COMMANDS.has(word));
21174
21486
  if (!wanted) return done;
21175
- const file = join26(configDir(env), UPDATE_CHECK_FILE);
21487
+ const file = join27(configDir(env), UPDATE_CHECK_FILE);
21176
21488
  const now = (opts.now ?? Date.now)();
21177
21489
  const cached = readCheck(file);
21178
21490
  const checkedAt = Date.parse(cached?.checkedAt ?? "");
@@ -21362,34 +21674,6 @@ function leaveRun(active) {
21362
21674
  graceTimer = void 0;
21363
21675
  }
21364
21676
  }
21365
- function normalizeBooleans(argv, names, strict) {
21366
- const out = [];
21367
- for (let i = 0; i < argv.length; i++) {
21368
- const arg = argv[i];
21369
- if (arg === "--") {
21370
- out.push(...argv.slice(i));
21371
- break;
21372
- }
21373
- const match = /^--([^=]+)=([\s\S]*)$/.exec(arg);
21374
- if (!match || !names.has(match[1])) {
21375
- out.push(arg);
21376
- continue;
21377
- }
21378
- const [, name, value] = match;
21379
- if (value === "true") out.push(`--${name}`);
21380
- else if (value === "false") out.push(`--no-${name}`);
21381
- else if (strict) {
21382
- throw new KensoError({
21383
- code: "invalid_flag_value",
21384
- message: `--${name} takes true or false (got "${value}"). Use --${name}, --no-${name}, --${name}=true or --${name}=false.`,
21385
- exitCode: ExitCode.Usage,
21386
- field: name,
21387
- next: `${strict.command} --help`
21388
- });
21389
- } else out.push(arg);
21390
- }
21391
- return out;
21392
- }
21393
21677
  async function knownCommands() {
21394
21678
  const commands = /* @__PURE__ */ new Set();
21395
21679
  for (const [resource, area] of Object.entries(handWritten)) {
@@ -21504,6 +21788,7 @@ function globalFlags(values) {
21504
21788
  verbose: values.verbose === true,
21505
21789
  yes: values.yes === true,
21506
21790
  dryRun: values["dry-run"] === true,
21791
+ readOnly: values["read-only"] === true,
21507
21792
  progress: values.progress === true,
21508
21793
  allCommands: values["all-commands"] === true
21509
21794
  };
@@ -21544,11 +21829,11 @@ function commandArgs(spec, parsed2, tokens) {
21544
21829
  }
21545
21830
  return { flags, positionals };
21546
21831
  }
21547
- async function main(argv, env = process.env, overrides = {}) {
21548
- const stdout = overrides.stdout ?? process.stdout;
21832
+ async function main(argv, env = process.env, overrides2 = {}) {
21833
+ const stdout = overrides2.stdout ?? process.stdout;
21549
21834
  guardClosedPipe(stdout);
21550
21835
  if (argv[0] === "__complete") return (await Promise.resolve().then(() => (init_complete(), complete_exports))).printCompletions(argv.slice(1), GLOBAL_OPTIONS, stdout);
21551
- let output = new Output({ stdout: overrides.stdout, stderr: overrides.stderr, stdoutIsTTY: overrides.stdoutIsTTY, stderrIsTTY: overrides.stderrIsTTY });
21836
+ let output = new Output({ stdout: overrides2.stdout, stderr: overrides2.stderr, stdoutIsTTY: overrides2.stdoutIsTTY, stderrIsTTY: overrides2.stderrIsTTY });
21552
21837
  const agent = detectAgent(env);
21553
21838
  const controller = new AbortController();
21554
21839
  const active = { controller, info: (message) => output.info(message) };
@@ -21563,12 +21848,14 @@ async function main(argv, env = process.env, overrides = {}) {
21563
21848
  }
21564
21849
  verbose = loose.values.verbose === true;
21565
21850
  const text4 = (value) => typeof value === "string" ? value : void 0;
21851
+ const lookupFlags = { profile: text4(loose.values.profile), workspace: text4(loose.values.workspace) };
21852
+ const lookupOverrides = { fetchImpl: overrides2.fetchImpl, sleep: overrides2.sleep, signal: controller.signal };
21566
21853
  const helpOptions = {
21567
21854
  agent,
21568
21855
  allCommands: loose.values["all-commands"] === true,
21569
21856
  env,
21570
- // Cached features, else GET /v1/me with a 1,500 ms timeout, with main's env, flags and test overrides.
21571
- loadFeatures: () => featuresFromEnv(env, { profile: text4(loose.values.profile), workspace: text4(loose.values.workspace) }, { fetchImpl: overrides.fetchImpl, sleep: overrides.sleep, signal: controller.signal }),
21857
+ // Cached features, else GET /v1/me with a 1,500 ms timeout.
21858
+ loadFeatures: () => featuresFromEnv(env, lookupFlags, lookupOverrides),
21572
21859
  warn: (message) => {
21573
21860
  lookupFailed = true;
21574
21861
  output.info(message);
@@ -21607,17 +21894,19 @@ async function main(argv, env = process.env, overrides = {}) {
21607
21894
  commandTokens = [resourceToken, actionToken];
21608
21895
  }
21609
21896
  if (wantHelp) {
21610
- stdout.write(renderCommandHelp(spec, helpOptions));
21897
+ const rateCards = spec.cost?.length ? await rateCardsForHelp(env, lookupFlags, lookupOverrides) : void 0;
21898
+ if (rateCards?.[0]?.source === "bundled") lookupFailed = true;
21899
+ stdout.write(renderCommandHelp(spec, { ...helpOptions, rateCards }));
21611
21900
  return ExitCode.Ok;
21612
21901
  }
21613
21902
  const parsed2 = strictParse(argv, spec);
21614
21903
  const flags = globalFlags(parsed2.values);
21615
21904
  if (flags.dryRun && spec.dryRun !== true) throw noDryRun(spec);
21616
21905
  const args = commandArgs(spec, parsed2, commandTokens);
21617
- const ctx = createContext(flags, env, { ...overrides, signal: controller.signal, noConfig: spec.ownCredential?.(args.flags) === true });
21906
+ const ctx = createContext(flags, env, { ...overrides2, signal: controller.signal, noConfig: spec.ownCredential?.(args.flags) === true });
21618
21907
  output = ctx.output;
21619
21908
  active.graceMs = spec.interruptGraceMs;
21620
- await beforeRun(ctx, spec, args);
21909
+ await beforeRun(ctx, spec, args, argv);
21621
21910
  enterRun(active);
21622
21911
  try {
21623
21912
  const code = await spec.run(ctx, args);
@@ -21659,6 +21948,7 @@ var init_main = __esm({
21659
21948
  init_invoked();
21660
21949
  init_output();
21661
21950
  init_pre_run();
21951
+ init_rate_card();
21662
21952
  init_redact();
21663
21953
  init_update_notice();
21664
21954
  init_version();
@@ -21672,6 +21962,7 @@ var init_main = __esm({
21672
21962
  verbose: { type: "boolean", short: "v" },
21673
21963
  yes: { type: "boolean", short: "y" },
21674
21964
  "dry-run": { type: "boolean" },
21965
+ "read-only": { type: "boolean" },
21675
21966
  progress: { type: "boolean" },
21676
21967
  "all-commands": { type: "boolean" },
21677
21968
  help: { type: "boolean", short: "h" },